entry.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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. # importlib was introduced in Python 2.7 but there was a report of it not
  8. # working in 2.7.12, so we work around this:
  9. # http://lists.denx.de/pipermail/u-boot/2016-October/269729.html
  10. try:
  11. import importlib
  12. have_importlib = True
  13. except:
  14. have_importlib = False
  15. import fdt_util
  16. import os
  17. import sys
  18. import tools
  19. modules = {}
  20. our_path = os.path.dirname(os.path.realpath(__file__))
  21. class Entry(object):
  22. """An Entry in the section
  23. An entry corresponds to a single node in the device-tree description
  24. of the section. Each entry ends up being a part of the final section.
  25. Entries can be placed either right next to each other, or with padding
  26. between them. The type of the entry determines the data that is in it.
  27. This class is not used by itself. All entry objects are subclasses of
  28. Entry.
  29. Attributes:
  30. section: The section containing this entry
  31. node: The node that created this entry
  32. offset: Offset of entry within the section, None if not known yet (in
  33. which case it will be calculated by Pack())
  34. size: Entry size in bytes, None if not known
  35. contents_size: Size of contents in bytes, 0 by default
  36. align: Entry start offset alignment, or None
  37. align_size: Entry size alignment, or None
  38. align_end: Entry end offset alignment, or None
  39. pad_before: Number of pad bytes before the contents, 0 if none
  40. pad_after: Number of pad bytes after the contents, 0 if none
  41. data: Contents of entry (string of bytes)
  42. """
  43. def __init__(self, section, etype, node, read_node=True, name_prefix=''):
  44. self.section = section
  45. self.etype = etype
  46. self._node = node
  47. self.name = node and (name_prefix + node.name) or 'none'
  48. self.offset = None
  49. self.size = None
  50. self.data = ''
  51. self.contents_size = 0
  52. self.align = None
  53. self.align_size = None
  54. self.align_end = None
  55. self.pad_before = 0
  56. self.pad_after = 0
  57. self.offset_unset = False
  58. if read_node:
  59. self.ReadNode()
  60. @staticmethod
  61. def Create(section, node, etype=None):
  62. """Create a new entry for a node.
  63. Args:
  64. section: Image object containing this node
  65. node: Node object containing information about the entry to create
  66. etype: Entry type to use, or None to work it out (used for tests)
  67. Returns:
  68. A new Entry object of the correct type (a subclass of Entry)
  69. """
  70. if not etype:
  71. etype = fdt_util.GetString(node, 'type', node.name)
  72. # Convert something like 'u-boot@0' to 'u_boot' since we are only
  73. # interested in the type.
  74. module_name = etype.replace('-', '_')
  75. if '@' in module_name:
  76. module_name = module_name.split('@')[0]
  77. module = modules.get(module_name)
  78. # Also allow entry-type modules to be brought in from the etype directory.
  79. # Import the module if we have not already done so.
  80. if not module:
  81. old_path = sys.path
  82. sys.path.insert(0, os.path.join(our_path, 'etype'))
  83. try:
  84. if have_importlib:
  85. module = importlib.import_module(module_name)
  86. else:
  87. module = __import__(module_name)
  88. except ImportError:
  89. raise ValueError("Unknown entry type '%s' in node '%s'" %
  90. (etype, node.path))
  91. finally:
  92. sys.path = old_path
  93. modules[module_name] = module
  94. # Call its constructor to get the object we want.
  95. obj = getattr(module, 'Entry_%s' % module_name)
  96. return obj(section, etype, node)
  97. def ReadNode(self):
  98. """Read entry information from the node
  99. This reads all the fields we recognise from the node, ready for use.
  100. """
  101. self.offset = fdt_util.GetInt(self._node, 'offset')
  102. self.size = fdt_util.GetInt(self._node, 'size')
  103. self.align = fdt_util.GetInt(self._node, 'align')
  104. if tools.NotPowerOfTwo(self.align):
  105. raise ValueError("Node '%s': Alignment %s must be a power of two" %
  106. (self._node.path, self.align))
  107. self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
  108. self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
  109. self.align_size = fdt_util.GetInt(self._node, 'align-size')
  110. if tools.NotPowerOfTwo(self.align_size):
  111. raise ValueError("Node '%s': Alignment size %s must be a power "
  112. "of two" % (self._node.path, self.align_size))
  113. self.align_end = fdt_util.GetInt(self._node, 'align-end')
  114. self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
  115. def AddMissingProperties(self):
  116. """Add new properties to the device tree as needed for this entry"""
  117. for prop in ['offset', 'size', 'global-pos']:
  118. if not prop in self._node.props:
  119. self._node.AddZeroProp(prop)
  120. def SetCalculatedProperties(self):
  121. """Set the value of device-tree properties calculated by binman"""
  122. self._node.SetInt('offset', self.offset)
  123. self._node.SetInt('size', self.size)
  124. def ProcessFdt(self, fdt):
  125. return True
  126. def SetPrefix(self, prefix):
  127. """Set the name prefix for a node
  128. Args:
  129. prefix: Prefix to set, or '' to not use a prefix
  130. """
  131. if prefix:
  132. self.name = prefix + self.name
  133. def SetContents(self, data):
  134. """Set the contents of an entry
  135. This sets both the data and content_size properties
  136. Args:
  137. data: Data to set to the contents (string)
  138. """
  139. self.data = data
  140. self.contents_size = len(self.data)
  141. def ProcessContentsUpdate(self, data):
  142. """Update the contens of an entry, after the size is fixed
  143. This checks that the new data is the same size as the old.
  144. Args:
  145. data: Data to set to the contents (string)
  146. Raises:
  147. ValueError if the new data size is not the same as the old
  148. """
  149. if len(data) != self.contents_size:
  150. self.Raise('Cannot update entry size from %d to %d' %
  151. (len(data), self.contents_size))
  152. self.SetContents(data)
  153. def ObtainContents(self):
  154. """Figure out the contents of an entry.
  155. Returns:
  156. True if the contents were found, False if another call is needed
  157. after the other entries are processed.
  158. """
  159. # No contents by default: subclasses can implement this
  160. return True
  161. def Pack(self, offset):
  162. """Figure out how to pack the entry into the section
  163. Most of the time the entries are not fully specified. There may be
  164. an alignment but no size. In that case we take the size from the
  165. contents of the entry.
  166. If an entry has no hard-coded offset, it will be placed at @offset.
  167. Once this function is complete, both the offset and size of the
  168. entry will be know.
  169. Args:
  170. Current section offset pointer
  171. Returns:
  172. New section offset pointer (after this entry)
  173. """
  174. if self.offset is None:
  175. if self.offset_unset:
  176. self.Raise('No offset set with offset-unset: should another '
  177. 'entry provide this correct offset?')
  178. self.offset = tools.Align(offset, self.align)
  179. needed = self.pad_before + self.contents_size + self.pad_after
  180. needed = tools.Align(needed, self.align_size)
  181. size = self.size
  182. if not size:
  183. size = needed
  184. new_offset = self.offset + size
  185. aligned_offset = tools.Align(new_offset, self.align_end)
  186. if aligned_offset != new_offset:
  187. size = aligned_offset - self.offset
  188. new_offset = aligned_offset
  189. if not self.size:
  190. self.size = size
  191. if self.size < needed:
  192. self.Raise("Entry contents size is %#x (%d) but entry size is "
  193. "%#x (%d)" % (needed, needed, self.size, self.size))
  194. # Check that the alignment is correct. It could be wrong if the
  195. # and offset or size values were provided (i.e. not calculated), but
  196. # conflict with the provided alignment values
  197. if self.size != tools.Align(self.size, self.align_size):
  198. self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  199. (self.size, self.size, self.align_size, self.align_size))
  200. if self.offset != tools.Align(self.offset, self.align):
  201. self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
  202. (self.offset, self.offset, self.align, self.align))
  203. return new_offset
  204. def Raise(self, msg):
  205. """Convenience function to raise an error referencing a node"""
  206. raise ValueError("Node '%s': %s" % (self._node.path, msg))
  207. def GetPath(self):
  208. """Get the path of a node
  209. Returns:
  210. Full path of the node for this entry
  211. """
  212. return self._node.path
  213. def GetData(self):
  214. return self.data
  215. def GetOffsets(self):
  216. return {}
  217. def SetOffsetSize(self, pos, size):
  218. self.offset = pos
  219. self.size = size
  220. def ProcessContents(self):
  221. pass
  222. def WriteSymbols(self, section):
  223. """Write symbol values into binary files for access at run time
  224. Args:
  225. section: Section containing the entry
  226. """
  227. pass
  228. def CheckOffset(self):
  229. """Check that the entry offsets are correct
  230. This is used for entries which have extra offset requirements (other
  231. than having to be fully inside their section). Sub-classes can implement
  232. this function and raise if there is a problem.
  233. """
  234. pass
  235. def WriteMap(self, fd, indent):
  236. """Write a map of the entry to a .map file
  237. Args:
  238. fd: File to write the map to
  239. indent: Curent indent level of map (0=none, 1=one level, etc.)
  240. """
  241. print('%s%08x %08x %s' % (' ' * indent, self.offset, self.size,
  242. self.name), file=fd)