entry.py 29 KB

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