blob: 1eedb67c09b46acbebc5f262592ca255b896bdc1 [file] [log] [blame]
David Browndbc57272017-07-17 15:38:54 -06001#! /usr/bin/env python3
David Brownb730e242017-12-20 11:10:55 -07002#
3# Copyright 2017 Linaro Limited
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.
David Browndbc57272017-07-17 15:38:54 -060016
17"""
18Assemble multiple images into a single image that can be flashed on the device.
19"""
20
21import argparse
David Brown2cf522c2017-07-20 12:15:31 -060022import errno
David Browndbc57272017-07-17 15:38:54 -060023import io
24import re
Fabio Utzig6ec2ec32020-07-10 09:26:14 -030025import os
David Browndbc57272017-07-17 15:38:54 -060026import os.path
Kumar Gala45b00ac2020-05-11 15:33:03 -050027import sys
28
David Browndbc57272017-07-17 15:38:54 -060029def same_keys(a, b):
30 """Determine if the dicts a and b have the same keys in them"""
31 for ak in a.keys():
32 if ak not in b:
33 return False
34 for bk in b.keys():
35 if bk not in a:
36 return False
37 return True
38
Fabio Utzig539d7662019-09-05 10:57:00 -030039offset_re = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_OFFSET(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
40size_re = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_SIZE(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
David Browndbc57272017-07-17 15:38:54 -060041
42class Assembly():
Kumar Gala45b00ac2020-05-11 15:33:03 -050043 def __init__(self, output, bootdir, edt):
44 self.find_slots(edt)
David Brown2cf522c2017-07-20 12:15:31 -060045 try:
46 os.unlink(output)
47 except OSError as e:
48 if e.errno != errno.ENOENT:
49 raise
David Browndbc57272017-07-17 15:38:54 -060050 self.output = output
51
Kumar Gala45b00ac2020-05-11 15:33:03 -050052 def find_slots(self, edt):
David Browndbc57272017-07-17 15:38:54 -060053 offsets = {}
54 sizes = {}
Kumar Gala45b00ac2020-05-11 15:33:03 -050055
56 part_nodes = edt.compat2nodes["fixed-partitions"]
57 for node in part_nodes:
58 for child in node.children.values():
59 if "label" in child.props:
60 label = child.props["label"].val
61 offsets[label] = child.regs[0].addr
62 sizes[label] = child.regs[0].size
David Browndbc57272017-07-17 15:38:54 -060063
64 if not same_keys(offsets, sizes):
Ulf Magnussone96b6872020-01-13 12:06:44 +010065 raise Exception("Inconsistent data in devicetree.h")
David Browndbc57272017-07-17 15:38:54 -060066
Kumar Gala45b00ac2020-05-11 15:33:03 -050067 # We care about the mcuboot, image-0, and image-1 partitions.
68 if 'mcuboot' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060069 raise Exception("Board partition table does not have mcuboot partition")
70
Kumar Gala45b00ac2020-05-11 15:33:03 -050071 if 'image-0' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060072 raise Exception("Board partition table does not have image-0 partition")
73
Kumar Gala45b00ac2020-05-11 15:33:03 -050074 if 'image-1' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060075 raise Exception("Board partition table does not have image-1 partition")
76
77 self.offsets = offsets
78 self.sizes = sizes
79
80 def add_image(self, source, partition):
81 with open(self.output, 'ab') as ofd:
82 pos = ofd.tell()
83 print("partition {}, pos={}, offset={}".format(partition, pos, self.offsets[partition]))
84 if pos > self.offsets[partition]:
85 raise Exception("Partitions not in order, unsupported")
86 if pos < self.offsets[partition]:
87 buf = b'\xFF' * (self.offsets[partition] - pos)
88 ofd.write(buf)
89 with open(source, 'rb') as rfd:
90 ibuf = rfd.read()
91 if len(ibuf) > self.sizes[partition]:
92 raise Exception("Image {} is too large for partition".format(source))
93 ofd.write(ibuf)
94
Viktor Sjölindf1e6e9c2020-07-08 12:22:08 +020095def find_board_name(bootdir):
96 suffix = ".dts.pre.tmp"
97
98 for _, _, files in os.walk(os.path.join(bootdir, "zephyr")):
99 for filename in files:
100 if filename.endswith(suffix):
101 return filename[:-len(suffix)]
102
103
David Browndbc57272017-07-17 15:38:54 -0600104def main():
105 parser = argparse.ArgumentParser()
106
107 parser.add_argument('-b', '--bootdir', required=True,
108 help='Directory of built bootloader')
109 parser.add_argument('-p', '--primary', required=True,
110 help='Signed image file for primary image')
111 parser.add_argument('-s', '--secondary',
112 help='Signed image file for secondary image')
113 parser.add_argument('-o', '--output', required=True,
114 help='Filename to write full image to')
Fabio Utzig6ec2ec32020-07-10 09:26:14 -0300115 parser.add_argument('-z', '--zephyr-base',
116 help='Zephyr base containing the Zephyr repository')
David Browndbc57272017-07-17 15:38:54 -0600117
118 args = parser.parse_args()
David Browndbc57272017-07-17 15:38:54 -0600119
Fabio Utzig6ec2ec32020-07-10 09:26:14 -0300120 zephyr_base = args.zephyr_base
121 if zephyr_base is None:
122 try:
123 zephyr_base = os.environ['ZEPHYR_BASE']
124 except KeyError:
125 print('Need to either have ZEPHYR_BASE in environment or pass in -z')
126 sys.exit(1)
127
128 sys.path.insert(0, os.path.join(zephyr_base, "scripts", "dts"))
Torsten Rasmussen33fbef52020-06-03 20:21:13 +0200129 import edtlib
130
Viktor Sjölindf1e6e9c2020-07-08 12:22:08 +0200131 board = find_board_name(args.bootdir)
Kumar Gala45b00ac2020-05-11 15:33:03 -0500132
133 dts_path = os.path.join(args.bootdir, "zephyr", board + ".dts.pre.tmp")
134
Fabio Utzig6ec2ec32020-07-10 09:26:14 -0300135 edt = edtlib.EDT(dts_path, [os.path.join(zephyr_base, "dts", "bindings")],
Kumar Gala45b00ac2020-05-11 15:33:03 -0500136 warn_reg_unit_address_mismatch=False)
137
138 output = Assembly(args.output, args.bootdir, edt)
139
140 output.add_image(os.path.join(args.bootdir, 'zephyr', 'zephyr.bin'), 'mcuboot')
141 output.add_image(args.primary, "image-0")
David Browndbc57272017-07-17 15:38:54 -0600142 if args.secondary is not None:
Kumar Gala45b00ac2020-05-11 15:33:03 -0500143 output.add_image(args.secondary, "image-1")
David Browndbc57272017-07-17 15:38:54 -0600144
145if __name__ == '__main__':
146 main()