16 void uncompresslzma(void *buf, size_t bufsize, FILE *out) {
17 lzma_stream s = LZMA_STREAM_INIT;
20 uint8_t outbuf[BUFSIZ];
26 ret = lzma_stream_decoder(strm, UINT64_MAX, 0);
27 /* The only reasonable error here is LZMA_MEM_ERROR. */
29 fprintf(stderr, "%s", ret == LZMA_MEM_ERROR ? strerror(ENOMEM)
30 : "Internal error (bug)");
34 strm->avail_in = bufsize;
36 strm->avail_out = BUFSIZ;
37 strm->next_out = outbuf;
39 lzma_action action = LZMA_RUN;
42 ret = lzma_code(strm, action);
44 // Write and check write error before checking decoder error.
45 // This way as much data as possible gets written to output
46 // even if decoder detected an error.
47 if (strm->avail_out == 0 || ret != LZMA_OK) {
48 const size_t write_size = BUFSIZ - strm->avail_out;
50 if (fwrite(outbuf, 1, write_size, out) != write_size) {
51 // Wouldn't be a surprise if writing to stderr
52 // would fail too but at least try to show an
54 fprintf(stderr, "Cannot write to output file stream: "
55 "%s", strerror(errno));
59 strm->next_out = outbuf;
60 strm->avail_out = BUFSIZ;
64 if (ret == LZMA_STREAM_END) {
65 // lzma_stream_decoder() already guarantees
66 // that there's no trailing garbage.
67 assert(strm->avail_in == 0);
68 //assert(action == LZMA_FINISH);
75 msg = strerror(ENOMEM);
78 case LZMA_FORMAT_ERROR:
79 msg = "File format not recognized";
82 case LZMA_OPTIONS_ERROR:
83 // FIXME: Better message?
84 msg = "Unsupported compression options";
88 msg = "File is corrupt";
92 msg = "Unexpected end of input";
96 msg = "Internal error (bug)";
100 fprintf(stderr, "xz: %s\n", msg);