entry.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951
  1. # SPDX-License-Identifier: GPL-2.0+
  2. # Copyright (c) 2016 Google, Inc
  3. #
  4. # Base class for all entries
  5. #
  6. from collections import namedtuple
  7. import importlib
  8. import os
  9. import sys
  10. from dtoc import fdt_util
  11. from patman import tools
  12. from patman.tools import ToHex, ToHexSize
  13. from patman import tout
  14. modules = {}
  15. # An argument which can be passed to entries on the command line, in lieu of
  16. # device-tree properties.
  17. EntryArg = namedtuple('EntryArg', ['name', 'datatype'])
  18. # Information about an entry for use when displaying summaries
  19. EntryInfo = namedtuple('EntryInfo', ['indent', 'name', 'etype', 'size',
  20. 'image_pos', 'uncomp_size', 'offset',
  21. 'entry'])
  22. class Entry(object):
  23. """An Entry in the section
  24. An entry corresponds to a single node in the device-tree description
  25. of the section. Each entry ends up being a part of the final section.
  26. Entries can be placed either right next to each other, or with padding
  27. between them. The type of the entry determines the data that is in it.
  28. This class is not used by itself. All entry objects are subclasses of
  29. Entry.
  30. Attributes:
  31. section: Section object containing this entry
  32. node: The node that created this entry
  33. offset: Offset of entry within the section, None if not known yet (in
  34. which case it will be calculated by Pack())
  35. size: Entry size in bytes, None if not known
  36. pre_reset_size: size as it was before ResetForPack(). This allows us to
  37. keep track of the size we started with and detect size changes
  38. uncomp_size: Size of uncompressed data in bytes, if the entry is
  39. compressed, else None
  40. contents_size: Size of contents in bytes, 0 by default
  41. align: Entry start offset alignment relative to the start of the
  42. containing section, or None
  43. align_size: Entry size alignment, or None
  44. align_end: Entry end offset alignment relative to the start of the
  45. containing section, or None
  46. pad_before: Number of pad bytes before the contents when it is placed
  47. in the containing section, 0 if none. The pad bytes become part of
  48. the entry.
  49. pad_after: Number of pad bytes after the contents when it is placed in
  50. the containing section, 0 if none. The pad bytes become part of
  51. the entry.
  52. data: Contents of entry (string of bytes). This does not include
  53. padding created by pad_before or pad_after. If the entry is
  54. compressed, this contains the compressed data.
  55. uncomp_data: Original uncompressed data, if this entry is compressed,
  56. else None
  57. compress: Compression algoithm used (e.g. 'lz4'), 'none' if none
  58. orig_offset: Original offset value read from node
  59. orig_size: Original size value read from node
  60. missing: True if this entry is missing its contents
  61. allow_missing: Allow children of this entry to be missing (used by
  62. subclasses such as Entry_section)
  63. external: True if this entry contains an external binary blob
  64. """
  65. def __init__(self, section, etype, node, name_prefix=''):
  66. # Put this here to allow entry-docs and help to work without libfdt
  67. global state
  68. from binman import state
  69. self.section = section
  70. self.etype = etype
  71. self._node = node
  72. self.name = node and (name_prefix + node.name) or 'none'
  73. self.offset = None
  74. self.size = None
  75. self.pre_reset_size = None
  76. self.uncomp_size = None
  77. self.data = None
  78. self.uncomp_data = None
  79. self.contents_size = 0
  80. self.align = None
  81. self.align_size = None
  82. self.align_end = None
  83. self.pad_before = 0
  84. self.pad_after = 0
  85. self.offset_unset = False
  86. self.image_pos = None
  87. self._expand_size = False
  88. self.compress = 'none'
  89. self.missing = False
  90. self.external = False
  91. self.allow_missing = False
  92. @staticmethod
  93. def Lookup(node_path, etype, expanded):
  94. """Look up the entry class for a node.
  95. Args:
  96. node_node: Path name of Node object containing information about
  97. the entry to create (used for errors)
  98. etype: Entry type to use
  99. expanded: Use the expanded version of etype
  100. Returns:
  101. The entry class object if found, else None if not found and expanded
  102. is True
  103. Raise:
  104. ValueError if expanded is False and the class is not found
  105. """
  106. # Convert something like 'u-boot@0' to 'u_boot' since we are only
  107. # interested in the type.
  108. module_name = etype.replace('-', '_')
  109. if '@' in module_name:
  110. module_name = module_name.split('@')[0]
  111. if expanded:
  112. module_name += '_expanded'
  113. module = modules.get(module_name)
  114. # Also allow entry-type modules to be brought in from the etype directory.
  115. # Import the module if we have not already done so.
  116. if not module:
  117. try:
  118. module = importlib.import_module('binman.etype.' + module_name)
  119. except ImportError as e:
  120. if expanded:
  121. return None
  122. raise ValueError("Unknown entry type '%s' in node '%s' (expected etype/%s.py, error '%s'" %
  123. (etype, node_path, module_name, e))
  124. modules[module_name] = module
  125. # Look up the expected class name
  126. return getattr(module, 'Entry_%s' % module_name)
  127. @staticmethod
  128. def Create(section, node, etype=None, expanded=False):
  129. """Create a new entry for a node.
  130. Args:
  131. section: Section object containing this node
  132. node: Node object containing information about the entry to
  133. create
  134. etype: Entry type to use, or None to work it out (used for tests)
  135. expanded: True to use expanded versions of entries, where available
  136. Returns:
  137. A new Entry object of the correct type (a subclass of Entry)
  138. """
  139. if not etype:
  140. etype = fdt_util.GetString(node, 'type', node.name)
  141. obj = Entry.Lookup(node.path, etype, expanded)
  142. if obj and expanded:
  143. # Check whether to use the expanded entry
  144. new_etype = etype + '-expanded'
  145. if obj.UseExpanded(node, etype, new_etype):
  146. etype = new_etype
  147. else:
  148. obj = None
  149. if not obj:
  150. obj = Entry.Lookup(node.path, etype, False)
  151. # Call its constructor to get the object we want.
  152. return obj(section, etype, node)
  153. def ReadNode(self):
  154. """Read entry information from the node
  155. This must be called as the first thing after the Entry is created.
  156. This reads all the fields we recognise from the node, ready for use.
  157. """
  158. if 'pos' in self._node.props:
  159. self.Raise("Please use 'offset' instead of 'pos'")
  160. self.offset = fdt_util.GetInt(self._node, 'offset')
  161. self.size = fdt_util.GetInt(self._node, 'size')
  162. self.orig_offset = fdt_util.GetInt(self._node, 'orig-offset')
  163. self.orig_size = fdt_util.GetInt(self._node, 'orig-size')
  164. if self.GetImage().copy_to_orig:
  165. self.orig_offset = self.offset
  166. self.orig_size = self.size
  167. # These should not be set in input files, but are set in an FDT map,
  168. # which is also read by this code.
  169. self.image_pos = fdt_util.GetInt(self._node, 'image-pos')
  170. self.uncomp_size = fdt_util.GetInt(self._node, 'uncomp-size')
  171. self.align = fdt_util.GetInt(self._node, 'align')
  172. if tools.NotPowerOfTwo(self.align):
  173. raise ValueError("Node '%s': Alignment %s must be a power of two" %
  174. (self._node.path, self.align))
  175. self.pad_before = fdt_util.GetInt(self._node, 'pad-before', 0)
  176. self.pad_after = fdt_util.GetInt(self._node, 'pad-after', 0)
  177. self.align_size = fdt_util.GetInt(self._node, 'align-size')
  178. if tools.NotPowerOfTwo(self.align_size):
  179. self.Raise("Alignment size %s must be a power of two" %
  180. self.align_size)
  181. self.align_end = fdt_util.GetInt(self._node, 'align-end')
  182. self.offset_unset = fdt_util.GetBool(self._node, 'offset-unset')
  183. self.expand_size = fdt_util.GetBool(self._node, 'expand-size')
  184. self.missing_msg = fdt_util.GetString(self._node, 'missing-msg')
  185. # This is only supported by blobs and sections at present
  186. self.compress = fdt_util.GetString(self._node, 'compress', 'none')
  187. def GetDefaultFilename(self):
  188. return None
  189. def GetFdts(self):
  190. """Get the device trees used by this entry
  191. Returns:
  192. Empty dict, if this entry is not a .dtb, otherwise:
  193. Dict:
  194. key: Filename from this entry (without the path)
  195. value: Tuple:
  196. Entry object for this dtb
  197. Filename of file containing this dtb
  198. """
  199. return {}
  200. def ExpandEntries(self):
  201. """Expand out entries which produce other entries
  202. Some entries generate subnodes automatically, from which sub-entries
  203. are then created. This method allows those to be added to the binman
  204. definition for the current image. An entry which implements this method
  205. should call state.AddSubnode() to add a subnode and can add properties
  206. with state.AddString(), etc.
  207. An example is 'files', which produces a section containing a list of
  208. files.
  209. """
  210. pass
  211. def AddMissingProperties(self, have_image_pos):
  212. """Add new properties to the device tree as needed for this entry
  213. Args:
  214. have_image_pos: True if this entry has an image position. This can
  215. be False if its parent section is compressed, since compression
  216. groups all entries together into a compressed block of data,
  217. obscuring the start of each individual child entry
  218. """
  219. for prop in ['offset', 'size']:
  220. if not prop in self._node.props:
  221. state.AddZeroProp(self._node, prop)
  222. if have_image_pos and 'image-pos' not in self._node.props:
  223. state.AddZeroProp(self._node, 'image-pos')
  224. if self.GetImage().allow_repack:
  225. if self.orig_offset is not None:
  226. state.AddZeroProp(self._node, 'orig-offset', True)
  227. if self.orig_size is not None:
  228. state.AddZeroProp(self._node, 'orig-size', True)
  229. if self.compress != 'none':
  230. state.AddZeroProp(self._node, 'uncomp-size')
  231. err = state.CheckAddHashProp(self._node)
  232. if err:
  233. self.Raise(err)
  234. def SetCalculatedProperties(self):
  235. """Set the value of device-tree properties calculated by binman"""
  236. state.SetInt(self._node, 'offset', self.offset)
  237. state.SetInt(self._node, 'size', self.size)
  238. base = self.section.GetRootSkipAtStart() if self.section else 0
  239. if self.image_pos is not None:
  240. state.SetInt(self._node, 'image-pos', self.image_pos - base)
  241. if self.GetImage().allow_repack:
  242. if self.orig_offset is not None:
  243. state.SetInt(self._node, 'orig-offset', self.orig_offset, True)
  244. if self.orig_size is not None:
  245. state.SetInt(self._node, 'orig-size', self.orig_size, True)
  246. if self.uncomp_size is not None:
  247. state.SetInt(self._node, 'uncomp-size', self.uncomp_size)
  248. state.CheckSetHashValue(self._node, self.GetData)
  249. def ProcessFdt(self, fdt):
  250. """Allow entries to adjust the device tree
  251. Some entries need to adjust the device tree for their purposes. This
  252. may involve adding or deleting properties.
  253. Returns:
  254. True if processing is complete
  255. False if processing could not be completed due to a dependency.
  256. This will cause the entry to be retried after others have been
  257. called
  258. """
  259. return True
  260. def SetPrefix(self, prefix):
  261. """Set the name prefix for a node
  262. Args:
  263. prefix: Prefix to set, or '' to not use a prefix
  264. """
  265. if prefix:
  266. self.name = prefix + self.name
  267. def SetContents(self, data):
  268. """Set the contents of an entry
  269. This sets both the data and content_size properties
  270. Args:
  271. data: Data to set to the contents (bytes)
  272. """
  273. self.data = data
  274. self.contents_size = len(self.data)
  275. def ProcessContentsUpdate(self, data):
  276. """Update the contents of an entry, after the size is fixed
  277. This checks that the new data is the same size as the old. If the size
  278. has changed, this triggers a re-run of the packing algorithm.
  279. Args:
  280. data: Data to set to the contents (bytes)
  281. Raises:
  282. ValueError if the new data size is not the same as the old
  283. """
  284. size_ok = True
  285. new_size = len(data)
  286. if state.AllowEntryExpansion() and new_size > self.contents_size:
  287. # self.data will indicate the new size needed
  288. size_ok = False
  289. elif state.AllowEntryContraction() and new_size < self.contents_size:
  290. size_ok = False
  291. # If not allowed to change, try to deal with it or give up
  292. if size_ok:
  293. if new_size > self.contents_size:
  294. self.Raise('Cannot update entry size from %d to %d' %
  295. (self.contents_size, new_size))
  296. # Don't let the data shrink. Pad it if necessary
  297. if size_ok and new_size < self.contents_size:
  298. data += tools.GetBytes(0, self.contents_size - new_size)
  299. if not size_ok:
  300. tout.Debug("Entry '%s' size change from %s to %s" % (
  301. self._node.path, ToHex(self.contents_size),
  302. ToHex(new_size)))
  303. self.SetContents(data)
  304. return size_ok
  305. def ObtainContents(self):
  306. """Figure out the contents of an entry.
  307. Returns:
  308. True if the contents were found, False if another call is needed
  309. after the other entries are processed.
  310. """
  311. # No contents by default: subclasses can implement this
  312. return True
  313. def ResetForPack(self):
  314. """Reset offset/size fields so that packing can be done again"""
  315. self.Detail('ResetForPack: offset %s->%s, size %s->%s' %
  316. (ToHex(self.offset), ToHex(self.orig_offset),
  317. ToHex(self.size), ToHex(self.orig_size)))
  318. self.pre_reset_size = self.size
  319. self.offset = self.orig_offset
  320. self.size = self.orig_size
  321. def Pack(self, offset):
  322. """Figure out how to pack the entry into the section
  323. Most of the time the entries are not fully specified. There may be
  324. an alignment but no size. In that case we take the size from the
  325. contents of the entry.
  326. If an entry has no hard-coded offset, it will be placed at @offset.
  327. Once this function is complete, both the offset and size of the
  328. entry will be know.
  329. Args:
  330. Current section offset pointer
  331. Returns:
  332. New section offset pointer (after this entry)
  333. """
  334. self.Detail('Packing: offset=%s, size=%s, content_size=%x' %
  335. (ToHex(self.offset), ToHex(self.size),
  336. self.contents_size))
  337. if self.offset is None:
  338. if self.offset_unset:
  339. self.Raise('No offset set with offset-unset: should another '
  340. 'entry provide this correct offset?')
  341. self.offset = tools.Align(offset, self.align)
  342. needed = self.pad_before + self.contents_size + self.pad_after
  343. needed = tools.Align(needed, self.align_size)
  344. size = self.size
  345. if not size:
  346. size = needed
  347. new_offset = self.offset + size
  348. aligned_offset = tools.Align(new_offset, self.align_end)
  349. if aligned_offset != new_offset:
  350. size = aligned_offset - self.offset
  351. new_offset = aligned_offset
  352. if not self.size:
  353. self.size = size
  354. if self.size < needed:
  355. self.Raise("Entry contents size is %#x (%d) but entry size is "
  356. "%#x (%d)" % (needed, needed, self.size, self.size))
  357. # Check that the alignment is correct. It could be wrong if the
  358. # and offset or size values were provided (i.e. not calculated), but
  359. # conflict with the provided alignment values
  360. if self.size != tools.Align(self.size, self.align_size):
  361. self.Raise("Size %#x (%d) does not match align-size %#x (%d)" %
  362. (self.size, self.size, self.align_size, self.align_size))
  363. if self.offset != tools.Align(self.offset, self.align):
  364. self.Raise("Offset %#x (%d) does not match align %#x (%d)" %
  365. (self.offset, self.offset, self.align, self.align))
  366. self.Detail(' - packed: offset=%#x, size=%#x, content_size=%#x, next_offset=%x' %
  367. (self.offset, self.size, self.contents_size, new_offset))
  368. return new_offset
  369. def Raise(self, msg):
  370. """Convenience function to raise an error referencing a node"""
  371. raise ValueError("Node '%s': %s" % (self._node.path, msg))
  372. def Detail(self, msg):
  373. """Convenience function to log detail referencing a node"""
  374. tag = "Node '%s'" % self._node.path
  375. tout.Detail('%30s: %s' % (tag, msg))
  376. def GetEntryArgsOrProps(self, props, required=False):
  377. """Return the values of a set of properties
  378. Args:
  379. props: List of EntryArg objects
  380. Raises:
  381. ValueError if a property is not found
  382. """
  383. values = []
  384. missing = []
  385. for prop in props:
  386. python_prop = prop.name.replace('-', '_')
  387. if hasattr(self, python_prop):
  388. value = getattr(self, python_prop)
  389. else:
  390. value = None
  391. if value is None:
  392. value = self.GetArg(prop.name, prop.datatype)
  393. if value is None and required:
  394. missing.append(prop.name)
  395. values.append(value)
  396. if missing:
  397. self.GetImage().MissingArgs(self, missing)
  398. return values
  399. def GetPath(self):
  400. """Get the path of a node
  401. Returns:
  402. Full path of the node for this entry
  403. """
  404. return self._node.path
  405. def GetData(self):
  406. """Get the contents of an entry
  407. Returns:
  408. bytes content of the entry, excluding any padding. If the entry is
  409. compressed, the compressed data is returned
  410. """
  411. self.Detail('GetData: size %s' % ToHexSize(self.data))
  412. return self.data
  413. def GetPaddedData(self, data=None):
  414. """Get the data for an entry including any padding
  415. Gets the entry data and uses its section's pad-byte value to add padding
  416. before and after as defined by the pad-before and pad-after properties.
  417. This does not consider alignment.
  418. Returns:
  419. Contents of the entry along with any pad bytes before and
  420. after it (bytes)
  421. """
  422. if data is None:
  423. data = self.GetData()
  424. return self.section.GetPaddedDataForEntry(self, data)
  425. def GetOffsets(self):
  426. """Get the offsets for siblings
  427. Some entry types can contain information about the position or size of
  428. other entries. An example of this is the Intel Flash Descriptor, which
  429. knows where the Intel Management Engine section should go.
  430. If this entry knows about the position of other entries, it can specify
  431. this by returning values here
  432. Returns:
  433. Dict:
  434. key: Entry type
  435. value: List containing position and size of the given entry
  436. type. Either can be None if not known
  437. """
  438. return {}
  439. def SetOffsetSize(self, offset, size):
  440. """Set the offset and/or size of an entry
  441. Args:
  442. offset: New offset, or None to leave alone
  443. size: New size, or None to leave alone
  444. """
  445. if offset is not None:
  446. self.offset = offset
  447. if size is not None:
  448. self.size = size
  449. def SetImagePos(self, image_pos):
  450. """Set the position in the image
  451. Args:
  452. image_pos: Position of this entry in the image
  453. """
  454. self.image_pos = image_pos + self.offset
  455. def ProcessContents(self):
  456. """Do any post-packing updates of entry contents
  457. This function should call ProcessContentsUpdate() to update the entry
  458. contents, if necessary, returning its return value here.
  459. Args:
  460. data: Data to set to the contents (bytes)
  461. Returns:
  462. True if the new data size is OK, False if expansion is needed
  463. Raises:
  464. ValueError if the new data size is not the same as the old and
  465. state.AllowEntryExpansion() is False
  466. """
  467. return True
  468. def WriteSymbols(self, section):
  469. """Write symbol values into binary files for access at run time
  470. Args:
  471. section: Section containing the entry
  472. """
  473. pass
  474. def CheckEntries(self):
  475. """Check that the entry offsets are correct
  476. This is used for entries which have extra offset requirements (other
  477. than having to be fully inside their section). Sub-classes can implement
  478. this function and raise if there is a problem.
  479. """
  480. pass
  481. @staticmethod
  482. def GetStr(value):
  483. if value is None:
  484. return '<none> '
  485. return '%08x' % value
  486. @staticmethod
  487. def WriteMapLine(fd, indent, name, offset, size, image_pos):
  488. print('%s %s%s %s %s' % (Entry.GetStr(image_pos), ' ' * indent,
  489. Entry.GetStr(offset), Entry.GetStr(size),
  490. name), file=fd)
  491. def WriteMap(self, fd, indent):
  492. """Write a map of the entry to a .map file
  493. Args:
  494. fd: File to write the map to
  495. indent: Curent indent level of map (0=none, 1=one level, etc.)
  496. """
  497. self.WriteMapLine(fd, indent, self.name, self.offset, self.size,
  498. self.image_pos)
  499. def GetEntries(self):
  500. """Return a list of entries contained by this entry
  501. Returns:
  502. List of entries, or None if none. A normal entry has no entries
  503. within it so will return None
  504. """
  505. return None
  506. def GetArg(self, name, datatype=str):
  507. """Get the value of an entry argument or device-tree-node property
  508. Some node properties can be provided as arguments to binman. First check
  509. the entry arguments, and fall back to the device tree if not found
  510. Args:
  511. name: Argument name
  512. datatype: Data type (str or int)
  513. Returns:
  514. Value of argument as a string or int, or None if no value
  515. Raises:
  516. ValueError if the argument cannot be converted to in
  517. """
  518. value = state.GetEntryArg(name)
  519. if value is not None:
  520. if datatype == int:
  521. try:
  522. value = int(value)
  523. except ValueError:
  524. self.Raise("Cannot convert entry arg '%s' (value '%s') to integer" %
  525. (name, value))
  526. elif datatype == str:
  527. pass
  528. else:
  529. raise ValueError("GetArg() internal error: Unknown data type '%s'" %
  530. datatype)
  531. else:
  532. value = fdt_util.GetDatatype(self._node, name, datatype)
  533. return value
  534. @staticmethod
  535. def WriteDocs(modules, test_missing=None):
  536. """Write out documentation about the various entry types to stdout
  537. Args:
  538. modules: List of modules to include
  539. test_missing: Used for testing. This is a module to report
  540. as missing
  541. """
  542. print('''Binman Entry Documentation
  543. ===========================
  544. This file describes the entry types supported by binman. These entry types can
  545. be placed in an image one by one to build up a final firmware image. It is
  546. fairly easy to create new entry types. Just add a new file to the 'etype'
  547. directory. You can use the existing entries as examples.
  548. Note that some entries are subclasses of others, using and extending their
  549. features to produce new behaviours.
  550. ''')
  551. modules = sorted(modules)
  552. # Don't show the test entry
  553. if '_testing' in modules:
  554. modules.remove('_testing')
  555. missing = []
  556. for name in modules:
  557. module = Entry.Lookup('WriteDocs', name, False)
  558. docs = getattr(module, '__doc__')
  559. if test_missing == name:
  560. docs = None
  561. if docs:
  562. lines = docs.splitlines()
  563. first_line = lines[0]
  564. rest = [line[4:] for line in lines[1:]]
  565. hdr = 'Entry: %s: %s' % (name.replace('_', '-'), first_line)
  566. print(hdr)
  567. print('-' * len(hdr))
  568. print('\n'.join(rest))
  569. print()
  570. print()
  571. else:
  572. missing.append(name)
  573. if missing:
  574. raise ValueError('Documentation is missing for modules: %s' %
  575. ', '.join(missing))
  576. def GetUniqueName(self):
  577. """Get a unique name for a node
  578. Returns:
  579. String containing a unique name for a node, consisting of the name
  580. of all ancestors (starting from within the 'binman' node) separated
  581. by a dot ('.'). This can be useful for generating unique filesnames
  582. in the output directory.
  583. """
  584. name = self.name
  585. node = self._node
  586. while node.parent:
  587. node = node.parent
  588. if node.name == 'binman':
  589. break
  590. name = '%s.%s' % (node.name, name)
  591. return name
  592. def ExpandToLimit(self, limit):
  593. """Expand an entry so that it ends at the given offset limit"""
  594. if self.offset + self.size < limit:
  595. self.size = limit - self.offset
  596. # Request the contents again, since changing the size requires that
  597. # the data grows. This should not fail, but check it to be sure.
  598. if not self.ObtainContents():
  599. self.Raise('Cannot obtain contents when expanding entry')
  600. def HasSibling(self, name):
  601. """Check if there is a sibling of a given name
  602. Returns:
  603. True if there is an entry with this name in the the same section,
  604. else False
  605. """
  606. return name in self.section.GetEntries()
  607. def GetSiblingImagePos(self, name):
  608. """Return the image position of the given sibling
  609. Returns:
  610. Image position of sibling, or None if the sibling has no position,
  611. or False if there is no such sibling
  612. """
  613. if not self.HasSibling(name):
  614. return False
  615. return self.section.GetEntries()[name].image_pos
  616. @staticmethod
  617. def AddEntryInfo(entries, indent, name, etype, size, image_pos,
  618. uncomp_size, offset, entry):
  619. """Add a new entry to the entries list
  620. Args:
  621. entries: List (of EntryInfo objects) to add to
  622. indent: Current indent level to add to list
  623. name: Entry name (string)
  624. etype: Entry type (string)
  625. size: Entry size in bytes (int)
  626. image_pos: Position within image in bytes (int)
  627. uncomp_size: Uncompressed size if the entry uses compression, else
  628. None
  629. offset: Entry offset within parent in bytes (int)
  630. entry: Entry object
  631. """
  632. entries.append(EntryInfo(indent, name, etype, size, image_pos,
  633. uncomp_size, offset, entry))
  634. def ListEntries(self, entries, indent):
  635. """Add files in this entry to the list of entries
  636. This can be overridden by subclasses which need different behaviour.
  637. Args:
  638. entries: List (of EntryInfo objects) to add to
  639. indent: Current indent level to add to list
  640. """
  641. self.AddEntryInfo(entries, indent, self.name, self.etype, self.size,
  642. self.image_pos, self.uncomp_size, self.offset, self)
  643. def ReadData(self, decomp=True):
  644. """Read the data for an entry from the image
  645. This is used when the image has been read in and we want to extract the
  646. data for a particular entry from that image.
  647. Args:
  648. decomp: True to decompress any compressed data before returning it;
  649. False to return the raw, uncompressed data
  650. Returns:
  651. Entry data (bytes)
  652. """
  653. # Use True here so that we get an uncompressed section to work from,
  654. # although compressed sections are currently not supported
  655. tout.Debug("ReadChildData section '%s', entry '%s'" %
  656. (self.section.GetPath(), self.GetPath()))
  657. data = self.section.ReadChildData(self, decomp)
  658. return data
  659. def ReadChildData(self, child, decomp=True):
  660. """Read the data for a particular child entry
  661. This reads data from the parent and extracts the piece that relates to
  662. the given child.
  663. Args:
  664. child: Child entry to read data for (must be valid)
  665. decomp: True to decompress any compressed data before returning it;
  666. False to return the raw, uncompressed data
  667. Returns:
  668. Data for the child (bytes)
  669. """
  670. pass
  671. def LoadData(self, decomp=True):
  672. data = self.ReadData(decomp)
  673. self.contents_size = len(data)
  674. self.ProcessContentsUpdate(data)
  675. self.Detail('Loaded data size %x' % len(data))
  676. def GetImage(self):
  677. """Get the image containing this entry
  678. Returns:
  679. Image object containing this entry
  680. """
  681. return self.section.GetImage()
  682. def WriteData(self, data, decomp=True):
  683. """Write the data to an entry in the image
  684. This is used when the image has been read in and we want to replace the
  685. data for a particular entry in that image.
  686. The image must be re-packed and written out afterwards.
  687. Args:
  688. data: Data to replace it with
  689. decomp: True to compress the data if needed, False if data is
  690. already compressed so should be used as is
  691. Returns:
  692. True if the data did not result in a resize of this entry, False if
  693. the entry must be resized
  694. """
  695. if self.size is not None:
  696. self.contents_size = self.size
  697. else:
  698. self.contents_size = self.pre_reset_size
  699. ok = self.ProcessContentsUpdate(data)
  700. self.Detail('WriteData: size=%x, ok=%s' % (len(data), ok))
  701. section_ok = self.section.WriteChildData(self)
  702. return ok and section_ok
  703. def WriteChildData(self, child):
  704. """Handle writing the data in a child entry
  705. This should be called on the child's parent section after the child's
  706. data has been updated. It
  707. This base-class implementation does nothing, since the base Entry object
  708. does not have any children.
  709. Args:
  710. child: Child Entry that was written
  711. Returns:
  712. True if the section could be updated successfully, False if the
  713. data is such that the section could not updat
  714. """
  715. return True
  716. def GetSiblingOrder(self):
  717. """Get the relative order of an entry amoung its siblings
  718. Returns:
  719. 'start' if this entry is first among siblings, 'end' if last,
  720. otherwise None
  721. """
  722. entries = list(self.section.GetEntries().values())
  723. if entries:
  724. if self == entries[0]:
  725. return 'start'
  726. elif self == entries[-1]:
  727. return 'end'
  728. return 'middle'
  729. def SetAllowMissing(self, allow_missing):
  730. """Set whether a section allows missing external blobs
  731. Args:
  732. allow_missing: True if allowed, False if not allowed
  733. """
  734. # This is meaningless for anything other than sections
  735. pass
  736. def CheckMissing(self, missing_list):
  737. """Check if any entries in this section have missing external blobs
  738. If there are missing blobs, the entries are added to the list
  739. Args:
  740. missing_list: List of Entry objects to be added to
  741. """
  742. if self.missing:
  743. missing_list.append(self)
  744. def GetAllowMissing(self):
  745. """Get whether a section allows missing external blobs
  746. Returns:
  747. True if allowed, False if not allowed
  748. """
  749. return self.allow_missing
  750. def GetHelpTags(self):
  751. """Get the tags use for missing-blob help
  752. Returns:
  753. list of possible tags, most desirable first
  754. """
  755. return list(filter(None, [self.missing_msg, self.name, self.etype]))
  756. def CompressData(self, indata):
  757. """Compress data according to the entry's compression method
  758. Args:
  759. indata: Data to compress
  760. Returns:
  761. Compressed data (first word is the compressed size)
  762. """
  763. self.uncomp_data = indata
  764. if self.compress != 'none':
  765. self.uncomp_size = len(indata)
  766. data = tools.Compress(indata, self.compress)
  767. return data
  768. @classmethod
  769. def UseExpanded(cls, node, etype, new_etype):
  770. """Check whether to use an expanded entry type
  771. This is called by Entry.Create() when it finds an expanded version of
  772. an entry type (e.g. 'u-boot-expanded'). If this method returns True then
  773. it will be used (e.g. in place of 'u-boot'). If it returns False, it is
  774. ignored.
  775. Args:
  776. node: Node object containing information about the entry to
  777. create
  778. etype: Original entry type being used
  779. new_etype: New entry type proposed
  780. Returns:
  781. True to use this entry type, False to use the original one
  782. """
  783. tout.Info("Node '%s': etype '%s': %s selected" %
  784. (node.path, etype, new_etype))
  785. return True