14 void uncompresslzma(void *buf, size_t bufsize, FILE *out) {
15 lzma_stream s = LZMA_STREAM_INIT;
18 uint8_t outbuf[BUFSIZ];
24 ret = lzma_stream_decoder(strm, UINT64_MAX, 0);
25 /* The only reasonable error here is LZMA_MEM_ERROR. */
27 fprintf(stderr, "%s", ret == LZMA_MEM_ERROR ? strerror(ENOMEM)
28 : "Internal error (bug)");
32 strm->avail_in = bufsize;
34 strm->avail_out = BUFSIZ;
35 strm->next_out = outbuf;
37 lzma_action action = LZMA_RUN;
40 ret = lzma_code(strm, action);
42 // Write and check write error before checking decoder error.
43 // This way as much data as possible gets written to output
44 // even if decoder detected an error.
45 if (strm->avail_out == 0 || ret != LZMA_OK) {
46 const size_t write_size = BUFSIZ - strm->avail_out;
48 if (fwrite(outbuf, 1, write_size, out) != write_size) {
49 // Wouldn't be a surprise if writing to stderr
50 // would fail too but at least try to show an
52 fprintf(stderr, "Cannot write to output file stream: "
53 "%s", strerror(errno));
57 strm->next_out = outbuf;
58 strm->avail_out = BUFSIZ;
62 if (ret == LZMA_STREAM_END) {
63 // lzma_stream_decoder() already guarantees
64 // that there's no trailing garbage.
65 assert(strm->avail_in == 0);
66 //assert(action == LZMA_FINISH);
73 msg = strerror(ENOMEM);
76 case LZMA_FORMAT_ERROR:
77 msg = "File format not recognized";
80 case LZMA_OPTIONS_ERROR:
81 // FIXME: Better message?
82 msg = "Unsupported compression options";
86 msg = "File is corrupt";
90 msg = "Unexpected end of input";
94 msg = "Internal error (bug)";
98 fprintf(stderr, "xz: %s\n", msg);