bsection.py 17 KB

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