bsection.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2018 Google, Inc
  3. # Written by Simon Glass <sjg@chromium.org>
  4. #
  5. # Base class for sections (collections of entries)
  6. #
  7. from __future__ import print_function
  8. from collections import OrderedDict
  9. import sys
  10. import fdt_util
  11. import re
  12. import tools
  13. class Section(object):
  14. """A section which contains multiple entries
  15. A section represents a collection of entries. There must be one or more
  16. sections in an image. Sections are used to group entries together.
  17. Attributes:
  18. _node: Node object that contains the section definition in device tree
  19. _size: Section size in bytes, or None if not known yet
  20. _align_size: Section size alignment, or None
  21. _pad_before: Number of bytes before the first entry starts. This
  22. effectively changes the place where entry position 0 starts
  23. _pad_after: Number of bytes after the last entry ends. The last
  24. entry will finish on or before this boundary
  25. _pad_byte: Byte to use to pad the section where there is no entry
  26. _sort: True if entries should be sorted by position, False if they
  27. must be in-order in the device tree description
  28. _skip_at_start: Number of bytes before the first entry starts. These
  29. effectively adjust the starting position of entries. For example,
  30. if _pad_before is 16, then the first entry would start at 16.
  31. An entry with pos = 20 would in fact be written at position 4
  32. in the image file.
  33. _end_4gb: Indicates that the section ends at the 4GB boundary. This is
  34. used for x86 images, which want to use positions such that a
  35. memory address (like 0xff800000) is the first entry position.
  36. This causes _skip_at_start to be set to the starting memory
  37. address.
  38. _name_prefix: Prefix to add to the name of all entries within this
  39. section
  40. _entries: OrderedDict() of entries
  41. """
  42. def __init__(self, name, node, test=False):
  43. global entry
  44. global Entry
  45. import entry
  46. from entry import Entry
  47. self._node = node
  48. self._size = None
  49. self._align_size = None
  50. self._pad_before = 0
  51. self._pad_after = 0
  52. self._pad_byte = 0
  53. self._sort = False
  54. self._skip_at_start = 0
  55. self._end_4gb = False
  56. self._name_prefix = ''
  57. self._entries = OrderedDict()
  58. if not test:
  59. self._ReadNode()
  60. self._ReadEntries()
  61. def _ReadNode(self):
  62. """Read properties from the section node"""
  63. self._size = fdt_util.GetInt(self._node, 'size')
  64. self._align_size = fdt_util.GetInt(self._node, 'align-size')
  65. if tools.NotPowerOfTwo(self._align_size):
  66. self._Raise("Alignment size %s must be a power of two" %
  67. self._align_size)
  68. self._pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
  69. self._pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
  70. self._pad_byte = fdt_util.GetInt(self._node, 'pad-byte', 0)
  71. self._sort = fdt_util.GetBool(self._node, 'sort-by-pos')
  72. self._end_4gb = fdt_util.GetBool(self._node, 'end-at-4gb')
  73. if self._end_4gb and not self._size:
  74. self._Raise("Section size must be provided when using end-at-4gb")
  75. if self._end_4gb:
  76. self._skip_at_start = 0x100000000 - self._size
  77. self._name_prefix = fdt_util.GetString(self._node, 'name-prefix')
  78. def _ReadEntries(self):
  79. for node in self._node.subnodes:
  80. entry = Entry.Create(self, node)
  81. entry.SetPrefix(self._name_prefix)
  82. self._entries[node.name] = entry
  83. def ProcessFdt(self, fdt):
  84. todo = self._entries.values()
  85. for passnum in range(3):
  86. next_todo = []
  87. for entry in todo:
  88. if not entry.ProcessFdt(fdt):
  89. next_todo.append(entry)
  90. todo = next_todo
  91. if not todo:
  92. break
  93. if todo:
  94. self._Raise('Internal error: Could not complete processing of Fdt: '
  95. 'remaining %s' % todo)
  96. return True
  97. def CheckSize(self):
  98. """Check that the section contents does not exceed its size, etc."""
  99. contents_size = 0
  100. for entry in self._entries.values():
  101. contents_size = max(contents_size, entry.pos + entry.size)
  102. contents_size -= self._skip_at_start
  103. size = self._size
  104. if not size:
  105. size = self._pad_before + contents_size + self._pad_after
  106. size = tools.Align(size, self._align_size)
  107. if self._size and contents_size > self._size:
  108. self._Raise("contents size %#x (%d) exceeds section size %#x (%d)" %
  109. (contents_size, contents_size, self._size, self._size))
  110. if not self._size:
  111. self._size = size
  112. if self._size != tools.Align(self._size, self._align_size):
  113. self._Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  114. (self._size, self._size, self._align_size, self._align_size))
  115. return size
  116. def _Raise(self, msg):
  117. """Raises an error for this section
  118. Args:
  119. msg: Error message to use in the raise string
  120. Raises:
  121. ValueError()
  122. """
  123. raise ValueError("Section '%s': %s" % (self._node.path, msg))
  124. def GetPath(self):
  125. """Get the path of an image (in the FDT)
  126. Returns:
  127. Full path of the node for this image
  128. """
  129. return self._node.path
  130. def FindEntryType(self, etype):
  131. """Find an entry type in the section
  132. Args:
  133. etype: Entry type to find
  134. Returns:
  135. entry matching that type, or None if not found
  136. """
  137. for entry in self._entries.values():
  138. if entry.etype == etype:
  139. return entry
  140. return None
  141. def GetEntryContents(self):
  142. """Call ObtainContents() for each entry
  143. This calls each entry's ObtainContents() a few times until they all
  144. return True. We stop calling an entry's function once it returns
  145. True. This allows the contents of one entry to depend on another.
  146. After 3 rounds we give up since it's likely an error.
  147. """
  148. todo = self._entries.values()
  149. for passnum in range(3):
  150. next_todo = []
  151. for entry in todo:
  152. if not entry.ObtainContents():
  153. next_todo.append(entry)
  154. todo = next_todo
  155. if not todo:
  156. break
  157. if todo:
  158. self._Raise('Internal error: Could not complete processing of '
  159. 'contents: remaining %s' % todo)
  160. return True
  161. def _SetEntryPosSize(self, name, pos, size):
  162. """Set the position and size of an entry
  163. Args:
  164. name: Entry name to update
  165. pos: New position
  166. size: New size
  167. """
  168. entry = self._entries.get(name)
  169. if not entry:
  170. self._Raise("Unable to set pos/size for unknown entry '%s'" % name)
  171. entry.SetPositionSize(self._skip_at_start + pos, size)
  172. def GetEntryPositions(self):
  173. """Handle entries that want to set the position/size of other entries
  174. This calls each entry's GetPositions() method. If it returns a list
  175. of entries to update, it updates them.
  176. """
  177. for entry in self._entries.values():
  178. pos_dict = entry.GetPositions()
  179. for name, info in pos_dict.iteritems():
  180. self._SetEntryPosSize(name, *info)
  181. def PackEntries(self):
  182. """Pack all entries into the section"""
  183. pos = self._skip_at_start
  184. for entry in self._entries.values():
  185. pos = entry.Pack(pos)
  186. def _SortEntries(self):
  187. """Sort entries by position"""
  188. entries = sorted(self._entries.values(), key=lambda entry: entry.pos)
  189. self._entries.clear()
  190. for entry in entries:
  191. self._entries[entry._node.name] = entry
  192. def CheckEntries(self):
  193. """Check that entries do not overlap or extend outside the section"""
  194. if self._sort:
  195. self._SortEntries()
  196. pos = 0
  197. prev_name = 'None'
  198. for entry in self._entries.values():
  199. entry.CheckPosition()
  200. if (entry.pos < self._skip_at_start or
  201. entry.pos >= self._skip_at_start + self._size):
  202. entry.Raise("Position %#x (%d) is outside the section starting "
  203. "at %#x (%d)" %
  204. (entry.pos, entry.pos, self._skip_at_start,
  205. self._skip_at_start))
  206. if entry.pos < pos:
  207. entry.Raise("Position %#x (%d) overlaps with previous entry '%s' "
  208. "ending at %#x (%d)" %
  209. (entry.pos, entry.pos, prev_name, pos, pos))
  210. pos = entry.pos + entry.size
  211. prev_name = entry.GetPath()
  212. def ProcessEntryContents(self):
  213. """Call the ProcessContents() method for each entry
  214. This is intended to adjust the contents as needed by the entry type.
  215. """
  216. for entry in self._entries.values():
  217. entry.ProcessContents()
  218. def WriteSymbols(self):
  219. """Write symbol values into binary files for access at run time"""
  220. for entry in self._entries.values():
  221. entry.WriteSymbols(self)
  222. def BuildSection(self, fd, base_pos):
  223. """Write the section to a file"""
  224. fd.seek(base_pos)
  225. fd.write(self.GetData())
  226. def GetData(self):
  227. """Write the section to a file"""
  228. section_data = chr(self._pad_byte) * self._size
  229. for entry in self._entries.values():
  230. data = entry.GetData()
  231. base = self._pad_before + entry.pos - self._skip_at_start
  232. section_data = (section_data[:base] + data +
  233. section_data[base + len(data):])
  234. return section_data
  235. def LookupSymbol(self, sym_name, optional, msg):
  236. """Look up a symbol in an ELF file
  237. Looks up a symbol in an ELF file. Only entry types which come from an
  238. ELF image can be used by this function.
  239. At present the only entry property supported is pos.
  240. Args:
  241. sym_name: Symbol name in the ELF file to look up in the format
  242. _binman_<entry>_prop_<property> where <entry> is the name of
  243. the entry and <property> is the property to find (e.g.
  244. _binman_u_boot_prop_pos). As a special case, you can append
  245. _any to <entry> to have it search for any matching entry. E.g.
  246. _binman_u_boot_any_prop_pos will match entries called u-boot,
  247. u-boot-img and u-boot-nodtb)
  248. optional: True if the symbol is optional. If False this function
  249. will raise if the symbol is not found
  250. msg: Message to display if an error occurs
  251. Returns:
  252. Value that should be assigned to that symbol, or None if it was
  253. optional and not found
  254. Raises:
  255. ValueError if the symbol is invalid or not found, or references a
  256. property which is not supported
  257. """
  258. m = re.match(r'^_binman_(\w+)_prop_(\w+)$', sym_name)
  259. if not m:
  260. raise ValueError("%s: Symbol '%s' has invalid format" %
  261. (msg, sym_name))
  262. entry_name, prop_name = m.groups()
  263. entry_name = entry_name.replace('_', '-')
  264. entry = self._entries.get(entry_name)
  265. if not entry:
  266. if entry_name.endswith('-any'):
  267. root = entry_name[:-4]
  268. for name in self._entries:
  269. if name.startswith(root):
  270. rest = name[len(root):]
  271. if rest in ['', '-img', '-nodtb']:
  272. entry = self._entries[name]
  273. if not entry:
  274. err = ("%s: Entry '%s' not found in list (%s)" %
  275. (msg, entry_name, ','.join(self._entries.keys())))
  276. if optional:
  277. print('Warning: %s' % err, file=sys.stderr)
  278. return None
  279. raise ValueError(err)
  280. if prop_name == 'pos':
  281. return entry.pos
  282. else:
  283. raise ValueError("%s: No such property '%s'" % (msg, prop_name))
  284. def GetEntries(self):
  285. return self._entries
  286. def WriteMap(self, fd, indent):
  287. """Write a map of the section to a .map file
  288. Args:
  289. fd: File to write the map to
  290. """
  291. for entry in self._entries.values():
  292. entry.WriteMap(fd, indent)