1 # SPDX-License-Identifier: GPL-2.0+
2 # Copyright (c) 2016 Google, Inc
4 # Base class for all entries
7 from __future__ import print_function
9 from collections import namedtuple
11 # importlib was introduced in Python 2.7 but there was a report of it not
12 # working in 2.7.12, so we work around this:
13 # http://lists.denx.de/pipermail/u-boot/2016-October/269729.html
18 have_importlib = False
29 our_path = os.path.dirname(os.path.realpath(__file__))
32 # An argument which can be passed to entries on the command line, in lieu of
33 # device-tree properties.
34 EntryArg = namedtuple('EntryArg', ['name', 'datatype'])
38 """An Entry in the section
40 An entry corresponds to a single node in the device-tree description
41 of the section. Each entry ends up being a part of the final section.
42 Entries can be placed either right next to each other, or with padding
43 between them. The type of the entry determines the data that is in it.
45 This class is not used by itself. All entry objects are subclasses of
49 section: Section object containing this entry
50 node: The node that created this entry
51 offset: Offset of entry within the section, None if not known yet (in
52 which case it will be calculated by Pack())
53 size: Entry size in bytes, None if not known
54 contents_size: Size of contents in bytes, 0 by default
55 align: Entry start offset alignment, or None
56 align_size: Entry size alignment, or None
57 align_end: Entry end offset alignment, or None
58 pad_before: Number of pad bytes before the contents, 0 if none
59 pad_after: Number of pad bytes after the contents, 0 if none
60 data: Contents of entry (string of bytes)
62 def __init__(self, section, etype, node, read_node=True, name_prefix=''):
63 self.section = section
66 self.name = node and (name_prefix + node.name) or 'none'
70 self.contents_size = 0
72 self.align_size = None
76 self.offset_unset = False
78 self._expand_size = False
83 def Lookup(section, node_path, etype):
84 """Look up the entry class for a node.
87 section: Section object containing this node
88 node_node: Path name of Node object containing information about
89 the entry to create (used for errors)
90 etype: Entry type to use
93 The entry class object if found, else None
95 # Convert something like 'u-boot@0' to 'u_boot' since we are only
96 # interested in the type.
97 module_name = etype.replace('-', '_')
98 if '@' in module_name:
99 module_name = module_name.split('@')[0]
100 module = modules.get(module_name)
102 # Also allow entry-type modules to be brought in from the etype directory.
104 # Import the module if we have not already done so.
107 sys.path.insert(0, os.path.join(our_path, 'etype'))
110 module = importlib.import_module(module_name)
112 module = __import__(module_name)
113 except ImportError as e:
114 raise ValueError("Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
115 (etype, node_path, module_name, e))
118 modules[module_name] = module
120 # Look up the expected class name
121 return getattr(module, 'Entry_%s' % module_name)
124 def Create(section, node, etype=None):
125 """Create a new entry for a node.
128 section: Section object containing this node
129 node: Node object containing information about the entry to
131 etype: Entry type to use, or None to work it out (used for tests)
134 A new Entry object of the correct type (a subclass of Entry)
137 etype = fdt_util.GetString(node, 'type', node.name)
138 obj = Entry.Lookup(section, node.path, etype)
140 # Call its constructor to get the object we want.
141 return obj(section, etype, node)
144 """Read entry information from the node
146 This reads all the fields we recognise from the node, ready for use.
148 if 'pos' in self._node.props:
149 self.Raise("Please use 'offset' instead of 'pos'")
150 self.offset = fdt_util.GetInt(self._node, 'offset')
151 self.size = fdt_util.GetInt(self._node, 'size')
152 self.align = fdt_util.GetInt(self._node, 'align')
153 if tools.NotPowerOfTwo(self.align):
154 raise ValueError("Node '%s': Alignment %s must be a power of two" %
155 (self._node.path, self.align))
156 self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
157 self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
158 self.align_size = fdt_util.GetInt(self._node, 'align-size')
159 if tools.NotPowerOfTwo(self.align_size):
160 raise ValueError("Node '%s': Alignment size %s must be a power "
161 "of two" % (self._node.path, self.align_size))
162 self.align_end = fdt_util.GetInt(self._node, 'align-end')
163 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
164 self.expand_size = fdt_util.GetBool(self._node, 'expand-size')
166 def GetDefaultFilename(self):
170 """Get the set of device trees used by this entry
173 Set containing the filename from this entry, if it is a .dtb, else
176 fname = self.GetDefaultFilename()
177 # It would be better to use isinstance(self, Entry_blob_dtb) here but
178 # we cannot access Entry_blob_dtb
179 if fname and fname.endswith('.dtb'):
183 def ExpandEntries(self):
186 def AddMissingProperties(self):
187 """Add new properties to the device tree as needed for this entry"""
188 for prop in ['offset', 'size', 'image-pos']:
189 if not prop in self._node.props:
190 state.AddZeroProp(self._node, prop)
191 err = state.CheckAddHashProp(self._node)
195 def SetCalculatedProperties(self):
196 """Set the value of device-tree properties calculated by binman"""
197 state.SetInt(self._node, 'offset', self.offset)
198 state.SetInt(self._node, 'size', self.size)
199 state.SetInt(self._node, 'image-pos',
200 self.image_pos - self.section.GetRootSkipAtStart())
201 state.CheckSetHashValue(self._node, self.GetData)
203 def ProcessFdt(self, fdt):
204 """Allow entries to adjust the device tree
206 Some entries need to adjust the device tree for their purposes. This
207 may involve adding or deleting properties.
210 True if processing is complete
211 False if processing could not be completed due to a dependency.
212 This will cause the entry to be retried after others have been
217 def SetPrefix(self, prefix):
218 """Set the name prefix for a node
221 prefix: Prefix to set, or '' to not use a prefix
224 self.name = prefix + self.name
226 def SetContents(self, data):
227 """Set the contents of an entry
229 This sets both the data and content_size properties
232 data: Data to set to the contents (string)
235 self.contents_size = len(self.data)
237 def ProcessContentsUpdate(self, data):
238 """Update the contens of an entry, after the size is fixed
240 This checks that the new data is the same size as the old.
243 data: Data to set to the contents (string)
246 ValueError if the new data size is not the same as the old
248 if len(data) != self.contents_size:
249 self.Raise('Cannot update entry size from %d to %d' %
250 (len(data), self.contents_size))
251 self.SetContents(data)
253 def ObtainContents(self):
254 """Figure out the contents of an entry.
257 True if the contents were found, False if another call is needed
258 after the other entries are processed.
260 # No contents by default: subclasses can implement this
263 def Pack(self, offset):
264 """Figure out how to pack the entry into the section
266 Most of the time the entries are not fully specified. There may be
267 an alignment but no size. In that case we take the size from the
268 contents of the entry.
270 If an entry has no hard-coded offset, it will be placed at @offset.
272 Once this function is complete, both the offset and size of the
276 Current section offset pointer
279 New section offset pointer (after this entry)
281 if self.offset is None:
282 if self.offset_unset:
283 self.Raise('No offset set with offset-unset: should another '
284 'entry provide this correct offset?')
285 self.offset = tools.Align(offset, self.align)
286 needed = self.pad_before + self.contents_size + self.pad_after
287 needed = tools.Align(needed, self.align_size)
291 new_offset = self.offset + size
292 aligned_offset = tools.Align(new_offset, self.align_end)
293 if aligned_offset != new_offset:
294 size = aligned_offset - self.offset
295 new_offset = aligned_offset
300 if self.size < needed:
301 self.Raise("Entry contents size is %#x (%d) but entry size is "
302 "%#x (%d)" % (needed, needed, self.size, self.size))
303 # Check that the alignment is correct. It could be wrong if the
304 # and offset or size values were provided (i.e. not calculated), but
305 # conflict with the provided alignment values
306 if self.size != tools.Align(self.size, self.align_size):
307 self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
308 (self.size, self.size, self.align_size, self.align_size))
309 if self.offset != tools.Align(self.offset, self.align):
310 self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
311 (self.offset, self.offset, self.align, self.align))
315 def Raise(self, msg):
316 """Convenience function to raise an error referencing a node"""
317 raise ValueError("Node '%s': %s" % (self._node.path, msg))
319 def GetEntryArgsOrProps(self, props, required=False):
320 """Return the values of a set of properties
323 props: List of EntryArg objects
326 ValueError if a property is not found
331 python_prop = prop.name.replace('-', '_')
332 if hasattr(self, python_prop):
333 value = getattr(self, python_prop)
337 value = self.GetArg(prop.name, prop.datatype)
338 if value is None and required:
339 missing.append(prop.name)
342 self.Raise('Missing required properties/entry args: %s' %
343 (', '.join(missing)))
347 """Get the path of a node
350 Full path of the node for this entry
352 return self._node.path
357 def GetOffsets(self):
360 def SetOffsetSize(self, pos, size):
364 def SetImagePos(self, image_pos):
365 """Set the position in the image
368 image_pos: Position of this entry in the image
370 self.image_pos = image_pos + self.offset
372 def ProcessContents(self):
375 def WriteSymbols(self, section):
376 """Write symbol values into binary files for access at run time
379 section: Section containing the entry
383 def CheckOffset(self):
384 """Check that the entry offsets are correct
386 This is used for entries which have extra offset requirements (other
387 than having to be fully inside their section). Sub-classes can implement
388 this function and raise if there is a problem.
396 return '%08x' % value
399 def WriteMapLine(fd, indent, name, offset, size, image_pos):
400 print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
401 Entry.GetStr(offset), Entry.GetStr(size),
404 def WriteMap(self, fd, indent):
405 """Write a map of the entry to a .map file
408 fd: File to write the map to
409 indent: Curent indent level of map (0=none, 1=one level, etc.)
411 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
414 def GetEntries(self):
415 """Return a list of entries contained by this entry
418 List of entries, or None if none. A normal entry has no entries
419 within it so will return None
423 def GetArg(self, name, datatype=str):
424 """Get the value of an entry argument or device-tree-node property
426 Some node properties can be provided as arguments to binman. First check
427 the entry arguments, and fall back to the device tree if not found
431 datatype: Data type (str or int)
434 Value of argument as a string or int, or None if no value
437 ValueError if the argument cannot be converted to in
439 value = state.GetEntryArg(name)
440 if value is not None:
445 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
447 elif datatype == str:
450 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
453 value = fdt_util.GetDatatype(self._node, name, datatype)
457 def WriteDocs(modules, test_missing=None):
458 """Write out documentation about the various entry types to stdout
461 modules: List of modules to include
462 test_missing: Used for testing. This is a module to report
465 print('''Binman Entry Documentation
466 ===========================
468 This file describes the entry types supported by binman. These entry types can
469 be placed in an image one by one to build up a final firmware image. It is
470 fairly easy to create new entry types. Just add a new file to the 'etype'
471 directory. You can use the existing entries as examples.
473 Note that some entries are subclasses of others, using and extending their
474 features to produce new behaviours.
478 modules = sorted(modules)
480 # Don't show the test entry
481 if '_testing' in modules:
482 modules.remove('_testing')
485 module = Entry.Lookup(name, name, name)
486 docs = getattr(module, '__doc__')
487 if test_missing == name:
490 lines = docs.splitlines()
491 first_line = lines[0]
492 rest = [line[4:] for line in lines[1:]]
493 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
495 print('-' * len(hdr))
496 print('\n'.join(rest))
503 raise ValueError('Documentation is missing for modules: %s' %
506 def GetUniqueName(self):
507 """Get a unique name for a node
510 String containing a unique name for a node, consisting of the name
511 of all ancestors (starting from within the 'binman' node) separated
512 by a dot ('.'). This can be useful for generating unique filesnames
513 in the output directory.
519 if node.name == 'binman':
521 name = '%s.%s' % (node.name, name)
524 def ExpandToLimit(self, limit):
525 """Expand an entry so that it ends at the given offset limit"""
526 if self.offset + self.size < limit:
527 self.size = limit - self.offset
528 # Request the contents again, since changing the size requires that
529 # the data grows. This should not fail, but check it to be sure.
530 if not self.ObtainContents():
531 self.Raise('Cannot obtain contents when expanding entry')