entry.py 18 KB

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