从压缩的内核映像中获取内核版本

Getting kernel version from the compressed kernel image

我正在编写 shell 脚本。我有一个预建的 zImage。是否可以知道创建此 zImage 的内核版本?

我已经尝试使用更新的命令@Getting uname information from a compressed kernel image,但是两个命令都失败了。

$ dd if=zImage bs=1 skip=$(LC_ALL=C grep -a -b -o $'\x1f\x8b\x08\x00\x00\x00\x00\x00' zImage | \
  cut -d ':' -f 1) | zcat | grep -a 'Linux version'

dd: unrecognized operand `3165585'
Try `dd --help' for more information.

gzip: stdin: unexpected end of file

$ dd if=zImage bs=1 skip=$(LC_ALL=C grep -a -b -o $'\xFD\x37\x7A\x58\x5A\x00' zImage | \
  head -n 1 | cut -d ':' -f 1) | xzcat | grep -a 'Linux version'

xzcat: (stdin): File format not recognized

能否指导我从zImage中识别内核版本。

检查内核压缩算法

您的 zImage 很可能是使用 LZMA 压缩器压缩的。您可以在下一个文件中查看它:

  • .config文件中(如果你自己构建内核)
  • /boot/config-`uname -r` 文件中(如果您正在使用您的发行版)
  • /proc/config.gz 文件中(如果启用 CONFIG_IKCONFIG_PROC

寻找CONFIG_KERNEL_*参数:

$ cat .config | grep '^CONFIG_KERNEL_[^_]\+='

如果设置了CONFIG_KERNEL_LZMA=y,表示使用了LZMA压缩器。

解压缩 zImage

LZMA格式has5d 00 00header签名。所以可以这样找到Image压缩文件在zImage文件中的位置:

$ grep -P -a -b -m 1 --only-matching '\x5D\x00\x00' zImage | cut -f 1 -d :

解压缩Image:

$ pos=$(grep -P -a -b -m 1 --only-matching '\x5D\x00\x00' zImage | cut -f 1 -d :)
$ dd if=arch/arm/boot/zImage of=piggy.lzma bs=1 skip=$pos

现在确保 piggy.lzma 实际上是 LZMA 存档:

$ file piggy.lzma 

piggy.lzma: LZMA compressed data, streamed

解压piggy.lzma:

$ unlzma -c piggy.lzma > Image

找到 Linux 版本

现在您已经解压了 Image,您可以使用 strings 工具找到 Linux 版本:

$ strings Image | grep 'Linux version'

应该给你这样的东西:

Linux version 4.4.11-188843-g94c4bf5-dirty (joe@joe-laptop) (gcc version 4.8 (GCC) ) #1 SMP PREEMPT Thu May 26 20:55:27 EEST 2016

Sam Protsenko 回答的补充:

由于你没有说明zImage文件使用的压缩算法,我推荐你使用vmlinux-to-elf。此工具可用于将zImage文件转换为ELF文件,并且可以识别多种压缩算法(不仅是LZMA)。

在一个简单的用例中,首先将 zImage 文件转换为 ELF 文件:

./vmlinux-to-elf ./zImage ./Image
file ./Image

./Image: ELF 32-bit LSB executable, ARM, version 1 (SYSV), statically linked, not stripped

然后,找到带有strings

的linux版本
strings ./Image | grep 'Linux version'

Linux version 3.4.0-gd59db4e (android-build@vpbs1.mtv.corp.google.com) (gcc version 4.7 (GCC) ) #1 SMP PREEMPT Mon Mar 17 15:16:36 PDT 2014