blob: 648cfd241f1dac53d87459f6cb1f725d1e86848a [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 Glass30732662018-06-01 09:38:20 -06007from __future__ import print_function
8
Simon Glass91710b32018-07-17 13:25:32 -06009from collections import namedtuple
10
Simon Glass2574ef62016-11-25 20:15:51 -070011# 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
14try:
15 import importlib
16 have_importlib = True
17except:
18 have_importlib = False
19
Simon Glass691198c2018-06-01 09:38:15 -060020import os
Simon Glass0c9d5b52018-09-14 04:57:22 -060021from sets import Set
Simon Glass691198c2018-06-01 09:38:15 -060022import sys
Simon Glass29aa7362018-09-14 04:57:19 -060023
24import fdt_util
25import state
Simon Glass2574ef62016-11-25 20:15:51 -070026import tools
27
28modules = {}
29
Simon Glass691198c2018-06-01 09:38:15 -060030our_path = os.path.dirname(os.path.realpath(__file__))
31
Simon Glass91710b32018-07-17 13:25:32 -060032
33# An argument which can be passed to entries on the command line, in lieu of
34# device-tree properties.
35EntryArg = namedtuple('EntryArg', ['name', 'datatype'])
36
37
Simon Glass2574ef62016-11-25 20:15:51 -070038class Entry(object):
Simon Glassad5a7712018-06-01 09:38:14 -060039 """An Entry in the section
Simon Glass2574ef62016-11-25 20:15:51 -070040
41 An entry corresponds to a single node in the device-tree description
Simon Glassad5a7712018-06-01 09:38:14 -060042 of the section. Each entry ends up being a part of the final section.
Simon Glass2574ef62016-11-25 20:15:51 -070043 Entries can be placed either right next to each other, or with padding
44 between them. The type of the entry determines the data that is in it.
45
46 This class is not used by itself. All entry objects are subclasses of
47 Entry.
48
49 Attributes:
Simon Glass3a9a2b82018-07-17 13:25:28 -060050 section: Section object containing this entry
Simon Glass2574ef62016-11-25 20:15:51 -070051 node: The node that created this entry
Simon Glasse8561af2018-08-01 15:22:37 -060052 offset: Offset of entry within the section, None if not known yet (in
53 which case it will be calculated by Pack())
Simon Glass2574ef62016-11-25 20:15:51 -070054 size: Entry size in bytes, None if not known
55 contents_size: Size of contents in bytes, 0 by default
Simon Glasse8561af2018-08-01 15:22:37 -060056 align: Entry start offset alignment, or None
Simon Glass2574ef62016-11-25 20:15:51 -070057 align_size: Entry size alignment, or None
Simon Glasse8561af2018-08-01 15:22:37 -060058 align_end: Entry end offset alignment, or None
Simon Glass2574ef62016-11-25 20:15:51 -070059 pad_before: Number of pad bytes before the contents, 0 if none
60 pad_after: Number of pad bytes after the contents, 0 if none
61 data: Contents of entry (string of bytes)
62 """
Simon Glass3b78d532018-06-01 09:38:21 -060063 def __init__(self, section, etype, node, read_node=True, name_prefix=''):
Simon Glassad5a7712018-06-01 09:38:14 -060064 self.section = section
Simon Glass2574ef62016-11-25 20:15:51 -070065 self.etype = etype
66 self._node = node
Simon Glass3b78d532018-06-01 09:38:21 -060067 self.name = node and (name_prefix + node.name) or 'none'
Simon Glasse8561af2018-08-01 15:22:37 -060068 self.offset = None
Simon Glass2574ef62016-11-25 20:15:51 -070069 self.size = None
Simon Glass5c350162018-07-17 13:25:47 -060070 self.data = None
Simon Glass2574ef62016-11-25 20:15:51 -070071 self.contents_size = 0
72 self.align = None
73 self.align_size = None
74 self.align_end = None
75 self.pad_before = 0
76 self.pad_after = 0
Simon Glasse8561af2018-08-01 15:22:37 -060077 self.offset_unset = False
Simon Glass9dcc8612018-08-01 15:22:42 -060078 self.image_pos = None
Simon Glassfa79a812018-09-14 04:57:29 -060079 self._expand_size = False
Simon Glass2574ef62016-11-25 20:15:51 -070080 if read_node:
81 self.ReadNode()
82
83 @staticmethod
Simon Glass969616c2018-07-17 13:25:36 -060084 def Lookup(section, node_path, etype):
85 """Look up the entry class for a node.
Simon Glass2574ef62016-11-25 20:15:51 -070086
87 Args:
Simon Glass969616c2018-07-17 13:25:36 -060088 section: Section object containing this node
89 node_node: Path name of Node object containing information about
90 the entry to create (used for errors)
91 etype: Entry type to use
Simon Glass2574ef62016-11-25 20:15:51 -070092
93 Returns:
Simon Glass969616c2018-07-17 13:25:36 -060094 The entry class object if found, else None
Simon Glass2574ef62016-11-25 20:15:51 -070095 """
Simon Glasse76a3e62018-06-01 09:38:11 -060096 # Convert something like 'u-boot@0' to 'u_boot' since we are only
97 # interested in the type.
Simon Glass2574ef62016-11-25 20:15:51 -070098 module_name = etype.replace('-', '_')
Simon Glasse76a3e62018-06-01 09:38:11 -060099 if '@' in module_name:
100 module_name = module_name.split('@')[0]
Simon Glass2574ef62016-11-25 20:15:51 -0700101 module = modules.get(module_name)
102
Simon Glass691198c2018-06-01 09:38:15 -0600103 # Also allow entry-type modules to be brought in from the etype directory.
104
Simon Glass2574ef62016-11-25 20:15:51 -0700105 # Import the module if we have not already done so.
106 if not module:
Simon Glass691198c2018-06-01 09:38:15 -0600107 old_path = sys.path
108 sys.path.insert(0, os.path.join(our_path, 'etype'))
Simon Glass2574ef62016-11-25 20:15:51 -0700109 try:
110 if have_importlib:
111 module = importlib.import_module(module_name)
112 else:
113 module = __import__(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 Glass691198c2018-06-01 09:38:15 -0600117 finally:
118 sys.path = old_path
Simon Glass2574ef62016-11-25 20:15:51 -0700119 modules[module_name] = module
120
Simon Glass969616c2018-07-17 13:25:36 -0600121 # Look up the expected class name
122 return getattr(module, 'Entry_%s' % module_name)
123
124 @staticmethod
125 def Create(section, node, etype=None):
126 """Create a new entry for a node.
127
128 Args:
129 section: Section object containing this node
130 node: Node object containing information about the entry to
131 create
132 etype: Entry type to use, or None to work it out (used for tests)
133
134 Returns:
135 A new Entry object of the correct type (a subclass of Entry)
136 """
137 if not etype:
138 etype = fdt_util.GetString(node, 'type', node.name)
139 obj = Entry.Lookup(section, node.path, etype)
140
Simon Glass2574ef62016-11-25 20:15:51 -0700141 # Call its constructor to get the object we want.
Simon Glassad5a7712018-06-01 09:38:14 -0600142 return obj(section, etype, node)
Simon Glass2574ef62016-11-25 20:15:51 -0700143
144 def ReadNode(self):
145 """Read entry information from the node
146
147 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')
153 self.align = fdt_util.GetInt(self._node, 'align')
154 if tools.NotPowerOfTwo(self.align):
155 raise ValueError("Node '%s': Alignment %s must be a power of two" %
156 (self._node.path, self.align))
157 self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
158 self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
159 self.align_size = fdt_util.GetInt(self._node, 'align-size')
160 if tools.NotPowerOfTwo(self.align_size):
161 raise ValueError("Node '%s': Alignment size %s must be a power "
162 "of two" % (self._node.path, self.align_size))
163 self.align_end = fdt_util.GetInt(self._node, 'align-end')
Simon Glasse8561af2018-08-01 15:22:37 -0600164 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
Simon Glassfa79a812018-09-14 04:57:29 -0600165 self.expand_size = fdt_util.GetBool(self._node, 'expand-size')
Simon Glass2574ef62016-11-25 20:15:51 -0700166
Simon Glass3732ec32018-09-14 04:57:18 -0600167 def GetDefaultFilename(self):
168 return None
169
Simon Glass0c9d5b52018-09-14 04:57:22 -0600170 def GetFdtSet(self):
171 """Get the set of device trees used by this entry
172
173 Returns:
174 Set containing the filename from this entry, if it is a .dtb, else
175 an empty set
176 """
177 fname = self.GetDefaultFilename()
178 # It would be better to use isinstance(self, Entry_blob_dtb) here but
179 # we cannot access Entry_blob_dtb
180 if fname and fname.endswith('.dtb'):
181 return Set([fname])
182 return Set()
183
Simon Glassac6328c2018-09-14 04:57:28 -0600184 def ExpandEntries(self):
185 pass
186
Simon Glasse22f8fa2018-07-06 10:27:41 -0600187 def AddMissingProperties(self):
188 """Add new properties to the device tree as needed for this entry"""
Simon Glass9dcc8612018-08-01 15:22:42 -0600189 for prop in ['offset', 'size', 'image-pos']:
Simon Glasse22f8fa2018-07-06 10:27:41 -0600190 if not prop in self._node.props:
Simon Glassc8135dc2018-09-14 04:57:21 -0600191 state.AddZeroProp(self._node, prop)
Simon Glassae7cf032018-09-14 04:57:31 -0600192 err = state.CheckAddHashProp(self._node)
193 if err:
194 self.Raise(err)
Simon Glasse22f8fa2018-07-06 10:27:41 -0600195
196 def SetCalculatedProperties(self):
197 """Set the value of device-tree properties calculated by binman"""
Simon Glassc8135dc2018-09-14 04:57:21 -0600198 state.SetInt(self._node, 'offset', self.offset)
199 state.SetInt(self._node, 'size', self.size)
Simon Glassc64aea52018-09-14 04:57:34 -0600200 state.SetInt(self._node, 'image-pos',
201 self.image_pos - self.section.GetRootSkipAtStart())
Simon Glassae7cf032018-09-14 04:57:31 -0600202 state.CheckSetHashValue(self._node, self.GetData)
Simon Glasse22f8fa2018-07-06 10:27:41 -0600203
Simon Glass92307732018-07-06 10:27:40 -0600204 def ProcessFdt(self, fdt):
Simon Glasse219aa42018-09-14 04:57:24 -0600205 """Allow entries to adjust the device tree
206
207 Some entries need to adjust the device tree for their purposes. This
208 may involve adding or deleting properties.
209
210 Returns:
211 True if processing is complete
212 False if processing could not be completed due to a dependency.
213 This will cause the entry to be retried after others have been
214 called
215 """
Simon Glass92307732018-07-06 10:27:40 -0600216 return True
217
Simon Glass3b78d532018-06-01 09:38:21 -0600218 def SetPrefix(self, prefix):
219 """Set the name prefix for a node
220
221 Args:
222 prefix: Prefix to set, or '' to not use a prefix
223 """
224 if prefix:
225 self.name = prefix + self.name
226
Simon Glass2e1169f2018-07-06 10:27:19 -0600227 def SetContents(self, data):
228 """Set the contents of an entry
229
230 This sets both the data and content_size properties
231
232 Args:
233 data: Data to set to the contents (string)
234 """
235 self.data = data
236 self.contents_size = len(self.data)
237
238 def ProcessContentsUpdate(self, data):
239 """Update the contens of an entry, after the size is fixed
240
241 This checks that the new data is the same size as the old.
242
243 Args:
244 data: Data to set to the contents (string)
245
246 Raises:
247 ValueError if the new data size is not the same as the old
248 """
249 if len(data) != self.contents_size:
250 self.Raise('Cannot update entry size from %d to %d' %
251 (len(data), self.contents_size))
252 self.SetContents(data)
253
Simon Glass2574ef62016-11-25 20:15:51 -0700254 def ObtainContents(self):
255 """Figure out the contents of an entry.
256
257 Returns:
258 True if the contents were found, False if another call is needed
259 after the other entries are processed.
260 """
261 # No contents by default: subclasses can implement this
262 return True
263
Simon Glasse8561af2018-08-01 15:22:37 -0600264 def Pack(self, offset):
Simon Glassad5a7712018-06-01 09:38:14 -0600265 """Figure out how to pack the entry into the section
Simon Glass2574ef62016-11-25 20:15:51 -0700266
267 Most of the time the entries are not fully specified. There may be
268 an alignment but no size. In that case we take the size from the
269 contents of the entry.
270
Simon Glasse8561af2018-08-01 15:22:37 -0600271 If an entry has no hard-coded offset, it will be placed at @offset.
Simon Glass2574ef62016-11-25 20:15:51 -0700272
Simon Glasse8561af2018-08-01 15:22:37 -0600273 Once this function is complete, both the offset and size of the
Simon Glass2574ef62016-11-25 20:15:51 -0700274 entry will be know.
275
276 Args:
Simon Glasse8561af2018-08-01 15:22:37 -0600277 Current section offset pointer
Simon Glass2574ef62016-11-25 20:15:51 -0700278
279 Returns:
Simon Glasse8561af2018-08-01 15:22:37 -0600280 New section offset pointer (after this entry)
Simon Glass2574ef62016-11-25 20:15:51 -0700281 """
Simon Glasse8561af2018-08-01 15:22:37 -0600282 if self.offset is None:
283 if self.offset_unset:
284 self.Raise('No offset set with offset-unset: should another '
285 'entry provide this correct offset?')
286 self.offset = tools.Align(offset, self.align)
Simon Glass2574ef62016-11-25 20:15:51 -0700287 needed = self.pad_before + self.contents_size + self.pad_after
288 needed = tools.Align(needed, self.align_size)
289 size = self.size
290 if not size:
291 size = needed
Simon Glasse8561af2018-08-01 15:22:37 -0600292 new_offset = self.offset + size
293 aligned_offset = tools.Align(new_offset, self.align_end)
294 if aligned_offset != new_offset:
295 size = aligned_offset - self.offset
296 new_offset = aligned_offset
Simon Glass2574ef62016-11-25 20:15:51 -0700297
298 if not self.size:
299 self.size = size
300
301 if self.size < needed:
302 self.Raise("Entry contents size is %#x (%d) but entry size is "
303 "%#x (%d)" % (needed, needed, self.size, self.size))
304 # Check that the alignment is correct. It could be wrong if the
Simon Glasse8561af2018-08-01 15:22:37 -0600305 # and offset or size values were provided (i.e. not calculated), but
Simon Glass2574ef62016-11-25 20:15:51 -0700306 # conflict with the provided alignment values
307 if self.size != tools.Align(self.size, self.align_size):
308 self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
309 (self.size, self.size, self.align_size, self.align_size))
Simon Glasse8561af2018-08-01 15:22:37 -0600310 if self.offset != tools.Align(self.offset, self.align):
311 self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
312 (self.offset, self.offset, self.align, self.align))
Simon Glass2574ef62016-11-25 20:15:51 -0700313
Simon Glasse8561af2018-08-01 15:22:37 -0600314 return new_offset
Simon Glass2574ef62016-11-25 20:15:51 -0700315
316 def Raise(self, msg):
317 """Convenience function to raise an error referencing a node"""
318 raise ValueError("Node '%s': %s" % (self._node.path, msg))
319
Simon Glass91710b32018-07-17 13:25:32 -0600320 def GetEntryArgsOrProps(self, props, required=False):
321 """Return the values of a set of properties
322
323 Args:
324 props: List of EntryArg objects
325
326 Raises:
327 ValueError if a property is not found
328 """
329 values = []
330 missing = []
331 for prop in props:
332 python_prop = prop.name.replace('-', '_')
333 if hasattr(self, python_prop):
334 value = getattr(self, python_prop)
335 else:
336 value = None
337 if value is None:
338 value = self.GetArg(prop.name, prop.datatype)
339 if value is None and required:
340 missing.append(prop.name)
341 values.append(value)
342 if missing:
343 self.Raise('Missing required properties/entry args: %s' %
344 (', '.join(missing)))
345 return values
346
Simon Glass2574ef62016-11-25 20:15:51 -0700347 def GetPath(self):
348 """Get the path of a node
349
350 Returns:
351 Full path of the node for this entry
352 """
353 return self._node.path
354
355 def GetData(self):
356 return self.data
357
Simon Glasse8561af2018-08-01 15:22:37 -0600358 def GetOffsets(self):
Simon Glass2574ef62016-11-25 20:15:51 -0700359 return {}
360
Simon Glasse8561af2018-08-01 15:22:37 -0600361 def SetOffsetSize(self, pos, size):
362 self.offset = pos
Simon Glass2574ef62016-11-25 20:15:51 -0700363 self.size = size
364
Simon Glass9dcc8612018-08-01 15:22:42 -0600365 def SetImagePos(self, image_pos):
366 """Set the position in the image
367
368 Args:
369 image_pos: Position of this entry in the image
370 """
371 self.image_pos = image_pos + self.offset
372
Simon Glass2574ef62016-11-25 20:15:51 -0700373 def ProcessContents(self):
374 pass
Simon Glass4ca8e042017-11-13 18:55:01 -0700375
Simon Glass8a6f56e2018-06-01 09:38:13 -0600376 def WriteSymbols(self, section):
Simon Glass4ca8e042017-11-13 18:55:01 -0700377 """Write symbol values into binary files for access at run time
378
379 Args:
Simon Glass8a6f56e2018-06-01 09:38:13 -0600380 section: Section containing the entry
Simon Glass4ca8e042017-11-13 18:55:01 -0700381 """
382 pass
Simon Glassa91e1152018-06-01 09:38:16 -0600383
Simon Glasse8561af2018-08-01 15:22:37 -0600384 def CheckOffset(self):
385 """Check that the entry offsets are correct
Simon Glassa91e1152018-06-01 09:38:16 -0600386
Simon Glasse8561af2018-08-01 15:22:37 -0600387 This is used for entries which have extra offset requirements (other
Simon Glassa91e1152018-06-01 09:38:16 -0600388 than having to be fully inside their section). Sub-classes can implement
389 this function and raise if there is a problem.
390 """
391 pass
Simon Glass30732662018-06-01 09:38:20 -0600392
Simon Glass3a9a2b82018-07-17 13:25:28 -0600393 @staticmethod
Simon Glasscd817d52018-09-14 04:57:36 -0600394 def GetStr(value):
395 if value is None:
396 return '<none> '
397 return '%08x' % value
398
399 @staticmethod
Simon Glass7eca7922018-07-17 13:25:49 -0600400 def WriteMapLine(fd, indent, name, offset, size, image_pos):
Simon Glasscd817d52018-09-14 04:57:36 -0600401 print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
402 Entry.GetStr(offset), Entry.GetStr(size),
403 name), file=fd)
Simon Glass3a9a2b82018-07-17 13:25:28 -0600404
Simon Glass30732662018-06-01 09:38:20 -0600405 def WriteMap(self, fd, indent):
406 """Write a map of the entry to a .map file
407
408 Args:
409 fd: File to write the map to
410 indent: Curent indent level of map (0=none, 1=one level, etc.)
411 """
Simon Glass7eca7922018-07-17 13:25:49 -0600412 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
413 self.image_pos)
Simon Glass91710b32018-07-17 13:25:32 -0600414
Simon Glass704784b2018-07-17 13:25:38 -0600415 def GetEntries(self):
416 """Return a list of entries contained by this entry
417
418 Returns:
419 List of entries, or None if none. A normal entry has no entries
420 within it so will return None
421 """
422 return None
423
Simon Glass91710b32018-07-17 13:25:32 -0600424 def GetArg(self, name, datatype=str):
425 """Get the value of an entry argument or device-tree-node property
426
427 Some node properties can be provided as arguments to binman. First check
428 the entry arguments, and fall back to the device tree if not found
429
430 Args:
431 name: Argument name
432 datatype: Data type (str or int)
433
434 Returns:
435 Value of argument as a string or int, or None if no value
436
437 Raises:
438 ValueError if the argument cannot be converted to in
439 """
Simon Glass29aa7362018-09-14 04:57:19 -0600440 value = state.GetEntryArg(name)
Simon Glass91710b32018-07-17 13:25:32 -0600441 if value is not None:
442 if datatype == int:
443 try:
444 value = int(value)
445 except ValueError:
446 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
447 (name, value))
448 elif datatype == str:
449 pass
450 else:
451 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
452 datatype)
453 else:
454 value = fdt_util.GetDatatype(self._node, name, datatype)
455 return value
Simon Glass969616c2018-07-17 13:25:36 -0600456
457 @staticmethod
458 def WriteDocs(modules, test_missing=None):
459 """Write out documentation about the various entry types to stdout
460
461 Args:
462 modules: List of modules to include
463 test_missing: Used for testing. This is a module to report
464 as missing
465 """
466 print('''Binman Entry Documentation
467===========================
468
469This file describes the entry types supported by binman. These entry types can
470be placed in an image one by one to build up a final firmware image. It is
471fairly easy to create new entry types. Just add a new file to the 'etype'
472directory. You can use the existing entries as examples.
473
474Note that some entries are subclasses of others, using and extending their
475features to produce new behaviours.
476
477
478''')
479 modules = sorted(modules)
480
481 # Don't show the test entry
482 if '_testing' in modules:
483 modules.remove('_testing')
484 missing = []
485 for name in modules:
486 module = Entry.Lookup(name, name, name)
487 docs = getattr(module, '__doc__')
488 if test_missing == name:
489 docs = None
490 if docs:
491 lines = docs.splitlines()
492 first_line = lines[0]
493 rest = [line[4:] for line in lines[1:]]
494 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
495 print(hdr)
496 print('-' * len(hdr))
497 print('\n'.join(rest))
498 print()
499 print()
500 else:
501 missing.append(name)
502
503 if missing:
504 raise ValueError('Documentation is missing for modules: %s' %
505 ', '.join(missing))
Simon Glass639505b2018-09-14 04:57:11 -0600506
507 def GetUniqueName(self):
508 """Get a unique name for a node
509
510 Returns:
511 String containing a unique name for a node, consisting of the name
512 of all ancestors (starting from within the 'binman' node) separated
513 by a dot ('.'). This can be useful for generating unique filesnames
514 in the output directory.
515 """
516 name = self.name
517 node = self._node
518 while node.parent:
519 node = node.parent
520 if node.name == 'binman':
521 break
522 name = '%s.%s' % (node.name, name)
523 return name
Simon Glassfa79a812018-09-14 04:57:29 -0600524
525 def ExpandToLimit(self, limit):
526 """Expand an entry so that it ends at the given offset limit"""
527 if self.offset + self.size < limit:
528 self.size = limit - self.offset
529 # Request the contents again, since changing the size requires that
530 # the data grows. This should not fail, but check it to be sure.
531 if not self.ObtainContents():
532 self.Raise('Cannot obtain contents when expanding entry')