blob: 94abea5c38e32edbf4214a7e1a4ba8d9cff5d183 [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glassbf7fd502016-11-25 20:15:51 -07002# Copyright (c) 2016 Google, Inc
3# Written by Simon Glass <sjg@chromium.org>
4#
Simon Glassbf7fd502016-11-25 20:15:51 -07005# Creates binary images from input files controlled by a description
6#
7
8from collections import OrderedDict
Simon Glass87d43322020-08-05 13:27:46 -06009import glob
Jan Kiszkade65b122023-04-22 16:42:48 +020010try:
11 import importlib.resources
Simon Glasse2259612023-06-01 10:22:25 -060012except ImportError: # pragma: no cover
Jan Kiszkade65b122023-04-22 16:42:48 +020013 # for Python 3.6
14 import importlib_resources
Simon Glassbf7fd502016-11-25 20:15:51 -070015import os
Simon Glass9fbfaba2020-08-29 11:36:14 -060016import pkg_resources
Simon Glassb2381432020-09-06 10:39:09 -060017import re
Simon Glass9fbfaba2020-08-29 11:36:14 -060018
Simon Glassbf7fd502016-11-25 20:15:51 -070019import sys
Simon Glassbf7fd502016-11-25 20:15:51 -070020
Simon Glass386c63c2022-01-09 20:13:50 -070021from binman import bintool
Simon Glass16287932020-04-17 18:09:03 -060022from binman import cbfs_util
Simon Glass7960a0a2022-08-07 09:46:46 -060023from binman import elf
24from binman import entry
Simon Glassf6abd522023-07-18 07:24:04 -060025from dtoc import fdt_util
Simon Glass4583c002023-02-23 18:18:04 -070026from u_boot_pylib import command
27from u_boot_pylib import tools
28from u_boot_pylib import tout
Simon Glassbf7fd502016-11-25 20:15:51 -070029
Simon Glass8d2ef3e2022-02-11 13:23:21 -070030# These are imported if needed since they import libfdt
31state = None
32Image = None
33
Simon Glassbf7fd502016-11-25 20:15:51 -070034# List of images we plan to create
35# Make this global so that it can be referenced from tests
36images = OrderedDict()
37
Simon Glassb2381432020-09-06 10:39:09 -060038# Help text for each type of missing blob, dict:
39# key: Value of the entry's 'missing-msg' or entry name
40# value: Text for the help
41missing_blob_help = {}
42
Simon Glass0b6023e2021-03-18 20:25:06 +130043def _ReadImageDesc(binman_node, use_expanded):
Simon Glassbf7fd502016-11-25 20:15:51 -070044 """Read the image descriptions from the /binman node
45
46 This normally produces a single Image object called 'image'. But if
47 multiple images are present, they will all be returned.
48
49 Args:
50 binman_node: Node object of the /binman node
Simon Glass0b6023e2021-03-18 20:25:06 +130051 use_expanded: True if the FDT will be updated with the entry information
Simon Glassbf7fd502016-11-25 20:15:51 -070052 Returns:
53 OrderedDict of Image objects, each of which describes an image
54 """
Simon Glass8d2ef3e2022-02-11 13:23:21 -070055 # For Image()
56 # pylint: disable=E1102
Simon Glassbf7fd502016-11-25 20:15:51 -070057 images = OrderedDict()
58 if 'multiple-images' in binman_node.props:
59 for node in binman_node.subnodes:
Simon Glass35f72fb2023-07-18 07:24:05 -060060 if 'template' not in node.name:
61 images[node.name] = Image(node.name, node,
62 use_expanded=use_expanded)
Simon Glassbf7fd502016-11-25 20:15:51 -070063 else:
Simon Glass0b6023e2021-03-18 20:25:06 +130064 images['image'] = Image('image', binman_node, use_expanded=use_expanded)
Simon Glassbf7fd502016-11-25 20:15:51 -070065 return images
66
Simon Glassec3f3782017-05-27 07:38:29 -060067def _FindBinmanNode(dtb):
Simon Glassbf7fd502016-11-25 20:15:51 -070068 """Find the 'binman' node in the device tree
69
70 Args:
Simon Glassec3f3782017-05-27 07:38:29 -060071 dtb: Fdt object to scan
Simon Glassbf7fd502016-11-25 20:15:51 -070072 Returns:
73 Node object of /binman node, or None if not found
74 """
Simon Glassec3f3782017-05-27 07:38:29 -060075 for node in dtb.GetRoot().subnodes:
Simon Glassbf7fd502016-11-25 20:15:51 -070076 if node.name == 'binman':
77 return node
78 return None
79
Simon Glassb2381432020-09-06 10:39:09 -060080def _ReadMissingBlobHelp():
81 """Read the missing-blob-help file
82
83 This file containins help messages explaining what to do when external blobs
84 are missing.
85
86 Returns:
87 Dict:
88 key: Message tag (str)
89 value: Message text (str)
90 """
91
92 def _FinishTag(tag, msg, result):
93 if tag:
94 result[tag] = msg.rstrip()
95 tag = None
96 msg = ''
97 return tag, msg
98
99 my_data = pkg_resources.resource_string(__name__, 'missing-blob-help')
100 re_tag = re.compile('^([-a-z0-9]+):$')
101 result = {}
102 tag = None
103 msg = ''
104 for line in my_data.decode('utf-8').splitlines():
105 if not line.startswith('#'):
106 m_tag = re_tag.match(line)
107 if m_tag:
108 _, msg = _FinishTag(tag, msg, result)
109 tag = m_tag.group(1)
110 elif tag:
111 msg += line + '\n'
112 _FinishTag(tag, msg, result)
113 return result
114
Jonas Karlmand92c4dd2023-07-18 20:34:35 +0000115def _ShowBlobHelp(level, path, text):
Jonas Karlmanc2600152023-07-18 20:34:37 +0000116 tout.do_output(level, '%s:' % path)
Simon Glassb2381432020-09-06 10:39:09 -0600117 for line in text.splitlines():
Jonas Karlmand92c4dd2023-07-18 20:34:35 +0000118 tout.do_output(level, ' %s' % line)
Jonas Karlmanc2600152023-07-18 20:34:37 +0000119 tout.do_output(level, '')
Simon Glassb2381432020-09-06 10:39:09 -0600120
Jonas Karlmand92c4dd2023-07-18 20:34:35 +0000121def _ShowHelpForMissingBlobs(level, missing_list):
Simon Glassb2381432020-09-06 10:39:09 -0600122 """Show help for each missing blob to help the user take action
123
124 Args:
125 missing_list: List of Entry objects to show help for
126 """
127 global missing_blob_help
128
129 if not missing_blob_help:
130 missing_blob_help = _ReadMissingBlobHelp()
131
132 for entry in missing_list:
133 tags = entry.GetHelpTags()
134
135 # Show the first match help message
136 for tag in tags:
137 if tag in missing_blob_help:
Jonas Karlmand92c4dd2023-07-18 20:34:35 +0000138 _ShowBlobHelp(level, entry._node.path, missing_blob_help[tag])
Simon Glassb2381432020-09-06 10:39:09 -0600139 break
140
Simon Glass87d43322020-08-05 13:27:46 -0600141def GetEntryModules(include_testing=True):
142 """Get a set of entry class implementations
143
144 Returns:
145 Set of paths to entry class filenames
146 """
Simon Glass9fbfaba2020-08-29 11:36:14 -0600147 glob_list = pkg_resources.resource_listdir(__name__, 'etype')
148 glob_list = [fname for fname in glob_list if fname.endswith('.py')]
Simon Glass87d43322020-08-05 13:27:46 -0600149 return set([os.path.splitext(os.path.basename(item))[0]
150 for item in glob_list
151 if include_testing or '_testing' not in item])
152
Simon Glassc55a50f2018-09-14 04:57:19 -0600153def WriteEntryDocs(modules, test_missing=None):
154 """Write out documentation for all entries
Simon Glassecab8972018-07-06 10:27:40 -0600155
156 Args:
Simon Glassc55a50f2018-09-14 04:57:19 -0600157 modules: List of Module objects to get docs for
Simon Glassbc570642022-01-09 20:14:11 -0700158 test_missing: Used for testing only, to force an entry's documentation
Simon Glassc55a50f2018-09-14 04:57:19 -0600159 to show as missing even if it is present. Should be set to None in
160 normal use.
Simon Glassecab8972018-07-06 10:27:40 -0600161 """
Simon Glass16287932020-04-17 18:09:03 -0600162 from binman.entry import Entry
Simon Glassfd8d1f72018-07-17 13:25:36 -0600163 Entry.WriteDocs(modules, test_missing)
164
Simon Glass61f564d2019-07-08 14:25:48 -0600165
Simon Glassbc570642022-01-09 20:14:11 -0700166def write_bintool_docs(modules, test_missing=None):
167 """Write out documentation for all bintools
168
169 Args:
170 modules: List of Module objects to get docs for
171 test_missing: Used for testing only, to force an entry's documentation
172 to show as missing even if it is present. Should be set to None in
173 normal use.
174 """
175 bintool.Bintool.WriteDocs(modules, test_missing)
176
177
Simon Glass61f564d2019-07-08 14:25:48 -0600178def ListEntries(image_fname, entry_paths):
179 """List the entries in an image
180
181 This decodes the supplied image and displays a table of entries from that
182 image, preceded by a header.
183
184 Args:
185 image_fname: Image filename to process
186 entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*',
187 'section/u-boot'])
188 """
189 image = Image.FromFile(image_fname)
190
191 entries, lines, widths = image.GetListEntries(entry_paths)
192
193 num_columns = len(widths)
194 for linenum, line in enumerate(lines):
195 if linenum == 1:
196 # Print header line
197 print('-' * (sum(widths) + num_columns * 2))
198 out = ''
199 for i, item in enumerate(line):
200 width = -widths[i]
201 if item.startswith('>'):
202 width = -width
203 item = item[1:]
204 txt = '%*s ' % (width, item)
205 out += txt
206 print(out.rstrip())
207
Simon Glassf667e452019-07-08 14:25:50 -0600208
209def ReadEntry(image_fname, entry_path, decomp=True):
210 """Extract an entry from an image
211
212 This extracts the data from a particular entry in an image
213
214 Args:
215 image_fname: Image filename to process
216 entry_path: Path to entry to extract
217 decomp: True to return uncompressed data, if the data is compress
218 False to return the raw data
219
220 Returns:
221 data extracted from the entry
222 """
Simon Glass8dbb7442019-08-24 07:22:44 -0600223 global Image
Simon Glass07237982020-08-05 13:27:47 -0600224 from binman.image import Image
Simon Glass8dbb7442019-08-24 07:22:44 -0600225
Simon Glassf667e452019-07-08 14:25:50 -0600226 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier917b3c32022-08-19 16:25:22 +0200227 image.CollectBintools()
Simon Glassf667e452019-07-08 14:25:50 -0600228 entry = image.FindEntryPath(entry_path)
229 return entry.ReadData(decomp)
230
231
Simon Glass943bf782021-11-23 21:09:50 -0700232def ShowAltFormats(image):
233 """Show alternative formats available for entries in the image
234
235 This shows a list of formats available.
236
237 Args:
238 image (Image): Image to check
239 """
240 alt_formats = {}
241 image.CheckAltFormats(alt_formats)
242 print('%-10s %-20s %s' % ('Flag (-F)', 'Entry type', 'Description'))
243 for name, val in alt_formats.items():
244 entry, helptext = val
245 print('%-10s %-20s %s' % (name, entry.etype, helptext))
246
247
Simon Glass71ce0ba2019-07-08 14:25:52 -0600248def ExtractEntries(image_fname, output_fname, outdir, entry_paths,
Simon Glass943bf782021-11-23 21:09:50 -0700249 decomp=True, alt_format=None):
Simon Glass71ce0ba2019-07-08 14:25:52 -0600250 """Extract the data from one or more entries and write it to files
251
252 Args:
253 image_fname: Image filename to process
254 output_fname: Single output filename to use if extracting one file, None
255 otherwise
256 outdir: Output directory to use (for any number of files), else None
257 entry_paths: List of entry paths to extract
Simon Glass3ad804e2019-07-20 12:24:12 -0600258 decomp: True to decompress the entry data
Simon Glass71ce0ba2019-07-08 14:25:52 -0600259
260 Returns:
261 List of EntryInfo records that were written
262 """
263 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier917b3c32022-08-19 16:25:22 +0200264 image.CollectBintools()
Simon Glass71ce0ba2019-07-08 14:25:52 -0600265
Simon Glass943bf782021-11-23 21:09:50 -0700266 if alt_format == 'list':
267 ShowAltFormats(image)
268 return
269
Simon Glass71ce0ba2019-07-08 14:25:52 -0600270 # Output an entry to a single file, as a special case
271 if output_fname:
272 if not entry_paths:
Simon Glassbb5edc12019-07-20 12:24:14 -0600273 raise ValueError('Must specify an entry path to write with -f')
Simon Glass71ce0ba2019-07-08 14:25:52 -0600274 if len(entry_paths) != 1:
Simon Glassbb5edc12019-07-20 12:24:14 -0600275 raise ValueError('Must specify exactly one entry path to write with -f')
Simon Glass71ce0ba2019-07-08 14:25:52 -0600276 entry = image.FindEntryPath(entry_paths[0])
Simon Glass943bf782021-11-23 21:09:50 -0700277 data = entry.ReadData(decomp, alt_format)
Simon Glassc1aa66e2022-01-29 14:14:04 -0700278 tools.write_file(output_fname, data)
Simon Glassf3385a52022-01-29 14:14:15 -0700279 tout.notice("Wrote %#x bytes to file '%s'" % (len(data), output_fname))
Simon Glass71ce0ba2019-07-08 14:25:52 -0600280 return
281
282 # Otherwise we will output to a path given by the entry path of each entry.
283 # This means that entries will appear in subdirectories if they are part of
284 # a sub-section.
285 einfos = image.GetListEntries(entry_paths)[0]
Simon Glassf3385a52022-01-29 14:14:15 -0700286 tout.notice('%d entries match and will be written' % len(einfos))
Simon Glass71ce0ba2019-07-08 14:25:52 -0600287 for einfo in einfos:
288 entry = einfo.entry
Simon Glass943bf782021-11-23 21:09:50 -0700289 data = entry.ReadData(decomp, alt_format)
Simon Glass71ce0ba2019-07-08 14:25:52 -0600290 path = entry.GetPath()[1:]
291 fname = os.path.join(outdir, path)
292
293 # If this entry has children, create a directory for it and put its
294 # data in a file called 'root' in that directory
295 if entry.GetEntries():
Simon Glass862ddf92021-03-18 20:24:51 +1300296 if fname and not os.path.exists(fname):
Simon Glass71ce0ba2019-07-08 14:25:52 -0600297 os.makedirs(fname)
298 fname = os.path.join(fname, 'root')
Simon Glassf3385a52022-01-29 14:14:15 -0700299 tout.notice("Write entry '%s' size %x to '%s'" %
Simon Glass5b378e42021-01-06 21:35:13 -0700300 (entry.GetPath(), len(data), fname))
Simon Glassc1aa66e2022-01-29 14:14:04 -0700301 tools.write_file(fname, data)
Simon Glass71ce0ba2019-07-08 14:25:52 -0600302 return einfos
303
304
Simon Glassd7fa4e42019-07-20 12:24:13 -0600305def BeforeReplace(image, allow_resize):
306 """Handle getting an image ready for replacing entries in it
307
308 Args:
309 image: Image to prepare
310 """
311 state.PrepareFromLoadedData(image)
Alper Nebi Yasak8ee4ec92022-03-27 18:31:45 +0300312 image.CollectBintools()
Lukas Funke7a52a452023-07-18 13:53:10 +0200313 image.LoadData(decomp=False)
Simon Glassd7fa4e42019-07-20 12:24:13 -0600314
315 # If repacking, drop the old offset/size values except for the original
316 # ones, so we are only left with the constraints.
Alper Nebi Yasake2ce4fb2022-03-27 18:31:46 +0300317 if image.allow_repack and allow_resize:
Simon Glassd7fa4e42019-07-20 12:24:13 -0600318 image.ResetForPack()
319
320
321def ReplaceOneEntry(image, entry, data, do_compress, allow_resize):
322 """Handle replacing a single entry an an image
323
324 Args:
325 image: Image to update
326 entry: Entry to write
327 data: Data to replace with
328 do_compress: True to compress the data if needed, False if data is
329 already compressed so should be used as is
330 allow_resize: True to allow entries to change size (this does a re-pack
331 of the entries), False to raise an exception
332 """
333 if not entry.WriteData(data, do_compress):
334 if not image.allow_repack:
335 entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
336 if not allow_resize:
337 entry.Raise('Entry data size does not match, but resize is disabled')
338
339
340def AfterReplace(image, allow_resize, write_map):
341 """Handle write out an image after replacing entries in it
342
343 Args:
344 image: Image to write
345 allow_resize: True to allow entries to change size (this does a re-pack
346 of the entries), False to raise an exception
347 write_map: True to write a map file
348 """
Simon Glassf3385a52022-01-29 14:14:15 -0700349 tout.info('Processing image')
Simon Glassd7fa4e42019-07-20 12:24:13 -0600350 ProcessImage(image, update_fdt=True, write_map=write_map,
351 get_contents=False, allow_resize=allow_resize)
352
353
354def WriteEntryToImage(image, entry, data, do_compress=True, allow_resize=True,
355 write_map=False):
356 BeforeReplace(image, allow_resize)
Simon Glassf3385a52022-01-29 14:14:15 -0700357 tout.info('Writing data to %s' % entry.GetPath())
Simon Glassd7fa4e42019-07-20 12:24:13 -0600358 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
359 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
360
361
Simon Glass3ad804e2019-07-20 12:24:12 -0600362def WriteEntry(image_fname, entry_path, data, do_compress=True,
363 allow_resize=True, write_map=False):
Simon Glass22a76b72019-07-20 12:24:11 -0600364 """Replace an entry in an image
365
366 This replaces the data in a particular entry in an image. This size of the
367 new data must match the size of the old data unless allow_resize is True.
368
369 Args:
370 image_fname: Image filename to process
371 entry_path: Path to entry to extract
372 data: Data to replace with
Simon Glass3ad804e2019-07-20 12:24:12 -0600373 do_compress: True to compress the data if needed, False if data is
Simon Glass22a76b72019-07-20 12:24:11 -0600374 already compressed so should be used as is
375 allow_resize: True to allow entries to change size (this does a re-pack
376 of the entries), False to raise an exception
Simon Glass3ad804e2019-07-20 12:24:12 -0600377 write_map: True to write a map file
Simon Glass22a76b72019-07-20 12:24:11 -0600378
379 Returns:
380 Image object that was updated
381 """
Simon Glassf3385a52022-01-29 14:14:15 -0700382 tout.info("Write entry '%s', file '%s'" % (entry_path, image_fname))
Simon Glass22a76b72019-07-20 12:24:11 -0600383 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier917b3c32022-08-19 16:25:22 +0200384 image.CollectBintools()
Simon Glass22a76b72019-07-20 12:24:11 -0600385 entry = image.FindEntryPath(entry_path)
Simon Glassd7fa4e42019-07-20 12:24:13 -0600386 WriteEntryToImage(image, entry, data, do_compress=do_compress,
387 allow_resize=allow_resize, write_map=write_map)
Simon Glass22a76b72019-07-20 12:24:11 -0600388
Simon Glass22a76b72019-07-20 12:24:11 -0600389 return image
390
Simon Glassa6cb9952019-07-20 12:24:15 -0600391
392def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
393 do_compress=True, allow_resize=True, write_map=False):
394 """Replace the data from one or more entries from input files
395
396 Args:
397 image_fname: Image filename to process
Jan Kiszka89cc0522021-11-11 08:13:30 +0100398 input_fname: Single input filename to use if replacing one file, None
Simon Glassa6cb9952019-07-20 12:24:15 -0600399 otherwise
400 indir: Input directory to use (for any number of files), else None
Jan Kiszka89cc0522021-11-11 08:13:30 +0100401 entry_paths: List of entry paths to replace
Simon Glassa6cb9952019-07-20 12:24:15 -0600402 do_compress: True if the input data is uncompressed and may need to be
403 compressed if the entry requires it, False if the data is already
404 compressed.
405 write_map: True to write a map file
406
407 Returns:
408 List of EntryInfo records that were written
409 """
Jan Kiszkac700f102021-11-11 08:14:18 +0100410 image_fname = os.path.abspath(image_fname)
Simon Glassa6cb9952019-07-20 12:24:15 -0600411 image = Image.FromFile(image_fname)
412
Simon Glass7caa3722023-03-02 17:02:44 -0700413 image.mark_build_done()
414
Simon Glassa6cb9952019-07-20 12:24:15 -0600415 # Replace an entry from a single file, as a special case
416 if input_fname:
417 if not entry_paths:
418 raise ValueError('Must specify an entry path to read with -f')
419 if len(entry_paths) != 1:
420 raise ValueError('Must specify exactly one entry path to write with -f')
421 entry = image.FindEntryPath(entry_paths[0])
Simon Glassc1aa66e2022-01-29 14:14:04 -0700422 data = tools.read_file(input_fname)
Simon Glassf3385a52022-01-29 14:14:15 -0700423 tout.notice("Read %#x bytes from file '%s'" % (len(data), input_fname))
Simon Glassa6cb9952019-07-20 12:24:15 -0600424 WriteEntryToImage(image, entry, data, do_compress=do_compress,
425 allow_resize=allow_resize, write_map=write_map)
426 return
427
428 # Otherwise we will input from a path given by the entry path of each entry.
429 # This means that files must appear in subdirectories if they are part of
430 # a sub-section.
431 einfos = image.GetListEntries(entry_paths)[0]
Simon Glassf3385a52022-01-29 14:14:15 -0700432 tout.notice("Replacing %d matching entries in image '%s'" %
Simon Glassa6cb9952019-07-20 12:24:15 -0600433 (len(einfos), image_fname))
434
435 BeforeReplace(image, allow_resize)
436
437 for einfo in einfos:
438 entry = einfo.entry
439 if entry.GetEntries():
Simon Glassf3385a52022-01-29 14:14:15 -0700440 tout.info("Skipping section entry '%s'" % entry.GetPath())
Simon Glassa6cb9952019-07-20 12:24:15 -0600441 continue
442
443 path = entry.GetPath()[1:]
444 fname = os.path.join(indir, path)
445
446 if os.path.exists(fname):
Simon Glassf3385a52022-01-29 14:14:15 -0700447 tout.notice("Write entry '%s' from file '%s'" %
Simon Glassa6cb9952019-07-20 12:24:15 -0600448 (entry.GetPath(), fname))
Simon Glassc1aa66e2022-01-29 14:14:04 -0700449 data = tools.read_file(fname)
Simon Glassa6cb9952019-07-20 12:24:15 -0600450 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
451 else:
Simon Glassf3385a52022-01-29 14:14:15 -0700452 tout.warning("Skipping entry '%s' from missing file '%s'" %
Simon Glassa6cb9952019-07-20 12:24:15 -0600453 (entry.GetPath(), fname))
454
455 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
456 return image
457
Ivan Mikhaylov4023dc92023-03-08 01:13:39 +0000458def SignEntries(image_fname, input_fname, privatekey_fname, algo, entry_paths,
459 write_map=False):
460 """Sign and replace the data from one or more entries from input files
461
462 Args:
463 image_fname: Image filename to process
464 input_fname: Single input filename to use if replacing one file, None
465 otherwise
466 algo: Hashing algorithm
467 entry_paths: List of entry paths to sign
468 privatekey_fname: Private key filename
469 write_map (bool): True to write the map file
470 """
471 image_fname = os.path.abspath(image_fname)
472 image = Image.FromFile(image_fname)
473
Ivan Mikhaylov5b34efe2023-03-08 01:13:40 +0000474 image.mark_build_done()
475
Ivan Mikhaylov4023dc92023-03-08 01:13:39 +0000476 BeforeReplace(image, allow_resize=True)
477
478 for entry_path in entry_paths:
479 entry = image.FindEntryPath(entry_path)
480 entry.UpdateSignatures(privatekey_fname, algo, input_fname)
481
482 AfterReplace(image, allow_resize=True, write_map=write_map)
Simon Glassa6cb9952019-07-20 12:24:15 -0600483
Simon Glassf6abd522023-07-18 07:24:04 -0600484def _ProcessTemplates(parent):
485 """Handle any templates in the binman description
486
487 Args:
488 parent: Binman node to process (typically /binman)
489
490 Search though each target node looking for those with an 'insert-template'
491 property. Use that as a list of references to template nodes to use to
492 adjust the target node.
493
494 Processing involves copying each subnode of the template node into the
495 target node.
496
Simon Glass696f2b72023-07-18 07:24:07 -0600497 This is done recursively, so templates can be at any level of the binman
498 image, e.g. inside a section.
Simon Glassf6abd522023-07-18 07:24:04 -0600499
500 See 'Templates' in the Binman documnentation for details.
501 """
502 for node in parent.subnodes:
503 tmpl = fdt_util.GetPhandleList(node, 'insert-template')
504 if tmpl:
505 node.copy_subnodes_from_phandles(tmpl)
Simon Glass696f2b72023-07-18 07:24:07 -0600506 _ProcessTemplates(node)
Simon Glassf6abd522023-07-18 07:24:04 -0600507
Simon Glass0b6023e2021-03-18 20:25:06 +1300508def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt, use_expanded):
Simon Glassa8573c42019-07-20 12:23:27 -0600509 """Prepare the images to be processed and select the device tree
510
511 This function:
512 - reads in the device tree
513 - finds and scans the binman node to create all entries
514 - selects which images to build
515 - Updates the device tress with placeholder properties for offset,
516 image-pos, etc.
517
518 Args:
519 dtb_fname: Filename of the device tree file to use (.dts or .dtb)
520 selected_images: List of images to output, or None for all
521 update_fdt: True to update the FDT wth entry offsets, etc.
Simon Glass0b6023e2021-03-18 20:25:06 +1300522 use_expanded: True to use expanded versions of entries, if available.
523 So if 'u-boot' is called for, we use 'u-boot-expanded' instead. This
524 is needed if update_fdt is True (although tests may disable it)
Simon Glasse9d336d2020-09-01 05:13:55 -0600525
526 Returns:
527 OrderedDict of images:
528 key: Image name (str)
529 value: Image object
Simon Glassa8573c42019-07-20 12:23:27 -0600530 """
531 # Import these here in case libfdt.py is not available, in which case
532 # the above help option still works.
Simon Glass16287932020-04-17 18:09:03 -0600533 from dtoc import fdt
534 from dtoc import fdt_util
Simon Glassa8573c42019-07-20 12:23:27 -0600535 global images
536
537 # Get the device tree ready by compiling it and copying the compiled
538 # output into a file in our output directly. Then scan it for use
539 # in binman.
540 dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
Simon Glassc1aa66e2022-01-29 14:14:04 -0700541 fname = tools.get_output_filename('u-boot.dtb.out')
542 tools.write_file(fname, tools.read_file(dtb_fname))
Simon Glassa8573c42019-07-20 12:23:27 -0600543 dtb = fdt.FdtScan(fname)
544
545 node = _FindBinmanNode(dtb)
546 if not node:
547 raise ValueError("Device tree '%s' does not have a 'binman' "
548 "node" % dtb_fname)
549
Simon Glassf6abd522023-07-18 07:24:04 -0600550 _ProcessTemplates(node)
551
Simon Glass0b6023e2021-03-18 20:25:06 +1300552 images = _ReadImageDesc(node, use_expanded)
Simon Glassa8573c42019-07-20 12:23:27 -0600553
554 if select_images:
555 skip = []
556 new_images = OrderedDict()
557 for name, image in images.items():
558 if name in select_images:
559 new_images[name] = image
560 else:
561 skip.append(name)
562 images = new_images
Simon Glassf3385a52022-01-29 14:14:15 -0700563 tout.notice('Skipping images: %s' % ', '.join(skip))
Simon Glassa8573c42019-07-20 12:23:27 -0600564
565 state.Prepare(images, dtb)
566
567 # Prepare the device tree by making sure that any missing
568 # properties are added (e.g. 'pos' and 'size'). The values of these
569 # may not be correct yet, but we add placeholders so that the
570 # size of the device tree is correct. Later, in
571 # SetCalculatedProperties() we will insert the correct values
572 # without changing the device-tree size, thus ensuring that our
573 # entry offsets remain the same.
574 for image in images.values():
Simon Glassc9ee33a2022-03-05 20:19:00 -0700575 image.gen_entries()
Stefan Herbrechtsmeier917b3c32022-08-19 16:25:22 +0200576 image.CollectBintools()
Simon Glassa8573c42019-07-20 12:23:27 -0600577 if update_fdt:
Simon Glassa9fad072020-10-26 17:40:17 -0600578 image.AddMissingProperties(True)
Simon Glassa8573c42019-07-20 12:23:27 -0600579 image.ProcessFdt(dtb)
580
Simon Glass4bdd1152019-07-20 12:23:29 -0600581 for dtb_item in state.GetAllFdts():
Simon Glassa8573c42019-07-20 12:23:27 -0600582 dtb_item.Sync(auto_resize=True)
583 dtb_item.Pack()
584 dtb_item.Flush()
585 return images
586
587
Simon Glass51014aa2019-07-20 12:23:56 -0600588def ProcessImage(image, update_fdt, write_map, get_contents=True,
Heiko Thierya89c8f22022-01-06 11:49:41 +0100589 allow_resize=True, allow_missing=False,
590 allow_fake_blobs=False):
Simon Glassb88e81c2019-07-20 12:23:24 -0600591 """Perform all steps for this image, including checking and # writing it.
592
593 This means that errors found with a later image will be reported after
594 earlier images are already completed and written, but that does not seem
595 important.
596
597 Args:
598 image: Image to process
599 update_fdt: True to update the FDT wth entry offsets, etc.
600 write_map: True to write a map file
Simon Glass10f9d002019-07-20 12:23:50 -0600601 get_contents: True to get the image contents from files, etc., False if
602 the contents is already present
Simon Glass51014aa2019-07-20 12:23:56 -0600603 allow_resize: True to allow entries to change size (this does a re-pack
604 of the entries), False to raise an exception
Simon Glass4f9f1052020-07-09 18:39:38 -0600605 allow_missing: Allow blob_ext objects to be missing
Heiko Thierya89c8f22022-01-06 11:49:41 +0100606 allow_fake_blobs: Allow blob_ext objects to be faked with dummy files
Simon Glassb1cca952020-07-09 18:39:40 -0600607
608 Returns:
Heiko Thierya89c8f22022-01-06 11:49:41 +0100609 True if one or more external blobs are missing or faked,
610 False if all are present
Simon Glassb88e81c2019-07-20 12:23:24 -0600611 """
Simon Glass10f9d002019-07-20 12:23:50 -0600612 if get_contents:
Simon Glass4f9f1052020-07-09 18:39:38 -0600613 image.SetAllowMissing(allow_missing)
Heiko Thierya89c8f22022-01-06 11:49:41 +0100614 image.SetAllowFakeBlob(allow_fake_blobs)
Simon Glass10f9d002019-07-20 12:23:50 -0600615 image.GetEntryContents()
Simon Glassc8c9f312023-01-07 14:07:12 -0700616 image.drop_absent()
Simon Glassb88e81c2019-07-20 12:23:24 -0600617 image.GetEntryOffsets()
618
619 # We need to pack the entries to figure out where everything
620 # should be placed. This sets the offset/size of each entry.
621 # However, after packing we call ProcessEntryContents() which
622 # may result in an entry changing size. In that case we need to
623 # do another pass. Since the device tree often contains the
624 # final offset/size information we try to make space for this in
625 # AddMissingProperties() above. However, if the device is
626 # compressed we cannot know this compressed size in advance,
627 # since changing an offset from 0x100 to 0x104 (for example) can
628 # alter the compressed size of the device tree. So we need a
629 # third pass for this.
Simon Glasseb0f4a42019-07-20 12:24:06 -0600630 passes = 5
Simon Glassb88e81c2019-07-20 12:23:24 -0600631 for pack_pass in range(passes):
632 try:
633 image.PackEntries()
Simon Glassb88e81c2019-07-20 12:23:24 -0600634 except Exception as e:
635 if write_map:
636 fname = image.WriteMap()
637 print("Wrote map file '%s' to show errors" % fname)
638 raise
639 image.SetImagePos()
640 if update_fdt:
641 image.SetCalculatedProperties()
Simon Glass4bdd1152019-07-20 12:23:29 -0600642 for dtb_item in state.GetAllFdts():
Simon Glassb88e81c2019-07-20 12:23:24 -0600643 dtb_item.Sync()
Simon Glass51014aa2019-07-20 12:23:56 -0600644 dtb_item.Flush()
Simon Glass261cbe02019-08-24 07:23:12 -0600645 image.WriteSymbols()
Simon Glassb88e81c2019-07-20 12:23:24 -0600646 sizes_ok = image.ProcessEntryContents()
647 if sizes_ok:
648 break
649 image.ResetForPack()
Simon Glassf3385a52022-01-29 14:14:15 -0700650 tout.info('Pack completed after %d pass(es)' % (pack_pass + 1))
Simon Glassb88e81c2019-07-20 12:23:24 -0600651 if not sizes_ok:
Simon Glass61ec04f2019-07-20 12:23:58 -0600652 image.Raise('Entries changed size after packing (tried %s passes)' %
Simon Glassb88e81c2019-07-20 12:23:24 -0600653 passes)
654
Simon Glassb88e81c2019-07-20 12:23:24 -0600655 image.BuildImage()
656 if write_map:
657 image.WriteMap()
Simon Glass67a05012023-01-07 14:07:15 -0700658
Simon Glassb1cca952020-07-09 18:39:40 -0600659 missing_list = []
660 image.CheckMissing(missing_list)
661 if missing_list:
Jonas Karlmanc2600152023-07-18 20:34:37 +0000662 tout.error("Image '%s' is missing external blobs and is non-functional: %s\n" %
Jonas Karlmand92c4dd2023-07-18 20:34:35 +0000663 (image.name, ' '.join([e.name for e in missing_list])))
664 _ShowHelpForMissingBlobs(tout.ERROR, missing_list)
Simon Glass67a05012023-01-07 14:07:15 -0700665
Heiko Thierya89c8f22022-01-06 11:49:41 +0100666 faked_list = []
667 image.CheckFakedBlobs(faked_list)
668 if faked_list:
Simon Glassf3385a52022-01-29 14:14:15 -0700669 tout.warning(
Jonas Karlmanc2600152023-07-18 20:34:37 +0000670 "Image '%s' has faked external blobs and is non-functional: %s\n" %
Simon Glass2cc8c1f2022-01-09 20:13:45 -0700671 (image.name, ' '.join([os.path.basename(e.GetDefaultFilename())
672 for e in faked_list])))
Simon Glass67a05012023-01-07 14:07:15 -0700673
674 optional_list = []
675 image.CheckOptional(optional_list)
676 if optional_list:
677 tout.warning(
Jonas Karlmanc2600152023-07-18 20:34:37 +0000678 "Image '%s' is missing optional external blobs but is still functional: %s\n" %
Simon Glass67a05012023-01-07 14:07:15 -0700679 (image.name, ' '.join([e.name for e in optional_list])))
Jonas Karlmand92c4dd2023-07-18 20:34:35 +0000680 _ShowHelpForMissingBlobs(tout.WARNING, optional_list)
Simon Glass67a05012023-01-07 14:07:15 -0700681
Simon Glass4f9ee832022-01-09 20:14:09 -0700682 missing_bintool_list = []
683 image.check_missing_bintools(missing_bintool_list)
684 if missing_bintool_list:
Simon Glassf3385a52022-01-29 14:14:15 -0700685 tout.warning(
Jonas Karlmanc2600152023-07-18 20:34:37 +0000686 "Image '%s' has missing bintools and is non-functional: %s\n" %
Simon Glass4f9ee832022-01-09 20:14:09 -0700687 (image.name, ' '.join([os.path.basename(bintool.name)
688 for bintool in missing_bintool_list])))
689 return any([missing_list, faked_list, missing_bintool_list])
Simon Glassb88e81c2019-07-20 12:23:24 -0600690
691
Simon Glass53cd5d92019-07-08 14:25:29 -0600692def Binman(args):
Simon Glassbf7fd502016-11-25 20:15:51 -0700693 """The main control code for binman
694
695 This assumes that help and test options have already been dealt with. It
696 deals with the core task of building images.
697
698 Args:
Simon Glass53cd5d92019-07-08 14:25:29 -0600699 args: Command line arguments Namespace object
Simon Glassbf7fd502016-11-25 20:15:51 -0700700 """
Simon Glass8dbb7442019-08-24 07:22:44 -0600701 global Image
702 global state
703
Simon Glass53cd5d92019-07-08 14:25:29 -0600704 if args.full_help:
Simon Glass8de6adb2023-02-23 18:18:20 -0700705 with importlib.resources.path('binman', 'README.rst') as readme:
706 tools.print_full_help(str(readme))
Simon Glassbf7fd502016-11-25 20:15:51 -0700707 return 0
708
Simon Glass8dbb7442019-08-24 07:22:44 -0600709 # Put these here so that we can import this module without libfdt
Simon Glass07237982020-08-05 13:27:47 -0600710 from binman.image import Image
Simon Glass16287932020-04-17 18:09:03 -0600711 from binman import state
Simon Glass8dbb7442019-08-24 07:22:44 -0600712
Simon Glassfe7e9242023-02-22 12:14:49 -0700713 tool_paths = []
714 if args.toolpath:
715 tool_paths += args.toolpath
716 if args.tooldir:
717 tool_paths.append(args.tooldir)
718 tools.set_tool_paths(tool_paths or None)
719 bintool.Bintool.set_tool_dir(args.tooldir)
720
Ivan Mikhaylov4023dc92023-03-08 01:13:39 +0000721 if args.cmd in ['ls', 'extract', 'replace', 'tool', 'sign']:
Simon Glass96b6c502019-07-20 12:23:53 -0600722 try:
Simon Glassf3385a52022-01-29 14:14:15 -0700723 tout.init(args.verbosity)
Simon Glasse00197f2023-03-02 17:02:42 -0700724 if args.cmd == 'replace':
725 tools.prepare_output_dir(args.outdir, args.preserve)
726 else:
727 tools.prepare_output_dir(None)
Simon Glass7bc4f0f2019-09-15 18:10:36 -0600728 if args.cmd == 'ls':
729 ListEntries(args.image, args.paths)
Simon Glass61f564d2019-07-08 14:25:48 -0600730
Simon Glass7bc4f0f2019-09-15 18:10:36 -0600731 if args.cmd == 'extract':
732 ExtractEntries(args.image, args.filename, args.outdir, args.paths,
Simon Glass943bf782021-11-23 21:09:50 -0700733 not args.uncompressed, args.format)
Simon Glass71ce0ba2019-07-08 14:25:52 -0600734
Simon Glass7bc4f0f2019-09-15 18:10:36 -0600735 if args.cmd == 'replace':
736 ReplaceEntries(args.image, args.filename, args.indir, args.paths,
737 do_compress=not args.compressed,
738 allow_resize=not args.fix_size, write_map=args.map)
Simon Glass386c63c2022-01-09 20:13:50 -0700739
Ivan Mikhaylov4023dc92023-03-08 01:13:39 +0000740 if args.cmd == 'sign':
741 SignEntries(args.image, args.file, args.key, args.algo, args.paths)
742
Simon Glass386c63c2022-01-09 20:13:50 -0700743 if args.cmd == 'tool':
Simon Glass386c63c2022-01-09 20:13:50 -0700744 if args.list:
745 bintool.Bintool.list_all()
746 elif args.fetch:
747 if not args.bintools:
748 raise ValueError(
749 "Please specify bintools to fetch or 'all' or 'missing'")
750 bintool.Bintool.fetch_tools(bintool.FETCH_ANY,
751 args.bintools)
752 else:
753 raise ValueError("Invalid arguments to 'tool' subcommand")
Simon Glass7bc4f0f2019-09-15 18:10:36 -0600754 except:
755 raise
Simon Glassa6cb9952019-07-20 12:24:15 -0600756 finally:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700757 tools.finalise_output_dir()
Simon Glassa6cb9952019-07-20 12:24:15 -0600758 return 0
759
Simon Glass0427bed2021-11-03 21:09:18 -0600760 elf_params = None
761 if args.update_fdt_in_elf:
762 elf_params = args.update_fdt_in_elf.split(',')
763 if len(elf_params) != 4:
764 raise ValueError('Invalid args %s to --update-fdt-in-elf: expected infile,outfile,begin_sym,end_sym' %
765 elf_params)
766
Simon Glassbf7fd502016-11-25 20:15:51 -0700767 # Try to figure out which device tree contains our image description
Simon Glass53cd5d92019-07-08 14:25:29 -0600768 if args.dt:
769 dtb_fname = args.dt
Simon Glassbf7fd502016-11-25 20:15:51 -0700770 else:
Simon Glass53cd5d92019-07-08 14:25:29 -0600771 board = args.board
Simon Glassbf7fd502016-11-25 20:15:51 -0700772 if not board:
773 raise ValueError('Must provide a board to process (use -b <board>)')
Simon Glass53cd5d92019-07-08 14:25:29 -0600774 board_pathname = os.path.join(args.build_dir, board)
Simon Glassbf7fd502016-11-25 20:15:51 -0700775 dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
Simon Glass53cd5d92019-07-08 14:25:29 -0600776 if not args.indir:
777 args.indir = ['.']
778 args.indir.append(board_pathname)
Simon Glassbf7fd502016-11-25 20:15:51 -0700779
780 try:
Simon Glassf3385a52022-01-29 14:14:15 -0700781 tout.init(args.verbosity)
Simon Glass53cd5d92019-07-08 14:25:29 -0600782 elf.debug = args.debug
783 cbfs_util.VERBOSE = args.verbosity > 2
784 state.use_fake_dtb = args.fake_dtb
Simon Glass0b6023e2021-03-18 20:25:06 +1300785
786 # Normally we replace the 'u-boot' etype with 'u-boot-expanded', etc.
787 # When running tests this can be disabled using this flag. When not
788 # updating the FDT in image, it is not needed by binman, but we use it
789 # for consistency, so that the images look the same to U-Boot at
790 # runtime.
791 use_expanded = not args.no_expanded
Simon Glassbf7fd502016-11-25 20:15:51 -0700792 try:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700793 tools.set_input_dirs(args.indir)
794 tools.prepare_output_dir(args.outdir, args.preserve)
Simon Glass53cd5d92019-07-08 14:25:29 -0600795 state.SetEntryArgs(args.entry_arg)
Simon Glassc69d19c2021-07-06 10:36:37 -0600796 state.SetThreads(args.threads)
Simon Glassecab8972018-07-06 10:27:40 -0600797
Simon Glassa8573c42019-07-20 12:23:27 -0600798 images = PrepareImagesAndDtbs(dtb_fname, args.image,
Simon Glass0b6023e2021-03-18 20:25:06 +1300799 args.update_fdt, use_expanded)
Heiko Thierya89c8f22022-01-06 11:49:41 +0100800
Simon Glassc69d19c2021-07-06 10:36:37 -0600801 if args.test_section_timeout:
802 # Set the first image to timeout, used in testThreadTimeout()
803 images[list(images.keys())[0]].test_section_timeout = True
Heiko Thierya89c8f22022-01-06 11:49:41 +0100804 invalid = False
Simon Glass4f9ee832022-01-09 20:14:09 -0700805 bintool.Bintool.set_missing_list(
806 args.force_missing_bintools.split(',') if
807 args.force_missing_bintools else None)
Simon Glass7960a0a2022-08-07 09:46:46 -0600808
809 # Create the directory here instead of Entry.check_fake_fname()
810 # since that is called from a threaded context so different threads
811 # may race to create the directory
812 if args.fake_ext_blobs:
813 entry.Entry.create_fake_dir()
814
Simon Glassbf7fd502016-11-25 20:15:51 -0700815 for image in images.values():
Heiko Thierya89c8f22022-01-06 11:49:41 +0100816 invalid |= ProcessImage(image, args.update_fdt, args.map,
817 allow_missing=args.allow_missing,
818 allow_fake_blobs=args.fake_ext_blobs)
Simon Glass2a72cc72018-09-14 04:57:20 -0600819
820 # Write the updated FDTs to our output files
Simon Glass4bdd1152019-07-20 12:23:29 -0600821 for dtb_item in state.GetAllFdts():
Simon Glassc1aa66e2022-01-29 14:14:04 -0700822 tools.write_file(dtb_item._fname, dtb_item.GetContents())
Simon Glass2a72cc72018-09-14 04:57:20 -0600823
Simon Glass0427bed2021-11-03 21:09:18 -0600824 if elf_params:
825 data = state.GetFdtForEtype('u-boot-dtb').GetContents()
826 elf.UpdateFile(*elf_params, data)
827
Simon Glassb38da152022-11-09 19:14:42 -0700828 # This can only be True if -M is provided, since otherwise binman
829 # would have raised an error already
Heiko Thierya89c8f22022-01-06 11:49:41 +0100830 if invalid:
Jonas Karlmanc2600152023-07-18 20:34:37 +0000831 msg = 'Some images are invalid'
Simon Glassb38da152022-11-09 19:14:42 -0700832 if args.ignore_missing:
833 tout.warning(msg)
834 else:
835 tout.error(msg)
836 return 103
Simon Glass03ebc202021-07-06 10:36:41 -0600837
838 # Use this to debug the time take to pack the image
839 #state.TimingShow()
Simon Glassbf7fd502016-11-25 20:15:51 -0700840 finally:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700841 tools.finalise_output_dir()
Simon Glassbf7fd502016-11-25 20:15:51 -0700842 finally:
Simon Glassf3385a52022-01-29 14:14:15 -0700843 tout.uninit()
Simon Glassbf7fd502016-11-25 20:15:51 -0700844
845 return 0