blob: ce57dc7efc7bf69ee160bc067666ce83fc377b9e [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 Glass2574ef62016-11-25 20:15:51 -070010import os
Simon Glassc1dc2f82020-08-29 11:36:14 -060011import pkg_resources
Simon Glassa820af72020-09-06 10:39:09 -060012import re
Simon Glassc1dc2f82020-08-29 11:36:14 -060013
Simon Glass2574ef62016-11-25 20:15:51 -070014import sys
Simon Glassa997ea52020-04-17 18:09:04 -060015from patman import tools
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
19from binman import elf
Simon Glassa997ea52020-04-17 18:09:04 -060020from patman import command
21from patman import tout
Simon Glass2574ef62016-11-25 20:15:51 -070022
Simon Glass2a0fa982022-02-11 13:23:21 -070023# These are imported if needed since they import libfdt
24state = None
25Image = None
26
Simon Glass2574ef62016-11-25 20:15:51 -070027# List of images we plan to create
28# Make this global so that it can be referenced from tests
29images = OrderedDict()
30
Simon Glassa820af72020-09-06 10:39:09 -060031# Help text for each type of missing blob, dict:
32# key: Value of the entry's 'missing-msg' or entry name
33# value: Text for the help
34missing_blob_help = {}
35
Simon Glass55ab0b62021-03-18 20:25:06 +130036def _ReadImageDesc(binman_node, use_expanded):
Simon Glass2574ef62016-11-25 20:15:51 -070037 """Read the image descriptions from the /binman node
38
39 This normally produces a single Image object called 'image'. But if
40 multiple images are present, they will all be returned.
41
42 Args:
43 binman_node: Node object of the /binman node
Simon Glass55ab0b62021-03-18 20:25:06 +130044 use_expanded: True if the FDT will be updated with the entry information
Simon Glass2574ef62016-11-25 20:15:51 -070045 Returns:
46 OrderedDict of Image objects, each of which describes an image
47 """
Simon Glass2a0fa982022-02-11 13:23:21 -070048 # For Image()
49 # pylint: disable=E1102
Simon Glass2574ef62016-11-25 20:15:51 -070050 images = OrderedDict()
51 if 'multiple-images' in binman_node.props:
52 for node in binman_node.subnodes:
Simon Glass55ab0b62021-03-18 20:25:06 +130053 images[node.name] = Image(node.name, node,
54 use_expanded=use_expanded)
Simon Glass2574ef62016-11-25 20:15:51 -070055 else:
Simon Glass55ab0b62021-03-18 20:25:06 +130056 images['image'] = Image('image', binman_node, use_expanded=use_expanded)
Simon Glass2574ef62016-11-25 20:15:51 -070057 return images
58
Simon Glass22c92ca2017-05-27 07:38:29 -060059def _FindBinmanNode(dtb):
Simon Glass2574ef62016-11-25 20:15:51 -070060 """Find the 'binman' node in the device tree
61
62 Args:
Simon Glass22c92ca2017-05-27 07:38:29 -060063 dtb: Fdt object to scan
Simon Glass2574ef62016-11-25 20:15:51 -070064 Returns:
65 Node object of /binman node, or None if not found
66 """
Simon Glass22c92ca2017-05-27 07:38:29 -060067 for node in dtb.GetRoot().subnodes:
Simon Glass2574ef62016-11-25 20:15:51 -070068 if node.name == 'binman':
69 return node
70 return None
71
Simon Glassa820af72020-09-06 10:39:09 -060072def _ReadMissingBlobHelp():
73 """Read the missing-blob-help file
74
75 This file containins help messages explaining what to do when external blobs
76 are missing.
77
78 Returns:
79 Dict:
80 key: Message tag (str)
81 value: Message text (str)
82 """
83
84 def _FinishTag(tag, msg, result):
85 if tag:
86 result[tag] = msg.rstrip()
87 tag = None
88 msg = ''
89 return tag, msg
90
91 my_data = pkg_resources.resource_string(__name__, 'missing-blob-help')
92 re_tag = re.compile('^([-a-z0-9]+):$')
93 result = {}
94 tag = None
95 msg = ''
96 for line in my_data.decode('utf-8').splitlines():
97 if not line.startswith('#'):
98 m_tag = re_tag.match(line)
99 if m_tag:
100 _, msg = _FinishTag(tag, msg, result)
101 tag = m_tag.group(1)
102 elif tag:
103 msg += line + '\n'
104 _FinishTag(tag, msg, result)
105 return result
106
107def _ShowBlobHelp(path, text):
Simon Glass011f1b32022-01-29 14:14:15 -0700108 tout.warning('\n%s:' % path)
Simon Glassa820af72020-09-06 10:39:09 -0600109 for line in text.splitlines():
Simon Glass011f1b32022-01-29 14:14:15 -0700110 tout.warning(' %s' % line)
Simon Glassa820af72020-09-06 10:39:09 -0600111
112def _ShowHelpForMissingBlobs(missing_list):
113 """Show help for each missing blob to help the user take action
114
115 Args:
116 missing_list: List of Entry objects to show help for
117 """
118 global missing_blob_help
119
120 if not missing_blob_help:
121 missing_blob_help = _ReadMissingBlobHelp()
122
123 for entry in missing_list:
124 tags = entry.GetHelpTags()
125
126 # Show the first match help message
127 for tag in tags:
128 if tag in missing_blob_help:
129 _ShowBlobHelp(entry._node.path, missing_blob_help[tag])
130 break
131
Simon Glass220ff5f2020-08-05 13:27:46 -0600132def GetEntryModules(include_testing=True):
133 """Get a set of entry class implementations
134
135 Returns:
136 Set of paths to entry class filenames
137 """
Simon Glassc1dc2f82020-08-29 11:36:14 -0600138 glob_list = pkg_resources.resource_listdir(__name__, 'etype')
139 glob_list = [fname for fname in glob_list if fname.endswith('.py')]
Simon Glass220ff5f2020-08-05 13:27:46 -0600140 return set([os.path.splitext(os.path.basename(item))[0]
141 for item in glob_list
142 if include_testing or '_testing' not in item])
143
Simon Glass29aa7362018-09-14 04:57:19 -0600144def WriteEntryDocs(modules, test_missing=None):
145 """Write out documentation for all entries
Simon Glass92307732018-07-06 10:27:40 -0600146
147 Args:
Simon Glass29aa7362018-09-14 04:57:19 -0600148 modules: List of Module objects to get docs for
Simon Glass620c4462022-01-09 20:14:11 -0700149 test_missing: Used for testing only, to force an entry's documentation
Simon Glass29aa7362018-09-14 04:57:19 -0600150 to show as missing even if it is present. Should be set to None in
151 normal use.
Simon Glass92307732018-07-06 10:27:40 -0600152 """
Simon Glassc585dd42020-04-17 18:09:03 -0600153 from binman.entry import Entry
Simon Glass969616c2018-07-17 13:25:36 -0600154 Entry.WriteDocs(modules, test_missing)
155
Simon Glassb2fd11d2019-07-08 14:25:48 -0600156
Simon Glass620c4462022-01-09 20:14:11 -0700157def write_bintool_docs(modules, test_missing=None):
158 """Write out documentation for all bintools
159
160 Args:
161 modules: List of Module objects to get docs for
162 test_missing: Used for testing only, to force an entry's documentation
163 to show as missing even if it is present. Should be set to None in
164 normal use.
165 """
166 bintool.Bintool.WriteDocs(modules, test_missing)
167
168
Simon Glassb2fd11d2019-07-08 14:25:48 -0600169def ListEntries(image_fname, entry_paths):
170 """List the entries in an image
171
172 This decodes the supplied image and displays a table of entries from that
173 image, preceded by a header.
174
175 Args:
176 image_fname: Image filename to process
177 entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*',
178 'section/u-boot'])
179 """
180 image = Image.FromFile(image_fname)
181
182 entries, lines, widths = image.GetListEntries(entry_paths)
183
184 num_columns = len(widths)
185 for linenum, line in enumerate(lines):
186 if linenum == 1:
187 # Print header line
188 print('-' * (sum(widths) + num_columns * 2))
189 out = ''
190 for i, item in enumerate(line):
191 width = -widths[i]
192 if item.startswith('>'):
193 width = -width
194 item = item[1:]
195 txt = '%*s ' % (width, item)
196 out += txt
197 print(out.rstrip())
198
Simon Glass4c613bf2019-07-08 14:25:50 -0600199
200def ReadEntry(image_fname, entry_path, decomp=True):
201 """Extract an entry from an image
202
203 This extracts the data from a particular entry in an image
204
205 Args:
206 image_fname: Image filename to process
207 entry_path: Path to entry to extract
208 decomp: True to return uncompressed data, if the data is compress
209 False to return the raw data
210
211 Returns:
212 data extracted from the entry
213 """
Simon Glassb9ba4e02019-08-24 07:22:44 -0600214 global Image
Simon Glass90cd6f02020-08-05 13:27:47 -0600215 from binman.image import Image
Simon Glassb9ba4e02019-08-24 07:22:44 -0600216
Simon Glass4c613bf2019-07-08 14:25:50 -0600217 image = Image.FromFile(image_fname)
218 entry = image.FindEntryPath(entry_path)
219 return entry.ReadData(decomp)
220
221
Simon Glass637958f2021-11-23 21:09:50 -0700222def ShowAltFormats(image):
223 """Show alternative formats available for entries in the image
224
225 This shows a list of formats available.
226
227 Args:
228 image (Image): Image to check
229 """
230 alt_formats = {}
231 image.CheckAltFormats(alt_formats)
232 print('%-10s %-20s %s' % ('Flag (-F)', 'Entry type', 'Description'))
233 for name, val in alt_formats.items():
234 entry, helptext = val
235 print('%-10s %-20s %s' % (name, entry.etype, helptext))
236
237
Simon Glass980a2842019-07-08 14:25:52 -0600238def ExtractEntries(image_fname, output_fname, outdir, entry_paths,
Simon Glass637958f2021-11-23 21:09:50 -0700239 decomp=True, alt_format=None):
Simon Glass980a2842019-07-08 14:25:52 -0600240 """Extract the data from one or more entries and write it to files
241
242 Args:
243 image_fname: Image filename to process
244 output_fname: Single output filename to use if extracting one file, None
245 otherwise
246 outdir: Output directory to use (for any number of files), else None
247 entry_paths: List of entry paths to extract
Simon Glassd48f94e2019-07-20 12:24:12 -0600248 decomp: True to decompress the entry data
Simon Glass980a2842019-07-08 14:25:52 -0600249
250 Returns:
251 List of EntryInfo records that were written
252 """
253 image = Image.FromFile(image_fname)
254
Simon Glass637958f2021-11-23 21:09:50 -0700255 if alt_format == 'list':
256 ShowAltFormats(image)
257 return
258
Simon Glass980a2842019-07-08 14:25:52 -0600259 # Output an entry to a single file, as a special case
260 if output_fname:
261 if not entry_paths:
Simon Glassa772d3f2019-07-20 12:24:14 -0600262 raise ValueError('Must specify an entry path to write with -f')
Simon Glass980a2842019-07-08 14:25:52 -0600263 if len(entry_paths) != 1:
Simon Glassa772d3f2019-07-20 12:24:14 -0600264 raise ValueError('Must specify exactly one entry path to write with -f')
Simon Glass980a2842019-07-08 14:25:52 -0600265 entry = image.FindEntryPath(entry_paths[0])
Simon Glass637958f2021-11-23 21:09:50 -0700266 data = entry.ReadData(decomp, alt_format)
Simon Glass80025522022-01-29 14:14:04 -0700267 tools.write_file(output_fname, data)
Simon Glass011f1b32022-01-29 14:14:15 -0700268 tout.notice("Wrote %#x bytes to file '%s'" % (len(data), output_fname))
Simon Glass980a2842019-07-08 14:25:52 -0600269 return
270
271 # Otherwise we will output to a path given by the entry path of each entry.
272 # This means that entries will appear in subdirectories if they are part of
273 # a sub-section.
274 einfos = image.GetListEntries(entry_paths)[0]
Simon Glass011f1b32022-01-29 14:14:15 -0700275 tout.notice('%d entries match and will be written' % len(einfos))
Simon Glass980a2842019-07-08 14:25:52 -0600276 for einfo in einfos:
277 entry = einfo.entry
Simon Glass637958f2021-11-23 21:09:50 -0700278 data = entry.ReadData(decomp, alt_format)
Simon Glass980a2842019-07-08 14:25:52 -0600279 path = entry.GetPath()[1:]
280 fname = os.path.join(outdir, path)
281
282 # If this entry has children, create a directory for it and put its
283 # data in a file called 'root' in that directory
284 if entry.GetEntries():
Simon Glass4ef93d92021-03-18 20:24:51 +1300285 if fname and not os.path.exists(fname):
Simon Glass980a2842019-07-08 14:25:52 -0600286 os.makedirs(fname)
287 fname = os.path.join(fname, 'root')
Simon Glass011f1b32022-01-29 14:14:15 -0700288 tout.notice("Write entry '%s' size %x to '%s'" %
Simon Glass08349452021-01-06 21:35:13 -0700289 (entry.GetPath(), len(data), fname))
Simon Glass80025522022-01-29 14:14:04 -0700290 tools.write_file(fname, data)
Simon Glass980a2842019-07-08 14:25:52 -0600291 return einfos
292
293
Simon Glass274bd0e2019-07-20 12:24:13 -0600294def BeforeReplace(image, allow_resize):
295 """Handle getting an image ready for replacing entries in it
296
297 Args:
298 image: Image to prepare
299 """
300 state.PrepareFromLoadedData(image)
301 image.LoadData()
Alper Nebi Yasake63ca5a2022-03-27 18:31:45 +0300302 image.CollectBintools()
Simon Glass274bd0e2019-07-20 12:24:13 -0600303
304 # If repacking, drop the old offset/size values except for the original
305 # ones, so we are only left with the constraints.
Alper Nebi Yasak00c68f12022-03-27 18:31:46 +0300306 if image.allow_repack and allow_resize:
Simon Glass274bd0e2019-07-20 12:24:13 -0600307 image.ResetForPack()
308
309
310def ReplaceOneEntry(image, entry, data, do_compress, allow_resize):
311 """Handle replacing a single entry an an image
312
313 Args:
314 image: Image to update
315 entry: Entry to write
316 data: Data to replace with
317 do_compress: True to compress the data if needed, False if data is
318 already compressed so should be used as is
319 allow_resize: True to allow entries to change size (this does a re-pack
320 of the entries), False to raise an exception
321 """
322 if not entry.WriteData(data, do_compress):
323 if not image.allow_repack:
324 entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
325 if not allow_resize:
326 entry.Raise('Entry data size does not match, but resize is disabled')
327
328
329def AfterReplace(image, allow_resize, write_map):
330 """Handle write out an image after replacing entries in it
331
332 Args:
333 image: Image to write
334 allow_resize: True to allow entries to change size (this does a re-pack
335 of the entries), False to raise an exception
336 write_map: True to write a map file
337 """
Simon Glass011f1b32022-01-29 14:14:15 -0700338 tout.info('Processing image')
Simon Glass274bd0e2019-07-20 12:24:13 -0600339 ProcessImage(image, update_fdt=True, write_map=write_map,
340 get_contents=False, allow_resize=allow_resize)
341
342
343def WriteEntryToImage(image, entry, data, do_compress=True, allow_resize=True,
344 write_map=False):
345 BeforeReplace(image, allow_resize)
Simon Glass011f1b32022-01-29 14:14:15 -0700346 tout.info('Writing data to %s' % entry.GetPath())
Simon Glass274bd0e2019-07-20 12:24:13 -0600347 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
348 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
349
350
Simon Glassd48f94e2019-07-20 12:24:12 -0600351def WriteEntry(image_fname, entry_path, data, do_compress=True,
352 allow_resize=True, write_map=False):
Simon Glass3971c952019-07-20 12:24:11 -0600353 """Replace an entry in an image
354
355 This replaces the data in a particular entry in an image. This size of the
356 new data must match the size of the old data unless allow_resize is True.
357
358 Args:
359 image_fname: Image filename to process
360 entry_path: Path to entry to extract
361 data: Data to replace with
Simon Glassd48f94e2019-07-20 12:24:12 -0600362 do_compress: True to compress the data if needed, False if data is
Simon Glass3971c952019-07-20 12:24:11 -0600363 already compressed so should be used as is
364 allow_resize: True to allow entries to change size (this does a re-pack
365 of the entries), False to raise an exception
Simon Glassd48f94e2019-07-20 12:24:12 -0600366 write_map: True to write a map file
Simon Glass3971c952019-07-20 12:24:11 -0600367
368 Returns:
369 Image object that was updated
370 """
Simon Glass011f1b32022-01-29 14:14:15 -0700371 tout.info("Write entry '%s', file '%s'" % (entry_path, image_fname))
Simon Glass3971c952019-07-20 12:24:11 -0600372 image = Image.FromFile(image_fname)
373 entry = image.FindEntryPath(entry_path)
Simon Glass274bd0e2019-07-20 12:24:13 -0600374 WriteEntryToImage(image, entry, data, do_compress=do_compress,
375 allow_resize=allow_resize, write_map=write_map)
Simon Glass3971c952019-07-20 12:24:11 -0600376
Simon Glass3971c952019-07-20 12:24:11 -0600377 return image
378
Simon Glass30033c22019-07-20 12:24:15 -0600379
380def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
381 do_compress=True, allow_resize=True, write_map=False):
382 """Replace the data from one or more entries from input files
383
384 Args:
385 image_fname: Image filename to process
Jan Kiszka8ea44432021-11-11 08:13:30 +0100386 input_fname: Single input filename to use if replacing one file, None
Simon Glass30033c22019-07-20 12:24:15 -0600387 otherwise
388 indir: Input directory to use (for any number of files), else None
Jan Kiszka8ea44432021-11-11 08:13:30 +0100389 entry_paths: List of entry paths to replace
Simon Glass30033c22019-07-20 12:24:15 -0600390 do_compress: True if the input data is uncompressed and may need to be
391 compressed if the entry requires it, False if the data is already
392 compressed.
393 write_map: True to write a map file
394
395 Returns:
396 List of EntryInfo records that were written
397 """
Jan Kiszkaafc8f292021-11-11 08:14:18 +0100398 image_fname = os.path.abspath(image_fname)
Simon Glass30033c22019-07-20 12:24:15 -0600399 image = Image.FromFile(image_fname)
400
401 # Replace an entry from a single file, as a special case
402 if input_fname:
403 if not entry_paths:
404 raise ValueError('Must specify an entry path to read with -f')
405 if len(entry_paths) != 1:
406 raise ValueError('Must specify exactly one entry path to write with -f')
407 entry = image.FindEntryPath(entry_paths[0])
Simon Glass80025522022-01-29 14:14:04 -0700408 data = tools.read_file(input_fname)
Simon Glass011f1b32022-01-29 14:14:15 -0700409 tout.notice("Read %#x bytes from file '%s'" % (len(data), input_fname))
Simon Glass30033c22019-07-20 12:24:15 -0600410 WriteEntryToImage(image, entry, data, do_compress=do_compress,
411 allow_resize=allow_resize, write_map=write_map)
412 return
413
414 # Otherwise we will input from a path given by the entry path of each entry.
415 # This means that files must appear in subdirectories if they are part of
416 # a sub-section.
417 einfos = image.GetListEntries(entry_paths)[0]
Simon Glass011f1b32022-01-29 14:14:15 -0700418 tout.notice("Replacing %d matching entries in image '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600419 (len(einfos), image_fname))
420
421 BeforeReplace(image, allow_resize)
422
423 for einfo in einfos:
424 entry = einfo.entry
425 if entry.GetEntries():
Simon Glass011f1b32022-01-29 14:14:15 -0700426 tout.info("Skipping section entry '%s'" % entry.GetPath())
Simon Glass30033c22019-07-20 12:24:15 -0600427 continue
428
429 path = entry.GetPath()[1:]
430 fname = os.path.join(indir, path)
431
432 if os.path.exists(fname):
Simon Glass011f1b32022-01-29 14:14:15 -0700433 tout.notice("Write entry '%s' from file '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600434 (entry.GetPath(), fname))
Simon Glass80025522022-01-29 14:14:04 -0700435 data = tools.read_file(fname)
Simon Glass30033c22019-07-20 12:24:15 -0600436 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
437 else:
Simon Glass011f1b32022-01-29 14:14:15 -0700438 tout.warning("Skipping entry '%s' from missing file '%s'" %
Simon Glass30033c22019-07-20 12:24:15 -0600439 (entry.GetPath(), fname))
440
441 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
442 return image
443
444
Simon Glass55ab0b62021-03-18 20:25:06 +1300445def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt, use_expanded):
Simon Glassd3151ff2019-07-20 12:23:27 -0600446 """Prepare the images to be processed and select the device tree
447
448 This function:
449 - reads in the device tree
450 - finds and scans the binman node to create all entries
451 - selects which images to build
452 - Updates the device tress with placeholder properties for offset,
453 image-pos, etc.
454
455 Args:
456 dtb_fname: Filename of the device tree file to use (.dts or .dtb)
457 selected_images: List of images to output, or None for all
458 update_fdt: True to update the FDT wth entry offsets, etc.
Simon Glass55ab0b62021-03-18 20:25:06 +1300459 use_expanded: True to use expanded versions of entries, if available.
460 So if 'u-boot' is called for, we use 'u-boot-expanded' instead. This
461 is needed if update_fdt is True (although tests may disable it)
Simon Glass31ee50f2020-09-01 05:13:55 -0600462
463 Returns:
464 OrderedDict of images:
465 key: Image name (str)
466 value: Image object
Simon Glassd3151ff2019-07-20 12:23:27 -0600467 """
468 # Import these here in case libfdt.py is not available, in which case
469 # the above help option still works.
Simon Glassc585dd42020-04-17 18:09:03 -0600470 from dtoc import fdt
471 from dtoc import fdt_util
Simon Glassd3151ff2019-07-20 12:23:27 -0600472 global images
473
474 # Get the device tree ready by compiling it and copying the compiled
475 # output into a file in our output directly. Then scan it for use
476 # in binman.
477 dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
Simon Glass80025522022-01-29 14:14:04 -0700478 fname = tools.get_output_filename('u-boot.dtb.out')
479 tools.write_file(fname, tools.read_file(dtb_fname))
Simon Glassd3151ff2019-07-20 12:23:27 -0600480 dtb = fdt.FdtScan(fname)
481
482 node = _FindBinmanNode(dtb)
483 if not node:
484 raise ValueError("Device tree '%s' does not have a 'binman' "
485 "node" % dtb_fname)
486
Simon Glass55ab0b62021-03-18 20:25:06 +1300487 images = _ReadImageDesc(node, use_expanded)
Simon Glassd3151ff2019-07-20 12:23:27 -0600488
489 if select_images:
490 skip = []
491 new_images = OrderedDict()
492 for name, image in images.items():
493 if name in select_images:
494 new_images[name] = image
495 else:
496 skip.append(name)
497 images = new_images
Simon Glass011f1b32022-01-29 14:14:15 -0700498 tout.notice('Skipping images: %s' % ', '.join(skip))
Simon Glassd3151ff2019-07-20 12:23:27 -0600499
500 state.Prepare(images, dtb)
501
502 # Prepare the device tree by making sure that any missing
503 # properties are added (e.g. 'pos' and 'size'). The values of these
504 # may not be correct yet, but we add placeholders so that the
505 # size of the device tree is correct. Later, in
506 # SetCalculatedProperties() we will insert the correct values
507 # without changing the device-tree size, thus ensuring that our
508 # entry offsets remain the same.
509 for image in images.values():
Simon Glass4eae9252022-01-09 20:13:50 -0700510 image.CollectBintools()
Simon Glassf86ddad2022-03-05 20:19:00 -0700511 image.gen_entries()
Simon Glassd3151ff2019-07-20 12:23:27 -0600512 if update_fdt:
Simon Glassacd6c6e2020-10-26 17:40:17 -0600513 image.AddMissingProperties(True)
Simon Glassd3151ff2019-07-20 12:23:27 -0600514 image.ProcessFdt(dtb)
515
Simon Glass5a300602019-07-20 12:23:29 -0600516 for dtb_item in state.GetAllFdts():
Simon Glassd3151ff2019-07-20 12:23:27 -0600517 dtb_item.Sync(auto_resize=True)
518 dtb_item.Pack()
519 dtb_item.Flush()
520 return images
521
522
Simon Glassf8a54bc2019-07-20 12:23:56 -0600523def ProcessImage(image, update_fdt, write_map, get_contents=True,
Heiko Thiery6d451362022-01-06 11:49:41 +0100524 allow_resize=True, allow_missing=False,
525 allow_fake_blobs=False):
Simon Glassb766c5e52019-07-20 12:23:24 -0600526 """Perform all steps for this image, including checking and # writing it.
527
528 This means that errors found with a later image will be reported after
529 earlier images are already completed and written, but that does not seem
530 important.
531
532 Args:
533 image: Image to process
534 update_fdt: True to update the FDT wth entry offsets, etc.
535 write_map: True to write a map file
Simon Glass072959a2019-07-20 12:23:50 -0600536 get_contents: True to get the image contents from files, etc., False if
537 the contents is already present
Simon Glassf8a54bc2019-07-20 12:23:56 -0600538 allow_resize: True to allow entries to change size (this does a re-pack
539 of the entries), False to raise an exception
Simon Glass5d94cc62020-07-09 18:39:38 -0600540 allow_missing: Allow blob_ext objects to be missing
Heiko Thiery6d451362022-01-06 11:49:41 +0100541 allow_fake_blobs: Allow blob_ext objects to be faked with dummy files
Simon Glassa003cd32020-07-09 18:39:40 -0600542
543 Returns:
Heiko Thiery6d451362022-01-06 11:49:41 +0100544 True if one or more external blobs are missing or faked,
545 False if all are present
Simon Glassb766c5e52019-07-20 12:23:24 -0600546 """
Simon Glass072959a2019-07-20 12:23:50 -0600547 if get_contents:
Simon Glass5d94cc62020-07-09 18:39:38 -0600548 image.SetAllowMissing(allow_missing)
Heiko Thiery6d451362022-01-06 11:49:41 +0100549 image.SetAllowFakeBlob(allow_fake_blobs)
Simon Glass072959a2019-07-20 12:23:50 -0600550 image.GetEntryContents()
Simon Glassb766c5e52019-07-20 12:23:24 -0600551 image.GetEntryOffsets()
552
553 # We need to pack the entries to figure out where everything
554 # should be placed. This sets the offset/size of each entry.
555 # However, after packing we call ProcessEntryContents() which
556 # may result in an entry changing size. In that case we need to
557 # do another pass. Since the device tree often contains the
558 # final offset/size information we try to make space for this in
559 # AddMissingProperties() above. However, if the device is
560 # compressed we cannot know this compressed size in advance,
561 # since changing an offset from 0x100 to 0x104 (for example) can
562 # alter the compressed size of the device tree. So we need a
563 # third pass for this.
Simon Glass37fdd142019-07-20 12:24:06 -0600564 passes = 5
Simon Glassb766c5e52019-07-20 12:23:24 -0600565 for pack_pass in range(passes):
566 try:
567 image.PackEntries()
Simon Glassb766c5e52019-07-20 12:23:24 -0600568 except Exception as e:
569 if write_map:
570 fname = image.WriteMap()
571 print("Wrote map file '%s' to show errors" % fname)
572 raise
573 image.SetImagePos()
574 if update_fdt:
575 image.SetCalculatedProperties()
Simon Glass5a300602019-07-20 12:23:29 -0600576 for dtb_item in state.GetAllFdts():
Simon Glassb766c5e52019-07-20 12:23:24 -0600577 dtb_item.Sync()
Simon Glassf8a54bc2019-07-20 12:23:56 -0600578 dtb_item.Flush()
Simon Glasse5943412019-08-24 07:23:12 -0600579 image.WriteSymbols()
Simon Glassb766c5e52019-07-20 12:23:24 -0600580 sizes_ok = image.ProcessEntryContents()
581 if sizes_ok:
582 break
583 image.ResetForPack()
Simon Glass011f1b32022-01-29 14:14:15 -0700584 tout.info('Pack completed after %d pass(es)' % (pack_pass + 1))
Simon Glassb766c5e52019-07-20 12:23:24 -0600585 if not sizes_ok:
Simon Glass9d8ee322019-07-20 12:23:58 -0600586 image.Raise('Entries changed size after packing (tried %s passes)' %
Simon Glassb766c5e52019-07-20 12:23:24 -0600587 passes)
588
Simon Glassb766c5e52019-07-20 12:23:24 -0600589 image.BuildImage()
590 if write_map:
591 image.WriteMap()
Simon Glassa003cd32020-07-09 18:39:40 -0600592 missing_list = []
593 image.CheckMissing(missing_list)
594 if missing_list:
Simon Glass011f1b32022-01-29 14:14:15 -0700595 tout.warning("Image '%s' is missing external blobs and is non-functional: %s" %
Simon Glassa003cd32020-07-09 18:39:40 -0600596 (image.name, ' '.join([e.name for e in missing_list])))
Simon Glassa820af72020-09-06 10:39:09 -0600597 _ShowHelpForMissingBlobs(missing_list)
Heiko Thiery6d451362022-01-06 11:49:41 +0100598 faked_list = []
599 image.CheckFakedBlobs(faked_list)
600 if faked_list:
Simon Glass011f1b32022-01-29 14:14:15 -0700601 tout.warning(
Simon Glassf9f34032022-01-09 20:13:45 -0700602 "Image '%s' has faked external blobs and is non-functional: %s" %
603 (image.name, ' '.join([os.path.basename(e.GetDefaultFilename())
604 for e in faked_list])))
Simon Glass66152ce2022-01-09 20:14:09 -0700605 missing_bintool_list = []
606 image.check_missing_bintools(missing_bintool_list)
607 if missing_bintool_list:
Simon Glass011f1b32022-01-29 14:14:15 -0700608 tout.warning(
Simon Glass66152ce2022-01-09 20:14:09 -0700609 "Image '%s' has missing bintools and is non-functional: %s" %
610 (image.name, ' '.join([os.path.basename(bintool.name)
611 for bintool in missing_bintool_list])))
612 return any([missing_list, faked_list, missing_bintool_list])
Simon Glassb766c5e52019-07-20 12:23:24 -0600613
614
Simon Glassf46732a2019-07-08 14:25:29 -0600615def Binman(args):
Simon Glass2574ef62016-11-25 20:15:51 -0700616 """The main control code for binman
617
618 This assumes that help and test options have already been dealt with. It
619 deals with the core task of building images.
620
621 Args:
Simon Glassf46732a2019-07-08 14:25:29 -0600622 args: Command line arguments Namespace object
Simon Glass2574ef62016-11-25 20:15:51 -0700623 """
Simon Glassb9ba4e02019-08-24 07:22:44 -0600624 global Image
625 global state
626
Simon Glassf46732a2019-07-08 14:25:29 -0600627 if args.full_help:
Simon Glass80025522022-01-29 14:14:04 -0700628 tools.print_full_help(
Paul Barker25ecd972021-09-08 12:38:01 +0100629 os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'README.rst')
630 )
Simon Glass2574ef62016-11-25 20:15:51 -0700631 return 0
632
Simon Glassb9ba4e02019-08-24 07:22:44 -0600633 # Put these here so that we can import this module without libfdt
Simon Glass90cd6f02020-08-05 13:27:47 -0600634 from binman.image import Image
Simon Glassc585dd42020-04-17 18:09:03 -0600635 from binman import state
Simon Glassb9ba4e02019-08-24 07:22:44 -0600636
Simon Glass4eae9252022-01-09 20:13:50 -0700637 if args.cmd in ['ls', 'extract', 'replace', 'tool']:
Simon Glass9b7f5002019-07-20 12:23:53 -0600638 try:
Simon Glass011f1b32022-01-29 14:14:15 -0700639 tout.init(args.verbosity)
Simon Glass80025522022-01-29 14:14:04 -0700640 tools.prepare_output_dir(None)
Simon Glassdf08cbb2019-09-15 18:10:36 -0600641 if args.cmd == 'ls':
642 ListEntries(args.image, args.paths)
Simon Glassb2fd11d2019-07-08 14:25:48 -0600643
Simon Glassdf08cbb2019-09-15 18:10:36 -0600644 if args.cmd == 'extract':
645 ExtractEntries(args.image, args.filename, args.outdir, args.paths,
Simon Glass637958f2021-11-23 21:09:50 -0700646 not args.uncompressed, args.format)
Simon Glass980a2842019-07-08 14:25:52 -0600647
Simon Glassdf08cbb2019-09-15 18:10:36 -0600648 if args.cmd == 'replace':
649 ReplaceEntries(args.image, args.filename, args.indir, args.paths,
650 do_compress=not args.compressed,
651 allow_resize=not args.fix_size, write_map=args.map)
Simon Glass4eae9252022-01-09 20:13:50 -0700652
653 if args.cmd == 'tool':
Simon Glass80025522022-01-29 14:14:04 -0700654 tools.set_tool_paths(args.toolpath)
Simon Glass4eae9252022-01-09 20:13:50 -0700655 if args.list:
656 bintool.Bintool.list_all()
657 elif args.fetch:
658 if not args.bintools:
659 raise ValueError(
660 "Please specify bintools to fetch or 'all' or 'missing'")
661 bintool.Bintool.fetch_tools(bintool.FETCH_ANY,
662 args.bintools)
663 else:
664 raise ValueError("Invalid arguments to 'tool' subcommand")
Simon Glassdf08cbb2019-09-15 18:10:36 -0600665 except:
666 raise
Simon Glass30033c22019-07-20 12:24:15 -0600667 finally:
Simon Glass80025522022-01-29 14:14:04 -0700668 tools.finalise_output_dir()
Simon Glass30033c22019-07-20 12:24:15 -0600669 return 0
670
Simon Glassadfb8492021-11-03 21:09:18 -0600671 elf_params = None
672 if args.update_fdt_in_elf:
673 elf_params = args.update_fdt_in_elf.split(',')
674 if len(elf_params) != 4:
675 raise ValueError('Invalid args %s to --update-fdt-in-elf: expected infile,outfile,begin_sym,end_sym' %
676 elf_params)
677
Simon Glass2574ef62016-11-25 20:15:51 -0700678 # Try to figure out which device tree contains our image description
Simon Glassf46732a2019-07-08 14:25:29 -0600679 if args.dt:
680 dtb_fname = args.dt
Simon Glass2574ef62016-11-25 20:15:51 -0700681 else:
Simon Glassf46732a2019-07-08 14:25:29 -0600682 board = args.board
Simon Glass2574ef62016-11-25 20:15:51 -0700683 if not board:
684 raise ValueError('Must provide a board to process (use -b <board>)')
Simon Glassf46732a2019-07-08 14:25:29 -0600685 board_pathname = os.path.join(args.build_dir, board)
Simon Glass2574ef62016-11-25 20:15:51 -0700686 dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
Simon Glassf46732a2019-07-08 14:25:29 -0600687 if not args.indir:
688 args.indir = ['.']
689 args.indir.append(board_pathname)
Simon Glass2574ef62016-11-25 20:15:51 -0700690
691 try:
Simon Glass011f1b32022-01-29 14:14:15 -0700692 tout.init(args.verbosity)
Simon Glassf46732a2019-07-08 14:25:29 -0600693 elf.debug = args.debug
694 cbfs_util.VERBOSE = args.verbosity > 2
695 state.use_fake_dtb = args.fake_dtb
Simon Glass55ab0b62021-03-18 20:25:06 +1300696
697 # Normally we replace the 'u-boot' etype with 'u-boot-expanded', etc.
698 # When running tests this can be disabled using this flag. When not
699 # updating the FDT in image, it is not needed by binman, but we use it
700 # for consistency, so that the images look the same to U-Boot at
701 # runtime.
702 use_expanded = not args.no_expanded
Simon Glass2574ef62016-11-25 20:15:51 -0700703 try:
Simon Glass80025522022-01-29 14:14:04 -0700704 tools.set_input_dirs(args.indir)
705 tools.prepare_output_dir(args.outdir, args.preserve)
706 tools.set_tool_paths(args.toolpath)
Simon Glassf46732a2019-07-08 14:25:29 -0600707 state.SetEntryArgs(args.entry_arg)
Simon Glass76f496d2021-07-06 10:36:37 -0600708 state.SetThreads(args.threads)
Simon Glass92307732018-07-06 10:27:40 -0600709
Simon Glassd3151ff2019-07-20 12:23:27 -0600710 images = PrepareImagesAndDtbs(dtb_fname, args.image,
Simon Glass55ab0b62021-03-18 20:25:06 +1300711 args.update_fdt, use_expanded)
Heiko Thiery6d451362022-01-06 11:49:41 +0100712
Simon Glass76f496d2021-07-06 10:36:37 -0600713 if args.test_section_timeout:
714 # Set the first image to timeout, used in testThreadTimeout()
715 images[list(images.keys())[0]].test_section_timeout = True
Heiko Thiery6d451362022-01-06 11:49:41 +0100716 invalid = False
Simon Glass66152ce2022-01-09 20:14:09 -0700717 bintool.Bintool.set_missing_list(
718 args.force_missing_bintools.split(',') if
719 args.force_missing_bintools else None)
Simon Glass2574ef62016-11-25 20:15:51 -0700720 for image in images.values():
Heiko Thiery6d451362022-01-06 11:49:41 +0100721 invalid |= ProcessImage(image, args.update_fdt, args.map,
722 allow_missing=args.allow_missing,
723 allow_fake_blobs=args.fake_ext_blobs)
Simon Glassbdb40312018-09-14 04:57:20 -0600724
725 # Write the updated FDTs to our output files
Simon Glass5a300602019-07-20 12:23:29 -0600726 for dtb_item in state.GetAllFdts():
Simon Glass80025522022-01-29 14:14:04 -0700727 tools.write_file(dtb_item._fname, dtb_item.GetContents())
Simon Glassbdb40312018-09-14 04:57:20 -0600728
Simon Glassadfb8492021-11-03 21:09:18 -0600729 if elf_params:
730 data = state.GetFdtForEtype('u-boot-dtb').GetContents()
731 elf.UpdateFile(*elf_params, data)
732
Heiko Thiery6d451362022-01-06 11:49:41 +0100733 if invalid:
Simon Glass011f1b32022-01-29 14:14:15 -0700734 tout.warning("\nSome images are invalid")
Simon Glass748a1d42021-07-06 10:36:41 -0600735
736 # Use this to debug the time take to pack the image
737 #state.TimingShow()
Simon Glass2574ef62016-11-25 20:15:51 -0700738 finally:
Simon Glass80025522022-01-29 14:14:04 -0700739 tools.finalise_output_dir()
Simon Glass2574ef62016-11-25 20:15:51 -0700740 finally:
Simon Glass011f1b32022-01-29 14:14:15 -0700741 tout.uninit()
Simon Glass2574ef62016-11-25 20:15:51 -0700742
743 return 0