blob: 05f9793798f4a67243a35358f080591a00b11f5c [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
Martí Bolívarcaa1f6b2021-12-06 10:49:52 -080029import pickle
Kumar Gala45b00ac2020-05-11 15:33:03 -050030import sys
31
David Browndbc57272017-07-17 15:38:54 -060032def same_keys(a, b):
33 """Determine if the dicts a and b have the same keys in them"""
34 for ak in a.keys():
35 if ak not in b:
36 return False
37 for bk in b.keys():
38 if bk not in a:
39 return False
40 return True
41
Fabio Utzig539d7662019-09-05 10:57:00 -030042offset_re = re.compile(r"^#define DT_FLASH_AREA_([0-9A-Z_]+)_OFFSET(_0)?\s+(0x[0-9a-fA-F]+|[0-9]+)$")
43size_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 -060044
45class Assembly():
Kumar Gala45b00ac2020-05-11 15:33:03 -050046 def __init__(self, output, bootdir, edt):
47 self.find_slots(edt)
David Brown2cf522c2017-07-20 12:15:31 -060048 try:
49 os.unlink(output)
50 except OSError as e:
51 if e.errno != errno.ENOENT:
52 raise
David Browndbc57272017-07-17 15:38:54 -060053 self.output = output
54
Kumar Gala45b00ac2020-05-11 15:33:03 -050055 def find_slots(self, edt):
David Browndbc57272017-07-17 15:38:54 -060056 offsets = {}
57 sizes = {}
Kumar Gala45b00ac2020-05-11 15:33:03 -050058
59 part_nodes = edt.compat2nodes["fixed-partitions"]
60 for node in part_nodes:
61 for child in node.children.values():
62 if "label" in child.props:
63 label = child.props["label"].val
64 offsets[label] = child.regs[0].addr
65 sizes[label] = child.regs[0].size
David Browndbc57272017-07-17 15:38:54 -060066
67 if not same_keys(offsets, sizes):
Ulf Magnussone96b6872020-01-13 12:06:44 +010068 raise Exception("Inconsistent data in devicetree.h")
David Browndbc57272017-07-17 15:38:54 -060069
Kumar Gala45b00ac2020-05-11 15:33:03 -050070 # We care about the mcuboot, image-0, and image-1 partitions.
71 if 'mcuboot' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060072 raise Exception("Board partition table does not have mcuboot partition")
73
Kumar Gala45b00ac2020-05-11 15:33:03 -050074 if 'image-0' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060075 raise Exception("Board partition table does not have image-0 partition")
76
Kumar Gala45b00ac2020-05-11 15:33:03 -050077 if 'image-1' not in offsets:
David Browndbc57272017-07-17 15:38:54 -060078 raise Exception("Board partition table does not have image-1 partition")
79
80 self.offsets = offsets
81 self.sizes = sizes
82
83 def add_image(self, source, partition):
84 with open(self.output, 'ab') as ofd:
85 pos = ofd.tell()
86 print("partition {}, pos={}, offset={}".format(partition, pos, self.offsets[partition]))
87 if pos > self.offsets[partition]:
88 raise Exception("Partitions not in order, unsupported")
89 if pos < self.offsets[partition]:
90 buf = b'\xFF' * (self.offsets[partition] - pos)
91 ofd.write(buf)
92 with open(source, 'rb') as rfd:
93 ibuf = rfd.read()
94 if len(ibuf) > self.sizes[partition]:
95 raise Exception("Image {} is too large for partition".format(source))
96 ofd.write(ibuf)
97
Viktor Sjölindf1e6e9c2020-07-08 12:22:08 +020098def find_board_name(bootdir):
Martí Bolívarcaa1f6b2021-12-06 10:49:52 -080099 dot_config = os.path.join(bootdir, "zephyr", ".config")
100 with open(dot_config, "r") as f:
101 for line in f:
102 if line.startswith("CONFIG_BOARD="):
103 return line.split("=", 1)[1].strip('"')
104 raise Exception("Expected CONFIG_BOARD line in {}".format(dot_config))
Viktor Sjölindf1e6e9c2020-07-08 12:22:08 +0200105
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
Carl-Johan Landinf44fd612021-06-30 11:31:34 +0200130 sys.path.insert(0, os.path.join(zephyr_base, "scripts", "dts", "python-devicetree", "src"))
131 import devicetree.edtlib
Torsten Rasmussen33fbef52020-06-03 20:21:13 +0200132
Viktor Sjölindf1e6e9c2020-07-08 12:22:08 +0200133 board = find_board_name(args.bootdir)
Kumar Gala45b00ac2020-05-11 15:33:03 -0500134
Martí Bolívarcaa1f6b2021-12-06 10:49:52 -0800135 edt_pickle = os.path.join(args.bootdir, "zephyr", "edt.pickle")
136 with open(edt_pickle, 'rb') as f:
137 edt = pickle.load(f)
138 assert isinstance(edt, devicetree.edtlib.EDT)
Kumar Gala45b00ac2020-05-11 15:33:03 -0500139
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()