blob: 7316ad43b5e8cdab57166d1830da63436add1e2c [file] [log] [blame]
Tom Rini83d290c2018-05-06 17:58:06 -04001# SPDX-License-Identifier: GPL-2.0+
Simon Glassbf7fd502016-11-25 20:15:51 -07002# Copyright (c) 2016 Google, Inc
3#
Simon Glassbf7fd502016-11-25 20:15:51 -07004# Base class for all entries
5#
6
Simon Glass3b0c3822018-06-01 09:38:20 -06007from __future__ import print_function
8
Simon Glass53af22a2018-07-17 13:25:32 -06009from collections import namedtuple
10
Simon Glassbf7fd502016-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 Glassbadf0ec2018-06-01 09:38:15 -060020import os
Simon Glass539aece2018-09-14 04:57:22 -060021from sets import Set
Simon Glassbadf0ec2018-06-01 09:38:15 -060022import sys
Simon Glassc55a50f2018-09-14 04:57:19 -060023
24import fdt_util
25import state
Simon Glassbf7fd502016-11-25 20:15:51 -070026import tools
27
28modules = {}
29
Simon Glassbadf0ec2018-06-01 09:38:15 -060030our_path = os.path.dirname(os.path.realpath(__file__))
31
Simon Glass53af22a2018-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 Glassbf7fd502016-11-25 20:15:51 -070038class Entry(object):
Simon Glass25ac0e62018-06-01 09:38:14 -060039 """An Entry in the section
Simon Glassbf7fd502016-11-25 20:15:51 -070040
41 An entry corresponds to a single node in the device-tree description
Simon Glass25ac0e62018-06-01 09:38:14 -060042 of the section. Each entry ends up being a part of the final section.
Simon Glassbf7fd502016-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 Glass8122f392018-07-17 13:25:28 -060050 section: Section object containing this entry
Simon Glassbf7fd502016-11-25 20:15:51 -070051 node: The node that created this entry
Simon Glass3ab95982018-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 Glassbf7fd502016-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 Glass3ab95982018-08-01 15:22:37 -060056 align: Entry start offset alignment, or None
Simon Glassbf7fd502016-11-25 20:15:51 -070057 align_size: Entry size alignment, or None
Simon Glass3ab95982018-08-01 15:22:37 -060058 align_end: Entry end offset alignment, or None
Simon Glassbf7fd502016-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 Glassc8d48ef2018-06-01 09:38:21 -060063 def __init__(self, section, etype, node, read_node=True, name_prefix=''):
Simon Glass25ac0e62018-06-01 09:38:14 -060064 self.section = section
Simon Glassbf7fd502016-11-25 20:15:51 -070065 self.etype = etype
66 self._node = node
Simon Glassc8d48ef2018-06-01 09:38:21 -060067 self.name = node and (name_prefix + node.name) or 'none'
Simon Glass3ab95982018-08-01 15:22:37 -060068 self.offset = None
Simon Glassbf7fd502016-11-25 20:15:51 -070069 self.size = None
Simon Glass24d0d3c2018-07-17 13:25:47 -060070 self.data = None
Simon Glassbf7fd502016-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 Glass3ab95982018-08-01 15:22:37 -060077 self.offset_unset = False
Simon Glassdbf6be92018-08-01 15:22:42 -060078 self.image_pos = None
Simon Glassbf7fd502016-11-25 20:15:51 -070079 if read_node:
80 self.ReadNode()
81
82 @staticmethod
Simon Glassfd8d1f72018-07-17 13:25:36 -060083 def Lookup(section, node_path, etype):
84 """Look up the entry class for a node.
Simon Glassbf7fd502016-11-25 20:15:51 -070085
86 Args:
Simon Glassfd8d1f72018-07-17 13:25:36 -060087 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
Simon Glassbf7fd502016-11-25 20:15:51 -070091
92 Returns:
Simon Glassfd8d1f72018-07-17 13:25:36 -060093 The entry class object if found, else None
Simon Glassbf7fd502016-11-25 20:15:51 -070094 """
Simon Glassdd57c132018-06-01 09:38:11 -060095 # Convert something like 'u-boot@0' to 'u_boot' since we are only
96 # interested in the type.
Simon Glassbf7fd502016-11-25 20:15:51 -070097 module_name = etype.replace('-', '_')
Simon Glassdd57c132018-06-01 09:38:11 -060098 if '@' in module_name:
99 module_name = module_name.split('@')[0]
Simon Glassbf7fd502016-11-25 20:15:51 -0700100 module = modules.get(module_name)
101
Simon Glassbadf0ec2018-06-01 09:38:15 -0600102 # Also allow entry-type modules to be brought in from the etype directory.
103
Simon Glassbf7fd502016-11-25 20:15:51 -0700104 # Import the module if we have not already done so.
105 if not module:
Simon Glassbadf0ec2018-06-01 09:38:15 -0600106 old_path = sys.path
107 sys.path.insert(0, os.path.join(our_path, 'etype'))
Simon Glassbf7fd502016-11-25 20:15:51 -0700108 try:
109 if have_importlib:
110 module = importlib.import_module(module_name)
111 else:
112 module = __import__(module_name)
Simon Glassfd8d1f72018-07-17 13:25:36 -0600113 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))
Simon Glassbadf0ec2018-06-01 09:38:15 -0600116 finally:
117 sys.path = old_path
Simon Glassbf7fd502016-11-25 20:15:51 -0700118 modules[module_name] = module
119
Simon Glassfd8d1f72018-07-17 13:25:36 -0600120 # Look up the expected class name
121 return getattr(module, 'Entry_%s' % module_name)
122
123 @staticmethod
124 def Create(section, node, etype=None):
125 """Create a new entry for a node.
126
127 Args:
128 section: Section object containing this node
129 node: Node object containing information about the entry to
130 create
131 etype: Entry type to use, or None to work it out (used for tests)
132
133 Returns:
134 A new Entry object of the correct type (a subclass of Entry)
135 """
136 if not etype:
137 etype = fdt_util.GetString(node, 'type', node.name)
138 obj = Entry.Lookup(section, node.path, etype)
139
Simon Glassbf7fd502016-11-25 20:15:51 -0700140 # Call its constructor to get the object we want.
Simon Glass25ac0e62018-06-01 09:38:14 -0600141 return obj(section, etype, node)
Simon Glassbf7fd502016-11-25 20:15:51 -0700142
143 def ReadNode(self):
144 """Read entry information from the node
145
146 This reads all the fields we recognise from the node, ready for use.
147 """
Simon Glass15a587c2018-07-17 13:25:51 -0600148 if 'pos' in self._node.props:
149 self.Raise("Please use 'offset' instead of 'pos'")
Simon Glass3ab95982018-08-01 15:22:37 -0600150 self.offset = fdt_util.GetInt(self._node, 'offset')
Simon Glassbf7fd502016-11-25 20:15:51 -0700151 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')
Simon Glass3ab95982018-08-01 15:22:37 -0600163 self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
Simon Glassbf7fd502016-11-25 20:15:51 -0700164
Simon Glass6c234bf2018-09-14 04:57:18 -0600165 def GetDefaultFilename(self):
166 return None
167
Simon Glass539aece2018-09-14 04:57:22 -0600168 def GetFdtSet(self):
169 """Get the set of device trees used by this entry
170
171 Returns:
172 Set containing the filename from this entry, if it is a .dtb, else
173 an empty set
174 """
175 fname = self.GetDefaultFilename()
176 # It would be better to use isinstance(self, Entry_blob_dtb) here but
177 # we cannot access Entry_blob_dtb
178 if fname and fname.endswith('.dtb'):
179 return Set([fname])
180 return Set()
181
Simon Glass0a98b282018-09-14 04:57:28 -0600182 def ExpandEntries(self):
183 pass
184
Simon Glass078ab1a2018-07-06 10:27:41 -0600185 def AddMissingProperties(self):
186 """Add new properties to the device tree as needed for this entry"""
Simon Glassdbf6be92018-08-01 15:22:42 -0600187 for prop in ['offset', 'size', 'image-pos']:
Simon Glass078ab1a2018-07-06 10:27:41 -0600188 if not prop in self._node.props:
Simon Glassf46621d2018-09-14 04:57:21 -0600189 state.AddZeroProp(self._node, prop)
Simon Glass078ab1a2018-07-06 10:27:41 -0600190
191 def SetCalculatedProperties(self):
192 """Set the value of device-tree properties calculated by binman"""
Simon Glassf46621d2018-09-14 04:57:21 -0600193 state.SetInt(self._node, 'offset', self.offset)
194 state.SetInt(self._node, 'size', self.size)
195 state.SetInt(self._node, 'image-pos', self.image_pos)
Simon Glass078ab1a2018-07-06 10:27:41 -0600196
Simon Glassecab8972018-07-06 10:27:40 -0600197 def ProcessFdt(self, fdt):
Simon Glass6ed45ba2018-09-14 04:57:24 -0600198 """Allow entries to adjust the device tree
199
200 Some entries need to adjust the device tree for their purposes. This
201 may involve adding or deleting properties.
202
203 Returns:
204 True if processing is complete
205 False if processing could not be completed due to a dependency.
206 This will cause the entry to be retried after others have been
207 called
208 """
Simon Glassecab8972018-07-06 10:27:40 -0600209 return True
210
Simon Glassc8d48ef2018-06-01 09:38:21 -0600211 def SetPrefix(self, prefix):
212 """Set the name prefix for a node
213
214 Args:
215 prefix: Prefix to set, or '' to not use a prefix
216 """
217 if prefix:
218 self.name = prefix + self.name
219
Simon Glass5c890232018-07-06 10:27:19 -0600220 def SetContents(self, data):
221 """Set the contents of an entry
222
223 This sets both the data and content_size properties
224
225 Args:
226 data: Data to set to the contents (string)
227 """
228 self.data = data
229 self.contents_size = len(self.data)
230
231 def ProcessContentsUpdate(self, data):
232 """Update the contens of an entry, after the size is fixed
233
234 This checks that the new data is the same size as the old.
235
236 Args:
237 data: Data to set to the contents (string)
238
239 Raises:
240 ValueError if the new data size is not the same as the old
241 """
242 if len(data) != self.contents_size:
243 self.Raise('Cannot update entry size from %d to %d' %
244 (len(data), self.contents_size))
245 self.SetContents(data)
246
Simon Glassbf7fd502016-11-25 20:15:51 -0700247 def ObtainContents(self):
248 """Figure out the contents of an entry.
249
250 Returns:
251 True if the contents were found, False if another call is needed
252 after the other entries are processed.
253 """
254 # No contents by default: subclasses can implement this
255 return True
256
Simon Glass3ab95982018-08-01 15:22:37 -0600257 def Pack(self, offset):
Simon Glass25ac0e62018-06-01 09:38:14 -0600258 """Figure out how to pack the entry into the section
Simon Glassbf7fd502016-11-25 20:15:51 -0700259
260 Most of the time the entries are not fully specified. There may be
261 an alignment but no size. In that case we take the size from the
262 contents of the entry.
263
Simon Glass3ab95982018-08-01 15:22:37 -0600264 If an entry has no hard-coded offset, it will be placed at @offset.
Simon Glassbf7fd502016-11-25 20:15:51 -0700265
Simon Glass3ab95982018-08-01 15:22:37 -0600266 Once this function is complete, both the offset and size of the
Simon Glassbf7fd502016-11-25 20:15:51 -0700267 entry will be know.
268
269 Args:
Simon Glass3ab95982018-08-01 15:22:37 -0600270 Current section offset pointer
Simon Glassbf7fd502016-11-25 20:15:51 -0700271
272 Returns:
Simon Glass3ab95982018-08-01 15:22:37 -0600273 New section offset pointer (after this entry)
Simon Glassbf7fd502016-11-25 20:15:51 -0700274 """
Simon Glass3ab95982018-08-01 15:22:37 -0600275 if self.offset is None:
276 if self.offset_unset:
277 self.Raise('No offset set with offset-unset: should another '
278 'entry provide this correct offset?')
279 self.offset = tools.Align(offset, self.align)
Simon Glassbf7fd502016-11-25 20:15:51 -0700280 needed = self.pad_before + self.contents_size + self.pad_after
281 needed = tools.Align(needed, self.align_size)
282 size = self.size
283 if not size:
284 size = needed
Simon Glass3ab95982018-08-01 15:22:37 -0600285 new_offset = self.offset + size
286 aligned_offset = tools.Align(new_offset, self.align_end)
287 if aligned_offset != new_offset:
288 size = aligned_offset - self.offset
289 new_offset = aligned_offset
Simon Glassbf7fd502016-11-25 20:15:51 -0700290
291 if not self.size:
292 self.size = size
293
294 if self.size < needed:
295 self.Raise("Entry contents size is %#x (%d) but entry size is "
296 "%#x (%d)" % (needed, needed, self.size, self.size))
297 # Check that the alignment is correct. It could be wrong if the
Simon Glass3ab95982018-08-01 15:22:37 -0600298 # and offset or size values were provided (i.e. not calculated), but
Simon Glassbf7fd502016-11-25 20:15:51 -0700299 # conflict with the provided alignment values
300 if self.size != tools.Align(self.size, self.align_size):
301 self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
302 (self.size, self.size, self.align_size, self.align_size))
Simon Glass3ab95982018-08-01 15:22:37 -0600303 if self.offset != tools.Align(self.offset, self.align):
304 self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
305 (self.offset, self.offset, self.align, self.align))
Simon Glassbf7fd502016-11-25 20:15:51 -0700306
Simon Glass3ab95982018-08-01 15:22:37 -0600307 return new_offset
Simon Glassbf7fd502016-11-25 20:15:51 -0700308
309 def Raise(self, msg):
310 """Convenience function to raise an error referencing a node"""
311 raise ValueError("Node '%s': %s" % (self._node.path, msg))
312
Simon Glass53af22a2018-07-17 13:25:32 -0600313 def GetEntryArgsOrProps(self, props, required=False):
314 """Return the values of a set of properties
315
316 Args:
317 props: List of EntryArg objects
318
319 Raises:
320 ValueError if a property is not found
321 """
322 values = []
323 missing = []
324 for prop in props:
325 python_prop = prop.name.replace('-', '_')
326 if hasattr(self, python_prop):
327 value = getattr(self, python_prop)
328 else:
329 value = None
330 if value is None:
331 value = self.GetArg(prop.name, prop.datatype)
332 if value is None and required:
333 missing.append(prop.name)
334 values.append(value)
335 if missing:
336 self.Raise('Missing required properties/entry args: %s' %
337 (', '.join(missing)))
338 return values
339
Simon Glassbf7fd502016-11-25 20:15:51 -0700340 def GetPath(self):
341 """Get the path of a node
342
343 Returns:
344 Full path of the node for this entry
345 """
346 return self._node.path
347
348 def GetData(self):
349 return self.data
350
Simon Glass3ab95982018-08-01 15:22:37 -0600351 def GetOffsets(self):
Simon Glassbf7fd502016-11-25 20:15:51 -0700352 return {}
353
Simon Glass3ab95982018-08-01 15:22:37 -0600354 def SetOffsetSize(self, pos, size):
355 self.offset = pos
Simon Glassbf7fd502016-11-25 20:15:51 -0700356 self.size = size
357
Simon Glassdbf6be92018-08-01 15:22:42 -0600358 def SetImagePos(self, image_pos):
359 """Set the position in the image
360
361 Args:
362 image_pos: Position of this entry in the image
363 """
364 self.image_pos = image_pos + self.offset
365
Simon Glassbf7fd502016-11-25 20:15:51 -0700366 def ProcessContents(self):
367 pass
Simon Glass19790632017-11-13 18:55:01 -0700368
Simon Glassf55382b2018-06-01 09:38:13 -0600369 def WriteSymbols(self, section):
Simon Glass19790632017-11-13 18:55:01 -0700370 """Write symbol values into binary files for access at run time
371
372 Args:
Simon Glassf55382b2018-06-01 09:38:13 -0600373 section: Section containing the entry
Simon Glass19790632017-11-13 18:55:01 -0700374 """
375 pass
Simon Glass18546952018-06-01 09:38:16 -0600376
Simon Glass3ab95982018-08-01 15:22:37 -0600377 def CheckOffset(self):
378 """Check that the entry offsets are correct
Simon Glass18546952018-06-01 09:38:16 -0600379
Simon Glass3ab95982018-08-01 15:22:37 -0600380 This is used for entries which have extra offset requirements (other
Simon Glass18546952018-06-01 09:38:16 -0600381 than having to be fully inside their section). Sub-classes can implement
382 this function and raise if there is a problem.
383 """
384 pass
Simon Glass3b0c3822018-06-01 09:38:20 -0600385
Simon Glass8122f392018-07-17 13:25:28 -0600386 @staticmethod
Simon Glass1be70d22018-07-17 13:25:49 -0600387 def WriteMapLine(fd, indent, name, offset, size, image_pos):
388 print('%08x %s%08x %08x %s' % (image_pos, ' ' * indent, offset,
389 size, name), file=fd)
Simon Glass8122f392018-07-17 13:25:28 -0600390
Simon Glass3b0c3822018-06-01 09:38:20 -0600391 def WriteMap(self, fd, indent):
392 """Write a map of the entry to a .map file
393
394 Args:
395 fd: File to write the map to
396 indent: Curent indent level of map (0=none, 1=one level, etc.)
397 """
Simon Glass1be70d22018-07-17 13:25:49 -0600398 self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
399 self.image_pos)
Simon Glass53af22a2018-07-17 13:25:32 -0600400
Simon Glass11e36cc2018-07-17 13:25:38 -0600401 def GetEntries(self):
402 """Return a list of entries contained by this entry
403
404 Returns:
405 List of entries, or None if none. A normal entry has no entries
406 within it so will return None
407 """
408 return None
409
Simon Glass53af22a2018-07-17 13:25:32 -0600410 def GetArg(self, name, datatype=str):
411 """Get the value of an entry argument or device-tree-node property
412
413 Some node properties can be provided as arguments to binman. First check
414 the entry arguments, and fall back to the device tree if not found
415
416 Args:
417 name: Argument name
418 datatype: Data type (str or int)
419
420 Returns:
421 Value of argument as a string or int, or None if no value
422
423 Raises:
424 ValueError if the argument cannot be converted to in
425 """
Simon Glassc55a50f2018-09-14 04:57:19 -0600426 value = state.GetEntryArg(name)
Simon Glass53af22a2018-07-17 13:25:32 -0600427 if value is not None:
428 if datatype == int:
429 try:
430 value = int(value)
431 except ValueError:
432 self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
433 (name, value))
434 elif datatype == str:
435 pass
436 else:
437 raise ValueError("GetArg() internal error: Unknown data type '%s'" %
438 datatype)
439 else:
440 value = fdt_util.GetDatatype(self._node, name, datatype)
441 return value
Simon Glassfd8d1f72018-07-17 13:25:36 -0600442
443 @staticmethod
444 def WriteDocs(modules, test_missing=None):
445 """Write out documentation about the various entry types to stdout
446
447 Args:
448 modules: List of modules to include
449 test_missing: Used for testing. This is a module to report
450 as missing
451 """
452 print('''Binman Entry Documentation
453===========================
454
455This file describes the entry types supported by binman. These entry types can
456be placed in an image one by one to build up a final firmware image. It is
457fairly easy to create new entry types. Just add a new file to the 'etype'
458directory. You can use the existing entries as examples.
459
460Note that some entries are subclasses of others, using and extending their
461features to produce new behaviours.
462
463
464''')
465 modules = sorted(modules)
466
467 # Don't show the test entry
468 if '_testing' in modules:
469 modules.remove('_testing')
470 missing = []
471 for name in modules:
472 module = Entry.Lookup(name, name, name)
473 docs = getattr(module, '__doc__')
474 if test_missing == name:
475 docs = None
476 if docs:
477 lines = docs.splitlines()
478 first_line = lines[0]
479 rest = [line[4:] for line in lines[1:]]
480 hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
481 print(hdr)
482 print('-' * len(hdr))
483 print('\n'.join(rest))
484 print()
485 print()
486 else:
487 missing.append(name)
488
489 if missing:
490 raise ValueError('Documentation is missing for modules: %s' %
491 ', '.join(missing))
Simon Glassa326b492018-09-14 04:57:11 -0600492
493 def GetUniqueName(self):
494 """Get a unique name for a node
495
496 Returns:
497 String containing a unique name for a node, consisting of the name
498 of all ancestors (starting from within the 'binman' node) separated
499 by a dot ('.'). This can be useful for generating unique filesnames
500 in the output directory.
501 """
502 name = self.name
503 node = self._node
504 while node.parent:
505 node = node.parent
506 if node.name == 'binman':
507 break
508 name = '%s.%s' % (node.name, name)
509 return name