blob: e6722c94593976da70725260cbc660458236ce5a [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
Simon Glass2ca84682019-05-14 15:53:37 -06008from __future__ import print_function
9
Simon Glassbf7fd502016-11-25 20:15:51 -070010from collections import OrderedDict
11import os
12import sys
13import tools
14
Simon Glassac62fba2019-07-08 13:18:53 -060015import cbfs_util
Simon Glassbf7fd502016-11-25 20:15:51 -070016import command
Simon Glass7fe91732017-11-13 18:55:00 -070017import elf
Simon Glassbf7fd502016-11-25 20:15:51 -070018from image import Image
Simon Glassc55a50f2018-09-14 04:57:19 -060019import state
Simon Glassbf7fd502016-11-25 20:15:51 -070020import tout
21
22# List of images we plan to create
23# Make this global so that it can be referenced from tests
24images = OrderedDict()
25
26def _ReadImageDesc(binman_node):
27 """Read the image descriptions from the /binman node
28
29 This normally produces a single Image object called 'image'. But if
30 multiple images are present, they will all be returned.
31
32 Args:
33 binman_node: Node object of the /binman node
34 Returns:
35 OrderedDict of Image objects, each of which describes an image
36 """
37 images = OrderedDict()
38 if 'multiple-images' in binman_node.props:
39 for node in binman_node.subnodes:
40 images[node.name] = Image(node.name, node)
41 else:
42 images['image'] = Image('image', binman_node)
43 return images
44
Simon Glassec3f3782017-05-27 07:38:29 -060045def _FindBinmanNode(dtb):
Simon Glassbf7fd502016-11-25 20:15:51 -070046 """Find the 'binman' node in the device tree
47
48 Args:
Simon Glassec3f3782017-05-27 07:38:29 -060049 dtb: Fdt object to scan
Simon Glassbf7fd502016-11-25 20:15:51 -070050 Returns:
51 Node object of /binman node, or None if not found
52 """
Simon Glassec3f3782017-05-27 07:38:29 -060053 for node in dtb.GetRoot().subnodes:
Simon Glassbf7fd502016-11-25 20:15:51 -070054 if node.name == 'binman':
55 return node
56 return None
57
Simon Glassc55a50f2018-09-14 04:57:19 -060058def WriteEntryDocs(modules, test_missing=None):
59 """Write out documentation for all entries
Simon Glassecab8972018-07-06 10:27:40 -060060
61 Args:
Simon Glassc55a50f2018-09-14 04:57:19 -060062 modules: List of Module objects to get docs for
63 test_missing: Used for testing only, to force an entry's documeentation
64 to show as missing even if it is present. Should be set to None in
65 normal use.
Simon Glassecab8972018-07-06 10:27:40 -060066 """
Simon Glassfd8d1f72018-07-17 13:25:36 -060067 from entry import Entry
68 Entry.WriteDocs(modules, test_missing)
69
Simon Glass61f564d2019-07-08 14:25:48 -060070
71def ListEntries(image_fname, entry_paths):
72 """List the entries in an image
73
74 This decodes the supplied image and displays a table of entries from that
75 image, preceded by a header.
76
77 Args:
78 image_fname: Image filename to process
79 entry_paths: List of wildcarded paths (e.g. ['*dtb*', 'u-boot*',
80 'section/u-boot'])
81 """
82 image = Image.FromFile(image_fname)
83
84 entries, lines, widths = image.GetListEntries(entry_paths)
85
86 num_columns = len(widths)
87 for linenum, line in enumerate(lines):
88 if linenum == 1:
89 # Print header line
90 print('-' * (sum(widths) + num_columns * 2))
91 out = ''
92 for i, item in enumerate(line):
93 width = -widths[i]
94 if item.startswith('>'):
95 width = -width
96 item = item[1:]
97 txt = '%*s ' % (width, item)
98 out += txt
99 print(out.rstrip())
100
Simon Glassf667e452019-07-08 14:25:50 -0600101
102def ReadEntry(image_fname, entry_path, decomp=True):
103 """Extract an entry from an image
104
105 This extracts the data from a particular entry in an image
106
107 Args:
108 image_fname: Image filename to process
109 entry_path: Path to entry to extract
110 decomp: True to return uncompressed data, if the data is compress
111 False to return the raw data
112
113 Returns:
114 data extracted from the entry
115 """
116 image = Image.FromFile(image_fname)
117 entry = image.FindEntryPath(entry_path)
118 return entry.ReadData(decomp)
119
120
Simon Glass71ce0ba2019-07-08 14:25:52 -0600121def ExtractEntries(image_fname, output_fname, outdir, entry_paths,
122 decomp=True):
123 """Extract the data from one or more entries and write it to files
124
125 Args:
126 image_fname: Image filename to process
127 output_fname: Single output filename to use if extracting one file, None
128 otherwise
129 outdir: Output directory to use (for any number of files), else None
130 entry_paths: List of entry paths to extract
Simon Glass3ad804e2019-07-20 12:24:12 -0600131 decomp: True to decompress the entry data
Simon Glass71ce0ba2019-07-08 14:25:52 -0600132
133 Returns:
134 List of EntryInfo records that were written
135 """
136 image = Image.FromFile(image_fname)
137
138 # Output an entry to a single file, as a special case
139 if output_fname:
140 if not entry_paths:
Simon Glassbb5edc12019-07-20 12:24:14 -0600141 raise ValueError('Must specify an entry path to write with -f')
Simon Glass71ce0ba2019-07-08 14:25:52 -0600142 if len(entry_paths) != 1:
Simon Glassbb5edc12019-07-20 12:24:14 -0600143 raise ValueError('Must specify exactly one entry path to write with -f')
Simon Glass71ce0ba2019-07-08 14:25:52 -0600144 entry = image.FindEntryPath(entry_paths[0])
145 data = entry.ReadData(decomp)
146 tools.WriteFile(output_fname, data)
147 tout.Notice("Wrote %#x bytes to file '%s'" % (len(data), output_fname))
148 return
149
150 # Otherwise we will output to a path given by the entry path of each entry.
151 # This means that entries will appear in subdirectories if they are part of
152 # a sub-section.
153 einfos = image.GetListEntries(entry_paths)[0]
154 tout.Notice('%d entries match and will be written' % len(einfos))
155 for einfo in einfos:
156 entry = einfo.entry
157 data = entry.ReadData(decomp)
158 path = entry.GetPath()[1:]
159 fname = os.path.join(outdir, path)
160
161 # If this entry has children, create a directory for it and put its
162 # data in a file called 'root' in that directory
163 if entry.GetEntries():
164 if not os.path.exists(fname):
165 os.makedirs(fname)
166 fname = os.path.join(fname, 'root')
167 tout.Notice("Write entry '%s' to '%s'" % (entry.GetPath(), fname))
168 tools.WriteFile(fname, data)
169 return einfos
170
171
Simon Glassd7fa4e42019-07-20 12:24:13 -0600172def BeforeReplace(image, allow_resize):
173 """Handle getting an image ready for replacing entries in it
174
175 Args:
176 image: Image to prepare
177 """
178 state.PrepareFromLoadedData(image)
179 image.LoadData()
180
181 # If repacking, drop the old offset/size values except for the original
182 # ones, so we are only left with the constraints.
183 if allow_resize:
184 image.ResetForPack()
185
186
187def ReplaceOneEntry(image, entry, data, do_compress, allow_resize):
188 """Handle replacing a single entry an an image
189
190 Args:
191 image: Image to update
192 entry: Entry to write
193 data: Data to replace with
194 do_compress: True to compress the data if needed, False if data is
195 already compressed so should be used as is
196 allow_resize: True to allow entries to change size (this does a re-pack
197 of the entries), False to raise an exception
198 """
199 if not entry.WriteData(data, do_compress):
200 if not image.allow_repack:
201 entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
202 if not allow_resize:
203 entry.Raise('Entry data size does not match, but resize is disabled')
204
205
206def AfterReplace(image, allow_resize, write_map):
207 """Handle write out an image after replacing entries in it
208
209 Args:
210 image: Image to write
211 allow_resize: True to allow entries to change size (this does a re-pack
212 of the entries), False to raise an exception
213 write_map: True to write a map file
214 """
215 tout.Info('Processing image')
216 ProcessImage(image, update_fdt=True, write_map=write_map,
217 get_contents=False, allow_resize=allow_resize)
218
219
220def WriteEntryToImage(image, entry, data, do_compress=True, allow_resize=True,
221 write_map=False):
222 BeforeReplace(image, allow_resize)
223 tout.Info('Writing data to %s' % entry.GetPath())
224 ReplaceOneEntry(image, entry, data, do_compress, allow_resize)
225 AfterReplace(image, allow_resize=allow_resize, write_map=write_map)
226
227
Simon Glass3ad804e2019-07-20 12:24:12 -0600228def WriteEntry(image_fname, entry_path, data, do_compress=True,
229 allow_resize=True, write_map=False):
Simon Glass22a76b72019-07-20 12:24:11 -0600230 """Replace an entry in an image
231
232 This replaces the data in a particular entry in an image. This size of the
233 new data must match the size of the old data unless allow_resize is True.
234
235 Args:
236 image_fname: Image filename to process
237 entry_path: Path to entry to extract
238 data: Data to replace with
Simon Glass3ad804e2019-07-20 12:24:12 -0600239 do_compress: True to compress the data if needed, False if data is
Simon Glass22a76b72019-07-20 12:24:11 -0600240 already compressed so should be used as is
241 allow_resize: True to allow entries to change size (this does a re-pack
242 of the entries), False to raise an exception
Simon Glass3ad804e2019-07-20 12:24:12 -0600243 write_map: True to write a map file
Simon Glass22a76b72019-07-20 12:24:11 -0600244
245 Returns:
246 Image object that was updated
247 """
Simon Glassd7fa4e42019-07-20 12:24:13 -0600248 tout.Info("Write entry '%s', file '%s'" % (entry_path, image_fname))
Simon Glass22a76b72019-07-20 12:24:11 -0600249 image = Image.FromFile(image_fname)
250 entry = image.FindEntryPath(entry_path)
Simon Glassd7fa4e42019-07-20 12:24:13 -0600251 WriteEntryToImage(image, entry, data, do_compress=do_compress,
252 allow_resize=allow_resize, write_map=write_map)
Simon Glass22a76b72019-07-20 12:24:11 -0600253
Simon Glass22a76b72019-07-20 12:24:11 -0600254 return image
255
Simon Glassa8573c42019-07-20 12:23:27 -0600256def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt):
257 """Prepare the images to be processed and select the device tree
258
259 This function:
260 - reads in the device tree
261 - finds and scans the binman node to create all entries
262 - selects which images to build
263 - Updates the device tress with placeholder properties for offset,
264 image-pos, etc.
265
266 Args:
267 dtb_fname: Filename of the device tree file to use (.dts or .dtb)
268 selected_images: List of images to output, or None for all
269 update_fdt: True to update the FDT wth entry offsets, etc.
270 """
271 # Import these here in case libfdt.py is not available, in which case
272 # the above help option still works.
273 import fdt
274 import fdt_util
275 global images
276
277 # Get the device tree ready by compiling it and copying the compiled
278 # output into a file in our output directly. Then scan it for use
279 # in binman.
280 dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
281 fname = tools.GetOutputFilename('u-boot.dtb.out')
282 tools.WriteFile(fname, tools.ReadFile(dtb_fname))
283 dtb = fdt.FdtScan(fname)
284
285 node = _FindBinmanNode(dtb)
286 if not node:
287 raise ValueError("Device tree '%s' does not have a 'binman' "
288 "node" % dtb_fname)
289
290 images = _ReadImageDesc(node)
291
292 if select_images:
293 skip = []
294 new_images = OrderedDict()
295 for name, image in images.items():
296 if name in select_images:
297 new_images[name] = image
298 else:
299 skip.append(name)
300 images = new_images
301 tout.Notice('Skipping images: %s' % ', '.join(skip))
302
303 state.Prepare(images, dtb)
304
305 # Prepare the device tree by making sure that any missing
306 # properties are added (e.g. 'pos' and 'size'). The values of these
307 # may not be correct yet, but we add placeholders so that the
308 # size of the device tree is correct. Later, in
309 # SetCalculatedProperties() we will insert the correct values
310 # without changing the device-tree size, thus ensuring that our
311 # entry offsets remain the same.
312 for image in images.values():
313 image.ExpandEntries()
314 if update_fdt:
315 image.AddMissingProperties()
316 image.ProcessFdt(dtb)
317
Simon Glass4bdd1152019-07-20 12:23:29 -0600318 for dtb_item in state.GetAllFdts():
Simon Glassa8573c42019-07-20 12:23:27 -0600319 dtb_item.Sync(auto_resize=True)
320 dtb_item.Pack()
321 dtb_item.Flush()
322 return images
323
324
Simon Glass51014aa2019-07-20 12:23:56 -0600325def ProcessImage(image, update_fdt, write_map, get_contents=True,
326 allow_resize=True):
Simon Glassb88e81c2019-07-20 12:23:24 -0600327 """Perform all steps for this image, including checking and # writing it.
328
329 This means that errors found with a later image will be reported after
330 earlier images are already completed and written, but that does not seem
331 important.
332
333 Args:
334 image: Image to process
335 update_fdt: True to update the FDT wth entry offsets, etc.
336 write_map: True to write a map file
Simon Glass10f9d002019-07-20 12:23:50 -0600337 get_contents: True to get the image contents from files, etc., False if
338 the contents is already present
Simon Glass51014aa2019-07-20 12:23:56 -0600339 allow_resize: True to allow entries to change size (this does a re-pack
340 of the entries), False to raise an exception
Simon Glassb88e81c2019-07-20 12:23:24 -0600341 """
Simon Glass10f9d002019-07-20 12:23:50 -0600342 if get_contents:
343 image.GetEntryContents()
Simon Glassb88e81c2019-07-20 12:23:24 -0600344 image.GetEntryOffsets()
345
346 # We need to pack the entries to figure out where everything
347 # should be placed. This sets the offset/size of each entry.
348 # However, after packing we call ProcessEntryContents() which
349 # may result in an entry changing size. In that case we need to
350 # do another pass. Since the device tree often contains the
351 # final offset/size information we try to make space for this in
352 # AddMissingProperties() above. However, if the device is
353 # compressed we cannot know this compressed size in advance,
354 # since changing an offset from 0x100 to 0x104 (for example) can
355 # alter the compressed size of the device tree. So we need a
356 # third pass for this.
Simon Glasseb0f4a42019-07-20 12:24:06 -0600357 passes = 5
Simon Glassb88e81c2019-07-20 12:23:24 -0600358 for pack_pass in range(passes):
359 try:
360 image.PackEntries()
361 image.CheckSize()
362 image.CheckEntries()
363 except Exception as e:
364 if write_map:
365 fname = image.WriteMap()
366 print("Wrote map file '%s' to show errors" % fname)
367 raise
368 image.SetImagePos()
369 if update_fdt:
370 image.SetCalculatedProperties()
Simon Glass4bdd1152019-07-20 12:23:29 -0600371 for dtb_item in state.GetAllFdts():
Simon Glassb88e81c2019-07-20 12:23:24 -0600372 dtb_item.Sync()
Simon Glass51014aa2019-07-20 12:23:56 -0600373 dtb_item.Flush()
Simon Glassb88e81c2019-07-20 12:23:24 -0600374 sizes_ok = image.ProcessEntryContents()
375 if sizes_ok:
376 break
377 image.ResetForPack()
378 if not sizes_ok:
Simon Glass61ec04f2019-07-20 12:23:58 -0600379 image.Raise('Entries changed size after packing (tried %s passes)' %
Simon Glassb88e81c2019-07-20 12:23:24 -0600380 passes)
381
382 image.WriteSymbols()
383 image.BuildImage()
384 if write_map:
385 image.WriteMap()
386
387
Simon Glass53cd5d92019-07-08 14:25:29 -0600388def Binman(args):
Simon Glassbf7fd502016-11-25 20:15:51 -0700389 """The main control code for binman
390
391 This assumes that help and test options have already been dealt with. It
392 deals with the core task of building images.
393
394 Args:
Simon Glass53cd5d92019-07-08 14:25:29 -0600395 args: Command line arguments Namespace object
Simon Glassbf7fd502016-11-25 20:15:51 -0700396 """
Simon Glass53cd5d92019-07-08 14:25:29 -0600397 if args.full_help:
Simon Glassbf7fd502016-11-25 20:15:51 -0700398 pager = os.getenv('PAGER')
399 if not pager:
400 pager = 'more'
401 fname = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
402 'README')
403 command.Run(pager, fname)
404 return 0
405
Simon Glass61f564d2019-07-08 14:25:48 -0600406 if args.cmd == 'ls':
Simon Glass96b6c502019-07-20 12:23:53 -0600407 try:
408 tools.PrepareOutputDir(None)
409 ListEntries(args.image, args.paths)
410 finally:
411 tools.FinaliseOutputDir()
Simon Glass61f564d2019-07-08 14:25:48 -0600412 return 0
413
Simon Glass71ce0ba2019-07-08 14:25:52 -0600414 if args.cmd == 'extract':
415 try:
416 tools.PrepareOutputDir(None)
417 ExtractEntries(args.image, args.filename, args.outdir, args.paths,
418 not args.uncompressed)
419 finally:
420 tools.FinaliseOutputDir()
421 return 0
422
Simon Glassbf7fd502016-11-25 20:15:51 -0700423 # Try to figure out which device tree contains our image description
Simon Glass53cd5d92019-07-08 14:25:29 -0600424 if args.dt:
425 dtb_fname = args.dt
Simon Glassbf7fd502016-11-25 20:15:51 -0700426 else:
Simon Glass53cd5d92019-07-08 14:25:29 -0600427 board = args.board
Simon Glassbf7fd502016-11-25 20:15:51 -0700428 if not board:
429 raise ValueError('Must provide a board to process (use -b <board>)')
Simon Glass53cd5d92019-07-08 14:25:29 -0600430 board_pathname = os.path.join(args.build_dir, board)
Simon Glassbf7fd502016-11-25 20:15:51 -0700431 dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
Simon Glass53cd5d92019-07-08 14:25:29 -0600432 if not args.indir:
433 args.indir = ['.']
434 args.indir.append(board_pathname)
Simon Glassbf7fd502016-11-25 20:15:51 -0700435
436 try:
Simon Glass53cd5d92019-07-08 14:25:29 -0600437 tout.Init(args.verbosity)
438 elf.debug = args.debug
439 cbfs_util.VERBOSE = args.verbosity > 2
440 state.use_fake_dtb = args.fake_dtb
Simon Glassbf7fd502016-11-25 20:15:51 -0700441 try:
Simon Glass53cd5d92019-07-08 14:25:29 -0600442 tools.SetInputDirs(args.indir)
443 tools.PrepareOutputDir(args.outdir, args.preserve)
444 tools.SetToolPaths(args.toolpath)
445 state.SetEntryArgs(args.entry_arg)
Simon Glassecab8972018-07-06 10:27:40 -0600446
Simon Glassa8573c42019-07-20 12:23:27 -0600447 images = PrepareImagesAndDtbs(dtb_fname, args.image,
448 args.update_fdt)
Simon Glassbf7fd502016-11-25 20:15:51 -0700449 for image in images.values():
Simon Glassb88e81c2019-07-20 12:23:24 -0600450 ProcessImage(image, args.update_fdt, args.map)
Simon Glass2a72cc72018-09-14 04:57:20 -0600451
452 # Write the updated FDTs to our output files
Simon Glass4bdd1152019-07-20 12:23:29 -0600453 for dtb_item in state.GetAllFdts():
Simon Glass2a72cc72018-09-14 04:57:20 -0600454 tools.WriteFile(dtb_item._fname, dtb_item.GetContents())
455
Simon Glassbf7fd502016-11-25 20:15:51 -0700456 finally:
457 tools.FinaliseOutputDir()
458 finally:
459 tout.Uninit()
460
461 return 0