blob: fd617e4f15f2a4e966e04b5a7351c8628aae32dd [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
Samuel Hollandb01ae032023-01-21 17:25:16 -060052 min_size: Minimum entry size in bytes
Simon Glass9a5d3dc2019-10-31 07:43:02 -060053 pre_reset_size: size as it was before ResetForPack(). This allows us to
54 keep track of the size we started with and detect size changes
Simon Glass8287ee82019-07-08 14:25:30 -060055 uncomp_size: Size of uncompressed data in bytes, if the entry is
56 compressed, else None
Simon Glassbf7fd502016-11-25 20:15:51 -070057 contents_size: Size of contents in bytes, 0 by default
Simon Glass4eec34c2020-10-26 17:40:10 -060058 align: Entry start offset alignment relative to the start of the
59 containing section, or None
Simon Glassbf7fd502016-11-25 20:15:51 -070060 align_size: Entry size alignment, or None
Simon Glass4eec34c2020-10-26 17:40:10 -060061 align_end: Entry end offset alignment relative to the start of the
62 containing section, or None
Simon Glassf90d9062020-10-26 17:40:09 -060063 pad_before: Number of pad bytes before the contents when it is placed
64 in the containing section, 0 if none. The pad bytes become part of
65 the entry.
66 pad_after: Number of pad bytes after the contents when it is placed in
67 the containing section, 0 if none. The pad bytes become part of
68 the entry.
69 data: Contents of entry (string of bytes). This does not include
Simon Glass97c3e9a2020-10-26 17:40:15 -060070 padding created by pad_before or pad_after. If the entry is
71 compressed, this contains the compressed data.
72 uncomp_data: Original uncompressed data, if this entry is compressed,
73 else None
Simon Glass8287ee82019-07-08 14:25:30 -060074 compress: Compression algoithm used (e.g. 'lz4'), 'none' if none
Simon Glassc52c9e72019-07-08 14:25:37 -060075 orig_offset: Original offset value read from node
76 orig_size: Original size value read from node
Simon Glass67a05012023-01-07 14:07:15 -070077 missing: True if this entry is missing its contents. Note that if it is
78 optional, this entry will not appear in the list generated by
79 entry.CheckMissing() since it is considered OK for it to be missing.
Simon Glass87958982020-09-01 05:13:57 -060080 allow_missing: Allow children of this entry to be missing (used by
81 subclasses such as Entry_section)
Heiko Thierya89c8f22022-01-06 11:49:41 +010082 allow_fake: Allow creating a dummy fake file if the blob file is not
83 available. This is mainly used for testing.
Simon Glass87958982020-09-01 05:13:57 -060084 external: True if this entry contains an external binary blob
Simon Glass386c63c2022-01-09 20:13:50 -070085 bintools: Bintools used by this entry (only populated for Image)
Simon Glass4f9ee832022-01-09 20:14:09 -070086 missing_bintools: List of missing bintools for this entry
Alper Nebi Yasakee813c82022-02-09 22:02:35 +030087 update_hash: True if this entry's "hash" subnode should be
88 updated with a hash of the entry contents
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +020089 comp_bintool: Bintools used for compress and decompress data
Simon Glass7960a0a2022-08-07 09:46:46 -060090 fake_fname: Fake filename, if one was created, else None
Simon Glasscdadada2022-08-13 11:40:44 -060091 required_props (dict of str): Properties which must be present. This can
92 be added to by subclasses
Simon Glass3fbba552022-10-20 18:22:46 -060093 elf_fname (str): Filename of the ELF file, if this entry holds an ELF
94 file, or is a binary file produced from an ELF file
95 auto_write_symbols (bool): True to write ELF symbols into this entry's
96 contents
Simon Glassc8c9f312023-01-07 14:07:12 -070097 absent (bool): True if this entry is absent. This can be controlled by
98 the entry itself, allowing it to vanish in certain circumstances.
99 An absent entry is removed during processing so that it does not
100 appear in the map
Simon Glass67a05012023-01-07 14:07:15 -0700101 optional (bool): True if this entry contains an optional external blob
Simon Glass9766f692023-01-11 16:10:16 -0700102 overlap (bool): True if this entry overlaps with others
Simon Glass9dbb02b2023-02-12 17:11:15 -0700103 preserve (bool): True if this entry should be preserved when updating
104 firmware. This means that it will not be changed by the update.
105 This is just a signal: enforcement of this is up to the updater.
106 This flag does not automatically propagate down to child entries.
Simon Glassbf7fd502016-11-25 20:15:51 -0700107 """
Simon Glass7960a0a2022-08-07 09:46:46 -0600108 fake_dir = None
109
Simon Glass3fbba552022-10-20 18:22:46 -0600110 def __init__(self, section, etype, node, name_prefix='',
111 auto_write_symbols=False):
Simon Glass8dbb7442019-08-24 07:22:44 -0600112 # Put this here to allow entry-docs and help to work without libfdt
113 global state
Simon Glass16287932020-04-17 18:09:03 -0600114 from binman import state
Simon Glass8dbb7442019-08-24 07:22:44 -0600115
Simon Glass25ac0e62018-06-01 09:38:14 -0600116 self.section = section
Simon Glassbf7fd502016-11-25 20:15:51 -0700117 self.etype = etype
118 self._node = node
Simon Glassc8d48ef2018-06-01 09:38:21 -0600119 self.name = node and (name_prefix + node.name) or 'none'
Simon Glass3ab95982018-08-01 15:22:37 -0600120 self.offset = None
Simon Glassbf7fd502016-11-25 20:15:51 -0700121 self.size = None
Samuel Hollandb01ae032023-01-21 17:25:16 -0600122 self.min_size = 0
Simon Glass9a5d3dc2019-10-31 07:43:02 -0600123 self.pre_reset_size = None
Simon Glass8287ee82019-07-08 14:25:30 -0600124 self.uncomp_size = None
Simon Glass24d0d3c2018-07-17 13:25:47 -0600125 self.data = None
Simon Glass97c3e9a2020-10-26 17:40:15 -0600126 self.uncomp_data = None
Simon Glassbf7fd502016-11-25 20:15:51 -0700127 self.contents_size = 0
128 self.align = None
129 self.align_size = None
130 self.align_end = None
131 self.pad_before = 0
132 self.pad_after = 0
Simon Glass3ab95982018-08-01 15:22:37 -0600133 self.offset_unset = False
Simon Glassdbf6be92018-08-01 15:22:42 -0600134 self.image_pos = None
Simon Glass80a66ae2022-03-05 20:18:59 -0700135 self.extend_size = False
Simon Glass8287ee82019-07-08 14:25:30 -0600136 self.compress = 'none'
Simon Glassb1cca952020-07-09 18:39:40 -0600137 self.missing = False
Heiko Thierya89c8f22022-01-06 11:49:41 +0100138 self.faked = False
Simon Glass87958982020-09-01 05:13:57 -0600139 self.external = False
140 self.allow_missing = False
Heiko Thierya89c8f22022-01-06 11:49:41 +0100141 self.allow_fake = False
Simon Glass386c63c2022-01-09 20:13:50 -0700142 self.bintools = {}
Simon Glass4f9ee832022-01-09 20:14:09 -0700143 self.missing_bintools = []
Alper Nebi Yasakee813c82022-02-09 22:02:35 +0300144 self.update_hash = True
Simon Glass7960a0a2022-08-07 09:46:46 -0600145 self.fake_fname = None
Simon Glasscdadada2022-08-13 11:40:44 -0600146 self.required_props = []
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +0200147 self.comp_bintool = None
Simon Glass3fbba552022-10-20 18:22:46 -0600148 self.elf_fname = None
149 self.auto_write_symbols = auto_write_symbols
Simon Glassc8c9f312023-01-07 14:07:12 -0700150 self.absent = False
Simon Glass67a05012023-01-07 14:07:15 -0700151 self.optional = False
Simon Glass9766f692023-01-11 16:10:16 -0700152 self.overlap = False
Simon Glassc1157862023-01-11 16:10:17 -0700153 self.elf_base_sym = None
Simon Glass571bc4e2023-01-11 16:10:19 -0700154 self.offset_from_elf = None
Simon Glass9dbb02b2023-02-12 17:11:15 -0700155 self.preserve = False
Simon Glassbf7fd502016-11-25 20:15:51 -0700156
157 @staticmethod
Simon Glass858436d2021-11-23 21:09:49 -0700158 def FindEntryClass(etype, expanded):
Simon Glassfd8d1f72018-07-17 13:25:36 -0600159 """Look up the entry class for a node.
Simon Glassbf7fd502016-11-25 20:15:51 -0700160
161 Args:
Simon Glassfd8d1f72018-07-17 13:25:36 -0600162 node_node: Path name of Node object containing information about
163 the entry to create (used for errors)
164 etype: Entry type to use
Simon Glassb35fb172021-03-18 20:25:04 +1300165 expanded: Use the expanded version of etype
Simon Glassbf7fd502016-11-25 20:15:51 -0700166
167 Returns:
Simon Glassb35fb172021-03-18 20:25:04 +1300168 The entry class object if found, else None if not found and expanded
Simon Glass858436d2021-11-23 21:09:49 -0700169 is True, else a tuple:
170 module name that could not be found
171 exception received
Simon Glassbf7fd502016-11-25 20:15:51 -0700172 """
Simon Glassdd57c132018-06-01 09:38:11 -0600173 # Convert something like 'u-boot@0' to 'u_boot' since we are only
174 # interested in the type.
Simon Glassbf7fd502016-11-25 20:15:51 -0700175 module_name = etype.replace('-', '_')
Simon Glassb35fb172021-03-18 20:25:04 +1300176
Simon Glassdd57c132018-06-01 09:38:11 -0600177 if '@' in module_name:
178 module_name = module_name.split('@')[0]
Simon Glassb35fb172021-03-18 20:25:04 +1300179 if expanded:
180 module_name += '_expanded'
Simon Glassbf7fd502016-11-25 20:15:51 -0700181 module = modules.get(module_name)
182
Simon Glassbadf0ec2018-06-01 09:38:15 -0600183 # Also allow entry-type modules to be brought in from the etype directory.
184
Simon Glassbf7fd502016-11-25 20:15:51 -0700185 # Import the module if we have not already done so.
186 if not module:
187 try:
Simon Glass16287932020-04-17 18:09:03 -0600188 module = importlib.import_module('binman.etype.' + module_name)
Simon Glassfd8d1f72018-07-17 13:25:36 -0600189 except ImportError as e:
Simon Glassb35fb172021-03-18 20:25:04 +1300190 if expanded:
191 return None
Simon Glass858436d2021-11-23 21:09:49 -0700192 return module_name, e
Simon Glassbf7fd502016-11-25 20:15:51 -0700193 modules[module_name] = module
194
Simon Glassfd8d1f72018-07-17 13:25:36 -0600195 # Look up the expected class name
196 return getattr(module, 'Entry_%s' % module_name)
197
198 @staticmethod
Simon Glass858436d2021-11-23 21:09:49 -0700199 def Lookup(node_path, etype, expanded, missing_etype=False):
200 """Look up the entry class for a node.
201
202 Args:
203 node_node (str): Path name of Node object containing information
204 about the entry to create (used for errors)
205 etype (str): Entry type to use
206 expanded (bool): Use the expanded version of etype
207 missing_etype (bool): True to default to a blob etype if the
208 requested etype is not found
209
210 Returns:
211 The entry class object if found, else None if not found and expanded
212 is True
213
214 Raise:
215 ValueError if expanded is False and the class is not found
216 """
217 # Convert something like 'u-boot@0' to 'u_boot' since we are only
218 # interested in the type.
219 cls = Entry.FindEntryClass(etype, expanded)
220 if cls is None:
221 return None
222 elif isinstance(cls, tuple):
223 if missing_etype:
224 cls = Entry.FindEntryClass('blob', False)
225 if isinstance(cls, tuple): # This should not fail
226 module_name, e = cls
227 raise ValueError(
228 "Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
229 (etype, node_path, module_name, e))
230 return cls
231
232 @staticmethod
233 def Create(section, node, etype=None, expanded=False, missing_etype=False):
Simon Glassfd8d1f72018-07-17 13:25:36 -0600234 """Create a new entry for a node.
235
236 Args:
Simon Glass858436d2021-11-23 21:09:49 -0700237 section (entry_Section): Section object containing this node
238 node (Node): Node object containing information about the entry to
239 create
240 etype (str): Entry type to use, or None to work it out (used for
241 tests)
242 expanded (bool): Use the expanded version of etype
243 missing_etype (bool): True to default to a blob etype if the
244 requested etype is not found
Simon Glassfd8d1f72018-07-17 13:25:36 -0600245
246 Returns:
247 A new Entry object of the correct type (a subclass of Entry)
248 """
249 if not etype:
250 etype = fdt_util.GetString(node, 'type', node.name)
Simon Glass858436d2021-11-23 21:09:49 -0700251 obj = Entry.Lookup(node.path, etype, expanded, missing_etype)
Simon Glassb35fb172021-03-18 20:25:04 +1300252 if obj and expanded:
253 # Check whether to use the expanded entry
254 new_etype = etype + '-expanded'
Simon Glass3d433382021-03-21 18:24:30 +1300255 can_expand = not fdt_util.GetBool(node, 'no-expanded')
256 if can_expand and obj.UseExpanded(node, etype, new_etype):
Simon Glassb35fb172021-03-18 20:25:04 +1300257 etype = new_etype
258 else:
259 obj = None
260 if not obj:
Simon Glass858436d2021-11-23 21:09:49 -0700261 obj = Entry.Lookup(node.path, etype, False, missing_etype)
Simon Glassfd8d1f72018-07-17 13:25:36 -0600262
Simon Glassbf7fd502016-11-25 20:15:51 -0700263 # Call its constructor to get the object we want.
Simon Glass25ac0e62018-06-01 09:38:14 -0600264 return obj(section, etype, node)
Simon Glassbf7fd502016-11-25 20:15:51 -0700265
266 def ReadNode(self):
267 """Read entry information from the node
268
Simon Glassc6bd6e22019-07-20 12:23:45 -0600269 This must be called as the first thing after the Entry is created.
270
Simon Glassbf7fd502016-11-25 20:15:51 -0700271 This reads all the fields we recognise from the node, ready for use.
272 """
Simon Glasscdadada2022-08-13 11:40:44 -0600273 self.ensure_props()
Simon Glass15a587c2018-07-17 13:25:51 -0600274 if 'pos' in self._node.props:
275 self.Raise("Please use 'offset' instead of 'pos'")
Simon Glass80a66ae2022-03-05 20:18:59 -0700276 if 'expand-size' in self._node.props:
277 self.Raise("Please use 'extend-size' instead of 'expand-size'")
Simon Glass3ab95982018-08-01 15:22:37 -0600278 self.offset = fdt_util.GetInt(self._node, 'offset')
Simon Glassbf7fd502016-11-25 20:15:51 -0700279 self.size = fdt_util.GetInt(self._node, 'size')
Samuel Hollandb01ae032023-01-21 17:25:16 -0600280 self.min_size = fdt_util.GetInt(self._node, 'min-size', 0)
Simon Glass12bb1a92019-07-20 12:23:51 -0600281 self.orig_offset = fdt_util.GetInt(self._node, 'orig-offset')
282 self.orig_size = fdt_util.GetInt(self._node, 'orig-size')
283 if self.GetImage().copy_to_orig:
284 self.orig_offset = self.offset
285 self.orig_size = self.size
Simon Glassc52c9e72019-07-08 14:25:37 -0600286
Simon Glassffded752019-07-08 14:25:46 -0600287 # These should not be set in input files, but are set in an FDT map,
288 # which is also read by this code.
289 self.image_pos = fdt_util.GetInt(self._node, 'image-pos')
290 self.uncomp_size = fdt_util.GetInt(self._node, 'uncomp-size')
291
Simon Glassbf7fd502016-11-25 20:15:51 -0700292 self.align = fdt_util.GetInt(self._node, 'align')
Simon Glassc1aa66e2022-01-29 14:14:04 -0700293 if tools.not_power_of_two(self.align):
Simon Glassbf7fd502016-11-25 20:15:51 -0700294 raise ValueError("Node '%s': Alignment %s must be a power of two" %
295 (self._node.path, self.align))
Simon Glass5ff9fed2021-03-21 18:24:33 +1300296 if self.section and self.align is None:
297 self.align = self.section.align_default
Simon Glassbf7fd502016-11-25 20:15:51 -0700298 self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
299 self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
300 self.align_size = fdt_util.GetInt(self._node, 'align-size')
Simon Glassc1aa66e2022-01-29 14:14:04 -0700301 if tools.not_power_of_two(self.align_size):
Simon Glass8beb11e2019-07-08 14:25:47 -0600302 self.Raise("Alignment size %s must be a power of two" %
303 self.align_size)
Simon Glassbf7fd502016-11-25 20:15:51 -0700304 self.align_end = fdt_util.GetInt(self._node, 'align-end')
Simon Glass3ab95982018-08-01 15:22:37 -0600305 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
Simon Glass80a66ae2022-03-05 20:18:59 -0700306 self.extend_size = fdt_util.GetBool(self._node, 'extend-size')
Simon Glassb2381432020-09-06 10:39:09 -0600307 self.missing_msg = fdt_util.GetString(self._node, 'missing-msg')
Simon Glass67a05012023-01-07 14:07:15 -0700308 self.optional = fdt_util.GetBool(self._node, 'optional')
Simon Glass9766f692023-01-11 16:10:16 -0700309 self.overlap = fdt_util.GetBool(self._node, 'overlap')
310 if self.overlap:
311 self.required_props += ['offset', 'size']
Simon Glassbf7fd502016-11-25 20:15:51 -0700312
Simon Glass87c96292020-10-26 17:40:06 -0600313 # This is only supported by blobs and sections at present
314 self.compress = fdt_util.GetString(self._node, 'compress', 'none')
Simon Glass571bc4e2023-01-11 16:10:19 -0700315 self.offset_from_elf = fdt_util.GetPhandleNameOffset(self._node,
316 'offset-from-elf')
Simon Glass87c96292020-10-26 17:40:06 -0600317
Simon Glass9dbb02b2023-02-12 17:11:15 -0700318 self.preserve = fdt_util.GetBool(self._node, 'preserve')
319
Simon Glass6c234bf2018-09-14 04:57:18 -0600320 def GetDefaultFilename(self):
321 return None
322
Simon Glassa8adb6d2019-07-20 12:23:28 -0600323 def GetFdts(self):
324 """Get the device trees used by this entry
Simon Glass539aece2018-09-14 04:57:22 -0600325
326 Returns:
Simon Glassa8adb6d2019-07-20 12:23:28 -0600327 Empty dict, if this entry is not a .dtb, otherwise:
328 Dict:
329 key: Filename from this entry (without the path)
Simon Glass4bdd3002019-07-20 12:23:31 -0600330 value: Tuple:
Simon Glassadb67bb2021-03-18 20:25:02 +1300331 Entry object for this dtb
Simon Glass4bdd3002019-07-20 12:23:31 -0600332 Filename of file containing this dtb
Simon Glass539aece2018-09-14 04:57:22 -0600333 """
Simon Glassa8adb6d2019-07-20 12:23:28 -0600334 return {}
Simon Glass539aece2018-09-14 04:57:22 -0600335
Simon Glassc9ee33a2022-03-05 20:19:00 -0700336 def gen_entries(self):
337 """Allow entries to generate other entries
Simon Glassa01d1a22021-03-18 20:24:52 +1300338
339 Some entries generate subnodes automatically, from which sub-entries
340 are then created. This method allows those to be added to the binman
341 definition for the current image. An entry which implements this method
342 should call state.AddSubnode() to add a subnode and can add properties
343 with state.AddString(), etc.
344
345 An example is 'files', which produces a section containing a list of
346 files.
347 """
Simon Glass0a98b282018-09-14 04:57:28 -0600348 pass
349
Simon Glassa9fad072020-10-26 17:40:17 -0600350 def AddMissingProperties(self, have_image_pos):
351 """Add new properties to the device tree as needed for this entry
352
353 Args:
354 have_image_pos: True if this entry has an image position. This can
355 be False if its parent section is compressed, since compression
356 groups all entries together into a compressed block of data,
357 obscuring the start of each individual child entry
358 """
359 for prop in ['offset', 'size']:
Simon Glass078ab1a2018-07-06 10:27:41 -0600360 if not prop in self._node.props:
Simon Glassf46621d2018-09-14 04:57:21 -0600361 state.AddZeroProp(self._node, prop)
Simon Glassa9fad072020-10-26 17:40:17 -0600362 if have_image_pos and 'image-pos' not in self._node.props:
363 state.AddZeroProp(self._node, 'image-pos')
Simon Glass12bb1a92019-07-20 12:23:51 -0600364 if self.GetImage().allow_repack:
365 if self.orig_offset is not None:
366 state.AddZeroProp(self._node, 'orig-offset', True)
367 if self.orig_size is not None:
368 state.AddZeroProp(self._node, 'orig-size', True)
369
Simon Glass8287ee82019-07-08 14:25:30 -0600370 if self.compress != 'none':
371 state.AddZeroProp(self._node, 'uncomp-size')
Alper Nebi Yasakee813c82022-02-09 22:02:35 +0300372
373 if self.update_hash:
374 err = state.CheckAddHashProp(self._node)
375 if err:
376 self.Raise(err)
Simon Glass078ab1a2018-07-06 10:27:41 -0600377
378 def SetCalculatedProperties(self):
379 """Set the value of device-tree properties calculated by binman"""
Simon Glassf46621d2018-09-14 04:57:21 -0600380 state.SetInt(self._node, 'offset', self.offset)
381 state.SetInt(self._node, 'size', self.size)
Simon Glass8beb11e2019-07-08 14:25:47 -0600382 base = self.section.GetRootSkipAtStart() if self.section else 0
Simon Glassa9fad072020-10-26 17:40:17 -0600383 if self.image_pos is not None:
Simon Glass08594d42020-11-02 12:55:44 -0700384 state.SetInt(self._node, 'image-pos', self.image_pos - base)
Simon Glass12bb1a92019-07-20 12:23:51 -0600385 if self.GetImage().allow_repack:
386 if self.orig_offset is not None:
387 state.SetInt(self._node, 'orig-offset', self.orig_offset, True)
388 if self.orig_size is not None:
389 state.SetInt(self._node, 'orig-size', self.orig_size, True)
Simon Glass8287ee82019-07-08 14:25:30 -0600390 if self.uncomp_size is not None:
391 state.SetInt(self._node, 'uncomp-size', self.uncomp_size)
Alper Nebi Yasakee813c82022-02-09 22:02:35 +0300392
393 if self.update_hash:
394 state.CheckSetHashValue(self._node, self.GetData)
Simon Glass078ab1a2018-07-06 10:27:41 -0600395
Simon Glassecab8972018-07-06 10:27:40 -0600396 def ProcessFdt(self, fdt):
Simon Glass6ed45ba2018-09-14 04:57:24 -0600397 """Allow entries to adjust the device tree
398
399 Some entries need to adjust the device tree for their purposes. This
400 may involve adding or deleting properties.
401
402 Returns:
403 True if processing is complete
404 False if processing could not be completed due to a dependency.
405 This will cause the entry to be retried after others have been
406 called
407 """
Simon Glassecab8972018-07-06 10:27:40 -0600408 return True
409
Simon Glassc8d48ef2018-06-01 09:38:21 -0600410 def SetPrefix(self, prefix):
411 """Set the name prefix for a node
412
413 Args:
414 prefix: Prefix to set, or '' to not use a prefix
415 """
416 if prefix:
417 self.name = prefix + self.name
418
Simon Glass5c890232018-07-06 10:27:19 -0600419 def SetContents(self, data):
420 """Set the contents of an entry
421
422 This sets both the data and content_size properties
423
424 Args:
Simon Glass5b463fc2019-07-08 14:25:33 -0600425 data: Data to set to the contents (bytes)
Simon Glass5c890232018-07-06 10:27:19 -0600426 """
427 self.data = data
428 self.contents_size = len(self.data)
429
430 def ProcessContentsUpdate(self, data):
Simon Glass5b463fc2019-07-08 14:25:33 -0600431 """Update the contents of an entry, after the size is fixed
Simon Glass5c890232018-07-06 10:27:19 -0600432
Simon Glassa0dcaf22019-07-08 14:25:35 -0600433 This checks that the new data is the same size as the old. If the size
434 has changed, this triggers a re-run of the packing algorithm.
Simon Glass5c890232018-07-06 10:27:19 -0600435
436 Args:
Simon Glass5b463fc2019-07-08 14:25:33 -0600437 data: Data to set to the contents (bytes)
Simon Glass5c890232018-07-06 10:27:19 -0600438
439 Raises:
440 ValueError if the new data size is not the same as the old
441 """
Simon Glassa0dcaf22019-07-08 14:25:35 -0600442 size_ok = True
Simon Glassc52c9e72019-07-08 14:25:37 -0600443 new_size = len(data)
Simon Glass61ec04f2019-07-20 12:23:58 -0600444 if state.AllowEntryExpansion() and new_size > self.contents_size:
445 # self.data will indicate the new size needed
446 size_ok = False
447 elif state.AllowEntryContraction() and new_size < self.contents_size:
448 size_ok = False
449
450 # If not allowed to change, try to deal with it or give up
451 if size_ok:
Simon Glassc52c9e72019-07-08 14:25:37 -0600452 if new_size > self.contents_size:
Simon Glass61ec04f2019-07-20 12:23:58 -0600453 self.Raise('Cannot update entry size from %d to %d' %
454 (self.contents_size, new_size))
455
456 # Don't let the data shrink. Pad it if necessary
457 if size_ok and new_size < self.contents_size:
Simon Glassc1aa66e2022-01-29 14:14:04 -0700458 data += tools.get_bytes(0, self.contents_size - new_size)
Simon Glass61ec04f2019-07-20 12:23:58 -0600459
460 if not size_ok:
Simon Glassf3385a52022-01-29 14:14:15 -0700461 tout.debug("Entry '%s' size change from %s to %s" % (
Simon Glassc1aa66e2022-01-29 14:14:04 -0700462 self._node.path, to_hex(self.contents_size),
463 to_hex(new_size)))
Simon Glass5c890232018-07-06 10:27:19 -0600464 self.SetContents(data)
Simon Glassa0dcaf22019-07-08 14:25:35 -0600465 return size_ok
Simon Glass5c890232018-07-06 10:27:19 -0600466
Simon Glass72e423c2022-03-05 20:19:05 -0700467 def ObtainContents(self, skip_entry=None, fake_size=0):
Simon Glassbf7fd502016-11-25 20:15:51 -0700468 """Figure out the contents of an entry.
469
Simon Glass72e423c2022-03-05 20:19:05 -0700470 Args:
471 skip_entry (Entry): Entry to skip when obtaining section contents
472 fake_size (int): Size of fake file to create if needed
473
Simon Glassbf7fd502016-11-25 20:15:51 -0700474 Returns:
475 True if the contents were found, False if another call is needed
Simon Glass62ef2f72023-01-11 16:10:14 -0700476 after the other entries are processed, None if there is no contents
Simon Glassbf7fd502016-11-25 20:15:51 -0700477 """
478 # No contents by default: subclasses can implement this
479 return True
480
Simon Glassc52c9e72019-07-08 14:25:37 -0600481 def ResetForPack(self):
482 """Reset offset/size fields so that packing can be done again"""
Simon Glass9f297b02019-07-20 12:23:36 -0600483 self.Detail('ResetForPack: offset %s->%s, size %s->%s' %
Simon Glassc1aa66e2022-01-29 14:14:04 -0700484 (to_hex(self.offset), to_hex(self.orig_offset),
485 to_hex(self.size), to_hex(self.orig_size)))
Simon Glass9a5d3dc2019-10-31 07:43:02 -0600486 self.pre_reset_size = self.size
Simon Glassc52c9e72019-07-08 14:25:37 -0600487 self.offset = self.orig_offset
488 self.size = self.orig_size
489
Simon Glass3ab95982018-08-01 15:22:37 -0600490 def Pack(self, offset):
Simon Glass25ac0e62018-06-01 09:38:14 -0600491 """Figure out how to pack the entry into the section
Simon Glassbf7fd502016-11-25 20:15:51 -0700492
493 Most of the time the entries are not fully specified. There may be
494 an alignment but no size. In that case we take the size from the
495 contents of the entry.
496
Simon Glass3ab95982018-08-01 15:22:37 -0600497 If an entry has no hard-coded offset, it will be placed at @offset.
Simon Glassbf7fd502016-11-25 20:15:51 -0700498
Simon Glass3ab95982018-08-01 15:22:37 -0600499 Once this function is complete, both the offset and size of the
Simon Glassbf7fd502016-11-25 20:15:51 -0700500 entry will be know.
501
502 Args:
Simon Glass3ab95982018-08-01 15:22:37 -0600503 Current section offset pointer
Simon Glassbf7fd502016-11-25 20:15:51 -0700504
505 Returns:
Simon Glass3ab95982018-08-01 15:22:37 -0600506 New section offset pointer (after this entry)
Simon Glassbf7fd502016-11-25 20:15:51 -0700507 """
Simon Glass9f297b02019-07-20 12:23:36 -0600508 self.Detail('Packing: offset=%s, size=%s, content_size=%x' %
Simon Glassc1aa66e2022-01-29 14:14:04 -0700509 (to_hex(self.offset), to_hex(self.size),
Simon Glass9f297b02019-07-20 12:23:36 -0600510 self.contents_size))
Simon Glass3ab95982018-08-01 15:22:37 -0600511 if self.offset is None:
512 if self.offset_unset:
513 self.Raise('No offset set with offset-unset: should another '
514 'entry provide this correct offset?')
Simon Glass571bc4e2023-01-11 16:10:19 -0700515 elif self.offset_from_elf:
516 self.offset = self.lookup_offset()
517 else:
518 self.offset = tools.align(offset, self.align)
Simon Glassbf7fd502016-11-25 20:15:51 -0700519 needed = self.pad_before + self.contents_size + self.pad_after
Samuel Hollandb01ae032023-01-21 17:25:16 -0600520 needed = max(needed, self.min_size)
Simon Glassc1aa66e2022-01-29 14:14:04 -0700521 needed = tools.align(needed, self.align_size)
Simon Glassbf7fd502016-11-25 20:15:51 -0700522 size = self.size
523 if not size:
524 size = needed
Simon Glass3ab95982018-08-01 15:22:37 -0600525 new_offset = self.offset + size
Simon Glassc1aa66e2022-01-29 14:14:04 -0700526 aligned_offset = tools.align(new_offset, self.align_end)
Simon Glass3ab95982018-08-01 15:22:37 -0600527 if aligned_offset != new_offset:
528 size = aligned_offset - self.offset
529 new_offset = aligned_offset
Simon Glassbf7fd502016-11-25 20:15:51 -0700530
531 if not self.size:
532 self.size = size
533
534 if self.size < needed:
535 self.Raise("Entry contents size is %#x (%d) but entry size is "
536 "%#x (%d)" % (needed, needed, self.size, self.size))
537 # Check that the alignment is correct. It could be wrong if the
Simon Glass3ab95982018-08-01 15:22:37 -0600538 # and offset or size values were provided (i.e. not calculated), but
Simon Glassbf7fd502016-11-25 20:15:51 -0700539 # conflict with the provided alignment values
Simon Glassc1aa66e2022-01-29 14:14:04 -0700540 if self.size != tools.align(self.size, self.align_size):
Simon Glassbf7fd502016-11-25 20:15:51 -0700541 self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
542 (self.size, self.size, self.align_size, self.align_size))
Simon Glassc1aa66e2022-01-29 14:14:04 -0700543 if self.offset != tools.align(self.offset, self.align):
Simon Glass3ab95982018-08-01 15:22:37 -0600544 self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
545 (self.offset, self.offset, self.align, self.align))
Simon Glass9f297b02019-07-20 12:23:36 -0600546 self.Detail(' - packed: offset=%#x, size=%#x, content_size=%#x, next_offset=%x' %
547 (self.offset, self.size, self.contents_size, new_offset))
Simon Glassbf7fd502016-11-25 20:15:51 -0700548
Simon Glass3ab95982018-08-01 15:22:37 -0600549 return new_offset
Simon Glassbf7fd502016-11-25 20:15:51 -0700550
551 def Raise(self, msg):
552 """Convenience function to raise an error referencing a node"""
553 raise ValueError("Node '%s': %s" % (self._node.path, msg))
554
Simon Glass189f2912021-03-21 18:24:31 +1300555 def Info(self, msg):
556 """Convenience function to log info referencing a node"""
557 tag = "Info '%s'" % self._node.path
Simon Glassf3385a52022-01-29 14:14:15 -0700558 tout.detail('%30s: %s' % (tag, msg))
Simon Glass189f2912021-03-21 18:24:31 +1300559
Simon Glass9f297b02019-07-20 12:23:36 -0600560 def Detail(self, msg):
561 """Convenience function to log detail referencing a node"""
562 tag = "Node '%s'" % self._node.path
Simon Glassf3385a52022-01-29 14:14:15 -0700563 tout.detail('%30s: %s' % (tag, msg))
Simon Glass9f297b02019-07-20 12:23:36 -0600564
Simon Glass53af22a2018-07-17 13:25:32 -0600565 def GetEntryArgsOrProps(self, props, required=False):
566 """Return the values of a set of properties
567
568 Args:
569 props: List of EntryArg objects
570
571 Raises:
572 ValueError if a property is not found
573 """
574 values = []
575 missing = []
576 for prop in props:
577 python_prop = prop.name.replace('-', '_')
578 if hasattr(self, python_prop):
579 value = getattr(self, python_prop)
580 else:
581 value = None
582 if value is None:
583 value = self.GetArg(prop.name, prop.datatype)
584 if value is None and required:
585 missing.append(prop.name)
586 values.append(value)
587 if missing:
Simon Glass939d1062021-01-06 21:35:16 -0700588 self.GetImage().MissingArgs(self, missing)
Simon Glass53af22a2018-07-17 13:25:32 -0600589 return values
590
Simon Glassbf7fd502016-11-25 20:15:51 -0700591 def GetPath(self):
592 """Get the path of a node
593
594 Returns:
595 Full path of the node for this entry
596 """
597 return self._node.path
598
Simon Glass631f7522021-03-21 18:24:32 +1300599 def GetData(self, required=True):
Simon Glass63e7ba62020-10-26 17:40:16 -0600600 """Get the contents of an entry
601
Simon Glass631f7522021-03-21 18:24:32 +1300602 Args:
603 required: True if the data must be present, False if it is OK to
604 return None
605
Simon Glass63e7ba62020-10-26 17:40:16 -0600606 Returns:
607 bytes content of the entry, excluding any padding. If the entry is
Simon Glass4331d662023-01-11 16:10:13 -0700608 compressed, the compressed data is returned. If the entry data
Simon Glass62ef2f72023-01-11 16:10:14 -0700609 is not yet available, False can be returned. If the entry data
610 is null, then None is returned.
Simon Glass63e7ba62020-10-26 17:40:16 -0600611 """
Simon Glassc1aa66e2022-01-29 14:14:04 -0700612 self.Detail('GetData: size %s' % to_hex_size(self.data))
Simon Glassbf7fd502016-11-25 20:15:51 -0700613 return self.data
614
Simon Glass271a0832020-11-02 12:55:43 -0700615 def GetPaddedData(self, data=None):
616 """Get the data for an entry including any padding
617
618 Gets the entry data and uses its section's pad-byte value to add padding
619 before and after as defined by the pad-before and pad-after properties.
620
621 This does not consider alignment.
622
623 Returns:
624 Contents of the entry along with any pad bytes before and
625 after it (bytes)
626 """
627 if data is None:
628 data = self.GetData()
629 return self.section.GetPaddedDataForEntry(self, data)
630
Simon Glass3ab95982018-08-01 15:22:37 -0600631 def GetOffsets(self):
Simon Glassed7dd5e2019-07-08 13:18:30 -0600632 """Get the offsets for siblings
633
634 Some entry types can contain information about the position or size of
635 other entries. An example of this is the Intel Flash Descriptor, which
636 knows where the Intel Management Engine section should go.
637
638 If this entry knows about the position of other entries, it can specify
639 this by returning values here
640
641 Returns:
642 Dict:
643 key: Entry type
644 value: List containing position and size of the given entry
Simon Glasscf549042019-07-08 13:18:39 -0600645 type. Either can be None if not known
Simon Glassed7dd5e2019-07-08 13:18:30 -0600646 """
Simon Glassbf7fd502016-11-25 20:15:51 -0700647 return {}
648
Simon Glasscf549042019-07-08 13:18:39 -0600649 def SetOffsetSize(self, offset, size):
650 """Set the offset and/or size of an entry
651
652 Args:
653 offset: New offset, or None to leave alone
654 size: New size, or None to leave alone
655 """
656 if offset is not None:
657 self.offset = offset
658 if size is not None:
659 self.size = size
Simon Glassbf7fd502016-11-25 20:15:51 -0700660
Simon Glassdbf6be92018-08-01 15:22:42 -0600661 def SetImagePos(self, image_pos):
662 """Set the position in the image
663
664 Args:
665 image_pos: Position of this entry in the image
666 """
667 self.image_pos = image_pos + self.offset
668
Simon Glassbf7fd502016-11-25 20:15:51 -0700669 def ProcessContents(self):
Simon Glassa0dcaf22019-07-08 14:25:35 -0600670 """Do any post-packing updates of entry contents
671
672 This function should call ProcessContentsUpdate() to update the entry
673 contents, if necessary, returning its return value here.
674
675 Args:
676 data: Data to set to the contents (bytes)
677
678 Returns:
679 True if the new data size is OK, False if expansion is needed
680
681 Raises:
682 ValueError if the new data size is not the same as the old and
683 state.AllowEntryExpansion() is False
684 """
685 return True
Simon Glass19790632017-11-13 18:55:01 -0700686
Simon Glassf55382b2018-06-01 09:38:13 -0600687 def WriteSymbols(self, section):
Simon Glass19790632017-11-13 18:55:01 -0700688 """Write symbol values into binary files for access at run time
689
690 Args:
Simon Glassf55382b2018-06-01 09:38:13 -0600691 section: Section containing the entry
Simon Glass19790632017-11-13 18:55:01 -0700692 """
Simon Glass3fbba552022-10-20 18:22:46 -0600693 if self.auto_write_symbols:
Simon Glassd2afb9e2022-10-20 18:22:47 -0600694 # Check if we are writing symbols into an ELF file
695 is_elf = self.GetDefaultFilename() == self.elf_fname
696 elf.LookupAndWriteSymbols(self.elf_fname, self, section.GetImage(),
Simon Glassc1157862023-01-11 16:10:17 -0700697 is_elf, self.elf_base_sym)
Simon Glass18546952018-06-01 09:38:16 -0600698
Simon Glass6ddd6112020-10-26 17:40:18 -0600699 def CheckEntries(self):
Simon Glass3ab95982018-08-01 15:22:37 -0600700 """Check that the entry offsets are correct
Simon Glass18546952018-06-01 09:38:16 -0600701
Simon Glass3ab95982018-08-01 15:22:37 -0600702 This is used for entries which have extra offset requirements (other
Simon Glass18546952018-06-01 09:38:16 -0600703 than having to be fully inside their section). Sub-classes can implement
704 this function and raise if there is a problem.
705 """
706 pass
Simon Glass3b0c3822018-06-01 09:38:20 -0600707
Simon Glass8122f392018-07-17 13:25:28 -0600708 @staticmethod
Simon Glass163ed6c2018-09-14 04:57:36 -0600709 def GetStr(value):
710 if value is None:
711 return '<none> '
712 return '%08x' % value
713
714 @staticmethod
Simon Glass1be70d22018-07-17 13:25:49 -0600715 def WriteMapLine(fd, indent, name, offset, size, image_pos):
Simon Glass163ed6c2018-09-14 04:57:36 -0600716 print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
717 Entry.GetStr(offset), Entry.GetStr(size),
718 name), file=fd)
Simon Glass8122f392018-07-17 13:25:28 -0600719
Simon Glass3b0c3822018-06-01 09:38:20 -0600720 def WriteMap(self, fd, indent):
721 """Write a map of the entry to a .map file
722
723 Args:
724 fd: File to write the map to
725 indent: Curent indent level of map (0=none, 1=one level, etc.)
726 """
Simon Glass1be70d22018-07-17 13:25:49 -0600727 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
728 self.image_pos)
Simon Glass53af22a2018-07-17 13:25:32 -0600729
Simon Glassd626e822022-08-13 11:40:50 -0600730 # pylint: disable=assignment-from-none
Simon Glass11e36cc2018-07-17 13:25:38 -0600731 def GetEntries(self):
732 """Return a list of entries contained by this entry
733
734 Returns:
735 List of entries, or None if none. A normal entry has no entries
736 within it so will return None
737 """
738 return None
739
Simon Glassd626e822022-08-13 11:40:50 -0600740 def FindEntryByNode(self, find_node):
741 """Find a node in an entry, searching all subentries
742
743 This does a recursive search.
744
745 Args:
746 find_node (fdt.Node): Node to find
747
748 Returns:
749 Entry: entry, if found, else None
750 """
751 entries = self.GetEntries()
752 if entries:
753 for entry in entries.values():
754 if entry._node == find_node:
755 return entry
756 found = entry.FindEntryByNode(find_node)
757 if found:
758 return found
759
760 return None
761
Simon Glass53af22a2018-07-17 13:25:32 -0600762 def GetArg(self, name, datatype=str):
763 """Get the value of an entry argument or device-tree-node property
764
765 Some node properties can be provided as arguments to binman. First check
766 the entry arguments, and fall back to the device tree if not found
767
768 Args:
769 name: Argument name
770 datatype: Data type (str or int)
771
772 Returns:
773 Value of argument as a string or int, or None if no value
774
775 Raises:
776 ValueError if the argument cannot be converted to in
777 """
Simon Glassc55a50f2018-09-14 04:57:19 -0600778 value = state.GetEntryArg(name)
Simon Glass53af22a2018-07-17 13:25:32 -0600779 if value is not None:
780 if datatype == int:
781 try:
782 value = int(value)
783 except ValueError:
784 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
785 (name, value))
786 elif datatype == str:
787 pass
788 else:
789 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
790 datatype)
791 else:
792 value = fdt_util.GetDatatype(self._node, name, datatype)
793 return value
Simon Glassfd8d1f72018-07-17 13:25:36 -0600794
795 @staticmethod
796 def WriteDocs(modules, test_missing=None):
797 """Write out documentation about the various entry types to stdout
798
799 Args:
800 modules: List of modules to include
801 test_missing: Used for testing. This is a module to report
802 as missing
803 """
804 print('''Binman Entry Documentation
805===========================
806
807This file describes the entry types supported by binman. These entry types can
808be placed in an image one by one to build up a final firmware image. It is
809fairly easy to create new entry types. Just add a new file to the 'etype'
810directory. You can use the existing entries as examples.
811
812Note that some entries are subclasses of others, using and extending their
813features to produce new behaviours.
814
815
816''')
817 modules = sorted(modules)
818
819 # Don't show the test entry
820 if '_testing' in modules:
821 modules.remove('_testing')
822 missing = []
823 for name in modules:
Simon Glassb35fb172021-03-18 20:25:04 +1300824 module = Entry.Lookup('WriteDocs', name, False)
Simon Glassfd8d1f72018-07-17 13:25:36 -0600825 docs = getattr(module, '__doc__')
826 if test_missing == name:
827 docs = None
828 if docs:
829 lines = docs.splitlines()
830 first_line = lines[0]
831 rest = [line[4:] for line in lines[1:]]
832 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
Simon Glass228c9b82022-08-07 16:33:25 -0600833
834 # Create a reference for use by rST docs
835 ref_name = f'etype_{module.__name__[6:]}'.lower()
836 print('.. _%s:' % ref_name)
837 print()
Simon Glassfd8d1f72018-07-17 13:25:36 -0600838 print(hdr)
839 print('-' * len(hdr))
840 print('\n'.join(rest))
841 print()
842 print()
843 else:
844 missing.append(name)
845
846 if missing:
847 raise ValueError('Documentation is missing for modules: %s' %
848 ', '.join(missing))
Simon Glassa326b492018-09-14 04:57:11 -0600849
850 def GetUniqueName(self):
851 """Get a unique name for a node
852
853 Returns:
854 String containing a unique name for a node, consisting of the name
855 of all ancestors (starting from within the 'binman' node) separated
856 by a dot ('.'). This can be useful for generating unique filesnames
857 in the output directory.
858 """
859 name = self.name
860 node = self._node
861 while node.parent:
862 node = node.parent
Alper Nebi Yasak67bf2c82022-03-27 18:31:44 +0300863 if node.name in ('binman', '/'):
Simon Glassa326b492018-09-14 04:57:11 -0600864 break
865 name = '%s.%s' % (node.name, name)
866 return name
Simon Glassba64a0b2018-09-14 04:57:29 -0600867
Simon Glass80a66ae2022-03-05 20:18:59 -0700868 def extend_to_limit(self, limit):
869 """Extend an entry so that it ends at the given offset limit"""
Simon Glassba64a0b2018-09-14 04:57:29 -0600870 if self.offset + self.size < limit:
871 self.size = limit - self.offset
872 # Request the contents again, since changing the size requires that
873 # the data grows. This should not fail, but check it to be sure.
874 if not self.ObtainContents():
875 self.Raise('Cannot obtain contents when expanding entry')
Simon Glassfa1c9372019-07-08 13:18:38 -0600876
877 def HasSibling(self, name):
878 """Check if there is a sibling of a given name
879
880 Returns:
881 True if there is an entry with this name in the the same section,
882 else False
883 """
884 return name in self.section.GetEntries()
Simon Glasscf228942019-07-08 14:25:28 -0600885
886 def GetSiblingImagePos(self, name):
887 """Return the image position of the given sibling
888
889 Returns:
890 Image position of sibling, or None if the sibling has no position,
891 or False if there is no such sibling
892 """
893 if not self.HasSibling(name):
894 return False
895 return self.section.GetEntries()[name].image_pos
Simon Glass41b8ba02019-07-08 14:25:43 -0600896
897 @staticmethod
898 def AddEntryInfo(entries, indent, name, etype, size, image_pos,
899 uncomp_size, offset, entry):
900 """Add a new entry to the entries list
901
902 Args:
903 entries: List (of EntryInfo objects) to add to
904 indent: Current indent level to add to list
905 name: Entry name (string)
906 etype: Entry type (string)
907 size: Entry size in bytes (int)
908 image_pos: Position within image in bytes (int)
909 uncomp_size: Uncompressed size if the entry uses compression, else
910 None
911 offset: Entry offset within parent in bytes (int)
912 entry: Entry object
913 """
914 entries.append(EntryInfo(indent, name, etype, size, image_pos,
915 uncomp_size, offset, entry))
916
917 def ListEntries(self, entries, indent):
918 """Add files in this entry to the list of entries
919
920 This can be overridden by subclasses which need different behaviour.
921
922 Args:
923 entries: List (of EntryInfo objects) to add to
924 indent: Current indent level to add to list
925 """
926 self.AddEntryInfo(entries, indent, self.name, self.etype, self.size,
927 self.image_pos, self.uncomp_size, self.offset, self)
Simon Glassf667e452019-07-08 14:25:50 -0600928
Simon Glass943bf782021-11-23 21:09:50 -0700929 def ReadData(self, decomp=True, alt_format=None):
Simon Glassf667e452019-07-08 14:25:50 -0600930 """Read the data for an entry from the image
931
932 This is used when the image has been read in and we want to extract the
933 data for a particular entry from that image.
934
935 Args:
936 decomp: True to decompress any compressed data before returning it;
937 False to return the raw, uncompressed data
938
939 Returns:
940 Entry data (bytes)
941 """
942 # Use True here so that we get an uncompressed section to work from,
943 # although compressed sections are currently not supported
Simon Glassf3385a52022-01-29 14:14:15 -0700944 tout.debug("ReadChildData section '%s', entry '%s'" %
Simon Glass2d553c02019-09-25 08:56:21 -0600945 (self.section.GetPath(), self.GetPath()))
Simon Glass943bf782021-11-23 21:09:50 -0700946 data = self.section.ReadChildData(self, decomp, alt_format)
Simon Glassa9cd39e2019-07-20 12:24:04 -0600947 return data
Simon Glassd5079332019-07-20 12:23:41 -0600948
Simon Glass943bf782021-11-23 21:09:50 -0700949 def ReadChildData(self, child, decomp=True, alt_format=None):
Simon Glass2d553c02019-09-25 08:56:21 -0600950 """Read the data for a particular child entry
Simon Glass4e185e82019-09-25 08:56:20 -0600951
952 This reads data from the parent and extracts the piece that relates to
953 the given child.
954
955 Args:
Simon Glass943bf782021-11-23 21:09:50 -0700956 child (Entry): Child entry to read data for (must be valid)
957 decomp (bool): True to decompress any compressed data before
958 returning it; False to return the raw, uncompressed data
959 alt_format (str): Alternative format to read in, or None
Simon Glass4e185e82019-09-25 08:56:20 -0600960
961 Returns:
962 Data for the child (bytes)
963 """
964 pass
965
Simon Glassd5079332019-07-20 12:23:41 -0600966 def LoadData(self, decomp=True):
967 data = self.ReadData(decomp)
Simon Glass10f9d002019-07-20 12:23:50 -0600968 self.contents_size = len(data)
Simon Glassd5079332019-07-20 12:23:41 -0600969 self.ProcessContentsUpdate(data)
970 self.Detail('Loaded data size %x' % len(data))
Simon Glassc5ad04b2019-07-20 12:23:46 -0600971
Simon Glass943bf782021-11-23 21:09:50 -0700972 def GetAltFormat(self, data, alt_format):
973 """Read the data for an extry in an alternative format
974
975 Supported formats are list in the documentation for each entry. An
976 example is fdtmap which provides .
977
978 Args:
979 data (bytes): Data to convert (this should have been produced by the
980 entry)
981 alt_format (str): Format to use
982
983 """
984 pass
985
Simon Glassc5ad04b2019-07-20 12:23:46 -0600986 def GetImage(self):
987 """Get the image containing this entry
988
989 Returns:
990 Image object containing this entry
991 """
992 return self.section.GetImage()
Simon Glass10f9d002019-07-20 12:23:50 -0600993
994 def WriteData(self, data, decomp=True):
995 """Write the data to an entry in the image
996
997 This is used when the image has been read in and we want to replace the
998 data for a particular entry in that image.
999
1000 The image must be re-packed and written out afterwards.
1001
1002 Args:
1003 data: Data to replace it with
1004 decomp: True to compress the data if needed, False if data is
1005 already compressed so should be used as is
1006
1007 Returns:
1008 True if the data did not result in a resize of this entry, False if
1009 the entry must be resized
1010 """
Simon Glass9a5d3dc2019-10-31 07:43:02 -06001011 if self.size is not None:
1012 self.contents_size = self.size
1013 else:
1014 self.contents_size = self.pre_reset_size
Simon Glass10f9d002019-07-20 12:23:50 -06001015 ok = self.ProcessContentsUpdate(data)
1016 self.Detail('WriteData: size=%x, ok=%s' % (len(data), ok))
Simon Glass7210c892019-07-20 12:24:05 -06001017 section_ok = self.section.WriteChildData(self)
1018 return ok and section_ok
1019
1020 def WriteChildData(self, child):
1021 """Handle writing the data in a child entry
1022
1023 This should be called on the child's parent section after the child's
Simon Glass557693e2021-11-23 11:03:44 -07001024 data has been updated. It should update any data structures needed to
1025 validate that the update is successful.
Simon Glass7210c892019-07-20 12:24:05 -06001026
1027 This base-class implementation does nothing, since the base Entry object
1028 does not have any children.
1029
1030 Args:
1031 child: Child Entry that was written
1032
1033 Returns:
1034 True if the section could be updated successfully, False if the
Simon Glass557693e2021-11-23 11:03:44 -07001035 data is such that the section could not update
Simon Glass7210c892019-07-20 12:24:05 -06001036 """
1037 return True
Simon Glasseba1f0c2019-07-20 12:23:55 -06001038
1039 def GetSiblingOrder(self):
1040 """Get the relative order of an entry amoung its siblings
1041
1042 Returns:
1043 'start' if this entry is first among siblings, 'end' if last,
1044 otherwise None
1045 """
1046 entries = list(self.section.GetEntries().values())
1047 if entries:
1048 if self == entries[0]:
1049 return 'start'
1050 elif self == entries[-1]:
1051 return 'end'
1052 return 'middle'
Simon Glass4f9f1052020-07-09 18:39:38 -06001053
1054 def SetAllowMissing(self, allow_missing):
1055 """Set whether a section allows missing external blobs
1056
1057 Args:
1058 allow_missing: True if allowed, False if not allowed
1059 """
1060 # This is meaningless for anything other than sections
1061 pass
Simon Glassb1cca952020-07-09 18:39:40 -06001062
Heiko Thierya89c8f22022-01-06 11:49:41 +01001063 def SetAllowFakeBlob(self, allow_fake):
1064 """Set whether a section allows to create a fake blob
1065
1066 Args:
1067 allow_fake: True if allowed, False if not allowed
1068 """
Simon Glassf4590e02022-01-09 20:13:46 -07001069 self.allow_fake = allow_fake
Heiko Thierya89c8f22022-01-06 11:49:41 +01001070
Simon Glassb1cca952020-07-09 18:39:40 -06001071 def CheckMissing(self, missing_list):
Simon Glass67a05012023-01-07 14:07:15 -07001072 """Check if the entry has missing external blobs
Simon Glassb1cca952020-07-09 18:39:40 -06001073
Simon Glass67a05012023-01-07 14:07:15 -07001074 If there are missing (non-optional) blobs, the entries are added to the
1075 list
Simon Glassb1cca952020-07-09 18:39:40 -06001076
1077 Args:
1078 missing_list: List of Entry objects to be added to
1079 """
Simon Glass67a05012023-01-07 14:07:15 -07001080 if self.missing and not self.optional:
Simon Glassb1cca952020-07-09 18:39:40 -06001081 missing_list.append(self)
Simon Glass87958982020-09-01 05:13:57 -06001082
Simon Glass3817ad42022-03-05 20:19:04 -07001083 def check_fake_fname(self, fname, size=0):
Simon Glass790ba9f2022-01-12 13:10:36 -07001084 """If the file is missing and the entry allows fake blobs, fake it
1085
1086 Sets self.faked to True if faked
1087
1088 Args:
1089 fname (str): Filename to check
Simon Glass3817ad42022-03-05 20:19:04 -07001090 size (int): Size of fake file to create
Simon Glass790ba9f2022-01-12 13:10:36 -07001091
1092 Returns:
Simon Glass9a0a2e92022-03-05 20:19:03 -07001093 tuple:
1094 fname (str): Filename of faked file
1095 bool: True if the blob was faked, False if not
Simon Glass790ba9f2022-01-12 13:10:36 -07001096 """
1097 if self.allow_fake and not pathlib.Path(fname).is_file():
Simon Glass7960a0a2022-08-07 09:46:46 -06001098 if not self.fake_fname:
1099 outfname = os.path.join(self.fake_dir, os.path.basename(fname))
1100 with open(outfname, "wb") as out:
1101 out.truncate(size)
1102 tout.info(f"Entry '{self._node.path}': Faked blob '{outfname}'")
1103 self.fake_fname = outfname
Simon Glass790ba9f2022-01-12 13:10:36 -07001104 self.faked = True
Simon Glass7960a0a2022-08-07 09:46:46 -06001105 return self.fake_fname, True
Simon Glass9a0a2e92022-03-05 20:19:03 -07001106 return fname, False
Simon Glass790ba9f2022-01-12 13:10:36 -07001107
Heiko Thierya89c8f22022-01-06 11:49:41 +01001108 def CheckFakedBlobs(self, faked_blobs_list):
1109 """Check if any entries in this section have faked external blobs
1110
1111 If there are faked blobs, the entries are added to the list
1112
1113 Args:
1114 fake_blobs_list: List of Entry objects to be added to
1115 """
1116 # This is meaningless for anything other than blobs
1117 pass
1118
Simon Glass67a05012023-01-07 14:07:15 -07001119 def CheckOptional(self, optional_list):
1120 """Check if the entry has missing but optional external blobs
1121
1122 If there are missing (optional) blobs, the entries are added to the list
1123
1124 Args:
1125 optional_list (list): List of Entry objects to be added to
1126 """
1127 if self.missing and self.optional:
1128 optional_list.append(self)
1129
Simon Glass87958982020-09-01 05:13:57 -06001130 def GetAllowMissing(self):
1131 """Get whether a section allows missing external blobs
1132
1133 Returns:
1134 True if allowed, False if not allowed
1135 """
1136 return self.allow_missing
Simon Glassb2381432020-09-06 10:39:09 -06001137
Simon Glass4f9ee832022-01-09 20:14:09 -07001138 def record_missing_bintool(self, bintool):
1139 """Record a missing bintool that was needed to produce this entry
1140
1141 Args:
1142 bintool (Bintool): Bintool that was missing
1143 """
Stefan Herbrechtsmeierfacc3782022-08-19 16:25:19 +02001144 if bintool not in self.missing_bintools:
1145 self.missing_bintools.append(bintool)
Simon Glass4f9ee832022-01-09 20:14:09 -07001146
1147 def check_missing_bintools(self, missing_list):
1148 """Check if any entries in this section have missing bintools
1149
1150 If there are missing bintools, these are added to the list
1151
1152 Args:
1153 missing_list: List of Bintool objects to be added to
1154 """
Stefan Herbrechtsmeierfacc3782022-08-19 16:25:19 +02001155 for bintool in self.missing_bintools:
1156 if bintool not in missing_list:
1157 missing_list.append(bintool)
1158
Simon Glass4f9ee832022-01-09 20:14:09 -07001159
Simon Glassb2381432020-09-06 10:39:09 -06001160 def GetHelpTags(self):
1161 """Get the tags use for missing-blob help
1162
1163 Returns:
1164 list of possible tags, most desirable first
1165 """
1166 return list(filter(None, [self.missing_msg, self.name, self.etype]))
Simon Glass87c96292020-10-26 17:40:06 -06001167
1168 def CompressData(self, indata):
1169 """Compress data according to the entry's compression method
1170
1171 Args:
1172 indata: Data to compress
1173
1174 Returns:
Stefan Herbrechtsmeier4f463e32022-08-19 16:25:27 +02001175 Compressed data
Simon Glass87c96292020-10-26 17:40:06 -06001176 """
Simon Glass97c3e9a2020-10-26 17:40:15 -06001177 self.uncomp_data = indata
Simon Glass87c96292020-10-26 17:40:06 -06001178 if self.compress != 'none':
1179 self.uncomp_size = len(indata)
Stefan Herbrechtsmeierc3665a82022-08-19 16:25:31 +02001180 if self.comp_bintool.is_present():
1181 data = self.comp_bintool.compress(indata)
1182 else:
1183 self.record_missing_bintool(self.comp_bintool)
1184 data = tools.get_bytes(0, 1024)
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001185 else:
1186 data = indata
Simon Glass87c96292020-10-26 17:40:06 -06001187 return data
Simon Glassb35fb172021-03-18 20:25:04 +13001188
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001189 def DecompressData(self, indata):
1190 """Decompress data according to the entry's compression method
1191
1192 Args:
1193 indata: Data to decompress
1194
1195 Returns:
1196 Decompressed data
1197 """
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001198 if self.compress != 'none':
Stefan Herbrechtsmeierc3665a82022-08-19 16:25:31 +02001199 if self.comp_bintool.is_present():
1200 data = self.comp_bintool.decompress(indata)
1201 self.uncomp_size = len(data)
1202 else:
1203 self.record_missing_bintool(self.comp_bintool)
1204 data = tools.get_bytes(0, 1024)
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001205 else:
1206 data = indata
Stefan Herbrechtsmeier204a27b2022-08-19 16:25:24 +02001207 self.uncomp_data = data
1208 return data
1209
Simon Glassb35fb172021-03-18 20:25:04 +13001210 @classmethod
1211 def UseExpanded(cls, node, etype, new_etype):
1212 """Check whether to use an expanded entry type
1213
1214 This is called by Entry.Create() when it finds an expanded version of
1215 an entry type (e.g. 'u-boot-expanded'). If this method returns True then
1216 it will be used (e.g. in place of 'u-boot'). If it returns False, it is
1217 ignored.
1218
1219 Args:
1220 node: Node object containing information about the entry to
1221 create
1222 etype: Original entry type being used
1223 new_etype: New entry type proposed
1224
1225 Returns:
1226 True to use this entry type, False to use the original one
1227 """
Simon Glassf3385a52022-01-29 14:14:15 -07001228 tout.info("Node '%s': etype '%s': %s selected" %
Simon Glassb35fb172021-03-18 20:25:04 +13001229 (node.path, etype, new_etype))
1230 return True
Simon Glass943bf782021-11-23 21:09:50 -07001231
1232 def CheckAltFormats(self, alt_formats):
1233 """Add any alternative formats supported by this entry type
1234
1235 Args:
1236 alt_formats (dict): Dict to add alt_formats to:
1237 key: Name of alt format
1238 value: Help text
1239 """
1240 pass
Simon Glass386c63c2022-01-09 20:13:50 -07001241
Simon Glassae9a4572022-03-05 20:19:02 -07001242 def AddBintools(self, btools):
Simon Glass386c63c2022-01-09 20:13:50 -07001243 """Add the bintools used by this entry type
1244
1245 Args:
Simon Glassae9a4572022-03-05 20:19:02 -07001246 btools (dict of Bintool):
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001247
1248 Raise:
1249 ValueError if compression algorithm is not supported
Simon Glass386c63c2022-01-09 20:13:50 -07001250 """
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001251 algo = self.compress
1252 if algo != 'none':
Stefan Herbrechtsmeiercd15b642022-08-19 16:25:38 +02001253 algos = ['bzip2', 'gzip', 'lz4', 'lzma', 'lzo', 'xz', 'zstd']
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001254 if algo not in algos:
1255 raise ValueError("Unknown algorithm '%s'" % algo)
Stefan Herbrechtsmeier7b26a462022-08-19 16:25:36 +02001256 names = {'lzma': 'lzma_alone', 'lzo': 'lzop'}
Stefan Herbrechtsmeierec7d27d2022-08-19 16:25:30 +02001257 name = names.get(self.compress, self.compress)
1258 self.comp_bintool = self.AddBintool(btools, name)
Simon Glass386c63c2022-01-09 20:13:50 -07001259
1260 @classmethod
1261 def AddBintool(self, tools, name):
1262 """Add a new bintool to the tools used by this etype
1263
1264 Args:
1265 name: Name of the tool
1266 """
1267 btool = bintool.Bintool.create(name)
1268 tools[name] = btool
1269 return btool
Alper Nebi Yasakee813c82022-02-09 22:02:35 +03001270
1271 def SetUpdateHash(self, update_hash):
1272 """Set whether this entry's "hash" subnode should be updated
1273
1274 Args:
1275 update_hash: True if hash should be updated, False if not
1276 """
1277 self.update_hash = update_hash
Simon Glass81b71c32022-02-08 11:50:00 -07001278
Simon Glass72e423c2022-03-05 20:19:05 -07001279 def collect_contents_to_file(self, entries, prefix, fake_size=0):
Simon Glass81b71c32022-02-08 11:50:00 -07001280 """Put the contents of a list of entries into a file
1281
1282 Args:
1283 entries (list of Entry): Entries to collect
1284 prefix (str): Filename prefix of file to write to
Simon Glass72e423c2022-03-05 20:19:05 -07001285 fake_size (int): Size of fake file to create if needed
Simon Glass81b71c32022-02-08 11:50:00 -07001286
1287 If any entry does not have contents yet, this function returns False
1288 for the data.
1289
1290 Returns:
1291 Tuple:
Simon Glass6d427c42022-03-05 20:18:58 -07001292 bytes: Concatenated data from all the entries (or None)
1293 str: Filename of file written (or None if no data)
1294 str: Unique portion of filename (or None if no data)
Simon Glass81b71c32022-02-08 11:50:00 -07001295 """
1296 data = b''
1297 for entry in entries:
1298 # First get the input data and put it in a file. If not available,
1299 # try later.
Simon Glass72e423c2022-03-05 20:19:05 -07001300 if not entry.ObtainContents(fake_size=fake_size):
Simon Glass6d427c42022-03-05 20:18:58 -07001301 return None, None, None
Simon Glass81b71c32022-02-08 11:50:00 -07001302 data += entry.GetData()
1303 uniq = self.GetUniqueName()
1304 fname = tools.get_output_filename(f'{prefix}.{uniq}')
1305 tools.write_file(fname, data)
1306 return data, fname, uniq
Simon Glass7960a0a2022-08-07 09:46:46 -06001307
1308 @classmethod
1309 def create_fake_dir(cls):
1310 """Create the directory for fake files"""
1311 cls.fake_dir = tools.get_output_filename('binman-fake')
1312 if not os.path.exists(cls.fake_dir):
1313 os.mkdir(cls.fake_dir)
1314 tout.notice(f"Fake-blob dir is '{cls.fake_dir}'")
Simon Glasscdadada2022-08-13 11:40:44 -06001315
1316 def ensure_props(self):
1317 """Raise an exception if properties are missing
1318
1319 Args:
1320 prop_list (list of str): List of properties to check for
1321
1322 Raises:
1323 ValueError: Any property is missing
1324 """
1325 not_present = []
1326 for prop in self.required_props:
1327 if not prop in self._node.props:
1328 not_present.append(prop)
1329 if not_present:
1330 self.Raise(f"'{self.etype}' entry is missing properties: {' '.join(not_present)}")
Simon Glassc8c9f312023-01-07 14:07:12 -07001331
1332 def mark_absent(self, msg):
1333 tout.info("Entry '%s' marked absent: %s" % (self._node.path, msg))
1334 self.absent = True
Simon Glass2f80c5e2023-01-07 14:07:14 -07001335
1336 def read_elf_segments(self):
1337 """Read segments from an entry that can generate an ELF file
1338
1339 Returns:
1340 tuple:
1341 list of segments, each:
1342 int: Segment number (0 = first)
1343 int: Start address of segment in memory
1344 bytes: Contents of segment
1345 int: entry address of ELF file
1346 """
1347 return None
Simon Glass571bc4e2023-01-11 16:10:19 -07001348
1349 def lookup_offset(self):
1350 node, sym_name, offset = self.offset_from_elf
1351 entry = self.section.FindEntryByNode(node)
1352 if not entry:
1353 self.Raise("Cannot find entry for node '%s'" % node.name)
1354 if not entry.elf_fname:
1355 entry.Raise("Need elf-fname property '%s'" % node.name)
1356 val = elf.GetSymbolOffset(entry.elf_fname, sym_name,
1357 entry.elf_base_sym)
1358 return val + offset