entry.py 32 KB

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