blob: 0046b38fafd245041061d6eab9b156628d632512 [file] [log] [blame]
Yifan Hong770ab052018-11-02 13:43:30 -07001#!/usr/bin/env python
2#
3# Copyright (C) 2018 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17"""
18A tool to extract kernel information from a kernel image.
19"""
20
21import argparse
22import subprocess
23import sys
24import re
25
26CONFIG_PREFIX = b'IKCFG_ST'
27GZIP_HEADER = b'\037\213\010'
28COMPRESSION_ALGO = (
29 (["gzip", "-d"], GZIP_HEADER),
30 (["xz", "-d"], b'\3757zXZ\000'),
31 (["bzip2", "-d"], b'BZh'),
32 (["lz4", "-d", "-l"], b'\002\041\114\030'),
33
34 # These are not supported in the build system yet.
35 # (["unlzma"], b'\135\0\0\0'),
36 # (["lzop", "-d"], b'\211\114\132'),
37)
38
39# "Linux version " UTS_RELEASE " (" LINUX_COMPILE_BY "@"
40# LINUX_COMPILE_HOST ") (" LINUX_COMPILER ") " UTS_VERSION "\n";
41LINUX_BANNER_PREFIX = b'Linux version '
42LINUX_BANNER_REGEX = LINUX_BANNER_PREFIX + \
Yongqin Liu2c8b8ec2020-08-08 14:32:47 +080043 r'(?P<release>(?P<version>[0-9]+[.][0-9]+[.][0-9]+).*) \(.*@.*\) \((?P<compiler>.*)\) .*\n'
Yifan Hong770ab052018-11-02 13:43:30 -070044
45
Yifan Hong351b6b82020-07-27 18:49:41 -070046def get_from_release(input_bytes, start_idx, key):
Yifan Hong770ab052018-11-02 13:43:30 -070047 null_idx = input_bytes.find('\x00', start_idx)
48 if null_idx < 0:
49 return None
Andrew Chant5d323c12019-07-08 15:53:00 -070050 try:
51 linux_banner = input_bytes[start_idx:null_idx].decode()
52 except UnicodeDecodeError:
53 return None
Yifan Hong770ab052018-11-02 13:43:30 -070054 mo = re.match(LINUX_BANNER_REGEX, linux_banner)
55 if mo:
Yifan Hong351b6b82020-07-27 18:49:41 -070056 return mo.group(key)
Yifan Hong770ab052018-11-02 13:43:30 -070057 return None
58
59
Yifan Hong351b6b82020-07-27 18:49:41 -070060def dump_from_release(input_bytes, key):
61 """
62 Helper of dump_version and dump_release
63 """
Yifan Hong770ab052018-11-02 13:43:30 -070064 idx = 0
65 while True:
66 idx = input_bytes.find(LINUX_BANNER_PREFIX, idx)
67 if idx < 0:
68 return None
69
Yifan Hong351b6b82020-07-27 18:49:41 -070070 value = get_from_release(input_bytes, idx, key)
71 if value:
72 return value
Yifan Hong770ab052018-11-02 13:43:30 -070073
74 idx += len(LINUX_BANNER_PREFIX)
75
76
Yifan Hong351b6b82020-07-27 18:49:41 -070077def dump_version(input_bytes):
78 """
79 Dump kernel version, w.x.y, from input_bytes. Search for the string
80 "Linux version " and do pattern matching after it. See LINUX_BANNER_REGEX.
81 """
82 return dump_from_release(input_bytes, "version")
83
84
Yongqin Liu2c8b8ec2020-08-08 14:32:47 +080085def dump_compiler(input_bytes):
86 """
87 Dump kernel version, w.x.y, from input_bytes. Search for the string
88 "Linux version " and do pattern matching after it. See LINUX_BANNER_REGEX.
89 """
90 return dump_from_release(input_bytes, "compiler")
91
92
Yifan Hong351b6b82020-07-27 18:49:41 -070093def dump_release(input_bytes):
94 """
95 Dump kernel release, w.x.y-..., from input_bytes. Search for the string
96 "Linux version " and do pattern matching after it. See LINUX_BANNER_REGEX.
97 """
98 return dump_from_release(input_bytes, "release")
99
100
Yifan Hong770ab052018-11-02 13:43:30 -0700101def dump_configs(input_bytes):
102 """
103 Dump kernel configuration from input_bytes. This can be done when
104 CONFIG_IKCONFIG is enabled, which is a requirement on Treble devices.
105
106 The kernel configuration is archived in GZip format right after the magic
107 string 'IKCFG_ST' in the built kernel.
108 """
109
110 # Search for magic string + GZip header
111 idx = input_bytes.find(CONFIG_PREFIX + GZIP_HEADER)
112 if idx < 0:
113 return None
114
115 # Seek to the start of the archive
116 idx += len(CONFIG_PREFIX)
117
118 sp = subprocess.Popen(["gzip", "-d", "-c"], stdin=subprocess.PIPE,
119 stdout=subprocess.PIPE, stderr=subprocess.PIPE)
120 o, _ = sp.communicate(input=input_bytes[idx:])
121 if sp.returncode == 1: # error
122 return None
123
124 # success or trailing garbage warning
125 assert sp.returncode in (0, 2), sp.returncode
126
127 return o
128
129
Yifan Hong8b727762019-09-04 12:40:13 -0700130def try_decompress_bytes(cmd, input_bytes):
Yifan Hong770ab052018-11-02 13:43:30 -0700131 sp = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE,
132 stderr=subprocess.PIPE)
Yifan Hong8b727762019-09-04 12:40:13 -0700133 o, _ = sp.communicate(input=input_bytes)
Yifan Hong770ab052018-11-02 13:43:30 -0700134 # ignore errors
135 return o
136
137
Yifan Hong8b727762019-09-04 12:40:13 -0700138def try_decompress(cmd, search_bytes, input_bytes):
139 idx = 0
140 while True:
141 idx = input_bytes.find(search_bytes, idx)
142 if idx < 0:
143 raise StopIteration()
144
145 yield try_decompress_bytes(cmd, input_bytes[idx:])
146 idx += 1
147
148
Yifan Hong770ab052018-11-02 13:43:30 -0700149def decompress_dump(func, input_bytes):
150 """
151 Run func(input_bytes) first; and if that fails (returns value evaluates to
152 False), then try different decompression algorithm before running func.
153 """
154 o = func(input_bytes)
155 if o:
156 return o
157 for cmd, search_bytes in COMPRESSION_ALGO:
Yifan Hong8b727762019-09-04 12:40:13 -0700158 for decompressed in try_decompress(cmd, search_bytes, input_bytes):
159 if decompressed:
160 o = decompress_dump(func, decompressed)
161 if o:
162 return o
Yifan Hong770ab052018-11-02 13:43:30 -0700163 # Force decompress the whole file even if header doesn't match
Yifan Hong8b727762019-09-04 12:40:13 -0700164 decompressed = try_decompress_bytes(cmd, input_bytes)
Yifan Hong770ab052018-11-02 13:43:30 -0700165 if decompressed:
Yifan Hong8b727762019-09-04 12:40:13 -0700166 o = decompress_dump(func, decompressed)
Yifan Hong770ab052018-11-02 13:43:30 -0700167 if o:
168 return o
169
Yifan Hong351b6b82020-07-27 18:49:41 -0700170
171def dump_to_file(f, dump_fn, input_bytes, desc):
172 """
173 Call decompress_dump(dump_fn, input_bytes) and write to f. If it fails, return
174 False; otherwise return True.
175 """
176 if f is not None:
177 o = decompress_dump(dump_fn, input_bytes)
178 if o:
179 f.write(o)
180 else:
181 sys.stderr.write(
182 "Cannot extract kernel {}".format(desc))
183 return False
184 return True
185
186
Yifan Hong770ab052018-11-02 13:43:30 -0700187def main():
188 parser = argparse.ArgumentParser(
189 formatter_class=argparse.RawTextHelpFormatter,
190 description=__doc__ +
191 "\nThese algorithms are tried when decompressing the image:\n " +
192 " ".join(tup[0][0] for tup in COMPRESSION_ALGO))
193 parser.add_argument('--input',
194 help='Input kernel image. If not specified, use stdin',
195 metavar='FILE',
196 type=argparse.FileType('rb'),
197 default=sys.stdin)
198 parser.add_argument('--output-configs',
199 help='If specified, write configs. Use stdout if no file '
200 'is specified.',
201 metavar='FILE',
202 nargs='?',
203 type=argparse.FileType('wb'),
204 const=sys.stdout)
205 parser.add_argument('--output-version',
206 help='If specified, write version. Use stdout if no file '
207 'is specified.',
208 metavar='FILE',
209 nargs='?',
210 type=argparse.FileType('wb'),
211 const=sys.stdout)
Yifan Hong351b6b82020-07-27 18:49:41 -0700212 parser.add_argument('--output-release',
213 help='If specified, write kernel release. Use stdout if '
214 'no file is specified.',
215 metavar='FILE',
216 nargs='?',
217 type=argparse.FileType('wb'),
218 const=sys.stdout)
Yongqin Liu2c8b8ec2020-08-08 14:32:47 +0800219 parser.add_argument('--output-compiler',
220 help='If specified, write the compiler information. Use stdout if no file '
221 'is specified.',
222 metavar='FILE',
223 nargs='?',
224 type=argparse.FileType('wb'),
225 const=sys.stdout)
Yifan Hong770ab052018-11-02 13:43:30 -0700226 parser.add_argument('--tools',
227 help='Decompression tools to use. If not specified, PATH '
228 'is searched.',
229 metavar='ALGORITHM:EXECUTABLE',
230 nargs='*')
231 args = parser.parse_args()
232
233 tools = {pair[0]: pair[1]
234 for pair in (token.split(':') for token in args.tools or [])}
235 for cmd, _ in COMPRESSION_ALGO:
236 if cmd[0] in tools:
237 cmd[0] = tools[cmd[0]]
238
239 input_bytes = args.input.read()
240
241 ret = 0
Yifan Hong351b6b82020-07-27 18:49:41 -0700242 if not dump_to_file(args.output_configs, dump_configs, input_bytes,
243 "configs in {}".format(args.input.name)):
244 ret = 1
245 if not dump_to_file(args.output_version, dump_version, input_bytes,
246 "version in {}".format(args.input.name)):
247 ret = 1
248 if not dump_to_file(args.output_release, dump_release, input_bytes,
249 "kernel release in {}".format(args.input.name)):
250 ret = 1
Yifan Hong770ab052018-11-02 13:43:30 -0700251
Yongqin Liu2c8b8ec2020-08-08 14:32:47 +0800252 if not dump_to_file(args.output_compiler, dump_compiler, input_bytes,
253 "kernel compiler in {}".format(args.input.name)):
254 ret = 1
255
Yifan Hong770ab052018-11-02 13:43:30 -0700256 return ret
257
258
259if __name__ == '__main__':
Yifan Hong351b6b82020-07-27 18:49:41 -0700260 sys.exit(main())