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
82 def Lookup(section, node_path, etype):
83 """Look up the entry class for a node.
86 section: Section object containing this node
87 node_node: Path name of Node object containing information about
88 the entry to create (used for errors)
89 etype: Entry type to use
92 The entry class object if found, else None
94 # Convert something like 'u-boot@0' to 'u_boot' since we are only
95 # interested in the type.
96 module_name = etype.replace('-', '_')
97 if '@' in module_name:
98 module_name = module_name.split('@')[0]
99 module = modules.get(module_name)
101 # Also allow entry-type modules to be brought in from the etype directory.
103 # Import the module if we have not already done so.
106 sys.path.insert(0, os.path.join(our_path, 'etype'))
109 module = importlib.import_module(module_name)
111 module = __import__(module_name)
112 except ImportError as e:
113 raise ValueError("Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
114 (etype, node_path, module_name, e))
117 modules[module_name] = module
119 # Look up the expected class name
120 return getattr(module, 'Entry_%s' % module_name)
123 def Create(section, node, etype=None):
124 """Create a new entry for a node.
127 section: Section object containing this node
128 node: Node object containing information about the entry to
130 etype: Entry type to use, or None to work it out (used for tests)
133 A new Entry object of the correct type (a subclass of Entry)
136 etype = fdt_util.GetString(node, 'type', node.name)
137 obj = Entry.Lookup(section, node.path, etype)
139 # Call its constructor to get the object we want.
140 return obj(section, etype, node)
143 """Read entry information from the node
145 This reads all the fields we recognise from the node, ready for use.
147 if 'pos' in self._node.props:
148 self.Raise("Please use 'offset' instead of 'pos'")
149 self.offset = fdt_util.GetInt(self._node, 'offset')
150 self.size = fdt_util.GetInt(self._node, 'size')
151 self.align = fdt_util.GetInt(self._node, 'align')
152 if tools.NotPowerOfTwo(self.align):
153 raise ValueError("Node '%s': Alignment %s must be a power of two" %
154 (self._node.path, self.align))
155 self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
156 self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
157 self.align_size = fdt_util.GetInt(self._node, 'align-size')
158 if tools.NotPowerOfTwo(self.align_size):
159 raise ValueError("Node '%s': Alignment size %s must be a power "
160 "of two" % (self._node.path, self.align_size))
161 self.align_end = fdt_util.GetInt(self._node, 'align-end')
162 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
164 def GetDefaultFilename(self):
167 def AddMissingProperties(self):
168 """Add new properties to the device tree as needed for this entry"""
169 for prop in ['offset', 'size', 'image-pos']:
170 if not prop in self._node.props:
171 state.AddZeroProp(self._node, prop)
173 def SetCalculatedProperties(self):
174 """Set the value of device-tree properties calculated by binman"""
175 state.SetInt(self._node, 'offset', self.offset)
176 state.SetInt(self._node, 'size', self.size)
177 state.SetInt(self._node, 'image-pos', self.image_pos)
179 def ProcessFdt(self, fdt):
182 def SetPrefix(self, prefix):
183 """Set the name prefix for a node
186 prefix: Prefix to set, or '' to not use a prefix
189 self.name = prefix + self.name
191 def SetContents(self, data):
192 """Set the contents of an entry
194 This sets both the data and content_size properties
197 data: Data to set to the contents (string)
200 self.contents_size = len(self.data)
202 def ProcessContentsUpdate(self, data):
203 """Update the contens of an entry, after the size is fixed
205 This checks that the new data is the same size as the old.
208 data: Data to set to the contents (string)
211 ValueError if the new data size is not the same as the old
213 if len(data) != self.contents_size:
214 self.Raise('Cannot update entry size from %d to %d' %
215 (len(data), self.contents_size))
216 self.SetContents(data)
218 def ObtainContents(self):
219 """Figure out the contents of an entry.
222 True if the contents were found, False if another call is needed
223 after the other entries are processed.
225 # No contents by default: subclasses can implement this
228 def Pack(self, offset):
229 """Figure out how to pack the entry into the section
231 Most of the time the entries are not fully specified. There may be
232 an alignment but no size. In that case we take the size from the
233 contents of the entry.
235 If an entry has no hard-coded offset, it will be placed at @offset.
237 Once this function is complete, both the offset and size of the
241 Current section offset pointer
244 New section offset pointer (after this entry)
246 if self.offset is None:
247 if self.offset_unset:
248 self.Raise('No offset set with offset-unset: should another '
249 'entry provide this correct offset?')
250 self.offset = tools.Align(offset, self.align)
251 needed = self.pad_before + self.contents_size + self.pad_after
252 needed = tools.Align(needed, self.align_size)
256 new_offset = self.offset + size
257 aligned_offset = tools.Align(new_offset, self.align_end)
258 if aligned_offset != new_offset:
259 size = aligned_offset - self.offset
260 new_offset = aligned_offset
265 if self.size < needed:
266 self.Raise("Entry contents size is %#x (%d) but entry size is "
267 "%#x (%d)" % (needed, needed, self.size, self.size))
268 # Check that the alignment is correct. It could be wrong if the
269 # and offset or size values were provided (i.e. not calculated), but
270 # conflict with the provided alignment values
271 if self.size != tools.Align(self.size, self.align_size):
272 self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
273 (self.size, self.size, self.align_size, self.align_size))
274 if self.offset != tools.Align(self.offset, self.align):
275 self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
276 (self.offset, self.offset, self.align, self.align))
280 def Raise(self, msg):
281 """Convenience function to raise an error referencing a node"""
282 raise ValueError("Node '%s': %s" % (self._node.path, msg))
284 def GetEntryArgsOrProps(self, props, required=False):
285 """Return the values of a set of properties
288 props: List of EntryArg objects
291 ValueError if a property is not found
296 python_prop = prop.name.replace('-', '_')
297 if hasattr(self, python_prop):
298 value = getattr(self, python_prop)
302 value = self.GetArg(prop.name, prop.datatype)
303 if value is None and required:
304 missing.append(prop.name)
307 self.Raise('Missing required properties/entry args: %s' %
308 (', '.join(missing)))
312 """Get the path of a node
315 Full path of the node for this entry
317 return self._node.path
322 def GetOffsets(self):
325 def SetOffsetSize(self, pos, size):
329 def SetImagePos(self, image_pos):
330 """Set the position in the image
333 image_pos: Position of this entry in the image
335 self.image_pos = image_pos + self.offset
337 def ProcessContents(self):
340 def WriteSymbols(self, section):
341 """Write symbol values into binary files for access at run time
344 section: Section containing the entry
348 def CheckOffset(self):
349 """Check that the entry offsets are correct
351 This is used for entries which have extra offset requirements (other
352 than having to be fully inside their section). Sub-classes can implement
353 this function and raise if there is a problem.
358 def WriteMapLine(fd, indent, name, offset, size, image_pos):
359 print('%08x %s%08x %08x %s' % (image_pos, ' ' * indent, offset,
360 size, name), file=fd)
362 def WriteMap(self, fd, indent):
363 """Write a map of the entry to a .map file
366 fd: File to write the map to
367 indent: Curent indent level of map (0=none, 1=one level, etc.)
369 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
372 def GetEntries(self):
373 """Return a list of entries contained by this entry
376 List of entries, or None if none. A normal entry has no entries
377 within it so will return None
381 def GetArg(self, name, datatype=str):
382 """Get the value of an entry argument or device-tree-node property
384 Some node properties can be provided as arguments to binman. First check
385 the entry arguments, and fall back to the device tree if not found
389 datatype: Data type (str or int)
392 Value of argument as a string or int, or None if no value
395 ValueError if the argument cannot be converted to in
397 value = state.GetEntryArg(name)
398 if value is not None:
403 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
405 elif datatype == str:
408 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
411 value = fdt_util.GetDatatype(self._node, name, datatype)
415 def WriteDocs(modules, test_missing=None):
416 """Write out documentation about the various entry types to stdout
419 modules: List of modules to include
420 test_missing: Used for testing. This is a module to report
423 print('''Binman Entry Documentation
424 ===========================
426 This file describes the entry types supported by binman. These entry types can
427 be placed in an image one by one to build up a final firmware image. It is
428 fairly easy to create new entry types. Just add a new file to the 'etype'
429 directory. You can use the existing entries as examples.
431 Note that some entries are subclasses of others, using and extending their
432 features to produce new behaviours.
436 modules = sorted(modules)
438 # Don't show the test entry
439 if '_testing' in modules:
440 modules.remove('_testing')
443 module = Entry.Lookup(name, name, name)
444 docs = getattr(module, '__doc__')
445 if test_missing == name:
448 lines = docs.splitlines()
449 first_line = lines[0]
450 rest = [line[4:] for line in lines[1:]]
451 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
453 print('-' * len(hdr))
454 print('\n'.join(rest))
461 raise ValueError('Documentation is missing for modules: %s' %
464 def GetUniqueName(self):
465 """Get a unique name for a node
468 String containing a unique name for a node, consisting of the name
469 of all ancestors (starting from within the 'binman' node) separated
470 by a dot ('.'). This can be useful for generating unique filesnames
471 in the output directory.
477 if node.name == 'binman':
479 name = '%s.%s' % (node.name, name)