blob: 459489558125855887308e8182f28c1902a33255 [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass2574ef62016-11-25 20:15:51 -07002# Copyright (c) 2016 Google, Inc
3# Written by Simon Glass <sjg@chromium.org>
4#
Simon Glass2574ef62016-11-25 20:15:51 -07005# Creates binary images from input files controlled by a description
6#
7
8from collections import OrderedDict
Simon Glass220ff5f2020-08-05 13:27:46 -06009import glob
Jan Kiszka6d7c40c2023-04-22 16:42:48 +020010try:
11 import importlib.resources
Simon Glass245c52c2023-06-01 10:22:25 -060012except ImportError: # pragma: no cover
Jan Kiszka6d7c40c2023-04-22 16:42:48 +020013 # for Python 3.6
14 import importlib_resources
Simon Glass2574ef62016-11-25 20:15:51 -070015import os
Simon Glassc1dc2f82020-08-29 11:36:14 -060016import pkg_resources
Simon Glassa820af72020-09-06 10:39:09 -060017import re
Simon Glassc1dc2f82020-08-29 11:36:14 -060018
Simon Glass2574ef62016-11-25 20:15:51 -070019import sys
Simon Glass2574ef62016-11-25 20:15:51 -070020
Simon Glass4eae9252022-01-09 20:13:50 -070021from binman import bintool
Simon Glassc585dd42020-04-17 18:09:03 -060022from binman import cbfs_util
Simon Glass7d3e4072022-08-07 09:46:46 -060023from binman import elf
24from binman import entry
Simon Glassfc5569f2023-08-02 09:23:13 -060025from dtoc import fdt
Simon Glassfc792842023-07-18 07:24:04 -060026from dtoc import fdt_util
Simon Glass131444f2023-02-23 18:18:04 -070027from u_boot_pylib import command
28from u_boot_pylib import tools
29from u_boot_pylib import tout
Simon Glass2574ef62016-11-25 20:15:51 -070030
Simon Glass2a0fa982022-02-11 13:23:21 -070031# These are imported if needed since they import libfdt
32state = None
33Image = None
34
Simon Glass2574ef62016-11-25 20:15:51 -070035# List of images we plan to create
36# Make this global so that it can be referenced from tests
37images = OrderedDict()
38
Simon Glassa820af72020-09-06 10:39:09 -060039# Help text for each type of missing blob, dict:
40# key: Value of the entry's 'missing-msg' or entry name
41# value: Text for the help
42missing_blob_help = {}
43
Simon Glass55ab0b62021-03-18 20:25:06 +130044def _ReadImageDesc(binman_node, use_expanded):
Simon Glass2574ef62016-11-25 20:15:51 -070045 """Read the image descriptions from the /binman node
46
47 This normally produces a single Image object called 'image'. But if
48 multiple images are present, they will all be returned.
49
50 Args:
51 binman_node: Node object of the /binman node
Simon Glass55ab0b62021-03-18 20:25:06 +130052 use_expanded: True if the FDT will be updated with the entry information
Simon Glass2574ef62016-11-25 20:15:51 -070053 Returns:
54 OrderedDict of Image objects, each of which describes an image
55 """
Simon Glass2a0fa982022-02-11 13:23:21 -070056 # For Image()
57 # pylint: disable=E1102
Simon Glass2574ef62016-11-25 20:15:51 -070058 images = OrderedDict()
59 if 'multiple-images' in binman_node.props:
60 for node in binman_node.subnodes:
Simon Glass54825e12023-07-22 21:43:56 -060061 if not node.name.startswith('template'):
Simon Glass9909c112023-07-18 07:24:05 -060062 images[node.name] = Image(node.name, node,
63 use_expanded=use_expanded)
Simon Glass2574ef62016-11-25 20:15:51 -070064 else:
Simon Glass55ab0b62021-03-18 20:25:06 +130065 images['image'] = Image('image', binman_node, use_expanded=use_expanded)
Simon Glass2574ef62016-11-25 20:15:51 -070066 return images
67
Simon Glass22c92ca2017-05-27 07:38:29 -060068def _FindBinmanNode(dtb):
Simon Glass2574ef62016-11-25 20:15:51 -070069 """Find the 'binman' node in the device tree
70
71 Args:
Simon Glass22c92ca2017-05-27 07:38:29 -060072 dtb: Fdt object to scan
Simon Glass2574ef62016-11-25 20:15:51 -070073 Returns:
74 Node object of /binman node, or None if not found
75 """
Simon Glass22c92ca2017-05-27 07:38:29 -060076 for node in dtb.GetRoot().subnodes:
Simon Glass2574ef62016-11-25 20:15:51 -070077 if node.name == 'binman':
78 return node
79 return None
80
Simon Glassa820af72020-09-06 10:39:09 -060081def _ReadMissingBlobHelp():
82 """Read the missing-blob-help file
83
84 This file containins help messages explaining what to do when external blobs
85 are missing.
86
87 Returns:
88 Dict:
89 key: Message tag (str)
90 value: Message text (str)
91 """
92
93 def _FinishTag(tag, msg, result):
94 if tag:
95 result[tag] = msg.rstrip()
96 tag = None
97 msg = ''
98 return tag, msg
99
100 my_data = pkg_resources.resource_string(__name__, 'missing-blob-help')
101 re_tag = re.compile('^([-a-z0-9]+):$')
102 result = {}
103 tag = None
104 msg = ''
105 for line in my_data.decode('utf-8').splitlines():
106 if not line.startswith('#'):
107 m_tag = re_tag.match(line)
108 if m_tag:
109 _, msg = _FinishTag(tag, msg, result)
110 tag = m_tag.group(1)
111 elif tag:
112 msg += line + '\n'
113 _FinishTag(tag, msg, result)
114 return result
115
Jonas Karlmanda423fc2023-07-18 20:34:39 +0000116def _ShowBlobHelp(level, path, text, fname):
117 tout.do_output(level, '%s (%s):' % (path, fname))
Simon Glassa820af72020-09-06 10:39:09 -0600118 for line in text.splitlines():
Jonas Karlman34f520c2023-07-18 20:34:35 +0000119 tout.do_output(level, ' %s' % line)
Jonas Karlmana0335b42023-07-18 20:34:37 +0000120 tout.do_output(level, '')
Simon Glassa820af72020-09-06 10:39:09 -0600121
Jonas Karlman34f520c2023-07-18 20:34:35 +0000122def _ShowHelpForMissingBlobs(level, missing_list):
Simon Glassa820af72020-09-06 10:39:09 -0600123 """Show help for each missing blob to help the user take action
124
125 Args:
126 missing_list: List of Entry objects to show help for
127 """
128 global missing_blob_help
129
130 if not missing_blob_help:
131 missing_blob_help = _ReadMissingBlobHelp()
132
133 for entry in missing_list:
134 tags = entry.GetHelpTags()
135
136 # Show the first match help message
Jonas Karlmanda423fc2023-07-18 20:34:39 +0000137 shown_help = False
Simon Glassa820af72020-09-06 10:39:09 -0600138 for tag in tags:
139 if tag in missing_blob_help:
Jonas Karlmanda423fc2023-07-18 20:34:39 +0000140 _ShowBlobHelp(level, entry._node.path, missing_blob_help[tag],
141 entry.GetDefaultFilename())
142 shown_help = True
Simon Glassa820af72020-09-06 10:39:09 -0600143 break
Jonas Karlmanda423fc2023-07-18 20:34:39 +0000144 # Or a generic help message
145 if not shown_help:
146 _ShowBlobHelp(level, entry._node.path, "Missing blob",
147 entry.GetDefaultFilename())
Simon Glassa820af72020-09-06 10:39:09 -0600148
Simon Glass220ff5f2020-08-05 13:27:46 -0600149def GetEntryModules(include_testing=True):
150 """Get a set of entry class implementations
151
152 Returns:
153 Set of paths to entry class filenames
154 """
Simon Glassc1dc2f82020-08-29 11:36:14 -0600155 glob_list = pkg_resources.resource_listdir(__name__, 'etype')
156 glob_list = [fname for fname in glob_list if fname.endswith('.py')]
Simon Glass220ff5f2020-08-05 13:27:46 -0600157 return set([os.path.splitext(os.path.basename(item))[0]
158 for item in glob_list
159 if include_testing or '_testing' not in item])
160
Simon Glass29aa7362018-09-14 04:57:19 -0600161def WriteEntryDocs(modules, test_missing=None):
162 """Write out documentation for all entries
Simon Glass92307732018-07-06 10:27:40 -0600163
164 Args:
Simon Glass29aa7362018-09-14 04:57:19 -0600165 modules: List of Module objects to get docs for
Simon Glass620c4462022-01-09 20:14:11 -0700166 test_missing: Used for testing only, to force an entry's documentation
Simon Glass29aa7362018-09-14 04:57:19 -0600167 to show as missing even if it is present. Should be set to None in
168 normal use.
Simon Glass92307732018-07-06 10:27:40 -0600169 """
Simon Glassc585dd42020-04-17 18:09:03 -0600170 from binman.entry import Entry
Simon Glass969616c2018-07-17 13:25:36 -0600171 Entry.WriteDocs(modules, test_missing)
172
Simon Glassb2fd11d2019-07-08 14:25:48 -0600173
Simon Glass620c4462022-01-09 20:14:11 -0700174def write_bintool_docs(modules, test_missing=None):
175 """Write out documentation for all bintools
176
177 Args:
178 modules: List of Module objects to get docs for
179 test_missing: Used for testing only, to force an entry's documentation
180 to show as missing even if it is present. Should be set to None in
181 normal use.
182 """
183 bintool.Bintool.WriteDocs(modules, test_missing)
184
185
Simon Glassb2fd11d2019-07-08 14:25:48 -0600186def ListEntries(image_fname, entry_paths):
187 """List the entries in an image
188
189 This decodes the supplied image and displays a table of entries from that
190 image, preceded by a header.
191
192 Args:
193 image_fname: Image filename to process
194 entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*',
195 'section/u-boot'])
196 """
197 image = Image.FromFile(image_fname)
198
199 entries, lines, widths = image.GetListEntries(entry_paths)
200
201 num_columns = len(widths)
202 for linenum, line in enumerate(lines):
203 if linenum == 1:
204 # Print header line
205 print('-' * (sum(widths) + num_columns * 2))
206 out = ''
207 for i, item in enumerate(line):
208 width = -widths[i]
209 if item.startswith('>'):
210 width = -width
211 item = item[1:]
212 txt = '%*s ' % (width, item)
213 out += txt
214 print(out.rstrip())
215
Simon Glass4c613bf2019-07-08 14:25:50 -0600216
217def ReadEntry(image_fname, entry_path, decomp=True):
218 """Extract an entry from an image
219
220 This extracts the data from a particular entry in an image
221
222 Args:
223 image_fname: Image filename to process
224 entry_path: Path to entry to extract
225 decomp: True to return uncompressed data, if the data is compress
226 False to return the raw data
227
228 Returns:
229 data extracted from the entry
230 """
Simon Glassb9ba4e02019-08-24 07:22:44 -0600231 global Image
Simon Glass90cd6f02020-08-05 13:27:47 -0600232 from binman.image import Image
Simon Glassb9ba4e02019-08-24 07:22:44 -0600233
Simon Glass4c613bf2019-07-08 14:25:50 -0600234 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier47250302022-08-19 16:25:22 +0200235 image.CollectBintools()
Simon Glass4c613bf2019-07-08 14:25:50 -0600236 entry = image.FindEntryPath(entry_path)
237 return entry.ReadData(decomp)
238
239
Simon Glass637958f2021-11-23 21:09:50 -0700240def ShowAltFormats(image):
241 """Show alternative formats available for entries in the image
242
243 This shows a list of formats available.
244
245 Args:
246 image (Image): Image to check
247 """
248 alt_formats = {}
249 image.CheckAltFormats(alt_formats)
250 print('%-10s %-20s %s' % ('Flag (-F)', 'Entry type', 'Description'))
251 for name, val in alt_formats.items():
252 entry, helptext = val
253 print('%-10s %-20s %s' % (name, entry.etype, helptext))
254
255
Simon Glass980a2842019-07-08 14:25:52 -0600256def ExtractEntries(image_fname, output_fname, outdir, entry_paths,
Simon Glass637958f2021-11-23 21:09:50 -0700257 decomp=True, alt_format=None):
Simon Glass980a2842019-07-08 14:25:52 -0600258 """Extract the data from one or more entries and write it to files
259
260 Args:
261 image_fname: Image filename to process
262 output_fname: Single output filename to use if extracting one file, None
263 otherwise
264 outdir: Output directory to use (for any number of files), else None
265 entry_paths: List of entry paths to extract
Simon Glassd48f94e2019-07-20 12:24:12 -0600266 decomp: True to decompress the entry data
Simon Glass980a2842019-07-08 14:25:52 -0600267
268 Returns:
269 List of EntryInfo records that were written
270 """
271 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier47250302022-08-19 16:25:22 +0200272 image.CollectBintools()
Simon Glass980a2842019-07-08 14:25:52 -0600273
Simon Glass637958f2021-11-23 21:09:50 -0700274 if alt_format == 'list':
275 ShowAltFormats(image)
276 return
277
Simon Glass980a2842019-07-08 14:25:52 -0600278 # Output an entry to a single file, as a special case
279 if output_fname:
280 if not entry_paths:
Simon Glassa772d3f2019-07-20 12:24:14 -0600281 raise ValueError('Must specify an entry path to write with -f')
Simon Glass980a2842019-07-08 14:25:52 -0600282 if len(entry_paths) != 1:
Simon Glassa772d3f2019-07-20 12:24:14 -0600283 raise ValueError('Must specify exactly one entry path to write with -f')
Simon Glass980a2842019-07-08 14:25:52 -0600284 entry = image.FindEntryPath(entry_paths[0])
Simon Glass637958f2021-11-23 21:09:50 -0700285 data = entry.ReadData(decomp, alt_format)
Simon Glass80025522022-01-29 14:14:04 -0700286 tools.write_file(output_fname, data)
Simon Glass011f1b32022-01-29 14:14:15 -0700287 tout.notice("Wrote %#x bytes to file '%s'" % (len(data), output_fname))
Simon Glass980a2842019-07-08 14:25:52 -0600288 return
289
290 # Otherwise we will output to a path given by the entry path of each entry.
291 # This means that entries will appear in subdirectories if they are part of
292 # a sub-section.
293 einfos = image.GetListEntries(entry_paths)[0]
Simon Glass011f1b32022-01-29 14:14:15 -0700294 tout.notice('%d entries match and will be written' % len(einfos))
Simon Glass980a2842019-07-08 14:25:52 -0600295 for einfo in einfos:
296 entry = einfo.entry
Simon Glass637958f2021-11-23 21:09:50 -0700297 data = entry.ReadData(decomp, alt_format)
Simon Glass980a2842019-07-08 14:25:52 -0600298 path = entry.GetPath()[1:]
299 fname = os.path.join(outdir, path)
300
301 # If this entry has children, create a directory for it and put its
302 # data in a file called 'root' in that directory
303 if entry.GetEntries():
Simon Glass4ef93d92021-03-18 20:24:51 +1300304 if fname and not os.path.exists(fname):
Simon Glass980a2842019-07-08 14:25:52 -0600305 os.makedirs(fname)
306 fname = os.path.join(fname, 'root')
Simon Glass011f1b32022-01-29 14:14:15 -0700307 tout.notice("Write entry '%s' size %x to '%s'" %
Simon Glass08349452021-01-06 21:35:13 -0700308 (entry.GetPath(), len(data), fname))
Simon Glass80025522022-01-29 14:14:04 -0700309 tools.write_file(fname, data)
Simon Glass980a2842019-07-08 14:25:52 -0600310 return einfos
311
312
Simon Glass274bd0e2019-07-20 12:24:13 -0600313def BeforeReplace(image, allow_resize):
314 """Handle getting an image ready for replacing entries in it
315
316 Args:
317 image: Image to prepare
318 """
319 state.PrepareFromLoadedData(image)
Alper Nebi Yasake63ca5a2022-03-27 18:31:45 +0300320 image.CollectBintools()
Lukas Funke6767d8f2023-07-18 13:53:10 +0200321 image.LoadData(decomp=False)
Simon Glass274bd0e2019-07-20 12:24:13 -0600322
323 # If repacking, drop the old offset/size values except for the original
324 # ones, so we are only left with the constraints.
Alper Nebi Yasak00c68f12022-03-27 18:31:46 +0300325 if image.allow_repack and allow_resize:
Simon Glass274bd0e2019-07-20 12:24:13 -0600326 image.ResetForPack()
327
328
329def ReplaceOneEntry(image, entry, data, do_compress, allow_resize):
330 """Handle replacing a single entry an an image
331
332 Args:
333 image: Image to update
334 entry: Entry to write
335 data: Data to replace with
336 do_compress: True to compress the data if needed, False if data is
337 already compressed so should be used as is
338 allow_resize: True to allow entries to change size (this does a re-pack
339 of the entries), False to raise an exception
340 """
341 if not entry.WriteData(data, do_compress):
342 if not image.allow_repack:
343 entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
344 if not allow_resize:
345 entry.Raise('Entry data size does not match, but resize is disabled')
346
347
348def AfterReplace(image, allow_resize, write_map):
349 """Handle write out an image after replacing entries in it
350
351 Args:
352 image: Image to write
353 allow_resize: True to allow entries to change size (this does a re-pack
354 of the entries), False to raise an exception
355 write_map: True to write a map file
356 """
Simon Glass011f1b32022-01-29 14:14:15 -0700357 tout.info('Processing image')
Simon Glass274bd0e2019-07-20 12:24:13 -0600358 ProcessImage(image, update_fdt=True, write_map=write_map,
359 get_contents=False, allow_resize=allow_resize)
360
361
362def WriteEntryToImage(image, entry, data, do_compress=True, allow_resize=True,
363 write_map=False):
364 BeforeReplace(image, allow_resize)
Simon Glass011f1b32022-01-29 14:14:15 -0700365 tout.info('Writing data to %s' % entry.GetPath())
Simon Glass274bd0e2019-07-20 12:24:13 -0600366 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
367 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
368
369
Simon Glassd48f94e2019-07-20 12:24:12 -0600370def WriteEntry(image_fname, entry_path, data, do_compress=True,
371 allow_resize=True, write_map=False):
Simon Glass3971c952019-07-20 12:24:11 -0600372 """Replace an entry in an image
373
374 This replaces the data in a particular entry in an image. This size of the
375 new data must match the size of the old data unless allow_resize is True.
376
377 Args:
378 image_fname: Image filename to process
379 entry_path: Path to entry to extract
380 data: Data to replace with
Simon Glassd48f94e2019-07-20 12:24:12 -0600381 do_compress: True to compress the data if needed, False if data is
Simon Glass3971c952019-07-20 12:24:11 -0600382 already compressed so should be used as is
383 allow_resize: True to allow entries to change size (this does a re-pack
384 of the entries), False to raise an exception
Simon Glassd48f94e2019-07-20 12:24:12 -0600385 write_map: True to write a map file
Simon Glass3971c952019-07-20 12:24:11 -0600386
387 Returns:
388 Image object that was updated
389 """
Simon Glass011f1b32022-01-29 14:14:15 -0700390 tout.info("Write entry '%s', file '%s'" % (entry_path, image_fname))
Simon Glass3971c952019-07-20 12:24:11 -0600391 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier47250302022-08-19 16:25:22 +0200392 image.CollectBintools()
Simon Glass3971c952019-07-20 12:24:11 -0600393 entry = image.FindEntryPath(entry_path)
Simon Glass274bd0e2019-07-20 12:24:13 -0600394 WriteEntryToImage(image, entry, data, do_compress=do_compress,
395 allow_resize=allow_resize, write_map=write_map)
Simon Glass3971c952019-07-20 12:24:11 -0600396
Simon Glass3971c952019-07-20 12:24:11 -0600397 return image
398
Simon Glass30033c22019-07-20 12:24:15 -0600399
400def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
401 do_compress=True, allow_resize=True, write_map=False):
402 """Replace the data from one or more entries from input files
403
404 Args:
405 image_fname: Image filename to process
Jan Kiszka8ea44432021-11-11 08:13:30 +0100406 input_fname: Single input filename to use if replacing one file, None
Simon Glass30033c22019-07-20 12:24:15 -0600407 otherwise
408 indir: Input directory to use (for any number of files), else None
Jan Kiszka8ea44432021-11-11 08:13:30 +0100409 entry_paths: List of entry paths to replace
Simon Glass30033c22019-07-20 12:24:15 -0600410 do_compress: True if the input data is uncompressed and may need to be
411 compressed if the entry requires it, False if the data is already
412 compressed.
413 write_map: True to write a map file
414
415 Returns:
416 List of EntryInfo records that were written
417 """
Jan Kiszkaafc8f292021-11-11 08:14:18 +0100418 image_fname = os.path.abspath(image_fname)
Simon Glass30033c22019-07-20 12:24:15 -0600419 image = Image.FromFile(image_fname)
420
Simon Glass49b77e82023-03-02 17:02:44 -0700421 image.mark_build_done()
422
Simon Glass30033c22019-07-20 12:24:15 -0600423 # Replace an entry from a single file, as a special case
424 if input_fname:
425 if not entry_paths:
426 raise ValueError('Must specify an entry path to read with -f')
427 if len(entry_paths) != 1:
428 raise ValueError('Must specify exactly one entry path to write with -f')
429 entry = image.FindEntryPath(entry_paths[0])
Simon Glass80025522022-01-29 14:14:04 -0700430 data = tools.read_file(input_fname)
Simon Glass011f1b32022-01-29 14:14:15 -0700431 tout.notice("Read %#x bytes from file '%s'" % (len(data), input_fname))
Simon Glass30033c22019-07-20 12:24:15 -0600432 WriteEntryToImage(image, entry, data, do_compress=do_compress,
433 allow_resize=allow_resize, write_map=write_map)
434 return
435
436 # Otherwise we will input from a path given by the entry path of each entry.
437 # This means that files must appear in subdirectories if they are part of
438 # a sub-section.
439 einfos = image.GetListEntries(entry_paths)[0]
Simon Glass011f1b32022-01-29 14:14:15 -0700440 tout.notice("Replacing %d matching entries in image '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600441 (len(einfos), image_fname))
442
443 BeforeReplace(image, allow_resize)
444
445 for einfo in einfos:
446 entry = einfo.entry
447 if entry.GetEntries():
Simon Glass011f1b32022-01-29 14:14:15 -0700448 tout.info("Skipping section entry '%s'" % entry.GetPath())
Simon Glass30033c22019-07-20 12:24:15 -0600449 continue
450
451 path = entry.GetPath()[1:]
452 fname = os.path.join(indir, path)
453
454 if os.path.exists(fname):
Simon Glass011f1b32022-01-29 14:14:15 -0700455 tout.notice("Write entry '%s' from file '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600456 (entry.GetPath(), fname))
Simon Glass80025522022-01-29 14:14:04 -0700457 data = tools.read_file(fname)
Simon Glass30033c22019-07-20 12:24:15 -0600458 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
459 else:
Simon Glass011f1b32022-01-29 14:14:15 -0700460 tout.warning("Skipping entry '%s' from missing file '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600461 (entry.GetPath(), fname))
462
463 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
464 return image
465
Ivan Mikhaylov8a803862023-03-08 01:13:39 +0000466def SignEntries(image_fname, input_fname, privatekey_fname, algo, entry_paths,
467 write_map=False):
468 """Sign and replace the data from one or more entries from input files
469
470 Args:
471 image_fname: Image filename to process
472 input_fname: Single input filename to use if replacing one file, None
473 otherwise
474 algo: Hashing algorithm
475 entry_paths: List of entry paths to sign
476 privatekey_fname: Private key filename
477 write_map (bool): True to write the map file
478 """
479 image_fname = os.path.abspath(image_fname)
480 image = Image.FromFile(image_fname)
481
Ivan Mikhaylov3cfcaa4d2023-03-08 01:13:40 +0000482 image.mark_build_done()
483
Ivan Mikhaylov8a803862023-03-08 01:13:39 +0000484 BeforeReplace(image, allow_resize=True)
485
486 for entry_path in entry_paths:
487 entry = image.FindEntryPath(entry_path)
488 entry.UpdateSignatures(privatekey_fname, algo, input_fname)
489
490 AfterReplace(image, allow_resize=True, write_map=write_map)
Simon Glass30033c22019-07-20 12:24:15 -0600491
Simon Glassfc792842023-07-18 07:24:04 -0600492def _ProcessTemplates(parent):
493 """Handle any templates in the binman description
494
495 Args:
496 parent: Binman node to process (typically /binman)
497
Simon Glass09490b02023-07-22 21:43:52 -0600498 Returns:
499 bool: True if any templates were processed
500
Simon Glassfc792842023-07-18 07:24:04 -0600501 Search though each target node looking for those with an 'insert-template'
502 property. Use that as a list of references to template nodes to use to
503 adjust the target node.
504
505 Processing involves copying each subnode of the template node into the
506 target node.
507
Simon Glassaa6e0552023-07-18 07:24:07 -0600508 This is done recursively, so templates can be at any level of the binman
509 image, e.g. inside a section.
Simon Glassfc792842023-07-18 07:24:04 -0600510
511 See 'Templates' in the Binman documnentation for details.
512 """
Simon Glass09490b02023-07-22 21:43:52 -0600513 found = False
Simon Glassfc792842023-07-18 07:24:04 -0600514 for node in parent.subnodes:
515 tmpl = fdt_util.GetPhandleList(node, 'insert-template')
516 if tmpl:
517 node.copy_subnodes_from_phandles(tmpl)
Simon Glass09490b02023-07-22 21:43:52 -0600518 found = True
519
520 found |= _ProcessTemplates(node)
521 return found
Simon Glassfc792842023-07-18 07:24:04 -0600522
Simon Glass54825e12023-07-22 21:43:56 -0600523def _RemoveTemplates(parent):
524 """Remove any templates in the binman description
525 """
526 for node in parent.subnodes:
527 if node.name.startswith('template'):
528 node.Delete()
529
Simon Glass55ab0b62021-03-18 20:25:06 +1300530def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt, use_expanded):
Simon Glassd3151ff2019-07-20 12:23:27 -0600531 """Prepare the images to be processed and select the device tree
532
533 This function:
534 - reads in the device tree
535 - finds and scans the binman node to create all entries
536 - selects which images to build
537 - Updates the device tress with placeholder properties for offset,
538 image-pos, etc.
539
540 Args:
541 dtb_fname: Filename of the device tree file to use (.dts or .dtb)
542 selected_images: List of images to output, or None for all
543 update_fdt: True to update the FDT wth entry offsets, etc.
Simon Glass55ab0b62021-03-18 20:25:06 +1300544 use_expanded: True to use expanded versions of entries, if available.
545 So if 'u-boot' is called for, we use 'u-boot-expanded' instead. This
546 is needed if update_fdt is True (although tests may disable it)
Simon Glass31ee50f2020-09-01 05:13:55 -0600547
548 Returns:
549 OrderedDict of images:
550 key: Image name (str)
551 value: Image object
Simon Glassd3151ff2019-07-20 12:23:27 -0600552 """
553 # Import these here in case libfdt.py is not available, in which case
554 # the above help option still works.
Simon Glassc585dd42020-04-17 18:09:03 -0600555 from dtoc import fdt
556 from dtoc import fdt_util
Simon Glassd3151ff2019-07-20 12:23:27 -0600557 global images
558
559 # Get the device tree ready by compiling it and copying the compiled
560 # output into a file in our output directly. Then scan it for use
561 # in binman.
562 dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
Simon Glass80025522022-01-29 14:14:04 -0700563 fname = tools.get_output_filename('u-boot.dtb.out')
564 tools.write_file(fname, tools.read_file(dtb_fname))
Simon Glassd3151ff2019-07-20 12:23:27 -0600565 dtb = fdt.FdtScan(fname)
566
567 node = _FindBinmanNode(dtb)
568 if not node:
569 raise ValueError("Device tree '%s' does not have a 'binman' "
570 "node" % dtb_fname)
571
Simon Glass09490b02023-07-22 21:43:52 -0600572 if _ProcessTemplates(node):
573 dtb.Sync(True)
574 fname = tools.get_output_filename('u-boot.dtb.tmpl1')
575 tools.write_file(fname, dtb.GetContents())
Simon Glassfc792842023-07-18 07:24:04 -0600576
Simon Glass54825e12023-07-22 21:43:56 -0600577 _RemoveTemplates(node)
578 dtb.Sync(True)
Simon Glass86b3e472023-07-22 21:43:57 -0600579
580 # Rescan the dtb to pick up the new phandles
581 dtb.Scan()
582 node = _FindBinmanNode(dtb)
Simon Glass54825e12023-07-22 21:43:56 -0600583 fname = tools.get_output_filename('u-boot.dtb.tmpl2')
584 tools.write_file(fname, dtb.GetContents())
585
Simon Glass55ab0b62021-03-18 20:25:06 +1300586 images = _ReadImageDesc(node, use_expanded)
Simon Glassd3151ff2019-07-20 12:23:27 -0600587
588 if select_images:
589 skip = []
590 new_images = OrderedDict()
591 for name, image in images.items():
592 if name in select_images:
593 new_images[name] = image
594 else:
595 skip.append(name)
596 images = new_images
Simon Glass011f1b32022-01-29 14:14:15 -0700597 tout.notice('Skipping images: %s' % ', '.join(skip))
Simon Glassd3151ff2019-07-20 12:23:27 -0600598
599 state.Prepare(images, dtb)
600
601 # Prepare the device tree by making sure that any missing
602 # properties are added (e.g. 'pos' and 'size'). The values of these
603 # may not be correct yet, but we add placeholders so that the
604 # size of the device tree is correct. Later, in
605 # SetCalculatedProperties() we will insert the correct values
606 # without changing the device-tree size, thus ensuring that our
607 # entry offsets remain the same.
608 for image in images.values():
Simon Glassf86ddad2022-03-05 20:19:00 -0700609 image.gen_entries()
Stefan Herbrechtsmeier47250302022-08-19 16:25:22 +0200610 image.CollectBintools()
Simon Glassd3151ff2019-07-20 12:23:27 -0600611 if update_fdt:
Simon Glassacd6c6e2020-10-26 17:40:17 -0600612 image.AddMissingProperties(True)
Simon Glassd3151ff2019-07-20 12:23:27 -0600613 image.ProcessFdt(dtb)
614
Simon Glass5a300602019-07-20 12:23:29 -0600615 for dtb_item in state.GetAllFdts():
Simon Glassd3151ff2019-07-20 12:23:27 -0600616 dtb_item.Sync(auto_resize=True)
617 dtb_item.Pack()
618 dtb_item.Flush()
619 return images
620
621
Simon Glassf8a54bc2019-07-20 12:23:56 -0600622def ProcessImage(image, update_fdt, write_map, get_contents=True,
Heiko Thiery6d451362022-01-06 11:49:41 +0100623 allow_resize=True, allow_missing=False,
624 allow_fake_blobs=False):
Simon Glassb766c5e52019-07-20 12:23:24 -0600625 """Perform all steps for this image, including checking and # writing it.
626
627 This means that errors found with a later image will be reported after
628 earlier images are already completed and written, but that does not seem
629 important.
630
631 Args:
632 image: Image to process
633 update_fdt: True to update the FDT wth entry offsets, etc.
634 write_map: True to write a map file
Simon Glass072959a2019-07-20 12:23:50 -0600635 get_contents: True to get the image contents from files, etc., False if
636 the contents is already present
Simon Glassf8a54bc2019-07-20 12:23:56 -0600637 allow_resize: True to allow entries to change size (this does a re-pack
638 of the entries), False to raise an exception
Simon Glass5d94cc62020-07-09 18:39:38 -0600639 allow_missing: Allow blob_ext objects to be missing
Heiko Thiery6d451362022-01-06 11:49:41 +0100640 allow_fake_blobs: Allow blob_ext objects to be faked with dummy files
Simon Glassa003cd32020-07-09 18:39:40 -0600641
642 Returns:
Heiko Thiery6d451362022-01-06 11:49:41 +0100643 True if one or more external blobs are missing or faked,
644 False if all are present
Simon Glassb766c5e52019-07-20 12:23:24 -0600645 """
Simon Glass072959a2019-07-20 12:23:50 -0600646 if get_contents:
Simon Glass5d94cc62020-07-09 18:39:38 -0600647 image.SetAllowMissing(allow_missing)
Heiko Thiery6d451362022-01-06 11:49:41 +0100648 image.SetAllowFakeBlob(allow_fake_blobs)
Simon Glass072959a2019-07-20 12:23:50 -0600649 image.GetEntryContents()
Simon Glass1e9e61c2023-01-07 14:07:12 -0700650 image.drop_absent()
Simon Glassb766c5e52019-07-20 12:23:24 -0600651 image.GetEntryOffsets()
652
653 # We need to pack the entries to figure out where everything
654 # should be placed. This sets the offset/size of each entry.
655 # However, after packing we call ProcessEntryContents() which
656 # may result in an entry changing size. In that case we need to
657 # do another pass. Since the device tree often contains the
658 # final offset/size information we try to make space for this in
659 # AddMissingProperties() above. However, if the device is
660 # compressed we cannot know this compressed size in advance,
661 # since changing an offset from 0x100 to 0x104 (for example) can
662 # alter the compressed size of the device tree. So we need a
663 # third pass for this.
Simon Glass37fdd142019-07-20 12:24:06 -0600664 passes = 5
Simon Glassb766c5e52019-07-20 12:23:24 -0600665 for pack_pass in range(passes):
666 try:
667 image.PackEntries()
Simon Glassb766c5e52019-07-20 12:23:24 -0600668 except Exception as e:
669 if write_map:
670 fname = image.WriteMap()
671 print("Wrote map file '%s' to show errors" % fname)
672 raise
673 image.SetImagePos()
674 if update_fdt:
675 image.SetCalculatedProperties()
Simon Glass5a300602019-07-20 12:23:29 -0600676 for dtb_item in state.GetAllFdts():
Simon Glassb766c5e52019-07-20 12:23:24 -0600677 dtb_item.Sync()
Simon Glassf8a54bc2019-07-20 12:23:56 -0600678 dtb_item.Flush()
Simon Glasse5943412019-08-24 07:23:12 -0600679 image.WriteSymbols()
Simon Glassb766c5e52019-07-20 12:23:24 -0600680 sizes_ok = image.ProcessEntryContents()
681 if sizes_ok:
682 break
683 image.ResetForPack()
Simon Glass011f1b32022-01-29 14:14:15 -0700684 tout.info('Pack completed after %d pass(es)' % (pack_pass + 1))
Simon Glassb766c5e52019-07-20 12:23:24 -0600685 if not sizes_ok:
Simon Glass9d8ee322019-07-20 12:23:58 -0600686 image.Raise('Entries changed size after packing (tried %s passes)' %
Simon Glassb766c5e52019-07-20 12:23:24 -0600687 passes)
688
Simon Glassb766c5e52019-07-20 12:23:24 -0600689 image.BuildImage()
690 if write_map:
691 image.WriteMap()
Simon Glass63328f12023-01-07 14:07:15 -0700692
Simon Glassa003cd32020-07-09 18:39:40 -0600693 missing_list = []
694 image.CheckMissing(missing_list)
695 if missing_list:
Jonas Karlmana0335b42023-07-18 20:34:37 +0000696 tout.error("Image '%s' is missing external blobs and is non-functional: %s\n" %
Jonas Karlman34f520c2023-07-18 20:34:35 +0000697 (image.name, ' '.join([e.name for e in missing_list])))
698 _ShowHelpForMissingBlobs(tout.ERROR, missing_list)
Simon Glass63328f12023-01-07 14:07:15 -0700699
Heiko Thiery6d451362022-01-06 11:49:41 +0100700 faked_list = []
701 image.CheckFakedBlobs(faked_list)
702 if faked_list:
Simon Glass011f1b32022-01-29 14:14:15 -0700703 tout.warning(
Jonas Karlmana0335b42023-07-18 20:34:37 +0000704 "Image '%s' has faked external blobs and is non-functional: %s\n" %
Simon Glassf9f34032022-01-09 20:13:45 -0700705 (image.name, ' '.join([os.path.basename(e.GetDefaultFilename())
706 for e in faked_list])))
Simon Glass63328f12023-01-07 14:07:15 -0700707
708 optional_list = []
709 image.CheckOptional(optional_list)
710 if optional_list:
711 tout.warning(
Jonas Karlmana0335b42023-07-18 20:34:37 +0000712 "Image '%s' is missing optional external blobs but is still functional: %s\n" %
Simon Glass63328f12023-01-07 14:07:15 -0700713 (image.name, ' '.join([e.name for e in optional_list])))
Jonas Karlman34f520c2023-07-18 20:34:35 +0000714 _ShowHelpForMissingBlobs(tout.WARNING, optional_list)
Simon Glass63328f12023-01-07 14:07:15 -0700715
Simon Glass66152ce2022-01-09 20:14:09 -0700716 missing_bintool_list = []
717 image.check_missing_bintools(missing_bintool_list)
718 if missing_bintool_list:
Simon Glass011f1b32022-01-29 14:14:15 -0700719 tout.warning(
Jonas Karlmana0335b42023-07-18 20:34:37 +0000720 "Image '%s' has missing bintools and is non-functional: %s\n" %
Simon Glass66152ce2022-01-09 20:14:09 -0700721 (image.name, ' '.join([os.path.basename(bintool.name)
722 for bintool in missing_bintool_list])))
723 return any([missing_list, faked_list, missing_bintool_list])
Simon Glassb766c5e52019-07-20 12:23:24 -0600724
725
Simon Glassf46732a2019-07-08 14:25:29 -0600726def Binman(args):
Simon Glass2574ef62016-11-25 20:15:51 -0700727 """The main control code for binman
728
729 This assumes that help and test options have already been dealt with. It
730 deals with the core task of building images.
731
732 Args:
Simon Glassf46732a2019-07-08 14:25:29 -0600733 args: Command line arguments Namespace object
Simon Glass2574ef62016-11-25 20:15:51 -0700734 """
Simon Glassb9ba4e02019-08-24 07:22:44 -0600735 global Image
736 global state
737
Simon Glassf46732a2019-07-08 14:25:29 -0600738 if args.full_help:
Simon Glassfeb80cc2023-02-23 18:18:20 -0700739 with importlib.resources.path('binman', 'README.rst') as readme:
740 tools.print_full_help(str(readme))
Simon Glass2574ef62016-11-25 20:15:51 -0700741 return 0
742
Simon Glassb9ba4e02019-08-24 07:22:44 -0600743 # Put these here so that we can import this module without libfdt
Simon Glass90cd6f02020-08-05 13:27:47 -0600744 from binman.image import Image
Simon Glassc585dd42020-04-17 18:09:03 -0600745 from binman import state
Simon Glassb9ba4e02019-08-24 07:22:44 -0600746
Simon Glass9a1c7262023-02-22 12:14:49 -0700747 tool_paths = []
748 if args.toolpath:
749 tool_paths += args.toolpath
750 if args.tooldir:
751 tool_paths.append(args.tooldir)
752 tools.set_tool_paths(tool_paths or None)
753 bintool.Bintool.set_tool_dir(args.tooldir)
754
Ivan Mikhaylov8a803862023-03-08 01:13:39 +0000755 if args.cmd in ['ls', 'extract', 'replace', 'tool', 'sign']:
Simon Glass9b7f5002019-07-20 12:23:53 -0600756 try:
Simon Glass011f1b32022-01-29 14:14:15 -0700757 tout.init(args.verbosity)
Simon Glassb9b9b272023-03-02 17:02:42 -0700758 if args.cmd == 'replace':
759 tools.prepare_output_dir(args.outdir, args.preserve)
760 else:
761 tools.prepare_output_dir(None)
Simon Glassdf08cbb2019-09-15 18:10:36 -0600762 if args.cmd == 'ls':
763 ListEntries(args.image, args.paths)
Simon Glassb2fd11d2019-07-08 14:25:48 -0600764
Simon Glassdf08cbb2019-09-15 18:10:36 -0600765 if args.cmd == 'extract':
766 ExtractEntries(args.image, args.filename, args.outdir, args.paths,
Simon Glass637958f2021-11-23 21:09:50 -0700767 not args.uncompressed, args.format)
Simon Glass980a2842019-07-08 14:25:52 -0600768
Simon Glassdf08cbb2019-09-15 18:10:36 -0600769 if args.cmd == 'replace':
770 ReplaceEntries(args.image, args.filename, args.indir, args.paths,
771 do_compress=not args.compressed,
772 allow_resize=not args.fix_size, write_map=args.map)
Simon Glass4eae9252022-01-09 20:13:50 -0700773
Ivan Mikhaylov8a803862023-03-08 01:13:39 +0000774 if args.cmd == 'sign':
775 SignEntries(args.image, args.file, args.key, args.algo, args.paths)
776
Simon Glass4eae9252022-01-09 20:13:50 -0700777 if args.cmd == 'tool':
Simon Glass4eae9252022-01-09 20:13:50 -0700778 if args.list:
779 bintool.Bintool.list_all()
780 elif args.fetch:
781 if not args.bintools:
782 raise ValueError(
783 "Please specify bintools to fetch or 'all' or 'missing'")
784 bintool.Bintool.fetch_tools(bintool.FETCH_ANY,
785 args.bintools)
786 else:
787 raise ValueError("Invalid arguments to 'tool' subcommand")
Simon Glassdf08cbb2019-09-15 18:10:36 -0600788 except:
789 raise
Simon Glass30033c22019-07-20 12:24:15 -0600790 finally:
Simon Glass80025522022-01-29 14:14:04 -0700791 tools.finalise_output_dir()
Simon Glass30033c22019-07-20 12:24:15 -0600792 return 0
793
Simon Glassadfb8492021-11-03 21:09:18 -0600794 elf_params = None
795 if args.update_fdt_in_elf:
796 elf_params = args.update_fdt_in_elf.split(',')
797 if len(elf_params) != 4:
798 raise ValueError('Invalid args %s to --update-fdt-in-elf: expected infile,outfile,begin_sym,end_sym' %
799 elf_params)
800
Simon Glass2574ef62016-11-25 20:15:51 -0700801 # Try to figure out which device tree contains our image description
Simon Glassf46732a2019-07-08 14:25:29 -0600802 if args.dt:
803 dtb_fname = args.dt
Simon Glass2574ef62016-11-25 20:15:51 -0700804 else:
Simon Glassf46732a2019-07-08 14:25:29 -0600805 board = args.board
Simon Glass2574ef62016-11-25 20:15:51 -0700806 if not board:
807 raise ValueError('Must provide a board to process (use -b <board>)')
Simon Glassf46732a2019-07-08 14:25:29 -0600808 board_pathname = os.path.join(args.build_dir, board)
Simon Glass2574ef62016-11-25 20:15:51 -0700809 dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
Simon Glassf46732a2019-07-08 14:25:29 -0600810 if not args.indir:
811 args.indir = ['.']
812 args.indir.append(board_pathname)
Simon Glass2574ef62016-11-25 20:15:51 -0700813
814 try:
Simon Glass011f1b32022-01-29 14:14:15 -0700815 tout.init(args.verbosity)
Simon Glassf46732a2019-07-08 14:25:29 -0600816 elf.debug = args.debug
817 cbfs_util.VERBOSE = args.verbosity > 2
818 state.use_fake_dtb = args.fake_dtb
Simon Glass55ab0b62021-03-18 20:25:06 +1300819
Simon Glassfc5569f2023-08-02 09:23:13 -0600820 # Temporary hack
821 if args.ignore_dup_phandles: # pragma: no cover
822 fdt.IGNORE_DUP_PHANDLES = True
823
Simon Glass55ab0b62021-03-18 20:25:06 +1300824 # Normally we replace the 'u-boot' etype with 'u-boot-expanded', etc.
825 # When running tests this can be disabled using this flag. When not
826 # updating the FDT in image, it is not needed by binman, but we use it
827 # for consistency, so that the images look the same to U-Boot at
828 # runtime.
829 use_expanded = not args.no_expanded
Simon Glass2574ef62016-11-25 20:15:51 -0700830 try:
Simon Glass80025522022-01-29 14:14:04 -0700831 tools.set_input_dirs(args.indir)
832 tools.prepare_output_dir(args.outdir, args.preserve)
Simon Glassf46732a2019-07-08 14:25:29 -0600833 state.SetEntryArgs(args.entry_arg)
Simon Glass76f496d2021-07-06 10:36:37 -0600834 state.SetThreads(args.threads)
Simon Glass92307732018-07-06 10:27:40 -0600835
Simon Glassd3151ff2019-07-20 12:23:27 -0600836 images = PrepareImagesAndDtbs(dtb_fname, args.image,
Simon Glass55ab0b62021-03-18 20:25:06 +1300837 args.update_fdt, use_expanded)
Heiko Thiery6d451362022-01-06 11:49:41 +0100838
Simon Glass76f496d2021-07-06 10:36:37 -0600839 if args.test_section_timeout:
840 # Set the first image to timeout, used in testThreadTimeout()
841 images[list(images.keys())[0]].test_section_timeout = True
Heiko Thiery6d451362022-01-06 11:49:41 +0100842 invalid = False
Simon Glass66152ce2022-01-09 20:14:09 -0700843 bintool.Bintool.set_missing_list(
844 args.force_missing_bintools.split(',') if
845 args.force_missing_bintools else None)
Simon Glass7d3e4072022-08-07 09:46:46 -0600846
847 # Create the directory here instead of Entry.check_fake_fname()
848 # since that is called from a threaded context so different threads
849 # may race to create the directory
850 if args.fake_ext_blobs:
851 entry.Entry.create_fake_dir()
852
Simon Glass2574ef62016-11-25 20:15:51 -0700853 for image in images.values():
Heiko Thiery6d451362022-01-06 11:49:41 +0100854 invalid |= ProcessImage(image, args.update_fdt, args.map,
855 allow_missing=args.allow_missing,
856 allow_fake_blobs=args.fake_ext_blobs)
Simon Glassbdb40312018-09-14 04:57:20 -0600857
858 # Write the updated FDTs to our output files
Simon Glass5a300602019-07-20 12:23:29 -0600859 for dtb_item in state.GetAllFdts():
Simon Glass80025522022-01-29 14:14:04 -0700860 tools.write_file(dtb_item._fname, dtb_item.GetContents())
Simon Glassbdb40312018-09-14 04:57:20 -0600861
Simon Glassadfb8492021-11-03 21:09:18 -0600862 if elf_params:
863 data = state.GetFdtForEtype('u-boot-dtb').GetContents()
864 elf.UpdateFile(*elf_params, data)
865
Simon Glass6bce5dc2022-11-09 19:14:42 -0700866 # This can only be True if -M is provided, since otherwise binman
867 # would have raised an error already
Heiko Thiery6d451362022-01-06 11:49:41 +0100868 if invalid:
Jonas Karlmana0335b42023-07-18 20:34:37 +0000869 msg = 'Some images are invalid'
Simon Glass6bce5dc2022-11-09 19:14:42 -0700870 if args.ignore_missing:
871 tout.warning(msg)
872 else:
873 tout.error(msg)
874 return 103
Simon Glass748a1d42021-07-06 10:36:41 -0600875
876 # Use this to debug the time take to pack the image
877 #state.TimingShow()
Simon Glass2574ef62016-11-25 20:15:51 -0700878 finally:
Simon Glass80025522022-01-29 14:14:04 -0700879 tools.finalise_output_dir()
Simon Glass2574ef62016-11-25 20:15:51 -0700880 finally:
Simon Glass011f1b32022-01-29 14:14:15 -0700881 tout.uninit()
Simon Glass2574ef62016-11-25 20:15:51 -0700882
883 return 0