blob: bd40f074c87f9f551badba6c20a1a986181083ef [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
Simon Glassfeb80cc2023-02-23 18:18:20 -070010import importlib.resources
Simon Glass2574ef62016-11-25 20:15:51 -070011import os
Simon Glassc1dc2f82020-08-29 11:36:14 -060012import pkg_resources
Simon Glassa820af72020-09-06 10:39:09 -060013import re
Simon Glassc1dc2f82020-08-29 11:36:14 -060014
Simon Glass2574ef62016-11-25 20:15:51 -070015import sys
Simon Glass2574ef62016-11-25 20:15:51 -070016
Simon Glass4eae9252022-01-09 20:13:50 -070017from binman import bintool
Simon Glassc585dd42020-04-17 18:09:03 -060018from binman import cbfs_util
Simon Glass7d3e4072022-08-07 09:46:46 -060019from binman import elf
20from binman import entry
Simon Glass131444f2023-02-23 18:18:04 -070021from u_boot_pylib import command
22from u_boot_pylib import tools
23from u_boot_pylib import tout
Simon Glass2574ef62016-11-25 20:15:51 -070024
Simon Glass2a0fa982022-02-11 13:23:21 -070025# These are imported if needed since they import libfdt
26state = None
27Image = None
28
Simon Glass2574ef62016-11-25 20:15:51 -070029# List of images we plan to create
30# Make this global so that it can be referenced from tests
31images = OrderedDict()
32
Simon Glassa820af72020-09-06 10:39:09 -060033# Help text for each type of missing blob, dict:
34# key: Value of the entry's 'missing-msg' or entry name
35# value: Text for the help
36missing_blob_help = {}
37
Simon Glass55ab0b62021-03-18 20:25:06 +130038def _ReadImageDesc(binman_node, use_expanded):
Simon Glass2574ef62016-11-25 20:15:51 -070039 """Read the image descriptions from the /binman node
40
41 This normally produces a single Image object called 'image'. But if
42 multiple images are present, they will all be returned.
43
44 Args:
45 binman_node: Node object of the /binman node
Simon Glass55ab0b62021-03-18 20:25:06 +130046 use_expanded: True if the FDT will be updated with the entry information
Simon Glass2574ef62016-11-25 20:15:51 -070047 Returns:
48 OrderedDict of Image objects, each of which describes an image
49 """
Simon Glass2a0fa982022-02-11 13:23:21 -070050 # For Image()
51 # pylint: disable=E1102
Simon Glass2574ef62016-11-25 20:15:51 -070052 images = OrderedDict()
53 if 'multiple-images' in binman_node.props:
54 for node in binman_node.subnodes:
Simon Glass55ab0b62021-03-18 20:25:06 +130055 images[node.name] = Image(node.name, node,
56 use_expanded=use_expanded)
Simon Glass2574ef62016-11-25 20:15:51 -070057 else:
Simon Glass55ab0b62021-03-18 20:25:06 +130058 images['image'] = Image('image', binman_node, use_expanded=use_expanded)
Simon Glass2574ef62016-11-25 20:15:51 -070059 return images
60
Simon Glass22c92ca2017-05-27 07:38:29 -060061def _FindBinmanNode(dtb):
Simon Glass2574ef62016-11-25 20:15:51 -070062 """Find the 'binman' node in the device tree
63
64 Args:
Simon Glass22c92ca2017-05-27 07:38:29 -060065 dtb: Fdt object to scan
Simon Glass2574ef62016-11-25 20:15:51 -070066 Returns:
67 Node object of /binman node, or None if not found
68 """
Simon Glass22c92ca2017-05-27 07:38:29 -060069 for node in dtb.GetRoot().subnodes:
Simon Glass2574ef62016-11-25 20:15:51 -070070 if node.name == 'binman':
71 return node
72 return None
73
Simon Glassa820af72020-09-06 10:39:09 -060074def _ReadMissingBlobHelp():
75 """Read the missing-blob-help file
76
77 This file containins help messages explaining what to do when external blobs
78 are missing.
79
80 Returns:
81 Dict:
82 key: Message tag (str)
83 value: Message text (str)
84 """
85
86 def _FinishTag(tag, msg, result):
87 if tag:
88 result[tag] = msg.rstrip()
89 tag = None
90 msg = ''
91 return tag, msg
92
93 my_data = pkg_resources.resource_string(__name__, 'missing-blob-help')
94 re_tag = re.compile('^([-a-z0-9]+):$')
95 result = {}
96 tag = None
97 msg = ''
98 for line in my_data.decode('utf-8').splitlines():
99 if not line.startswith('#'):
100 m_tag = re_tag.match(line)
101 if m_tag:
102 _, msg = _FinishTag(tag, msg, result)
103 tag = m_tag.group(1)
104 elif tag:
105 msg += line + '\n'
106 _FinishTag(tag, msg, result)
107 return result
108
109def _ShowBlobHelp(path, text):
Simon Glass011f1b32022-01-29 14:14:15 -0700110 tout.warning('\n%s:' % path)
Simon Glassa820af72020-09-06 10:39:09 -0600111 for line in text.splitlines():
Simon Glass011f1b32022-01-29 14:14:15 -0700112 tout.warning(' %s' % line)
Simon Glassa820af72020-09-06 10:39:09 -0600113
114def _ShowHelpForMissingBlobs(missing_list):
115 """Show help for each missing blob to help the user take action
116
117 Args:
118 missing_list: List of Entry objects to show help for
119 """
120 global missing_blob_help
121
122 if not missing_blob_help:
123 missing_blob_help = _ReadMissingBlobHelp()
124
125 for entry in missing_list:
126 tags = entry.GetHelpTags()
127
128 # Show the first match help message
129 for tag in tags:
130 if tag in missing_blob_help:
131 _ShowBlobHelp(entry._node.path, missing_blob_help[tag])
132 break
133
Simon Glass220ff5f2020-08-05 13:27:46 -0600134def GetEntryModules(include_testing=True):
135 """Get a set of entry class implementations
136
137 Returns:
138 Set of paths to entry class filenames
139 """
Simon Glassc1dc2f82020-08-29 11:36:14 -0600140 glob_list = pkg_resources.resource_listdir(__name__, 'etype')
141 glob_list = [fname for fname in glob_list if fname.endswith('.py')]
Simon Glass220ff5f2020-08-05 13:27:46 -0600142 return set([os.path.splitext(os.path.basename(item))[0]
143 for item in glob_list
144 if include_testing or '_testing' not in item])
145
Simon Glass29aa7362018-09-14 04:57:19 -0600146def WriteEntryDocs(modules, test_missing=None):
147 """Write out documentation for all entries
Simon Glass92307732018-07-06 10:27:40 -0600148
149 Args:
Simon Glass29aa7362018-09-14 04:57:19 -0600150 modules: List of Module objects to get docs for
Simon Glass620c4462022-01-09 20:14:11 -0700151 test_missing: Used for testing only, to force an entry's documentation
Simon Glass29aa7362018-09-14 04:57:19 -0600152 to show as missing even if it is present. Should be set to None in
153 normal use.
Simon Glass92307732018-07-06 10:27:40 -0600154 """
Simon Glassc585dd42020-04-17 18:09:03 -0600155 from binman.entry import Entry
Simon Glass969616c2018-07-17 13:25:36 -0600156 Entry.WriteDocs(modules, test_missing)
157
Simon Glassb2fd11d2019-07-08 14:25:48 -0600158
Simon Glass620c4462022-01-09 20:14:11 -0700159def write_bintool_docs(modules, test_missing=None):
160 """Write out documentation for all bintools
161
162 Args:
163 modules: List of Module objects to get docs for
164 test_missing: Used for testing only, to force an entry's documentation
165 to show as missing even if it is present. Should be set to None in
166 normal use.
167 """
168 bintool.Bintool.WriteDocs(modules, test_missing)
169
170
Simon Glassb2fd11d2019-07-08 14:25:48 -0600171def ListEntries(image_fname, entry_paths):
172 """List the entries in an image
173
174 This decodes the supplied image and displays a table of entries from that
175 image, preceded by a header.
176
177 Args:
178 image_fname: Image filename to process
179 entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*',
180 'section/u-boot'])
181 """
182 image = Image.FromFile(image_fname)
183
184 entries, lines, widths = image.GetListEntries(entry_paths)
185
186 num_columns = len(widths)
187 for linenum, line in enumerate(lines):
188 if linenum == 1:
189 # Print header line
190 print('-' * (sum(widths) + num_columns * 2))
191 out = ''
192 for i, item in enumerate(line):
193 width = -widths[i]
194 if item.startswith('>'):
195 width = -width
196 item = item[1:]
197 txt = '%*s ' % (width, item)
198 out += txt
199 print(out.rstrip())
200
Simon Glass4c613bf2019-07-08 14:25:50 -0600201
202def ReadEntry(image_fname, entry_path, decomp=True):
203 """Extract an entry from an image
204
205 This extracts the data from a particular entry in an image
206
207 Args:
208 image_fname: Image filename to process
209 entry_path: Path to entry to extract
210 decomp: True to return uncompressed data, if the data is compress
211 False to return the raw data
212
213 Returns:
214 data extracted from the entry
215 """
Simon Glassb9ba4e02019-08-24 07:22:44 -0600216 global Image
Simon Glass90cd6f02020-08-05 13:27:47 -0600217 from binman.image import Image
Simon Glassb9ba4e02019-08-24 07:22:44 -0600218
Simon Glass4c613bf2019-07-08 14:25:50 -0600219 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier47250302022-08-19 16:25:22 +0200220 image.CollectBintools()
Simon Glass4c613bf2019-07-08 14:25:50 -0600221 entry = image.FindEntryPath(entry_path)
222 return entry.ReadData(decomp)
223
224
Simon Glass637958f2021-11-23 21:09:50 -0700225def ShowAltFormats(image):
226 """Show alternative formats available for entries in the image
227
228 This shows a list of formats available.
229
230 Args:
231 image (Image): Image to check
232 """
233 alt_formats = {}
234 image.CheckAltFormats(alt_formats)
235 print('%-10s %-20s %s' % ('Flag (-F)', 'Entry type', 'Description'))
236 for name, val in alt_formats.items():
237 entry, helptext = val
238 print('%-10s %-20s %s' % (name, entry.etype, helptext))
239
240
Simon Glass980a2842019-07-08 14:25:52 -0600241def ExtractEntries(image_fname, output_fname, outdir, entry_paths,
Simon Glass637958f2021-11-23 21:09:50 -0700242 decomp=True, alt_format=None):
Simon Glass980a2842019-07-08 14:25:52 -0600243 """Extract the data from one or more entries and write it to files
244
245 Args:
246 image_fname: Image filename to process
247 output_fname: Single output filename to use if extracting one file, None
248 otherwise
249 outdir: Output directory to use (for any number of files), else None
250 entry_paths: List of entry paths to extract
Simon Glassd48f94e2019-07-20 12:24:12 -0600251 decomp: True to decompress the entry data
Simon Glass980a2842019-07-08 14:25:52 -0600252
253 Returns:
254 List of EntryInfo records that were written
255 """
256 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier47250302022-08-19 16:25:22 +0200257 image.CollectBintools()
Simon Glass980a2842019-07-08 14:25:52 -0600258
Simon Glass637958f2021-11-23 21:09:50 -0700259 if alt_format == 'list':
260 ShowAltFormats(image)
261 return
262
Simon Glass980a2842019-07-08 14:25:52 -0600263 # Output an entry to a single file, as a special case
264 if output_fname:
265 if not entry_paths:
Simon Glassa772d3f2019-07-20 12:24:14 -0600266 raise ValueError('Must specify an entry path to write with -f')
Simon Glass980a2842019-07-08 14:25:52 -0600267 if len(entry_paths) != 1:
Simon Glassa772d3f2019-07-20 12:24:14 -0600268 raise ValueError('Must specify exactly one entry path to write with -f')
Simon Glass980a2842019-07-08 14:25:52 -0600269 entry = image.FindEntryPath(entry_paths[0])
Simon Glass637958f2021-11-23 21:09:50 -0700270 data = entry.ReadData(decomp, alt_format)
Simon Glass80025522022-01-29 14:14:04 -0700271 tools.write_file(output_fname, data)
Simon Glass011f1b32022-01-29 14:14:15 -0700272 tout.notice("Wrote %#x bytes to file '%s'" % (len(data), output_fname))
Simon Glass980a2842019-07-08 14:25:52 -0600273 return
274
275 # Otherwise we will output to a path given by the entry path of each entry.
276 # This means that entries will appear in subdirectories if they are part of
277 # a sub-section.
278 einfos = image.GetListEntries(entry_paths)[0]
Simon Glass011f1b32022-01-29 14:14:15 -0700279 tout.notice('%d entries match and will be written' % len(einfos))
Simon Glass980a2842019-07-08 14:25:52 -0600280 for einfo in einfos:
281 entry = einfo.entry
Simon Glass637958f2021-11-23 21:09:50 -0700282 data = entry.ReadData(decomp, alt_format)
Simon Glass980a2842019-07-08 14:25:52 -0600283 path = entry.GetPath()[1:]
284 fname = os.path.join(outdir, path)
285
286 # If this entry has children, create a directory for it and put its
287 # data in a file called 'root' in that directory
288 if entry.GetEntries():
Simon Glass4ef93d92021-03-18 20:24:51 +1300289 if fname and not os.path.exists(fname):
Simon Glass980a2842019-07-08 14:25:52 -0600290 os.makedirs(fname)
291 fname = os.path.join(fname, 'root')
Simon Glass011f1b32022-01-29 14:14:15 -0700292 tout.notice("Write entry '%s' size %x to '%s'" %
Simon Glass08349452021-01-06 21:35:13 -0700293 (entry.GetPath(), len(data), fname))
Simon Glass80025522022-01-29 14:14:04 -0700294 tools.write_file(fname, data)
Simon Glass980a2842019-07-08 14:25:52 -0600295 return einfos
296
297
Simon Glass274bd0e2019-07-20 12:24:13 -0600298def BeforeReplace(image, allow_resize):
299 """Handle getting an image ready for replacing entries in it
300
301 Args:
302 image: Image to prepare
303 """
304 state.PrepareFromLoadedData(image)
305 image.LoadData()
Alper Nebi Yasake63ca5a2022-03-27 18:31:45 +0300306 image.CollectBintools()
Simon Glass274bd0e2019-07-20 12:24:13 -0600307
308 # If repacking, drop the old offset/size values except for the original
309 # ones, so we are only left with the constraints.
Alper Nebi Yasak00c68f12022-03-27 18:31:46 +0300310 if image.allow_repack and allow_resize:
Simon Glass274bd0e2019-07-20 12:24:13 -0600311 image.ResetForPack()
312
313
314def ReplaceOneEntry(image, entry, data, do_compress, allow_resize):
315 """Handle replacing a single entry an an image
316
317 Args:
318 image: Image to update
319 entry: Entry to write
320 data: Data to replace with
321 do_compress: True to compress the data if needed, False if data is
322 already compressed so should be used as is
323 allow_resize: True to allow entries to change size (this does a re-pack
324 of the entries), False to raise an exception
325 """
326 if not entry.WriteData(data, do_compress):
327 if not image.allow_repack:
328 entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
329 if not allow_resize:
330 entry.Raise('Entry data size does not match, but resize is disabled')
331
332
333def AfterReplace(image, allow_resize, write_map):
334 """Handle write out an image after replacing entries in it
335
336 Args:
337 image: Image to write
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 write_map: True to write a map file
341 """
Simon Glass011f1b32022-01-29 14:14:15 -0700342 tout.info('Processing image')
Simon Glass274bd0e2019-07-20 12:24:13 -0600343 ProcessImage(image, update_fdt=True, write_map=write_map,
344 get_contents=False, allow_resize=allow_resize)
345
346
347def WriteEntryToImage(image, entry, data, do_compress=True, allow_resize=True,
348 write_map=False):
349 BeforeReplace(image, allow_resize)
Simon Glass011f1b32022-01-29 14:14:15 -0700350 tout.info('Writing data to %s' % entry.GetPath())
Simon Glass274bd0e2019-07-20 12:24:13 -0600351 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
352 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
353
354
Simon Glassd48f94e2019-07-20 12:24:12 -0600355def WriteEntry(image_fname, entry_path, data, do_compress=True,
356 allow_resize=True, write_map=False):
Simon Glass3971c952019-07-20 12:24:11 -0600357 """Replace an entry in an image
358
359 This replaces the data in a particular entry in an image. This size of the
360 new data must match the size of the old data unless allow_resize is True.
361
362 Args:
363 image_fname: Image filename to process
364 entry_path: Path to entry to extract
365 data: Data to replace with
Simon Glassd48f94e2019-07-20 12:24:12 -0600366 do_compress: True to compress the data if needed, False if data is
Simon Glass3971c952019-07-20 12:24:11 -0600367 already compressed so should be used as is
368 allow_resize: True to allow entries to change size (this does a re-pack
369 of the entries), False to raise an exception
Simon Glassd48f94e2019-07-20 12:24:12 -0600370 write_map: True to write a map file
Simon Glass3971c952019-07-20 12:24:11 -0600371
372 Returns:
373 Image object that was updated
374 """
Simon Glass011f1b32022-01-29 14:14:15 -0700375 tout.info("Write entry '%s', file '%s'" % (entry_path, image_fname))
Simon Glass3971c952019-07-20 12:24:11 -0600376 image = Image.FromFile(image_fname)
Stefan Herbrechtsmeier47250302022-08-19 16:25:22 +0200377 image.CollectBintools()
Simon Glass3971c952019-07-20 12:24:11 -0600378 entry = image.FindEntryPath(entry_path)
Simon Glass274bd0e2019-07-20 12:24:13 -0600379 WriteEntryToImage(image, entry, data, do_compress=do_compress,
380 allow_resize=allow_resize, write_map=write_map)
Simon Glass3971c952019-07-20 12:24:11 -0600381
Simon Glass3971c952019-07-20 12:24:11 -0600382 return image
383
Simon Glass30033c22019-07-20 12:24:15 -0600384
385def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
386 do_compress=True, allow_resize=True, write_map=False):
387 """Replace the data from one or more entries from input files
388
389 Args:
390 image_fname: Image filename to process
Jan Kiszka8ea44432021-11-11 08:13:30 +0100391 input_fname: Single input filename to use if replacing one file, None
Simon Glass30033c22019-07-20 12:24:15 -0600392 otherwise
393 indir: Input directory to use (for any number of files), else None
Jan Kiszka8ea44432021-11-11 08:13:30 +0100394 entry_paths: List of entry paths to replace
Simon Glass30033c22019-07-20 12:24:15 -0600395 do_compress: True if the input data is uncompressed and may need to be
396 compressed if the entry requires it, False if the data is already
397 compressed.
398 write_map: True to write a map file
399
400 Returns:
401 List of EntryInfo records that were written
402 """
Jan Kiszkaafc8f292021-11-11 08:14:18 +0100403 image_fname = os.path.abspath(image_fname)
Simon Glass30033c22019-07-20 12:24:15 -0600404 image = Image.FromFile(image_fname)
405
406 # Replace an entry from a single file, as a special case
407 if input_fname:
408 if not entry_paths:
409 raise ValueError('Must specify an entry path to read with -f')
410 if len(entry_paths) != 1:
411 raise ValueError('Must specify exactly one entry path to write with -f')
412 entry = image.FindEntryPath(entry_paths[0])
Simon Glass80025522022-01-29 14:14:04 -0700413 data = tools.read_file(input_fname)
Simon Glass011f1b32022-01-29 14:14:15 -0700414 tout.notice("Read %#x bytes from file '%s'" % (len(data), input_fname))
Simon Glass30033c22019-07-20 12:24:15 -0600415 WriteEntryToImage(image, entry, data, do_compress=do_compress,
416 allow_resize=allow_resize, write_map=write_map)
417 return
418
419 # Otherwise we will input from a path given by the entry path of each entry.
420 # This means that files must appear in subdirectories if they are part of
421 # a sub-section.
422 einfos = image.GetListEntries(entry_paths)[0]
Simon Glass011f1b32022-01-29 14:14:15 -0700423 tout.notice("Replacing %d matching entries in image '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600424 (len(einfos), image_fname))
425
426 BeforeReplace(image, allow_resize)
427
428 for einfo in einfos:
429 entry = einfo.entry
430 if entry.GetEntries():
Simon Glass011f1b32022-01-29 14:14:15 -0700431 tout.info("Skipping section entry '%s'" % entry.GetPath())
Simon Glass30033c22019-07-20 12:24:15 -0600432 continue
433
434 path = entry.GetPath()[1:]
435 fname = os.path.join(indir, path)
436
437 if os.path.exists(fname):
Simon Glass011f1b32022-01-29 14:14:15 -0700438 tout.notice("Write entry '%s' from file '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600439 (entry.GetPath(), fname))
Simon Glass80025522022-01-29 14:14:04 -0700440 data = tools.read_file(fname)
Simon Glass30033c22019-07-20 12:24:15 -0600441 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
442 else:
Simon Glass011f1b32022-01-29 14:14:15 -0700443 tout.warning("Skipping entry '%s' from missing file '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600444 (entry.GetPath(), fname))
445
446 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
447 return image
448
449
Simon Glass55ab0b62021-03-18 20:25:06 +1300450def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt, use_expanded):
Simon Glassd3151ff2019-07-20 12:23:27 -0600451 """Prepare the images to be processed and select the device tree
452
453 This function:
454 - reads in the device tree
455 - finds and scans the binman node to create all entries
456 - selects which images to build
457 - Updates the device tress with placeholder properties for offset,
458 image-pos, etc.
459
460 Args:
461 dtb_fname: Filename of the device tree file to use (.dts or .dtb)
462 selected_images: List of images to output, or None for all
463 update_fdt: True to update the FDT wth entry offsets, etc.
Simon Glass55ab0b62021-03-18 20:25:06 +1300464 use_expanded: True to use expanded versions of entries, if available.
465 So if 'u-boot' is called for, we use 'u-boot-expanded' instead. This
466 is needed if update_fdt is True (although tests may disable it)
Simon Glass31ee50f2020-09-01 05:13:55 -0600467
468 Returns:
469 OrderedDict of images:
470 key: Image name (str)
471 value: Image object
Simon Glassd3151ff2019-07-20 12:23:27 -0600472 """
473 # Import these here in case libfdt.py is not available, in which case
474 # the above help option still works.
Simon Glassc585dd42020-04-17 18:09:03 -0600475 from dtoc import fdt
476 from dtoc import fdt_util
Simon Glassd3151ff2019-07-20 12:23:27 -0600477 global images
478
479 # Get the device tree ready by compiling it and copying the compiled
480 # output into a file in our output directly. Then scan it for use
481 # in binman.
482 dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
Simon Glass80025522022-01-29 14:14:04 -0700483 fname = tools.get_output_filename('u-boot.dtb.out')
484 tools.write_file(fname, tools.read_file(dtb_fname))
Simon Glassd3151ff2019-07-20 12:23:27 -0600485 dtb = fdt.FdtScan(fname)
486
487 node = _FindBinmanNode(dtb)
488 if not node:
489 raise ValueError("Device tree '%s' does not have a 'binman' "
490 "node" % dtb_fname)
491
Simon Glass55ab0b62021-03-18 20:25:06 +1300492 images = _ReadImageDesc(node, use_expanded)
Simon Glassd3151ff2019-07-20 12:23:27 -0600493
494 if select_images:
495 skip = []
496 new_images = OrderedDict()
497 for name, image in images.items():
498 if name in select_images:
499 new_images[name] = image
500 else:
501 skip.append(name)
502 images = new_images
Simon Glass011f1b32022-01-29 14:14:15 -0700503 tout.notice('Skipping images: %s' % ', '.join(skip))
Simon Glassd3151ff2019-07-20 12:23:27 -0600504
505 state.Prepare(images, dtb)
506
507 # Prepare the device tree by making sure that any missing
508 # properties are added (e.g. 'pos' and 'size'). The values of these
509 # may not be correct yet, but we add placeholders so that the
510 # size of the device tree is correct. Later, in
511 # SetCalculatedProperties() we will insert the correct values
512 # without changing the device-tree size, thus ensuring that our
513 # entry offsets remain the same.
514 for image in images.values():
Simon Glassf86ddad2022-03-05 20:19:00 -0700515 image.gen_entries()
Stefan Herbrechtsmeier47250302022-08-19 16:25:22 +0200516 image.CollectBintools()
Simon Glassd3151ff2019-07-20 12:23:27 -0600517 if update_fdt:
Simon Glassacd6c6e2020-10-26 17:40:17 -0600518 image.AddMissingProperties(True)
Simon Glassd3151ff2019-07-20 12:23:27 -0600519 image.ProcessFdt(dtb)
520
Simon Glass5a300602019-07-20 12:23:29 -0600521 for dtb_item in state.GetAllFdts():
Simon Glassd3151ff2019-07-20 12:23:27 -0600522 dtb_item.Sync(auto_resize=True)
523 dtb_item.Pack()
524 dtb_item.Flush()
525 return images
526
527
Simon Glassf8a54bc2019-07-20 12:23:56 -0600528def ProcessImage(image, update_fdt, write_map, get_contents=True,
Heiko Thiery6d451362022-01-06 11:49:41 +0100529 allow_resize=True, allow_missing=False,
530 allow_fake_blobs=False):
Simon Glassb766c5e52019-07-20 12:23:24 -0600531 """Perform all steps for this image, including checking and # writing it.
532
533 This means that errors found with a later image will be reported after
534 earlier images are already completed and written, but that does not seem
535 important.
536
537 Args:
538 image: Image to process
539 update_fdt: True to update the FDT wth entry offsets, etc.
540 write_map: True to write a map file
Simon Glass072959a2019-07-20 12:23:50 -0600541 get_contents: True to get the image contents from files, etc., False if
542 the contents is already present
Simon Glassf8a54bc2019-07-20 12:23:56 -0600543 allow_resize: True to allow entries to change size (this does a re-pack
544 of the entries), False to raise an exception
Simon Glass5d94cc62020-07-09 18:39:38 -0600545 allow_missing: Allow blob_ext objects to be missing
Heiko Thiery6d451362022-01-06 11:49:41 +0100546 allow_fake_blobs: Allow blob_ext objects to be faked with dummy files
Simon Glassa003cd32020-07-09 18:39:40 -0600547
548 Returns:
Heiko Thiery6d451362022-01-06 11:49:41 +0100549 True if one or more external blobs are missing or faked,
550 False if all are present
Simon Glassb766c5e52019-07-20 12:23:24 -0600551 """
Simon Glass072959a2019-07-20 12:23:50 -0600552 if get_contents:
Simon Glass5d94cc62020-07-09 18:39:38 -0600553 image.SetAllowMissing(allow_missing)
Heiko Thiery6d451362022-01-06 11:49:41 +0100554 image.SetAllowFakeBlob(allow_fake_blobs)
Simon Glass072959a2019-07-20 12:23:50 -0600555 image.GetEntryContents()
Simon Glass1e9e61c2023-01-07 14:07:12 -0700556 image.drop_absent()
Simon Glassb766c5e52019-07-20 12:23:24 -0600557 image.GetEntryOffsets()
558
559 # We need to pack the entries to figure out where everything
560 # should be placed. This sets the offset/size of each entry.
561 # However, after packing we call ProcessEntryContents() which
562 # may result in an entry changing size. In that case we need to
563 # do another pass. Since the device tree often contains the
564 # final offset/size information we try to make space for this in
565 # AddMissingProperties() above. However, if the device is
566 # compressed we cannot know this compressed size in advance,
567 # since changing an offset from 0x100 to 0x104 (for example) can
568 # alter the compressed size of the device tree. So we need a
569 # third pass for this.
Simon Glass37fdd142019-07-20 12:24:06 -0600570 passes = 5
Simon Glassb766c5e52019-07-20 12:23:24 -0600571 for pack_pass in range(passes):
572 try:
573 image.PackEntries()
Simon Glassb766c5e52019-07-20 12:23:24 -0600574 except Exception as e:
575 if write_map:
576 fname = image.WriteMap()
577 print("Wrote map file '%s' to show errors" % fname)
578 raise
579 image.SetImagePos()
580 if update_fdt:
581 image.SetCalculatedProperties()
Simon Glass5a300602019-07-20 12:23:29 -0600582 for dtb_item in state.GetAllFdts():
Simon Glassb766c5e52019-07-20 12:23:24 -0600583 dtb_item.Sync()
Simon Glassf8a54bc2019-07-20 12:23:56 -0600584 dtb_item.Flush()
Simon Glasse5943412019-08-24 07:23:12 -0600585 image.WriteSymbols()
Simon Glassb766c5e52019-07-20 12:23:24 -0600586 sizes_ok = image.ProcessEntryContents()
587 if sizes_ok:
588 break
589 image.ResetForPack()
Simon Glass011f1b32022-01-29 14:14:15 -0700590 tout.info('Pack completed after %d pass(es)' % (pack_pass + 1))
Simon Glassb766c5e52019-07-20 12:23:24 -0600591 if not sizes_ok:
Simon Glass9d8ee322019-07-20 12:23:58 -0600592 image.Raise('Entries changed size after packing (tried %s passes)' %
Simon Glassb766c5e52019-07-20 12:23:24 -0600593 passes)
594
Simon Glassb766c5e52019-07-20 12:23:24 -0600595 image.BuildImage()
596 if write_map:
597 image.WriteMap()
Simon Glass63328f12023-01-07 14:07:15 -0700598
Simon Glassa003cd32020-07-09 18:39:40 -0600599 missing_list = []
600 image.CheckMissing(missing_list)
601 if missing_list:
Simon Glass011f1b32022-01-29 14:14:15 -0700602 tout.warning("Image '%s' is missing external blobs and is non-functional: %s" %
Simon Glassa003cd32020-07-09 18:39:40 -0600603 (image.name, ' '.join([e.name for e in missing_list])))
Simon Glassa820af72020-09-06 10:39:09 -0600604 _ShowHelpForMissingBlobs(missing_list)
Simon Glass63328f12023-01-07 14:07:15 -0700605
Heiko Thiery6d451362022-01-06 11:49:41 +0100606 faked_list = []
607 image.CheckFakedBlobs(faked_list)
608 if faked_list:
Simon Glass011f1b32022-01-29 14:14:15 -0700609 tout.warning(
Simon Glassf9f34032022-01-09 20:13:45 -0700610 "Image '%s' has faked external blobs and is non-functional: %s" %
611 (image.name, ' '.join([os.path.basename(e.GetDefaultFilename())
612 for e in faked_list])))
Simon Glass63328f12023-01-07 14:07:15 -0700613
614 optional_list = []
615 image.CheckOptional(optional_list)
616 if optional_list:
617 tout.warning(
618 "Image '%s' is missing external blobs but is still functional: %s" %
619 (image.name, ' '.join([e.name for e in optional_list])))
620 _ShowHelpForMissingBlobs(optional_list)
621
Simon Glass66152ce2022-01-09 20:14:09 -0700622 missing_bintool_list = []
623 image.check_missing_bintools(missing_bintool_list)
624 if missing_bintool_list:
Simon Glass011f1b32022-01-29 14:14:15 -0700625 tout.warning(
Simon Glass66152ce2022-01-09 20:14:09 -0700626 "Image '%s' has missing bintools and is non-functional: %s" %
627 (image.name, ' '.join([os.path.basename(bintool.name)
628 for bintool in missing_bintool_list])))
629 return any([missing_list, faked_list, missing_bintool_list])
Simon Glassb766c5e52019-07-20 12:23:24 -0600630
631
Simon Glassf46732a2019-07-08 14:25:29 -0600632def Binman(args):
Simon Glass2574ef62016-11-25 20:15:51 -0700633 """The main control code for binman
634
635 This assumes that help and test options have already been dealt with. It
636 deals with the core task of building images.
637
638 Args:
Simon Glassf46732a2019-07-08 14:25:29 -0600639 args: Command line arguments Namespace object
Simon Glass2574ef62016-11-25 20:15:51 -0700640 """
Simon Glassb9ba4e02019-08-24 07:22:44 -0600641 global Image
642 global state
643
Simon Glassf46732a2019-07-08 14:25:29 -0600644 if args.full_help:
Simon Glassfeb80cc2023-02-23 18:18:20 -0700645 with importlib.resources.path('binman', 'README.rst') as readme:
646 tools.print_full_help(str(readme))
Simon Glass2574ef62016-11-25 20:15:51 -0700647 return 0
648
Simon Glassb9ba4e02019-08-24 07:22:44 -0600649 # Put these here so that we can import this module without libfdt
Simon Glass90cd6f02020-08-05 13:27:47 -0600650 from binman.image import Image
Simon Glassc585dd42020-04-17 18:09:03 -0600651 from binman import state
Simon Glassb9ba4e02019-08-24 07:22:44 -0600652
Simon Glass9a1c7262023-02-22 12:14:49 -0700653 tool_paths = []
654 if args.toolpath:
655 tool_paths += args.toolpath
656 if args.tooldir:
657 tool_paths.append(args.tooldir)
658 tools.set_tool_paths(tool_paths or None)
659 bintool.Bintool.set_tool_dir(args.tooldir)
660
Simon Glass4eae9252022-01-09 20:13:50 -0700661 if args.cmd in ['ls', 'extract', 'replace', 'tool']:
Simon Glass9b7f5002019-07-20 12:23:53 -0600662 try:
Simon Glass011f1b32022-01-29 14:14:15 -0700663 tout.init(args.verbosity)
Simon Glassb9b9b272023-03-02 17:02:42 -0700664 if args.cmd == 'replace':
665 tools.prepare_output_dir(args.outdir, args.preserve)
666 else:
667 tools.prepare_output_dir(None)
Simon Glassdf08cbb2019-09-15 18:10:36 -0600668 if args.cmd == 'ls':
669 ListEntries(args.image, args.paths)
Simon Glassb2fd11d2019-07-08 14:25:48 -0600670
Simon Glassdf08cbb2019-09-15 18:10:36 -0600671 if args.cmd == 'extract':
672 ExtractEntries(args.image, args.filename, args.outdir, args.paths,
Simon Glass637958f2021-11-23 21:09:50 -0700673 not args.uncompressed, args.format)
Simon Glass980a2842019-07-08 14:25:52 -0600674
Simon Glassdf08cbb2019-09-15 18:10:36 -0600675 if args.cmd == 'replace':
676 ReplaceEntries(args.image, args.filename, args.indir, args.paths,
677 do_compress=not args.compressed,
678 allow_resize=not args.fix_size, write_map=args.map)
Simon Glass4eae9252022-01-09 20:13:50 -0700679
680 if args.cmd == 'tool':
Simon Glass4eae9252022-01-09 20:13:50 -0700681 if args.list:
682 bintool.Bintool.list_all()
683 elif args.fetch:
684 if not args.bintools:
685 raise ValueError(
686 "Please specify bintools to fetch or 'all' or 'missing'")
687 bintool.Bintool.fetch_tools(bintool.FETCH_ANY,
688 args.bintools)
689 else:
690 raise ValueError("Invalid arguments to 'tool' subcommand")
Simon Glassdf08cbb2019-09-15 18:10:36 -0600691 except:
692 raise
Simon Glass30033c22019-07-20 12:24:15 -0600693 finally:
Simon Glass80025522022-01-29 14:14:04 -0700694 tools.finalise_output_dir()
Simon Glass30033c22019-07-20 12:24:15 -0600695 return 0
696
Simon Glassadfb8492021-11-03 21:09:18 -0600697 elf_params = None
698 if args.update_fdt_in_elf:
699 elf_params = args.update_fdt_in_elf.split(',')
700 if len(elf_params) != 4:
701 raise ValueError('Invalid args %s to --update-fdt-in-elf: expected infile,outfile,begin_sym,end_sym' %
702 elf_params)
703
Simon Glass2574ef62016-11-25 20:15:51 -0700704 # Try to figure out which device tree contains our image description
Simon Glassf46732a2019-07-08 14:25:29 -0600705 if args.dt:
706 dtb_fname = args.dt
Simon Glass2574ef62016-11-25 20:15:51 -0700707 else:
Simon Glassf46732a2019-07-08 14:25:29 -0600708 board = args.board
Simon Glass2574ef62016-11-25 20:15:51 -0700709 if not board:
710 raise ValueError('Must provide a board to process (use -b <board>)')
Simon Glassf46732a2019-07-08 14:25:29 -0600711 board_pathname = os.path.join(args.build_dir, board)
Simon Glass2574ef62016-11-25 20:15:51 -0700712 dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
Simon Glassf46732a2019-07-08 14:25:29 -0600713 if not args.indir:
714 args.indir = ['.']
715 args.indir.append(board_pathname)
Simon Glass2574ef62016-11-25 20:15:51 -0700716
717 try:
Simon Glass011f1b32022-01-29 14:14:15 -0700718 tout.init(args.verbosity)
Simon Glassf46732a2019-07-08 14:25:29 -0600719 elf.debug = args.debug
720 cbfs_util.VERBOSE = args.verbosity > 2
721 state.use_fake_dtb = args.fake_dtb
Simon Glass55ab0b62021-03-18 20:25:06 +1300722
723 # Normally we replace the 'u-boot' etype with 'u-boot-expanded', etc.
724 # When running tests this can be disabled using this flag. When not
725 # updating the FDT in image, it is not needed by binman, but we use it
726 # for consistency, so that the images look the same to U-Boot at
727 # runtime.
728 use_expanded = not args.no_expanded
Simon Glass2574ef62016-11-25 20:15:51 -0700729 try:
Simon Glass80025522022-01-29 14:14:04 -0700730 tools.set_input_dirs(args.indir)
731 tools.prepare_output_dir(args.outdir, args.preserve)
Simon Glassf46732a2019-07-08 14:25:29 -0600732 state.SetEntryArgs(args.entry_arg)
Simon Glass76f496d2021-07-06 10:36:37 -0600733 state.SetThreads(args.threads)
Simon Glass92307732018-07-06 10:27:40 -0600734
Simon Glassd3151ff2019-07-20 12:23:27 -0600735 images = PrepareImagesAndDtbs(dtb_fname, args.image,
Simon Glass55ab0b62021-03-18 20:25:06 +1300736 args.update_fdt, use_expanded)
Heiko Thiery6d451362022-01-06 11:49:41 +0100737
Simon Glass76f496d2021-07-06 10:36:37 -0600738 if args.test_section_timeout:
739 # Set the first image to timeout, used in testThreadTimeout()
740 images[list(images.keys())[0]].test_section_timeout = True
Heiko Thiery6d451362022-01-06 11:49:41 +0100741 invalid = False
Simon Glass66152ce2022-01-09 20:14:09 -0700742 bintool.Bintool.set_missing_list(
743 args.force_missing_bintools.split(',') if
744 args.force_missing_bintools else None)
Simon Glass7d3e4072022-08-07 09:46:46 -0600745
746 # Create the directory here instead of Entry.check_fake_fname()
747 # since that is called from a threaded context so different threads
748 # may race to create the directory
749 if args.fake_ext_blobs:
750 entry.Entry.create_fake_dir()
751
Simon Glass2574ef62016-11-25 20:15:51 -0700752 for image in images.values():
Heiko Thiery6d451362022-01-06 11:49:41 +0100753 invalid |= ProcessImage(image, args.update_fdt, args.map,
754 allow_missing=args.allow_missing,
755 allow_fake_blobs=args.fake_ext_blobs)
Simon Glassbdb40312018-09-14 04:57:20 -0600756
757 # Write the updated FDTs to our output files
Simon Glass5a300602019-07-20 12:23:29 -0600758 for dtb_item in state.GetAllFdts():
Simon Glass80025522022-01-29 14:14:04 -0700759 tools.write_file(dtb_item._fname, dtb_item.GetContents())
Simon Glassbdb40312018-09-14 04:57:20 -0600760
Simon Glassadfb8492021-11-03 21:09:18 -0600761 if elf_params:
762 data = state.GetFdtForEtype('u-boot-dtb').GetContents()
763 elf.UpdateFile(*elf_params, data)
764
Simon Glass6bce5dc2022-11-09 19:14:42 -0700765 # This can only be True if -M is provided, since otherwise binman
766 # would have raised an error already
Heiko Thiery6d451362022-01-06 11:49:41 +0100767 if invalid:
Simon Glass6bce5dc2022-11-09 19:14:42 -0700768 msg = '\nSome images are invalid'
769 if args.ignore_missing:
770 tout.warning(msg)
771 else:
772 tout.error(msg)
773 return 103
Simon Glass748a1d42021-07-06 10:36:41 -0600774
775 # Use this to debug the time take to pack the image
776 #state.TimingShow()
Simon Glass2574ef62016-11-25 20:15:51 -0700777 finally:
Simon Glass80025522022-01-29 14:14:04 -0700778 tools.finalise_output_dir()
Simon Glass2574ef62016-11-25 20:15:51 -0700779 finally:
Simon Glass011f1b32022-01-29 14:14:15 -0700780 tout.uninit()
Simon Glass2574ef62016-11-25 20:15:51 -0700781
782 return 0