section.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2018 Google, Inc
  3. # Written by Simon Glass <sjg@chromium.org>
  4. """Entry-type module for sections (groups of entries)
  5. Sections are entries which can contain other entries. This allows hierarchical
  6. images to be created.
  7. """
  8. from collections import OrderedDict
  9. import re
  10. import sys
  11. from binman.entry import Entry
  12. from dtoc import fdt_util
  13. from patman import tools
  14. from patman import tout
  15. class Entry_section(Entry):
  16. """Entry that contains other entries
  17. Properties / Entry arguments: (see binman README for more information)
  18. pad-byte: Pad byte to use when padding
  19. sort-by-offset: True if entries should be sorted by offset, False if
  20. they must be in-order in the device tree description
  21. end-at-4gb: Used to build an x86 ROM which ends at 4GB (2^32)
  22. skip-at-start: Number of bytes before the first entry starts. These
  23. effectively adjust the starting offset of entries. For example,
  24. if this is 16, then the first entry would start at 16. An entry
  25. with offset = 20 would in fact be written at offset 4 in the image
  26. file, since the first 16 bytes are skipped when writing.
  27. name-prefix: Adds a prefix to the name of every entry in the section
  28. when writing out the map
  29. Since a section is also an entry, it inherits all the properies of entries
  30. too.
  31. A section is an entry which can contain other entries, thus allowing
  32. hierarchical images to be created. See 'Sections and hierarchical images'
  33. in the binman README for more information.
  34. """
  35. def __init__(self, section, etype, node, test=False):
  36. if not test:
  37. Entry.__init__(self, section, etype, node)
  38. self._entries = OrderedDict()
  39. self._pad_byte = 0
  40. self._sort = False
  41. self._skip_at_start = None
  42. self._end_4gb = False
  43. def ReadNode(self):
  44. """Read properties from the image node"""
  45. Entry.ReadNode(self)
  46. self._pad_byte = fdt_util.GetInt(self._node, 'pad-byte', 0)
  47. self._sort = fdt_util.GetBool(self._node, 'sort-by-offset')
  48. self._end_4gb = fdt_util.GetBool(self._node, 'end-at-4gb')
  49. self._skip_at_start = fdt_util.GetInt(self._node, 'skip-at-start')
  50. if self._end_4gb:
  51. if not self.size:
  52. self.Raise("Section size must be provided when using end-at-4gb")
  53. if self._skip_at_start is not None:
  54. self.Raise("Provide either 'end-at-4gb' or 'skip-at-start'")
  55. else:
  56. self._skip_at_start = 0x100000000 - self.size
  57. else:
  58. if self._skip_at_start is None:
  59. self._skip_at_start = 0
  60. self._name_prefix = fdt_util.GetString(self._node, 'name-prefix')
  61. filename = fdt_util.GetString(self._node, 'filename')
  62. if filename:
  63. self._filename = filename
  64. self._ReadEntries()
  65. def _ReadEntries(self):
  66. for node in self._node.subnodes:
  67. if node.name == 'hash':
  68. continue
  69. entry = Entry.Create(self, node)
  70. entry.ReadNode()
  71. entry.SetPrefix(self._name_prefix)
  72. self._entries[node.name] = entry
  73. def _Raise(self, msg):
  74. """Raises an error for this section
  75. Args:
  76. msg: Error message to use in the raise string
  77. Raises:
  78. ValueError()
  79. """
  80. raise ValueError("Section '%s': %s" % (self._node.path, msg))
  81. def GetFdts(self):
  82. fdts = {}
  83. for entry in self._entries.values():
  84. fdts.update(entry.GetFdts())
  85. return fdts
  86. def ProcessFdt(self, fdt):
  87. """Allow entries to adjust the device tree
  88. Some entries need to adjust the device tree for their purposes. This
  89. may involve adding or deleting properties.
  90. """
  91. todo = self._entries.values()
  92. for passnum in range(3):
  93. next_todo = []
  94. for entry in todo:
  95. if not entry.ProcessFdt(fdt):
  96. next_todo.append(entry)
  97. todo = next_todo
  98. if not todo:
  99. break
  100. if todo:
  101. self.Raise('Internal error: Could not complete processing of Fdt: remaining %s' %
  102. todo)
  103. return True
  104. def ExpandEntries(self):
  105. """Expand out any entries which have calculated sub-entries
  106. Some entries are expanded out at runtime, e.g. 'files', which produces
  107. a section containing a list of files. Process these entries so that
  108. this information is added to the device tree.
  109. """
  110. Entry.ExpandEntries(self)
  111. for entry in self._entries.values():
  112. entry.ExpandEntries()
  113. def AddMissingProperties(self):
  114. """Add new properties to the device tree as needed for this entry"""
  115. Entry.AddMissingProperties(self)
  116. for entry in self._entries.values():
  117. entry.AddMissingProperties()
  118. def ObtainContents(self):
  119. return self.GetEntryContents()
  120. def GetData(self):
  121. section_data = b''
  122. for entry in self._entries.values():
  123. data = entry.GetData()
  124. base = self.pad_before + (entry.offset or 0) - self._skip_at_start
  125. pad = base - len(section_data)
  126. if pad > 0:
  127. section_data += tools.GetBytes(self._pad_byte, pad)
  128. section_data += data
  129. if self.size:
  130. pad = self.size - len(section_data)
  131. if pad > 0:
  132. section_data += tools.GetBytes(self._pad_byte, pad)
  133. self.Detail('GetData: %d entries, total size %#x' %
  134. (len(self._entries), len(section_data)))
  135. return section_data
  136. def GetOffsets(self):
  137. """Handle entries that want to set the offset/size of other entries
  138. This calls each entry's GetOffsets() method. If it returns a list
  139. of entries to update, it updates them.
  140. """
  141. self.GetEntryOffsets()
  142. return {}
  143. def ResetForPack(self):
  144. """Reset offset/size fields so that packing can be done again"""
  145. Entry.ResetForPack(self)
  146. for entry in self._entries.values():
  147. entry.ResetForPack()
  148. def Pack(self, offset):
  149. """Pack all entries into the section"""
  150. self._PackEntries()
  151. return Entry.Pack(self, offset)
  152. def _PackEntries(self):
  153. """Pack all entries into the image"""
  154. offset = self._skip_at_start
  155. for entry in self._entries.values():
  156. offset = entry.Pack(offset)
  157. self.size = self.CheckSize()
  158. def _ExpandEntries(self):
  159. """Expand any entries that are permitted to"""
  160. exp_entry = None
  161. for entry in self._entries.values():
  162. if exp_entry:
  163. exp_entry.ExpandToLimit(entry.offset)
  164. exp_entry = None
  165. if entry.expand_size:
  166. exp_entry = entry
  167. if exp_entry:
  168. exp_entry.ExpandToLimit(self.size)
  169. def _SortEntries(self):
  170. """Sort entries by offset"""
  171. entries = sorted(self._entries.values(), key=lambda entry: entry.offset)
  172. self._entries.clear()
  173. for entry in entries:
  174. self._entries[entry._node.name] = entry
  175. def CheckEntries(self):
  176. """Check that entries do not overlap or extend outside the image"""
  177. if self._sort:
  178. self._SortEntries()
  179. self._ExpandEntries()
  180. offset = 0
  181. prev_name = 'None'
  182. for entry in self._entries.values():
  183. entry.CheckOffset()
  184. if (entry.offset < self._skip_at_start or
  185. entry.offset + entry.size > self._skip_at_start +
  186. self.size):
  187. entry.Raise("Offset %#x (%d) is outside the section starting "
  188. "at %#x (%d)" %
  189. (entry.offset, entry.offset, self._skip_at_start,
  190. self._skip_at_start))
  191. if entry.offset < offset:
  192. entry.Raise("Offset %#x (%d) overlaps with previous entry '%s' "
  193. "ending at %#x (%d)" %
  194. (entry.offset, entry.offset, prev_name, offset, offset))
  195. offset = entry.offset + entry.size
  196. prev_name = entry.GetPath()
  197. def WriteSymbols(self, section):
  198. """Write symbol values into binary files for access at run time"""
  199. for entry in self._entries.values():
  200. entry.WriteSymbols(self)
  201. def SetCalculatedProperties(self):
  202. Entry.SetCalculatedProperties(self)
  203. for entry in self._entries.values():
  204. entry.SetCalculatedProperties()
  205. def SetImagePos(self, image_pos):
  206. Entry.SetImagePos(self, image_pos)
  207. for entry in self._entries.values():
  208. entry.SetImagePos(image_pos + self.offset)
  209. def ProcessContents(self):
  210. sizes_ok_base = super(Entry_section, self).ProcessContents()
  211. sizes_ok = True
  212. for entry in self._entries.values():
  213. if not entry.ProcessContents():
  214. sizes_ok = False
  215. return sizes_ok and sizes_ok_base
  216. def CheckOffset(self):
  217. self.CheckEntries()
  218. def WriteMap(self, fd, indent):
  219. """Write a map of the section to a .map file
  220. Args:
  221. fd: File to write the map to
  222. """
  223. Entry.WriteMapLine(fd, indent, self.name, self.offset or 0,
  224. self.size, self.image_pos)
  225. for entry in self._entries.values():
  226. entry.WriteMap(fd, indent + 1)
  227. def GetEntries(self):
  228. return self._entries
  229. def GetContentsByPhandle(self, phandle, source_entry):
  230. """Get the data contents of an entry specified by a phandle
  231. This uses a phandle to look up a node and and find the entry
  232. associated with it. Then it returnst he contents of that entry.
  233. Args:
  234. phandle: Phandle to look up (integer)
  235. source_entry: Entry containing that phandle (used for error
  236. reporting)
  237. Returns:
  238. data from associated entry (as a string), or None if not found
  239. """
  240. node = self._node.GetFdt().LookupPhandle(phandle)
  241. if not node:
  242. source_entry.Raise("Cannot find node for phandle %d" % phandle)
  243. for entry in self._entries.values():
  244. if entry._node == node:
  245. return entry.GetData()
  246. source_entry.Raise("Cannot find entry for node '%s'" % node.name)
  247. def LookupSymbol(self, sym_name, optional, msg, base_addr):
  248. """Look up a symbol in an ELF file
  249. Looks up a symbol in an ELF file. Only entry types which come from an
  250. ELF image can be used by this function.
  251. At present the only entry properties supported are:
  252. offset
  253. image_pos - 'base_addr' is added if this is not an end-at-4gb image
  254. size
  255. Args:
  256. sym_name: Symbol name in the ELF file to look up in the format
  257. _binman_<entry>_prop_<property> where <entry> is the name of
  258. the entry and <property> is the property to find (e.g.
  259. _binman_u_boot_prop_offset). As a special case, you can append
  260. _any to <entry> to have it search for any matching entry. E.g.
  261. _binman_u_boot_any_prop_offset will match entries called u-boot,
  262. u-boot-img and u-boot-nodtb)
  263. optional: True if the symbol is optional. If False this function
  264. will raise if the symbol is not found
  265. msg: Message to display if an error occurs
  266. base_addr: Base address of image. This is added to the returned
  267. image_pos in most cases so that the returned position indicates
  268. where the targetted entry/binary has actually been loaded. But
  269. if end-at-4gb is used, this is not done, since the binary is
  270. already assumed to be linked to the ROM position and using
  271. execute-in-place (XIP).
  272. Returns:
  273. Value that should be assigned to that symbol, or None if it was
  274. optional and not found
  275. Raises:
  276. ValueError if the symbol is invalid or not found, or references a
  277. property which is not supported
  278. """
  279. m = re.match(r'^_binman_(\w+)_prop_(\w+)$', sym_name)
  280. if not m:
  281. raise ValueError("%s: Symbol '%s' has invalid format" %
  282. (msg, sym_name))
  283. entry_name, prop_name = m.groups()
  284. entry_name = entry_name.replace('_', '-')
  285. entry = self._entries.get(entry_name)
  286. if not entry:
  287. if entry_name.endswith('-any'):
  288. root = entry_name[:-4]
  289. for name in self._entries:
  290. if name.startswith(root):
  291. rest = name[len(root):]
  292. if rest in ['', '-img', '-nodtb']:
  293. entry = self._entries[name]
  294. if not entry:
  295. err = ("%s: Entry '%s' not found in list (%s)" %
  296. (msg, entry_name, ','.join(self._entries.keys())))
  297. if optional:
  298. print('Warning: %s' % err, file=sys.stderr)
  299. return None
  300. raise ValueError(err)
  301. if prop_name == 'offset':
  302. return entry.offset
  303. elif prop_name == 'image_pos':
  304. value = entry.image_pos
  305. if not self.GetImage()._end_4gb:
  306. value += base_addr
  307. return value
  308. if prop_name == 'size':
  309. return entry.size
  310. else:
  311. raise ValueError("%s: No such property '%s'" % (msg, prop_name))
  312. def GetRootSkipAtStart(self):
  313. """Get the skip-at-start value for the top-level section
  314. This is used to find out the starting offset for root section that
  315. contains this section. If this is a top-level section then it returns
  316. the skip-at-start offset for this section.
  317. This is used to get the absolute position of section within the image.
  318. Returns:
  319. Integer skip-at-start value for the root section containing this
  320. section
  321. """
  322. if self.section:
  323. return self.section.GetRootSkipAtStart()
  324. return self._skip_at_start
  325. def GetStartOffset(self):
  326. """Get the start offset for this section
  327. Returns:
  328. The first available offset in this section (typically 0)
  329. """
  330. return self._skip_at_start
  331. def GetImageSize(self):
  332. """Get the size of the image containing this section
  333. Returns:
  334. Image size as an integer number of bytes, which may be None if the
  335. image size is dynamic and its sections have not yet been packed
  336. """
  337. return self.GetImage().size
  338. def FindEntryType(self, etype):
  339. """Find an entry type in the section
  340. Args:
  341. etype: Entry type to find
  342. Returns:
  343. entry matching that type, or None if not found
  344. """
  345. for entry in self._entries.values():
  346. if entry.etype == etype:
  347. return entry
  348. return None
  349. def GetEntryContents(self):
  350. """Call ObtainContents() for the section
  351. """
  352. todo = self._entries.values()
  353. for passnum in range(3):
  354. next_todo = []
  355. for entry in todo:
  356. if not entry.ObtainContents():
  357. next_todo.append(entry)
  358. todo = next_todo
  359. if not todo:
  360. break
  361. if todo:
  362. self.Raise('Internal error: Could not complete processing of contents: remaining %s' %
  363. todo)
  364. return True
  365. def _SetEntryOffsetSize(self, name, offset, size):
  366. """Set the offset and size of an entry
  367. Args:
  368. name: Entry name to update
  369. offset: New offset, or None to leave alone
  370. size: New size, or None to leave alone
  371. """
  372. entry = self._entries.get(name)
  373. if not entry:
  374. self._Raise("Unable to set offset/size for unknown entry '%s'" %
  375. name)
  376. entry.SetOffsetSize(self._skip_at_start + offset if offset else None,
  377. size)
  378. def GetEntryOffsets(self):
  379. """Handle entries that want to set the offset/size of other entries
  380. This calls each entry's GetOffsets() method. If it returns a list
  381. of entries to update, it updates them.
  382. """
  383. for entry in self._entries.values():
  384. offset_dict = entry.GetOffsets()
  385. for name, info in offset_dict.items():
  386. self._SetEntryOffsetSize(name, *info)
  387. def CheckSize(self):
  388. """Check that the image contents does not exceed its size, etc."""
  389. contents_size = 0
  390. for entry in self._entries.values():
  391. contents_size = max(contents_size, entry.offset + entry.size)
  392. contents_size -= self._skip_at_start
  393. size = self.size
  394. if not size:
  395. size = self.pad_before + contents_size + self.pad_after
  396. size = tools.Align(size, self.align_size)
  397. if self.size and contents_size > self.size:
  398. self._Raise("contents size %#x (%d) exceeds section size %#x (%d)" %
  399. (contents_size, contents_size, self.size, self.size))
  400. if not self.size:
  401. self.size = size
  402. if self.size != tools.Align(self.size, self.align_size):
  403. self._Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  404. (self.size, self.size, self.align_size,
  405. self.align_size))
  406. return size
  407. def ListEntries(self, entries, indent):
  408. """List the files in the section"""
  409. Entry.AddEntryInfo(entries, indent, self.name, 'section', self.size,
  410. self.image_pos, None, self.offset, self)
  411. for entry in self._entries.values():
  412. entry.ListEntries(entries, indent + 1)
  413. def LoadData(self, decomp=True):
  414. for entry in self._entries.values():
  415. entry.LoadData(decomp)
  416. self.Detail('Loaded data')
  417. def GetImage(self):
  418. """Get the image containing this section
  419. Note that a top-level section is actually an Image, so this function may
  420. return self.
  421. Returns:
  422. Image object containing this section
  423. """
  424. if not self.section:
  425. return self
  426. return self.section.GetImage()
  427. def GetSort(self):
  428. """Check if the entries in this section will be sorted
  429. Returns:
  430. True if to be sorted, False if entries will be left in the order
  431. they appear in the device tree
  432. """
  433. return self._sort
  434. def ReadData(self, decomp=True):
  435. tout.Info("ReadData path='%s'" % self.GetPath())
  436. parent_data = self.section.ReadData(True)
  437. tout.Info('%s: Reading data from offset %#x-%#x, size %#x' %
  438. (self.GetPath(), self.offset, self.offset + self.size,
  439. self.size))
  440. data = parent_data[self.offset:self.offset + self.size]
  441. return data
  442. def ReadChildData(self, child, decomp=True):
  443. tout.Debug("ReadChildData for child '%s'" % child.GetPath())
  444. parent_data = self.ReadData(True)
  445. offset = child.offset - self._skip_at_start
  446. tout.Debug("Extract for child '%s': offset %#x, skip_at_start %#x, result %#x" %
  447. (child.GetPath(), child.offset, self._skip_at_start, offset))
  448. data = parent_data[offset:offset + child.size]
  449. if decomp:
  450. indata = data
  451. data = tools.Decompress(indata, child.compress)
  452. if child.uncomp_size:
  453. tout.Info("%s: Decompressing data size %#x with algo '%s' to data size %#x" %
  454. (child.GetPath(), len(indata), child.compress,
  455. len(data)))
  456. return data
  457. def WriteChildData(self, child):
  458. return True