bsection.py 16 KB

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