blob: ac20d050324958cfe2e7b2e6e0501a4c04bf4de0 [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
48def write_header(args):
49 BOOT_MAGIC = 'ANDROID!'.encode()
50 args.output.write(pack('8s', BOOT_MAGIC))
Sami Tolvanend1628282016-03-14 09:08:59 -070051 args.output.write(pack('10I',
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070052 filesize(args.kernel), # size in bytes
53 args.base + args.kernel_offset, # physical load addr
54 filesize(args.ramdisk), # size in bytes
55 args.base + args.ramdisk_offset, # physical load addr
56 filesize(args.second), # size in bytes
57 args.base + args.second_offset, # physical load addr
58 args.base + args.tags_offset, # physical addr for kernel tags
Sami Tolvanend1628282016-03-14 09:08:59 -070059 args.pagesize, # flash page size we assume
Hridya Valsaraju147b3552018-03-20 15:26:00 -070060 args.header_version, # version of bootimage header
Sami Tolvanend1628282016-03-14 09:08:59 -070061 (args.os_version << 11) | args.os_patch_level)) # os version and patch level
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070062 args.output.write(pack('16s', args.board.encode())) # asciiz product name
63 args.output.write(pack('512s', args.cmdline[:512].encode()))
64
65 sha = sha1()
66 update_sha(sha, args.kernel)
67 update_sha(sha, args.ramdisk)
68 update_sha(sha, args.second)
Hridya Valsaraju147b3552018-03-20 15:26:00 -070069
70 if args.header_version > 0:
71 update_sha(sha, args.recovery_dtbo)
72
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070073 img_id = pack('32s', sha.digest())
74
75 args.output.write(img_id)
76 args.output.write(pack('1024s', args.cmdline[512:].encode()))
Hridya Valsaraju147b3552018-03-20 15:26:00 -070077
78 if args.header_version > 0:
79 args.output.write(pack('I', filesize(args.recovery_dtbo))) # size in bytes
80 args.output.write(pack('Q', args.base + args.recovery_dtbo_offset)) # physical load addr
81 args.output.write(pack('I', args.output.tell() + 4)) # size of boot header
82
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -070083 pad_file(args.output, args.pagesize)
84 return img_id
85
86
87class ValidateStrLenAction(Action):
88 def __init__(self, option_strings, dest, nargs=None, **kwargs):
89 if 'maxlen' not in kwargs:
90 raise ValueError('maxlen must be set')
91 self.maxlen = int(kwargs['maxlen'])
92 del kwargs['maxlen']
93 super(ValidateStrLenAction, self).__init__(option_strings, dest, **kwargs)
94
95 def __call__(self, parser, namespace, values, option_string=None):
96 if len(values) > self.maxlen:
97 raise ValueError('String argument too long: max {0:d}, got {1:d}'.
98 format(self.maxlen, len(values)))
99 setattr(namespace, self.dest, values)
100
101
102def write_padded_file(f_out, f_in, padding):
103 if f_in is None:
104 return
105 f_out.write(f_in.read())
106 pad_file(f_out, padding)
107
108
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700109def parse_int(x):
Rom Lemarchanda8221d32015-06-04 09:59:01 -0700110 return int(x, 0)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700111
Sami Tolvanend1628282016-03-14 09:08:59 -0700112def parse_os_version(x):
113 match = re.search(r'^(\d{1,3})(?:\.(\d{1,3})(?:\.(\d{1,3}))?)?', x)
114 if match:
Sami Tolvanen294eb9d2016-03-29 16:06:37 -0700115 a = int(match.group(1))
Sami Tolvanend1628282016-03-14 09:08:59 -0700116 b = c = 0
117 if match.lastindex >= 2:
Sami Tolvanen294eb9d2016-03-29 16:06:37 -0700118 b = int(match.group(2))
Sami Tolvanend1628282016-03-14 09:08:59 -0700119 if match.lastindex == 3:
Sami Tolvanen294eb9d2016-03-29 16:06:37 -0700120 c = int(match.group(3))
Sami Tolvanend1628282016-03-14 09:08:59 -0700121 # 7 bits allocated for each field
122 assert a < 128
123 assert b < 128
124 assert c < 128
125 return (a << 14) | (b << 7) | c
126 return 0
127
128def parse_os_patch_level(x):
129 match = re.search(r'^(\d{4})-(\d{2})-(\d{2})', x)
130 if match:
Sami Tolvanen294eb9d2016-03-29 16:06:37 -0700131 y = int(match.group(1)) - 2000
132 m = int(match.group(2))
Sami Tolvanend1628282016-03-14 09:08:59 -0700133 # 7 bits allocated for the year, 4 bits for the month
134 assert y >= 0 and y < 128
135 assert m > 0 and m <= 12
136 return (y << 4) | m
137 return 0
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700138
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700139def parse_cmdline():
140 parser = ArgumentParser()
141 parser.add_argument('--kernel', help='path to the kernel', type=FileType('rb'),
142 required=True)
143 parser.add_argument('--ramdisk', help='path to the ramdisk', type=FileType('rb'))
144 parser.add_argument('--second', help='path to the 2nd bootloader', type=FileType('rb'))
Hridya Valsaraju147b3552018-03-20 15:26:00 -0700145 parser.add_argument('--recovery_dtbo', help='path to the recovery DTBO', type=FileType('rb'))
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700146 parser.add_argument('--cmdline', help='extra arguments to be passed on the '
147 'kernel command line', default='', action=ValidateStrLenAction, maxlen=1536)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700148 parser.add_argument('--base', help='base address', type=parse_int, default=0x10000000)
Rom Lemarchanda8221d32015-06-04 09:59:01 -0700149 parser.add_argument('--kernel_offset', help='kernel offset', type=parse_int, default=0x00008000)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700150 parser.add_argument('--ramdisk_offset', help='ramdisk offset', type=parse_int, default=0x01000000)
151 parser.add_argument('--second_offset', help='2nd bootloader offset', type=parse_int,
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700152 default=0x00f00000)
Hridya Valsaraju147b3552018-03-20 15:26:00 -0700153 parser.add_argument('--recovery_dtbo_offset', help='recovery dtbo offset', type=parse_int,
154 default=0x0f000000)
Sami Tolvanend1628282016-03-14 09:08:59 -0700155 parser.add_argument('--os_version', help='operating system version', type=parse_os_version,
156 default=0)
157 parser.add_argument('--os_patch_level', help='operating system patch level',
158 type=parse_os_patch_level, default=0)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700159 parser.add_argument('--tags_offset', help='tags offset', type=parse_int, default=0x00000100)
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700160 parser.add_argument('--board', help='board name', default='', action=ValidateStrLenAction,
161 maxlen=16)
Rom Lemarchand45f2ce12015-06-02 19:01:25 -0700162 parser.add_argument('--pagesize', help='page size', type=parse_int,
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700163 choices=[2**i for i in range(11,15)], default=2048)
164 parser.add_argument('--id', help='print the image ID on standard output',
165 action='store_true')
Hridya Valsaraju147b3552018-03-20 15:26:00 -0700166 parser.add_argument('--header_version', help='boot image header version', type=parse_int, default=0)
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700167 parser.add_argument('-o', '--output', help='output file name', type=FileType('wb'),
168 required=True)
169 return parser.parse_args()
170
171
172def write_data(args):
173 write_padded_file(args.output, args.kernel, args.pagesize)
174 write_padded_file(args.output, args.ramdisk, args.pagesize)
175 write_padded_file(args.output, args.second, args.pagesize)
176
Hridya Valsaraju147b3552018-03-20 15:26:00 -0700177 if args.header_version > 0:
178 write_padded_file(args.output, args.recovery_dtbo, args.pagesize)
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700179
180def main():
181 args = parse_cmdline()
182 img_id = write_header(args)
183 write_data(args)
184 if args.id:
Bernhard Rosenkränzerc434cf82016-02-23 20:54:35 +0100185 if isinstance(img_id, str):
186 # Python 2's struct.pack returns a string, but py3 returns bytes.
187 img_id = [ord(x) for x in img_id]
188 print('0x' + ''.join('{:02x}'.format(c) for c in img_id))
Rom Lemarchandad6ec0c2015-05-19 16:58:40 -0700189
190if __name__ == '__main__':
191 main()