blob: 1be31a05e00a8feb650c913116c69236146e0e59 [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#
Simon Glassbf7fd502016-11-25 20:15:51 -07004# Base class for all entries
5#
6
Simon Glass53af22a2018-07-17 13:25:32 -06007from collections import namedtuple
Simon Glassb4cf5f12019-10-31 07:42:59 -06008import importlib
Simon Glassbadf0ec2018-06-01 09:38:15 -06009import os
Simon Glass790ba9f2022-01-12 13:10:36 -070010import pathlib
Simon Glassbadf0ec2018-06-01 09:38:15 -060011import sys
Simon Glass7960a0a2022-08-07 09:46:46 -060012import time
Simon Glassc55a50f2018-09-14 04:57:19 -060013
Simon Glass386c63c2022-01-09 20:13:50 -070014from binman import bintool
Simon Glass3fbba552022-10-20 18:22:46 -060015from binman import elf
Simon Glass16287932020-04-17 18:09:03 -060016from dtoc import fdt_util
Simon Glassbf776672020-04-17 18:09:04 -060017from patman import tools
Simon Glassc1aa66e2022-01-29 14:14:04 -070018from patman.tools import to_hex, to_hex_size
Simon Glassbf776672020-04-17 18:09:04 -060019from patman import tout
Simon Glassbf7fd502016-11-25 20:15:51 -070020
21modules = {}
22
Simon Glass8d2ef3e2022-02-11 13:23:21 -070023# This is imported if needed
24state = None
Simon Glass53af22a2018-07-17 13:25:32 -060025
26# An argument which can be passed to entries on the command line, in lieu of
27# device-tree properties.
28EntryArg = namedtuple('EntryArg', ['name', 'datatype'])
29
Simon Glass41b8ba02019-07-08 14:25:43 -060030# Information about an entry for use when displaying summaries
31EntryInfo = namedtuple('EntryInfo', ['indent', 'name', 'etype', 'size',
32 'image_pos', 'uncomp_size', 'offset',
33 'entry'])
Simon Glass53af22a2018-07-17 13:25:32 -060034
Simon Glassbf7fd502016-11-25 20:15:51 -070035class Entry(object):
Simon Glass25ac0e62018-06-01 09:38:14 -060036 """An Entry in the section
Simon Glassbf7fd502016-11-25 20:15:51 -070037
38 An entry corresponds to a single node in the device-tree description
Simon Glass25ac0e62018-06-01 09:38:14 -060039 of the section. Each entry ends up being a part of the final section.
Simon Glassbf7fd502016-11-25 20:15:51 -070040 Entries can be placed either right next to each other, or with padding
41 between them. The type of the entry determines the data that is in it.
42
43 This class is not used by itself. All entry objects are subclasses of
44 Entry.
45
46 Attributes:
Simon Glass8122f392018-07-17 13:25:28 -060047 section: Section object containing this entry
Simon Glassbf7fd502016-11-25 20:15:51 -070048 node: The node that created this entry
Simon Glass3ab95982018-08-01 15:22:37 -060049 offset: Offset of entry within the section, None if not known yet (in
50 which case it will be calculated by Pack())
Simon Glassbf7fd502016-11-25 20:15:51 -070051 size: Entry size in bytes, None if not known
Simon Glass9a5d3dc2019-10-31 07:43:02 -060052 pre_reset_size: size as it was before ResetForPack(). This allows us to
53 keep track of the size we started with and detect size changes
Simon Glass8287ee82019-07-08 14:25:30 -060054 uncomp_size: Size of uncompressed data in bytes, if the entry is
55 compressed, else None
Simon Glassbf7fd502016-11-25 20:15:51 -070056 contents_size: Size of contents in bytes, 0 by default
Simon Glass4eec34c2020-10-26 17:40:10 -060057 align: Entry start offset alignment relative to the start of the
58 containing section, or None
Simon Glassbf7fd502016-11-25 20:15:51 -070059 align_size: Entry size alignment, or None
Simon Glass4eec34c2020-10-26 17:40:10 -060060 align_end: Entry end offset alignment relative to the start of the
61 containing section, or None
Simon Glassf90d9062020-10-26 17:40:09 -060062 pad_before: Number of pad bytes before the contents when it is placed
63 in the containing section, 0 if none. The pad bytes become part of
64 the entry.
65 pad_after: Number of pad bytes after the contents when it is placed in
66 the containing section, 0 if none. The pad bytes become part of
67 the entry.
68 data: Contents of entry (string of bytes). This does not include
Simon Glass97c3e9a2020-10-26 17:40:15 -060069 padding created by pad_before or pad_after. If the entry is
70 compressed, this contains the compressed data.
71 uncomp_data: Original uncompressed data, if this entry is compressed,
72 else None
Simon Glass8287ee82019-07-08 14:25:30 -060073 compress: Compression algoithm used (e.g. 'lz4'), 'none' if none
Simon Glassc52c9e72019-07-08 14:25:37 -060074 orig_offset: Original offset value read from node
75 orig_size: Original size value read from node
Simon Glass87958982020-09-01 05:13:57 -060076 missing: True if this entry is missing its contents
77 allow_missing: Allow children of this entry to be missing (used by
78 subclasses such as Entry_section)
Heiko Thierya89c8f22022-01-06 11:49:41 +010079 allow_fake: Allow creating a dummy fake file if the blob file is not
80 available. This is mainly used for testing.
Simon Glass87958982020-09-01 05:13:57 -060081 external: True if this entry contains an external binary blob
Simon Glass386c63c2022-01-09 20:13:50 -070082 bintools: Bintools used by this entry (only populated for Image)
Simon Glass4f9ee832022-01-09 20:14:09 -070083 missing_bintools: List of missing bintools for this entry
Alper Nebi Yasakee813c82022-02-09 22:02:35 +030084 update_hash: True if this entry's "hash" subnode should be
85 updated with a hash of the entry contents
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +020086 comp_bintool: Bintools used for compress and decompress data
Simon Glass7960a0a2022-08-07 09:46:46 -060087 fake_fname: Fake filename, if one was created, else None
Simon Glasscdadada2022-08-13 11:40:44 -060088 required_props (dict of str): Properties which must be present. This can
89 be added to by subclasses
Simon Glass3fbba552022-10-20 18:22:46 -060090 elf_fname (str): Filename of the ELF file, if this entry holds an ELF
91 file, or is a binary file produced from an ELF file
92 auto_write_symbols (bool): True to write ELF symbols into this entry's
93 contents
Simon Glassbf7fd502016-11-25 20:15:51 -070094 """
Simon Glass7960a0a2022-08-07 09:46:46 -060095 fake_dir = None
96
Simon Glass3fbba552022-10-20 18:22:46 -060097 def __init__(self, section, etype, node, name_prefix='',
98 auto_write_symbols=False):
Simon Glass8dbb7442019-08-24 07:22:44 -060099 # Put this here to allow entry-docs and help to work without libfdt
100 global state
Simon Glass16287932020-04-17 18:09:03 -0600101 from binman import state
Simon Glass8dbb7442019-08-24 07:22:44 -0600102
Simon Glass25ac0e62018-06-01 09:38:14 -0600103 self.section = section
Simon Glassbf7fd502016-11-25 20:15:51 -0700104 self.etype = etype
105 self._node = node
Simon Glassc8d48ef2018-06-01 09:38:21 -0600106 self.name = node and (name_prefix + node.name) or 'none'
Simon Glass3ab95982018-08-01 15:22:37 -0600107 self.offset = None
Simon Glassbf7fd502016-11-25 20:15:51 -0700108 self.size = None
Simon Glass9a5d3dc2019-10-31 07:43:02 -0600109 self.pre_reset_size = None
Simon Glass8287ee82019-07-08 14:25:30 -0600110 self.uncomp_size = None
Simon Glass24d0d3c2018-07-17 13:25:47 -0600111 self.data = None
Simon Glass97c3e9a2020-10-26 17:40:15 -0600112 self.uncomp_data = None
Simon Glassbf7fd502016-11-25 20:15:51 -0700113 self.contents_size = 0
114 self.align = None
115 self.align_size = None
116 self.align_end = None
117 self.pad_before = 0
118 self.pad_after = 0
Simon Glass3ab95982018-08-01 15:22:37 -0600119 self.offset_unset = False
Simon Glassdbf6be92018-08-01 15:22:42 -0600120 self.image_pos = None
Simon Glass80a66ae2022-03-05 20:18:59 -0700121 self.extend_size = False
Simon Glass8287ee82019-07-08 14:25:30 -0600122 self.compress = 'none'
Simon Glassb1cca952020-07-09 18:39:40 -0600123 self.missing = False
Heiko Thierya89c8f22022-01-06 11:49:41 +0100124 self.faked = False
Simon Glass87958982020-09-01 05:13:57 -0600125 self.external = False
126 self.allow_missing = False
Heiko Thierya89c8f22022-01-06 11:49:41 +0100127 self.allow_fake = False
Simon Glass386c63c2022-01-09 20:13:50 -0700128 self.bintools = {}
Simon Glass4f9ee832022-01-09 20:14:09 -0700129 self.missing_bintools = []
Alper Nebi Yasakee813c82022-02-09 22:02:35 +0300130 self.update_hash = True
Simon Glass7960a0a2022-08-07 09:46:46 -0600131 self.fake_fname = None
Simon Glasscdadada2022-08-13 11:40:44 -0600132 self.required_props = []
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +0200133 self.comp_bintool = None
Simon Glass3fbba552022-10-20 18:22:46 -0600134 self.elf_fname = None
135 self.auto_write_symbols = auto_write_symbols
Simon Glassbf7fd502016-11-25 20:15:51 -0700136
137 @staticmethod
Simon Glass858436d2021-11-23 21:09:49 -0700138 def FindEntryClass(etype, expanded):
Simon Glassfd8d1f72018-07-17 13:25:36 -0600139 """Look up the entry class for a node.
Simon Glassbf7fd502016-11-25 20:15:51 -0700140
141 Args:
Simon Glassfd8d1f72018-07-17 13:25:36 -0600142 node_node: Path name of Node object containing information about
143 the entry to create (used for errors)
144 etype: Entry type to use
Simon Glassb35fb172021-03-18 20:25:04 +1300145 expanded: Use the expanded version of etype
Simon Glassbf7fd502016-11-25 20:15:51 -0700146
147 Returns:
Simon Glassb35fb172021-03-18 20:25:04 +1300148 The entry class object if found, else None if not found and expanded
Simon Glass858436d2021-11-23 21:09:49 -0700149 is True, else a tuple:
150 module name that could not be found
151 exception received
Simon Glassbf7fd502016-11-25 20:15:51 -0700152 """
Simon Glassdd57c132018-06-01 09:38:11 -0600153 # Convert something like 'u-boot@0' to 'u_boot' since we are only
154 # interested in the type.
Simon Glassbf7fd502016-11-25 20:15:51 -0700155 module_name = etype.replace('-', '_')
Simon Glassb35fb172021-03-18 20:25:04 +1300156
Simon Glassdd57c132018-06-01 09:38:11 -0600157 if '@' in module_name:
158 module_name = module_name.split('@')[0]
Simon Glassb35fb172021-03-18 20:25:04 +1300159 if expanded:
160 module_name += '_expanded'
Simon Glassbf7fd502016-11-25 20:15:51 -0700161 module = modules.get(module_name)
162
Simon Glassbadf0ec2018-06-01 09:38:15 -0600163 # Also allow entry-type modules to be brought in from the etype directory.
164
Simon Glassbf7fd502016-11-25 20:15:51 -0700165 # Import the module if we have not already done so.
166 if not module:
167 try:
Simon Glass16287932020-04-17 18:09:03 -0600168 module = importlib.import_module('binman.etype.' + module_name)
Simon Glassfd8d1f72018-07-17 13:25:36 -0600169 except ImportError as e:
Simon Glassb35fb172021-03-18 20:25:04 +1300170 if expanded:
171 return None
Simon Glass858436d2021-11-23 21:09:49 -0700172 return module_name, e
Simon Glassbf7fd502016-11-25 20:15:51 -0700173 modules[module_name] = module
174
Simon Glassfd8d1f72018-07-17 13:25:36 -0600175 # Look up the expected class name
176 return getattr(module, 'Entry_%s' % module_name)
177
178 @staticmethod
Simon Glass858436d2021-11-23 21:09:49 -0700179 def Lookup(node_path, etype, expanded, missing_etype=False):
180 """Look up the entry class for a node.
181
182 Args:
183 node_node (str): Path name of Node object containing information
184 about the entry to create (used for errors)
185 etype (str): Entry type to use
186 expanded (bool): Use the expanded version of etype
187 missing_etype (bool): True to default to a blob etype if the
188 requested etype is not found
189
190 Returns:
191 The entry class object if found, else None if not found and expanded
192 is True
193
194 Raise:
195 ValueError if expanded is False and the class is not found
196 """
197 # Convert something like 'u-boot@0' to 'u_boot' since we are only
198 # interested in the type.
199 cls = Entry.FindEntryClass(etype, expanded)
200 if cls is None:
201 return None
202 elif isinstance(cls, tuple):
203 if missing_etype:
204 cls = Entry.FindEntryClass('blob', False)
205 if isinstance(cls, tuple): # This should not fail
206 module_name, e = cls
207 raise ValueError(
208 "Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
209 (etype, node_path, module_name, e))
210 return cls
211
212 @staticmethod
213 def Create(section, node, etype=None, expanded=False, missing_etype=False):
Simon Glassfd8d1f72018-07-17 13:25:36 -0600214 """Create a new entry for a node.
215
216 Args:
Simon Glass858436d2021-11-23 21:09:49 -0700217 section (entry_Section): Section object containing this node
218 node (Node): Node object containing information about the entry to
219 create
220 etype (str): Entry type to use, or None to work it out (used for
221 tests)
222 expanded (bool): Use the expanded version of etype
223 missing_etype (bool): True to default to a blob etype if the
224 requested etype is not found
Simon Glassfd8d1f72018-07-17 13:25:36 -0600225
226 Returns:
227 A new Entry object of the correct type (a subclass of Entry)
228 """
229 if not etype:
230 etype = fdt_util.GetString(node, 'type', node.name)
Simon Glass858436d2021-11-23 21:09:49 -0700231 obj = Entry.Lookup(node.path, etype, expanded, missing_etype)
Simon Glassb35fb172021-03-18 20:25:04 +1300232 if obj and expanded:
233 # Check whether to use the expanded entry
234 new_etype = etype + '-expanded'
Simon Glass3d433382021-03-21 18:24:30 +1300235 can_expand = not fdt_util.GetBool(node, 'no-expanded')
236 if can_expand and obj.UseExpanded(node, etype, new_etype):
Simon Glassb35fb172021-03-18 20:25:04 +1300237 etype = new_etype
238 else:
239 obj = None
240 if not obj:
Simon Glass858436d2021-11-23 21:09:49 -0700241 obj = Entry.Lookup(node.path, etype, False, missing_etype)
Simon Glassfd8d1f72018-07-17 13:25:36 -0600242
Simon Glassbf7fd502016-11-25 20:15:51 -0700243 # Call its constructor to get the object we want.
Simon Glass25ac0e62018-06-01 09:38:14 -0600244 return obj(section, etype, node)
Simon Glassbf7fd502016-11-25 20:15:51 -0700245
246 def ReadNode(self):
247 """Read entry information from the node
248
Simon Glassc6bd6e22019-07-20 12:23:45 -0600249 This must be called as the first thing after the Entry is created.
250
Simon Glassbf7fd502016-11-25 20:15:51 -0700251 This reads all the fields we recognise from the node, ready for use.
252 """
Simon Glasscdadada2022-08-13 11:40:44 -0600253 self.ensure_props()
Simon Glass15a587c2018-07-17 13:25:51 -0600254 if 'pos' in self._node.props:
255 self.Raise("Please use 'offset' instead of 'pos'")
Simon Glass80a66ae2022-03-05 20:18:59 -0700256 if 'expand-size' in self._node.props:
257 self.Raise("Please use 'extend-size' instead of 'expand-size'")
Simon Glass3ab95982018-08-01 15:22:37 -0600258 self.offset = fdt_util.GetInt(self._node, 'offset')
Simon Glassbf7fd502016-11-25 20:15:51 -0700259 self.size = fdt_util.GetInt(self._node, 'size')
Simon Glass12bb1a92019-07-20 12:23:51 -0600260 self.orig_offset = fdt_util.GetInt(self._node, 'orig-offset')
261 self.orig_size = fdt_util.GetInt(self._node, 'orig-size')
262 if self.GetImage().copy_to_orig:
263 self.orig_offset = self.offset
264 self.orig_size = self.size
Simon Glassc52c9e72019-07-08 14:25:37 -0600265
Simon Glassffded752019-07-08 14:25:46 -0600266 # These should not be set in input files, but are set in an FDT map,
267 # which is also read by this code.
268 self.image_pos = fdt_util.GetInt(self._node, 'image-pos')
269 self.uncomp_size = fdt_util.GetInt(self._node, 'uncomp-size')
270
Simon Glassbf7fd502016-11-25 20:15:51 -0700271 self.align = fdt_util.GetInt(self._node, 'align')
Simon Glassc1aa66e2022-01-29 14:14:04 -0700272 if tools.not_power_of_two(self.align):
Simon Glassbf7fd502016-11-25 20:15:51 -0700273 raise ValueError("Node '%s': Alignment %s must be a power of two" %
274 (self._node.path, self.align))
Simon Glass5ff9fed2021-03-21 18:24:33 +1300275 if self.section and self.align is None:
276 self.align = self.section.align_default
Simon Glassbf7fd502016-11-25 20:15:51 -0700277 self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
278 self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
279 self.align_size = fdt_util.GetInt(self._node, 'align-size')
Simon Glassc1aa66e2022-01-29 14:14:04 -0700280 if tools.not_power_of_two(self.align_size):
Simon Glass8beb11e2019-07-08 14:25:47 -0600281 self.Raise("Alignment size %s must be a power of two" %
282 self.align_size)
Simon Glassbf7fd502016-11-25 20:15:51 -0700283 self.align_end = fdt_util.GetInt(self._node, 'align-end')
Simon Glass3ab95982018-08-01 15:22:37 -0600284 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
Simon Glass80a66ae2022-03-05 20:18:59 -0700285 self.extend_size = fdt_util.GetBool(self._node, 'extend-size')
Simon Glassb2381432020-09-06 10:39:09 -0600286 self.missing_msg = fdt_util.GetString(self._node, 'missing-msg')
Simon Glassbf7fd502016-11-25 20:15:51 -0700287
Simon Glass87c96292020-10-26 17:40:06 -0600288 # This is only supported by blobs and sections at present
289 self.compress = fdt_util.GetString(self._node, 'compress', 'none')
290
Simon Glass6c234bf2018-09-14 04:57:18 -0600291 def GetDefaultFilename(self):
292 return None
293
Simon Glassa8adb6d2019-07-20 12:23:28 -0600294 def GetFdts(self):
295 """Get the device trees used by this entry
Simon Glass539aece2018-09-14 04:57:22 -0600296
297 Returns:
Simon Glassa8adb6d2019-07-20 12:23:28 -0600298 Empty dict, if this entry is not a .dtb, otherwise:
299 Dict:
300 key: Filename from this entry (without the path)
Simon Glass4bdd3002019-07-20 12:23:31 -0600301 value: Tuple:
Simon Glassadb67bb2021-03-18 20:25:02 +1300302 Entry object for this dtb
Simon Glass4bdd3002019-07-20 12:23:31 -0600303 Filename of file containing this dtb
Simon Glass539aece2018-09-14 04:57:22 -0600304 """
Simon Glassa8adb6d2019-07-20 12:23:28 -0600305 return {}
Simon Glass539aece2018-09-14 04:57:22 -0600306
Simon Glassc9ee33a2022-03-05 20:19:00 -0700307 def gen_entries(self):
308 """Allow entries to generate other entries
Simon Glassa01d1a22021-03-18 20:24:52 +1300309
310 Some entries generate subnodes automatically, from which sub-entries
311 are then created. This method allows those to be added to the binman
312 definition for the current image. An entry which implements this method
313 should call state.AddSubnode() to add a subnode and can add properties
314 with state.AddString(), etc.
315
316 An example is 'files', which produces a section containing a list of
317 files.
318 """
Simon Glass0a98b282018-09-14 04:57:28 -0600319 pass
320
Simon Glassa9fad072020-10-26 17:40:17 -0600321 def AddMissingProperties(self, have_image_pos):
322 """Add new properties to the device tree as needed for this entry
323
324 Args:
325 have_image_pos: True if this entry has an image position. This can
326 be False if its parent section is compressed, since compression
327 groups all entries together into a compressed block of data,
328 obscuring the start of each individual child entry
329 """
330 for prop in ['offset', 'size']:
Simon Glass078ab1a2018-07-06 10:27:41 -0600331 if not prop in self._node.props:
Simon Glassf46621d2018-09-14 04:57:21 -0600332 state.AddZeroProp(self._node, prop)
Simon Glassa9fad072020-10-26 17:40:17 -0600333 if have_image_pos and 'image-pos' not in self._node.props:
334 state.AddZeroProp(self._node, 'image-pos')
Simon Glass12bb1a92019-07-20 12:23:51 -0600335 if self.GetImage().allow_repack:
336 if self.orig_offset is not None:
337 state.AddZeroProp(self._node, 'orig-offset', True)
338 if self.orig_size is not None:
339 state.AddZeroProp(self._node, 'orig-size', True)
340
Simon Glass8287ee82019-07-08 14:25:30 -0600341 if self.compress != 'none':
342 state.AddZeroProp(self._node, 'uncomp-size')
Alper Nebi Yasakee813c82022-02-09 22:02:35 +0300343
344 if self.update_hash:
345 err = state.CheckAddHashProp(self._node)
346 if err:
347 self.Raise(err)
Simon Glass078ab1a2018-07-06 10:27:41 -0600348
349 def SetCalculatedProperties(self):
350 """Set the value of device-tree properties calculated by binman"""
Simon Glassf46621d2018-09-14 04:57:21 -0600351 state.SetInt(self._node, 'offset', self.offset)
352 state.SetInt(self._node, 'size', self.size)
Simon Glass8beb11e2019-07-08 14:25:47 -0600353 base = self.section.GetRootSkipAtStart() if self.section else 0
Simon Glassa9fad072020-10-26 17:40:17 -0600354 if self.image_pos is not None:
Simon Glass08594d42020-11-02 12:55:44 -0700355 state.SetInt(self._node, 'image-pos', self.image_pos - base)
Simon Glass12bb1a92019-07-20 12:23:51 -0600356 if self.GetImage().allow_repack:
357 if self.orig_offset is not None:
358 state.SetInt(self._node, 'orig-offset', self.orig_offset, True)
359 if self.orig_size is not None:
360 state.SetInt(self._node, 'orig-size', self.orig_size, True)
Simon Glass8287ee82019-07-08 14:25:30 -0600361 if self.uncomp_size is not None:
362 state.SetInt(self._node, 'uncomp-size', self.uncomp_size)
Alper Nebi Yasakee813c82022-02-09 22:02:35 +0300363
364 if self.update_hash:
365 state.CheckSetHashValue(self._node, self.GetData)
Simon Glass078ab1a2018-07-06 10:27:41 -0600366
Simon Glassecab8972018-07-06 10:27:40 -0600367 def ProcessFdt(self, fdt):
Simon Glass6ed45ba2018-09-14 04:57:24 -0600368 """Allow entries to adjust the device tree
369
370 Some entries need to adjust the device tree for their purposes. This
371 may involve adding or deleting properties.
372
373 Returns:
374 True if processing is complete
375 False if processing could not be completed due to a dependency.
376 This will cause the entry to be retried after others have been
377 called
378 """
Simon Glassecab8972018-07-06 10:27:40 -0600379 return True
380
Simon Glassc8d48ef2018-06-01 09:38:21 -0600381 def SetPrefix(self, prefix):
382 """Set the name prefix for a node
383
384 Args:
385 prefix: Prefix to set, or '' to not use a prefix
386 """
387 if prefix:
388 self.name = prefix + self.name
389
Simon Glass5c890232018-07-06 10:27:19 -0600390 def SetContents(self, data):
391 """Set the contents of an entry
392
393 This sets both the data and content_size properties
394
395 Args:
Simon Glass5b463fc2019-07-08 14:25:33 -0600396 data: Data to set to the contents (bytes)
Simon Glass5c890232018-07-06 10:27:19 -0600397 """
398 self.data = data
399 self.contents_size = len(self.data)
400
401 def ProcessContentsUpdate(self, data):
Simon Glass5b463fc2019-07-08 14:25:33 -0600402 """Update the contents of an entry, after the size is fixed
Simon Glass5c890232018-07-06 10:27:19 -0600403
Simon Glassa0dcaf22019-07-08 14:25:35 -0600404 This checks that the new data is the same size as the old. If the size
405 has changed, this triggers a re-run of the packing algorithm.
Simon Glass5c890232018-07-06 10:27:19 -0600406
407 Args:
Simon Glass5b463fc2019-07-08 14:25:33 -0600408 data: Data to set to the contents (bytes)
Simon Glass5c890232018-07-06 10:27:19 -0600409
410 Raises:
411 ValueError if the new data size is not the same as the old
412 """
Simon Glassa0dcaf22019-07-08 14:25:35 -0600413 size_ok = True
Simon Glassc52c9e72019-07-08 14:25:37 -0600414 new_size = len(data)
Simon Glass61ec04f2019-07-20 12:23:58 -0600415 if state.AllowEntryExpansion() and new_size > self.contents_size:
416 # self.data will indicate the new size needed
417 size_ok = False
418 elif state.AllowEntryContraction() and new_size < self.contents_size:
419 size_ok = False
420
421 # If not allowed to change, try to deal with it or give up
422 if size_ok:
Simon Glassc52c9e72019-07-08 14:25:37 -0600423 if new_size > self.contents_size:
Simon Glass61ec04f2019-07-20 12:23:58 -0600424 self.Raise('Cannot update entry size from %d to %d' %
425 (self.contents_size, new_size))
426
427 # Don't let the data shrink. Pad it if necessary
428 if size_ok and new_size < self.contents_size:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700429 data += tools.get_bytes(0, self.contents_size - new_size)
Simon Glass61ec04f2019-07-20 12:23:58 -0600430
431 if not size_ok:
Simon Glassf3385a52022-01-29 14:14:15 -0700432 tout.debug("Entry '%s' size change from %s to %s" % (
Simon Glassc1aa66e2022-01-29 14:14:04 -0700433 self._node.path, to_hex(self.contents_size),
434 to_hex(new_size)))
Simon Glass5c890232018-07-06 10:27:19 -0600435 self.SetContents(data)
Simon Glassa0dcaf22019-07-08 14:25:35 -0600436 return size_ok
Simon Glass5c890232018-07-06 10:27:19 -0600437
Simon Glass72e423c2022-03-05 20:19:05 -0700438 def ObtainContents(self, skip_entry=None, fake_size=0):
Simon Glassbf7fd502016-11-25 20:15:51 -0700439 """Figure out the contents of an entry.
440
Simon Glass72e423c2022-03-05 20:19:05 -0700441 Args:
442 skip_entry (Entry): Entry to skip when obtaining section contents
443 fake_size (int): Size of fake file to create if needed
444
Simon Glassbf7fd502016-11-25 20:15:51 -0700445 Returns:
446 True if the contents were found, False if another call is needed
447 after the other entries are processed.
448 """
449 # No contents by default: subclasses can implement this
450 return True
451
Simon Glassc52c9e72019-07-08 14:25:37 -0600452 def ResetForPack(self):
453 """Reset offset/size fields so that packing can be done again"""
Simon Glass9f297b02019-07-20 12:23:36 -0600454 self.Detail('ResetForPack: offset %s->%s, size %s->%s' %
Simon Glassc1aa66e2022-01-29 14:14:04 -0700455 (to_hex(self.offset), to_hex(self.orig_offset),
456 to_hex(self.size), to_hex(self.orig_size)))
Simon Glass9a5d3dc2019-10-31 07:43:02 -0600457 self.pre_reset_size = self.size
Simon Glassc52c9e72019-07-08 14:25:37 -0600458 self.offset = self.orig_offset
459 self.size = self.orig_size
460
Simon Glass3ab95982018-08-01 15:22:37 -0600461 def Pack(self, offset):
Simon Glass25ac0e62018-06-01 09:38:14 -0600462 """Figure out how to pack the entry into the section
Simon Glassbf7fd502016-11-25 20:15:51 -0700463
464 Most of the time the entries are not fully specified. There may be
465 an alignment but no size. In that case we take the size from the
466 contents of the entry.
467
Simon Glass3ab95982018-08-01 15:22:37 -0600468 If an entry has no hard-coded offset, it will be placed at @offset.
Simon Glassbf7fd502016-11-25 20:15:51 -0700469
Simon Glass3ab95982018-08-01 15:22:37 -0600470 Once this function is complete, both the offset and size of the
Simon Glassbf7fd502016-11-25 20:15:51 -0700471 entry will be know.
472
473 Args:
Simon Glass3ab95982018-08-01 15:22:37 -0600474 Current section offset pointer
Simon Glassbf7fd502016-11-25 20:15:51 -0700475
476 Returns:
Simon Glass3ab95982018-08-01 15:22:37 -0600477 New section offset pointer (after this entry)
Simon Glassbf7fd502016-11-25 20:15:51 -0700478 """
Simon Glass9f297b02019-07-20 12:23:36 -0600479 self.Detail('Packing: offset=%s, size=%s, content_size=%x' %
Simon Glassc1aa66e2022-01-29 14:14:04 -0700480 (to_hex(self.offset), to_hex(self.size),
Simon Glass9f297b02019-07-20 12:23:36 -0600481 self.contents_size))
Simon Glass3ab95982018-08-01 15:22:37 -0600482 if self.offset is None:
483 if self.offset_unset:
484 self.Raise('No offset set with offset-unset: should another '
485 'entry provide this correct offset?')
Simon Glassc1aa66e2022-01-29 14:14:04 -0700486 self.offset = tools.align(offset, self.align)
Simon Glassbf7fd502016-11-25 20:15:51 -0700487 needed = self.pad_before + self.contents_size + self.pad_after
Simon Glassc1aa66e2022-01-29 14:14:04 -0700488 needed = tools.align(needed, self.align_size)
Simon Glassbf7fd502016-11-25 20:15:51 -0700489 size = self.size
490 if not size:
491 size = needed
Simon Glass3ab95982018-08-01 15:22:37 -0600492 new_offset = self.offset + size
Simon Glassc1aa66e2022-01-29 14:14:04 -0700493 aligned_offset = tools.align(new_offset, self.align_end)
Simon Glass3ab95982018-08-01 15:22:37 -0600494 if aligned_offset != new_offset:
495 size = aligned_offset - self.offset
496 new_offset = aligned_offset
Simon Glassbf7fd502016-11-25 20:15:51 -0700497
498 if not self.size:
499 self.size = size
500
501 if self.size < needed:
502 self.Raise("Entry contents size is %#x (%d) but entry size is "
503 "%#x (%d)" % (needed, needed, self.size, self.size))
504 # Check that the alignment is correct. It could be wrong if the
Simon Glass3ab95982018-08-01 15:22:37 -0600505 # and offset or size values were provided (i.e. not calculated), but
Simon Glassbf7fd502016-11-25 20:15:51 -0700506 # conflict with the provided alignment values
Simon Glassc1aa66e2022-01-29 14:14:04 -0700507 if self.size != tools.align(self.size, self.align_size):
Simon Glassbf7fd502016-11-25 20:15:51 -0700508 self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
509 (self.size, self.size, self.align_size, self.align_size))
Simon Glassc1aa66e2022-01-29 14:14:04 -0700510 if self.offset != tools.align(self.offset, self.align):
Simon Glass3ab95982018-08-01 15:22:37 -0600511 self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
512 (self.offset, self.offset, self.align, self.align))
Simon Glass9f297b02019-07-20 12:23:36 -0600513 self.Detail(' - packed: offset=%#x, size=%#x, content_size=%#x, next_offset=%x' %
514 (self.offset, self.size, self.contents_size, new_offset))
Simon Glassbf7fd502016-11-25 20:15:51 -0700515
Simon Glass3ab95982018-08-01 15:22:37 -0600516 return new_offset
Simon Glassbf7fd502016-11-25 20:15:51 -0700517
518 def Raise(self, msg):
519 """Convenience function to raise an error referencing a node"""
520 raise ValueError("Node '%s': %s" % (self._node.path, msg))
521
Simon Glass189f2912021-03-21 18:24:31 +1300522 def Info(self, msg):
523 """Convenience function to log info referencing a node"""
524 tag = "Info '%s'" % self._node.path
Simon Glassf3385a52022-01-29 14:14:15 -0700525 tout.detail('%30s: %s' % (tag, msg))
Simon Glass189f2912021-03-21 18:24:31 +1300526
Simon Glass9f297b02019-07-20 12:23:36 -0600527 def Detail(self, msg):
528 """Convenience function to log detail referencing a node"""
529 tag = "Node '%s'" % self._node.path
Simon Glassf3385a52022-01-29 14:14:15 -0700530 tout.detail('%30s: %s' % (tag, msg))
Simon Glass9f297b02019-07-20 12:23:36 -0600531
Simon Glass53af22a2018-07-17 13:25:32 -0600532 def GetEntryArgsOrProps(self, props, required=False):
533 """Return the values of a set of properties
534
535 Args:
536 props: List of EntryArg objects
537
538 Raises:
539 ValueError if a property is not found
540 """
541 values = []
542 missing = []
543 for prop in props:
544 python_prop = prop.name.replace('-', '_')
545 if hasattr(self, python_prop):
546 value = getattr(self, python_prop)
547 else:
548 value = None
549 if value is None:
550 value = self.GetArg(prop.name, prop.datatype)
551 if value is None and required:
552 missing.append(prop.name)
553 values.append(value)
554 if missing:
Simon Glass939d1062021-01-06 21:35:16 -0700555 self.GetImage().MissingArgs(self, missing)
Simon Glass53af22a2018-07-17 13:25:32 -0600556 return values
557
Simon Glassbf7fd502016-11-25 20:15:51 -0700558 def GetPath(self):
559 """Get the path of a node
560
561 Returns:
562 Full path of the node for this entry
563 """
564 return self._node.path
565
Simon Glass631f7522021-03-21 18:24:32 +1300566 def GetData(self, required=True):
Simon Glass63e7ba62020-10-26 17:40:16 -0600567 """Get the contents of an entry
568
Simon Glass631f7522021-03-21 18:24:32 +1300569 Args:
570 required: True if the data must be present, False if it is OK to
571 return None
572
Simon Glass63e7ba62020-10-26 17:40:16 -0600573 Returns:
574 bytes content of the entry, excluding any padding. If the entry is
575 compressed, the compressed data is returned
576 """
Simon Glassc1aa66e2022-01-29 14:14:04 -0700577 self.Detail('GetData: size %s' % to_hex_size(self.data))
Simon Glassbf7fd502016-11-25 20:15:51 -0700578 return self.data
579
Simon Glass271a0832020-11-02 12:55:43 -0700580 def GetPaddedData(self, data=None):
581 """Get the data for an entry including any padding
582
583 Gets the entry data and uses its section's pad-byte value to add padding
584 before and after as defined by the pad-before and pad-after properties.
585
586 This does not consider alignment.
587
588 Returns:
589 Contents of the entry along with any pad bytes before and
590 after it (bytes)
591 """
592 if data is None:
593 data = self.GetData()
594 return self.section.GetPaddedDataForEntry(self, data)
595
Simon Glass3ab95982018-08-01 15:22:37 -0600596 def GetOffsets(self):
Simon Glassed7dd5e2019-07-08 13:18:30 -0600597 """Get the offsets for siblings
598
599 Some entry types can contain information about the position or size of
600 other entries. An example of this is the Intel Flash Descriptor, which
601 knows where the Intel Management Engine section should go.
602
603 If this entry knows about the position of other entries, it can specify
604 this by returning values here
605
606 Returns:
607 Dict:
608 key: Entry type
609 value: List containing position and size of the given entry
Simon Glasscf549042019-07-08 13:18:39 -0600610 type. Either can be None if not known
Simon Glassed7dd5e2019-07-08 13:18:30 -0600611 """
Simon Glassbf7fd502016-11-25 20:15:51 -0700612 return {}
613
Simon Glasscf549042019-07-08 13:18:39 -0600614 def SetOffsetSize(self, offset, size):
615 """Set the offset and/or size of an entry
616
617 Args:
618 offset: New offset, or None to leave alone
619 size: New size, or None to leave alone
620 """
621 if offset is not None:
622 self.offset = offset
623 if size is not None:
624 self.size = size
Simon Glassbf7fd502016-11-25 20:15:51 -0700625
Simon Glassdbf6be92018-08-01 15:22:42 -0600626 def SetImagePos(self, image_pos):
627 """Set the position in the image
628
629 Args:
630 image_pos: Position of this entry in the image
631 """
632 self.image_pos = image_pos + self.offset
633
Simon Glassbf7fd502016-11-25 20:15:51 -0700634 def ProcessContents(self):
Simon Glassa0dcaf22019-07-08 14:25:35 -0600635 """Do any post-packing updates of entry contents
636
637 This function should call ProcessContentsUpdate() to update the entry
638 contents, if necessary, returning its return value here.
639
640 Args:
641 data: Data to set to the contents (bytes)
642
643 Returns:
644 True if the new data size is OK, False if expansion is needed
645
646 Raises:
647 ValueError if the new data size is not the same as the old and
648 state.AllowEntryExpansion() is False
649 """
650 return True
Simon Glass19790632017-11-13 18:55:01 -0700651
Simon Glassf55382b2018-06-01 09:38:13 -0600652 def WriteSymbols(self, section):
Simon Glass19790632017-11-13 18:55:01 -0700653 """Write symbol values into binary files for access at run time
654
655 Args:
Simon Glassf55382b2018-06-01 09:38:13 -0600656 section: Section containing the entry
Simon Glass19790632017-11-13 18:55:01 -0700657 """
Simon Glass3fbba552022-10-20 18:22:46 -0600658 if self.auto_write_symbols:
Simon Glassd2afb9e2022-10-20 18:22:47 -0600659 # Check if we are writing symbols into an ELF file
660 is_elf = self.GetDefaultFilename() == self.elf_fname
661 elf.LookupAndWriteSymbols(self.elf_fname, self, section.GetImage(),
662 is_elf)
Simon Glass18546952018-06-01 09:38:16 -0600663
Simon Glass6ddd6112020-10-26 17:40:18 -0600664 def CheckEntries(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600665 """Check that the entry offsets are correct
Simon Glass18546952018-06-01 09:38:16 -0600666
Simon Glass3ab95982018-08-01 15:22:37 -0600667 This is used for entries which have extra offset requirements (other
Simon Glass18546952018-06-01 09:38:16 -0600668 than having to be fully inside their section). Sub-classes can implement
669 this function and raise if there is a problem.
670 """
671 pass
Simon Glass3b0c3822018-06-01 09:38:20 -0600672
Simon Glass8122f392018-07-17 13:25:28 -0600673 @staticmethod
Simon Glass163ed6c2018-09-14 04:57:36 -0600674 def GetStr(value):
675 if value is None:
676 return '<none> '
677 return '%08x' % value
678
679 @staticmethod
Simon Glass1be70d22018-07-17 13:25:49 -0600680 def WriteMapLine(fd, indent, name, offset, size, image_pos):
Simon Glass163ed6c2018-09-14 04:57:36 -0600681 print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
682 Entry.GetStr(offset), Entry.GetStr(size),
683 name), file=fd)
Simon Glass8122f392018-07-17 13:25:28 -0600684
Simon Glass3b0c3822018-06-01 09:38:20 -0600685 def WriteMap(self, fd, indent):
686 """Write a map of the entry to a .map file
687
688 Args:
689 fd: File to write the map to
690 indent: Curent indent level of map (0=none, 1=one level, etc.)
691 """
Simon Glass1be70d22018-07-17 13:25:49 -0600692 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
693 self.image_pos)
Simon Glass53af22a2018-07-17 13:25:32 -0600694
Simon Glassd626e822022-08-13 11:40:50 -0600695 # pylint: disable=assignment-from-none
Simon Glass11e36cc2018-07-17 13:25:38 -0600696 def GetEntries(self):
697 """Return a list of entries contained by this entry
698
699 Returns:
700 List of entries, or None if none. A normal entry has no entries
701 within it so will return None
702 """
703 return None
704
Simon Glassd626e822022-08-13 11:40:50 -0600705 def FindEntryByNode(self, find_node):
706 """Find a node in an entry, searching all subentries
707
708 This does a recursive search.
709
710 Args:
711 find_node (fdt.Node): Node to find
712
713 Returns:
714 Entry: entry, if found, else None
715 """
716 entries = self.GetEntries()
717 if entries:
718 for entry in entries.values():
719 if entry._node == find_node:
720 return entry
721 found = entry.FindEntryByNode(find_node)
722 if found:
723 return found
724
725 return None
726
Simon Glass53af22a2018-07-17 13:25:32 -0600727 def GetArg(self, name, datatype=str):
728 """Get the value of an entry argument or device-tree-node property
729
730 Some node properties can be provided as arguments to binman. First check
731 the entry arguments, and fall back to the device tree if not found
732
733 Args:
734 name: Argument name
735 datatype: Data type (str or int)
736
737 Returns:
738 Value of argument as a string or int, or None if no value
739
740 Raises:
741 ValueError if the argument cannot be converted to in
742 """
Simon Glassc55a50f2018-09-14 04:57:19 -0600743 value = state.GetEntryArg(name)
Simon Glass53af22a2018-07-17 13:25:32 -0600744 if value is not None:
745 if datatype == int:
746 try:
747 value = int(value)
748 except ValueError:
749 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
750 (name, value))
751 elif datatype == str:
752 pass
753 else:
754 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
755 datatype)
756 else:
757 value = fdt_util.GetDatatype(self._node, name, datatype)
758 return value
Simon Glassfd8d1f72018-07-17 13:25:36 -0600759
760 @staticmethod
761 def WriteDocs(modules, test_missing=None):
762 """Write out documentation about the various entry types to stdout
763
764 Args:
765 modules: List of modules to include
766 test_missing: Used for testing. This is a module to report
767 as missing
768 """
769 print('''Binman Entry Documentation
770===========================
771
772This file describes the entry types supported by binman. These entry types can
773be placed in an image one by one to build up a final firmware image. It is
774fairly easy to create new entry types. Just add a new file to the 'etype'
775directory. You can use the existing entries as examples.
776
777Note that some entries are subclasses of others, using and extending their
778features to produce new behaviours.
779
780
781''')
782 modules = sorted(modules)
783
784 # Don't show the test entry
785 if '_testing' in modules:
786 modules.remove('_testing')
787 missing = []
788 for name in modules:
Simon Glassb35fb172021-03-18 20:25:04 +1300789 module = Entry.Lookup('WriteDocs', name, False)
Simon Glassfd8d1f72018-07-17 13:25:36 -0600790 docs = getattr(module, '__doc__')
791 if test_missing == name:
792 docs = None
793 if docs:
794 lines = docs.splitlines()
795 first_line = lines[0]
796 rest = [line[4:] for line in lines[1:]]
797 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
Simon Glass228c9b82022-08-07 16:33:25 -0600798
799 # Create a reference for use by rST docs
800 ref_name = f'etype_{module.__name__[6:]}'.lower()
801 print('.. _%s:' % ref_name)
802 print()
Simon Glassfd8d1f72018-07-17 13:25:36 -0600803 print(hdr)
804 print('-' * len(hdr))
805 print('\n'.join(rest))
806 print()
807 print()
808 else:
809 missing.append(name)
810
811 if missing:
812 raise ValueError('Documentation is missing for modules: %s' %
813 ', '.join(missing))
Simon Glassa326b492018-09-14 04:57:11 -0600814
815 def GetUniqueName(self):
816 """Get a unique name for a node
817
818 Returns:
819 String containing a unique name for a node, consisting of the name
820 of all ancestors (starting from within the 'binman' node) separated
821 by a dot ('.'). This can be useful for generating unique filesnames
822 in the output directory.
823 """
824 name = self.name
825 node = self._node
826 while node.parent:
827 node = node.parent
Alper Nebi Yasak67bf2c82022-03-27 18:31:44 +0300828 if node.name in ('binman', '/'):
Simon Glassa326b492018-09-14 04:57:11 -0600829 break
830 name = '%s.%s' % (node.name, name)
831 return name
Simon Glassba64a0b2018-09-14 04:57:29 -0600832
Simon Glass80a66ae2022-03-05 20:18:59 -0700833 def extend_to_limit(self, limit):
834 """Extend an entry so that it ends at the given offset limit"""
Simon Glassba64a0b2018-09-14 04:57:29 -0600835 if self.offset + self.size < limit:
836 self.size = limit - self.offset
837 # Request the contents again, since changing the size requires that
838 # the data grows. This should not fail, but check it to be sure.
839 if not self.ObtainContents():
840 self.Raise('Cannot obtain contents when expanding entry')
Simon Glassfa1c9372019-07-08 13:18:38 -0600841
842 def HasSibling(self, name):
843 """Check if there is a sibling of a given name
844
845 Returns:
846 True if there is an entry with this name in the the same section,
847 else False
848 """
849 return name in self.section.GetEntries()
Simon Glasscf228942019-07-08 14:25:28 -0600850
851 def GetSiblingImagePos(self, name):
852 """Return the image position of the given sibling
853
854 Returns:
855 Image position of sibling, or None if the sibling has no position,
856 or False if there is no such sibling
857 """
858 if not self.HasSibling(name):
859 return False
860 return self.section.GetEntries()[name].image_pos
Simon Glass41b8ba02019-07-08 14:25:43 -0600861
862 @staticmethod
863 def AddEntryInfo(entries, indent, name, etype, size, image_pos,
864 uncomp_size, offset, entry):
865 """Add a new entry to the entries list
866
867 Args:
868 entries: List (of EntryInfo objects) to add to
869 indent: Current indent level to add to list
870 name: Entry name (string)
871 etype: Entry type (string)
872 size: Entry size in bytes (int)
873 image_pos: Position within image in bytes (int)
874 uncomp_size: Uncompressed size if the entry uses compression, else
875 None
876 offset: Entry offset within parent in bytes (int)
877 entry: Entry object
878 """
879 entries.append(EntryInfo(indent, name, etype, size, image_pos,
880 uncomp_size, offset, entry))
881
882 def ListEntries(self, entries, indent):
883 """Add files in this entry to the list of entries
884
885 This can be overridden by subclasses which need different behaviour.
886
887 Args:
888 entries: List (of EntryInfo objects) to add to
889 indent: Current indent level to add to list
890 """
891 self.AddEntryInfo(entries, indent, self.name, self.etype, self.size,
892 self.image_pos, self.uncomp_size, self.offset, self)
Simon Glassf667e452019-07-08 14:25:50 -0600893
Simon Glass943bf782021-11-23 21:09:50 -0700894 def ReadData(self, decomp=True, alt_format=None):
Simon Glassf667e452019-07-08 14:25:50 -0600895 """Read the data for an entry from the image
896
897 This is used when the image has been read in and we want to extract the
898 data for a particular entry from that image.
899
900 Args:
901 decomp: True to decompress any compressed data before returning it;
902 False to return the raw, uncompressed data
903
904 Returns:
905 Entry data (bytes)
906 """
907 # Use True here so that we get an uncompressed section to work from,
908 # although compressed sections are currently not supported
Simon Glassf3385a52022-01-29 14:14:15 -0700909 tout.debug("ReadChildData section '%s', entry '%s'" %
Simon Glass2d553c02019-09-25 08:56:21 -0600910 (self.section.GetPath(), self.GetPath()))
Simon Glass943bf782021-11-23 21:09:50 -0700911 data = self.section.ReadChildData(self, decomp, alt_format)
Simon Glassa9cd39e2019-07-20 12:24:04 -0600912 return data
Simon Glassd5079332019-07-20 12:23:41 -0600913
Simon Glass943bf782021-11-23 21:09:50 -0700914 def ReadChildData(self, child, decomp=True, alt_format=None):
Simon Glass2d553c02019-09-25 08:56:21 -0600915 """Read the data for a particular child entry
Simon Glass4e185e82019-09-25 08:56:20 -0600916
917 This reads data from the parent and extracts the piece that relates to
918 the given child.
919
920 Args:
Simon Glass943bf782021-11-23 21:09:50 -0700921 child (Entry): Child entry to read data for (must be valid)
922 decomp (bool): True to decompress any compressed data before
923 returning it; False to return the raw, uncompressed data
924 alt_format (str): Alternative format to read in, or None
Simon Glass4e185e82019-09-25 08:56:20 -0600925
926 Returns:
927 Data for the child (bytes)
928 """
929 pass
930
Simon Glassd5079332019-07-20 12:23:41 -0600931 def LoadData(self, decomp=True):
932 data = self.ReadData(decomp)
Simon Glass10f9d002019-07-20 12:23:50 -0600933 self.contents_size = len(data)
Simon Glassd5079332019-07-20 12:23:41 -0600934 self.ProcessContentsUpdate(data)
935 self.Detail('Loaded data size %x' % len(data))
Simon Glassc5ad04b2019-07-20 12:23:46 -0600936
Simon Glass943bf782021-11-23 21:09:50 -0700937 def GetAltFormat(self, data, alt_format):
938 """Read the data for an extry in an alternative format
939
940 Supported formats are list in the documentation for each entry. An
941 example is fdtmap which provides .
942
943 Args:
944 data (bytes): Data to convert (this should have been produced by the
945 entry)
946 alt_format (str): Format to use
947
948 """
949 pass
950
Simon Glassc5ad04b2019-07-20 12:23:46 -0600951 def GetImage(self):
952 """Get the image containing this entry
953
954 Returns:
955 Image object containing this entry
956 """
957 return self.section.GetImage()
Simon Glass10f9d002019-07-20 12:23:50 -0600958
959 def WriteData(self, data, decomp=True):
960 """Write the data to an entry in the image
961
962 This is used when the image has been read in and we want to replace the
963 data for a particular entry in that image.
964
965 The image must be re-packed and written out afterwards.
966
967 Args:
968 data: Data to replace it with
969 decomp: True to compress the data if needed, False if data is
970 already compressed so should be used as is
971
972 Returns:
973 True if the data did not result in a resize of this entry, False if
974 the entry must be resized
975 """
Simon Glass9a5d3dc2019-10-31 07:43:02 -0600976 if self.size is not None:
977 self.contents_size = self.size
978 else:
979 self.contents_size = self.pre_reset_size
Simon Glass10f9d002019-07-20 12:23:50 -0600980 ok = self.ProcessContentsUpdate(data)
981 self.Detail('WriteData: size=%x, ok=%s' % (len(data), ok))
Simon Glass7210c892019-07-20 12:24:05 -0600982 section_ok = self.section.WriteChildData(self)
983 return ok and section_ok
984
985 def WriteChildData(self, child):
986 """Handle writing the data in a child entry
987
988 This should be called on the child's parent section after the child's
Simon Glass557693e2021-11-23 11:03:44 -0700989 data has been updated. It should update any data structures needed to
990 validate that the update is successful.
Simon Glass7210c892019-07-20 12:24:05 -0600991
992 This base-class implementation does nothing, since the base Entry object
993 does not have any children.
994
995 Args:
996 child: Child Entry that was written
997
998 Returns:
999 True if the section could be updated successfully, False if the
Simon Glass557693e2021-11-23 11:03:44 -07001000 data is such that the section could not update
Simon Glass7210c892019-07-20 12:24:05 -06001001 """
1002 return True
Simon Glasseba1f0c2019-07-20 12:23:55 -06001003
1004 def GetSiblingOrder(self):
1005 """Get the relative order of an entry amoung its siblings
1006
1007 Returns:
1008 'start' if this entry is first among siblings, 'end' if last,
1009 otherwise None
1010 """
1011 entries = list(self.section.GetEntries().values())
1012 if entries:
1013 if self == entries[0]:
1014 return 'start'
1015 elif self == entries[-1]:
1016 return 'end'
1017 return 'middle'
Simon Glass4f9f1052020-07-09 18:39:38 -06001018
1019 def SetAllowMissing(self, allow_missing):
1020 """Set whether a section allows missing external blobs
1021
1022 Args:
1023 allow_missing: True if allowed, False if not allowed
1024 """
1025 # This is meaningless for anything other than sections
1026 pass
Simon Glassb1cca952020-07-09 18:39:40 -06001027
Heiko Thierya89c8f22022-01-06 11:49:41 +01001028 def SetAllowFakeBlob(self, allow_fake):
1029 """Set whether a section allows to create a fake blob
1030
1031 Args:
1032 allow_fake: True if allowed, False if not allowed
1033 """
Simon Glassf4590e02022-01-09 20:13:46 -07001034 self.allow_fake = allow_fake
Heiko Thierya89c8f22022-01-06 11:49:41 +01001035
Simon Glassb1cca952020-07-09 18:39:40 -06001036 def CheckMissing(self, missing_list):
1037 """Check if any entries in this section have missing external blobs
1038
1039 If there are missing blobs, the entries are added to the list
1040
1041 Args:
1042 missing_list: List of Entry objects to be added to
1043 """
1044 if self.missing:
1045 missing_list.append(self)
Simon Glass87958982020-09-01 05:13:57 -06001046
Simon Glass3817ad42022-03-05 20:19:04 -07001047 def check_fake_fname(self, fname, size=0):
Simon Glass790ba9f2022-01-12 13:10:36 -07001048 """If the file is missing and the entry allows fake blobs, fake it
1049
1050 Sets self.faked to True if faked
1051
1052 Args:
1053 fname (str): Filename to check
Simon Glass3817ad42022-03-05 20:19:04 -07001054 size (int): Size of fake file to create
Simon Glass790ba9f2022-01-12 13:10:36 -07001055
1056 Returns:
Simon Glass9a0a2e92022-03-05 20:19:03 -07001057 tuple:
1058 fname (str): Filename of faked file
1059 bool: True if the blob was faked, False if not
Simon Glass790ba9f2022-01-12 13:10:36 -07001060 """
1061 if self.allow_fake and not pathlib.Path(fname).is_file():
Simon Glass7960a0a2022-08-07 09:46:46 -06001062 if not self.fake_fname:
1063 outfname = os.path.join(self.fake_dir, os.path.basename(fname))
1064 with open(outfname, "wb") as out:
1065 out.truncate(size)
1066 tout.info(f"Entry '{self._node.path}': Faked blob '{outfname}'")
1067 self.fake_fname = outfname
Simon Glass790ba9f2022-01-12 13:10:36 -07001068 self.faked = True
Simon Glass7960a0a2022-08-07 09:46:46 -06001069 return self.fake_fname, True
Simon Glass9a0a2e92022-03-05 20:19:03 -07001070 return fname, False
Simon Glass790ba9f2022-01-12 13:10:36 -07001071
Heiko Thierya89c8f22022-01-06 11:49:41 +01001072 def CheckFakedBlobs(self, faked_blobs_list):
1073 """Check if any entries in this section have faked external blobs
1074
1075 If there are faked blobs, the entries are added to the list
1076
1077 Args:
1078 fake_blobs_list: List of Entry objects to be added to
1079 """
1080 # This is meaningless for anything other than blobs
1081 pass
1082
Simon Glass87958982020-09-01 05:13:57 -06001083 def GetAllowMissing(self):
1084 """Get whether a section allows missing external blobs
1085
1086 Returns:
1087 True if allowed, False if not allowed
1088 """
1089 return self.allow_missing
Simon Glassb2381432020-09-06 10:39:09 -06001090
Simon Glass4f9ee832022-01-09 20:14:09 -07001091 def record_missing_bintool(self, bintool):
1092 """Record a missing bintool that was needed to produce this entry
1093
1094 Args:
1095 bintool (Bintool): Bintool that was missing
1096 """
Stefan Herbrechtsmeierfacc3782022-08-19 16:25:19 +02001097 if bintool not in self.missing_bintools:
1098 self.missing_bintools.append(bintool)
Simon Glass4f9ee832022-01-09 20:14:09 -07001099
1100 def check_missing_bintools(self, missing_list):
1101 """Check if any entries in this section have missing bintools
1102
1103 If there are missing bintools, these are added to the list
1104
1105 Args:
1106 missing_list: List of Bintool objects to be added to
1107 """
Stefan Herbrechtsmeierfacc3782022-08-19 16:25:19 +02001108 for bintool in self.missing_bintools:
1109 if bintool not in missing_list:
1110 missing_list.append(bintool)
1111
Simon Glass4f9ee832022-01-09 20:14:09 -07001112
Simon Glassb2381432020-09-06 10:39:09 -06001113 def GetHelpTags(self):
1114 """Get the tags use for missing-blob help
1115
1116 Returns:
1117 list of possible tags, most desirable first
1118 """
1119 return list(filter(None, [self.missing_msg, self.name, self.etype]))
Simon Glass87c96292020-10-26 17:40:06 -06001120
1121 def CompressData(self, indata):
1122 """Compress data according to the entry's compression method
1123
1124 Args:
1125 indata: Data to compress
1126
1127 Returns:
Stefan Herbrechtsmeier4f463e32022-08-19 16:25:27 +02001128 Compressed data
Simon Glass87c96292020-10-26 17:40:06 -06001129 """
Simon Glass97c3e9a2020-10-26 17:40:15 -06001130 self.uncomp_data = indata
Simon Glass87c96292020-10-26 17:40:06 -06001131 if self.compress != 'none':
1132 self.uncomp_size = len(indata)
Stefan Herbrechtsmeierc3665a82022-08-19 16:25:31 +02001133 if self.comp_bintool.is_present():
1134 data = self.comp_bintool.compress(indata)
1135 else:
1136 self.record_missing_bintool(self.comp_bintool)
1137 data = tools.get_bytes(0, 1024)
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001138 else:
1139 data = indata
Simon Glass87c96292020-10-26 17:40:06 -06001140 return data
Simon Glassb35fb172021-03-18 20:25:04 +13001141
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001142 def DecompressData(self, indata):
1143 """Decompress data according to the entry's compression method
1144
1145 Args:
1146 indata: Data to decompress
1147
1148 Returns:
1149 Decompressed data
1150 """
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001151 if self.compress != 'none':
Stefan Herbrechtsmeierc3665a82022-08-19 16:25:31 +02001152 if self.comp_bintool.is_present():
1153 data = self.comp_bintool.decompress(indata)
1154 self.uncomp_size = len(data)
1155 else:
1156 self.record_missing_bintool(self.comp_bintool)
1157 data = tools.get_bytes(0, 1024)
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001158 else:
1159 data = indata
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001160 self.uncomp_data = data
1161 return data
1162
Simon Glassb35fb172021-03-18 20:25:04 +13001163 @classmethod
1164 def UseExpanded(cls, node, etype, new_etype):
1165 """Check whether to use an expanded entry type
1166
1167 This is called by Entry.Create() when it finds an expanded version of
1168 an entry type (e.g. 'u-boot-expanded'). If this method returns True then
1169 it will be used (e.g. in place of 'u-boot'). If it returns False, it is
1170 ignored.
1171
1172 Args:
1173 node: Node object containing information about the entry to
1174 create
1175 etype: Original entry type being used
1176 new_etype: New entry type proposed
1177
1178 Returns:
1179 True to use this entry type, False to use the original one
1180 """
Simon Glassf3385a52022-01-29 14:14:15 -07001181 tout.info("Node '%s': etype '%s': %s selected" %
Simon Glassb35fb172021-03-18 20:25:04 +13001182 (node.path, etype, new_etype))
1183 return True
Simon Glass943bf782021-11-23 21:09:50 -07001184
1185 def CheckAltFormats(self, alt_formats):
1186 """Add any alternative formats supported by this entry type
1187
1188 Args:
1189 alt_formats (dict): Dict to add alt_formats to:
1190 key: Name of alt format
1191 value: Help text
1192 """
1193 pass
Simon Glass386c63c2022-01-09 20:13:50 -07001194
Simon Glassae9a4572022-03-05 20:19:02 -07001195 def AddBintools(self, btools):
Simon Glass386c63c2022-01-09 20:13:50 -07001196 """Add the bintools used by this entry type
1197
1198 Args:
Simon Glassae9a4572022-03-05 20:19:02 -07001199 btools (dict of Bintool):
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001200
1201 Raise:
1202 ValueError if compression algorithm is not supported
Simon Glass386c63c2022-01-09 20:13:50 -07001203 """
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001204 algo = self.compress
1205 if algo != 'none':
Stefan Herbrechtsmeiercd15b642022-08-19 16:25:38 +02001206 algos = ['bzip2', 'gzip', 'lz4', 'lzma', 'lzo', 'xz', 'zstd']
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001207 if algo not in algos:
1208 raise ValueError("Unknown algorithm '%s'" % algo)
Stefan Herbrechtsmeier7b26a462022-08-19 16:25:36 +02001209 names = {'lzma': 'lzma_alone', 'lzo': 'lzop'}
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001210 name = names.get(self.compress, self.compress)
1211 self.comp_bintool = self.AddBintool(btools, name)
Simon Glass386c63c2022-01-09 20:13:50 -07001212
1213 @classmethod
1214 def AddBintool(self, tools, name):
1215 """Add a new bintool to the tools used by this etype
1216
1217 Args:
1218 name: Name of the tool
1219 """
1220 btool = bintool.Bintool.create(name)
1221 tools[name] = btool
1222 return btool
Alper Nebi Yasakee813c82022-02-09 22:02:35 +03001223
1224 def SetUpdateHash(self, update_hash):
1225 """Set whether this entry's "hash" subnode should be updated
1226
1227 Args:
1228 update_hash: True if hash should be updated, False if not
1229 """
1230 self.update_hash = update_hash
Simon Glass81b71c32022-02-08 11:50:00 -07001231
Simon Glass72e423c2022-03-05 20:19:05 -07001232 def collect_contents_to_file(self, entries, prefix, fake_size=0):
Simon Glass81b71c32022-02-08 11:50:00 -07001233 """Put the contents of a list of entries into a file
1234
1235 Args:
1236 entries (list of Entry): Entries to collect
1237 prefix (str): Filename prefix of file to write to
Simon Glass72e423c2022-03-05 20:19:05 -07001238 fake_size (int): Size of fake file to create if needed
Simon Glass81b71c32022-02-08 11:50:00 -07001239
1240 If any entry does not have contents yet, this function returns False
1241 for the data.
1242
1243 Returns:
1244 Tuple:
Simon Glass6d427c42022-03-05 20:18:58 -07001245 bytes: Concatenated data from all the entries (or None)
1246 str: Filename of file written (or None if no data)
1247 str: Unique portion of filename (or None if no data)
Simon Glass81b71c32022-02-08 11:50:00 -07001248 """
1249 data = b''
1250 for entry in entries:
1251 # First get the input data and put it in a file. If not available,
1252 # try later.
Simon Glass72e423c2022-03-05 20:19:05 -07001253 if not entry.ObtainContents(fake_size=fake_size):
Simon Glass6d427c42022-03-05 20:18:58 -07001254 return None, None, None
Simon Glass81b71c32022-02-08 11:50:00 -07001255 data += entry.GetData()
1256 uniq = self.GetUniqueName()
1257 fname = tools.get_output_filename(f'{prefix}.{uniq}')
1258 tools.write_file(fname, data)
1259 return data, fname, uniq
Simon Glass7960a0a2022-08-07 09:46:46 -06001260
1261 @classmethod
1262 def create_fake_dir(cls):
1263 """Create the directory for fake files"""
1264 cls.fake_dir = tools.get_output_filename('binman-fake')
1265 if not os.path.exists(cls.fake_dir):
1266 os.mkdir(cls.fake_dir)
1267 tout.notice(f"Fake-blob dir is '{cls.fake_dir}'")
Simon Glasscdadada2022-08-13 11:40:44 -06001268
1269 def ensure_props(self):
1270 """Raise an exception if properties are missing
1271
1272 Args:
1273 prop_list (list of str): List of properties to check for
1274
1275 Raises:
1276 ValueError: Any property is missing
1277 """
1278 not_present = []
1279 for prop in self.required_props:
1280 if not prop in self._node.props:
1281 not_present.append(prop)
1282 if not_present:
1283 self.Raise(f"'{self.etype}' entry is missing properties: {' '.join(not_present)}")