section.py 25 KB

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