blob: bdf53ddd922eef1cc4e2a9de2e136783cbc4ba0a [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:
659 elf.LookupAndWriteSymbols(self.elf_fname, self, section.GetImage())
Simon Glass18546952018-06-01 09:38:16 -0600660
Simon Glass6ddd6112020-10-26 17:40:18 -0600661 def CheckEntries(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600662 """Check that the entry offsets are correct
Simon Glass18546952018-06-01 09:38:16 -0600663
Simon Glass3ab95982018-08-01 15:22:37 -0600664 This is used for entries which have extra offset requirements (other
Simon Glass18546952018-06-01 09:38:16 -0600665 than having to be fully inside their section). Sub-classes can implement
666 this function and raise if there is a problem.
667 """
668 pass
Simon Glass3b0c3822018-06-01 09:38:20 -0600669
Simon Glass8122f392018-07-17 13:25:28 -0600670 @staticmethod
Simon Glass163ed6c2018-09-14 04:57:36 -0600671 def GetStr(value):
672 if value is None:
673 return '<none> '
674 return '%08x' % value
675
676 @staticmethod
Simon Glass1be70d22018-07-17 13:25:49 -0600677 def WriteMapLine(fd, indent, name, offset, size, image_pos):
Simon Glass163ed6c2018-09-14 04:57:36 -0600678 print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
679 Entry.GetStr(offset), Entry.GetStr(size),
680 name), file=fd)
Simon Glass8122f392018-07-17 13:25:28 -0600681
Simon Glass3b0c3822018-06-01 09:38:20 -0600682 def WriteMap(self, fd, indent):
683 """Write a map of the entry to a .map file
684
685 Args:
686 fd: File to write the map to
687 indent: Curent indent level of map (0=none, 1=one level, etc.)
688 """
Simon Glass1be70d22018-07-17 13:25:49 -0600689 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
690 self.image_pos)
Simon Glass53af22a2018-07-17 13:25:32 -0600691
Simon Glassd626e822022-08-13 11:40:50 -0600692 # pylint: disable=assignment-from-none
Simon Glass11e36cc2018-07-17 13:25:38 -0600693 def GetEntries(self):
694 """Return a list of entries contained by this entry
695
696 Returns:
697 List of entries, or None if none. A normal entry has no entries
698 within it so will return None
699 """
700 return None
701
Simon Glassd626e822022-08-13 11:40:50 -0600702 def FindEntryByNode(self, find_node):
703 """Find a node in an entry, searching all subentries
704
705 This does a recursive search.
706
707 Args:
708 find_node (fdt.Node): Node to find
709
710 Returns:
711 Entry: entry, if found, else None
712 """
713 entries = self.GetEntries()
714 if entries:
715 for entry in entries.values():
716 if entry._node == find_node:
717 return entry
718 found = entry.FindEntryByNode(find_node)
719 if found:
720 return found
721
722 return None
723
Simon Glass53af22a2018-07-17 13:25:32 -0600724 def GetArg(self, name, datatype=str):
725 """Get the value of an entry argument or device-tree-node property
726
727 Some node properties can be provided as arguments to binman. First check
728 the entry arguments, and fall back to the device tree if not found
729
730 Args:
731 name: Argument name
732 datatype: Data type (str or int)
733
734 Returns:
735 Value of argument as a string or int, or None if no value
736
737 Raises:
738 ValueError if the argument cannot be converted to in
739 """
Simon Glassc55a50f2018-09-14 04:57:19 -0600740 value = state.GetEntryArg(name)
Simon Glass53af22a2018-07-17 13:25:32 -0600741 if value is not None:
742 if datatype == int:
743 try:
744 value = int(value)
745 except ValueError:
746 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
747 (name, value))
748 elif datatype == str:
749 pass
750 else:
751 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
752 datatype)
753 else:
754 value = fdt_util.GetDatatype(self._node, name, datatype)
755 return value
Simon Glassfd8d1f72018-07-17 13:25:36 -0600756
757 @staticmethod
758 def WriteDocs(modules, test_missing=None):
759 """Write out documentation about the various entry types to stdout
760
761 Args:
762 modules: List of modules to include
763 test_missing: Used for testing. This is a module to report
764 as missing
765 """
766 print('''Binman Entry Documentation
767===========================
768
769This file describes the entry types supported by binman. These entry types can
770be placed in an image one by one to build up a final firmware image. It is
771fairly easy to create new entry types. Just add a new file to the 'etype'
772directory. You can use the existing entries as examples.
773
774Note that some entries are subclasses of others, using and extending their
775features to produce new behaviours.
776
777
778''')
779 modules = sorted(modules)
780
781 # Don't show the test entry
782 if '_testing' in modules:
783 modules.remove('_testing')
784 missing = []
785 for name in modules:
Simon Glassb35fb172021-03-18 20:25:04 +1300786 module = Entry.Lookup('WriteDocs', name, False)
Simon Glassfd8d1f72018-07-17 13:25:36 -0600787 docs = getattr(module, '__doc__')
788 if test_missing == name:
789 docs = None
790 if docs:
791 lines = docs.splitlines()
792 first_line = lines[0]
793 rest = [line[4:] for line in lines[1:]]
794 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
Simon Glass228c9b82022-08-07 16:33:25 -0600795
796 # Create a reference for use by rST docs
797 ref_name = f'etype_{module.__name__[6:]}'.lower()
798 print('.. _%s:' % ref_name)
799 print()
Simon Glassfd8d1f72018-07-17 13:25:36 -0600800 print(hdr)
801 print('-' * len(hdr))
802 print('\n'.join(rest))
803 print()
804 print()
805 else:
806 missing.append(name)
807
808 if missing:
809 raise ValueError('Documentation is missing for modules: %s' %
810 ', '.join(missing))
Simon Glassa326b492018-09-14 04:57:11 -0600811
812 def GetUniqueName(self):
813 """Get a unique name for a node
814
815 Returns:
816 String containing a unique name for a node, consisting of the name
817 of all ancestors (starting from within the 'binman' node) separated
818 by a dot ('.'). This can be useful for generating unique filesnames
819 in the output directory.
820 """
821 name = self.name
822 node = self._node
823 while node.parent:
824 node = node.parent
Alper Nebi Yasak67bf2c82022-03-27 18:31:44 +0300825 if node.name in ('binman', '/'):
Simon Glassa326b492018-09-14 04:57:11 -0600826 break
827 name = '%s.%s' % (node.name, name)
828 return name
Simon Glassba64a0b2018-09-14 04:57:29 -0600829
Simon Glass80a66ae2022-03-05 20:18:59 -0700830 def extend_to_limit(self, limit):
831 """Extend an entry so that it ends at the given offset limit"""
Simon Glassba64a0b2018-09-14 04:57:29 -0600832 if self.offset + self.size < limit:
833 self.size = limit - self.offset
834 # Request the contents again, since changing the size requires that
835 # the data grows. This should not fail, but check it to be sure.
836 if not self.ObtainContents():
837 self.Raise('Cannot obtain contents when expanding entry')
Simon Glassfa1c9372019-07-08 13:18:38 -0600838
839 def HasSibling(self, name):
840 """Check if there is a sibling of a given name
841
842 Returns:
843 True if there is an entry with this name in the the same section,
844 else False
845 """
846 return name in self.section.GetEntries()
Simon Glasscf228942019-07-08 14:25:28 -0600847
848 def GetSiblingImagePos(self, name):
849 """Return the image position of the given sibling
850
851 Returns:
852 Image position of sibling, or None if the sibling has no position,
853 or False if there is no such sibling
854 """
855 if not self.HasSibling(name):
856 return False
857 return self.section.GetEntries()[name].image_pos
Simon Glass41b8ba02019-07-08 14:25:43 -0600858
859 @staticmethod
860 def AddEntryInfo(entries, indent, name, etype, size, image_pos,
861 uncomp_size, offset, entry):
862 """Add a new entry to the entries list
863
864 Args:
865 entries: List (of EntryInfo objects) to add to
866 indent: Current indent level to add to list
867 name: Entry name (string)
868 etype: Entry type (string)
869 size: Entry size in bytes (int)
870 image_pos: Position within image in bytes (int)
871 uncomp_size: Uncompressed size if the entry uses compression, else
872 None
873 offset: Entry offset within parent in bytes (int)
874 entry: Entry object
875 """
876 entries.append(EntryInfo(indent, name, etype, size, image_pos,
877 uncomp_size, offset, entry))
878
879 def ListEntries(self, entries, indent):
880 """Add files in this entry to the list of entries
881
882 This can be overridden by subclasses which need different behaviour.
883
884 Args:
885 entries: List (of EntryInfo objects) to add to
886 indent: Current indent level to add to list
887 """
888 self.AddEntryInfo(entries, indent, self.name, self.etype, self.size,
889 self.image_pos, self.uncomp_size, self.offset, self)
Simon Glassf667e452019-07-08 14:25:50 -0600890
Simon Glass943bf782021-11-23 21:09:50 -0700891 def ReadData(self, decomp=True, alt_format=None):
Simon Glassf667e452019-07-08 14:25:50 -0600892 """Read the data for an entry from the image
893
894 This is used when the image has been read in and we want to extract the
895 data for a particular entry from that image.
896
897 Args:
898 decomp: True to decompress any compressed data before returning it;
899 False to return the raw, uncompressed data
900
901 Returns:
902 Entry data (bytes)
903 """
904 # Use True here so that we get an uncompressed section to work from,
905 # although compressed sections are currently not supported
Simon Glassf3385a52022-01-29 14:14:15 -0700906 tout.debug("ReadChildData section '%s', entry '%s'" %
Simon Glass2d553c02019-09-25 08:56:21 -0600907 (self.section.GetPath(), self.GetPath()))
Simon Glass943bf782021-11-23 21:09:50 -0700908 data = self.section.ReadChildData(self, decomp, alt_format)
Simon Glassa9cd39e2019-07-20 12:24:04 -0600909 return data
Simon Glassd5079332019-07-20 12:23:41 -0600910
Simon Glass943bf782021-11-23 21:09:50 -0700911 def ReadChildData(self, child, decomp=True, alt_format=None):
Simon Glass2d553c02019-09-25 08:56:21 -0600912 """Read the data for a particular child entry
Simon Glass4e185e82019-09-25 08:56:20 -0600913
914 This reads data from the parent and extracts the piece that relates to
915 the given child.
916
917 Args:
Simon Glass943bf782021-11-23 21:09:50 -0700918 child (Entry): Child entry to read data for (must be valid)
919 decomp (bool): True to decompress any compressed data before
920 returning it; False to return the raw, uncompressed data
921 alt_format (str): Alternative format to read in, or None
Simon Glass4e185e82019-09-25 08:56:20 -0600922
923 Returns:
924 Data for the child (bytes)
925 """
926 pass
927
Simon Glassd5079332019-07-20 12:23:41 -0600928 def LoadData(self, decomp=True):
929 data = self.ReadData(decomp)
Simon Glass10f9d002019-07-20 12:23:50 -0600930 self.contents_size = len(data)
Simon Glassd5079332019-07-20 12:23:41 -0600931 self.ProcessContentsUpdate(data)
932 self.Detail('Loaded data size %x' % len(data))
Simon Glassc5ad04b2019-07-20 12:23:46 -0600933
Simon Glass943bf782021-11-23 21:09:50 -0700934 def GetAltFormat(self, data, alt_format):
935 """Read the data for an extry in an alternative format
936
937 Supported formats are list in the documentation for each entry. An
938 example is fdtmap which provides .
939
940 Args:
941 data (bytes): Data to convert (this should have been produced by the
942 entry)
943 alt_format (str): Format to use
944
945 """
946 pass
947
Simon Glassc5ad04b2019-07-20 12:23:46 -0600948 def GetImage(self):
949 """Get the image containing this entry
950
951 Returns:
952 Image object containing this entry
953 """
954 return self.section.GetImage()
Simon Glass10f9d002019-07-20 12:23:50 -0600955
956 def WriteData(self, data, decomp=True):
957 """Write the data to an entry in the image
958
959 This is used when the image has been read in and we want to replace the
960 data for a particular entry in that image.
961
962 The image must be re-packed and written out afterwards.
963
964 Args:
965 data: Data to replace it with
966 decomp: True to compress the data if needed, False if data is
967 already compressed so should be used as is
968
969 Returns:
970 True if the data did not result in a resize of this entry, False if
971 the entry must be resized
972 """
Simon Glass9a5d3dc2019-10-31 07:43:02 -0600973 if self.size is not None:
974 self.contents_size = self.size
975 else:
976 self.contents_size = self.pre_reset_size
Simon Glass10f9d002019-07-20 12:23:50 -0600977 ok = self.ProcessContentsUpdate(data)
978 self.Detail('WriteData: size=%x, ok=%s' % (len(data), ok))
Simon Glass7210c892019-07-20 12:24:05 -0600979 section_ok = self.section.WriteChildData(self)
980 return ok and section_ok
981
982 def WriteChildData(self, child):
983 """Handle writing the data in a child entry
984
985 This should be called on the child's parent section after the child's
Simon Glass557693e2021-11-23 11:03:44 -0700986 data has been updated. It should update any data structures needed to
987 validate that the update is successful.
Simon Glass7210c892019-07-20 12:24:05 -0600988
989 This base-class implementation does nothing, since the base Entry object
990 does not have any children.
991
992 Args:
993 child: Child Entry that was written
994
995 Returns:
996 True if the section could be updated successfully, False if the
Simon Glass557693e2021-11-23 11:03:44 -0700997 data is such that the section could not update
Simon Glass7210c892019-07-20 12:24:05 -0600998 """
999 return True
Simon Glasseba1f0c2019-07-20 12:23:55 -06001000
1001 def GetSiblingOrder(self):
1002 """Get the relative order of an entry amoung its siblings
1003
1004 Returns:
1005 'start' if this entry is first among siblings, 'end' if last,
1006 otherwise None
1007 """
1008 entries = list(self.section.GetEntries().values())
1009 if entries:
1010 if self == entries[0]:
1011 return 'start'
1012 elif self == entries[-1]:
1013 return 'end'
1014 return 'middle'
Simon Glass4f9f1052020-07-09 18:39:38 -06001015
1016 def SetAllowMissing(self, allow_missing):
1017 """Set whether a section allows missing external blobs
1018
1019 Args:
1020 allow_missing: True if allowed, False if not allowed
1021 """
1022 # This is meaningless for anything other than sections
1023 pass
Simon Glassb1cca952020-07-09 18:39:40 -06001024
Heiko Thierya89c8f22022-01-06 11:49:41 +01001025 def SetAllowFakeBlob(self, allow_fake):
1026 """Set whether a section allows to create a fake blob
1027
1028 Args:
1029 allow_fake: True if allowed, False if not allowed
1030 """
Simon Glassf4590e02022-01-09 20:13:46 -07001031 self.allow_fake = allow_fake
Heiko Thierya89c8f22022-01-06 11:49:41 +01001032
Simon Glassb1cca952020-07-09 18:39:40 -06001033 def CheckMissing(self, missing_list):
1034 """Check if any entries in this section have missing external blobs
1035
1036 If there are missing blobs, the entries are added to the list
1037
1038 Args:
1039 missing_list: List of Entry objects to be added to
1040 """
1041 if self.missing:
1042 missing_list.append(self)
Simon Glass87958982020-09-01 05:13:57 -06001043
Simon Glass3817ad42022-03-05 20:19:04 -07001044 def check_fake_fname(self, fname, size=0):
Simon Glass790ba9f2022-01-12 13:10:36 -07001045 """If the file is missing and the entry allows fake blobs, fake it
1046
1047 Sets self.faked to True if faked
1048
1049 Args:
1050 fname (str): Filename to check
Simon Glass3817ad42022-03-05 20:19:04 -07001051 size (int): Size of fake file to create
Simon Glass790ba9f2022-01-12 13:10:36 -07001052
1053 Returns:
Simon Glass9a0a2e92022-03-05 20:19:03 -07001054 tuple:
1055 fname (str): Filename of faked file
1056 bool: True if the blob was faked, False if not
Simon Glass790ba9f2022-01-12 13:10:36 -07001057 """
1058 if self.allow_fake and not pathlib.Path(fname).is_file():
Simon Glass7960a0a2022-08-07 09:46:46 -06001059 if not self.fake_fname:
1060 outfname = os.path.join(self.fake_dir, os.path.basename(fname))
1061 with open(outfname, "wb") as out:
1062 out.truncate(size)
1063 tout.info(f"Entry '{self._node.path}': Faked blob '{outfname}'")
1064 self.fake_fname = outfname
Simon Glass790ba9f2022-01-12 13:10:36 -07001065 self.faked = True
Simon Glass7960a0a2022-08-07 09:46:46 -06001066 return self.fake_fname, True
Simon Glass9a0a2e92022-03-05 20:19:03 -07001067 return fname, False
Simon Glass790ba9f2022-01-12 13:10:36 -07001068
Heiko Thierya89c8f22022-01-06 11:49:41 +01001069 def CheckFakedBlobs(self, faked_blobs_list):
1070 """Check if any entries in this section have faked external blobs
1071
1072 If there are faked blobs, the entries are added to the list
1073
1074 Args:
1075 fake_blobs_list: List of Entry objects to be added to
1076 """
1077 # This is meaningless for anything other than blobs
1078 pass
1079
Simon Glass87958982020-09-01 05:13:57 -06001080 def GetAllowMissing(self):
1081 """Get whether a section allows missing external blobs
1082
1083 Returns:
1084 True if allowed, False if not allowed
1085 """
1086 return self.allow_missing
Simon Glassb2381432020-09-06 10:39:09 -06001087
Simon Glass4f9ee832022-01-09 20:14:09 -07001088 def record_missing_bintool(self, bintool):
1089 """Record a missing bintool that was needed to produce this entry
1090
1091 Args:
1092 bintool (Bintool): Bintool that was missing
1093 """
Stefan Herbrechtsmeierfacc3782022-08-19 16:25:19 +02001094 if bintool not in self.missing_bintools:
1095 self.missing_bintools.append(bintool)
Simon Glass4f9ee832022-01-09 20:14:09 -07001096
1097 def check_missing_bintools(self, missing_list):
1098 """Check if any entries in this section have missing bintools
1099
1100 If there are missing bintools, these are added to the list
1101
1102 Args:
1103 missing_list: List of Bintool objects to be added to
1104 """
Stefan Herbrechtsmeierfacc3782022-08-19 16:25:19 +02001105 for bintool in self.missing_bintools:
1106 if bintool not in missing_list:
1107 missing_list.append(bintool)
1108
Simon Glass4f9ee832022-01-09 20:14:09 -07001109
Simon Glassb2381432020-09-06 10:39:09 -06001110 def GetHelpTags(self):
1111 """Get the tags use for missing-blob help
1112
1113 Returns:
1114 list of possible tags, most desirable first
1115 """
1116 return list(filter(None, [self.missing_msg, self.name, self.etype]))
Simon Glass87c96292020-10-26 17:40:06 -06001117
1118 def CompressData(self, indata):
1119 """Compress data according to the entry's compression method
1120
1121 Args:
1122 indata: Data to compress
1123
1124 Returns:
Stefan Herbrechtsmeier4f463e32022-08-19 16:25:27 +02001125 Compressed data
Simon Glass87c96292020-10-26 17:40:06 -06001126 """
Simon Glass97c3e9a2020-10-26 17:40:15 -06001127 self.uncomp_data = indata
Simon Glass87c96292020-10-26 17:40:06 -06001128 if self.compress != 'none':
1129 self.uncomp_size = len(indata)
Stefan Herbrechtsmeierc3665a82022-08-19 16:25:31 +02001130 if self.comp_bintool.is_present():
1131 data = self.comp_bintool.compress(indata)
1132 else:
1133 self.record_missing_bintool(self.comp_bintool)
1134 data = tools.get_bytes(0, 1024)
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001135 else:
1136 data = indata
Simon Glass87c96292020-10-26 17:40:06 -06001137 return data
Simon Glassb35fb172021-03-18 20:25:04 +13001138
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001139 def DecompressData(self, indata):
1140 """Decompress data according to the entry's compression method
1141
1142 Args:
1143 indata: Data to decompress
1144
1145 Returns:
1146 Decompressed data
1147 """
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001148 if self.compress != 'none':
Stefan Herbrechtsmeierc3665a82022-08-19 16:25:31 +02001149 if self.comp_bintool.is_present():
1150 data = self.comp_bintool.decompress(indata)
1151 self.uncomp_size = len(data)
1152 else:
1153 self.record_missing_bintool(self.comp_bintool)
1154 data = tools.get_bytes(0, 1024)
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001155 else:
1156 data = indata
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001157 self.uncomp_data = data
1158 return data
1159
Simon Glassb35fb172021-03-18 20:25:04 +13001160 @classmethod
1161 def UseExpanded(cls, node, etype, new_etype):
1162 """Check whether to use an expanded entry type
1163
1164 This is called by Entry.Create() when it finds an expanded version of
1165 an entry type (e.g. 'u-boot-expanded'). If this method returns True then
1166 it will be used (e.g. in place of 'u-boot'). If it returns False, it is
1167 ignored.
1168
1169 Args:
1170 node: Node object containing information about the entry to
1171 create
1172 etype: Original entry type being used
1173 new_etype: New entry type proposed
1174
1175 Returns:
1176 True to use this entry type, False to use the original one
1177 """
Simon Glassf3385a52022-01-29 14:14:15 -07001178 tout.info("Node '%s': etype '%s': %s selected" %
Simon Glassb35fb172021-03-18 20:25:04 +13001179 (node.path, etype, new_etype))
1180 return True
Simon Glass943bf782021-11-23 21:09:50 -07001181
1182 def CheckAltFormats(self, alt_formats):
1183 """Add any alternative formats supported by this entry type
1184
1185 Args:
1186 alt_formats (dict): Dict to add alt_formats to:
1187 key: Name of alt format
1188 value: Help text
1189 """
1190 pass
Simon Glass386c63c2022-01-09 20:13:50 -07001191
Simon Glassae9a4572022-03-05 20:19:02 -07001192 def AddBintools(self, btools):
Simon Glass386c63c2022-01-09 20:13:50 -07001193 """Add the bintools used by this entry type
1194
1195 Args:
Simon Glassae9a4572022-03-05 20:19:02 -07001196 btools (dict of Bintool):
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001197
1198 Raise:
1199 ValueError if compression algorithm is not supported
Simon Glass386c63c2022-01-09 20:13:50 -07001200 """
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001201 algo = self.compress
1202 if algo != 'none':
Stefan Herbrechtsmeiercd15b642022-08-19 16:25:38 +02001203 algos = ['bzip2', 'gzip', 'lz4', 'lzma', 'lzo', 'xz', 'zstd']
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001204 if algo not in algos:
1205 raise ValueError("Unknown algorithm '%s'" % algo)
Stefan Herbrechtsmeier7b26a462022-08-19 16:25:36 +02001206 names = {'lzma': 'lzma_alone', 'lzo': 'lzop'}
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001207 name = names.get(self.compress, self.compress)
1208 self.comp_bintool = self.AddBintool(btools, name)
Simon Glass386c63c2022-01-09 20:13:50 -07001209
1210 @classmethod
1211 def AddBintool(self, tools, name):
1212 """Add a new bintool to the tools used by this etype
1213
1214 Args:
1215 name: Name of the tool
1216 """
1217 btool = bintool.Bintool.create(name)
1218 tools[name] = btool
1219 return btool
Alper Nebi Yasakee813c82022-02-09 22:02:35 +03001220
1221 def SetUpdateHash(self, update_hash):
1222 """Set whether this entry's "hash" subnode should be updated
1223
1224 Args:
1225 update_hash: True if hash should be updated, False if not
1226 """
1227 self.update_hash = update_hash
Simon Glass81b71c32022-02-08 11:50:00 -07001228
Simon Glass72e423c2022-03-05 20:19:05 -07001229 def collect_contents_to_file(self, entries, prefix, fake_size=0):
Simon Glass81b71c32022-02-08 11:50:00 -07001230 """Put the contents of a list of entries into a file
1231
1232 Args:
1233 entries (list of Entry): Entries to collect
1234 prefix (str): Filename prefix of file to write to
Simon Glass72e423c2022-03-05 20:19:05 -07001235 fake_size (int): Size of fake file to create if needed
Simon Glass81b71c32022-02-08 11:50:00 -07001236
1237 If any entry does not have contents yet, this function returns False
1238 for the data.
1239
1240 Returns:
1241 Tuple:
Simon Glass6d427c42022-03-05 20:18:58 -07001242 bytes: Concatenated data from all the entries (or None)
1243 str: Filename of file written (or None if no data)
1244 str: Unique portion of filename (or None if no data)
Simon Glass81b71c32022-02-08 11:50:00 -07001245 """
1246 data = b''
1247 for entry in entries:
1248 # First get the input data and put it in a file. If not available,
1249 # try later.
Simon Glass72e423c2022-03-05 20:19:05 -07001250 if not entry.ObtainContents(fake_size=fake_size):
Simon Glass6d427c42022-03-05 20:18:58 -07001251 return None, None, None
Simon Glass81b71c32022-02-08 11:50:00 -07001252 data += entry.GetData()
1253 uniq = self.GetUniqueName()
1254 fname = tools.get_output_filename(f'{prefix}.{uniq}')
1255 tools.write_file(fname, data)
1256 return data, fname, uniq
Simon Glass7960a0a2022-08-07 09:46:46 -06001257
1258 @classmethod
1259 def create_fake_dir(cls):
1260 """Create the directory for fake files"""
1261 cls.fake_dir = tools.get_output_filename('binman-fake')
1262 if not os.path.exists(cls.fake_dir):
1263 os.mkdir(cls.fake_dir)
1264 tout.notice(f"Fake-blob dir is '{cls.fake_dir}'")
Simon Glasscdadada2022-08-13 11:40:44 -06001265
1266 def ensure_props(self):
1267 """Raise an exception if properties are missing
1268
1269 Args:
1270 prop_list (list of str): List of properties to check for
1271
1272 Raises:
1273 ValueError: Any property is missing
1274 """
1275 not_present = []
1276 for prop in self.required_props:
1277 if not prop in self._node.props:
1278 not_present.append(prop)
1279 if not_present:
1280 self.Raise(f"'{self.etype}' entry is missing properties: {' '.join(not_present)}")