bsection.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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._node = node
  47. self._offset = 0
  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-offset')
  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 AddMissingProperties(self):
  84. for entry in self._entries.values():
  85. entry.AddMissingProperties()
  86. def SetCalculatedProperties(self):
  87. for entry in self._entries.values():
  88. entry.SetCalculatedProperties()
  89. def ProcessFdt(self, fdt):
  90. todo = self._entries.values()
  91. for passnum in range(3):
  92. next_todo = []
  93. for entry in todo:
  94. if not entry.ProcessFdt(fdt):
  95. next_todo.append(entry)
  96. todo = next_todo
  97. if not todo:
  98. break
  99. if todo:
  100. self._Raise('Internal error: Could not complete processing of Fdt: '
  101. 'remaining %s' % todo)
  102. return True
  103. def CheckSize(self):
  104. """Check that the section contents does not exceed its size, etc."""
  105. contents_size = 0
  106. for entry in self._entries.values():
  107. contents_size = max(contents_size, entry.offset + entry.size)
  108. contents_size -= self._skip_at_start
  109. size = self._size
  110. if not size:
  111. size = self._pad_before + contents_size + self._pad_after
  112. size = tools.Align(size, self._align_size)
  113. if self._size and contents_size > self._size:
  114. self._Raise("contents size %#x (%d) exceeds section size %#x (%d)" %
  115. (contents_size, contents_size, self._size, self._size))
  116. if not self._size:
  117. self._size = size
  118. if self._size != tools.Align(self._size, self._align_size):
  119. self._Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  120. (self._size, self._size, self._align_size, self._align_size))
  121. return size
  122. def _Raise(self, msg):
  123. """Raises an error for this section
  124. Args:
  125. msg: Error message to use in the raise string
  126. Raises:
  127. ValueError()
  128. """
  129. raise ValueError("Section '%s': %s" % (self._node.path, msg))
  130. def GetPath(self):
  131. """Get the path of an image (in the FDT)
  132. Returns:
  133. Full path of the node for this image
  134. """
  135. return self._node.path
  136. def FindEntryType(self, etype):
  137. """Find an entry type in the section
  138. Args:
  139. etype: Entry type to find
  140. Returns:
  141. entry matching that type, or None if not found
  142. """
  143. for entry in self._entries.values():
  144. if entry.etype == etype:
  145. return entry
  146. return None
  147. def GetEntryContents(self):
  148. """Call ObtainContents() for each entry
  149. This calls each entry's ObtainContents() a few times until they all
  150. return True. We stop calling an entry's function once it returns
  151. True. This allows the contents of one entry to depend on another.
  152. After 3 rounds we give up since it's likely an error.
  153. """
  154. todo = self._entries.values()
  155. for passnum in range(3):
  156. next_todo = []
  157. for entry in todo:
  158. if not entry.ObtainContents():
  159. next_todo.append(entry)
  160. todo = next_todo
  161. if not todo:
  162. break
  163. if todo:
  164. self._Raise('Internal error: Could not complete processing of '
  165. 'contents: remaining %s' % todo)
  166. return True
  167. def _SetEntryOffsetSize(self, name, offset, size):
  168. """Set the offset and size of an entry
  169. Args:
  170. name: Entry name to update
  171. offset: New offset
  172. size: New size
  173. """
  174. entry = self._entries.get(name)
  175. if not entry:
  176. self._Raise("Unable to set offset/size for unknown entry '%s'" %
  177. name)
  178. entry.SetOffsetSize(self._skip_at_start + offset, size)
  179. def GetEntryOffsets(self):
  180. """Handle entries that want to set the offset/size of other entries
  181. This calls each entry's GetOffsets() method. If it returns a list
  182. of entries to update, it updates them.
  183. """
  184. for entry in self._entries.values():
  185. offset_dict = entry.GetOffsets()
  186. for name, info in offset_dict.iteritems():
  187. self._SetEntryOffsetSize(name, *info)
  188. def PackEntries(self):
  189. """Pack all entries into the section"""
  190. offset = self._skip_at_start
  191. for entry in self._entries.values():
  192. offset = entry.Pack(offset)
  193. self._size = self.CheckSize()
  194. def _SortEntries(self):
  195. """Sort entries by offset"""
  196. entries = sorted(self._entries.values(), key=lambda entry: entry.offset)
  197. self._entries.clear()
  198. for entry in entries:
  199. self._entries[entry._node.name] = entry
  200. def CheckEntries(self):
  201. """Check that entries do not overlap or extend outside the section"""
  202. if self._sort:
  203. self._SortEntries()
  204. offset = 0
  205. prev_name = 'None'
  206. for entry in self._entries.values():
  207. entry.CheckOffset()
  208. if (entry.offset < self._skip_at_start or
  209. entry.offset >= self._skip_at_start + self._size):
  210. entry.Raise("Offset %#x (%d) is outside the section starting "
  211. "at %#x (%d)" %
  212. (entry.offset, entry.offset, self._skip_at_start,
  213. self._skip_at_start))
  214. if entry.offset < offset:
  215. entry.Raise("Offset %#x (%d) overlaps with previous entry '%s' "
  216. "ending at %#x (%d)" %
  217. (entry.offset, entry.offset, prev_name, offset, offset))
  218. offset = entry.offset + entry.size
  219. prev_name = entry.GetPath()
  220. def ProcessEntryContents(self):
  221. """Call the ProcessContents() method for each entry
  222. This is intended to adjust the contents as needed by the entry type.
  223. """
  224. for entry in self._entries.values():
  225. entry.ProcessContents()
  226. def WriteSymbols(self):
  227. """Write symbol values into binary files for access at run time"""
  228. for entry in self._entries.values():
  229. entry.WriteSymbols(self)
  230. def BuildSection(self, fd, base_offset):
  231. """Write the section to a file"""
  232. fd.seek(base_offset)
  233. fd.write(self.GetData())
  234. def GetData(self):
  235. """Write the section to a file"""
  236. section_data = chr(self._pad_byte) * self._size
  237. for entry in self._entries.values():
  238. data = entry.GetData()
  239. base = self._pad_before + entry.offset - self._skip_at_start
  240. section_data = (section_data[:base] + data +
  241. section_data[base + len(data):])
  242. return section_data
  243. def LookupSymbol(self, sym_name, optional, msg):
  244. """Look up a symbol in an ELF file
  245. Looks up a symbol in an ELF file. Only entry types which come from an
  246. ELF image can be used by this function.
  247. At present the only entry property supported is offset.
  248. Args:
  249. sym_name: Symbol name in the ELF file to look up in the format
  250. _binman_<entry>_prop_<property> where <entry> is the name of
  251. the entry and <property> is the property to find (e.g.
  252. _binman_u_boot_prop_offset). As a special case, you can append
  253. _any to <entry> to have it search for any matching entry. E.g.
  254. _binman_u_boot_any_prop_offset will match entries called u-boot,
  255. u-boot-img and u-boot-nodtb)
  256. optional: True if the symbol is optional. If False this function
  257. will raise if the symbol is not found
  258. msg: Message to display if an error occurs
  259. Returns:
  260. Value that should be assigned to that symbol, or None if it was
  261. optional and not found
  262. Raises:
  263. ValueError if the symbol is invalid or not found, or references a
  264. property which is not supported
  265. """
  266. m = re.match(r'^_binman_(\w+)_prop_(\w+)$', sym_name)
  267. if not m:
  268. raise ValueError("%s: Symbol '%s' has invalid format" %
  269. (msg, sym_name))
  270. entry_name, prop_name = m.groups()
  271. entry_name = entry_name.replace('_', '-')
  272. entry = self._entries.get(entry_name)
  273. if not entry:
  274. if entry_name.endswith('-any'):
  275. root = entry_name[:-4]
  276. for name in self._entries:
  277. if name.startswith(root):
  278. rest = name[len(root):]
  279. if rest in ['', '-img', '-nodtb']:
  280. entry = self._entries[name]
  281. if not entry:
  282. err = ("%s: Entry '%s' not found in list (%s)" %
  283. (msg, entry_name, ','.join(self._entries.keys())))
  284. if optional:
  285. print('Warning: %s' % err, file=sys.stderr)
  286. return None
  287. raise ValueError(err)
  288. if prop_name == 'offset':
  289. return entry.offset
  290. else:
  291. raise ValueError("%s: No such property '%s'" % (msg, prop_name))
  292. def GetEntries(self):
  293. return self._entries
  294. def WriteMap(self, fd, indent):
  295. """Write a map of the section to a .map file
  296. Args:
  297. fd: File to write the map to
  298. """
  299. for entry in self._entries.values():
  300. entry.WriteMap(fd, indent)