blob: 219d5dcecab75b65b7e2a18de837c0796f880029 [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 Glass131444f2023-02-23 18:18:04 -070017from u_boot_pylib import tools
18from u_boot_pylib.tools import to_hex, to_hex_size
19from u_boot_pylib 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 Glass49b77e82023-03-02 17:02:44 -0700107 build_done (bool): Indicates that the entry data has been built and does
108 not need to be done again. This is only used with 'binman replace',
109 to stop sections from being rebuilt if their entries have not been
110 replaced
Simon Glass2574ef62016-11-25 20:15:51 -0700111 """
Simon Glass7d3e4072022-08-07 09:46:46 -0600112 fake_dir = None
113
Simon Glass6fc079e2022-10-20 18:22:46 -0600114 def __init__(self, section, etype, node, name_prefix='',
115 auto_write_symbols=False):
Simon Glassb9ba4e02019-08-24 07:22:44 -0600116 # Put this here to allow entry-docs and help to work without libfdt
117 global state
Simon Glassc585dd42020-04-17 18:09:03 -0600118 from binman import state
Simon Glassb9ba4e02019-08-24 07:22:44 -0600119
Simon Glassad5a7712018-06-01 09:38:14 -0600120 self.section = section
Simon Glass2574ef62016-11-25 20:15:51 -0700121 self.etype = etype
122 self._node = node
Simon Glass3b78d532018-06-01 09:38:21 -0600123 self.name = node and (name_prefix + node.name) or 'none'
Simon Glasse8561af2018-08-01 15:22:37 -0600124 self.offset = None
Simon Glass2574ef62016-11-25 20:15:51 -0700125 self.size = None
Samuel Hollande2574022023-01-21 17:25:16 -0600126 self.min_size = 0
Simon Glass1fdb4872019-10-31 07:43:02 -0600127 self.pre_reset_size = None
Simon Glassaa2fcf92019-07-08 14:25:30 -0600128 self.uncomp_size = None
Simon Glass5c350162018-07-17 13:25:47 -0600129 self.data = None
Simon Glass789b34402020-10-26 17:40:15 -0600130 self.uncomp_data = None
Simon Glass2574ef62016-11-25 20:15:51 -0700131 self.contents_size = 0
132 self.align = None
133 self.align_size = None
134 self.align_end = None
135 self.pad_before = 0
136 self.pad_after = 0
Simon Glasse8561af2018-08-01 15:22:37 -0600137 self.offset_unset = False
Simon Glass9dcc8612018-08-01 15:22:42 -0600138 self.image_pos = None
Simon Glassdd156a42022-03-05 20:18:59 -0700139 self.extend_size = False
Simon Glassaa2fcf92019-07-08 14:25:30 -0600140 self.compress = 'none'
Simon Glassa003cd32020-07-09 18:39:40 -0600141 self.missing = False
Heiko Thiery6d451362022-01-06 11:49:41 +0100142 self.faked = False
Simon Glassb8f90372020-09-01 05:13:57 -0600143 self.external = False
144 self.allow_missing = False
Heiko Thiery6d451362022-01-06 11:49:41 +0100145 self.allow_fake = False
Simon Glass4eae9252022-01-09 20:13:50 -0700146 self.bintools = {}
Simon Glass66152ce2022-01-09 20:14:09 -0700147 self.missing_bintools = []
Alper Nebi Yasak1e4ffd82022-02-09 22:02:35 +0300148 self.update_hash = True
Simon Glass7d3e4072022-08-07 09:46:46 -0600149 self.fake_fname = None
Simon Glass0cf5bce2022-08-13 11:40:44 -0600150 self.required_props = []
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +0200151 self.comp_bintool = None
Simon Glass6fc079e2022-10-20 18:22:46 -0600152 self.elf_fname = None
153 self.auto_write_symbols = auto_write_symbols
Simon Glass1e9e61c2023-01-07 14:07:12 -0700154 self.absent = False
Simon Glass63328f12023-01-07 14:07:15 -0700155 self.optional = False
Simon Glassf1ee03b2023-01-11 16:10:16 -0700156 self.overlap = False
Simon Glasse0035c92023-01-11 16:10:17 -0700157 self.elf_base_sym = None
Simon Glass49e9c002023-01-11 16:10:19 -0700158 self.offset_from_elf = None
Simon Glasscda991e2023-02-12 17:11:15 -0700159 self.preserve = False
Simon Glass49b77e82023-03-02 17:02:44 -0700160 self.build_done = False
Simon Glass4abf7842023-07-18 07:23:54 -0600161 self.no_write_symbols = False
Simon Glass2574ef62016-11-25 20:15:51 -0700162
163 @staticmethod
Simon Glassb9028bc2021-11-23 21:09:49 -0700164 def FindEntryClass(etype, expanded):
Simon Glass969616c2018-07-17 13:25:36 -0600165 """Look up the entry class for a node.
Simon Glass2574ef62016-11-25 20:15:51 -0700166
167 Args:
Simon Glass969616c2018-07-17 13:25:36 -0600168 node_node: Path name of Node object containing information about
169 the entry to create (used for errors)
170 etype: Entry type to use
Simon Glass2f859412021-03-18 20:25:04 +1300171 expanded: Use the expanded version of etype
Simon Glass2574ef62016-11-25 20:15:51 -0700172
173 Returns:
Simon Glass2f859412021-03-18 20:25:04 +1300174 The entry class object if found, else None if not found and expanded
Simon Glassb9028bc2021-11-23 21:09:49 -0700175 is True, else a tuple:
176 module name that could not be found
177 exception received
Simon Glass2574ef62016-11-25 20:15:51 -0700178 """
Simon Glasse76a3e62018-06-01 09:38:11 -0600179 # Convert something like 'u-boot@0' to 'u_boot' since we are only
180 # interested in the type.
Simon Glass2574ef62016-11-25 20:15:51 -0700181 module_name = etype.replace('-', '_')
Simon Glass2f859412021-03-18 20:25:04 +1300182
Simon Glasse76a3e62018-06-01 09:38:11 -0600183 if '@' in module_name:
184 module_name = module_name.split('@')[0]
Simon Glass2f859412021-03-18 20:25:04 +1300185 if expanded:
186 module_name += '_expanded'
Simon Glass2574ef62016-11-25 20:15:51 -0700187 module = modules.get(module_name)
188
Simon Glass691198c2018-06-01 09:38:15 -0600189 # Also allow entry-type modules to be brought in from the etype directory.
190
Simon Glass2574ef62016-11-25 20:15:51 -0700191 # Import the module if we have not already done so.
192 if not module:
193 try:
Simon Glassc585dd42020-04-17 18:09:03 -0600194 module = importlib.import_module('binman.etype.' + module_name)
Simon Glass969616c2018-07-17 13:25:36 -0600195 except ImportError as e:
Simon Glass2f859412021-03-18 20:25:04 +1300196 if expanded:
197 return None
Simon Glassb9028bc2021-11-23 21:09:49 -0700198 return module_name, e
Simon Glass2574ef62016-11-25 20:15:51 -0700199 modules[module_name] = module
200
Simon Glass969616c2018-07-17 13:25:36 -0600201 # Look up the expected class name
202 return getattr(module, 'Entry_%s' % module_name)
203
204 @staticmethod
Simon Glassb9028bc2021-11-23 21:09:49 -0700205 def Lookup(node_path, etype, expanded, missing_etype=False):
206 """Look up the entry class for a node.
207
208 Args:
209 node_node (str): Path name of Node object containing information
210 about the entry to create (used for errors)
211 etype (str): Entry type to use
212 expanded (bool): Use the expanded version of etype
213 missing_etype (bool): True to default to a blob etype if the
214 requested etype is not found
215
216 Returns:
217 The entry class object if found, else None if not found and expanded
218 is True
219
220 Raise:
221 ValueError if expanded is False and the class is not found
222 """
223 # Convert something like 'u-boot@0' to 'u_boot' since we are only
224 # interested in the type.
225 cls = Entry.FindEntryClass(etype, expanded)
226 if cls is None:
227 return None
228 elif isinstance(cls, tuple):
229 if missing_etype:
230 cls = Entry.FindEntryClass('blob', False)
231 if isinstance(cls, tuple): # This should not fail
232 module_name, e = cls
233 raise ValueError(
234 "Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
235 (etype, node_path, module_name, e))
236 return cls
237
238 @staticmethod
239 def Create(section, node, etype=None, expanded=False, missing_etype=False):
Simon Glass969616c2018-07-17 13:25:36 -0600240 """Create a new entry for a node.
241
242 Args:
Simon Glassb9028bc2021-11-23 21:09:49 -0700243 section (entry_Section): Section object containing this node
244 node (Node): Node object containing information about the entry to
245 create
246 etype (str): Entry type to use, or None to work it out (used for
247 tests)
248 expanded (bool): Use the expanded version of etype
249 missing_etype (bool): True to default to a blob etype if the
250 requested etype is not found
Simon Glass969616c2018-07-17 13:25:36 -0600251
252 Returns:
253 A new Entry object of the correct type (a subclass of Entry)
254 """
255 if not etype:
256 etype = fdt_util.GetString(node, 'type', node.name)
Simon Glassb9028bc2021-11-23 21:09:49 -0700257 obj = Entry.Lookup(node.path, etype, expanded, missing_etype)
Simon Glass2f859412021-03-18 20:25:04 +1300258 if obj and expanded:
259 # Check whether to use the expanded entry
260 new_etype = etype + '-expanded'
Simon Glass7098b7f2021-03-21 18:24:30 +1300261 can_expand = not fdt_util.GetBool(node, 'no-expanded')
262 if can_expand and obj.UseExpanded(node, etype, new_etype):
Simon Glass2f859412021-03-18 20:25:04 +1300263 etype = new_etype
264 else:
265 obj = None
266 if not obj:
Simon Glassb9028bc2021-11-23 21:09:49 -0700267 obj = Entry.Lookup(node.path, etype, False, missing_etype)
Simon Glass969616c2018-07-17 13:25:36 -0600268
Simon Glass2574ef62016-11-25 20:15:51 -0700269 # Call its constructor to get the object we want.
Simon Glassad5a7712018-06-01 09:38:14 -0600270 return obj(section, etype, node)
Simon Glass2574ef62016-11-25 20:15:51 -0700271
272 def ReadNode(self):
273 """Read entry information from the node
274
Simon Glass2c360cf2019-07-20 12:23:45 -0600275 This must be called as the first thing after the Entry is created.
276
Simon Glass2574ef62016-11-25 20:15:51 -0700277 This reads all the fields we recognise from the node, ready for use.
278 """
Simon Glass0cf5bce2022-08-13 11:40:44 -0600279 self.ensure_props()
Simon Glass24b97442018-07-17 13:25:51 -0600280 if 'pos' in self._node.props:
281 self.Raise("Please use 'offset' instead of 'pos'")
Simon Glassdd156a42022-03-05 20:18:59 -0700282 if 'expand-size' in self._node.props:
283 self.Raise("Please use 'extend-size' instead of 'expand-size'")
Simon Glasse8561af2018-08-01 15:22:37 -0600284 self.offset = fdt_util.GetInt(self._node, 'offset')
Simon Glass2574ef62016-11-25 20:15:51 -0700285 self.size = fdt_util.GetInt(self._node, 'size')
Samuel Hollande2574022023-01-21 17:25:16 -0600286 self.min_size = fdt_util.GetInt(self._node, 'min-size', 0)
Simon Glassfb30e292019-07-20 12:23:51 -0600287 self.orig_offset = fdt_util.GetInt(self._node, 'orig-offset')
288 self.orig_size = fdt_util.GetInt(self._node, 'orig-size')
289 if self.GetImage().copy_to_orig:
290 self.orig_offset = self.offset
291 self.orig_size = self.size
Simon Glasse61b6f62019-07-08 14:25:37 -0600292
Simon Glassb8424fa2019-07-08 14:25:46 -0600293 # These should not be set in input files, but are set in an FDT map,
294 # which is also read by this code.
295 self.image_pos = fdt_util.GetInt(self._node, 'image-pos')
296 self.uncomp_size = fdt_util.GetInt(self._node, 'uncomp-size')
297
Simon Glass2574ef62016-11-25 20:15:51 -0700298 self.align = fdt_util.GetInt(self._node, 'align')
Simon Glass80025522022-01-29 14:14:04 -0700299 if tools.not_power_of_two(self.align):
Simon Glass2574ef62016-11-25 20:15:51 -0700300 raise ValueError("Node '%s': Alignment %s must be a power of two" %
301 (self._node.path, self.align))
Simon Glassf427c5f2021-03-21 18:24:33 +1300302 if self.section and self.align is None:
303 self.align = self.section.align_default
Simon Glass2574ef62016-11-25 20:15:51 -0700304 self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
305 self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
306 self.align_size = fdt_util.GetInt(self._node, 'align-size')
Simon Glass80025522022-01-29 14:14:04 -0700307 if tools.not_power_of_two(self.align_size):
Simon Glass39dd2152019-07-08 14:25:47 -0600308 self.Raise("Alignment size %s must be a power of two" %
309 self.align_size)
Simon Glass2574ef62016-11-25 20:15:51 -0700310 self.align_end = fdt_util.GetInt(self._node, 'align-end')
Simon Glasse8561af2018-08-01 15:22:37 -0600311 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
Simon Glassdd156a42022-03-05 20:18:59 -0700312 self.extend_size = fdt_util.GetBool(self._node, 'extend-size')
Simon Glassa820af72020-09-06 10:39:09 -0600313 self.missing_msg = fdt_util.GetString(self._node, 'missing-msg')
Simon Glass63328f12023-01-07 14:07:15 -0700314 self.optional = fdt_util.GetBool(self._node, 'optional')
Simon Glassf1ee03b2023-01-11 16:10:16 -0700315 self.overlap = fdt_util.GetBool(self._node, 'overlap')
316 if self.overlap:
317 self.required_props += ['offset', 'size']
Simon Glassa360b8f2024-06-23 11:55:06 -0600318 self.assume_size = fdt_util.GetInt(self._node, 'assume-size', 0)
Simon Glass2574ef62016-11-25 20:15:51 -0700319
Simon Glassa1301a22020-10-26 17:40:06 -0600320 # This is only supported by blobs and sections at present
321 self.compress = fdt_util.GetString(self._node, 'compress', 'none')
Simon Glass49e9c002023-01-11 16:10:19 -0700322 self.offset_from_elf = fdt_util.GetPhandleNameOffset(self._node,
323 'offset-from-elf')
Simon Glassa1301a22020-10-26 17:40:06 -0600324
Simon Glasscda991e2023-02-12 17:11:15 -0700325 self.preserve = fdt_util.GetBool(self._node, 'preserve')
Simon Glass4abf7842023-07-18 07:23:54 -0600326 self.no_write_symbols = fdt_util.GetBool(self._node, 'no-write-symbols')
Simon Glasscda991e2023-02-12 17:11:15 -0700327
Simon Glass3732ec32018-09-14 04:57:18 -0600328 def GetDefaultFilename(self):
329 return None
330
Simon Glass267112e2019-07-20 12:23:28 -0600331 def GetFdts(self):
332 """Get the device trees used by this entry
Simon Glass0c9d5b52018-09-14 04:57:22 -0600333
334 Returns:
Simon Glass267112e2019-07-20 12:23:28 -0600335 Empty dict, if this entry is not a .dtb, otherwise:
336 Dict:
337 key: Filename from this entry (without the path)
Simon Glass684a4f12019-07-20 12:23:31 -0600338 value: Tuple:
Simon Glass8235dd82021-03-18 20:25:02 +1300339 Entry object for this dtb
Simon Glass684a4f12019-07-20 12:23:31 -0600340 Filename of file containing this dtb
Simon Glass0c9d5b52018-09-14 04:57:22 -0600341 """
Simon Glass267112e2019-07-20 12:23:28 -0600342 return {}
Simon Glass0c9d5b52018-09-14 04:57:22 -0600343
Simon Glassf86ddad2022-03-05 20:19:00 -0700344 def gen_entries(self):
345 """Allow entries to generate other entries
Simon Glassfcb2a7c2021-03-18 20:24:52 +1300346
347 Some entries generate subnodes automatically, from which sub-entries
348 are then created. This method allows those to be added to the binman
349 definition for the current image. An entry which implements this method
350 should call state.AddSubnode() to add a subnode and can add properties
351 with state.AddString(), etc.
352
353 An example is 'files', which produces a section containing a list of
354 files.
355 """
Simon Glassac6328c2018-09-14 04:57:28 -0600356 pass
357
Simon Glassacd6c6e2020-10-26 17:40:17 -0600358 def AddMissingProperties(self, have_image_pos):
359 """Add new properties to the device tree as needed for this entry
360
361 Args:
362 have_image_pos: True if this entry has an image position. This can
363 be False if its parent section is compressed, since compression
364 groups all entries together into a compressed block of data,
365 obscuring the start of each individual child entry
366 """
367 for prop in ['offset', 'size']:
Simon Glasse22f8fa2018-07-06 10:27:41 -0600368 if not prop in self._node.props:
Simon Glassc8135dc2018-09-14 04:57:21 -0600369 state.AddZeroProp(self._node, prop)
Simon Glassacd6c6e2020-10-26 17:40:17 -0600370 if have_image_pos and 'image-pos' not in self._node.props:
371 state.AddZeroProp(self._node, 'image-pos')
Simon Glassfb30e292019-07-20 12:23:51 -0600372 if self.GetImage().allow_repack:
373 if self.orig_offset is not None:
374 state.AddZeroProp(self._node, 'orig-offset', True)
375 if self.orig_size is not None:
376 state.AddZeroProp(self._node, 'orig-size', True)
377
Simon Glassaa2fcf92019-07-08 14:25:30 -0600378 if self.compress != 'none':
379 state.AddZeroProp(self._node, 'uncomp-size')
Alper Nebi Yasak1e4ffd82022-02-09 22:02:35 +0300380
381 if self.update_hash:
382 err = state.CheckAddHashProp(self._node)
383 if err:
384 self.Raise(err)
Simon Glasse22f8fa2018-07-06 10:27:41 -0600385
386 def SetCalculatedProperties(self):
387 """Set the value of device-tree properties calculated by binman"""
Simon Glassc8135dc2018-09-14 04:57:21 -0600388 state.SetInt(self._node, 'offset', self.offset)
389 state.SetInt(self._node, 'size', self.size)
Simon Glass39dd2152019-07-08 14:25:47 -0600390 base = self.section.GetRootSkipAtStart() if self.section else 0
Simon Glassacd6c6e2020-10-26 17:40:17 -0600391 if self.image_pos is not None:
Simon Glasseb943b12020-11-02 12:55:44 -0700392 state.SetInt(self._node, 'image-pos', self.image_pos - base)
Simon Glassfb30e292019-07-20 12:23:51 -0600393 if self.GetImage().allow_repack:
394 if self.orig_offset is not None:
395 state.SetInt(self._node, 'orig-offset', self.orig_offset, True)
396 if self.orig_size is not None:
397 state.SetInt(self._node, 'orig-size', self.orig_size, True)
Simon Glassaa2fcf92019-07-08 14:25:30 -0600398 if self.uncomp_size is not None:
399 state.SetInt(self._node, 'uncomp-size', self.uncomp_size)
Alper Nebi Yasak1e4ffd82022-02-09 22:02:35 +0300400
401 if self.update_hash:
402 state.CheckSetHashValue(self._node, self.GetData)
Simon Glasse22f8fa2018-07-06 10:27:41 -0600403
Simon Glass92307732018-07-06 10:27:40 -0600404 def ProcessFdt(self, fdt):
Simon Glasse219aa42018-09-14 04:57:24 -0600405 """Allow entries to adjust the device tree
406
407 Some entries need to adjust the device tree for their purposes. This
408 may involve adding or deleting properties.
409
410 Returns:
411 True if processing is complete
412 False if processing could not be completed due to a dependency.
413 This will cause the entry to be retried after others have been
414 called
415 """
Simon Glass92307732018-07-06 10:27:40 -0600416 return True
417
Simon Glass3b78d532018-06-01 09:38:21 -0600418 def SetPrefix(self, prefix):
419 """Set the name prefix for a node
420
421 Args:
422 prefix: Prefix to set, or '' to not use a prefix
423 """
424 if prefix:
425 self.name = prefix + self.name
426
Simon Glass2e1169f2018-07-06 10:27:19 -0600427 def SetContents(self, data):
428 """Set the contents of an entry
429
430 This sets both the data and content_size properties
431
432 Args:
Simon Glassd17dfea2019-07-08 14:25:33 -0600433 data: Data to set to the contents (bytes)
Simon Glass2e1169f2018-07-06 10:27:19 -0600434 """
435 self.data = data
436 self.contents_size = len(self.data)
437
438 def ProcessContentsUpdate(self, data):
Simon Glassd17dfea2019-07-08 14:25:33 -0600439 """Update the contents of an entry, after the size is fixed
Simon Glass2e1169f2018-07-06 10:27:19 -0600440
Simon Glassec849852019-07-08 14:25:35 -0600441 This checks that the new data is the same size as the old. If the size
442 has changed, this triggers a re-run of the packing algorithm.
Simon Glass2e1169f2018-07-06 10:27:19 -0600443
444 Args:
Simon Glassd17dfea2019-07-08 14:25:33 -0600445 data: Data to set to the contents (bytes)
Simon Glass2e1169f2018-07-06 10:27:19 -0600446
447 Raises:
448 ValueError if the new data size is not the same as the old
449 """
Simon Glassec849852019-07-08 14:25:35 -0600450 size_ok = True
Simon Glasse61b6f62019-07-08 14:25:37 -0600451 new_size = len(data)
Simon Glass9d8ee322019-07-20 12:23:58 -0600452 if state.AllowEntryExpansion() and new_size > self.contents_size:
453 # self.data will indicate the new size needed
454 size_ok = False
455 elif state.AllowEntryContraction() and new_size < self.contents_size:
456 size_ok = False
457
458 # If not allowed to change, try to deal with it or give up
459 if size_ok:
Simon Glasse61b6f62019-07-08 14:25:37 -0600460 if new_size > self.contents_size:
Simon Glass9d8ee322019-07-20 12:23:58 -0600461 self.Raise('Cannot update entry size from %d to %d' %
462 (self.contents_size, new_size))
463
464 # Don't let the data shrink. Pad it if necessary
465 if size_ok and new_size < self.contents_size:
Simon Glass80025522022-01-29 14:14:04 -0700466 data += tools.get_bytes(0, self.contents_size - new_size)
Simon Glass9d8ee322019-07-20 12:23:58 -0600467
468 if not size_ok:
Simon Glass011f1b32022-01-29 14:14:15 -0700469 tout.debug("Entry '%s' size change from %s to %s" % (
Simon Glass80025522022-01-29 14:14:04 -0700470 self._node.path, to_hex(self.contents_size),
471 to_hex(new_size)))
Simon Glass2e1169f2018-07-06 10:27:19 -0600472 self.SetContents(data)
Simon Glassec849852019-07-08 14:25:35 -0600473 return size_ok
Simon Glass2e1169f2018-07-06 10:27:19 -0600474
Simon Glassfc5a1682022-03-05 20:19:05 -0700475 def ObtainContents(self, skip_entry=None, fake_size=0):
Simon Glass2574ef62016-11-25 20:15:51 -0700476 """Figure out the contents of an entry.
477
Simon Glass0b25b432023-07-18 07:23:57 -0600478 For missing blobs (where allow-missing is enabled), the contents are set
479 to b'' and self.missing is set to True.
480
Simon Glassfc5a1682022-03-05 20:19:05 -0700481 Args:
482 skip_entry (Entry): Entry to skip when obtaining section contents
483 fake_size (int): Size of fake file to create if needed
484
Simon Glass2574ef62016-11-25 20:15:51 -0700485 Returns:
486 True if the contents were found, False if another call is needed
Simon Glassa4948b22023-01-11 16:10:14 -0700487 after the other entries are processed, None if there is no contents
Simon Glass2574ef62016-11-25 20:15:51 -0700488 """
489 # No contents by default: subclasses can implement this
490 return True
491
Simon Glasse61b6f62019-07-08 14:25:37 -0600492 def ResetForPack(self):
493 """Reset offset/size fields so that packing can be done again"""
Simon Glassb6dff4c2019-07-20 12:23:36 -0600494 self.Detail('ResetForPack: offset %s->%s, size %s->%s' %
Simon Glass80025522022-01-29 14:14:04 -0700495 (to_hex(self.offset), to_hex(self.orig_offset),
496 to_hex(self.size), to_hex(self.orig_size)))
Simon Glass1fdb4872019-10-31 07:43:02 -0600497 self.pre_reset_size = self.size
Simon Glasse61b6f62019-07-08 14:25:37 -0600498 self.offset = self.orig_offset
499 self.size = self.orig_size
500
Simon Glasse8561af2018-08-01 15:22:37 -0600501 def Pack(self, offset):
Simon Glassad5a7712018-06-01 09:38:14 -0600502 """Figure out how to pack the entry into the section
Simon Glass2574ef62016-11-25 20:15:51 -0700503
504 Most of the time the entries are not fully specified. There may be
505 an alignment but no size. In that case we take the size from the
506 contents of the entry.
507
Simon Glasse8561af2018-08-01 15:22:37 -0600508 If an entry has no hard-coded offset, it will be placed at @offset.
Simon Glass2574ef62016-11-25 20:15:51 -0700509
Simon Glasse8561af2018-08-01 15:22:37 -0600510 Once this function is complete, both the offset and size of the
Simon Glass2574ef62016-11-25 20:15:51 -0700511 entry will be know.
512
513 Args:
Simon Glasse8561af2018-08-01 15:22:37 -0600514 Current section offset pointer
Simon Glass2574ef62016-11-25 20:15:51 -0700515
516 Returns:
Simon Glasse8561af2018-08-01 15:22:37 -0600517 New section offset pointer (after this entry)
Simon Glass2574ef62016-11-25 20:15:51 -0700518 """
Simon Glassb6dff4c2019-07-20 12:23:36 -0600519 self.Detail('Packing: offset=%s, size=%s, content_size=%x' %
Simon Glass80025522022-01-29 14:14:04 -0700520 (to_hex(self.offset), to_hex(self.size),
Simon Glassb6dff4c2019-07-20 12:23:36 -0600521 self.contents_size))
Simon Glasse8561af2018-08-01 15:22:37 -0600522 if self.offset is None:
523 if self.offset_unset:
524 self.Raise('No offset set with offset-unset: should another '
525 'entry provide this correct offset?')
Simon Glass49e9c002023-01-11 16:10:19 -0700526 elif self.offset_from_elf:
527 self.offset = self.lookup_offset()
528 else:
529 self.offset = tools.align(offset, self.align)
Simon Glass2574ef62016-11-25 20:15:51 -0700530 needed = self.pad_before + self.contents_size + self.pad_after
Samuel Hollande2574022023-01-21 17:25:16 -0600531 needed = max(needed, self.min_size)
Simon Glass80025522022-01-29 14:14:04 -0700532 needed = tools.align(needed, self.align_size)
Simon Glass2574ef62016-11-25 20:15:51 -0700533 size = self.size
534 if not size:
535 size = needed
Simon Glasse8561af2018-08-01 15:22:37 -0600536 new_offset = self.offset + size
Simon Glass80025522022-01-29 14:14:04 -0700537 aligned_offset = tools.align(new_offset, self.align_end)
Simon Glasse8561af2018-08-01 15:22:37 -0600538 if aligned_offset != new_offset:
539 size = aligned_offset - self.offset
540 new_offset = aligned_offset
Simon Glass2574ef62016-11-25 20:15:51 -0700541
542 if not self.size:
543 self.size = size
544
545 if self.size < needed:
546 self.Raise("Entry contents size is %#x (%d) but entry size is "
547 "%#x (%d)" % (needed, needed, self.size, self.size))
548 # Check that the alignment is correct. It could be wrong if the
Simon Glasse8561af2018-08-01 15:22:37 -0600549 # and offset or size values were provided (i.e. not calculated), but
Simon Glass2574ef62016-11-25 20:15:51 -0700550 # conflict with the provided alignment values
Simon Glass80025522022-01-29 14:14:04 -0700551 if self.size != tools.align(self.size, self.align_size):
Simon Glass2574ef62016-11-25 20:15:51 -0700552 self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
553 (self.size, self.size, self.align_size, self.align_size))
Simon Glass80025522022-01-29 14:14:04 -0700554 if self.offset != tools.align(self.offset, self.align):
Simon Glasse8561af2018-08-01 15:22:37 -0600555 self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
556 (self.offset, self.offset, self.align, self.align))
Simon Glassb6dff4c2019-07-20 12:23:36 -0600557 self.Detail(' - packed: offset=%#x, size=%#x, content_size=%#x, next_offset=%x' %
558 (self.offset, self.size, self.contents_size, new_offset))
Simon Glass2574ef62016-11-25 20:15:51 -0700559
Simon Glasse8561af2018-08-01 15:22:37 -0600560 return new_offset
Simon Glass2574ef62016-11-25 20:15:51 -0700561
562 def Raise(self, msg):
563 """Convenience function to raise an error referencing a node"""
564 raise ValueError("Node '%s': %s" % (self._node.path, msg))
565
Simon Glasse1915782021-03-21 18:24:31 +1300566 def Info(self, msg):
567 """Convenience function to log info referencing a node"""
568 tag = "Info '%s'" % self._node.path
Simon Glass011f1b32022-01-29 14:14:15 -0700569 tout.detail('%30s: %s' % (tag, msg))
Simon Glasse1915782021-03-21 18:24:31 +1300570
Simon Glassb6dff4c2019-07-20 12:23:36 -0600571 def Detail(self, msg):
572 """Convenience function to log detail referencing a node"""
573 tag = "Node '%s'" % self._node.path
Simon Glass011f1b32022-01-29 14:14:15 -0700574 tout.detail('%30s: %s' % (tag, msg))
Simon Glassb6dff4c2019-07-20 12:23:36 -0600575
Simon Glass91710b32018-07-17 13:25:32 -0600576 def GetEntryArgsOrProps(self, props, required=False):
577 """Return the values of a set of properties
578
579 Args:
580 props: List of EntryArg objects
581
582 Raises:
583 ValueError if a property is not found
584 """
585 values = []
586 missing = []
587 for prop in props:
588 python_prop = prop.name.replace('-', '_')
589 if hasattr(self, python_prop):
590 value = getattr(self, python_prop)
591 else:
592 value = None
593 if value is None:
594 value = self.GetArg(prop.name, prop.datatype)
595 if value is None and required:
596 missing.append(prop.name)
597 values.append(value)
598 if missing:
Simon Glass3fb25402021-01-06 21:35:16 -0700599 self.GetImage().MissingArgs(self, missing)
Simon Glass91710b32018-07-17 13:25:32 -0600600 return values
601
Simon Glass2574ef62016-11-25 20:15:51 -0700602 def GetPath(self):
603 """Get the path of a node
604
605 Returns:
606 Full path of the node for this entry
607 """
608 return self._node.path
609
Simon Glass27a7f772021-03-21 18:24:32 +1300610 def GetData(self, required=True):
Simon Glass72eeff12020-10-26 17:40:16 -0600611 """Get the contents of an entry
612
Simon Glass27a7f772021-03-21 18:24:32 +1300613 Args:
614 required: True if the data must be present, False if it is OK to
615 return None
616
Simon Glass72eeff12020-10-26 17:40:16 -0600617 Returns:
618 bytes content of the entry, excluding any padding. If the entry is
Simon Glass02997652023-01-11 16:10:13 -0700619 compressed, the compressed data is returned. If the entry data
Simon Glassa4948b22023-01-11 16:10:14 -0700620 is not yet available, False can be returned. If the entry data
621 is null, then None is returned.
Simon Glass72eeff12020-10-26 17:40:16 -0600622 """
Simon Glass80025522022-01-29 14:14:04 -0700623 self.Detail('GetData: size %s' % to_hex_size(self.data))
Simon Glass2574ef62016-11-25 20:15:51 -0700624 return self.data
625
Simon Glasse17220f2020-11-02 12:55:43 -0700626 def GetPaddedData(self, data=None):
627 """Get the data for an entry including any padding
628
629 Gets the entry data and uses its section's pad-byte value to add padding
630 before and after as defined by the pad-before and pad-after properties.
631
632 This does not consider alignment.
633
634 Returns:
635 Contents of the entry along with any pad bytes before and
636 after it (bytes)
637 """
638 if data is None:
639 data = self.GetData()
640 return self.section.GetPaddedDataForEntry(self, data)
641
Simon Glasse8561af2018-08-01 15:22:37 -0600642 def GetOffsets(self):
Simon Glass224bc662019-07-08 13:18:30 -0600643 """Get the offsets for siblings
644
645 Some entry types can contain information about the position or size of
646 other entries. An example of this is the Intel Flash Descriptor, which
647 knows where the Intel Management Engine section should go.
648
649 If this entry knows about the position of other entries, it can specify
650 this by returning values here
651
652 Returns:
653 Dict:
654 key: Entry type
655 value: List containing position and size of the given entry
Simon Glassed365eb2019-07-08 13:18:39 -0600656 type. Either can be None if not known
Simon Glass224bc662019-07-08 13:18:30 -0600657 """
Simon Glass2574ef62016-11-25 20:15:51 -0700658 return {}
659
Simon Glassed365eb2019-07-08 13:18:39 -0600660 def SetOffsetSize(self, offset, size):
661 """Set the offset and/or size of an entry
662
663 Args:
664 offset: New offset, or None to leave alone
665 size: New size, or None to leave alone
666 """
667 if offset is not None:
668 self.offset = offset
669 if size is not None:
670 self.size = size
Simon Glass2574ef62016-11-25 20:15:51 -0700671
Simon Glass9dcc8612018-08-01 15:22:42 -0600672 def SetImagePos(self, image_pos):
673 """Set the position in the image
674
675 Args:
676 image_pos: Position of this entry in the image
677 """
678 self.image_pos = image_pos + self.offset
679
Simon Glass2574ef62016-11-25 20:15:51 -0700680 def ProcessContents(self):
Simon Glassec849852019-07-08 14:25:35 -0600681 """Do any post-packing updates of entry contents
682
683 This function should call ProcessContentsUpdate() to update the entry
684 contents, if necessary, returning its return value here.
685
686 Args:
687 data: Data to set to the contents (bytes)
688
689 Returns:
690 True if the new data size is OK, False if expansion is needed
691
692 Raises:
693 ValueError if the new data size is not the same as the old and
694 state.AllowEntryExpansion() is False
695 """
696 return True
Simon Glass4ca8e042017-11-13 18:55:01 -0700697
Simon Glass8a6f56e2018-06-01 09:38:13 -0600698 def WriteSymbols(self, section):
Simon Glass4ca8e042017-11-13 18:55:01 -0700699 """Write symbol values into binary files for access at run time
700
701 Args:
Simon Glass8a6f56e2018-06-01 09:38:13 -0600702 section: Section containing the entry
Simon Glass4ca8e042017-11-13 18:55:01 -0700703 """
Simon Glass4abf7842023-07-18 07:23:54 -0600704 if self.auto_write_symbols and not self.no_write_symbols:
Simon Glass37f85de2022-10-20 18:22:47 -0600705 # Check if we are writing symbols into an ELF file
706 is_elf = self.GetDefaultFilename() == self.elf_fname
707 elf.LookupAndWriteSymbols(self.elf_fname, self, section.GetImage(),
Simon Glasse0035c92023-01-11 16:10:17 -0700708 is_elf, self.elf_base_sym)
Simon Glassa91e1152018-06-01 09:38:16 -0600709
Simon Glass55f68072020-10-26 17:40:18 -0600710 def CheckEntries(self):
Simon Glasse8561af2018-08-01 15:22:37 -0600711 """Check that the entry offsets are correct
Simon Glassa91e1152018-06-01 09:38:16 -0600712
Simon Glasse8561af2018-08-01 15:22:37 -0600713 This is used for entries which have extra offset requirements (other
Simon Glassa91e1152018-06-01 09:38:16 -0600714 than having to be fully inside their section). Sub-classes can implement
715 this function and raise if there is a problem.
716 """
717 pass
Simon Glass30732662018-06-01 09:38:20 -0600718
Simon Glass3a9a2b82018-07-17 13:25:28 -0600719 @staticmethod
Simon Glasscd817d52018-09-14 04:57:36 -0600720 def GetStr(value):
721 if value is None:
722 return '<none> '
723 return '%08x' % value
724
725 @staticmethod
Simon Glass7eca7922018-07-17 13:25:49 -0600726 def WriteMapLine(fd, indent, name, offset, size, image_pos):
Simon Glasscd817d52018-09-14 04:57:36 -0600727 print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
728 Entry.GetStr(offset), Entry.GetStr(size),
729 name), file=fd)
Simon Glass3a9a2b82018-07-17 13:25:28 -0600730
Simon Glass30732662018-06-01 09:38:20 -0600731 def WriteMap(self, fd, indent):
732 """Write a map of the entry to a .map file
733
734 Args:
735 fd: File to write the map to
736 indent: Curent indent level of map (0=none, 1=one level, etc.)
737 """
Simon Glass7eca7922018-07-17 13:25:49 -0600738 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
739 self.image_pos)
Simon Glass91710b32018-07-17 13:25:32 -0600740
Simon Glassbd5cd882022-08-13 11:40:50 -0600741 # pylint: disable=assignment-from-none
Simon Glass704784b2018-07-17 13:25:38 -0600742 def GetEntries(self):
743 """Return a list of entries contained by this entry
744
745 Returns:
746 List of entries, or None if none. A normal entry has no entries
747 within it so will return None
748 """
749 return None
750
Simon Glassbd5cd882022-08-13 11:40:50 -0600751 def FindEntryByNode(self, find_node):
752 """Find a node in an entry, searching all subentries
753
754 This does a recursive search.
755
756 Args:
757 find_node (fdt.Node): Node to find
758
759 Returns:
760 Entry: entry, if found, else None
761 """
762 entries = self.GetEntries()
763 if entries:
764 for entry in entries.values():
765 if entry._node == find_node:
766 return entry
767 found = entry.FindEntryByNode(find_node)
768 if found:
769 return found
770
771 return None
772
Simon Glass91710b32018-07-17 13:25:32 -0600773 def GetArg(self, name, datatype=str):
774 """Get the value of an entry argument or device-tree-node property
775
776 Some node properties can be provided as arguments to binman. First check
777 the entry arguments, and fall back to the device tree if not found
778
779 Args:
780 name: Argument name
781 datatype: Data type (str or int)
782
783 Returns:
784 Value of argument as a string or int, or None if no value
785
786 Raises:
787 ValueError if the argument cannot be converted to in
788 """
Simon Glass29aa7362018-09-14 04:57:19 -0600789 value = state.GetEntryArg(name)
Simon Glass91710b32018-07-17 13:25:32 -0600790 if value is not None:
791 if datatype == int:
792 try:
793 value = int(value)
794 except ValueError:
795 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
796 (name, value))
797 elif datatype == str:
798 pass
799 else:
800 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
801 datatype)
802 else:
803 value = fdt_util.GetDatatype(self._node, name, datatype)
804 return value
Simon Glass969616c2018-07-17 13:25:36 -0600805
806 @staticmethod
807 def WriteDocs(modules, test_missing=None):
808 """Write out documentation about the various entry types to stdout
809
810 Args:
811 modules: List of modules to include
812 test_missing: Used for testing. This is a module to report
813 as missing
814 """
815 print('''Binman Entry Documentation
Simon Glassc4f8c282024-06-23 11:55:05 -0600816==========================
Simon Glass969616c2018-07-17 13:25:36 -0600817
818This file describes the entry types supported by binman. These entry types can
819be placed in an image one by one to build up a final firmware image. It is
820fairly easy to create new entry types. Just add a new file to the 'etype'
821directory. You can use the existing entries as examples.
822
823Note that some entries are subclasses of others, using and extending their
824features to produce new behaviours.
825
826
827''')
828 modules = sorted(modules)
829
830 # Don't show the test entry
831 if '_testing' in modules:
832 modules.remove('_testing')
833 missing = []
834 for name in modules:
Simon Glass2f859412021-03-18 20:25:04 +1300835 module = Entry.Lookup('WriteDocs', name, False)
Simon Glass969616c2018-07-17 13:25:36 -0600836 docs = getattr(module, '__doc__')
837 if test_missing == name:
838 docs = None
839 if docs:
840 lines = docs.splitlines()
841 first_line = lines[0]
842 rest = [line[4:] for line in lines[1:]]
843 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
Simon Glassa7c97782022-08-07 16:33:25 -0600844
845 # Create a reference for use by rST docs
846 ref_name = f'etype_{module.__name__[6:]}'.lower()
847 print('.. _%s:' % ref_name)
848 print()
Simon Glass969616c2018-07-17 13:25:36 -0600849 print(hdr)
850 print('-' * len(hdr))
851 print('\n'.join(rest))
852 print()
853 print()
854 else:
855 missing.append(name)
856
857 if missing:
858 raise ValueError('Documentation is missing for modules: %s' %
859 ', '.join(missing))
Simon Glass639505b2018-09-14 04:57:11 -0600860
861 def GetUniqueName(self):
862 """Get a unique name for a node
863
864 Returns:
865 String containing a unique name for a node, consisting of the name
866 of all ancestors (starting from within the 'binman' node) separated
867 by a dot ('.'). This can be useful for generating unique filesnames
868 in the output directory.
869 """
870 name = self.name
871 node = self._node
872 while node.parent:
873 node = node.parent
Alper Nebi Yasak5cff63f2022-03-27 18:31:44 +0300874 if node.name in ('binman', '/'):
Simon Glass639505b2018-09-14 04:57:11 -0600875 break
876 name = '%s.%s' % (node.name, name)
877 return name
Simon Glassfa79a812018-09-14 04:57:29 -0600878
Simon Glassdd156a42022-03-05 20:18:59 -0700879 def extend_to_limit(self, limit):
880 """Extend an entry so that it ends at the given offset limit"""
Simon Glassfa79a812018-09-14 04:57:29 -0600881 if self.offset + self.size < limit:
882 self.size = limit - self.offset
883 # Request the contents again, since changing the size requires that
884 # the data grows. This should not fail, but check it to be sure.
885 if not self.ObtainContents():
886 self.Raise('Cannot obtain contents when expanding entry')
Simon Glassc4056b82019-07-08 13:18:38 -0600887
888 def HasSibling(self, name):
889 """Check if there is a sibling of a given name
890
891 Returns:
892 True if there is an entry with this name in the the same section,
893 else False
894 """
895 return name in self.section.GetEntries()
Simon Glasscec34ba2019-07-08 14:25:28 -0600896
897 def GetSiblingImagePos(self, name):
898 """Return the image position of the given sibling
899
900 Returns:
901 Image position of sibling, or None if the sibling has no position,
902 or False if there is no such sibling
903 """
904 if not self.HasSibling(name):
905 return False
906 return self.section.GetEntries()[name].image_pos
Simon Glass6b156f82019-07-08 14:25:43 -0600907
908 @staticmethod
909 def AddEntryInfo(entries, indent, name, etype, size, image_pos,
910 uncomp_size, offset, entry):
911 """Add a new entry to the entries list
912
913 Args:
914 entries: List (of EntryInfo objects) to add to
915 indent: Current indent level to add to list
916 name: Entry name (string)
917 etype: Entry type (string)
918 size: Entry size in bytes (int)
919 image_pos: Position within image in bytes (int)
920 uncomp_size: Uncompressed size if the entry uses compression, else
921 None
922 offset: Entry offset within parent in bytes (int)
923 entry: Entry object
924 """
925 entries.append(EntryInfo(indent, name, etype, size, image_pos,
926 uncomp_size, offset, entry))
927
928 def ListEntries(self, entries, indent):
929 """Add files in this entry to the list of entries
930
931 This can be overridden by subclasses which need different behaviour.
932
933 Args:
934 entries: List (of EntryInfo objects) to add to
935 indent: Current indent level to add to list
936 """
937 self.AddEntryInfo(entries, indent, self.name, self.etype, self.size,
938 self.image_pos, self.uncomp_size, self.offset, self)
Simon Glass4c613bf2019-07-08 14:25:50 -0600939
Simon Glass637958f2021-11-23 21:09:50 -0700940 def ReadData(self, decomp=True, alt_format=None):
Simon Glass4c613bf2019-07-08 14:25:50 -0600941 """Read the data for an entry from the image
942
943 This is used when the image has been read in and we want to extract the
944 data for a particular entry from that image.
945
946 Args:
947 decomp: True to decompress any compressed data before returning it;
948 False to return the raw, uncompressed data
949
950 Returns:
951 Entry data (bytes)
952 """
953 # Use True here so that we get an uncompressed section to work from,
954 # although compressed sections are currently not supported
Simon Glass011f1b32022-01-29 14:14:15 -0700955 tout.debug("ReadChildData section '%s', entry '%s'" %
Simon Glass4d8151f2019-09-25 08:56:21 -0600956 (self.section.GetPath(), self.GetPath()))
Simon Glass637958f2021-11-23 21:09:50 -0700957 data = self.section.ReadChildData(self, decomp, alt_format)
Simon Glass0cd8ace2019-07-20 12:24:04 -0600958 return data
Simon Glassaf8c45c2019-07-20 12:23:41 -0600959
Simon Glass637958f2021-11-23 21:09:50 -0700960 def ReadChildData(self, child, decomp=True, alt_format=None):
Simon Glass4d8151f2019-09-25 08:56:21 -0600961 """Read the data for a particular child entry
Simon Glass23f00472019-09-25 08:56:20 -0600962
963 This reads data from the parent and extracts the piece that relates to
964 the given child.
965
966 Args:
Simon Glass637958f2021-11-23 21:09:50 -0700967 child (Entry): Child entry to read data for (must be valid)
968 decomp (bool): True to decompress any compressed data before
969 returning it; False to return the raw, uncompressed data
970 alt_format (str): Alternative format to read in, or None
Simon Glass23f00472019-09-25 08:56:20 -0600971
972 Returns:
973 Data for the child (bytes)
974 """
975 pass
976
Simon Glassaf8c45c2019-07-20 12:23:41 -0600977 def LoadData(self, decomp=True):
978 data = self.ReadData(decomp)
Simon Glass072959a2019-07-20 12:23:50 -0600979 self.contents_size = len(data)
Simon Glassaf8c45c2019-07-20 12:23:41 -0600980 self.ProcessContentsUpdate(data)
981 self.Detail('Loaded data size %x' % len(data))
Simon Glass990b1742019-07-20 12:23:46 -0600982
Simon Glass637958f2021-11-23 21:09:50 -0700983 def GetAltFormat(self, data, alt_format):
984 """Read the data for an extry in an alternative format
985
986 Supported formats are list in the documentation for each entry. An
987 example is fdtmap which provides .
988
989 Args:
990 data (bytes): Data to convert (this should have been produced by the
991 entry)
992 alt_format (str): Format to use
993
994 """
995 pass
996
Simon Glass990b1742019-07-20 12:23:46 -0600997 def GetImage(self):
998 """Get the image containing this entry
999
1000 Returns:
1001 Image object containing this entry
1002 """
1003 return self.section.GetImage()
Simon Glass072959a2019-07-20 12:23:50 -06001004
1005 def WriteData(self, data, decomp=True):
1006 """Write the data to an entry in the image
1007
1008 This is used when the image has been read in and we want to replace the
1009 data for a particular entry in that image.
1010
1011 The image must be re-packed and written out afterwards.
1012
1013 Args:
1014 data: Data to replace it with
1015 decomp: True to compress the data if needed, False if data is
1016 already compressed so should be used as is
1017
1018 Returns:
1019 True if the data did not result in a resize of this entry, False if
1020 the entry must be resized
1021 """
Simon Glass1fdb4872019-10-31 07:43:02 -06001022 if self.size is not None:
1023 self.contents_size = self.size
1024 else:
1025 self.contents_size = self.pre_reset_size
Simon Glass072959a2019-07-20 12:23:50 -06001026 ok = self.ProcessContentsUpdate(data)
Simon Glass49b77e82023-03-02 17:02:44 -07001027 self.build_done = False
Simon Glass072959a2019-07-20 12:23:50 -06001028 self.Detail('WriteData: size=%x, ok=%s' % (len(data), ok))
Simon Glassd34af7a2019-07-20 12:24:05 -06001029 section_ok = self.section.WriteChildData(self)
1030 return ok and section_ok
1031
1032 def WriteChildData(self, child):
1033 """Handle writing the data in a child entry
1034
1035 This should be called on the child's parent section after the child's
Simon Glasse796f242021-11-23 11:03:44 -07001036 data has been updated. It should update any data structures needed to
1037 validate that the update is successful.
Simon Glassd34af7a2019-07-20 12:24:05 -06001038
1039 This base-class implementation does nothing, since the base Entry object
1040 does not have any children.
1041
1042 Args:
1043 child: Child Entry that was written
1044
1045 Returns:
1046 True if the section could be updated successfully, False if the
Simon Glasse796f242021-11-23 11:03:44 -07001047 data is such that the section could not update
Simon Glassd34af7a2019-07-20 12:24:05 -06001048 """
Simon Glass49b77e82023-03-02 17:02:44 -07001049 self.build_done = False
1050 entry = self.section
1051
1052 # Now we must rebuild all sections above this one
1053 while entry and entry != entry.section:
1054 self.build_done = False
1055 entry = entry.section
1056
Simon Glassd34af7a2019-07-20 12:24:05 -06001057 return True
Simon Glass11453762019-07-20 12:23:55 -06001058
1059 def GetSiblingOrder(self):
1060 """Get the relative order of an entry amoung its siblings
1061
1062 Returns:
1063 'start' if this entry is first among siblings, 'end' if last,
1064 otherwise None
1065 """
1066 entries = list(self.section.GetEntries().values())
1067 if entries:
1068 if self == entries[0]:
1069 return 'start'
1070 elif self == entries[-1]:
1071 return 'end'
1072 return 'middle'
Simon Glass5d94cc62020-07-09 18:39:38 -06001073
1074 def SetAllowMissing(self, allow_missing):
1075 """Set whether a section allows missing external blobs
1076
1077 Args:
1078 allow_missing: True if allowed, False if not allowed
1079 """
1080 # This is meaningless for anything other than sections
1081 pass
Simon Glassa003cd32020-07-09 18:39:40 -06001082
Heiko Thiery6d451362022-01-06 11:49:41 +01001083 def SetAllowFakeBlob(self, allow_fake):
1084 """Set whether a section allows to create a fake blob
1085
1086 Args:
1087 allow_fake: True if allowed, False if not allowed
1088 """
Simon Glassceb5f912022-01-09 20:13:46 -07001089 self.allow_fake = allow_fake
Heiko Thiery6d451362022-01-06 11:49:41 +01001090
Simon Glassa003cd32020-07-09 18:39:40 -06001091 def CheckMissing(self, missing_list):
Simon Glass63328f12023-01-07 14:07:15 -07001092 """Check if the entry has missing external blobs
Simon Glassa003cd32020-07-09 18:39:40 -06001093
Simon Glass63328f12023-01-07 14:07:15 -07001094 If there are missing (non-optional) blobs, the entries are added to the
1095 list
Simon Glassa003cd32020-07-09 18:39:40 -06001096
1097 Args:
1098 missing_list: List of Entry objects to be added to
1099 """
Simon Glass63328f12023-01-07 14:07:15 -07001100 if self.missing and not self.optional:
Simon Glassa003cd32020-07-09 18:39:40 -06001101 missing_list.append(self)
Simon Glassb8f90372020-09-01 05:13:57 -06001102
Simon Glass8c0533b2022-03-05 20:19:04 -07001103 def check_fake_fname(self, fname, size=0):
Simon Glass7a602fd2022-01-12 13:10:36 -07001104 """If the file is missing and the entry allows fake blobs, fake it
1105
1106 Sets self.faked to True if faked
1107
1108 Args:
1109 fname (str): Filename to check
Simon Glass8c0533b2022-03-05 20:19:04 -07001110 size (int): Size of fake file to create
Simon Glass7a602fd2022-01-12 13:10:36 -07001111
1112 Returns:
Simon Glass214d36f2022-03-05 20:19:03 -07001113 tuple:
1114 fname (str): Filename of faked file
1115 bool: True if the blob was faked, False if not
Simon Glass7a602fd2022-01-12 13:10:36 -07001116 """
1117 if self.allow_fake and not pathlib.Path(fname).is_file():
Simon Glass7d3e4072022-08-07 09:46:46 -06001118 if not self.fake_fname:
1119 outfname = os.path.join(self.fake_dir, os.path.basename(fname))
1120 with open(outfname, "wb") as out:
1121 out.truncate(size)
1122 tout.info(f"Entry '{self._node.path}': Faked blob '{outfname}'")
1123 self.fake_fname = outfname
Simon Glass7a602fd2022-01-12 13:10:36 -07001124 self.faked = True
Simon Glass7d3e4072022-08-07 09:46:46 -06001125 return self.fake_fname, True
Simon Glass214d36f2022-03-05 20:19:03 -07001126 return fname, False
Simon Glass7a602fd2022-01-12 13:10:36 -07001127
Heiko Thiery6d451362022-01-06 11:49:41 +01001128 def CheckFakedBlobs(self, faked_blobs_list):
1129 """Check if any entries in this section have faked external blobs
1130
1131 If there are faked blobs, the entries are added to the list
1132
1133 Args:
Jonas Karlmanf2c52eb2023-02-19 22:02:04 +00001134 faked_blobs_list: List of Entry objects to be added to
Heiko Thiery6d451362022-01-06 11:49:41 +01001135 """
1136 # This is meaningless for anything other than blobs
1137 pass
1138
Simon Glass63328f12023-01-07 14:07:15 -07001139 def CheckOptional(self, optional_list):
1140 """Check if the entry has missing but optional external blobs
1141
1142 If there are missing (optional) blobs, the entries are added to the list
1143
1144 Args:
1145 optional_list (list): List of Entry objects to be added to
1146 """
1147 if self.missing and self.optional:
1148 optional_list.append(self)
1149
Simon Glassb8f90372020-09-01 05:13:57 -06001150 def GetAllowMissing(self):
1151 """Get whether a section allows missing external blobs
1152
1153 Returns:
1154 True if allowed, False if not allowed
1155 """
1156 return self.allow_missing
Simon Glassa820af72020-09-06 10:39:09 -06001157
Simon Glass66152ce2022-01-09 20:14:09 -07001158 def record_missing_bintool(self, bintool):
1159 """Record a missing bintool that was needed to produce this entry
1160
1161 Args:
1162 bintool (Bintool): Bintool that was missing
1163 """
Stefan Herbrechtsmeier486b9442022-08-19 16:25:19 +02001164 if bintool not in self.missing_bintools:
1165 self.missing_bintools.append(bintool)
Simon Glass66152ce2022-01-09 20:14:09 -07001166
1167 def check_missing_bintools(self, missing_list):
1168 """Check if any entries in this section have missing bintools
1169
1170 If there are missing bintools, these are added to the list
1171
1172 Args:
1173 missing_list: List of Bintool objects to be added to
1174 """
Stefan Herbrechtsmeier486b9442022-08-19 16:25:19 +02001175 for bintool in self.missing_bintools:
1176 if bintool not in missing_list:
1177 missing_list.append(bintool)
1178
Simon Glass66152ce2022-01-09 20:14:09 -07001179
Simon Glassa820af72020-09-06 10:39:09 -06001180 def GetHelpTags(self):
1181 """Get the tags use for missing-blob help
1182
1183 Returns:
1184 list of possible tags, most desirable first
1185 """
1186 return list(filter(None, [self.missing_msg, self.name, self.etype]))
Simon Glassa1301a22020-10-26 17:40:06 -06001187
1188 def CompressData(self, indata):
1189 """Compress data according to the entry's compression method
1190
1191 Args:
1192 indata: Data to compress
1193
1194 Returns:
Stefan Herbrechtsmeierb2f8d612022-08-19 16:25:27 +02001195 Compressed data
Simon Glassa1301a22020-10-26 17:40:06 -06001196 """
Simon Glass789b34402020-10-26 17:40:15 -06001197 self.uncomp_data = indata
Simon Glassa1301a22020-10-26 17:40:06 -06001198 if self.compress != 'none':
1199 self.uncomp_size = len(indata)
Stefan Herbrechtsmeier94813a02022-08-19 16:25:31 +02001200 if self.comp_bintool.is_present():
1201 data = self.comp_bintool.compress(indata)
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
Simon Glassa1301a22020-10-26 17:40:06 -06001207 return data
Simon Glass2f859412021-03-18 20:25:04 +13001208
Stefan Herbrechtsmeier7f128a72022-08-19 16:25:24 +02001209 def DecompressData(self, indata):
1210 """Decompress data according to the entry's compression method
1211
1212 Args:
1213 indata: Data to decompress
1214
1215 Returns:
1216 Decompressed data
1217 """
Stefan Herbrechtsmeier7f128a72022-08-19 16:25:24 +02001218 if self.compress != 'none':
Stefan Herbrechtsmeier94813a02022-08-19 16:25:31 +02001219 if self.comp_bintool.is_present():
1220 data = self.comp_bintool.decompress(indata)
1221 self.uncomp_size = len(data)
1222 else:
1223 self.record_missing_bintool(self.comp_bintool)
1224 data = tools.get_bytes(0, 1024)
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001225 else:
1226 data = indata
Stefan Herbrechtsmeier7f128a72022-08-19 16:25:24 +02001227 self.uncomp_data = data
1228 return data
1229
Simon Glass2f859412021-03-18 20:25:04 +13001230 @classmethod
1231 def UseExpanded(cls, node, etype, new_etype):
1232 """Check whether to use an expanded entry type
1233
1234 This is called by Entry.Create() when it finds an expanded version of
1235 an entry type (e.g. 'u-boot-expanded'). If this method returns True then
1236 it will be used (e.g. in place of 'u-boot'). If it returns False, it is
1237 ignored.
1238
1239 Args:
1240 node: Node object containing information about the entry to
1241 create
1242 etype: Original entry type being used
1243 new_etype: New entry type proposed
1244
1245 Returns:
1246 True to use this entry type, False to use the original one
1247 """
Simon Glass011f1b32022-01-29 14:14:15 -07001248 tout.info("Node '%s': etype '%s': %s selected" %
Simon Glass2f859412021-03-18 20:25:04 +13001249 (node.path, etype, new_etype))
1250 return True
Simon Glass637958f2021-11-23 21:09:50 -07001251
1252 def CheckAltFormats(self, alt_formats):
1253 """Add any alternative formats supported by this entry type
1254
1255 Args:
1256 alt_formats (dict): Dict to add alt_formats to:
1257 key: Name of alt format
1258 value: Help text
1259 """
1260 pass
Simon Glass4eae9252022-01-09 20:13:50 -07001261
Simon Glassfff147a2022-03-05 20:19:02 -07001262 def AddBintools(self, btools):
Simon Glass4eae9252022-01-09 20:13:50 -07001263 """Add the bintools used by this entry type
1264
1265 Args:
Simon Glassfff147a2022-03-05 20:19:02 -07001266 btools (dict of Bintool):
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001267
1268 Raise:
1269 ValueError if compression algorithm is not supported
Simon Glass4eae9252022-01-09 20:13:50 -07001270 """
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001271 algo = self.compress
1272 if algo != 'none':
Stefan Herbrechtsmeiera5e4dcb2022-08-19 16:25:38 +02001273 algos = ['bzip2', 'gzip', 'lz4', 'lzma', 'lzo', 'xz', 'zstd']
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001274 if algo not in algos:
1275 raise ValueError("Unknown algorithm '%s'" % algo)
Stefan Herbrechtsmeier9087fc52022-08-19 16:25:36 +02001276 names = {'lzma': 'lzma_alone', 'lzo': 'lzop'}
Stefan Herbrechtsmeiera6e0b502022-08-19 16:25:30 +02001277 name = names.get(self.compress, self.compress)
1278 self.comp_bintool = self.AddBintool(btools, name)
Simon Glass4eae9252022-01-09 20:13:50 -07001279
1280 @classmethod
1281 def AddBintool(self, tools, name):
1282 """Add a new bintool to the tools used by this etype
1283
1284 Args:
1285 name: Name of the tool
1286 """
1287 btool = bintool.Bintool.create(name)
1288 tools[name] = btool
1289 return btool
Alper Nebi Yasak1e4ffd82022-02-09 22:02:35 +03001290
1291 def SetUpdateHash(self, update_hash):
1292 """Set whether this entry's "hash" subnode should be updated
1293
1294 Args:
1295 update_hash: True if hash should be updated, False if not
1296 """
1297 self.update_hash = update_hash
Simon Glass6fba35c2022-02-08 11:50:00 -07001298
Simon Glassfc5a1682022-03-05 20:19:05 -07001299 def collect_contents_to_file(self, entries, prefix, fake_size=0):
Simon Glass6fba35c2022-02-08 11:50:00 -07001300 """Put the contents of a list of entries into a file
1301
1302 Args:
1303 entries (list of Entry): Entries to collect
1304 prefix (str): Filename prefix of file to write to
Simon Glassfc5a1682022-03-05 20:19:05 -07001305 fake_size (int): Size of fake file to create if needed
Simon Glass6fba35c2022-02-08 11:50:00 -07001306
1307 If any entry does not have contents yet, this function returns False
1308 for the data.
1309
1310 Returns:
1311 Tuple:
Simon Glass43a98cc2022-03-05 20:18:58 -07001312 bytes: Concatenated data from all the entries (or None)
1313 str: Filename of file written (or None if no data)
1314 str: Unique portion of filename (or None if no data)
Simon Glass6fba35c2022-02-08 11:50:00 -07001315 """
1316 data = b''
1317 for entry in entries:
Simon Glass6fba35c2022-02-08 11:50:00 -07001318 data += entry.GetData()
1319 uniq = self.GetUniqueName()
1320 fname = tools.get_output_filename(f'{prefix}.{uniq}')
1321 tools.write_file(fname, data)
1322 return data, fname, uniq
Simon Glass7d3e4072022-08-07 09:46:46 -06001323
1324 @classmethod
1325 def create_fake_dir(cls):
1326 """Create the directory for fake files"""
1327 cls.fake_dir = tools.get_output_filename('binman-fake')
1328 if not os.path.exists(cls.fake_dir):
1329 os.mkdir(cls.fake_dir)
1330 tout.notice(f"Fake-blob dir is '{cls.fake_dir}'")
Simon Glass0cf5bce2022-08-13 11:40:44 -06001331
1332 def ensure_props(self):
1333 """Raise an exception if properties are missing
1334
1335 Args:
1336 prop_list (list of str): List of properties to check for
1337
1338 Raises:
1339 ValueError: Any property is missing
1340 """
1341 not_present = []
1342 for prop in self.required_props:
1343 if not prop in self._node.props:
1344 not_present.append(prop)
1345 if not_present:
1346 self.Raise(f"'{self.etype}' entry is missing properties: {' '.join(not_present)}")
Simon Glass1e9e61c2023-01-07 14:07:12 -07001347
1348 def mark_absent(self, msg):
1349 tout.info("Entry '%s' marked absent: %s" % (self._node.path, msg))
1350 self.absent = True
Simon Glassad5cfe12023-01-07 14:07:14 -07001351
1352 def read_elf_segments(self):
1353 """Read segments from an entry that can generate an ELF file
1354
1355 Returns:
1356 tuple:
1357 list of segments, each:
1358 int: Segment number (0 = first)
1359 int: Start address of segment in memory
1360 bytes: Contents of segment
1361 int: entry address of ELF file
1362 """
1363 return None
Simon Glass49e9c002023-01-11 16:10:19 -07001364
1365 def lookup_offset(self):
1366 node, sym_name, offset = self.offset_from_elf
1367 entry = self.section.FindEntryByNode(node)
1368 if not entry:
1369 self.Raise("Cannot find entry for node '%s'" % node.name)
1370 if not entry.elf_fname:
1371 entry.Raise("Need elf-fname property '%s'" % node.name)
1372 val = elf.GetSymbolOffset(entry.elf_fname, sym_name,
1373 entry.elf_base_sym)
1374 return val + offset
Simon Glass49b77e82023-03-02 17:02:44 -07001375
1376 def mark_build_done(self):
1377 """Mark an entry as already built"""
1378 self.build_done = True
1379 entries = self.GetEntries()
1380 if entries:
1381 for entry in entries.values():
1382 entry.mark_build_done()
Ivan Mikhaylov3cfcaa4d2023-03-08 01:13:40 +00001383
1384 def UpdateSignatures(self, privatekey_fname, algo, input_fname):
1385 self.Raise('Updating signatures is not supported with this entry type')