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