blob: 934f28e43029db496934673d961e241d04e38869 [file] [log] [blame]
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -07001#!/usr/bin/env python
2# Copyright 2015, The Android Open Source Project
3#
4# Licensed under the Apache License, Version 2.0 (the "License");
5# you may not use this file except in compliance with the License.
6# You may obtain a copy of the License at
7#
8# http://www.apache.org/licenses/LICENSE-2.0
9#
10# Unless required by applicable law or agreed to in writing, software
11# distributed under the License is distributed on an "AS IS" BASIS,
12# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13# See the License for the specific language governing permissions and
14# limitations under the License.
15
16from __future__ import print_function
17from sys import argv, exit, stderr
18from argparse import ArgumentParser, FileType, Action
19from os import fstat
20from struct import pack
21from hashlib import sha1
Bernhard Rosenkränzerc434cf82016-02-23 20:54:35 +010022import sys
Sami Tolvanend1628282016-03-14 09:08:59 -070023import re
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070024
25def filesize(f):
26 if f is None:
27 return 0
28 try:
29 return fstat(f.fileno()).st_size
30 except OSError:
31 return 0
32
33
34def update_sha(sha, f):
35 if f:
36 sha.update(f.read())
37 f.seek(0)
38 sha.update(pack('I', filesize(f)))
39 else:
40 sha.update(pack('I', 0))
41
42
43def pad_file(f, padding):
44 pad = (padding - (f.tell() & (padding - 1))) & (padding - 1)
45 f.write(pack(str(pad) + 'x'))
46
47
Hridya Valsaraju26e01bb2018-05-31 12:39:58 -070048def get_number_of_pages(image_size, page_size):
49 """calculates the number of pages required for the image"""
50 return (image_size + page_size - 1) / page_size
51
52
53def get_recovery_dtbo_offset(args):
54 """calculates the offset of recovery_dtbo image in the boot image"""
55 num_header_pages = 1 # header occupies a page
56 num_kernel_pages = get_number_of_pages(filesize(args.kernel), args.pagesize)
57 num_ramdisk_pages = get_number_of_pages(filesize(args.ramdisk), args.pagesize)
58 num_second_pages = get_number_of_pages(filesize(args.second), args.pagesize)
59 dtbo_offset = args.pagesize * (num_header_pages + num_kernel_pages +
60 num_ramdisk_pages + num_second_pages)
61 return dtbo_offset
62
63
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070064def write_header(args):
Hridya Valsarajua057a332019-01-24 15:59:15 -080065 BOOT_IMAGE_HEADER_V1_SIZE = 1648
66 BOOT_IMAGE_HEADER_V2_SIZE = 1660
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070067 BOOT_MAGIC = 'ANDROID!'.encode()
Hridya Valsarajua057a332019-01-24 15:59:15 -080068
69 if (args.header_version > 2):
70 raise ValueError('Boot header version %d not supported' % args.header_version)
71
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070072 args.output.write(pack('8s', BOOT_MAGIC))
Sami Tolvanend1628282016-03-14 09:08:59 -070073 args.output.write(pack('10I',
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070074 filesize(args.kernel), # size in bytes
75 args.base + args.kernel_offset, # physical load addr
76 filesize(args.ramdisk), # size in bytes
77 args.base + args.ramdisk_offset, # physical load addr
78 filesize(args.second), # size in bytes
79 args.base + args.second_offset, # physical load addr
80 args.base + args.tags_offset, # physical addr for kernel tags
Sami Tolvanend1628282016-03-14 09:08:59 -070081 args.pagesize, # flash page size we assume
Hridya Valsaraju147b3552018-03-20 15:26:00 -070082 args.header_version, # version of bootimage header
Sami Tolvanend1628282016-03-14 09:08:59 -070083 (args.os_version << 11) | args.os_patch_level)) # os version and patch level
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070084 args.output.write(pack('16s', args.board.encode())) # asciiz product name
85 args.output.write(pack('512s', args.cmdline[:512].encode()))
86
87 sha = sha1()
88 update_sha(sha, args.kernel)
89 update_sha(sha, args.ramdisk)
90 update_sha(sha, args.second)
Hridya Valsaraju147b3552018-03-20 15:26:00 -070091
92 if args.header_version > 0:
93 update_sha(sha, args.recovery_dtbo)
Hridya Valsarajuad518bd2019-01-22 08:58:27 -080094 if args.header_version > 1:
95 update_sha(sha, args.dtb)
Hridya Valsaraju147b3552018-03-20 15:26:00 -070096
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070097 img_id = pack('32s', sha.digest())
98
99 args.output.write(img_id)
100 args.output.write(pack('1024s', args.cmdline[512:].encode()))
Hridya Valsaraju147b3552018-03-20 15:26:00 -0700101
102 if args.header_version > 0:
Hridya Valsaraju26e01bb2018-05-31 12:39:58 -0700103 args.output.write(pack('I', filesize(args.recovery_dtbo))) # size in bytes
104 if args.recovery_dtbo:
105 args.output.write(pack('Q', get_recovery_dtbo_offset(args))) # recovery dtbo offset
106 else:
107 args.output.write(pack('Q', 0)) # Will be set to 0 for devices without a recovery dtbo
Hridya Valsaraju147b3552018-03-20 15:26:00 -0700108
Hridya Valsarajua057a332019-01-24 15:59:15 -0800109 # Populate boot image header size for header versions 1 and 2.
110 if args.header_version == 1:
111 args.output.write(pack('I', BOOT_IMAGE_HEADER_V1_SIZE))
112 elif args.header_version == 2:
113 args.output.write(pack('I', BOOT_IMAGE_HEADER_V2_SIZE))
Hridya Valsarajuad518bd2019-01-22 08:58:27 -0800114
115 if args.header_version > 1:
Hridya Valsaraju96fd8872019-05-17 16:43:25 -0700116
117 if filesize(args.dtb) == 0:
118 raise ValueError("DTB image must not be empty.")
119
Hridya Valsarajuad518bd2019-01-22 08:58:27 -0800120 args.output.write(pack('I', filesize(args.dtb))) # size in bytes
121 args.output.write(pack('Q', args.base + args.dtb_offset)) # dtb physical load address
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700122 pad_file(args.output, args.pagesize)
123 return img_id
124
125
126class ValidateStrLenAction(Action):
127 def __init__(self, option_strings, dest, nargs=None, **kwargs):
128 if 'maxlen' not in kwargs:
129 raise ValueError('maxlen must be set')
130 self.maxlen = int(kwargs['maxlen'])
131 del kwargs['maxlen']
132 super(ValidateStrLenAction, self).__init__(option_strings, dest, **kwargs)
133
134 def __call__(self, parser, namespace, values, option_string=None):
135 if len(values) > self.maxlen:
136 raise ValueError('String argument too long: max {0:d}, got {1:d}'.
137 format(self.maxlen, len(values)))
138 setattr(namespace, self.dest, values)
139
140
141def write_padded_file(f_out, f_in, padding):
142 if f_in is None:
143 return
144 f_out.write(f_in.read())
145 pad_file(f_out, padding)
146
147
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700148def parse_int(x):
Rom Lemarchanda8221d32015-06-04 09:59:01 -0700149 return int(x, 0)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700150
Sami Tolvanend1628282016-03-14 09:08:59 -0700151def parse_os_version(x):
152 match = re.search(r'^(\d{1,3})(?:\.(\d{1,3})(?:\.(\d{1,3}))?)?', x)
153 if match:
Sami Tolvanen294eb9d2016-03-29 16:06:37 -0700154 a = int(match.group(1))
Sami Tolvanend1628282016-03-14 09:08:59 -0700155 b = c = 0
156 if match.lastindex >= 2:
Sami Tolvanen294eb9d2016-03-29 16:06:37 -0700157 b = int(match.group(2))
Sami Tolvanend1628282016-03-14 09:08:59 -0700158 if match.lastindex == 3:
Sami Tolvanen294eb9d2016-03-29 16:06:37 -0700159 c = int(match.group(3))
Sami Tolvanend1628282016-03-14 09:08:59 -0700160 # 7 bits allocated for each field
161 assert a < 128
162 assert b < 128
163 assert c < 128
164 return (a << 14) | (b << 7) | c
165 return 0
166
167def parse_os_patch_level(x):
168 match = re.search(r'^(\d{4})-(\d{2})-(\d{2})', x)
169 if match:
Sami Tolvanen294eb9d2016-03-29 16:06:37 -0700170 y = int(match.group(1)) - 2000
171 m = int(match.group(2))
Sami Tolvanend1628282016-03-14 09:08:59 -0700172 # 7 bits allocated for the year, 4 bits for the month
173 assert y >= 0 and y < 128
174 assert m > 0 and m <= 12
175 return (y << 4) | m
176 return 0
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700177
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700178def parse_cmdline():
179 parser = ArgumentParser()
180 parser.add_argument('--kernel', help='path to the kernel', type=FileType('rb'),
181 required=True)
182 parser.add_argument('--ramdisk', help='path to the ramdisk', type=FileType('rb'))
183 parser.add_argument('--second', help='path to the 2nd bootloader', type=FileType('rb'))
Hridya Valsarajuad518bd2019-01-22 08:58:27 -0800184 parser.add_argument('--dtb', help='path to dtb', type=FileType('rb'))
Chen, ZhiminX97f13252018-08-30 14:30:32 +0800185 recovery_dtbo_group = parser.add_mutually_exclusive_group()
186 recovery_dtbo_group.add_argument('--recovery_dtbo', help='path to the recovery DTBO', type=FileType('rb'))
187 recovery_dtbo_group.add_argument('--recovery_acpio', help='path to the recovery ACPIO',
188 type=FileType('rb'), metavar='RECOVERY_ACPIO', dest='recovery_dtbo')
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700189 parser.add_argument('--cmdline', help='extra arguments to be passed on the '
190 'kernel command line', default='', action=ValidateStrLenAction, maxlen=1536)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700191 parser.add_argument('--base', help='base address', type=parse_int, default=0x10000000)
Rom Lemarchanda8221d32015-06-04 09:59:01 -0700192 parser.add_argument('--kernel_offset', help='kernel offset', type=parse_int, default=0x00008000)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700193 parser.add_argument('--ramdisk_offset', help='ramdisk offset', type=parse_int, default=0x01000000)
194 parser.add_argument('--second_offset', help='2nd bootloader offset', type=parse_int,
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700195 default=0x00f00000)
Hridya Valsarajuad518bd2019-01-22 08:58:27 -0800196 parser.add_argument('--dtb_offset', help='dtb offset', type=parse_int, default=0x01f00000)
197
Sami Tolvanend1628282016-03-14 09:08:59 -0700198 parser.add_argument('--os_version', help='operating system version', type=parse_os_version,
199 default=0)
200 parser.add_argument('--os_patch_level', help='operating system patch level',
201 type=parse_os_patch_level, default=0)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700202 parser.add_argument('--tags_offset', help='tags offset', type=parse_int, default=0x00000100)
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700203 parser.add_argument('--board', help='board name', default='', action=ValidateStrLenAction,
204 maxlen=16)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700205 parser.add_argument('--pagesize', help='page size', type=parse_int,
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700206 choices=[2**i for i in range(11,15)], default=2048)
207 parser.add_argument('--id', help='print the image ID on standard output',
208 action='store_true')
Hridya Valsaraju147b3552018-03-20 15:26:00 -0700209 parser.add_argument('--header_version', help='boot image header version', type=parse_int, default=0)
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700210 parser.add_argument('-o', '--output', help='output file name', type=FileType('wb'),
211 required=True)
212 return parser.parse_args()
213
214
215def write_data(args):
216 write_padded_file(args.output, args.kernel, args.pagesize)
217 write_padded_file(args.output, args.ramdisk, args.pagesize)
218 write_padded_file(args.output, args.second, args.pagesize)
219
Hridya Valsaraju147b3552018-03-20 15:26:00 -0700220 if args.header_version > 0:
221 write_padded_file(args.output, args.recovery_dtbo, args.pagesize)
Hridya Valsarajuad518bd2019-01-22 08:58:27 -0800222 if args.header_version > 1:
223 write_padded_file(args.output, args.dtb, args.pagesize)
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700224
225def main():
226 args = parse_cmdline()
227 img_id = write_header(args)
228 write_data(args)
229 if args.id:
Bernhard Rosenkränzerc434cf82016-02-23 20:54:35 +0100230 if isinstance(img_id, str):
231 # Python 2's struct.pack returns a string, but py3 returns bytes.
232 img_id = [ord(x) for x in img_id]
233 print('0x' + ''.join('{:02x}'.format(c) for c in img_id))
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700234
235if __name__ == '__main__':
236 main()