blob: 8eea864d45bcf2b7d70cd2d1978cf6de7953bafd [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glassbf7fd502016-11-25 20:15:51 -07002# Copyright (c) 2016 Google, Inc
3# Written by Simon Glass <sjg@chromium.org>
4#
Simon Glassbf7fd502016-11-25 20:15:51 -07005# Creates binary images from input files controlled by a description
6#
7
8from collections import OrderedDict
Simon Glass87d43322020-08-05 13:27:46 -06009import glob
Simon Glassbf7fd502016-11-25 20:15:51 -070010import os
Simon Glass9fbfaba2020-08-29 11:36:14 -060011import pkg_resources
Simon Glassb2381432020-09-06 10:39:09 -060012import re
Simon Glass9fbfaba2020-08-29 11:36:14 -060013
Simon Glassbf7fd502016-11-25 20:15:51 -070014import sys
Simon Glassbf776672020-04-17 18:09:04 -060015from patman import tools
Simon Glassbf7fd502016-11-25 20:15:51 -070016
Simon Glass386c63c2022-01-09 20:13:50 -070017from binman import bintool
Simon Glass16287932020-04-17 18:09:03 -060018from binman import cbfs_util
Simon Glassbf776672020-04-17 18:09:04 -060019from patman import command
Simon Glass7960a0a2022-08-07 09:46:46 -060020from binman import elf
21from binman import entry
Simon Glassbf776672020-04-17 18:09:04 -060022from patman import tout
Simon Glassbf7fd502016-11-25 20:15:51 -070023
Simon Glass8d2ef3e2022-02-11 13:23:21 -070024# These are imported if needed since they import libfdt
25state = None
26Image = None
27
Simon Glassbf7fd502016-11-25 20:15:51 -070028# List of images we plan to create
29# Make this global so that it can be referenced from tests
30images = OrderedDict()
31
Simon Glassb2381432020-09-06 10:39:09 -060032# Help text for each type of missing blob, dict:
33# key: Value of the entry's 'missing-msg' or entry name
34# value: Text for the help
35missing_blob_help = {}
36
Simon Glass0b6023e2021-03-18 20:25:06 +130037def _ReadImageDesc(binman_node, use_expanded):
Simon Glassbf7fd502016-11-25 20:15:51 -070038 """Read the image descriptions from the /binman node
39
40 This normally produces a single Image object called 'image'. But if
41 multiple images are present, they will all be returned.
42
43 Args:
44 binman_node: Node object of the /binman node
Simon Glass0b6023e2021-03-18 20:25:06 +130045 use_expanded: True if the FDT will be updated with the entry information
Simon Glassbf7fd502016-11-25 20:15:51 -070046 Returns:
47 OrderedDict of Image objects, each of which describes an image
48 """
Simon Glass8d2ef3e2022-02-11 13:23:21 -070049 # For Image()
50 # pylint: disable=E1102
Simon Glassbf7fd502016-11-25 20:15:51 -070051 images = OrderedDict()
52 if 'multiple-images' in binman_node.props:
53 for node in binman_node.subnodes:
Simon Glass0b6023e2021-03-18 20:25:06 +130054 images[node.name] = Image(node.name, node,
55 use_expanded=use_expanded)
Simon Glassbf7fd502016-11-25 20:15:51 -070056 else:
Simon Glass0b6023e2021-03-18 20:25:06 +130057 images['image'] = Image('image', binman_node, use_expanded=use_expanded)
Simon Glassbf7fd502016-11-25 20:15:51 -070058 return images
59
Simon Glassec3f3782017-05-27 07:38:29 -060060def _FindBinmanNode(dtb):
Simon Glassbf7fd502016-11-25 20:15:51 -070061 """Find the 'binman' node in the device tree
62
63 Args:
Simon Glassec3f3782017-05-27 07:38:29 -060064 dtb: Fdt object to scan
Simon Glassbf7fd502016-11-25 20:15:51 -070065 Returns:
66 Node object of /binman node, or None if not found
67 """
Simon Glassec3f3782017-05-27 07:38:29 -060068 for node in dtb.GetRoot().subnodes:
Simon Glassbf7fd502016-11-25 20:15:51 -070069 if node.name == 'binman':
70 return node
71 return None
72
Simon Glassb2381432020-09-06 10:39:09 -060073def _ReadMissingBlobHelp():
74 """Read the missing-blob-help file
75
76 This file containins help messages explaining what to do when external blobs
77 are missing.
78
79 Returns:
80 Dict:
81 key: Message tag (str)
82 value: Message text (str)
83 """
84
85 def _FinishTag(tag, msg, result):
86 if tag:
87 result[tag] = msg.rstrip()
88 tag = None
89 msg = ''
90 return tag, msg
91
92 my_data = pkg_resources.resource_string(__name__, 'missing-blob-help')
93 re_tag = re.compile('^([-a-z0-9]+):$')
94 result = {}
95 tag = None
96 msg = ''
97 for line in my_data.decode('utf-8').splitlines():
98 if not line.startswith('#'):
99 m_tag = re_tag.match(line)
100 if m_tag:
101 _, msg = _FinishTag(tag, msg, result)
102 tag = m_tag.group(1)
103 elif tag:
104 msg += line + '\n'
105 _FinishTag(tag, msg, result)
106 return result
107
108def _ShowBlobHelp(path, text):
Simon Glassf3385a52022-01-29 14:14:15 -0700109 tout.warning('\n%s:' % path)
Simon Glassb2381432020-09-06 10:39:09 -0600110 for line in text.splitlines():
Simon Glassf3385a52022-01-29 14:14:15 -0700111 tout.warning(' %s' % line)
Simon Glassb2381432020-09-06 10:39:09 -0600112
113def _ShowHelpForMissingBlobs(missing_list):
114 """Show help for each missing blob to help the user take action
115
116 Args:
117 missing_list: List of Entry objects to show help for
118 """
119 global missing_blob_help
120
121 if not missing_blob_help:
122 missing_blob_help = _ReadMissingBlobHelp()
123
124 for entry in missing_list:
125 tags = entry.GetHelpTags()
126
127 # Show the first match help message
128 for tag in tags:
129 if tag in missing_blob_help:
130 _ShowBlobHelp(entry._node.path, missing_blob_help[tag])
131 break
132
Simon Glass87d43322020-08-05 13:27:46 -0600133def GetEntryModules(include_testing=True):
134 """Get a set of entry class implementations
135
136 Returns:
137 Set of paths to entry class filenames
138 """
Simon Glass9fbfaba2020-08-29 11:36:14 -0600139 glob_list = pkg_resources.resource_listdir(__name__, 'etype')
140 glob_list = [fname for fname in glob_list if fname.endswith('.py')]
Simon Glass87d43322020-08-05 13:27:46 -0600141 return set([os.path.splitext(os.path.basename(item))[0]
142 for item in glob_list
143 if include_testing or '_testing' not in item])
144
Simon Glassc55a50f2018-09-14 04:57:19 -0600145def WriteEntryDocs(modules, test_missing=None):
146 """Write out documentation for all entries
Simon Glassecab8972018-07-06 10:27:40 -0600147
148 Args:
Simon Glassc55a50f2018-09-14 04:57:19 -0600149 modules: List of Module objects to get docs for
Simon Glassbc570642022-01-09 20:14:11 -0700150 test_missing: Used for testing only, to force an entry's documentation
Simon Glassc55a50f2018-09-14 04:57:19 -0600151 to show as missing even if it is present. Should be set to None in
152 normal use.
Simon Glassecab8972018-07-06 10:27:40 -0600153 """
Simon Glass16287932020-04-17 18:09:03 -0600154 from binman.entry import Entry
Simon Glassfd8d1f72018-07-17 13:25:36 -0600155 Entry.WriteDocs(modules, test_missing)
156
Simon Glass61f564d2019-07-08 14:25:48 -0600157
Simon Glassbc570642022-01-09 20:14:11 -0700158def write_bintool_docs(modules, test_missing=None):
159 """Write out documentation for all bintools
160
161 Args:
162 modules: List of Module objects to get docs for
163 test_missing: Used for testing only, to force an entry's documentation
164 to show as missing even if it is present. Should be set to None in
165 normal use.
166 """
167 bintool.Bintool.WriteDocs(modules, test_missing)
168
169
Simon Glass61f564d2019-07-08 14:25:48 -0600170def ListEntries(image_fname, entry_paths):
171 """List the entries in an image
172
173 This decodes the supplied image and displays a table of entries from that
174 image, preceded by a header.
175
176 Args:
177 image_fname: Image filename to process
178 entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*',
179 'section/u-boot'])
180 """
181 image = Image.FromFile(image_fname)
182
183 entries, lines, widths = image.GetListEntries(entry_paths)
184
185 num_columns = len(widths)
186 for linenum, line in enumerate(lines):
187 if linenum == 1:
188 # Print header line
189 print('-' * (sum(widths) + num_columns * 2))
190 out = ''
191 for i, item in enumerate(line):
192 width = -widths[i]
193 if item.startswith('>'):
194 width = -width
195 item = item[1:]
196 txt = '%*s ' % (width, item)
197 out += txt
198 print(out.rstrip())
199
Simon Glassf667e452019-07-08 14:25:50 -0600200
201def ReadEntry(image_fname, entry_path, decomp=True):
202 """Extract an entry from an image
203
204 This extracts the data from a particular entry in an image
205
206 Args:
207 image_fname: Image filename to process
208 entry_path: Path to entry to extract
209 decomp: True to return uncompressed data, if the data is compress
210 False to return the raw data
211
212 Returns:
213 data extracted from the entry
214 """
Simon Glass8dbb7442019-08-24 07:22:44 -0600215 global Image
Simon Glass07237982020-08-05 13:27:47 -0600216 from binman.image import Image
Simon Glass8dbb7442019-08-24 07:22:44 -0600217
Simon Glassf667e452019-07-08 14:25:50 -0600218 image = Image.FromFile(image_fname)
219 entry = image.FindEntryPath(entry_path)
220 return entry.ReadData(decomp)
221
222
Simon Glass943bf782021-11-23 21:09:50 -0700223def ShowAltFormats(image):
224 """Show alternative formats available for entries in the image
225
226 This shows a list of formats available.
227
228 Args:
229 image (Image): Image to check
230 """
231 alt_formats = {}
232 image.CheckAltFormats(alt_formats)
233 print('%-10s %-20s %s' % ('Flag (-F)', 'Entry type', 'Description'))
234 for name, val in alt_formats.items():
235 entry, helptext = val
236 print('%-10s %-20s %s' % (name, entry.etype, helptext))
237
238
Simon Glass71ce0ba2019-07-08 14:25:52 -0600239def ExtractEntries(image_fname, output_fname, outdir, entry_paths,
Simon Glass943bf782021-11-23 21:09:50 -0700240 decomp=True, alt_format=None):
Simon Glass71ce0ba2019-07-08 14:25:52 -0600241 """Extract the data from one or more entries and write it to files
242
243 Args:
244 image_fname: Image filename to process
245 output_fname: Single output filename to use if extracting one file, None
246 otherwise
247 outdir: Output directory to use (for any number of files), else None
248 entry_paths: List of entry paths to extract
Simon Glass3ad804e2019-07-20 12:24:12 -0600249 decomp: True to decompress the entry data
Simon Glass71ce0ba2019-07-08 14:25:52 -0600250
251 Returns:
252 List of EntryInfo records that were written
253 """
254 image = Image.FromFile(image_fname)
255
Simon Glass943bf782021-11-23 21:09:50 -0700256 if alt_format == 'list':
257 ShowAltFormats(image)
258 return
259
Simon Glass71ce0ba2019-07-08 14:25:52 -0600260 # Output an entry to a single file, as a special case
261 if output_fname:
262 if not entry_paths:
Simon Glassbb5edc12019-07-20 12:24:14 -0600263 raise ValueError('Must specify an entry path to write with -f')
Simon Glass71ce0ba2019-07-08 14:25:52 -0600264 if len(entry_paths) != 1:
Simon Glassbb5edc12019-07-20 12:24:14 -0600265 raise ValueError('Must specify exactly one entry path to write with -f')
Simon Glass71ce0ba2019-07-08 14:25:52 -0600266 entry = image.FindEntryPath(entry_paths[0])
Simon Glass943bf782021-11-23 21:09:50 -0700267 data = entry.ReadData(decomp, alt_format)
Simon Glassc1aa66e2022-01-29 14:14:04 -0700268 tools.write_file(output_fname, data)
Simon Glassf3385a52022-01-29 14:14:15 -0700269 tout.notice("Wrote %#x bytes to file '%s'" % (len(data), output_fname))
Simon Glass71ce0ba2019-07-08 14:25:52 -0600270 return
271
272 # Otherwise we will output to a path given by the entry path of each entry.
273 # This means that entries will appear in subdirectories if they are part of
274 # a sub-section.
275 einfos = image.GetListEntries(entry_paths)[0]
Simon Glassf3385a52022-01-29 14:14:15 -0700276 tout.notice('%d entries match and will be written' % len(einfos))
Simon Glass71ce0ba2019-07-08 14:25:52 -0600277 for einfo in einfos:
278 entry = einfo.entry
Simon Glass943bf782021-11-23 21:09:50 -0700279 data = entry.ReadData(decomp, alt_format)
Simon Glass71ce0ba2019-07-08 14:25:52 -0600280 path = entry.GetPath()[1:]
281 fname = os.path.join(outdir, path)
282
283 # If this entry has children, create a directory for it and put its
284 # data in a file called 'root' in that directory
285 if entry.GetEntries():
Simon Glass862ddf92021-03-18 20:24:51 +1300286 if fname and not os.path.exists(fname):
Simon Glass71ce0ba2019-07-08 14:25:52 -0600287 os.makedirs(fname)
288 fname = os.path.join(fname, 'root')
Simon Glassf3385a52022-01-29 14:14:15 -0700289 tout.notice("Write entry '%s' size %x to '%s'" %
Simon Glass5b378e42021-01-06 21:35:13 -0700290 (entry.GetPath(), len(data), fname))
Simon Glassc1aa66e2022-01-29 14:14:04 -0700291 tools.write_file(fname, data)
Simon Glass71ce0ba2019-07-08 14:25:52 -0600292 return einfos
293
294
Simon Glassd7fa4e42019-07-20 12:24:13 -0600295def BeforeReplace(image, allow_resize):
296 """Handle getting an image ready for replacing entries in it
297
298 Args:
299 image: Image to prepare
300 """
301 state.PrepareFromLoadedData(image)
302 image.LoadData()
Alper Nebi Yasak8ee4ec92022-03-27 18:31:45 +0300303 image.CollectBintools()
Simon Glassd7fa4e42019-07-20 12:24:13 -0600304
305 # If repacking, drop the old offset/size values except for the original
306 # ones, so we are only left with the constraints.
Alper Nebi Yasake2ce4fb2022-03-27 18:31:46 +0300307 if image.allow_repack and allow_resize:
Simon Glassd7fa4e42019-07-20 12:24:13 -0600308 image.ResetForPack()
309
310
311def ReplaceOneEntry(image, entry, data, do_compress, allow_resize):
312 """Handle replacing a single entry an an image
313
314 Args:
315 image: Image to update
316 entry: Entry to write
317 data: Data to replace with
318 do_compress: True to compress the data if needed, False if data is
319 already compressed so should be used as is
320 allow_resize: True to allow entries to change size (this does a re-pack
321 of the entries), False to raise an exception
322 """
323 if not entry.WriteData(data, do_compress):
324 if not image.allow_repack:
325 entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
326 if not allow_resize:
327 entry.Raise('Entry data size does not match, but resize is disabled')
328
329
330def AfterReplace(image, allow_resize, write_map):
331 """Handle write out an image after replacing entries in it
332
333 Args:
334 image: Image to write
335 allow_resize: True to allow entries to change size (this does a re-pack
336 of the entries), False to raise an exception
337 write_map: True to write a map file
338 """
Simon Glassf3385a52022-01-29 14:14:15 -0700339 tout.info('Processing image')
Simon Glassd7fa4e42019-07-20 12:24:13 -0600340 ProcessImage(image, update_fdt=True, write_map=write_map,
341 get_contents=False, allow_resize=allow_resize)
342
343
344def WriteEntryToImage(image, entry, data, do_compress=True, allow_resize=True,
345 write_map=False):
346 BeforeReplace(image, allow_resize)
Simon Glassf3385a52022-01-29 14:14:15 -0700347 tout.info('Writing data to %s' % entry.GetPath())
Simon Glassd7fa4e42019-07-20 12:24:13 -0600348 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
349 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
350
351
Simon Glass3ad804e2019-07-20 12:24:12 -0600352def WriteEntry(image_fname, entry_path, data, do_compress=True,
353 allow_resize=True, write_map=False):
Simon Glass22a76b72019-07-20 12:24:11 -0600354 """Replace an entry in an image
355
356 This replaces the data in a particular entry in an image. This size of the
357 new data must match the size of the old data unless allow_resize is True.
358
359 Args:
360 image_fname: Image filename to process
361 entry_path: Path to entry to extract
362 data: Data to replace with
Simon Glass3ad804e2019-07-20 12:24:12 -0600363 do_compress: True to compress the data if needed, False if data is
Simon Glass22a76b72019-07-20 12:24:11 -0600364 already compressed so should be used as is
365 allow_resize: True to allow entries to change size (this does a re-pack
366 of the entries), False to raise an exception
Simon Glass3ad804e2019-07-20 12:24:12 -0600367 write_map: True to write a map file
Simon Glass22a76b72019-07-20 12:24:11 -0600368
369 Returns:
370 Image object that was updated
371 """
Simon Glassf3385a52022-01-29 14:14:15 -0700372 tout.info("Write entry '%s', file '%s'" % (entry_path, image_fname))
Simon Glass22a76b72019-07-20 12:24:11 -0600373 image = Image.FromFile(image_fname)
374 entry = image.FindEntryPath(entry_path)
Simon Glassd7fa4e42019-07-20 12:24:13 -0600375 WriteEntryToImage(image, entry, data, do_compress=do_compress,
376 allow_resize=allow_resize, write_map=write_map)
Simon Glass22a76b72019-07-20 12:24:11 -0600377
Simon Glass22a76b72019-07-20 12:24:11 -0600378 return image
379
Simon Glassa6cb9952019-07-20 12:24:15 -0600380
381def ReplaceEntries(image_fname, input_fname, indir, entry_paths,
382 do_compress=True, allow_resize=True, write_map=False):
383 """Replace the data from one or more entries from input files
384
385 Args:
386 image_fname: Image filename to process
Jan Kiszka89cc0522021-11-11 08:13:30 +0100387 input_fname: Single input filename to use if replacing one file, None
Simon Glassa6cb9952019-07-20 12:24:15 -0600388 otherwise
389 indir: Input directory to use (for any number of files), else None
Jan Kiszka89cc0522021-11-11 08:13:30 +0100390 entry_paths: List of entry paths to replace
Simon Glassa6cb9952019-07-20 12:24:15 -0600391 do_compress: True if the input data is uncompressed and may need to be
392 compressed if the entry requires it, False if the data is already
393 compressed.
394 write_map: True to write a map file
395
396 Returns:
397 List of EntryInfo records that were written
398 """
Jan Kiszkac700f102021-11-11 08:14:18 +0100399 image_fname = os.path.abspath(image_fname)
Simon Glassa6cb9952019-07-20 12:24:15 -0600400 image = Image.FromFile(image_fname)
401
402 # Replace an entry from a single file, as a special case
403 if input_fname:
404 if not entry_paths:
405 raise ValueError('Must specify an entry path to read with -f')
406 if len(entry_paths) != 1:
407 raise ValueError('Must specify exactly one entry path to write with -f')
408 entry = image.FindEntryPath(entry_paths[0])
Simon Glassc1aa66e2022-01-29 14:14:04 -0700409 data = tools.read_file(input_fname)
Simon Glassf3385a52022-01-29 14:14:15 -0700410 tout.notice("Read %#x bytes from file '%s'" % (len(data), input_fname))
Simon Glassa6cb9952019-07-20 12:24:15 -0600411 WriteEntryToImage(image, entry, data, do_compress=do_compress,
412 allow_resize=allow_resize, write_map=write_map)
413 return
414
415 # Otherwise we will input from a path given by the entry path of each entry.
416 # This means that files must appear in subdirectories if they are part of
417 # a sub-section.
418 einfos = image.GetListEntries(entry_paths)[0]
Simon Glassf3385a52022-01-29 14:14:15 -0700419 tout.notice("Replacing %d matching entries in image '%s'" %
Simon Glassa6cb9952019-07-20 12:24:15 -0600420 (len(einfos), image_fname))
421
422 BeforeReplace(image, allow_resize)
423
424 for einfo in einfos:
425 entry = einfo.entry
426 if entry.GetEntries():
Simon Glassf3385a52022-01-29 14:14:15 -0700427 tout.info("Skipping section entry '%s'" % entry.GetPath())
Simon Glassa6cb9952019-07-20 12:24:15 -0600428 continue
429
430 path = entry.GetPath()[1:]
431 fname = os.path.join(indir, path)
432
433 if os.path.exists(fname):
Simon Glassf3385a52022-01-29 14:14:15 -0700434 tout.notice("Write entry '%s' from file '%s'" %
Simon Glassa6cb9952019-07-20 12:24:15 -0600435 (entry.GetPath(), fname))
Simon Glassc1aa66e2022-01-29 14:14:04 -0700436 data = tools.read_file(fname)
Simon Glassa6cb9952019-07-20 12:24:15 -0600437 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
438 else:
Simon Glassf3385a52022-01-29 14:14:15 -0700439 tout.warning("Skipping entry '%s' from missing file '%s'" %
Simon Glassa6cb9952019-07-20 12:24:15 -0600440 (entry.GetPath(), fname))
441
442 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
443 return image
444
445
Simon Glass0b6023e2021-03-18 20:25:06 +1300446def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt, use_expanded):
Simon Glassa8573c42019-07-20 12:23:27 -0600447 """Prepare the images to be processed and select the device tree
448
449 This function:
450 - reads in the device tree
451 - finds and scans the binman node to create all entries
452 - selects which images to build
453 - Updates the device tress with placeholder properties for offset,
454 image-pos, etc.
455
456 Args:
457 dtb_fname: Filename of the device tree file to use (.dts or .dtb)
458 selected_images: List of images to output, or None for all
459 update_fdt: True to update the FDT wth entry offsets, etc.
Simon Glass0b6023e2021-03-18 20:25:06 +1300460 use_expanded: True to use expanded versions of entries, if available.
461 So if 'u-boot' is called for, we use 'u-boot-expanded' instead. This
462 is needed if update_fdt is True (although tests may disable it)
Simon Glasse9d336d2020-09-01 05:13:55 -0600463
464 Returns:
465 OrderedDict of images:
466 key: Image name (str)
467 value: Image object
Simon Glassa8573c42019-07-20 12:23:27 -0600468 """
469 # Import these here in case libfdt.py is not available, in which case
470 # the above help option still works.
Simon Glass16287932020-04-17 18:09:03 -0600471 from dtoc import fdt
472 from dtoc import fdt_util
Simon Glassa8573c42019-07-20 12:23:27 -0600473 global images
474
475 # Get the device tree ready by compiling it and copying the compiled
476 # output into a file in our output directly. Then scan it for use
477 # in binman.
478 dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
Simon Glassc1aa66e2022-01-29 14:14:04 -0700479 fname = tools.get_output_filename('u-boot.dtb.out')
480 tools.write_file(fname, tools.read_file(dtb_fname))
Simon Glassa8573c42019-07-20 12:23:27 -0600481 dtb = fdt.FdtScan(fname)
482
483 node = _FindBinmanNode(dtb)
484 if not node:
485 raise ValueError("Device tree '%s' does not have a 'binman' "
486 "node" % dtb_fname)
487
Simon Glass0b6023e2021-03-18 20:25:06 +1300488 images = _ReadImageDesc(node, use_expanded)
Simon Glassa8573c42019-07-20 12:23:27 -0600489
490 if select_images:
491 skip = []
492 new_images = OrderedDict()
493 for name, image in images.items():
494 if name in select_images:
495 new_images[name] = image
496 else:
497 skip.append(name)
498 images = new_images
Simon Glassf3385a52022-01-29 14:14:15 -0700499 tout.notice('Skipping images: %s' % ', '.join(skip))
Simon Glassa8573c42019-07-20 12:23:27 -0600500
501 state.Prepare(images, dtb)
502
503 # Prepare the device tree by making sure that any missing
504 # properties are added (e.g. 'pos' and 'size'). The values of these
505 # may not be correct yet, but we add placeholders so that the
506 # size of the device tree is correct. Later, in
507 # SetCalculatedProperties() we will insert the correct values
508 # without changing the device-tree size, thus ensuring that our
509 # entry offsets remain the same.
510 for image in images.values():
Simon Glass386c63c2022-01-09 20:13:50 -0700511 image.CollectBintools()
Simon Glassc9ee33a2022-03-05 20:19:00 -0700512 image.gen_entries()
Simon Glassa8573c42019-07-20 12:23:27 -0600513 if update_fdt:
Simon Glassa9fad072020-10-26 17:40:17 -0600514 image.AddMissingProperties(True)
Simon Glassa8573c42019-07-20 12:23:27 -0600515 image.ProcessFdt(dtb)
516
Simon Glass4bdd1152019-07-20 12:23:29 -0600517 for dtb_item in state.GetAllFdts():
Simon Glassa8573c42019-07-20 12:23:27 -0600518 dtb_item.Sync(auto_resize=True)
519 dtb_item.Pack()
520 dtb_item.Flush()
521 return images
522
523
Simon Glass51014aa2019-07-20 12:23:56 -0600524def ProcessImage(image, update_fdt, write_map, get_contents=True,
Heiko Thierya89c8f22022-01-06 11:49:41 +0100525 allow_resize=True, allow_missing=False,
526 allow_fake_blobs=False):
Simon Glassb88e81c2019-07-20 12:23:24 -0600527 """Perform all steps for this image, including checking and # writing it.
528
529 This means that errors found with a later image will be reported after
530 earlier images are already completed and written, but that does not seem
531 important.
532
533 Args:
534 image: Image to process
535 update_fdt: True to update the FDT wth entry offsets, etc.
536 write_map: True to write a map file
Simon Glass10f9d002019-07-20 12:23:50 -0600537 get_contents: True to get the image contents from files, etc., False if
538 the contents is already present
Simon Glass51014aa2019-07-20 12:23:56 -0600539 allow_resize: True to allow entries to change size (this does a re-pack
540 of the entries), False to raise an exception
Simon Glass4f9f1052020-07-09 18:39:38 -0600541 allow_missing: Allow blob_ext objects to be missing
Heiko Thierya89c8f22022-01-06 11:49:41 +0100542 allow_fake_blobs: Allow blob_ext objects to be faked with dummy files
Simon Glassb1cca952020-07-09 18:39:40 -0600543
544 Returns:
Heiko Thierya89c8f22022-01-06 11:49:41 +0100545 True if one or more external blobs are missing or faked,
546 False if all are present
Simon Glassb88e81c2019-07-20 12:23:24 -0600547 """
Simon Glass10f9d002019-07-20 12:23:50 -0600548 if get_contents:
Simon Glass4f9f1052020-07-09 18:39:38 -0600549 image.SetAllowMissing(allow_missing)
Heiko Thierya89c8f22022-01-06 11:49:41 +0100550 image.SetAllowFakeBlob(allow_fake_blobs)
Simon Glass10f9d002019-07-20 12:23:50 -0600551 image.GetEntryContents()
Simon Glassb88e81c2019-07-20 12:23:24 -0600552 image.GetEntryOffsets()
553
554 # We need to pack the entries to figure out where everything
555 # should be placed. This sets the offset/size of each entry.
556 # However, after packing we call ProcessEntryContents() which
557 # may result in an entry changing size. In that case we need to
558 # do another pass. Since the device tree often contains the
559 # final offset/size information we try to make space for this in
560 # AddMissingProperties() above. However, if the device is
561 # compressed we cannot know this compressed size in advance,
562 # since changing an offset from 0x100 to 0x104 (for example) can
563 # alter the compressed size of the device tree. So we need a
564 # third pass for this.
Simon Glasseb0f4a42019-07-20 12:24:06 -0600565 passes = 5
Simon Glassb88e81c2019-07-20 12:23:24 -0600566 for pack_pass in range(passes):
567 try:
568 image.PackEntries()
Simon Glassb88e81c2019-07-20 12:23:24 -0600569 except Exception as e:
570 if write_map:
571 fname = image.WriteMap()
572 print("Wrote map file '%s' to show errors" % fname)
573 raise
574 image.SetImagePos()
575 if update_fdt:
576 image.SetCalculatedProperties()
Simon Glass4bdd1152019-07-20 12:23:29 -0600577 for dtb_item in state.GetAllFdts():
Simon Glassb88e81c2019-07-20 12:23:24 -0600578 dtb_item.Sync()
Simon Glass51014aa2019-07-20 12:23:56 -0600579 dtb_item.Flush()
Simon Glass261cbe02019-08-24 07:23:12 -0600580 image.WriteSymbols()
Simon Glassb88e81c2019-07-20 12:23:24 -0600581 sizes_ok = image.ProcessEntryContents()
582 if sizes_ok:
583 break
584 image.ResetForPack()
Simon Glassf3385a52022-01-29 14:14:15 -0700585 tout.info('Pack completed after %d pass(es)' % (pack_pass + 1))
Simon Glassb88e81c2019-07-20 12:23:24 -0600586 if not sizes_ok:
Simon Glass61ec04f2019-07-20 12:23:58 -0600587 image.Raise('Entries changed size after packing (tried %s passes)' %
Simon Glassb88e81c2019-07-20 12:23:24 -0600588 passes)
589
Simon Glassb88e81c2019-07-20 12:23:24 -0600590 image.BuildImage()
591 if write_map:
592 image.WriteMap()
Simon Glassb1cca952020-07-09 18:39:40 -0600593 missing_list = []
594 image.CheckMissing(missing_list)
595 if missing_list:
Simon Glassf3385a52022-01-29 14:14:15 -0700596 tout.warning("Image '%s' is missing external blobs and is non-functional: %s" %
Simon Glassb1cca952020-07-09 18:39:40 -0600597 (image.name, ' '.join([e.name for e in missing_list])))
Simon Glassb2381432020-09-06 10:39:09 -0600598 _ShowHelpForMissingBlobs(missing_list)
Heiko Thierya89c8f22022-01-06 11:49:41 +0100599 faked_list = []
600 image.CheckFakedBlobs(faked_list)
601 if faked_list:
Simon Glassf3385a52022-01-29 14:14:15 -0700602 tout.warning(
Simon Glass2cc8c1f2022-01-09 20:13:45 -0700603 "Image '%s' has faked external blobs and is non-functional: %s" %
604 (image.name, ' '.join([os.path.basename(e.GetDefaultFilename())
605 for e in faked_list])))
Simon Glass4f9ee832022-01-09 20:14:09 -0700606 missing_bintool_list = []
607 image.check_missing_bintools(missing_bintool_list)
608 if missing_bintool_list:
Simon Glassf3385a52022-01-29 14:14:15 -0700609 tout.warning(
Simon Glass4f9ee832022-01-09 20:14:09 -0700610 "Image '%s' has missing bintools and is non-functional: %s" %
611 (image.name, ' '.join([os.path.basename(bintool.name)
612 for bintool in missing_bintool_list])))
613 return any([missing_list, faked_list, missing_bintool_list])
Simon Glassb88e81c2019-07-20 12:23:24 -0600614
615
Simon Glass53cd5d92019-07-08 14:25:29 -0600616def Binman(args):
Simon Glassbf7fd502016-11-25 20:15:51 -0700617 """The main control code for binman
618
619 This assumes that help and test options have already been dealt with. It
620 deals with the core task of building images.
621
622 Args:
Simon Glass53cd5d92019-07-08 14:25:29 -0600623 args: Command line arguments Namespace object
Simon Glassbf7fd502016-11-25 20:15:51 -0700624 """
Simon Glass8dbb7442019-08-24 07:22:44 -0600625 global Image
626 global state
627
Simon Glass53cd5d92019-07-08 14:25:29 -0600628 if args.full_help:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700629 tools.print_full_help(
Paul Barker5fe50f92021-09-08 12:38:01 +0100630 os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])), 'README.rst')
631 )
Simon Glassbf7fd502016-11-25 20:15:51 -0700632 return 0
633
Simon Glass8dbb7442019-08-24 07:22:44 -0600634 # Put these here so that we can import this module without libfdt
Simon Glass07237982020-08-05 13:27:47 -0600635 from binman.image import Image
Simon Glass16287932020-04-17 18:09:03 -0600636 from binman import state
Simon Glass8dbb7442019-08-24 07:22:44 -0600637
Simon Glass386c63c2022-01-09 20:13:50 -0700638 if args.cmd in ['ls', 'extract', 'replace', 'tool']:
Simon Glass96b6c502019-07-20 12:23:53 -0600639 try:
Simon Glassf3385a52022-01-29 14:14:15 -0700640 tout.init(args.verbosity)
Simon Glassc1aa66e2022-01-29 14:14:04 -0700641 tools.prepare_output_dir(None)
Simon Glass7bc4f0f2019-09-15 18:10:36 -0600642 if args.cmd == 'ls':
643 ListEntries(args.image, args.paths)
Simon Glass61f564d2019-07-08 14:25:48 -0600644
Simon Glass7bc4f0f2019-09-15 18:10:36 -0600645 if args.cmd == 'extract':
646 ExtractEntries(args.image, args.filename, args.outdir, args.paths,
Simon Glass943bf782021-11-23 21:09:50 -0700647 not args.uncompressed, args.format)
Simon Glass71ce0ba2019-07-08 14:25:52 -0600648
Simon Glass7bc4f0f2019-09-15 18:10:36 -0600649 if args.cmd == 'replace':
650 ReplaceEntries(args.image, args.filename, args.indir, args.paths,
651 do_compress=not args.compressed,
652 allow_resize=not args.fix_size, write_map=args.map)
Simon Glass386c63c2022-01-09 20:13:50 -0700653
654 if args.cmd == 'tool':
Simon Glassc1aa66e2022-01-29 14:14:04 -0700655 tools.set_tool_paths(args.toolpath)
Simon Glass386c63c2022-01-09 20:13:50 -0700656 if args.list:
657 bintool.Bintool.list_all()
658 elif args.fetch:
659 if not args.bintools:
660 raise ValueError(
661 "Please specify bintools to fetch or 'all' or 'missing'")
662 bintool.Bintool.fetch_tools(bintool.FETCH_ANY,
663 args.bintools)
664 else:
665 raise ValueError("Invalid arguments to 'tool' subcommand")
Simon Glass7bc4f0f2019-09-15 18:10:36 -0600666 except:
667 raise
Simon Glassa6cb9952019-07-20 12:24:15 -0600668 finally:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700669 tools.finalise_output_dir()
Simon Glassa6cb9952019-07-20 12:24:15 -0600670 return 0
671
Simon Glass0427bed2021-11-03 21:09:18 -0600672 elf_params = None
673 if args.update_fdt_in_elf:
674 elf_params = args.update_fdt_in_elf.split(',')
675 if len(elf_params) != 4:
676 raise ValueError('Invalid args %s to --update-fdt-in-elf: expected infile,outfile,begin_sym,end_sym' %
677 elf_params)
678
Simon Glassbf7fd502016-11-25 20:15:51 -0700679 # Try to figure out which device tree contains our image description
Simon Glass53cd5d92019-07-08 14:25:29 -0600680 if args.dt:
681 dtb_fname = args.dt
Simon Glassbf7fd502016-11-25 20:15:51 -0700682 else:
Simon Glass53cd5d92019-07-08 14:25:29 -0600683 board = args.board
Simon Glassbf7fd502016-11-25 20:15:51 -0700684 if not board:
685 raise ValueError('Must provide a board to process (use -b <board>)')
Simon Glass53cd5d92019-07-08 14:25:29 -0600686 board_pathname = os.path.join(args.build_dir, board)
Simon Glassbf7fd502016-11-25 20:15:51 -0700687 dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
Simon Glass53cd5d92019-07-08 14:25:29 -0600688 if not args.indir:
689 args.indir = ['.']
690 args.indir.append(board_pathname)
Simon Glassbf7fd502016-11-25 20:15:51 -0700691
692 try:
Simon Glassf3385a52022-01-29 14:14:15 -0700693 tout.init(args.verbosity)
Simon Glass53cd5d92019-07-08 14:25:29 -0600694 elf.debug = args.debug
695 cbfs_util.VERBOSE = args.verbosity > 2
696 state.use_fake_dtb = args.fake_dtb
Simon Glass0b6023e2021-03-18 20:25:06 +1300697
698 # Normally we replace the 'u-boot' etype with 'u-boot-expanded', etc.
699 # When running tests this can be disabled using this flag. When not
700 # updating the FDT in image, it is not needed by binman, but we use it
701 # for consistency, so that the images look the same to U-Boot at
702 # runtime.
703 use_expanded = not args.no_expanded
Simon Glassbf7fd502016-11-25 20:15:51 -0700704 try:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700705 tools.set_input_dirs(args.indir)
706 tools.prepare_output_dir(args.outdir, args.preserve)
707 tools.set_tool_paths(args.toolpath)
Simon Glass53cd5d92019-07-08 14:25:29 -0600708 state.SetEntryArgs(args.entry_arg)
Simon Glassc69d19c2021-07-06 10:36:37 -0600709 state.SetThreads(args.threads)
Simon Glassecab8972018-07-06 10:27:40 -0600710
Simon Glassa8573c42019-07-20 12:23:27 -0600711 images = PrepareImagesAndDtbs(dtb_fname, args.image,
Simon Glass0b6023e2021-03-18 20:25:06 +1300712 args.update_fdt, use_expanded)
Heiko Thierya89c8f22022-01-06 11:49:41 +0100713
Simon Glassc69d19c2021-07-06 10:36:37 -0600714 if args.test_section_timeout:
715 # Set the first image to timeout, used in testThreadTimeout()
716 images[list(images.keys())[0]].test_section_timeout = True
Heiko Thierya89c8f22022-01-06 11:49:41 +0100717 invalid = False
Simon Glass4f9ee832022-01-09 20:14:09 -0700718 bintool.Bintool.set_missing_list(
719 args.force_missing_bintools.split(',') if
720 args.force_missing_bintools else None)
Simon Glass7960a0a2022-08-07 09:46:46 -0600721
722 # Create the directory here instead of Entry.check_fake_fname()
723 # since that is called from a threaded context so different threads
724 # may race to create the directory
725 if args.fake_ext_blobs:
726 entry.Entry.create_fake_dir()
727
Simon Glassbf7fd502016-11-25 20:15:51 -0700728 for image in images.values():
Heiko Thierya89c8f22022-01-06 11:49:41 +0100729 invalid |= ProcessImage(image, args.update_fdt, args.map,
730 allow_missing=args.allow_missing,
731 allow_fake_blobs=args.fake_ext_blobs)
Simon Glass2a72cc72018-09-14 04:57:20 -0600732
733 # Write the updated FDTs to our output files
Simon Glass4bdd1152019-07-20 12:23:29 -0600734 for dtb_item in state.GetAllFdts():
Simon Glassc1aa66e2022-01-29 14:14:04 -0700735 tools.write_file(dtb_item._fname, dtb_item.GetContents())
Simon Glass2a72cc72018-09-14 04:57:20 -0600736
Simon Glass0427bed2021-11-03 21:09:18 -0600737 if elf_params:
738 data = state.GetFdtForEtype('u-boot-dtb').GetContents()
739 elf.UpdateFile(*elf_params, data)
740
Heiko Thierya89c8f22022-01-06 11:49:41 +0100741 if invalid:
Simon Glassf3385a52022-01-29 14:14:15 -0700742 tout.warning("\nSome images are invalid")
Simon Glass03ebc202021-07-06 10:36:41 -0600743
744 # Use this to debug the time take to pack the image
745 #state.TimingShow()
Simon Glassbf7fd502016-11-25 20:15:51 -0700746 finally:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700747 tools.finalise_output_dir()
Simon Glassbf7fd502016-11-25 20:15:51 -0700748 finally:
Simon Glassf3385a52022-01-29 14:14:15 -0700749 tout.uninit()
Simon Glassbf7fd502016-11-25 20:15:51 -0700750
751 return 0