bsection.py 15 KB

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