xref: /linux/tools/perf/util/lzma.c (revision 2fe05e1139a555ae91f00a812cb9520e7d3022ab)
1 #include <errno.h>
2 #include <lzma.h>
3 #include <stdio.h>
4 #include <linux/compiler.h>
5 #include "compress.h"
6 #include "util.h"
7 #include "debug.h"
8 
9 #define BUFSIZE 8192
10 
11 static const char *lzma_strerror(lzma_ret ret)
12 {
13 	switch ((int) ret) {
14 	case LZMA_MEM_ERROR:
15 		return "Memory allocation failed";
16 	case LZMA_OPTIONS_ERROR:
17 		return "Unsupported decompressor flags";
18 	case LZMA_FORMAT_ERROR:
19 		return "The input is not in the .xz format";
20 	case LZMA_DATA_ERROR:
21 		return "Compressed file is corrupt";
22 	case LZMA_BUF_ERROR:
23 		return "Compressed file is truncated or otherwise corrupt";
24 	default:
25 		return "Unknown error, possibly a bug";
26 	}
27 }
28 
29 int lzma_decompress_to_file(const char *input, int output_fd)
30 {
31 	lzma_action action = LZMA_RUN;
32 	lzma_stream strm   = LZMA_STREAM_INIT;
33 	lzma_ret ret;
34 	int err = -1;
35 
36 	u8 buf_in[BUFSIZE];
37 	u8 buf_out[BUFSIZE];
38 	FILE *infile;
39 
40 	infile = fopen(input, "rb");
41 	if (!infile) {
42 		pr_err("lzma: fopen failed on %s: '%s'\n",
43 		       input, strerror(errno));
44 		return -1;
45 	}
46 
47 	ret = lzma_stream_decoder(&strm, UINT64_MAX, LZMA_CONCATENATED);
48 	if (ret != LZMA_OK) {
49 		pr_err("lzma: lzma_stream_decoder failed %s (%d)\n",
50 			lzma_strerror(ret), ret);
51 		goto err_fclose;
52 	}
53 
54 	strm.next_in   = NULL;
55 	strm.avail_in  = 0;
56 	strm.next_out  = buf_out;
57 	strm.avail_out = sizeof(buf_out);
58 
59 	while (1) {
60 		if (strm.avail_in == 0 && !feof(infile)) {
61 			strm.next_in  = buf_in;
62 			strm.avail_in = fread(buf_in, 1, sizeof(buf_in), infile);
63 
64 			if (ferror(infile)) {
65 				pr_err("lzma: read error: %s\n", strerror(errno));
66 				goto err_fclose;
67 			}
68 
69 			if (feof(infile))
70 				action = LZMA_FINISH;
71 		}
72 
73 		ret = lzma_code(&strm, action);
74 
75 		if (strm.avail_out == 0 || ret == LZMA_STREAM_END) {
76 			ssize_t write_size = sizeof(buf_out) - strm.avail_out;
77 
78 			if (writen(output_fd, buf_out, write_size) != write_size) {
79 				pr_err("lzma: write error: %s\n", strerror(errno));
80 				goto err_fclose;
81 			}
82 
83 			strm.next_out  = buf_out;
84 			strm.avail_out = sizeof(buf_out);
85 		}
86 
87 		if (ret != LZMA_OK) {
88 			if (ret == LZMA_STREAM_END)
89 				break;
90 
91 			pr_err("lzma: failed %s\n", lzma_strerror(ret));
92 			goto err_fclose;
93 		}
94 	}
95 
96 	err = 0;
97 err_fclose:
98 	fclose(infile);
99 	return err;
100 }
101