entry.py 35 KB

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