blob: 5ef403fa6cbf02803df8ea842aefb4de32b46a7e [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#
David Brown79c4fcf2021-01-26 15:04:05 -07005# SPDX-License-Identifier: Apache-2.0
6#
David Brownb730e242017-12-20 11:10:55 -07007# Licensed under the Apache License, Version 2.0 (the "License");
8# you may not use this file except in compliance with the License.
9# You may obtain a copy of the License at
10#
11# http://www.apache.org/licenses/LICENSE-2.0
12#
13# Unless required by applicable law or agreed to in writing, software
14# distributed under the License is distributed on an "AS IS" BASIS,
15# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
David Browndbc57272017-07-17 15:38:54 -060018
19"""
20Assemble multiple images into a single image that can be flashed on the device.
21"""
22
23import argparse
David Brown2cf522c2017-07-20 12:15:31 -060024import errno
David Browndbc57272017-07-17 15:38:54 -060025import io
26import re
Fabio Utzig6ec2ec32020-07-10 09:26:14 -030027import os
David Browndbc57272017-07-17 15:38:54 -060028import os.path
Kumar Gala45b00ac2020-05-11 15:33:03 -050029import sys
30
David Browndbc57272017-07-17 15:38:54 -060031def same_keys(a, b):
32 """Determine if the dicts a and b have the same keys in them"""
33 for ak in a.keys():
34 if ak not in b:
35 return False
36 for bk in b.keys():
37 if bk not in a:
38 return False
39 return True
40
Fabio Utzig539d7662019-09-05 10:57:00 -030041offset_re = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_OFFSET(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
42size_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 -060043
44class Assembly():
Kumar Gala45b00ac2020-05-11 15:33:03 -050045 def __init__(self, output, bootdir, edt):
46 self.find_slots(edt)
David Brown2cf522c2017-07-20 12:15:31 -060047 try:
48 os.unlink(output)
49 except OSError as e:
50 if e.errno != errno.ENOENT:
51 raise
David Browndbc57272017-07-17 15:38:54 -060052 self.output = output
53
Kumar Gala45b00ac2020-05-11 15:33:03 -050054 def find_slots(self, edt):
David Browndbc57272017-07-17 15:38:54 -060055 offsets = {}
56 sizes = {}
Kumar Gala45b00ac2020-05-11 15:33:03 -050057
58 part_nodes = edt.compat2nodes["fixed-partitions"]
59 for node in part_nodes:
60 for child in node.children.values():
61 if "label" in child.props:
62 label = child.props["label"].val
63 offsets[label] = child.regs[0].addr
64 sizes[label] = child.regs[0].size
David Browndbc57272017-07-17 15:38:54 -060065
66 if not same_keys(offsets, sizes):
Ulf Magnussone96b6872020-01-13 12:06:44 +010067 raise Exception("Inconsistent data in devicetree.h")
David Browndbc57272017-07-17 15:38:54 -060068
Kumar Gala45b00ac2020-05-11 15:33:03 -050069 # We care about the mcuboot, image-0, and image-1 partitions.
70 if 'mcuboot' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060071 raise Exception("Board partition table does not have mcuboot partition")
72
Kumar Gala45b00ac2020-05-11 15:33:03 -050073 if 'image-0' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060074 raise Exception("Board partition table does not have image-0 partition")
75
Kumar Gala45b00ac2020-05-11 15:33:03 -050076 if 'image-1' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060077 raise Exception("Board partition table does not have image-1 partition")
78
79 self.offsets = offsets
80 self.sizes = sizes
81
82 def add_image(self, source, partition):
83 with open(self.output, 'ab') as ofd:
84 pos = ofd.tell()
85 print("partition {}, pos={}, offset={}".format(partition, pos, self.offsets[partition]))
86 if pos > self.offsets[partition]:
87 raise Exception("Partitions not in order, unsupported")
88 if pos < self.offsets[partition]:
89 buf = b'\xFF' * (self.offsets[partition] - pos)
90 ofd.write(buf)
91 with open(source, 'rb') as rfd:
92 ibuf = rfd.read()
93 if len(ibuf) > self.sizes[partition]:
94 raise Exception("Image {} is too large for partition".format(source))
95 ofd.write(ibuf)
96
Viktor Sjölindf1e6e9c2020-07-08 12:22:08 +020097def find_board_name(bootdir):
98 suffix = ".dts.pre.tmp"
99
100 for _, _, files in os.walk(os.path.join(bootdir, "zephyr")):
101 for filename in files:
102 if filename.endswith(suffix):
103 return filename[:-len(suffix)]
104
105
David Browndbc57272017-07-17 15:38:54 -0600106def main():
107 parser = argparse.ArgumentParser()
108
109 parser.add_argument('-b', '--bootdir', required=True,
110 help='Directory of built bootloader')
111 parser.add_argument('-p', '--primary', required=True,
112 help='Signed image file for primary image')
113 parser.add_argument('-s', '--secondary',
114 help='Signed image file for secondary image')
115 parser.add_argument('-o', '--output', required=True,
116 help='Filename to write full image to')
Fabio Utzig6ec2ec32020-07-10 09:26:14 -0300117 parser.add_argument('-z', '--zephyr-base',
118 help='Zephyr base containing the Zephyr repository')
David Browndbc57272017-07-17 15:38:54 -0600119
120 args = parser.parse_args()
David Browndbc57272017-07-17 15:38:54 -0600121
Fabio Utzig6ec2ec32020-07-10 09:26:14 -0300122 zephyr_base = args.zephyr_base
123 if zephyr_base is None:
124 try:
125 zephyr_base = os.environ['ZEPHYR_BASE']
126 except KeyError:
127 print('Need to either have ZEPHYR_BASE in environment or pass in -z')
128 sys.exit(1)
129
130 sys.path.insert(0, os.path.join(zephyr_base, "scripts", "dts"))
Torsten Rasmussen33fbef52020-06-03 20:21:13 +0200131 import edtlib
132
Viktor Sjölindf1e6e9c2020-07-08 12:22:08 +0200133 board = find_board_name(args.bootdir)
Kumar Gala45b00ac2020-05-11 15:33:03 -0500134
135 dts_path = os.path.join(args.bootdir, "zephyr", board + ".dts.pre.tmp")
136
Fabio Utzig6ec2ec32020-07-10 09:26:14 -0300137 edt = edtlib.EDT(dts_path, [os.path.join(zephyr_base, "dts", "bindings")],
Kumar Gala45b00ac2020-05-11 15:33:03 -0500138 warn_reg_unit_address_mismatch=False)
139
140 output = Assembly(args.output, args.bootdir, edt)
141
142 output.add_image(os.path.join(args.bootdir, 'zephyr', 'zephyr.bin'), 'mcuboot')
143 output.add_image(args.primary, "image-0")
David Browndbc57272017-07-17 15:38:54 -0600144 if args.secondary is not None:
Kumar Gala45b00ac2020-05-11 15:33:03 -0500145 output.add_image(args.secondary, "image-1")
David Browndbc57272017-07-17 15:38:54 -0600146
147if __name__ == '__main__':
148 main()