Linux 5.1.15
[linux/fpc-iii.git] / tools / perf / util / lzma.c
blobb1dd29a9d915efac1953d0d04ad9b99a5f3425de
1 // SPDX-License-Identifier: GPL-2.0
2 #include <errno.h>
3 #include <lzma.h>
4 #include <stdio.h>
5 #include <linux/compiler.h>
6 #include <sys/types.h>
7 #include <sys/stat.h>
8 #include <fcntl.h>
9 #include "compress.h"
10 #include "util.h"
11 #include "debug.h"
12 #include <unistd.h>
14 #define BUFSIZE 8192
16 static const char *lzma_strerror(lzma_ret ret)
18 switch ((int) ret) {
19 case LZMA_MEM_ERROR:
20 return "Memory allocation failed";
21 case LZMA_OPTIONS_ERROR:
22 return "Unsupported decompressor flags";
23 case LZMA_FORMAT_ERROR:
24 return "The input is not in the .xz format";
25 case LZMA_DATA_ERROR:
26 return "Compressed file is corrupt";
27 case LZMA_BUF_ERROR:
28 return "Compressed file is truncated or otherwise corrupt";
29 default:
30 return "Unknown error, possibly a bug";
34 int lzma_decompress_to_file(const char *input, int output_fd)
36 lzma_action action = LZMA_RUN;
37 lzma_stream strm = LZMA_STREAM_INIT;
38 lzma_ret ret;
39 int err = -1;
41 u8 buf_in[BUFSIZE];
42 u8 buf_out[BUFSIZE];
43 FILE *infile;
45 infile = fopen(input, "rb");
46 if (!infile) {
47 pr_err("lzma: fopen failed on %s: '%s'\n",
48 input, strerror(errno));
49 return -1;
52 ret = lzma_stream_decoder(&strm, UINT64_MAX, LZMA_CONCATENATED);
53 if (ret != LZMA_OK) {
54 pr_err("lzma: lzma_stream_decoder failed %s (%d)\n",
55 lzma_strerror(ret), ret);
56 goto err_fclose;
59 strm.next_in = NULL;
60 strm.avail_in = 0;
61 strm.next_out = buf_out;
62 strm.avail_out = sizeof(buf_out);
64 while (1) {
65 if (strm.avail_in == 0 && !feof(infile)) {
66 strm.next_in = buf_in;
67 strm.avail_in = fread(buf_in, 1, sizeof(buf_in), infile);
69 if (ferror(infile)) {
70 pr_err("lzma: read error: %s\n", strerror(errno));
71 goto err_fclose;
74 if (feof(infile))
75 action = LZMA_FINISH;
78 ret = lzma_code(&strm, action);
80 if (strm.avail_out == 0 || ret == LZMA_STREAM_END) {
81 ssize_t write_size = sizeof(buf_out) - strm.avail_out;
83 if (writen(output_fd, buf_out, write_size) != write_size) {
84 pr_err("lzma: write error: %s\n", strerror(errno));
85 goto err_fclose;
88 strm.next_out = buf_out;
89 strm.avail_out = sizeof(buf_out);
92 if (ret != LZMA_OK) {
93 if (ret == LZMA_STREAM_END)
94 break;
96 pr_err("lzma: failed %s\n", lzma_strerror(ret));
97 goto err_fclose;
101 err = 0;
102 err_fclose:
103 fclose(infile);
104 return err;
107 bool lzma_is_compressed(const char *input)
109 int fd = open(input, O_RDONLY);
110 const uint8_t magic[6] = { 0xFD, '7', 'z', 'X', 'Z', 0x00 };
111 char buf[6] = { 0 };
112 ssize_t rc;
114 if (fd < 0)
115 return -1;
117 rc = read(fd, buf, sizeof(buf));
118 close(fd);
119 return rc == sizeof(buf) ?
120 memcmp(buf, magic, sizeof(buf)) == 0 : false;