blob: 11aa8e50d4a2e890d821ef2cca1892bf251be860 [file] [log] [blame]
Tom Rini10e47792018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glass2574ef62016-11-25 20:15:51 -07002# Copyright (c) 2016 Google, Inc
3#
Simon Glass2574ef62016-11-25 20:15:51 -07004# Base class for all entries
5#
6
Simon Glass91710b32018-07-17 13:25:32 -06007from collections import namedtuple
Simon Glass7ccca832019-10-31 07:42:59 -06008import importlib
Simon Glass691198c2018-06-01 09:38:15 -06009import os
Simon Glass7a602fd2022-01-12 13:10:36 -070010import pathlib
Simon Glass691198c2018-06-01 09:38:15 -060011import sys
Simon Glass7d3e4072022-08-07 09:46:46 -060012import time
Simon Glass29aa7362018-09-14 04:57:19 -060013
Simon Glass4eae9252022-01-09 20:13:50 -070014from binman import bintool
Simon Glass6fc079e2022-10-20 18:22:46 -060015from binman import elf
Simon Glassc585dd42020-04-17 18:09:03 -060016from dtoc import fdt_util
Simon Glassa997ea52020-04-17 18:09:04 -060017from patman import tools
Simon Glass80025522022-01-29 14:14:04 -070018from patman.tools import to_hex, to_hex_size
Simon Glassa997ea52020-04-17 18:09:04 -060019from patman import tout
Simon Glass2574ef62016-11-25 20:15:51 -070020
21modules = {}
22
Simon Glass2a0fa982022-02-11 13:23:21 -070023# This is imported if needed
24state = None
Simon Glass91710b32018-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 Glass6b156f82019-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 Glass91710b32018-07-17 13:25:32 -060034
Simon Glass2574ef62016-11-25 20:15:51 -070035class Entry(object):
Simon Glassad5a7712018-06-01 09:38:14 -060036 """An Entry in the section
Simon Glass2574ef62016-11-25 20:15:51 -070037
38 An entry corresponds to a single node in the device-tree description
Simon Glassad5a7712018-06-01 09:38:14 -060039 of the section. Each entry ends up being a part of the final section.
Simon Glass2574ef62016-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 Glass3a9a2b82018-07-17 13:25:28 -060047 section: Section object containing this entry
Simon Glass2574ef62016-11-25 20:15:51 -070048 node: The node that created this entry
Simon Glasse8561af2018-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 Glass2574ef62016-11-25 20:15:51 -070051 size: Entry size in bytes, None if not known
Samuel Hollande2574022023-01-21 17:25:16 -060052 min_size: Minimum entry size in bytes
Simon Glass1fdb4872019-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 Glassaa2fcf92019-07-08 14:25:30 -060055 uncomp_size: Size of uncompressed data in bytes, if the entry is
56 compressed, else None
Simon Glass2574ef62016-11-25 20:15:51 -070057 contents_size: Size of contents in bytes, 0 by default
Simon Glassafb9caa2020-10-26 17:40:10 -060058 align: Entry start offset alignment relative to the start of the
59 containing section, or None
Simon Glass2574ef62016-11-25 20:15:51 -070060 align_size: Entry size alignment, or None
Simon Glassafb9caa2020-10-26 17:40:10 -060061 align_end: Entry end offset alignment relative to the start of the
62 containing section, or None
Simon Glassd12599d2020-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 Glass789b34402020-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 Glassaa2fcf92019-07-08 14:25:30 -060074 compress: Compression algoithm used (e.g. 'lz4'), 'none' if none
Simon Glasse61b6f62019-07-08 14:25:37 -060075 orig_offset: Original offset value read from node
76 orig_size: Original size value read from node
Simon Glass63328f12023-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 Glassb8f90372020-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 Thiery6d451362022-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 Glassb8f90372020-09-01 05:13:57 -060084 external: True if this entry contains an external binary blob
Simon Glass4eae9252022-01-09 20:13:50 -070085 bintools: Bintools used by this entry (only populated for Image)
Simon Glass66152ce2022-01-09 20:14:09 -070086 missing_bintools: List of missing bintools for this entry
Alper Nebi Yasak1e4ffd82022-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 Herbrechtsmeiera6e0b502022-08-19 16:25:30 +020089 comp_bintool: Bintools used for compress and decompress data
Simon Glass7d3e4072022-08-07 09:46:46 -060090 fake_fname: Fake filename, if one was created, else None
Simon Glass0cf5bce2022-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 Glass6fc079e2022-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 Glass1e9e61c2023-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 Glass63328f12023-01-07 14:07:15 -0700101 optional (bool): True if this entry contains an optional external blob
Simon Glassf1ee03b2023-01-11 16:10:16 -0700102 overlap (bool): True if this entry overlaps with others
Simon Glasscda991e2023-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 Glass2574ef62016-11-25 20:15:51 -0700107 """
Simon Glass7d3e4072022-08-07 09:46:46 -0600108 fake_dir = None
109
Simon Glass6fc079e2022-10-20 18:22:46 -0600110 def __init__(self, section, etype, node, name_prefix='',
111 auto_write_symbols=False):
Simon Glassb9ba4e02019-08-24 07:22:44 -0600112 # Put this here to allow entry-docs and help to work without libfdt
113 global state
Simon Glassc585dd42020-04-17 18:09:03 -0600114 from binman import state
Simon Glassb9ba4e02019-08-24 07:22:44 -0600115
Simon Glassad5a7712018-06-01 09:38:14 -0600116 self.section = section
Simon Glass2574ef62016-11-25 20:15:51 -0700117 self.etype = etype
118 self._node = node
Simon Glass3b78d532018-06-01 09:38:21 -0600119 self.name = node and (name_prefix + node.name) or 'none'
Simon Glasse8561af2018-08-01 15:22:37 -0600120 self.offset = None
Simon Glass2574ef62016-11-25 20:15:51 -0700121 self.size = None
Samuel Hollande2574022023-01-21 17:25:16 -0600122 self.min_size = 0
Simon Glass1fdb4872019-10-31 07:43:02 -0600123 self.pre_reset_size = None
Simon Glassaa2fcf92019-07-08 14:25:30 -0600124 self.uncomp_size = None
Simon Glass5c350162018-07-17 13:25:47 -0600125 self.data = None
Simon Glass789b34402020-10-26 17:40:15 -0600126 self.uncomp_data = None
Simon Glass2574ef62016-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 Glasse8561af2018-08-01 15:22:37 -0600133 self.offset_unset = False
Simon Glass9dcc8612018-08-01 15:22:42 -0600134 self.image_pos = None
Simon Glassdd156a42022-03-05 20:18:59 -0700135 self.extend_size = False
Simon Glassaa2fcf92019-07-08 14:25:30 -0600136 self.compress = 'none'
Simon Glassa003cd32020-07-09 18:39:40 -0600137 self.missing = False
Heiko Thiery6d451362022-01-06 11:49:41 +0100138 self.faked = False
Simon Glassb8f90372020-09-01 05:13:57 -0600139 self.external = False
140 self.allow_missing = False
Heiko Thiery6d451362022-01-06 11:49:41 +0100141 self.allow_fake = False
Simon Glass4eae9252022-01-09 20:13:50 -0700142 self.bintools = {}
Simon Glass66152ce2022-01-09 20:14:09 -0700143 self.missing_bintools = []
Alper Nebi Yasak1e4ffd82022-02-09 22:02:35 +0300144 self.update_hash = True
Simon Glass7d3e4072022-08-07 09:46:46 -0600145 self.fake_fname = None
Simon Glass0cf5bce2022-08-13 11:40:44 -0600146 self.required_props = []
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +0200147 self.comp_bintool = None
Simon Glass6fc079e2022-10-20 18:22:46 -0600148 self.elf_fname = None
149 self.auto_write_symbols = auto_write_symbols
Simon Glass1e9e61c2023-01-07 14:07:12 -0700150 self.absent = False
Simon Glass63328f12023-01-07 14:07:15 -0700151 self.optional = False
Simon Glassf1ee03b2023-01-11 16:10:16 -0700152 self.overlap = False
Simon Glasse0035c92023-01-11 16:10:17 -0700153 self.elf_base_sym = None
Simon Glass49e9c002023-01-11 16:10:19 -0700154 self.offset_from_elf = None
Simon Glasscda991e2023-02-12 17:11:15 -0700155 self.preserve = False
Simon Glass2574ef62016-11-25 20:15:51 -0700156
157 @staticmethod
Simon Glassb9028bc2021-11-23 21:09:49 -0700158 def FindEntryClass(etype, expanded):
Simon Glass969616c2018-07-17 13:25:36 -0600159 """Look up the entry class for a node.
Simon Glass2574ef62016-11-25 20:15:51 -0700160
161 Args:
Simon Glass969616c2018-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 Glass2f859412021-03-18 20:25:04 +1300165 expanded: Use the expanded version of etype
Simon Glass2574ef62016-11-25 20:15:51 -0700166
167 Returns:
Simon Glass2f859412021-03-18 20:25:04 +1300168 The entry class object if found, else None if not found and expanded
Simon Glassb9028bc2021-11-23 21:09:49 -0700169 is True, else a tuple:
170 module name that could not be found
171 exception received
Simon Glass2574ef62016-11-25 20:15:51 -0700172 """
Simon Glasse76a3e62018-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 Glass2574ef62016-11-25 20:15:51 -0700175 module_name = etype.replace('-', '_')
Simon Glass2f859412021-03-18 20:25:04 +1300176
Simon Glasse76a3e62018-06-01 09:38:11 -0600177 if '@' in module_name:
178 module_name = module_name.split('@')[0]
Simon Glass2f859412021-03-18 20:25:04 +1300179 if expanded:
180 module_name += '_expanded'
Simon Glass2574ef62016-11-25 20:15:51 -0700181 module = modules.get(module_name)
182
Simon Glass691198c2018-06-01 09:38:15 -0600183 # Also allow entry-type modules to be brought in from the etype directory.
184
Simon Glass2574ef62016-11-25 20:15:51 -0700185 # Import the module if we have not already done so.
186 if not module:
187 try:
Simon Glassc585dd42020-04-17 18:09:03 -0600188 module = importlib.import_module('binman.etype.' + module_name)
Simon Glass969616c2018-07-17 13:25:36 -0600189 except ImportError as e:
Simon Glass2f859412021-03-18 20:25:04 +1300190 if expanded:
191 return None
Simon Glassb9028bc2021-11-23 21:09:49 -0700192 return module_name, e
Simon Glass2574ef62016-11-25 20:15:51 -0700193 modules[module_name] = module
194
Simon Glass969616c2018-07-17 13:25:36 -0600195 # Look up the expected class name
196 return getattr(module, 'Entry_%s' % module_name)
197
198 @staticmethod
Simon Glassb9028bc2021-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 Glass969616c2018-07-17 13:25:36 -0600234 """Create a new entry for a node.
235
236 Args:
Simon Glassb9028bc2021-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 Glass969616c2018-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 Glassb9028bc2021-11-23 21:09:49 -0700251 obj = Entry.Lookup(node.path, etype, expanded, missing_etype)
Simon Glass2f859412021-03-18 20:25:04 +1300252 if obj and expanded:
253 # Check whether to use the expanded entry
254 new_etype = etype + '-expanded'
Simon Glass7098b7f2021-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 Glass2f859412021-03-18 20:25:04 +1300257 etype = new_etype
258 else:
259 obj = None
260 if not obj:
Simon Glassb9028bc2021-11-23 21:09:49 -0700261 obj = Entry.Lookup(node.path, etype, False, missing_etype)
Simon Glass969616c2018-07-17 13:25:36 -0600262
Simon Glass2574ef62016-11-25 20:15:51 -0700263 # Call its constructor to get the object we want.
Simon Glassad5a7712018-06-01 09:38:14 -0600264 return obj(section, etype, node)
Simon Glass2574ef62016-11-25 20:15:51 -0700265
266 def ReadNode(self):
267 """Read entry information from the node
268
Simon Glass2c360cf2019-07-20 12:23:45 -0600269 This must be called as the first thing after the Entry is created.
270
Simon Glass2574ef62016-11-25 20:15:51 -0700271 This reads all the fields we recognise from the node, ready for use.
272 """
Simon Glass0cf5bce2022-08-13 11:40:44 -0600273 self.ensure_props()
Simon Glass24b97442018-07-17 13:25:51 -0600274 if 'pos' in self._node.props:
275 self.Raise("Please use 'offset' instead of 'pos'")
Simon Glassdd156a42022-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 Glasse8561af2018-08-01 15:22:37 -0600278 self.offset = fdt_util.GetInt(self._node, 'offset')
Simon Glass2574ef62016-11-25 20:15:51 -0700279 self.size = fdt_util.GetInt(self._node, 'size')
Samuel Hollande2574022023-01-21 17:25:16 -0600280 self.min_size = fdt_util.GetInt(self._node, 'min-size', 0)
Simon Glassfb30e292019-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 Glasse61b6f62019-07-08 14:25:37 -0600286
Simon Glassb8424fa2019-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 Glass2574ef62016-11-25 20:15:51 -0700292 self.align = fdt_util.GetInt(self._node, 'align')
Simon Glass80025522022-01-29 14:14:04 -0700293 if tools.not_power_of_two(self.align):
Simon Glass2574ef62016-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 Glassf427c5f2021-03-21 18:24:33 +1300296 if self.section and self.align is None:
297 self.align = self.section.align_default
Simon Glass2574ef62016-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 Glass80025522022-01-29 14:14:04 -0700301 if tools.not_power_of_two(self.align_size):
Simon Glass39dd2152019-07-08 14:25:47 -0600302 self.Raise("Alignment size %s must be a power of two" %
303 self.align_size)
Simon Glass2574ef62016-11-25 20:15:51 -0700304 self.align_end = fdt_util.GetInt(self._node, 'align-end')
Simon Glasse8561af2018-08-01 15:22:37 -0600305 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
Simon Glassdd156a42022-03-05 20:18:59 -0700306 self.extend_size = fdt_util.GetBool(self._node, 'extend-size')
Simon Glassa820af72020-09-06 10:39:09 -0600307 self.missing_msg = fdt_util.GetString(self._node, 'missing-msg')
Simon Glass63328f12023-01-07 14:07:15 -0700308 self.optional = fdt_util.GetBool(self._node, 'optional')
Simon Glassf1ee03b2023-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 Glass2574ef62016-11-25 20:15:51 -0700312
Simon Glassa1301a22020-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 Glass49e9c002023-01-11 16:10:19 -0700315 self.offset_from_elf = fdt_util.GetPhandleNameOffset(self._node,
316 'offset-from-elf')
Simon Glassa1301a22020-10-26 17:40:06 -0600317
Simon Glasscda991e2023-02-12 17:11:15 -0700318 self.preserve = fdt_util.GetBool(self._node, 'preserve')
319
Simon Glass3732ec32018-09-14 04:57:18 -0600320 def GetDefaultFilename(self):
321 return None
322
Simon Glass267112e2019-07-20 12:23:28 -0600323 def GetFdts(self):
324 """Get the device trees used by this entry
Simon Glass0c9d5b52018-09-14 04:57:22 -0600325
326 Returns:
Simon Glass267112e2019-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 Glass684a4f12019-07-20 12:23:31 -0600330 value: Tuple:
Simon Glass8235dd82021-03-18 20:25:02 +1300331 Entry object for this dtb
Simon Glass684a4f12019-07-20 12:23:31 -0600332 Filename of file containing this dtb
Simon Glass0c9d5b52018-09-14 04:57:22 -0600333 """
Simon Glass267112e2019-07-20 12:23:28 -0600334 return {}
Simon Glass0c9d5b52018-09-14 04:57:22 -0600335
Simon Glassf86ddad2022-03-05 20:19:00 -0700336 def gen_entries(self):
337 """Allow entries to generate other entries
Simon Glassfcb2a7c2021-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 Glassac6328c2018-09-14 04:57:28 -0600348 pass
349
Simon Glassacd6c6e2020-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 Glasse22f8fa2018-07-06 10:27:41 -0600360 if not prop in self._node.props:
Simon Glassc8135dc2018-09-14 04:57:21 -0600361 state.AddZeroProp(self._node, prop)
Simon Glassacd6c6e2020-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 Glassfb30e292019-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 Glassaa2fcf92019-07-08 14:25:30 -0600370 if self.compress != 'none':
371 state.AddZeroProp(self._node, 'uncomp-size')
Alper Nebi Yasak1e4ffd82022-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 Glasse22f8fa2018-07-06 10:27:41 -0600377
378 def SetCalculatedProperties(self):
379 """Set the value of device-tree properties calculated by binman"""
Simon Glassc8135dc2018-09-14 04:57:21 -0600380 state.SetInt(self._node, 'offset', self.offset)
381 state.SetInt(self._node, 'size', self.size)
Simon Glass39dd2152019-07-08 14:25:47 -0600382 base = self.section.GetRootSkipAtStart() if self.section else 0
Simon Glassacd6c6e2020-10-26 17:40:17 -0600383 if self.image_pos is not None:
Simon Glasseb943b12020-11-02 12:55:44 -0700384 state.SetInt(self._node, 'image-pos', self.image_pos - base)
Simon Glassfb30e292019-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 Glassaa2fcf92019-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 Yasak1e4ffd82022-02-09 22:02:35 +0300392
393 if self.update_hash:
394 state.CheckSetHashValue(self._node, self.GetData)
Simon Glasse22f8fa2018-07-06 10:27:41 -0600395
Simon Glass92307732018-07-06 10:27:40 -0600396 def ProcessFdt(self, fdt):
Simon Glasse219aa42018-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 Glass92307732018-07-06 10:27:40 -0600408 return True
409
Simon Glass3b78d532018-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 Glass2e1169f2018-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 Glassd17dfea2019-07-08 14:25:33 -0600425 data: Data to set to the contents (bytes)
Simon Glass2e1169f2018-07-06 10:27:19 -0600426 """
427 self.data = data
428 self.contents_size = len(self.data)
429
430 def ProcessContentsUpdate(self, data):
Simon Glassd17dfea2019-07-08 14:25:33 -0600431 """Update the contents of an entry, after the size is fixed
Simon Glass2e1169f2018-07-06 10:27:19 -0600432
Simon Glassec849852019-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 Glass2e1169f2018-07-06 10:27:19 -0600435
436 Args:
Simon Glassd17dfea2019-07-08 14:25:33 -0600437 data: Data to set to the contents (bytes)
Simon Glass2e1169f2018-07-06 10:27:19 -0600438
439 Raises:
440 ValueError if the new data size is not the same as the old
441 """
Simon Glassec849852019-07-08 14:25:35 -0600442 size_ok = True
Simon Glasse61b6f62019-07-08 14:25:37 -0600443 new_size = len(data)
Simon Glass9d8ee322019-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 Glasse61b6f62019-07-08 14:25:37 -0600452 if new_size > self.contents_size:
Simon Glass9d8ee322019-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 Glass80025522022-01-29 14:14:04 -0700458 data += tools.get_bytes(0, self.contents_size - new_size)
Simon Glass9d8ee322019-07-20 12:23:58 -0600459
460 if not size_ok:
Simon Glass011f1b32022-01-29 14:14:15 -0700461 tout.debug("Entry '%s' size change from %s to %s" % (
Simon Glass80025522022-01-29 14:14:04 -0700462 self._node.path, to_hex(self.contents_size),
463 to_hex(new_size)))
Simon Glass2e1169f2018-07-06 10:27:19 -0600464 self.SetContents(data)
Simon Glassec849852019-07-08 14:25:35 -0600465 return size_ok
Simon Glass2e1169f2018-07-06 10:27:19 -0600466
Simon Glassfc5a1682022-03-05 20:19:05 -0700467 def ObtainContents(self, skip_entry=None, fake_size=0):
Simon Glass2574ef62016-11-25 20:15:51 -0700468 """Figure out the contents of an entry.
469
Simon Glassfc5a1682022-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 Glass2574ef62016-11-25 20:15:51 -0700474 Returns:
475 True if the contents were found, False if another call is needed
Simon Glassa4948b22023-01-11 16:10:14 -0700476 after the other entries are processed, None if there is no contents
Simon Glass2574ef62016-11-25 20:15:51 -0700477 """
478 # No contents by default: subclasses can implement this
479 return True
480
Simon Glasse61b6f62019-07-08 14:25:37 -0600481 def ResetForPack(self):
482 """Reset offset/size fields so that packing can be done again"""
Simon Glassb6dff4c2019-07-20 12:23:36 -0600483 self.Detail('ResetForPack: offset %s->%s, size %s->%s' %
Simon Glass80025522022-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 Glass1fdb4872019-10-31 07:43:02 -0600486 self.pre_reset_size = self.size
Simon Glasse61b6f62019-07-08 14:25:37 -0600487 self.offset = self.orig_offset
488 self.size = self.orig_size
489
Simon Glasse8561af2018-08-01 15:22:37 -0600490 def Pack(self, offset):
Simon Glassad5a7712018-06-01 09:38:14 -0600491 """Figure out how to pack the entry into the section
Simon Glass2574ef62016-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 Glasse8561af2018-08-01 15:22:37 -0600497 If an entry has no hard-coded offset, it will be placed at @offset.
Simon Glass2574ef62016-11-25 20:15:51 -0700498
Simon Glasse8561af2018-08-01 15:22:37 -0600499 Once this function is complete, both the offset and size of the
Simon Glass2574ef62016-11-25 20:15:51 -0700500 entry will be know.
501
502 Args:
Simon Glasse8561af2018-08-01 15:22:37 -0600503 Current section offset pointer
Simon Glass2574ef62016-11-25 20:15:51 -0700504
505 Returns:
Simon Glasse8561af2018-08-01 15:22:37 -0600506 New section offset pointer (after this entry)
Simon Glass2574ef62016-11-25 20:15:51 -0700507 """
Simon Glassb6dff4c2019-07-20 12:23:36 -0600508 self.Detail('Packing: offset=%s, size=%s, content_size=%x' %
Simon Glass80025522022-01-29 14:14:04 -0700509 (to_hex(self.offset), to_hex(self.size),
Simon Glassb6dff4c2019-07-20 12:23:36 -0600510 self.contents_size))
Simon Glasse8561af2018-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 Glass49e9c002023-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 Glass2574ef62016-11-25 20:15:51 -0700519 needed = self.pad_before + self.contents_size + self.pad_after
Samuel Hollande2574022023-01-21 17:25:16 -0600520 needed = max(needed, self.min_size)
Simon Glass80025522022-01-29 14:14:04 -0700521 needed = tools.align(needed, self.align_size)
Simon Glass2574ef62016-11-25 20:15:51 -0700522 size = self.size
523 if not size:
524 size = needed
Simon Glasse8561af2018-08-01 15:22:37 -0600525 new_offset = self.offset + size
Simon Glass80025522022-01-29 14:14:04 -0700526 aligned_offset = tools.align(new_offset, self.align_end)
Simon Glasse8561af2018-08-01 15:22:37 -0600527 if aligned_offset != new_offset:
528 size = aligned_offset - self.offset
529 new_offset = aligned_offset
Simon Glass2574ef62016-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 Glasse8561af2018-08-01 15:22:37 -0600538 # and offset or size values were provided (i.e. not calculated), but
Simon Glass2574ef62016-11-25 20:15:51 -0700539 # conflict with the provided alignment values
Simon Glass80025522022-01-29 14:14:04 -0700540 if self.size != tools.align(self.size, self.align_size):
Simon Glass2574ef62016-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 Glass80025522022-01-29 14:14:04 -0700543 if self.offset != tools.align(self.offset, self.align):
Simon Glasse8561af2018-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 Glassb6dff4c2019-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 Glass2574ef62016-11-25 20:15:51 -0700548
Simon Glasse8561af2018-08-01 15:22:37 -0600549 return new_offset
Simon Glass2574ef62016-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 Glasse1915782021-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 Glass011f1b32022-01-29 14:14:15 -0700558 tout.detail('%30s: %s' % (tag, msg))
Simon Glasse1915782021-03-21 18:24:31 +1300559
Simon Glassb6dff4c2019-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 Glass011f1b32022-01-29 14:14:15 -0700563 tout.detail('%30s: %s' % (tag, msg))
Simon Glassb6dff4c2019-07-20 12:23:36 -0600564
Simon Glass91710b32018-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 Glass3fb25402021-01-06 21:35:16 -0700588 self.GetImage().MissingArgs(self, missing)
Simon Glass91710b32018-07-17 13:25:32 -0600589 return values
590
Simon Glass2574ef62016-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 Glass27a7f772021-03-21 18:24:32 +1300599 def GetData(self, required=True):
Simon Glass72eeff12020-10-26 17:40:16 -0600600 """Get the contents of an entry
601
Simon Glass27a7f772021-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 Glass72eeff12020-10-26 17:40:16 -0600606 Returns:
607 bytes content of the entry, excluding any padding. If the entry is
Simon Glass02997652023-01-11 16:10:13 -0700608 compressed, the compressed data is returned. If the entry data
Simon Glassa4948b22023-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 Glass72eeff12020-10-26 17:40:16 -0600611 """
Simon Glass80025522022-01-29 14:14:04 -0700612 self.Detail('GetData: size %s' % to_hex_size(self.data))
Simon Glass2574ef62016-11-25 20:15:51 -0700613 return self.data
614
Simon Glasse17220f2020-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 Glasse8561af2018-08-01 15:22:37 -0600631 def GetOffsets(self):
Simon Glass224bc662019-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 Glassed365eb2019-07-08 13:18:39 -0600645 type. Either can be None if not known
Simon Glass224bc662019-07-08 13:18:30 -0600646 """
Simon Glass2574ef62016-11-25 20:15:51 -0700647 return {}
648
Simon Glassed365eb2019-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 Glass2574ef62016-11-25 20:15:51 -0700660
Simon Glass9dcc8612018-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 Glass2574ef62016-11-25 20:15:51 -0700669 def ProcessContents(self):
Simon Glassec849852019-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 Glass4ca8e042017-11-13 18:55:01 -0700686
Simon Glass8a6f56e2018-06-01 09:38:13 -0600687 def WriteSymbols(self, section):
Simon Glass4ca8e042017-11-13 18:55:01 -0700688 """Write symbol values into binary files for access at run time
689
690 Args:
Simon Glass8a6f56e2018-06-01 09:38:13 -0600691 section: Section containing the entry
Simon Glass4ca8e042017-11-13 18:55:01 -0700692 """
Simon Glass6fc079e2022-10-20 18:22:46 -0600693 if self.auto_write_symbols:
Simon Glass37f85de2022-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 Glasse0035c92023-01-11 16:10:17 -0700697 is_elf, self.elf_base_sym)
Simon Glassa91e1152018-06-01 09:38:16 -0600698
Simon Glass55f68072020-10-26 17:40:18 -0600699 def CheckEntries(self):
Simon Glasse8561af2018-08-01 15:22:37 -0600700 """Check that the entry offsets are correct
Simon Glassa91e1152018-06-01 09:38:16 -0600701
Simon Glasse8561af2018-08-01 15:22:37 -0600702 This is used for entries which have extra offset requirements (other
Simon Glassa91e1152018-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 Glass30732662018-06-01 09:38:20 -0600707
Simon Glass3a9a2b82018-07-17 13:25:28 -0600708 @staticmethod
Simon Glasscd817d52018-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 Glass7eca7922018-07-17 13:25:49 -0600715 def WriteMapLine(fd, indent, name, offset, size, image_pos):
Simon Glasscd817d52018-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 Glass3a9a2b82018-07-17 13:25:28 -0600719
Simon Glass30732662018-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 Glass7eca7922018-07-17 13:25:49 -0600727 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
728 self.image_pos)
Simon Glass91710b32018-07-17 13:25:32 -0600729
Simon Glassbd5cd882022-08-13 11:40:50 -0600730 # pylint: disable=assignment-from-none
Simon Glass704784b2018-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 Glassbd5cd882022-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 Glass91710b32018-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 Glass29aa7362018-09-14 04:57:19 -0600778 value = state.GetEntryArg(name)
Simon Glass91710b32018-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 Glass969616c2018-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 Glass2f859412021-03-18 20:25:04 +1300824 module = Entry.Lookup('WriteDocs', name, False)
Simon Glass969616c2018-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 Glassa7c97782022-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 Glass969616c2018-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 Glass639505b2018-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 Yasak5cff63f2022-03-27 18:31:44 +0300863 if node.name in ('binman', '/'):
Simon Glass639505b2018-09-14 04:57:11 -0600864 break
865 name = '%s.%s' % (node.name, name)
866 return name
Simon Glassfa79a812018-09-14 04:57:29 -0600867
Simon Glassdd156a42022-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 Glassfa79a812018-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 Glassc4056b82019-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 Glasscec34ba2019-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 Glass6b156f82019-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 Glass4c613bf2019-07-08 14:25:50 -0600928
Simon Glass637958f2021-11-23 21:09:50 -0700929 def ReadData(self, decomp=True, alt_format=None):
Simon Glass4c613bf2019-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 Glass011f1b32022-01-29 14:14:15 -0700944 tout.debug("ReadChildData section '%s', entry '%s'" %
Simon Glass4d8151f2019-09-25 08:56:21 -0600945 (self.section.GetPath(), self.GetPath()))
Simon Glass637958f2021-11-23 21:09:50 -0700946 data = self.section.ReadChildData(self, decomp, alt_format)
Simon Glass0cd8ace2019-07-20 12:24:04 -0600947 return data
Simon Glassaf8c45c2019-07-20 12:23:41 -0600948
Simon Glass637958f2021-11-23 21:09:50 -0700949 def ReadChildData(self, child, decomp=True, alt_format=None):
Simon Glass4d8151f2019-09-25 08:56:21 -0600950 """Read the data for a particular child entry
Simon Glass23f00472019-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 Glass637958f2021-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 Glass23f00472019-09-25 08:56:20 -0600960
961 Returns:
962 Data for the child (bytes)
963 """
964 pass
965
Simon Glassaf8c45c2019-07-20 12:23:41 -0600966 def LoadData(self, decomp=True):
967 data = self.ReadData(decomp)
Simon Glass072959a2019-07-20 12:23:50 -0600968 self.contents_size = len(data)
Simon Glassaf8c45c2019-07-20 12:23:41 -0600969 self.ProcessContentsUpdate(data)
970 self.Detail('Loaded data size %x' % len(data))
Simon Glass990b1742019-07-20 12:23:46 -0600971
Simon Glass637958f2021-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 Glass990b1742019-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 Glass072959a2019-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 Glass1fdb4872019-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 Glass072959a2019-07-20 12:23:50 -06001015 ok = self.ProcessContentsUpdate(data)
1016 self.Detail('WriteData: size=%x, ok=%s' % (len(data), ok))
Simon Glassd34af7a2019-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 Glasse796f242021-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 Glassd34af7a2019-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 Glasse796f242021-11-23 11:03:44 -07001035 data is such that the section could not update
Simon Glassd34af7a2019-07-20 12:24:05 -06001036 """
1037 return True
Simon Glass11453762019-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 Glass5d94cc62020-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 Glassa003cd32020-07-09 18:39:40 -06001062
Heiko Thiery6d451362022-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 Glassceb5f912022-01-09 20:13:46 -07001069 self.allow_fake = allow_fake
Heiko Thiery6d451362022-01-06 11:49:41 +01001070
Simon Glassa003cd32020-07-09 18:39:40 -06001071 def CheckMissing(self, missing_list):
Simon Glass63328f12023-01-07 14:07:15 -07001072 """Check if the entry has missing external blobs
Simon Glassa003cd32020-07-09 18:39:40 -06001073
Simon Glass63328f12023-01-07 14:07:15 -07001074 If there are missing (non-optional) blobs, the entries are added to the
1075 list
Simon Glassa003cd32020-07-09 18:39:40 -06001076
1077 Args:
1078 missing_list: List of Entry objects to be added to
1079 """
Simon Glass63328f12023-01-07 14:07:15 -07001080 if self.missing and not self.optional:
Simon Glassa003cd32020-07-09 18:39:40 -06001081 missing_list.append(self)
Simon Glassb8f90372020-09-01 05:13:57 -06001082
Simon Glass8c0533b2022-03-05 20:19:04 -07001083 def check_fake_fname(self, fname, size=0):
Simon Glass7a602fd2022-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 Glass8c0533b2022-03-05 20:19:04 -07001090 size (int): Size of fake file to create
Simon Glass7a602fd2022-01-12 13:10:36 -07001091
1092 Returns:
Simon Glass214d36f2022-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 Glass7a602fd2022-01-12 13:10:36 -07001096 """
1097 if self.allow_fake and not pathlib.Path(fname).is_file():
Simon Glass7d3e4072022-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 Glass7a602fd2022-01-12 13:10:36 -07001104 self.faked = True
Simon Glass7d3e4072022-08-07 09:46:46 -06001105 return self.fake_fname, True
Simon Glass214d36f2022-03-05 20:19:03 -07001106 return fname, False
Simon Glass7a602fd2022-01-12 13:10:36 -07001107
Heiko Thiery6d451362022-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:
Jonas Karlmanf2c52eb2023-02-19 22:02:04 +00001114 faked_blobs_list: List of Entry objects to be added to
Heiko Thiery6d451362022-01-06 11:49:41 +01001115 """
1116 # This is meaningless for anything other than blobs
1117 pass
1118
Simon Glass63328f12023-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 Glassb8f90372020-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 Glassa820af72020-09-06 10:39:09 -06001137
Simon Glass66152ce2022-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 Herbrechtsmeier486b9442022-08-19 16:25:19 +02001144 if bintool not in self.missing_bintools:
1145 self.missing_bintools.append(bintool)
Simon Glass66152ce2022-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 Herbrechtsmeier486b9442022-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 Glass66152ce2022-01-09 20:14:09 -07001159
Simon Glassa820af72020-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 Glassa1301a22020-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 Herbrechtsmeierb2f8d612022-08-19 16:25:27 +02001175 Compressed data
Simon Glassa1301a22020-10-26 17:40:06 -06001176 """
Simon Glass789b34402020-10-26 17:40:15 -06001177 self.uncomp_data = indata
Simon Glassa1301a22020-10-26 17:40:06 -06001178 if self.compress != 'none':
1179 self.uncomp_size = len(indata)
Stefan Herbrechtsmeier94813a02022-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 Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001185 else:
1186 data = indata
Simon Glassa1301a22020-10-26 17:40:06 -06001187 return data
Simon Glass2f859412021-03-18 20:25:04 +13001188
Stefan Herbrechtsmeier7f128a72022-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 Herbrechtsmeier7f128a72022-08-19 16:25:24 +02001198 if self.compress != 'none':
Stefan Herbrechtsmeier94813a02022-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 Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001205 else:
1206 data = indata
Stefan Herbrechtsmeier7f128a72022-08-19 16:25:24 +02001207 self.uncomp_data = data
1208 return data
1209
Simon Glass2f859412021-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 Glass011f1b32022-01-29 14:14:15 -07001228 tout.info("Node '%s': etype '%s': %s selected" %
Simon Glass2f859412021-03-18 20:25:04 +13001229 (node.path, etype, new_etype))
1230 return True
Simon Glass637958f2021-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 Glass4eae9252022-01-09 20:13:50 -07001241
Simon Glassfff147a2022-03-05 20:19:02 -07001242 def AddBintools(self, btools):
Simon Glass4eae9252022-01-09 20:13:50 -07001243 """Add the bintools used by this entry type
1244
1245 Args:
Simon Glassfff147a2022-03-05 20:19:02 -07001246 btools (dict of Bintool):
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001247
1248 Raise:
1249 ValueError if compression algorithm is not supported
Simon Glass4eae9252022-01-09 20:13:50 -07001250 """
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001251 algo = self.compress
1252 if algo != 'none':
Stefan Herbrechtsmeiera5e4dcb2022-08-19 16:25:38 +02001253 algos = ['bzip2', 'gzip', 'lz4', 'lzma', 'lzo', 'xz', 'zstd']
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001254 if algo not in algos:
1255 raise ValueError("Unknown algorithm '%s'" % algo)
Stefan Herbrechtsmeier9087fc52022-08-19 16:25:36 +02001256 names = {'lzma': 'lzma_alone', 'lzo': 'lzop'}
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001257 name = names.get(self.compress, self.compress)
1258 self.comp_bintool = self.AddBintool(btools, name)
Simon Glass4eae9252022-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 Yasak1e4ffd82022-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 Glass6fba35c2022-02-08 11:50:00 -07001278
Simon Glassfc5a1682022-03-05 20:19:05 -07001279 def collect_contents_to_file(self, entries, prefix, fake_size=0):
Simon Glass6fba35c2022-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 Glassfc5a1682022-03-05 20:19:05 -07001285 fake_size (int): Size of fake file to create if needed
Simon Glass6fba35c2022-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 Glass43a98cc2022-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 Glass6fba35c2022-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 Glassfc5a1682022-03-05 20:19:05 -07001300 if not entry.ObtainContents(fake_size=fake_size):
Simon Glass43a98cc2022-03-05 20:18:58 -07001301 return None, None, None
Simon Glass6fba35c2022-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 Glass7d3e4072022-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 Glass0cf5bce2022-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 Glass1e9e61c2023-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 Glassad5cfe12023-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 Glass49e9c002023-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