bsection.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383
  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 offset 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 offset, 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 offset of entries. For example,
  30. if _pad_before is 16, then the first entry would start at 16.
  31. An entry with offset = 20 would in fact be written at offset 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 offsets such that a memory
  35. address (like 0xff800000) is the first entry offset. This causes
  36. _skip_at_start to be set to the starting memory address.
  37. _name_prefix: Prefix to add to the name of all entries within this
  38. section
  39. _entries: OrderedDict() of entries
  40. """
  41. def __init__(self, name, node, test=False):
  42. global entry
  43. global Entry
  44. import entry
  45. from entry import Entry
  46. self._name = name
  47. self._node = node
  48. self._offset = 0
  49. self._size = None
  50. self._align_size = None
  51. self._pad_before = 0
  52. self._pad_after = 0
  53. self._pad_byte = 0
  54. self._sort = False
  55. self._skip_at_start = 0
  56. self._end_4gb = False
  57. self._name_prefix = ''
  58. self._entries = OrderedDict()
  59. if not test:
  60. self._ReadNode()
  61. self._ReadEntries()
  62. def _ReadNode(self):
  63. """Read properties from the section node"""
  64. self._size = fdt_util.GetInt(self._node, 'size')
  65. self._align_size = fdt_util.GetInt(self._node, 'align-size')
  66. if tools.NotPowerOfTwo(self._align_size):
  67. self._Raise("Alignment size %s must be a power of two" %
  68. self._align_size)
  69. self._pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
  70. self._pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
  71. self._pad_byte = fdt_util.GetInt(self._node, 'pad-byte', 0)
  72. self._sort = fdt_util.GetBool(self._node, 'sort-by-offset')
  73. self._end_4gb = fdt_util.GetBool(self._node, 'end-at-4gb')
  74. if self._end_4gb and not self._size:
  75. self._Raise("Section size must be provided when using end-at-4gb")
  76. if self._end_4gb:
  77. self._skip_at_start = 0x100000000 - self._size
  78. self._name_prefix = fdt_util.GetString(self._node, 'name-prefix')
  79. def _ReadEntries(self):
  80. for node in self._node.subnodes:
  81. entry = Entry.Create(self, node)
  82. entry.SetPrefix(self._name_prefix)
  83. self._entries[node.name] = entry
  84. def SetOffset(self, offset):
  85. self._offset = offset
  86. def AddMissingProperties(self):
  87. """Add new properties to the device tree as needed for this entry"""
  88. for prop in ['offset', 'size', 'image-pos']:
  89. if not prop in self._node.props:
  90. self._node.AddZeroProp(prop)
  91. for entry in self._entries.values():
  92. entry.AddMissingProperties()
  93. def SetCalculatedProperties(self):
  94. self._node.SetInt('offset', self._offset)
  95. self._node.SetInt('size', self._size)
  96. self._node.SetInt('image-pos', self._image_pos)
  97. for entry in self._entries.values():
  98. entry.SetCalculatedProperties()
  99. def ProcessFdt(self, fdt):
  100. todo = self._entries.values()
  101. for passnum in range(3):
  102. next_todo = []
  103. for entry in todo:
  104. if not entry.ProcessFdt(fdt):
  105. next_todo.append(entry)
  106. todo = next_todo
  107. if not todo:
  108. break
  109. if todo:
  110. self._Raise('Internal error: Could not complete processing of Fdt: '
  111. 'remaining %s' % todo)
  112. return True
  113. def CheckSize(self):
  114. """Check that the section contents does not exceed its size, etc."""
  115. contents_size = 0
  116. for entry in self._entries.values():
  117. contents_size = max(contents_size, entry.offset + entry.size)
  118. contents_size -= self._skip_at_start
  119. size = self._size
  120. if not size:
  121. size = self._pad_before + contents_size + self._pad_after
  122. size = tools.Align(size, self._align_size)
  123. if self._size and contents_size > self._size:
  124. self._Raise("contents size %#x (%d) exceeds section size %#x (%d)" %
  125. (contents_size, contents_size, self._size, self._size))
  126. if not self._size:
  127. self._size = size
  128. if self._size != tools.Align(self._size, self._align_size):
  129. self._Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  130. (self._size, self._size, self._align_size, self._align_size))
  131. return size
  132. def _Raise(self, msg):
  133. """Raises an error for this section
  134. Args:
  135. msg: Error message to use in the raise string
  136. Raises:
  137. ValueError()
  138. """
  139. raise ValueError("Section '%s': %s" % (self._node.path, msg))
  140. def GetPath(self):
  141. """Get the path of an image (in the FDT)
  142. Returns:
  143. Full path of the node for this image
  144. """
  145. return self._node.path
  146. def FindEntryType(self, etype):
  147. """Find an entry type in the section
  148. Args:
  149. etype: Entry type to find
  150. Returns:
  151. entry matching that type, or None if not found
  152. """
  153. for entry in self._entries.values():
  154. if entry.etype == etype:
  155. return entry
  156. return None
  157. def GetEntryContents(self):
  158. """Call ObtainContents() for each entry
  159. This calls each entry's ObtainContents() a few times until they all
  160. return True. We stop calling an entry's function once it returns
  161. True. This allows the contents of one entry to depend on another.
  162. After 3 rounds we give up since it's likely an error.
  163. """
  164. todo = self._entries.values()
  165. for passnum in range(3):
  166. next_todo = []
  167. for entry in todo:
  168. if not entry.ObtainContents():
  169. next_todo.append(entry)
  170. todo = next_todo
  171. if not todo:
  172. break
  173. if todo:
  174. self._Raise('Internal error: Could not complete processing of '
  175. 'contents: remaining %s' % todo)
  176. return True
  177. def _SetEntryOffsetSize(self, name, offset, size):
  178. """Set the offset and size of an entry
  179. Args:
  180. name: Entry name to update
  181. offset: New offset
  182. size: New size
  183. """
  184. entry = self._entries.get(name)
  185. if not entry:
  186. self._Raise("Unable to set offset/size for unknown entry '%s'" %
  187. name)
  188. entry.SetOffsetSize(self._skip_at_start + offset, size)
  189. def GetEntryOffsets(self):
  190. """Handle entries that want to set the offset/size of other entries
  191. This calls each entry's GetOffsets() method. If it returns a list
  192. of entries to update, it updates them.
  193. """
  194. for entry in self._entries.values():
  195. offset_dict = entry.GetOffsets()
  196. for name, info in offset_dict.iteritems():
  197. self._SetEntryOffsetSize(name, *info)
  198. def PackEntries(self):
  199. """Pack all entries into the section"""
  200. offset = self._skip_at_start
  201. for entry in self._entries.values():
  202. offset = entry.Pack(offset)
  203. self._size = self.CheckSize()
  204. def _SortEntries(self):
  205. """Sort entries by offset"""
  206. entries = sorted(self._entries.values(), key=lambda entry: entry.offset)
  207. self._entries.clear()
  208. for entry in entries:
  209. self._entries[entry._node.name] = entry
  210. def CheckEntries(self):
  211. """Check that entries do not overlap or extend outside the section"""
  212. if self._sort:
  213. self._SortEntries()
  214. offset = 0
  215. prev_name = 'None'
  216. for entry in self._entries.values():
  217. entry.CheckOffset()
  218. if (entry.offset < self._skip_at_start or
  219. entry.offset >= self._skip_at_start + self._size):
  220. entry.Raise("Offset %#x (%d) is outside the section starting "
  221. "at %#x (%d)" %
  222. (entry.offset, entry.offset, self._skip_at_start,
  223. self._skip_at_start))
  224. if entry.offset < offset:
  225. entry.Raise("Offset %#x (%d) overlaps with previous entry '%s' "
  226. "ending at %#x (%d)" %
  227. (entry.offset, entry.offset, prev_name, offset, offset))
  228. offset = entry.offset + entry.size
  229. prev_name = entry.GetPath()
  230. def SetImagePos(self, image_pos):
  231. self._image_pos = image_pos
  232. for entry in self._entries.values():
  233. entry.SetImagePos(image_pos)
  234. def ProcessEntryContents(self):
  235. """Call the ProcessContents() method for each entry
  236. This is intended to adjust the contents as needed by the entry type.
  237. """
  238. for entry in self._entries.values():
  239. entry.ProcessContents()
  240. def WriteSymbols(self):
  241. """Write symbol values into binary files for access at run time"""
  242. for entry in self._entries.values():
  243. entry.WriteSymbols(self)
  244. def BuildSection(self, fd, base_offset):
  245. """Write the section to a file"""
  246. fd.seek(base_offset)
  247. fd.write(self.GetData())
  248. def GetData(self):
  249. """Get the contents of the section"""
  250. section_data = chr(self._pad_byte) * self._size
  251. for entry in self._entries.values():
  252. data = entry.GetData()
  253. base = self._pad_before + entry.offset - self._skip_at_start
  254. section_data = (section_data[:base] + data +
  255. section_data[base + len(data):])
  256. return section_data
  257. def LookupSymbol(self, sym_name, optional, msg):
  258. """Look up a symbol in an ELF file
  259. Looks up a symbol in an ELF file. Only entry types which come from an
  260. ELF image can be used by this function.
  261. At present the only entry property supported is offset.
  262. Args:
  263. sym_name: Symbol name in the ELF file to look up in the format
  264. _binman_<entry>_prop_<property> where <entry> is the name of
  265. the entry and <property> is the property to find (e.g.
  266. _binman_u_boot_prop_offset). As a special case, you can append
  267. _any to <entry> to have it search for any matching entry. E.g.
  268. _binman_u_boot_any_prop_offset will match entries called u-boot,
  269. u-boot-img and u-boot-nodtb)
  270. optional: True if the symbol is optional. If False this function
  271. will raise if the symbol is not found
  272. msg: Message to display if an error occurs
  273. Returns:
  274. Value that should be assigned to that symbol, or None if it was
  275. optional and not found
  276. Raises:
  277. ValueError if the symbol is invalid or not found, or references a
  278. property which is not supported
  279. """
  280. m = re.match(r'^_binman_(\w+)_prop_(\w+)$', sym_name)
  281. if not m:
  282. raise ValueError("%s: Symbol '%s' has invalid format" %
  283. (msg, sym_name))
  284. entry_name, prop_name = m.groups()
  285. entry_name = entry_name.replace('_', '-')
  286. entry = self._entries.get(entry_name)
  287. if not entry:
  288. if entry_name.endswith('-any'):
  289. root = entry_name[:-4]
  290. for name in self._entries:
  291. if name.startswith(root):
  292. rest = name[len(root):]
  293. if rest in ['', '-img', '-nodtb']:
  294. entry = self._entries[name]
  295. if not entry:
  296. err = ("%s: Entry '%s' not found in list (%s)" %
  297. (msg, entry_name, ','.join(self._entries.keys())))
  298. if optional:
  299. print('Warning: %s' % err, file=sys.stderr)
  300. return None
  301. raise ValueError(err)
  302. if prop_name == 'offset':
  303. return entry.offset
  304. elif prop_name == 'image_pos':
  305. return entry.image_pos
  306. else:
  307. raise ValueError("%s: No such property '%s'" % (msg, prop_name))
  308. def GetEntries(self):
  309. """Get the number of entries in a section
  310. Returns:
  311. Number of entries in a section
  312. """
  313. return self._entries
  314. def GetSize(self):
  315. """Get the size of a section in bytes
  316. This is only meaningful if the section has a pre-defined size, or the
  317. entries within it have been packed, so that the size has been
  318. calculated.
  319. Returns:
  320. Entry size in bytes
  321. """
  322. return self._size
  323. def WriteMap(self, fd, indent):
  324. """Write a map of the section to a .map file
  325. Args:
  326. fd: File to write the map to
  327. """
  328. Entry.WriteMapLine(fd, indent, self._name, self._offset, self._size)
  329. for entry in self._entries.values():
  330. entry.WriteMap(fd, indent + 1)