1 // SPDX-License-Identifier: GPL-2.0
5 #include <linux/compiler.h>
13 #include <internal/lib.h>
17 static const char *lzma_strerror(lzma_ret ret)
21 return "Memory allocation failed";
22 case LZMA_OPTIONS_ERROR:
23 return "Unsupported decompressor flags";
24 case LZMA_FORMAT_ERROR:
25 return "The input is not in the .xz format";
27 return "Compressed file is corrupt";
29 return "Compressed file is truncated or otherwise corrupt";
31 return "Unknown error, possibly a bug";
35 int lzma_decompress_to_file(const char *input, int output_fd)
37 lzma_action action = LZMA_RUN;
38 lzma_stream strm = LZMA_STREAM_INIT;
46 infile = fopen(input, "rb");
48 pr_debug("lzma: fopen failed on %s: '%s'\n", input, strerror(errno));
52 ret = lzma_stream_decoder(&strm, UINT64_MAX, LZMA_CONCATENATED);
54 pr_debug("lzma: lzma_stream_decoder failed %s (%d)\n", lzma_strerror(ret), ret);
60 strm.next_out = buf_out;
61 strm.avail_out = sizeof(buf_out);
64 if (strm.avail_in == 0 && !feof(infile)) {
65 strm.next_in = buf_in;
66 strm.avail_in = fread(buf_in, 1, sizeof(buf_in), infile);
69 pr_debug("lzma: read error: %s\n", strerror(errno));
77 ret = lzma_code(&strm, action);
79 if (strm.avail_out == 0 || ret == LZMA_STREAM_END) {
80 ssize_t write_size = sizeof(buf_out) - strm.avail_out;
82 if (writen(output_fd, buf_out, write_size) != write_size) {
83 pr_debug("lzma: write error: %s\n", strerror(errno));
87 strm.next_out = buf_out;
88 strm.avail_out = sizeof(buf_out);
92 if (ret == LZMA_STREAM_END)
95 pr_debug("lzma: failed %s\n", lzma_strerror(ret));
108 bool lzma_is_compressed(const char *input)
110 int fd = open(input, O_RDONLY);
111 const uint8_t magic[6] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
118 rc = read(fd, buf, sizeof(buf));
120 return rc == sizeof(buf) ?
121 memcmp(buf, magic, sizeof(buf)) == 0 : false;