binman: Move control.WriteEntry further down the file
[oweals/u-boot.git] / tools / binman / control.py
1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2016 Google, Inc
3 # Written by Simon Glass <sjg@chromium.org>
4 #
5 # Creates binary images from input files controlled by a description
6 #
7
8 from __future__ import print_function
9
10 from collections import OrderedDict
11 import os
12 import sys
13 import tools
14
15 import cbfs_util
16 import command
17 import elf
18 from image import Image
19 import state
20 import tout
21
22 # List of images we plan to create
23 # Make this global so that it can be referenced from tests
24 images = OrderedDict()
25
26 def _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
45 def _FindBinmanNode(dtb):
46     """Find the 'binman' node in the device tree
47
48     Args:
49         dtb: Fdt object to scan
50     Returns:
51         Node object of /binman node, or None if not found
52     """
53     for node in dtb.GetRoot().subnodes:
54         if node.name == 'binman':
55             return node
56     return None
57
58 def WriteEntryDocs(modules, test_missing=None):
59     """Write out documentation for all entries
60
61     Args:
62         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.
66     """
67     from entry import Entry
68     Entry.WriteDocs(modules, test_missing)
69
70
71 def 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
101
102 def 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
121 def 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
131         decomp: True to compress the entry data
132
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:
141             raise ValueError('Must specify an entry path to write with -o')
142         if len(entry_paths) != 1:
143             raise ValueError('Must specify exactly one entry path to write with -o')
144         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
172 def WriteEntry(image_fname, entry_path, data, decomp=True, allow_resize=True):
173     """Replace an entry in an image
174
175     This replaces the data in a particular entry in an image. This size of the
176     new data must match the size of the old data unless allow_resize is True.
177
178     Args:
179         image_fname: Image filename to process
180         entry_path: Path to entry to extract
181         data: Data to replace with
182         decomp: True to compress the data if needed, False if data is
183             already compressed so should be used as is
184         allow_resize: True to allow entries to change size (this does a re-pack
185             of the entries), False to raise an exception
186
187     Returns:
188         Image object that was updated
189     """
190     tout.Info("WriteEntry '%s', file '%s'" % (entry_path, image_fname))
191     image = Image.FromFile(image_fname)
192     entry = image.FindEntryPath(entry_path)
193     state.PrepareFromLoadedData(image)
194     image.LoadData()
195
196     # If repacking, drop the old offset/size values except for the original
197     # ones, so we are only left with the constraints.
198     if allow_resize:
199         image.ResetForPack()
200     tout.Info('Writing data to %s' % entry.GetPath())
201     if not entry.WriteData(data, decomp):
202         if not image.allow_repack:
203             entry.Raise('Entry data size does not match, but allow-repack is not present for this image')
204         if not allow_resize:
205             entry.Raise('Entry data size does not match, but resize is disabled')
206     tout.Info('Processing image')
207     ProcessImage(image, update_fdt=True, write_map=False, get_contents=False,
208                  allow_resize=allow_resize)
209     tout.Info('WriteEntry done')
210     return image
211
212 def PrepareImagesAndDtbs(dtb_fname, select_images, update_fdt):
213     """Prepare the images to be processed and select the device tree
214
215     This function:
216     - reads in the device tree
217     - finds and scans the binman node to create all entries
218     - selects which images to build
219     - Updates the device tress with placeholder properties for offset,
220         image-pos, etc.
221
222     Args:
223         dtb_fname: Filename of the device tree file to use (.dts or .dtb)
224         selected_images: List of images to output, or None for all
225         update_fdt: True to update the FDT wth entry offsets, etc.
226     """
227     # Import these here in case libfdt.py is not available, in which case
228     # the above help option still works.
229     import fdt
230     import fdt_util
231     global images
232
233     # Get the device tree ready by compiling it and copying the compiled
234     # output into a file in our output directly. Then scan it for use
235     # in binman.
236     dtb_fname = fdt_util.EnsureCompiled(dtb_fname)
237     fname = tools.GetOutputFilename('u-boot.dtb.out')
238     tools.WriteFile(fname, tools.ReadFile(dtb_fname))
239     dtb = fdt.FdtScan(fname)
240
241     node = _FindBinmanNode(dtb)
242     if not node:
243         raise ValueError("Device tree '%s' does not have a 'binman' "
244                             "node" % dtb_fname)
245
246     images = _ReadImageDesc(node)
247
248     if select_images:
249         skip = []
250         new_images = OrderedDict()
251         for name, image in images.items():
252             if name in select_images:
253                 new_images[name] = image
254             else:
255                 skip.append(name)
256         images = new_images
257         tout.Notice('Skipping images: %s' % ', '.join(skip))
258
259     state.Prepare(images, dtb)
260
261     # Prepare the device tree by making sure that any missing
262     # properties are added (e.g. 'pos' and 'size'). The values of these
263     # may not be correct yet, but we add placeholders so that the
264     # size of the device tree is correct. Later, in
265     # SetCalculatedProperties() we will insert the correct values
266     # without changing the device-tree size, thus ensuring that our
267     # entry offsets remain the same.
268     for image in images.values():
269         image.ExpandEntries()
270         if update_fdt:
271             image.AddMissingProperties()
272         image.ProcessFdt(dtb)
273
274     for dtb_item in state.GetAllFdts():
275         dtb_item.Sync(auto_resize=True)
276         dtb_item.Pack()
277         dtb_item.Flush()
278     return images
279
280
281 def ProcessImage(image, update_fdt, write_map, get_contents=True,
282                  allow_resize=True):
283     """Perform all steps for this image, including checking and # writing it.
284
285     This means that errors found with a later image will be reported after
286     earlier images are already completed and written, but that does not seem
287     important.
288
289     Args:
290         image: Image to process
291         update_fdt: True to update the FDT wth entry offsets, etc.
292         write_map: True to write a map file
293         get_contents: True to get the image contents from files, etc., False if
294             the contents is already present
295         allow_resize: True to allow entries to change size (this does a re-pack
296             of the entries), False to raise an exception
297     """
298     if get_contents:
299         image.GetEntryContents()
300     image.GetEntryOffsets()
301
302     # We need to pack the entries to figure out where everything
303     # should be placed. This sets the offset/size of each entry.
304     # However, after packing we call ProcessEntryContents() which
305     # may result in an entry changing size. In that case we need to
306     # do another pass. Since the device tree often contains the
307     # final offset/size information we try to make space for this in
308     # AddMissingProperties() above. However, if the device is
309     # compressed we cannot know this compressed size in advance,
310     # since changing an offset from 0x100 to 0x104 (for example) can
311     # alter the compressed size of the device tree. So we need a
312     # third pass for this.
313     passes = 5
314     for pack_pass in range(passes):
315         try:
316             image.PackEntries()
317             image.CheckSize()
318             image.CheckEntries()
319         except Exception as e:
320             if write_map:
321                 fname = image.WriteMap()
322                 print("Wrote map file '%s' to show errors"  % fname)
323             raise
324         image.SetImagePos()
325         if update_fdt:
326             image.SetCalculatedProperties()
327             for dtb_item in state.GetAllFdts():
328                 dtb_item.Sync()
329                 dtb_item.Flush()
330         sizes_ok = image.ProcessEntryContents()
331         if sizes_ok:
332             break
333         image.ResetForPack()
334     if not sizes_ok:
335         image.Raise('Entries changed size after packing (tried %s passes)' %
336                     passes)
337
338     image.WriteSymbols()
339     image.BuildImage()
340     if write_map:
341         image.WriteMap()
342
343
344 def Binman(args):
345     """The main control code for binman
346
347     This assumes that help and test options have already been dealt with. It
348     deals with the core task of building images.
349
350     Args:
351         args: Command line arguments Namespace object
352     """
353     if args.full_help:
354         pager = os.getenv('PAGER')
355         if not pager:
356             pager = 'more'
357         fname = os.path.join(os.path.dirname(os.path.realpath(sys.argv[0])),
358                             'README')
359         command.Run(pager, fname)
360         return 0
361
362     if args.cmd == 'ls':
363         try:
364             tools.PrepareOutputDir(None)
365             ListEntries(args.image, args.paths)
366         finally:
367             tools.FinaliseOutputDir()
368         return 0
369
370     if args.cmd == 'extract':
371         try:
372             tools.PrepareOutputDir(None)
373             ExtractEntries(args.image, args.filename, args.outdir, args.paths,
374                            not args.uncompressed)
375         finally:
376             tools.FinaliseOutputDir()
377         return 0
378
379     # Try to figure out which device tree contains our image description
380     if args.dt:
381         dtb_fname = args.dt
382     else:
383         board = args.board
384         if not board:
385             raise ValueError('Must provide a board to process (use -b <board>)')
386         board_pathname = os.path.join(args.build_dir, board)
387         dtb_fname = os.path.join(board_pathname, 'u-boot.dtb')
388         if not args.indir:
389             args.indir = ['.']
390         args.indir.append(board_pathname)
391
392     try:
393         tout.Init(args.verbosity)
394         elf.debug = args.debug
395         cbfs_util.VERBOSE = args.verbosity > 2
396         state.use_fake_dtb = args.fake_dtb
397         try:
398             tools.SetInputDirs(args.indir)
399             tools.PrepareOutputDir(args.outdir, args.preserve)
400             tools.SetToolPaths(args.toolpath)
401             state.SetEntryArgs(args.entry_arg)
402
403             images = PrepareImagesAndDtbs(dtb_fname, args.image,
404                                           args.update_fdt)
405             for image in images.values():
406                 ProcessImage(image, args.update_fdt, args.map)
407
408             # Write the updated FDTs to our output files
409             for dtb_item in state.GetAllFdts():
410                 tools.WriteFile(dtb_item._fname, dtb_item.GetContents())
411
412         finally:
413             tools.FinaliseOutputDir()
414     finally:
415         tout.Uninit()
416
417     return 0