entry.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  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. if read_node:
  66. self.ReadNode()
  67. @staticmethod
  68. def Lookup(section, node_path, etype):
  69. """Look up the entry class for a node.
  70. Args:
  71. section: Section object containing this node
  72. node_node: Path name of Node object containing information about
  73. the entry to create (used for errors)
  74. etype: Entry type to use
  75. Returns:
  76. The entry class object if found, else None
  77. """
  78. # Convert something like 'u-boot@0' to 'u_boot' since we are only
  79. # interested in the type.
  80. module_name = etype.replace('-', '_')
  81. if '@' in module_name:
  82. module_name = module_name.split('@')[0]
  83. module = modules.get(module_name)
  84. # Also allow entry-type modules to be brought in from the etype directory.
  85. # Import the module if we have not already done so.
  86. if not module:
  87. old_path = sys.path
  88. sys.path.insert(0, os.path.join(our_path, 'etype'))
  89. try:
  90. if have_importlib:
  91. module = importlib.import_module(module_name)
  92. else:
  93. module = __import__(module_name)
  94. except ImportError as e:
  95. raise ValueError("Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
  96. (etype, node_path, module_name, e))
  97. finally:
  98. sys.path = old_path
  99. modules[module_name] = module
  100. # Look up the expected class name
  101. return getattr(module, 'Entry_%s' % module_name)
  102. @staticmethod
  103. def Create(section, node, etype=None):
  104. """Create a new entry for a node.
  105. Args:
  106. section: Section object containing this node
  107. node: Node object containing information about the entry to
  108. create
  109. etype: Entry type to use, or None to work it out (used for tests)
  110. Returns:
  111. A new Entry object of the correct type (a subclass of Entry)
  112. """
  113. if not etype:
  114. etype = fdt_util.GetString(node, 'type', node.name)
  115. obj = Entry.Lookup(section, node.path, etype)
  116. # Call its constructor to get the object we want.
  117. return obj(section, etype, node)
  118. def ReadNode(self):
  119. """Read entry information from the node
  120. This reads all the fields we recognise from the node, ready for use.
  121. """
  122. if 'pos' in self._node.props:
  123. self.Raise("Please use 'offset' instead of 'pos'")
  124. self.offset = fdt_util.GetInt(self._node, 'offset')
  125. self.size = fdt_util.GetInt(self._node, 'size')
  126. self.align = fdt_util.GetInt(self._node, 'align')
  127. if tools.NotPowerOfTwo(self.align):
  128. raise ValueError("Node '%s': Alignment %s must be a power of two" %
  129. (self._node.path, self.align))
  130. self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
  131. self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
  132. self.align_size = fdt_util.GetInt(self._node, 'align-size')
  133. if tools.NotPowerOfTwo(self.align_size):
  134. raise ValueError("Node '%s': Alignment size %s must be a power "
  135. "of two" % (self._node.path, self.align_size))
  136. self.align_end = fdt_util.GetInt(self._node, 'align-end')
  137. self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
  138. def GetDefaultFilename(self):
  139. return None
  140. def GetFdtSet(self):
  141. """Get the set of device trees used by this entry
  142. Returns:
  143. Set containing the filename from this entry, if it is a .dtb, else
  144. an empty set
  145. """
  146. fname = self.GetDefaultFilename()
  147. # It would be better to use isinstance(self, Entry_blob_dtb) here but
  148. # we cannot access Entry_blob_dtb
  149. if fname and fname.endswith('.dtb'):
  150. return Set([fname])
  151. return Set()
  152. def AddMissingProperties(self):
  153. """Add new properties to the device tree as needed for this entry"""
  154. for prop in ['offset', 'size', 'image-pos']:
  155. if not prop in self._node.props:
  156. state.AddZeroProp(self._node, prop)
  157. def SetCalculatedProperties(self):
  158. """Set the value of device-tree properties calculated by binman"""
  159. state.SetInt(self._node, 'offset', self.offset)
  160. state.SetInt(self._node, 'size', self.size)
  161. state.SetInt(self._node, 'image-pos', self.image_pos)
  162. def ProcessFdt(self, fdt):
  163. return True
  164. def SetPrefix(self, prefix):
  165. """Set the name prefix for a node
  166. Args:
  167. prefix: Prefix to set, or '' to not use a prefix
  168. """
  169. if prefix:
  170. self.name = prefix + self.name
  171. def SetContents(self, data):
  172. """Set the contents of an entry
  173. This sets both the data and content_size properties
  174. Args:
  175. data: Data to set to the contents (string)
  176. """
  177. self.data = data
  178. self.contents_size = len(self.data)
  179. def ProcessContentsUpdate(self, data):
  180. """Update the contens of an entry, after the size is fixed
  181. This checks that the new data is the same size as the old.
  182. Args:
  183. data: Data to set to the contents (string)
  184. Raises:
  185. ValueError if the new data size is not the same as the old
  186. """
  187. if len(data) != self.contents_size:
  188. self.Raise('Cannot update entry size from %d to %d' %
  189. (len(data), self.contents_size))
  190. self.SetContents(data)
  191. def ObtainContents(self):
  192. """Figure out the contents of an entry.
  193. Returns:
  194. True if the contents were found, False if another call is needed
  195. after the other entries are processed.
  196. """
  197. # No contents by default: subclasses can implement this
  198. return True
  199. def Pack(self, offset):
  200. """Figure out how to pack the entry into the section
  201. Most of the time the entries are not fully specified. There may be
  202. an alignment but no size. In that case we take the size from the
  203. contents of the entry.
  204. If an entry has no hard-coded offset, it will be placed at @offset.
  205. Once this function is complete, both the offset and size of the
  206. entry will be know.
  207. Args:
  208. Current section offset pointer
  209. Returns:
  210. New section offset pointer (after this entry)
  211. """
  212. if self.offset is None:
  213. if self.offset_unset:
  214. self.Raise('No offset set with offset-unset: should another '
  215. 'entry provide this correct offset?')
  216. self.offset = tools.Align(offset, self.align)
  217. needed = self.pad_before + self.contents_size + self.pad_after
  218. needed = tools.Align(needed, self.align_size)
  219. size = self.size
  220. if not size:
  221. size = needed
  222. new_offset = self.offset + size
  223. aligned_offset = tools.Align(new_offset, self.align_end)
  224. if aligned_offset != new_offset:
  225. size = aligned_offset - self.offset
  226. new_offset = aligned_offset
  227. if not self.size:
  228. self.size = size
  229. if self.size < needed:
  230. self.Raise("Entry contents size is %#x (%d) but entry size is "
  231. "%#x (%d)" % (needed, needed, self.size, self.size))
  232. # Check that the alignment is correct. It could be wrong if the
  233. # and offset or size values were provided (i.e. not calculated), but
  234. # conflict with the provided alignment values
  235. if self.size != tools.Align(self.size, self.align_size):
  236. self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  237. (self.size, self.size, self.align_size, self.align_size))
  238. if self.offset != tools.Align(self.offset, self.align):
  239. self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
  240. (self.offset, self.offset, self.align, self.align))
  241. return new_offset
  242. def Raise(self, msg):
  243. """Convenience function to raise an error referencing a node"""
  244. raise ValueError("Node '%s': %s" % (self._node.path, msg))
  245. def GetEntryArgsOrProps(self, props, required=False):
  246. """Return the values of a set of properties
  247. Args:
  248. props: List of EntryArg objects
  249. Raises:
  250. ValueError if a property is not found
  251. """
  252. values = []
  253. missing = []
  254. for prop in props:
  255. python_prop = prop.name.replace('-', '_')
  256. if hasattr(self, python_prop):
  257. value = getattr(self, python_prop)
  258. else:
  259. value = None
  260. if value is None:
  261. value = self.GetArg(prop.name, prop.datatype)
  262. if value is None and required:
  263. missing.append(prop.name)
  264. values.append(value)
  265. if missing:
  266. self.Raise('Missing required properties/entry args: %s' %
  267. (', '.join(missing)))
  268. return values
  269. def GetPath(self):
  270. """Get the path of a node
  271. Returns:
  272. Full path of the node for this entry
  273. """
  274. return self._node.path
  275. def GetData(self):
  276. return self.data
  277. def GetOffsets(self):
  278. return {}
  279. def SetOffsetSize(self, pos, size):
  280. self.offset = pos
  281. self.size = size
  282. def SetImagePos(self, image_pos):
  283. """Set the position in the image
  284. Args:
  285. image_pos: Position of this entry in the image
  286. """
  287. self.image_pos = image_pos + self.offset
  288. def ProcessContents(self):
  289. pass
  290. def WriteSymbols(self, section):
  291. """Write symbol values into binary files for access at run time
  292. Args:
  293. section: Section containing the entry
  294. """
  295. pass
  296. def CheckOffset(self):
  297. """Check that the entry offsets are correct
  298. This is used for entries which have extra offset requirements (other
  299. than having to be fully inside their section). Sub-classes can implement
  300. this function and raise if there is a problem.
  301. """
  302. pass
  303. @staticmethod
  304. def WriteMapLine(fd, indent, name, offset, size, image_pos):
  305. print('%08x %s%08x %08x %s' % (image_pos, ' ' * indent, offset,
  306. size, name), file=fd)
  307. def WriteMap(self, fd, indent):
  308. """Write a map of the entry to a .map file
  309. Args:
  310. fd: File to write the map to
  311. indent: Curent indent level of map (0=none, 1=one level, etc.)
  312. """
  313. self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
  314. self.image_pos)
  315. def GetEntries(self):
  316. """Return a list of entries contained by this entry
  317. Returns:
  318. List of entries, or None if none. A normal entry has no entries
  319. within it so will return None
  320. """
  321. return None
  322. def GetArg(self, name, datatype=str):
  323. """Get the value of an entry argument or device-tree-node property
  324. Some node properties can be provided as arguments to binman. First check
  325. the entry arguments, and fall back to the device tree if not found
  326. Args:
  327. name: Argument name
  328. datatype: Data type (str or int)
  329. Returns:
  330. Value of argument as a string or int, or None if no value
  331. Raises:
  332. ValueError if the argument cannot be converted to in
  333. """
  334. value = state.GetEntryArg(name)
  335. if value is not None:
  336. if datatype == int:
  337. try:
  338. value = int(value)
  339. except ValueError:
  340. self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
  341. (name, value))
  342. elif datatype == str:
  343. pass
  344. else:
  345. raise ValueError("GetArg() internal error: Unknown data type '%s'" %
  346. datatype)
  347. else:
  348. value = fdt_util.GetDatatype(self._node, name, datatype)
  349. return value
  350. @staticmethod
  351. def WriteDocs(modules, test_missing=None):
  352. """Write out documentation about the various entry types to stdout
  353. Args:
  354. modules: List of modules to include
  355. test_missing: Used for testing. This is a module to report
  356. as missing
  357. """
  358. print('''Binman Entry Documentation
  359. ===========================
  360. This file describes the entry types supported by binman. These entry types can
  361. be placed in an image one by one to build up a final firmware image. It is
  362. fairly easy to create new entry types. Just add a new file to the 'etype'
  363. directory. You can use the existing entries as examples.
  364. Note that some entries are subclasses of others, using and extending their
  365. features to produce new behaviours.
  366. ''')
  367. modules = sorted(modules)
  368. # Don't show the test entry
  369. if '_testing' in modules:
  370. modules.remove('_testing')
  371. missing = []
  372. for name in modules:
  373. module = Entry.Lookup(name, name, name)
  374. docs = getattr(module, '__doc__')
  375. if test_missing == name:
  376. docs = None
  377. if docs:
  378. lines = docs.splitlines()
  379. first_line = lines[0]
  380. rest = [line[4:] for line in lines[1:]]
  381. hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
  382. print(hdr)
  383. print('-' * len(hdr))
  384. print('\n'.join(rest))
  385. print()
  386. print()
  387. else:
  388. missing.append(name)
  389. if missing:
  390. raise ValueError('Documentation is missing for modules: %s' %
  391. ', '.join(missing))
  392. def GetUniqueName(self):
  393. """Get a unique name for a node
  394. Returns:
  395. String containing a unique name for a node, consisting of the name
  396. of all ancestors (starting from within the 'binman' node) separated
  397. by a dot ('.'). This can be useful for generating unique filesnames
  398. in the output directory.
  399. """
  400. name = self.name
  401. node = self._node
  402. while node.parent:
  403. node = node.parent
  404. if node.name == 'binman':
  405. break
  406. name = '%s.%s' % (node.name, name)
  407. return name