lzma.c 2.2 KB

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