decompress.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * decompress.c
  4. *
  5. * Detect the decompression method based on magic number
  6. */
  7. #include <linux/decompress/generic.h>
  8. #include <linux/decompress/bunzip2.h>
  9. #include <linux/decompress/unlzma.h>
  10. #include <linux/decompress/unxz.h>
  11. #include <linux/decompress/inflate.h>
  12. #include <linux/decompress/unlzo.h>
  13. #include <linux/decompress/unlz4.h>
  14. #include <linux/decompress/unzstd.h>
  15. #include <linux/types.h>
  16. #include <linux/string.h>
  17. #include <linux/init.h>
  18. #include <linux/printk.h>
  19. #ifndef CONFIG_DECOMPRESS_GZIP
  20. # define gunzip NULL
  21. #endif
  22. #ifndef CONFIG_DECOMPRESS_BZIP2
  23. # define bunzip2 NULL
  24. #endif
  25. #ifndef CONFIG_DECOMPRESS_LZMA
  26. # define unlzma NULL
  27. #endif
  28. #ifndef CONFIG_DECOMPRESS_XZ
  29. # define unxz NULL
  30. #endif
  31. #ifndef CONFIG_DECOMPRESS_LZO
  32. # define unlzo NULL
  33. #endif
  34. #ifndef CONFIG_DECOMPRESS_LZ4
  35. # define unlz4 NULL
  36. #endif
  37. #ifndef CONFIG_DECOMPRESS_ZSTD
  38. # define unzstd NULL
  39. #endif
  40. struct compress_format {
  41. unsigned char magic[2];
  42. const char *name;
  43. decompress_fn decompressor;
  44. };
  45. static const struct compress_format compressed_formats[] __initconst = {
  46. { {0x1f, 0x8b}, "gzip", gunzip },
  47. { {0x1f, 0x9e}, "gzip", gunzip },
  48. { {0x42, 0x5a}, "bzip2", bunzip2 },
  49. { {0x5d, 0x00}, "lzma", unlzma },
  50. { {0xfd, 0x37}, "xz", unxz },
  51. { {0x89, 0x4c}, "lzo", unlzo },
  52. { {0x02, 0x21}, "lz4", unlz4 },
  53. { {0x28, 0xb5}, "zstd", unzstd },
  54. { {0, 0}, NULL, NULL }
  55. };
  56. decompress_fn __init decompress_method(const unsigned char *inbuf, long len,
  57. const char **name)
  58. {
  59. const struct compress_format *cf;
  60. if (len < 2) {
  61. if (name)
  62. *name = NULL;
  63. return NULL; /* Need at least this much... */
  64. }
  65. pr_debug("Compressed data magic: %#.2x %#.2x\n", inbuf[0], inbuf[1]);
  66. for (cf = compressed_formats; cf->name; cf++) {
  67. if (!memcmp(inbuf, cf->magic, 2))
  68. break;
  69. }
  70. if (name)
  71. *name = cf->name;
  72. return cf->decompressor;
  73. }