decompress.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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/types.h>
  15. #include <linux/string.h>
  16. #include <linux/init.h>
  17. #include <linux/printk.h>
  18. #ifndef CONFIG_DECOMPRESS_GZIP
  19. # define gunzip NULL
  20. #endif
  21. #ifndef CONFIG_DECOMPRESS_BZIP2
  22. # define bunzip2 NULL
  23. #endif
  24. #ifndef CONFIG_DECOMPRESS_LZMA
  25. # define unlzma NULL
  26. #endif
  27. #ifndef CONFIG_DECOMPRESS_XZ
  28. # define unxz NULL
  29. #endif
  30. #ifndef CONFIG_DECOMPRESS_LZO
  31. # define unlzo NULL
  32. #endif
  33. #ifndef CONFIG_DECOMPRESS_LZ4
  34. # define unlz4 NULL
  35. #endif
  36. struct compress_format {
  37. unsigned char magic[2];
  38. const char *name;
  39. decompress_fn decompressor;
  40. };
  41. static const struct compress_format compressed_formats[] __initconst = {
  42. { {0x1f, 0x8b}, "gzip", gunzip },
  43. { {0x1f, 0x9e}, "gzip", gunzip },
  44. { {0x42, 0x5a}, "bzip2", bunzip2 },
  45. { {0x5d, 0x00}, "lzma", unlzma },
  46. { {0xfd, 0x37}, "xz", unxz },
  47. { {0x89, 0x4c}, "lzo", unlzo },
  48. { {0x02, 0x21}, "lz4", unlz4 },
  49. { {0, 0}, NULL, NULL }
  50. };
  51. decompress_fn __init decompress_method(const unsigned char *inbuf, long len,
  52. const char **name)
  53. {
  54. const struct compress_format *cf;
  55. if (len < 2) {
  56. if (name)
  57. *name = NULL;
  58. return NULL; /* Need at least this much... */
  59. }
  60. pr_debug("Compressed data magic: %#.2x %#.2x\n", inbuf[0], inbuf[1]);
  61. for (cf = compressed_formats; cf->name; cf++) {
  62. if (!memcmp(inbuf, cf->magic, 2))
  63. break;
  64. }
  65. if (name)
  66. *name = cf->name;
  67. return cf->decompressor;
  68. }