entry.py 16 KB

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