entry.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2016 Google, Inc
  3. #
  4. # Base class for all entries
  5. #
  6. from __future__ import print_function
  7. from collections import namedtuple
  8. # importlib was introduced in Python 2.7 but there was a report of it not
  9. # working in 2.7.12, so we work around this:
  10. # http://lists.denx.de/pipermail/u-boot/2016-October/269729.html
  11. try:
  12. import importlib
  13. have_importlib = True
  14. except:
  15. have_importlib = False
  16. import os
  17. from sets import Set
  18. import sys
  19. import fdt_util
  20. import state
  21. import tools
  22. modules = {}
  23. our_path = os.path.dirname(os.path.realpath(__file__))
  24. # An argument which can be passed to entries on the command line, in lieu of
  25. # device-tree properties.
  26. EntryArg = namedtuple('EntryArg', ['name', 'datatype'])
  27. class Entry(object):
  28. """An Entry in the section
  29. An entry corresponds to a single node in the device-tree description
  30. of the section. Each entry ends up being a part of the final section.
  31. Entries can be placed either right next to each other, or with padding
  32. between them. The type of the entry determines the data that is in it.
  33. This class is not used by itself. All entry objects are subclasses of
  34. Entry.
  35. Attributes:
  36. section: Section object containing this entry
  37. node: The node that created this entry
  38. offset: Offset of entry within the section, None if not known yet (in
  39. which case it will be calculated by Pack())
  40. size: Entry size in bytes, None if not known
  41. contents_size: Size of contents in bytes, 0 by default
  42. align: Entry start offset alignment, or None
  43. align_size: Entry size alignment, or None
  44. align_end: Entry end offset alignment, or None
  45. pad_before: Number of pad bytes before the contents, 0 if none
  46. pad_after: Number of pad bytes after the contents, 0 if none
  47. data: Contents of entry (string of bytes)
  48. """
  49. def __init__(self, section, etype, node, read_node=True, name_prefix=''):
  50. self.section = section
  51. self.etype = etype
  52. self._node = node
  53. self.name = node and (name_prefix + node.name) or 'none'
  54. self.offset = None
  55. self.size = None
  56. self.data = None
  57. self.contents_size = 0
  58. self.align = None
  59. self.align_size = None
  60. self.align_end = None
  61. self.pad_before = 0
  62. self.pad_after = 0
  63. self.offset_unset = False
  64. self.image_pos = None
  65. self._expand_size = False
  66. if read_node:
  67. self.ReadNode()
  68. @staticmethod
  69. def Lookup(section, node_path, etype):
  70. """Look up the entry class for a node.
  71. Args:
  72. section: Section object containing this node
  73. node_node: Path name of Node object containing information about
  74. the entry to create (used for errors)
  75. etype: Entry type to use
  76. Returns:
  77. The entry class object if found, else None
  78. """
  79. # Convert something like 'u-boot@0' to 'u_boot' since we are only
  80. # interested in the type.
  81. module_name = etype.replace('-', '_')
  82. if '@' in module_name:
  83. module_name = module_name.split('@')[0]
  84. module = modules.get(module_name)
  85. # Also allow entry-type modules to be brought in from the etype directory.
  86. # Import the module if we have not already done so.
  87. if not module:
  88. old_path = sys.path
  89. sys.path.insert(0, os.path.join(our_path, 'etype'))
  90. try:
  91. if have_importlib:
  92. module = importlib.import_module(module_name)
  93. else:
  94. module = __import__(module_name)
  95. except ImportError as e:
  96. raise ValueError("Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
  97. (etype, node_path, module_name, e))
  98. finally:
  99. sys.path = old_path
  100. modules[module_name] = module
  101. # Look up the expected class name
  102. return getattr(module, 'Entry_%s' % module_name)
  103. @staticmethod
  104. def Create(section, node, etype=None):
  105. """Create a new entry for a node.
  106. Args:
  107. section: Section object containing this node
  108. node: Node object containing information about the entry to
  109. create
  110. etype: Entry type to use, or None to work it out (used for tests)
  111. Returns:
  112. A new Entry object of the correct type (a subclass of Entry)
  113. """
  114. if not etype:
  115. etype = fdt_util.GetString(node, 'type', node.name)
  116. obj = Entry.Lookup(section, node.path, etype)
  117. # Call its constructor to get the object we want.
  118. return obj(section, etype, node)
  119. def ReadNode(self):
  120. """Read entry information from the node
  121. This reads all the fields we recognise from the node, ready for use.
  122. """
  123. if 'pos' in self._node.props:
  124. self.Raise("Please use 'offset' instead of 'pos'")
  125. self.offset = fdt_util.GetInt(self._node, 'offset')
  126. self.size = fdt_util.GetInt(self._node, 'size')
  127. self.align = fdt_util.GetInt(self._node, 'align')
  128. if tools.NotPowerOfTwo(self.align):
  129. raise ValueError("Node '%s': Alignment %s must be a power of two" %
  130. (self._node.path, self.align))
  131. self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
  132. self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
  133. self.align_size = fdt_util.GetInt(self._node, 'align-size')
  134. if tools.NotPowerOfTwo(self.align_size):
  135. raise ValueError("Node '%s': Alignment size %s must be a power "
  136. "of two" % (self._node.path, self.align_size))
  137. self.align_end = fdt_util.GetInt(self._node, 'align-end')
  138. self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
  139. self.expand_size = fdt_util.GetBool(self._node, 'expand-size')
  140. def GetDefaultFilename(self):
  141. return None
  142. def GetFdtSet(self):
  143. """Get the set of device trees used by this entry
  144. Returns:
  145. Set containing the filename from this entry, if it is a .dtb, else
  146. an empty set
  147. """
  148. fname = self.GetDefaultFilename()
  149. # It would be better to use isinstance(self, Entry_blob_dtb) here but
  150. # we cannot access Entry_blob_dtb
  151. if fname and fname.endswith('.dtb'):
  152. return Set([fname])
  153. return Set()
  154. def ExpandEntries(self):
  155. pass
  156. def AddMissingProperties(self):
  157. """Add new properties to the device tree as needed for this entry"""
  158. for prop in ['offset', 'size', 'image-pos']:
  159. if not prop in self._node.props:
  160. state.AddZeroProp(self._node, prop)
  161. err = state.CheckAddHashProp(self._node)
  162. if err:
  163. self.Raise(err)
  164. def SetCalculatedProperties(self):
  165. """Set the value of device-tree properties calculated by binman"""
  166. state.SetInt(self._node, 'offset', self.offset)
  167. state.SetInt(self._node, 'size', self.size)
  168. state.SetInt(self._node, 'image-pos',
  169. self.image_pos - self.section.GetRootSkipAtStart())
  170. state.CheckSetHashValue(self._node, self.GetData)
  171. def ProcessFdt(self, fdt):
  172. """Allow entries to adjust the device tree
  173. Some entries need to adjust the device tree for their purposes. This
  174. may involve adding or deleting properties.
  175. Returns:
  176. True if processing is complete
  177. False if processing could not be completed due to a dependency.
  178. This will cause the entry to be retried after others have been
  179. called
  180. """
  181. return True
  182. def SetPrefix(self, prefix):
  183. """Set the name prefix for a node
  184. Args:
  185. prefix: Prefix to set, or '' to not use a prefix
  186. """
  187. if prefix:
  188. self.name = prefix + self.name
  189. def SetContents(self, data):
  190. """Set the contents of an entry
  191. This sets both the data and content_size properties
  192. Args:
  193. data: Data to set to the contents (string)
  194. """
  195. self.data = data
  196. self.contents_size = len(self.data)
  197. def ProcessContentsUpdate(self, data):
  198. """Update the contens of an entry, after the size is fixed
  199. This checks that the new data is the same size as the old.
  200. Args:
  201. data: Data to set to the contents (string)
  202. Raises:
  203. ValueError if the new data size is not the same as the old
  204. """
  205. if len(data) != self.contents_size:
  206. self.Raise('Cannot update entry size from %d to %d' %
  207. (len(data), self.contents_size))
  208. self.SetContents(data)
  209. def ObtainContents(self):
  210. """Figure out the contents of an entry.
  211. Returns:
  212. True if the contents were found, False if another call is needed
  213. after the other entries are processed.
  214. """
  215. # No contents by default: subclasses can implement this
  216. return True
  217. def Pack(self, offset):
  218. """Figure out how to pack the entry into the section
  219. Most of the time the entries are not fully specified. There may be
  220. an alignment but no size. In that case we take the size from the
  221. contents of the entry.
  222. If an entry has no hard-coded offset, it will be placed at @offset.
  223. Once this function is complete, both the offset and size of the
  224. entry will be know.
  225. Args:
  226. Current section offset pointer
  227. Returns:
  228. New section offset pointer (after this entry)
  229. """
  230. if self.offset is None:
  231. if self.offset_unset:
  232. self.Raise('No offset set with offset-unset: should another '
  233. 'entry provide this correct offset?')
  234. self.offset = tools.Align(offset, self.align)
  235. needed = self.pad_before + self.contents_size + self.pad_after
  236. needed = tools.Align(needed, self.align_size)
  237. size = self.size
  238. if not size:
  239. size = needed
  240. new_offset = self.offset + size
  241. aligned_offset = tools.Align(new_offset, self.align_end)
  242. if aligned_offset != new_offset:
  243. size = aligned_offset - self.offset
  244. new_offset = aligned_offset
  245. if not self.size:
  246. self.size = size
  247. if self.size < needed:
  248. self.Raise("Entry contents size is %#x (%d) but entry size is "
  249. "%#x (%d)" % (needed, needed, self.size, self.size))
  250. # Check that the alignment is correct. It could be wrong if the
  251. # and offset or size values were provided (i.e. not calculated), but
  252. # conflict with the provided alignment values
  253. if self.size != tools.Align(self.size, self.align_size):
  254. self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  255. (self.size, self.size, self.align_size, self.align_size))
  256. if self.offset != tools.Align(self.offset, self.align):
  257. self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
  258. (self.offset, self.offset, self.align, self.align))
  259. return new_offset
  260. def Raise(self, msg):
  261. """Convenience function to raise an error referencing a node"""
  262. raise ValueError("Node '%s': %s" % (self._node.path, msg))
  263. def GetEntryArgsOrProps(self, props, required=False):
  264. """Return the values of a set of properties
  265. Args:
  266. props: List of EntryArg objects
  267. Raises:
  268. ValueError if a property is not found
  269. """
  270. values = []
  271. missing = []
  272. for prop in props:
  273. python_prop = prop.name.replace('-', '_')
  274. if hasattr(self, python_prop):
  275. value = getattr(self, python_prop)
  276. else:
  277. value = None
  278. if value is None:
  279. value = self.GetArg(prop.name, prop.datatype)
  280. if value is None and required:
  281. missing.append(prop.name)
  282. values.append(value)
  283. if missing:
  284. self.Raise('Missing required properties/entry args: %s' %
  285. (', '.join(missing)))
  286. return values
  287. def GetPath(self):
  288. """Get the path of a node
  289. Returns:
  290. Full path of the node for this entry
  291. """
  292. return self._node.path
  293. def GetData(self):
  294. return self.data
  295. def GetOffsets(self):
  296. return {}
  297. def SetOffsetSize(self, pos, size):
  298. self.offset = pos
  299. self.size = size
  300. def SetImagePos(self, image_pos):
  301. """Set the position in the image
  302. Args:
  303. image_pos: Position of this entry in the image
  304. """
  305. self.image_pos = image_pos + self.offset
  306. def ProcessContents(self):
  307. pass
  308. def WriteSymbols(self, section):
  309. """Write symbol values into binary files for access at run time
  310. Args:
  311. section: Section containing the entry
  312. """
  313. pass
  314. def CheckOffset(self):
  315. """Check that the entry offsets are correct
  316. This is used for entries which have extra offset requirements (other
  317. than having to be fully inside their section). Sub-classes can implement
  318. this function and raise if there is a problem.
  319. """
  320. pass
  321. @staticmethod
  322. def GetStr(value):
  323. if value is None:
  324. return '<none> '
  325. return '%08x' % value
  326. @staticmethod
  327. def WriteMapLine(fd, indent, name, offset, size, image_pos):
  328. print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
  329. Entry.GetStr(offset), Entry.GetStr(size),
  330. name), file=fd)
  331. def WriteMap(self, fd, indent):
  332. """Write a map of the entry to a .map file
  333. Args:
  334. fd: File to write the map to
  335. indent: Curent indent level of map (0=none, 1=one level, etc.)
  336. """
  337. self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
  338. self.image_pos)
  339. def GetEntries(self):
  340. """Return a list of entries contained by this entry
  341. Returns:
  342. List of entries, or None if none. A normal entry has no entries
  343. within it so will return None
  344. """
  345. return None
  346. def GetArg(self, name, datatype=str):
  347. """Get the value of an entry argument or device-tree-node property
  348. Some node properties can be provided as arguments to binman. First check
  349. the entry arguments, and fall back to the device tree if not found
  350. Args:
  351. name: Argument name
  352. datatype: Data type (str or int)
  353. Returns:
  354. Value of argument as a string or int, or None if no value
  355. Raises:
  356. ValueError if the argument cannot be converted to in
  357. """
  358. value = state.GetEntryArg(name)
  359. if value is not None:
  360. if datatype == int:
  361. try:
  362. value = int(value)
  363. except ValueError:
  364. self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
  365. (name, value))
  366. elif datatype == str:
  367. pass
  368. else:
  369. raise ValueError("GetArg() internal error: Unknown data type '%s'" %
  370. datatype)
  371. else:
  372. value = fdt_util.GetDatatype(self._node, name, datatype)
  373. return value
  374. @staticmethod
  375. def WriteDocs(modules, test_missing=None):
  376. """Write out documentation about the various entry types to stdout
  377. Args:
  378. modules: List of modules to include
  379. test_missing: Used for testing. This is a module to report
  380. as missing
  381. """
  382. print('''Binman Entry Documentation
  383. ===========================
  384. This file describes the entry types supported by binman. These entry types can
  385. be placed in an image one by one to build up a final firmware image. It is
  386. fairly easy to create new entry types. Just add a new file to the 'etype'
  387. directory. You can use the existing entries as examples.
  388. Note that some entries are subclasses of others, using and extending their
  389. features to produce new behaviours.
  390. ''')
  391. modules = sorted(modules)
  392. # Don't show the test entry
  393. if '_testing' in modules:
  394. modules.remove('_testing')
  395. missing = []
  396. for name in modules:
  397. module = Entry.Lookup(name, name, name)
  398. docs = getattr(module, '__doc__')
  399. if test_missing == name:
  400. docs = None
  401. if docs:
  402. lines = docs.splitlines()
  403. first_line = lines[0]
  404. rest = [line[4:] for line in lines[1:]]
  405. hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
  406. print(hdr)
  407. print('-' * len(hdr))
  408. print('\n'.join(rest))
  409. print()
  410. print()
  411. else:
  412. missing.append(name)
  413. if missing:
  414. raise ValueError('Documentation is missing for modules: %s' %
  415. ', '.join(missing))
  416. def GetUniqueName(self):
  417. """Get a unique name for a node
  418. Returns:
  419. String containing a unique name for a node, consisting of the name
  420. of all ancestors (starting from within the 'binman' node) separated
  421. by a dot ('.'). This can be useful for generating unique filesnames
  422. in the output directory.
  423. """
  424. name = self.name
  425. node = self._node
  426. while node.parent:
  427. node = node.parent
  428. if node.name == 'binman':
  429. break
  430. name = '%s.%s' % (node.name, name)
  431. return name
  432. def ExpandToLimit(self, limit):
  433. """Expand an entry so that it ends at the given offset limit"""
  434. if self.offset + self.size < limit:
  435. self.size = limit - self.offset
  436. # Request the contents again, since changing the size requires that
  437. # the data grows. This should not fail, but check it to be sure.
  438. if not self.ObtainContents():
  439. self.Raise('Cannot obtain contents when expanding entry')