entry.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524
  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', self.image_pos)
  169. state.CheckSetHashValue(self._node, self.GetData)
  170. def ProcessFdt(self, fdt):
  171. """Allow entries to adjust the device tree
  172. Some entries need to adjust the device tree for their purposes. This
  173. may involve adding or deleting properties.
  174. Returns:
  175. True if processing is complete
  176. False if processing could not be completed due to a dependency.
  177. This will cause the entry to be retried after others have been
  178. called
  179. """
  180. return True
  181. def SetPrefix(self, prefix):
  182. """Set the name prefix for a node
  183. Args:
  184. prefix: Prefix to set, or '' to not use a prefix
  185. """
  186. if prefix:
  187. self.name = prefix + self.name
  188. def SetContents(self, data):
  189. """Set the contents of an entry
  190. This sets both the data and content_size properties
  191. Args:
  192. data: Data to set to the contents (string)
  193. """
  194. self.data = data
  195. self.contents_size = len(self.data)
  196. def ProcessContentsUpdate(self, data):
  197. """Update the contens of an entry, after the size is fixed
  198. This checks that the new data is the same size as the old.
  199. Args:
  200. data: Data to set to the contents (string)
  201. Raises:
  202. ValueError if the new data size is not the same as the old
  203. """
  204. if len(data) != self.contents_size:
  205. self.Raise('Cannot update entry size from %d to %d' %
  206. (len(data), self.contents_size))
  207. self.SetContents(data)
  208. def ObtainContents(self):
  209. """Figure out the contents of an entry.
  210. Returns:
  211. True if the contents were found, False if another call is needed
  212. after the other entries are processed.
  213. """
  214. # No contents by default: subclasses can implement this
  215. return True
  216. def Pack(self, offset):
  217. """Figure out how to pack the entry into the section
  218. Most of the time the entries are not fully specified. There may be
  219. an alignment but no size. In that case we take the size from the
  220. contents of the entry.
  221. If an entry has no hard-coded offset, it will be placed at @offset.
  222. Once this function is complete, both the offset and size of the
  223. entry will be know.
  224. Args:
  225. Current section offset pointer
  226. Returns:
  227. New section offset pointer (after this entry)
  228. """
  229. if self.offset is None:
  230. if self.offset_unset:
  231. self.Raise('No offset set with offset-unset: should another '
  232. 'entry provide this correct offset?')
  233. self.offset = tools.Align(offset, self.align)
  234. needed = self.pad_before + self.contents_size + self.pad_after
  235. needed = tools.Align(needed, self.align_size)
  236. size = self.size
  237. if not size:
  238. size = needed
  239. new_offset = self.offset + size
  240. aligned_offset = tools.Align(new_offset, self.align_end)
  241. if aligned_offset != new_offset:
  242. size = aligned_offset - self.offset
  243. new_offset = aligned_offset
  244. if not self.size:
  245. self.size = size
  246. if self.size < needed:
  247. self.Raise("Entry contents size is %#x (%d) but entry size is "
  248. "%#x (%d)" % (needed, needed, self.size, self.size))
  249. # Check that the alignment is correct. It could be wrong if the
  250. # and offset or size values were provided (i.e. not calculated), but
  251. # conflict with the provided alignment values
  252. if self.size != tools.Align(self.size, self.align_size):
  253. self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  254. (self.size, self.size, self.align_size, self.align_size))
  255. if self.offset != tools.Align(self.offset, self.align):
  256. self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
  257. (self.offset, self.offset, self.align, self.align))
  258. return new_offset
  259. def Raise(self, msg):
  260. """Convenience function to raise an error referencing a node"""
  261. raise ValueError("Node '%s': %s" % (self._node.path, msg))
  262. def GetEntryArgsOrProps(self, props, required=False):
  263. """Return the values of a set of properties
  264. Args:
  265. props: List of EntryArg objects
  266. Raises:
  267. ValueError if a property is not found
  268. """
  269. values = []
  270. missing = []
  271. for prop in props:
  272. python_prop = prop.name.replace('-', '_')
  273. if hasattr(self, python_prop):
  274. value = getattr(self, python_prop)
  275. else:
  276. value = None
  277. if value is None:
  278. value = self.GetArg(prop.name, prop.datatype)
  279. if value is None and required:
  280. missing.append(prop.name)
  281. values.append(value)
  282. if missing:
  283. self.Raise('Missing required properties/entry args: %s' %
  284. (', '.join(missing)))
  285. return values
  286. def GetPath(self):
  287. """Get the path of a node
  288. Returns:
  289. Full path of the node for this entry
  290. """
  291. return self._node.path
  292. def GetData(self):
  293. return self.data
  294. def GetOffsets(self):
  295. return {}
  296. def SetOffsetSize(self, pos, size):
  297. self.offset = pos
  298. self.size = size
  299. def SetImagePos(self, image_pos):
  300. """Set the position in the image
  301. Args:
  302. image_pos: Position of this entry in the image
  303. """
  304. self.image_pos = image_pos + self.offset
  305. def ProcessContents(self):
  306. pass
  307. def WriteSymbols(self, section):
  308. """Write symbol values into binary files for access at run time
  309. Args:
  310. section: Section containing the entry
  311. """
  312. pass
  313. def CheckOffset(self):
  314. """Check that the entry offsets are correct
  315. This is used for entries which have extra offset requirements (other
  316. than having to be fully inside their section). Sub-classes can implement
  317. this function and raise if there is a problem.
  318. """
  319. pass
  320. @staticmethod
  321. def WriteMapLine(fd, indent, name, offset, size, image_pos):
  322. print('%08x %s%08x %08x %s' % (image_pos, ' ' * indent, offset,
  323. size, name), file=fd)
  324. def WriteMap(self, fd, indent):
  325. """Write a map of the entry to a .map file
  326. Args:
  327. fd: File to write the map to
  328. indent: Curent indent level of map (0=none, 1=one level, etc.)
  329. """
  330. self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
  331. self.image_pos)
  332. def GetEntries(self):
  333. """Return a list of entries contained by this entry
  334. Returns:
  335. List of entries, or None if none. A normal entry has no entries
  336. within it so will return None
  337. """
  338. return None
  339. def GetArg(self, name, datatype=str):
  340. """Get the value of an entry argument or device-tree-node property
  341. Some node properties can be provided as arguments to binman. First check
  342. the entry arguments, and fall back to the device tree if not found
  343. Args:
  344. name: Argument name
  345. datatype: Data type (str or int)
  346. Returns:
  347. Value of argument as a string or int, or None if no value
  348. Raises:
  349. ValueError if the argument cannot be converted to in
  350. """
  351. value = state.GetEntryArg(name)
  352. if value is not None:
  353. if datatype == int:
  354. try:
  355. value = int(value)
  356. except ValueError:
  357. self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
  358. (name, value))
  359. elif datatype == str:
  360. pass
  361. else:
  362. raise ValueError("GetArg() internal error: Unknown data type '%s'" %
  363. datatype)
  364. else:
  365. value = fdt_util.GetDatatype(self._node, name, datatype)
  366. return value
  367. @staticmethod
  368. def WriteDocs(modules, test_missing=None):
  369. """Write out documentation about the various entry types to stdout
  370. Args:
  371. modules: List of modules to include
  372. test_missing: Used for testing. This is a module to report
  373. as missing
  374. """
  375. print('''Binman Entry Documentation
  376. ===========================
  377. This file describes the entry types supported by binman. These entry types can
  378. be placed in an image one by one to build up a final firmware image. It is
  379. fairly easy to create new entry types. Just add a new file to the 'etype'
  380. directory. You can use the existing entries as examples.
  381. Note that some entries are subclasses of others, using and extending their
  382. features to produce new behaviours.
  383. ''')
  384. modules = sorted(modules)
  385. # Don't show the test entry
  386. if '_testing' in modules:
  387. modules.remove('_testing')
  388. missing = []
  389. for name in modules:
  390. module = Entry.Lookup(name, name, name)
  391. docs = getattr(module, '__doc__')
  392. if test_missing == name:
  393. docs = None
  394. if docs:
  395. lines = docs.splitlines()
  396. first_line = lines[0]
  397. rest = [line[4:] for line in lines[1:]]
  398. hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
  399. print(hdr)
  400. print('-' * len(hdr))
  401. print('\n'.join(rest))
  402. print()
  403. print()
  404. else:
  405. missing.append(name)
  406. if missing:
  407. raise ValueError('Documentation is missing for modules: %s' %
  408. ', '.join(missing))
  409. def GetUniqueName(self):
  410. """Get a unique name for a node
  411. Returns:
  412. String containing a unique name for a node, consisting of the name
  413. of all ancestors (starting from within the 'binman' node) separated
  414. by a dot ('.'). This can be useful for generating unique filesnames
  415. in the output directory.
  416. """
  417. name = self.name
  418. node = self._node
  419. while node.parent:
  420. node = node.parent
  421. if node.name == 'binman':
  422. break
  423. name = '%s.%s' % (node.name, name)
  424. return name
  425. def ExpandToLimit(self, limit):
  426. """Expand an entry so that it ends at the given offset limit"""
  427. if self.offset + self.size < limit:
  428. self.size = limit - self.offset
  429. # Request the contents again, since changing the size requires that
  430. # the data grows. This should not fail, but check it to be sure.
  431. if not self.ObtainContents():
  432. self.Raise('Cannot obtain contents when expanding entry')