blob: 3434a3f8048cfdce271da9022ee47dbffc2eca27 [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
10import sys
Simon Glass29aa7362018-09-14 04:57:19 -060011
Simon Glassc585dd42020-04-17 18:09:03 -060012from dtoc import fdt_util
Simon Glassa997ea52020-04-17 18:09:04 -060013from patman import tools
Simon Glassc585dd42020-04-17 18:09:03 -060014from patman.tools import ToHex, ToHexSize
Simon Glassa997ea52020-04-17 18:09:04 -060015from patman import tout
Simon Glass2574ef62016-11-25 20:15:51 -070016
17modules = {}
18
Simon Glass691198c2018-06-01 09:38:15 -060019our_path = os.path.dirname(os.path.realpath(__file__))
20
Simon Glass91710b32018-07-17 13:25:32 -060021
22# An argument which can be passed to entries on the command line, in lieu of
23# device-tree properties.
24EntryArg = namedtuple('EntryArg', ['name', 'datatype'])
25
Simon Glass6b156f82019-07-08 14:25:43 -060026# Information about an entry for use when displaying summaries
27EntryInfo = namedtuple('EntryInfo', ['indent', 'name', 'etype', 'size',
28 'image_pos', 'uncomp_size', 'offset',
29 'entry'])
Simon Glass91710b32018-07-17 13:25:32 -060030
Simon Glass2574ef62016-11-25 20:15:51 -070031class Entry(object):
Simon Glassad5a7712018-06-01 09:38:14 -060032 """An Entry in the section
Simon Glass2574ef62016-11-25 20:15:51 -070033
34 An entry corresponds to a single node in the device-tree description
Simon Glassad5a7712018-06-01 09:38:14 -060035 of the section. Each entry ends up being a part of the final section.
Simon Glass2574ef62016-11-25 20:15:51 -070036 Entries can be placed either right next to each other, or with padding
37 between them. The type of the entry determines the data that is in it.
38
39 This class is not used by itself. All entry objects are subclasses of
40 Entry.
41
42 Attributes:
Simon Glass3a9a2b82018-07-17 13:25:28 -060043 section: Section object containing this entry
Simon Glass2574ef62016-11-25 20:15:51 -070044 node: The node that created this entry
Simon Glasse8561af2018-08-01 15:22:37 -060045 offset: Offset of entry within the section, None if not known yet (in
46 which case it will be calculated by Pack())
Simon Glass2574ef62016-11-25 20:15:51 -070047 size: Entry size in bytes, None if not known
Simon Glass1fdb4872019-10-31 07:43:02 -060048 pre_reset_size: size as it was before ResetForPack(). This allows us to
49 keep track of the size we started with and detect size changes
Simon Glassaa2fcf92019-07-08 14:25:30 -060050 uncomp_size: Size of uncompressed data in bytes, if the entry is
51 compressed, else None
Simon Glass2574ef62016-11-25 20:15:51 -070052 contents_size: Size of contents in bytes, 0 by default
Simon Glasse8561af2018-08-01 15:22:37 -060053 align: Entry start offset alignment, or None
Simon Glass2574ef62016-11-25 20:15:51 -070054 align_size: Entry size alignment, or None
Simon Glasse8561af2018-08-01 15:22:37 -060055 align_end: Entry end offset alignment, or None
Simon Glass2574ef62016-11-25 20:15:51 -070056 pad_before: Number of pad bytes before the contents, 0 if none
57 pad_after: Number of pad bytes after the contents, 0 if none
58 data: Contents of entry (string of bytes)
Simon Glassaa2fcf92019-07-08 14:25:30 -060059 compress: Compression algoithm used (e.g. 'lz4'), 'none' if none
Simon Glasse61b6f62019-07-08 14:25:37 -060060 orig_offset: Original offset value read from node
61 orig_size: Original size value read from node
Simon Glass2574ef62016-11-25 20:15:51 -070062 """
Simon Glass2c360cf2019-07-20 12:23:45 -060063 def __init__(self, section, etype, node, name_prefix=''):
Simon Glassb9ba4e02019-08-24 07:22:44 -060064 # Put this here to allow entry-docs and help to work without libfdt
65 global state
Simon Glassc585dd42020-04-17 18:09:03 -060066 from binman import state
Simon Glassb9ba4e02019-08-24 07:22:44 -060067
Simon Glassad5a7712018-06-01 09:38:14 -060068 self.section = section
Simon Glass2574ef62016-11-25 20:15:51 -070069 self.etype = etype
70 self._node = node
Simon Glass3b78d532018-06-01 09:38:21 -060071 self.name = node and (name_prefix + node.name) or 'none'
Simon Glasse8561af2018-08-01 15:22:37 -060072 self.offset = None
Simon Glass2574ef62016-11-25 20:15:51 -070073 self.size = None
Simon Glass1fdb4872019-10-31 07:43:02 -060074 self.pre_reset_size = None
Simon Glassaa2fcf92019-07-08 14:25:30 -060075 self.uncomp_size = None
Simon Glass5c350162018-07-17 13:25:47 -060076 self.data = None
Simon Glass2574ef62016-11-25 20:15:51 -070077 self.contents_size = 0
78 self.align = None
79 self.align_size = None
80 self.align_end = None
81 self.pad_before = 0
82 self.pad_after = 0
Simon Glasse8561af2018-08-01 15:22:37 -060083 self.offset_unset = False
Simon Glass9dcc8612018-08-01 15:22:42 -060084 self.image_pos = None
Simon Glassfa79a812018-09-14 04:57:29 -060085 self._expand_size = False
Simon Glassaa2fcf92019-07-08 14:25:30 -060086 self.compress = 'none'
Simon Glassa003cd32020-07-09 18:39:40 -060087 self.missing = False
Simon Glass2574ef62016-11-25 20:15:51 -070088
89 @staticmethod
Simon Glass75502932019-07-08 14:25:31 -060090 def Lookup(node_path, etype):
Simon Glass969616c2018-07-17 13:25:36 -060091 """Look up the entry class for a node.
Simon Glass2574ef62016-11-25 20:15:51 -070092
93 Args:
Simon Glass969616c2018-07-17 13:25:36 -060094 node_node: Path name of Node object containing information about
95 the entry to create (used for errors)
96 etype: Entry type to use
Simon Glass2574ef62016-11-25 20:15:51 -070097
98 Returns:
Simon Glass969616c2018-07-17 13:25:36 -060099 The entry class object if found, else None
Simon Glass2574ef62016-11-25 20:15:51 -0700100 """
Simon Glasse76a3e62018-06-01 09:38:11 -0600101 # Convert something like 'u-boot@0' to 'u_boot' since we are only
102 # interested in the type.
Simon Glass2574ef62016-11-25 20:15:51 -0700103 module_name = etype.replace('-', '_')
Simon Glasse76a3e62018-06-01 09:38:11 -0600104 if '@' in module_name:
105 module_name = module_name.split('@')[0]
Simon Glass2574ef62016-11-25 20:15:51 -0700106 module = modules.get(module_name)
107
Simon Glass691198c2018-06-01 09:38:15 -0600108 # Also allow entry-type modules to be brought in from the etype directory.
109
Simon Glass2574ef62016-11-25 20:15:51 -0700110 # Import the module if we have not already done so.
111 if not module:
112 try:
Simon Glassc585dd42020-04-17 18:09:03 -0600113 module = importlib.import_module('binman.etype.' + module_name)
Simon Glass969616c2018-07-17 13:25:36 -0600114 except ImportError as e:
115 raise ValueError("Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
116 (etype, node_path, module_name, e))
Simon Glass2574ef62016-11-25 20:15:51 -0700117 modules[module_name] = module
118
Simon Glass969616c2018-07-17 13:25:36 -0600119 # Look up the expected class name
120 return getattr(module, 'Entry_%s' % module_name)
121
122 @staticmethod
123 def Create(section, node, etype=None):
124 """Create a new entry for a node.
125
126 Args:
127 section: Section object containing this node
128 node: Node object containing information about the entry to
129 create
130 etype: Entry type to use, or None to work it out (used for tests)
131
132 Returns:
133 A new Entry object of the correct type (a subclass of Entry)
134 """
135 if not etype:
136 etype = fdt_util.GetString(node, 'type', node.name)
Simon Glass75502932019-07-08 14:25:31 -0600137 obj = Entry.Lookup(node.path, etype)
Simon Glass969616c2018-07-17 13:25:36 -0600138
Simon Glass2574ef62016-11-25 20:15:51 -0700139 # Call its constructor to get the object we want.
Simon Glassad5a7712018-06-01 09:38:14 -0600140 return obj(section, etype, node)
Simon Glass2574ef62016-11-25 20:15:51 -0700141
142 def ReadNode(self):
143 """Read entry information from the node
144
Simon Glass2c360cf2019-07-20 12:23:45 -0600145 This must be called as the first thing after the Entry is created.
146
Simon Glass2574ef62016-11-25 20:15:51 -0700147 This reads all the fields we recognise from the node, ready for use.
148 """
Simon Glass24b97442018-07-17 13:25:51 -0600149 if 'pos' in self._node.props:
150 self.Raise("Please use 'offset' instead of 'pos'")
Simon Glasse8561af2018-08-01 15:22:37 -0600151 self.offset = fdt_util.GetInt(self._node, 'offset')
Simon Glass2574ef62016-11-25 20:15:51 -0700152 self.size = fdt_util.GetInt(self._node, 'size')
Simon Glassfb30e292019-07-20 12:23:51 -0600153 self.orig_offset = fdt_util.GetInt(self._node, 'orig-offset')
154 self.orig_size = fdt_util.GetInt(self._node, 'orig-size')
155 if self.GetImage().copy_to_orig:
156 self.orig_offset = self.offset
157 self.orig_size = self.size
Simon Glasse61b6f62019-07-08 14:25:37 -0600158
Simon Glassb8424fa2019-07-08 14:25:46 -0600159 # These should not be set in input files, but are set in an FDT map,
160 # which is also read by this code.
161 self.image_pos = fdt_util.GetInt(self._node, 'image-pos')
162 self.uncomp_size = fdt_util.GetInt(self._node, 'uncomp-size')
163
Simon Glass2574ef62016-11-25 20:15:51 -0700164 self.align = fdt_util.GetInt(self._node, 'align')
165 if tools.NotPowerOfTwo(self.align):
166 raise ValueError("Node '%s': Alignment %s must be a power of two" %
167 (self._node.path, self.align))
168 self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
169 self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
170 self.align_size = fdt_util.GetInt(self._node, 'align-size')
171 if tools.NotPowerOfTwo(self.align_size):
Simon Glass39dd2152019-07-08 14:25:47 -0600172 self.Raise("Alignment size %s must be a power of two" %
173 self.align_size)
Simon Glass2574ef62016-11-25 20:15:51 -0700174 self.align_end = fdt_util.GetInt(self._node, 'align-end')
Simon Glasse8561af2018-08-01 15:22:37 -0600175 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
Simon Glassfa79a812018-09-14 04:57:29 -0600176 self.expand_size = fdt_util.GetBool(self._node, 'expand-size')
Simon Glass2574ef62016-11-25 20:15:51 -0700177
Simon Glass3732ec32018-09-14 04:57:18 -0600178 def GetDefaultFilename(self):
179 return None
180
Simon Glass267112e2019-07-20 12:23:28 -0600181 def GetFdts(self):
182 """Get the device trees used by this entry
Simon Glass0c9d5b52018-09-14 04:57:22 -0600183
184 Returns:
Simon Glass267112e2019-07-20 12:23:28 -0600185 Empty dict, if this entry is not a .dtb, otherwise:
186 Dict:
187 key: Filename from this entry (without the path)
Simon Glass684a4f12019-07-20 12:23:31 -0600188 value: Tuple:
189 Fdt object for this dtb, or None if not available
190 Filename of file containing this dtb
Simon Glass0c9d5b52018-09-14 04:57:22 -0600191 """
Simon Glass267112e2019-07-20 12:23:28 -0600192 return {}
Simon Glass0c9d5b52018-09-14 04:57:22 -0600193
Simon Glassac6328c2018-09-14 04:57:28 -0600194 def ExpandEntries(self):
195 pass
196
Simon Glasse22f8fa2018-07-06 10:27:41 -0600197 def AddMissingProperties(self):
198 """Add new properties to the device tree as needed for this entry"""
Simon Glass9dcc8612018-08-01 15:22:42 -0600199 for prop in ['offset', 'size', 'image-pos']:
Simon Glasse22f8fa2018-07-06 10:27:41 -0600200 if not prop in self._node.props:
Simon Glassc8135dc2018-09-14 04:57:21 -0600201 state.AddZeroProp(self._node, prop)
Simon Glassfb30e292019-07-20 12:23:51 -0600202 if self.GetImage().allow_repack:
203 if self.orig_offset is not None:
204 state.AddZeroProp(self._node, 'orig-offset', True)
205 if self.orig_size is not None:
206 state.AddZeroProp(self._node, 'orig-size', True)
207
Simon Glassaa2fcf92019-07-08 14:25:30 -0600208 if self.compress != 'none':
209 state.AddZeroProp(self._node, 'uncomp-size')
Simon Glassae7cf032018-09-14 04:57:31 -0600210 err = state.CheckAddHashProp(self._node)
211 if err:
212 self.Raise(err)
Simon Glasse22f8fa2018-07-06 10:27:41 -0600213
214 def SetCalculatedProperties(self):
215 """Set the value of device-tree properties calculated by binman"""
Simon Glassc8135dc2018-09-14 04:57:21 -0600216 state.SetInt(self._node, 'offset', self.offset)
217 state.SetInt(self._node, 'size', self.size)
Simon Glass39dd2152019-07-08 14:25:47 -0600218 base = self.section.GetRootSkipAtStart() if self.section else 0
219 state.SetInt(self._node, 'image-pos', self.image_pos - base)
Simon Glassfb30e292019-07-20 12:23:51 -0600220 if self.GetImage().allow_repack:
221 if self.orig_offset is not None:
222 state.SetInt(self._node, 'orig-offset', self.orig_offset, True)
223 if self.orig_size is not None:
224 state.SetInt(self._node, 'orig-size', self.orig_size, True)
Simon Glassaa2fcf92019-07-08 14:25:30 -0600225 if self.uncomp_size is not None:
226 state.SetInt(self._node, 'uncomp-size', self.uncomp_size)
Simon Glassae7cf032018-09-14 04:57:31 -0600227 state.CheckSetHashValue(self._node, self.GetData)
Simon Glasse22f8fa2018-07-06 10:27:41 -0600228
Simon Glass92307732018-07-06 10:27:40 -0600229 def ProcessFdt(self, fdt):
Simon Glasse219aa42018-09-14 04:57:24 -0600230 """Allow entries to adjust the device tree
231
232 Some entries need to adjust the device tree for their purposes. This
233 may involve adding or deleting properties.
234
235 Returns:
236 True if processing is complete
237 False if processing could not be completed due to a dependency.
238 This will cause the entry to be retried after others have been
239 called
240 """
Simon Glass92307732018-07-06 10:27:40 -0600241 return True
242
Simon Glass3b78d532018-06-01 09:38:21 -0600243 def SetPrefix(self, prefix):
244 """Set the name prefix for a node
245
246 Args:
247 prefix: Prefix to set, or '' to not use a prefix
248 """
249 if prefix:
250 self.name = prefix + self.name
251
Simon Glass2e1169f2018-07-06 10:27:19 -0600252 def SetContents(self, data):
253 """Set the contents of an entry
254
255 This sets both the data and content_size properties
256
257 Args:
Simon Glassd17dfea2019-07-08 14:25:33 -0600258 data: Data to set to the contents (bytes)
Simon Glass2e1169f2018-07-06 10:27:19 -0600259 """
260 self.data = data
261 self.contents_size = len(self.data)
262
263 def ProcessContentsUpdate(self, data):
Simon Glassd17dfea2019-07-08 14:25:33 -0600264 """Update the contents of an entry, after the size is fixed
Simon Glass2e1169f2018-07-06 10:27:19 -0600265
Simon Glassec849852019-07-08 14:25:35 -0600266 This checks that the new data is the same size as the old. If the size
267 has changed, this triggers a re-run of the packing algorithm.
Simon Glass2e1169f2018-07-06 10:27:19 -0600268
269 Args:
Simon Glassd17dfea2019-07-08 14:25:33 -0600270 data: Data to set to the contents (bytes)
Simon Glass2e1169f2018-07-06 10:27:19 -0600271
272 Raises:
273 ValueError if the new data size is not the same as the old
274 """
Simon Glassec849852019-07-08 14:25:35 -0600275 size_ok = True
Simon Glasse61b6f62019-07-08 14:25:37 -0600276 new_size = len(data)
Simon Glass9d8ee322019-07-20 12:23:58 -0600277 if state.AllowEntryExpansion() and new_size > self.contents_size:
278 # self.data will indicate the new size needed
279 size_ok = False
280 elif state.AllowEntryContraction() and new_size < self.contents_size:
281 size_ok = False
282
283 # If not allowed to change, try to deal with it or give up
284 if size_ok:
Simon Glasse61b6f62019-07-08 14:25:37 -0600285 if new_size > self.contents_size:
Simon Glass9d8ee322019-07-20 12:23:58 -0600286 self.Raise('Cannot update entry size from %d to %d' %
287 (self.contents_size, new_size))
288
289 # Don't let the data shrink. Pad it if necessary
290 if size_ok and new_size < self.contents_size:
291 data += tools.GetBytes(0, self.contents_size - new_size)
292
293 if not size_ok:
294 tout.Debug("Entry '%s' size change from %s to %s" % (
295 self._node.path, ToHex(self.contents_size),
296 ToHex(new_size)))
Simon Glass2e1169f2018-07-06 10:27:19 -0600297 self.SetContents(data)
Simon Glassec849852019-07-08 14:25:35 -0600298 return size_ok
Simon Glass2e1169f2018-07-06 10:27:19 -0600299
Simon Glass2574ef62016-11-25 20:15:51 -0700300 def ObtainContents(self):
301 """Figure out the contents of an entry.
302
303 Returns:
304 True if the contents were found, False if another call is needed
305 after the other entries are processed.
306 """
307 # No contents by default: subclasses can implement this
308 return True
309
Simon Glasse61b6f62019-07-08 14:25:37 -0600310 def ResetForPack(self):
311 """Reset offset/size fields so that packing can be done again"""
Simon Glassb6dff4c2019-07-20 12:23:36 -0600312 self.Detail('ResetForPack: offset %s->%s, size %s->%s' %
313 (ToHex(self.offset), ToHex(self.orig_offset),
314 ToHex(self.size), ToHex(self.orig_size)))
Simon Glass1fdb4872019-10-31 07:43:02 -0600315 self.pre_reset_size = self.size
Simon Glasse61b6f62019-07-08 14:25:37 -0600316 self.offset = self.orig_offset
317 self.size = self.orig_size
318
Simon Glasse8561af2018-08-01 15:22:37 -0600319 def Pack(self, offset):
Simon Glassad5a7712018-06-01 09:38:14 -0600320 """Figure out how to pack the entry into the section
Simon Glass2574ef62016-11-25 20:15:51 -0700321
322 Most of the time the entries are not fully specified. There may be
323 an alignment but no size. In that case we take the size from the
324 contents of the entry.
325
Simon Glasse8561af2018-08-01 15:22:37 -0600326 If an entry has no hard-coded offset, it will be placed at @offset.
Simon Glass2574ef62016-11-25 20:15:51 -0700327
Simon Glasse8561af2018-08-01 15:22:37 -0600328 Once this function is complete, both the offset and size of the
Simon Glass2574ef62016-11-25 20:15:51 -0700329 entry will be know.
330
331 Args:
Simon Glasse8561af2018-08-01 15:22:37 -0600332 Current section offset pointer
Simon Glass2574ef62016-11-25 20:15:51 -0700333
334 Returns:
Simon Glasse8561af2018-08-01 15:22:37 -0600335 New section offset pointer (after this entry)
Simon Glass2574ef62016-11-25 20:15:51 -0700336 """
Simon Glassb6dff4c2019-07-20 12:23:36 -0600337 self.Detail('Packing: offset=%s, size=%s, content_size=%x' %
338 (ToHex(self.offset), ToHex(self.size),
339 self.contents_size))
Simon Glasse8561af2018-08-01 15:22:37 -0600340 if self.offset is None:
341 if self.offset_unset:
342 self.Raise('No offset set with offset-unset: should another '
343 'entry provide this correct offset?')
344 self.offset = tools.Align(offset, self.align)
Simon Glass2574ef62016-11-25 20:15:51 -0700345 needed = self.pad_before + self.contents_size + self.pad_after
346 needed = tools.Align(needed, self.align_size)
347 size = self.size
348 if not size:
349 size = needed
Simon Glasse8561af2018-08-01 15:22:37 -0600350 new_offset = self.offset + size
351 aligned_offset = tools.Align(new_offset, self.align_end)
352 if aligned_offset != new_offset:
353 size = aligned_offset - self.offset
354 new_offset = aligned_offset
Simon Glass2574ef62016-11-25 20:15:51 -0700355
356 if not self.size:
357 self.size = size
358
359 if self.size < needed:
360 self.Raise("Entry contents size is %#x (%d) but entry size is "
361 "%#x (%d)" % (needed, needed, self.size, self.size))
362 # Check that the alignment is correct. It could be wrong if the
Simon Glasse8561af2018-08-01 15:22:37 -0600363 # and offset or size values were provided (i.e. not calculated), but
Simon Glass2574ef62016-11-25 20:15:51 -0700364 # conflict with the provided alignment values
365 if self.size != tools.Align(self.size, self.align_size):
366 self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
367 (self.size, self.size, self.align_size, self.align_size))
Simon Glasse8561af2018-08-01 15:22:37 -0600368 if self.offset != tools.Align(self.offset, self.align):
369 self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
370 (self.offset, self.offset, self.align, self.align))
Simon Glassb6dff4c2019-07-20 12:23:36 -0600371 self.Detail(' - packed: offset=%#x, size=%#x, content_size=%#x, next_offset=%x' %
372 (self.offset, self.size, self.contents_size, new_offset))
Simon Glass2574ef62016-11-25 20:15:51 -0700373
Simon Glasse8561af2018-08-01 15:22:37 -0600374 return new_offset
Simon Glass2574ef62016-11-25 20:15:51 -0700375
376 def Raise(self, msg):
377 """Convenience function to raise an error referencing a node"""
378 raise ValueError("Node '%s': %s" % (self._node.path, msg))
379
Simon Glassb6dff4c2019-07-20 12:23:36 -0600380 def Detail(self, msg):
381 """Convenience function to log detail referencing a node"""
382 tag = "Node '%s'" % self._node.path
383 tout.Detail('%30s: %s' % (tag, msg))
384
Simon Glass91710b32018-07-17 13:25:32 -0600385 def GetEntryArgsOrProps(self, props, required=False):
386 """Return the values of a set of properties
387
388 Args:
389 props: List of EntryArg objects
390
391 Raises:
392 ValueError if a property is not found
393 """
394 values = []
395 missing = []
396 for prop in props:
397 python_prop = prop.name.replace('-', '_')
398 if hasattr(self, python_prop):
399 value = getattr(self, python_prop)
400 else:
401 value = None
402 if value is None:
403 value = self.GetArg(prop.name, prop.datatype)
404 if value is None and required:
405 missing.append(prop.name)
406 values.append(value)
407 if missing:
408 self.Raise('Missing required properties/entry args: %s' %
409 (', '.join(missing)))
410 return values
411
Simon Glass2574ef62016-11-25 20:15:51 -0700412 def GetPath(self):
413 """Get the path of a node
414
415 Returns:
416 Full path of the node for this entry
417 """
418 return self._node.path
419
420 def GetData(self):
Simon Glassb6dff4c2019-07-20 12:23:36 -0600421 self.Detail('GetData: size %s' % ToHexSize(self.data))
Simon Glass2574ef62016-11-25 20:15:51 -0700422 return self.data
423
Simon Glasse8561af2018-08-01 15:22:37 -0600424 def GetOffsets(self):
Simon Glass224bc662019-07-08 13:18:30 -0600425 """Get the offsets for siblings
426
427 Some entry types can contain information about the position or size of
428 other entries. An example of this is the Intel Flash Descriptor, which
429 knows where the Intel Management Engine section should go.
430
431 If this entry knows about the position of other entries, it can specify
432 this by returning values here
433
434 Returns:
435 Dict:
436 key: Entry type
437 value: List containing position and size of the given entry
Simon Glassed365eb2019-07-08 13:18:39 -0600438 type. Either can be None if not known
Simon Glass224bc662019-07-08 13:18:30 -0600439 """
Simon Glass2574ef62016-11-25 20:15:51 -0700440 return {}
441
Simon Glassed365eb2019-07-08 13:18:39 -0600442 def SetOffsetSize(self, offset, size):
443 """Set the offset and/or size of an entry
444
445 Args:
446 offset: New offset, or None to leave alone
447 size: New size, or None to leave alone
448 """
449 if offset is not None:
450 self.offset = offset
451 if size is not None:
452 self.size = size
Simon Glass2574ef62016-11-25 20:15:51 -0700453
Simon Glass9dcc8612018-08-01 15:22:42 -0600454 def SetImagePos(self, image_pos):
455 """Set the position in the image
456
457 Args:
458 image_pos: Position of this entry in the image
459 """
460 self.image_pos = image_pos + self.offset
461
Simon Glass2574ef62016-11-25 20:15:51 -0700462 def ProcessContents(self):
Simon Glassec849852019-07-08 14:25:35 -0600463 """Do any post-packing updates of entry contents
464
465 This function should call ProcessContentsUpdate() to update the entry
466 contents, if necessary, returning its return value here.
467
468 Args:
469 data: Data to set to the contents (bytes)
470
471 Returns:
472 True if the new data size is OK, False if expansion is needed
473
474 Raises:
475 ValueError if the new data size is not the same as the old and
476 state.AllowEntryExpansion() is False
477 """
478 return True
Simon Glass4ca8e042017-11-13 18:55:01 -0700479
Simon Glass8a6f56e2018-06-01 09:38:13 -0600480 def WriteSymbols(self, section):
Simon Glass4ca8e042017-11-13 18:55:01 -0700481 """Write symbol values into binary files for access at run time
482
483 Args:
Simon Glass8a6f56e2018-06-01 09:38:13 -0600484 section: Section containing the entry
Simon Glass4ca8e042017-11-13 18:55:01 -0700485 """
486 pass
Simon Glassa91e1152018-06-01 09:38:16 -0600487
Simon Glasse8561af2018-08-01 15:22:37 -0600488 def CheckOffset(self):
489 """Check that the entry offsets are correct
Simon Glassa91e1152018-06-01 09:38:16 -0600490
Simon Glasse8561af2018-08-01 15:22:37 -0600491 This is used for entries which have extra offset requirements (other
Simon Glassa91e1152018-06-01 09:38:16 -0600492 than having to be fully inside their section). Sub-classes can implement
493 this function and raise if there is a problem.
494 """
495 pass
Simon Glass30732662018-06-01 09:38:20 -0600496
Simon Glass3a9a2b82018-07-17 13:25:28 -0600497 @staticmethod
Simon Glasscd817d52018-09-14 04:57:36 -0600498 def GetStr(value):
499 if value is None:
500 return '<none> '
501 return '%08x' % value
502
503 @staticmethod
Simon Glass7eca7922018-07-17 13:25:49 -0600504 def WriteMapLine(fd, indent, name, offset, size, image_pos):
Simon Glasscd817d52018-09-14 04:57:36 -0600505 print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
506 Entry.GetStr(offset), Entry.GetStr(size),
507 name), file=fd)
Simon Glass3a9a2b82018-07-17 13:25:28 -0600508
Simon Glass30732662018-06-01 09:38:20 -0600509 def WriteMap(self, fd, indent):
510 """Write a map of the entry to a .map file
511
512 Args:
513 fd: File to write the map to
514 indent: Curent indent level of map (0=none, 1=one level, etc.)
515 """
Simon Glass7eca7922018-07-17 13:25:49 -0600516 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
517 self.image_pos)
Simon Glass91710b32018-07-17 13:25:32 -0600518
Simon Glass704784b2018-07-17 13:25:38 -0600519 def GetEntries(self):
520 """Return a list of entries contained by this entry
521
522 Returns:
523 List of entries, or None if none. A normal entry has no entries
524 within it so will return None
525 """
526 return None
527
Simon Glass91710b32018-07-17 13:25:32 -0600528 def GetArg(self, name, datatype=str):
529 """Get the value of an entry argument or device-tree-node property
530
531 Some node properties can be provided as arguments to binman. First check
532 the entry arguments, and fall back to the device tree if not found
533
534 Args:
535 name: Argument name
536 datatype: Data type (str or int)
537
538 Returns:
539 Value of argument as a string or int, or None if no value
540
541 Raises:
542 ValueError if the argument cannot be converted to in
543 """
Simon Glass29aa7362018-09-14 04:57:19 -0600544 value = state.GetEntryArg(name)
Simon Glass91710b32018-07-17 13:25:32 -0600545 if value is not None:
546 if datatype == int:
547 try:
548 value = int(value)
549 except ValueError:
550 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
551 (name, value))
552 elif datatype == str:
553 pass
554 else:
555 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
556 datatype)
557 else:
558 value = fdt_util.GetDatatype(self._node, name, datatype)
559 return value
Simon Glass969616c2018-07-17 13:25:36 -0600560
561 @staticmethod
562 def WriteDocs(modules, test_missing=None):
563 """Write out documentation about the various entry types to stdout
564
565 Args:
566 modules: List of modules to include
567 test_missing: Used for testing. This is a module to report
568 as missing
569 """
570 print('''Binman Entry Documentation
571===========================
572
573This file describes the entry types supported by binman. These entry types can
574be placed in an image one by one to build up a final firmware image. It is
575fairly easy to create new entry types. Just add a new file to the 'etype'
576directory. You can use the existing entries as examples.
577
578Note that some entries are subclasses of others, using and extending their
579features to produce new behaviours.
580
581
582''')
583 modules = sorted(modules)
584
585 # Don't show the test entry
586 if '_testing' in modules:
587 modules.remove('_testing')
588 missing = []
589 for name in modules:
Simon Glassc585dd42020-04-17 18:09:03 -0600590 module = Entry.Lookup('WriteDocs', name)
Simon Glass969616c2018-07-17 13:25:36 -0600591 docs = getattr(module, '__doc__')
592 if test_missing == name:
593 docs = None
594 if docs:
595 lines = docs.splitlines()
596 first_line = lines[0]
597 rest = [line[4:] for line in lines[1:]]
598 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
599 print(hdr)
600 print('-' * len(hdr))
601 print('\n'.join(rest))
602 print()
603 print()
604 else:
605 missing.append(name)
606
607 if missing:
608 raise ValueError('Documentation is missing for modules: %s' %
609 ', '.join(missing))
Simon Glass639505b2018-09-14 04:57:11 -0600610
611 def GetUniqueName(self):
612 """Get a unique name for a node
613
614 Returns:
615 String containing a unique name for a node, consisting of the name
616 of all ancestors (starting from within the 'binman' node) separated
617 by a dot ('.'). This can be useful for generating unique filesnames
618 in the output directory.
619 """
620 name = self.name
621 node = self._node
622 while node.parent:
623 node = node.parent
624 if node.name == 'binman':
625 break
626 name = '%s.%s' % (node.name, name)
627 return name
Simon Glassfa79a812018-09-14 04:57:29 -0600628
629 def ExpandToLimit(self, limit):
630 """Expand an entry so that it ends at the given offset limit"""
631 if self.offset + self.size < limit:
632 self.size = limit - self.offset
633 # Request the contents again, since changing the size requires that
634 # the data grows. This should not fail, but check it to be sure.
635 if not self.ObtainContents():
636 self.Raise('Cannot obtain contents when expanding entry')
Simon Glassc4056b82019-07-08 13:18:38 -0600637
638 def HasSibling(self, name):
639 """Check if there is a sibling of a given name
640
641 Returns:
642 True if there is an entry with this name in the the same section,
643 else False
644 """
645 return name in self.section.GetEntries()
Simon Glasscec34ba2019-07-08 14:25:28 -0600646
647 def GetSiblingImagePos(self, name):
648 """Return the image position of the given sibling
649
650 Returns:
651 Image position of sibling, or None if the sibling has no position,
652 or False if there is no such sibling
653 """
654 if not self.HasSibling(name):
655 return False
656 return self.section.GetEntries()[name].image_pos
Simon Glass6b156f82019-07-08 14:25:43 -0600657
658 @staticmethod
659 def AddEntryInfo(entries, indent, name, etype, size, image_pos,
660 uncomp_size, offset, entry):
661 """Add a new entry to the entries list
662
663 Args:
664 entries: List (of EntryInfo objects) to add to
665 indent: Current indent level to add to list
666 name: Entry name (string)
667 etype: Entry type (string)
668 size: Entry size in bytes (int)
669 image_pos: Position within image in bytes (int)
670 uncomp_size: Uncompressed size if the entry uses compression, else
671 None
672 offset: Entry offset within parent in bytes (int)
673 entry: Entry object
674 """
675 entries.append(EntryInfo(indent, name, etype, size, image_pos,
676 uncomp_size, offset, entry))
677
678 def ListEntries(self, entries, indent):
679 """Add files in this entry to the list of entries
680
681 This can be overridden by subclasses which need different behaviour.
682
683 Args:
684 entries: List (of EntryInfo objects) to add to
685 indent: Current indent level to add to list
686 """
687 self.AddEntryInfo(entries, indent, self.name, self.etype, self.size,
688 self.image_pos, self.uncomp_size, self.offset, self)
Simon Glass4c613bf2019-07-08 14:25:50 -0600689
690 def ReadData(self, decomp=True):
691 """Read the data for an entry from the image
692
693 This is used when the image has been read in and we want to extract the
694 data for a particular entry from that image.
695
696 Args:
697 decomp: True to decompress any compressed data before returning it;
698 False to return the raw, uncompressed data
699
700 Returns:
701 Entry data (bytes)
702 """
703 # Use True here so that we get an uncompressed section to work from,
704 # although compressed sections are currently not supported
Simon Glass4d8151f2019-09-25 08:56:21 -0600705 tout.Debug("ReadChildData section '%s', entry '%s'" %
706 (self.section.GetPath(), self.GetPath()))
Simon Glass0cd8ace2019-07-20 12:24:04 -0600707 data = self.section.ReadChildData(self, decomp)
708 return data
Simon Glassaf8c45c2019-07-20 12:23:41 -0600709
Simon Glass23f00472019-09-25 08:56:20 -0600710 def ReadChildData(self, child, decomp=True):
Simon Glass4d8151f2019-09-25 08:56:21 -0600711 """Read the data for a particular child entry
Simon Glass23f00472019-09-25 08:56:20 -0600712
713 This reads data from the parent and extracts the piece that relates to
714 the given child.
715
716 Args:
Simon Glass4d8151f2019-09-25 08:56:21 -0600717 child: Child entry to read data for (must be valid)
Simon Glass23f00472019-09-25 08:56:20 -0600718 decomp: True to decompress any compressed data before returning it;
719 False to return the raw, uncompressed data
720
721 Returns:
722 Data for the child (bytes)
723 """
724 pass
725
Simon Glassaf8c45c2019-07-20 12:23:41 -0600726 def LoadData(self, decomp=True):
727 data = self.ReadData(decomp)
Simon Glass072959a2019-07-20 12:23:50 -0600728 self.contents_size = len(data)
Simon Glassaf8c45c2019-07-20 12:23:41 -0600729 self.ProcessContentsUpdate(data)
730 self.Detail('Loaded data size %x' % len(data))
Simon Glass990b1742019-07-20 12:23:46 -0600731
732 def GetImage(self):
733 """Get the image containing this entry
734
735 Returns:
736 Image object containing this entry
737 """
738 return self.section.GetImage()
Simon Glass072959a2019-07-20 12:23:50 -0600739
740 def WriteData(self, data, decomp=True):
741 """Write the data to an entry in the image
742
743 This is used when the image has been read in and we want to replace the
744 data for a particular entry in that image.
745
746 The image must be re-packed and written out afterwards.
747
748 Args:
749 data: Data to replace it with
750 decomp: True to compress the data if needed, False if data is
751 already compressed so should be used as is
752
753 Returns:
754 True if the data did not result in a resize of this entry, False if
755 the entry must be resized
756 """
Simon Glass1fdb4872019-10-31 07:43:02 -0600757 if self.size is not None:
758 self.contents_size = self.size
759 else:
760 self.contents_size = self.pre_reset_size
Simon Glass072959a2019-07-20 12:23:50 -0600761 ok = self.ProcessContentsUpdate(data)
762 self.Detail('WriteData: size=%x, ok=%s' % (len(data), ok))
Simon Glassd34af7a2019-07-20 12:24:05 -0600763 section_ok = self.section.WriteChildData(self)
764 return ok and section_ok
765
766 def WriteChildData(self, child):
767 """Handle writing the data in a child entry
768
769 This should be called on the child's parent section after the child's
770 data has been updated. It
771
772 This base-class implementation does nothing, since the base Entry object
773 does not have any children.
774
775 Args:
776 child: Child Entry that was written
777
778 Returns:
779 True if the section could be updated successfully, False if the
780 data is such that the section could not updat
781 """
782 return True
Simon Glass11453762019-07-20 12:23:55 -0600783
784 def GetSiblingOrder(self):
785 """Get the relative order of an entry amoung its siblings
786
787 Returns:
788 'start' if this entry is first among siblings, 'end' if last,
789 otherwise None
790 """
791 entries = list(self.section.GetEntries().values())
792 if entries:
793 if self == entries[0]:
794 return 'start'
795 elif self == entries[-1]:
796 return 'end'
797 return 'middle'
Simon Glass5d94cc62020-07-09 18:39:38 -0600798
799 def SetAllowMissing(self, allow_missing):
800 """Set whether a section allows missing external blobs
801
802 Args:
803 allow_missing: True if allowed, False if not allowed
804 """
805 # This is meaningless for anything other than sections
806 pass
Simon Glassa003cd32020-07-09 18:39:40 -0600807
808 def CheckMissing(self, missing_list):
809 """Check if any entries in this section have missing external blobs
810
811 If there are missing blobs, the entries are added to the list
812
813 Args:
814 missing_list: List of Entry objects to be added to
815 """
816 if self.missing:
817 missing_list.append(self)