fdt.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. #!/usr/bin/python
  2. # SPDX-License-Identifier: GPL-2.0+
  3. #
  4. # Copyright (C) 2016 Google, Inc
  5. # Written by Simon Glass <sjg@chromium.org>
  6. #
  7. from enum import IntEnum
  8. import struct
  9. import sys
  10. from dtoc import fdt_util
  11. import libfdt
  12. from libfdt import QUIET_NOTFOUND
  13. from patman import tools
  14. # This deals with a device tree, presenting it as an assortment of Node and
  15. # Prop objects, representing nodes and properties, respectively. This file
  16. # contains the base classes and defines the high-level API. You can use
  17. # FdtScan() as a convenience function to create and scan an Fdt.
  18. # This implementation uses a libfdt Python library to access the device tree,
  19. # so it is fairly efficient.
  20. # A list of types we support
  21. class Type(IntEnum):
  22. # Types in order from widest to narrowest
  23. (BYTE, INT, STRING, BOOL, INT64) = range(5)
  24. def needs_widening(self, other):
  25. """Check if this type needs widening to hold a value from another type
  26. A wider type is one that can hold a wider array of information than
  27. another one, or is less restrictive, so it can hold the information of
  28. another type as well as its own. This is similar to the concept of
  29. type-widening in C.
  30. This uses a simple arithmetic comparison, since type values are in order
  31. from widest (BYTE) to narrowest (INT64).
  32. Args:
  33. other: Other type to compare against
  34. Return:
  35. True if the other type is wider
  36. """
  37. return self.value > other.value
  38. def CheckErr(errnum, msg):
  39. if errnum:
  40. raise ValueError('Error %d: %s: %s' %
  41. (errnum, libfdt.fdt_strerror(errnum), msg))
  42. def BytesToValue(data):
  43. """Converts a string of bytes into a type and value
  44. Args:
  45. A bytes value (which on Python 2 is an alias for str)
  46. Return:
  47. A tuple:
  48. Type of data
  49. Data, either a single element or a list of elements. Each element
  50. is one of:
  51. Type.STRING: str/bytes value from the property
  52. Type.INT: a byte-swapped integer stored as a 4-byte str/bytes
  53. Type.BYTE: a byte stored as a single-byte str/bytes
  54. """
  55. data = bytes(data)
  56. size = len(data)
  57. strings = data.split(b'\0')
  58. is_string = True
  59. count = len(strings) - 1
  60. if count > 0 and not len(strings[-1]):
  61. for string in strings[:-1]:
  62. if not string:
  63. is_string = False
  64. break
  65. for ch in string:
  66. if ch < 32 or ch > 127:
  67. is_string = False
  68. break
  69. else:
  70. is_string = False
  71. if is_string:
  72. if count == 1:
  73. return Type.STRING, strings[0].decode()
  74. else:
  75. return Type.STRING, [s.decode() for s in strings[:-1]]
  76. if size % 4:
  77. if size == 1:
  78. return Type.BYTE, chr(data[0])
  79. else:
  80. return Type.BYTE, [chr(ch) for ch in list(data)]
  81. val = []
  82. for i in range(0, size, 4):
  83. val.append(data[i:i + 4])
  84. if size == 4:
  85. return Type.INT, val[0]
  86. else:
  87. return Type.INT, val
  88. class Prop:
  89. """A device tree property
  90. Properties:
  91. node: Node containing this property
  92. offset: Offset of the property (None if still to be synced)
  93. name: Property name (as per the device tree)
  94. value: Property value as a string of bytes, or a list of strings of
  95. bytes
  96. type: Value type
  97. """
  98. def __init__(self, node, offset, name, data):
  99. self._node = node
  100. self._offset = offset
  101. self.name = name
  102. self.value = None
  103. self.bytes = bytes(data)
  104. self.dirty = offset is None
  105. if not data:
  106. self.type = Type.BOOL
  107. self.value = True
  108. return
  109. self.type, self.value = BytesToValue(bytes(data))
  110. def RefreshOffset(self, poffset):
  111. self._offset = poffset
  112. def Widen(self, newprop):
  113. """Figure out which property type is more general
  114. Given a current property and a new property, this function returns the
  115. one that is less specific as to type. The less specific property will
  116. be ble to represent the data in the more specific property. This is
  117. used for things like:
  118. node1 {
  119. compatible = "fred";
  120. value = <1>;
  121. };
  122. node1 {
  123. compatible = "fred";
  124. value = <1 2>;
  125. };
  126. He we want to use an int array for 'value'. The first property
  127. suggests that a single int is enough, but the second one shows that
  128. it is not. Calling this function with these two propertes would
  129. update the current property to be like the second, since it is less
  130. specific.
  131. """
  132. if self.type.needs_widening(newprop.type):
  133. if self.type == Type.INT and newprop.type == Type.BYTE:
  134. if type(self.value) == list:
  135. new_value = []
  136. for val in self.value:
  137. new_value += [chr(by) for by in val]
  138. else:
  139. new_value = [chr(by) for by in self.value]
  140. self.value = new_value
  141. self.type = newprop.type
  142. if type(newprop.value) == list:
  143. if type(self.value) != list:
  144. self.value = [self.value]
  145. if len(newprop.value) > len(self.value):
  146. val = self.GetEmpty(self.type)
  147. while len(self.value) < len(newprop.value):
  148. self.value.append(val)
  149. @classmethod
  150. def GetEmpty(self, type):
  151. """Get an empty / zero value of the given type
  152. Returns:
  153. A single value of the given type
  154. """
  155. if type == Type.BYTE:
  156. return chr(0)
  157. elif type == Type.INT:
  158. return struct.pack('>I', 0);
  159. elif type == Type.STRING:
  160. return ''
  161. else:
  162. return True
  163. def GetOffset(self):
  164. """Get the offset of a property
  165. Returns:
  166. The offset of the property (struct fdt_property) within the file
  167. """
  168. self._node._fdt.CheckCache()
  169. return self._node._fdt.GetStructOffset(self._offset)
  170. def SetInt(self, val):
  171. """Set the integer value of the property
  172. The device tree is marked dirty so that the value will be written to
  173. the block on the next sync.
  174. Args:
  175. val: Integer value (32-bit, single cell)
  176. """
  177. self.bytes = struct.pack('>I', val);
  178. self.value = self.bytes
  179. self.type = Type.INT
  180. self.dirty = True
  181. def SetData(self, bytes):
  182. """Set the value of a property as bytes
  183. Args:
  184. bytes: New property value to set
  185. """
  186. self.bytes = bytes
  187. self.type, self.value = BytesToValue(bytes)
  188. self.dirty = True
  189. def Sync(self, auto_resize=False):
  190. """Sync property changes back to the device tree
  191. This updates the device tree blob with any changes to this property
  192. since the last sync.
  193. Args:
  194. auto_resize: Resize the device tree automatically if it does not
  195. have enough space for the update
  196. Raises:
  197. FdtException if auto_resize is False and there is not enough space
  198. """
  199. if self.dirty:
  200. node = self._node
  201. fdt_obj = node._fdt._fdt_obj
  202. node_name = fdt_obj.get_name(node._offset)
  203. if node_name and node_name != node.name:
  204. raise ValueError("Internal error, node '%s' name mismatch '%s'" %
  205. (node.path, node_name))
  206. if auto_resize:
  207. while fdt_obj.setprop(node.Offset(), self.name, self.bytes,
  208. (libfdt.NOSPACE,)) == -libfdt.NOSPACE:
  209. fdt_obj.resize(fdt_obj.totalsize() + 1024 +
  210. len(self.bytes))
  211. fdt_obj.setprop(node.Offset(), self.name, self.bytes)
  212. else:
  213. fdt_obj.setprop(node.Offset(), self.name, self.bytes)
  214. self.dirty = False
  215. class Node:
  216. """A device tree node
  217. Properties:
  218. parent: Parent Node
  219. offset: Integer offset in the device tree (None if to be synced)
  220. name: Device tree node tname
  221. path: Full path to node, along with the node name itself
  222. _fdt: Device tree object
  223. subnodes: A list of subnodes for this node, each a Node object
  224. props: A dict of properties for this node, each a Prop object.
  225. Keyed by property name
  226. """
  227. def __init__(self, fdt, parent, offset, name, path):
  228. self._fdt = fdt
  229. self.parent = parent
  230. self._offset = offset
  231. self.name = name
  232. self.path = path
  233. self.subnodes = []
  234. self.props = {}
  235. def GetFdt(self):
  236. """Get the Fdt object for this node
  237. Returns:
  238. Fdt object
  239. """
  240. return self._fdt
  241. def FindNode(self, name):
  242. """Find a node given its name
  243. Args:
  244. name: Node name to look for
  245. Returns:
  246. Node object if found, else None
  247. """
  248. for subnode in self.subnodes:
  249. if subnode.name == name:
  250. return subnode
  251. return None
  252. def Offset(self):
  253. """Returns the offset of a node, after checking the cache
  254. This should be used instead of self._offset directly, to ensure that
  255. the cache does not contain invalid offsets.
  256. """
  257. self._fdt.CheckCache()
  258. return self._offset
  259. def Scan(self):
  260. """Scan a node's properties and subnodes
  261. This fills in the props and subnodes properties, recursively
  262. searching into subnodes so that the entire tree is built.
  263. """
  264. fdt_obj = self._fdt._fdt_obj
  265. self.props = self._fdt.GetProps(self)
  266. phandle = fdt_obj.get_phandle(self.Offset())
  267. if phandle:
  268. self._fdt.phandle_to_node[phandle] = self
  269. offset = fdt_obj.first_subnode(self.Offset(), QUIET_NOTFOUND)
  270. while offset >= 0:
  271. sep = '' if self.path[-1] == '/' else '/'
  272. name = fdt_obj.get_name(offset)
  273. path = self.path + sep + name
  274. node = Node(self._fdt, self, offset, name, path)
  275. self.subnodes.append(node)
  276. node.Scan()
  277. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  278. def Refresh(self, my_offset):
  279. """Fix up the _offset for each node, recursively
  280. Note: This does not take account of property offsets - these will not
  281. be updated.
  282. """
  283. fdt_obj = self._fdt._fdt_obj
  284. if self._offset != my_offset:
  285. self._offset = my_offset
  286. name = fdt_obj.get_name(self._offset)
  287. if name and self.name != name:
  288. raise ValueError("Internal error, node '%s' name mismatch '%s'" %
  289. (self.path, name))
  290. offset = fdt_obj.first_subnode(self._offset, QUIET_NOTFOUND)
  291. for subnode in self.subnodes:
  292. if subnode.name != fdt_obj.get_name(offset):
  293. raise ValueError('Internal error, node name mismatch %s != %s' %
  294. (subnode.name, fdt_obj.get_name(offset)))
  295. subnode.Refresh(offset)
  296. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  297. if offset != -libfdt.FDT_ERR_NOTFOUND:
  298. raise ValueError('Internal error, offset == %d' % offset)
  299. poffset = fdt_obj.first_property_offset(self._offset, QUIET_NOTFOUND)
  300. while poffset >= 0:
  301. p = fdt_obj.get_property_by_offset(poffset)
  302. prop = self.props.get(p.name)
  303. if not prop:
  304. raise ValueError("Internal error, node '%s' property '%s' missing, "
  305. 'offset %d' % (self.path, p.name, poffset))
  306. prop.RefreshOffset(poffset)
  307. poffset = fdt_obj.next_property_offset(poffset, QUIET_NOTFOUND)
  308. def DeleteProp(self, prop_name):
  309. """Delete a property of a node
  310. The property is deleted and the offset cache is invalidated.
  311. Args:
  312. prop_name: Name of the property to delete
  313. Raises:
  314. ValueError if the property does not exist
  315. """
  316. CheckErr(self._fdt._fdt_obj.delprop(self.Offset(), prop_name),
  317. "Node '%s': delete property: '%s'" % (self.path, prop_name))
  318. del self.props[prop_name]
  319. self._fdt.Invalidate()
  320. def AddZeroProp(self, prop_name):
  321. """Add a new property to the device tree with an integer value of 0.
  322. Args:
  323. prop_name: Name of property
  324. """
  325. self.props[prop_name] = Prop(self, None, prop_name,
  326. tools.GetBytes(0, 4))
  327. def AddEmptyProp(self, prop_name, len):
  328. """Add a property with a fixed data size, for filling in later
  329. The device tree is marked dirty so that the value will be written to
  330. the blob on the next sync.
  331. Args:
  332. prop_name: Name of property
  333. len: Length of data in property
  334. """
  335. value = tools.GetBytes(0, len)
  336. self.props[prop_name] = Prop(self, None, prop_name, value)
  337. def _CheckProp(self, prop_name):
  338. """Check if a property is present
  339. Args:
  340. prop_name: Name of property
  341. Returns:
  342. self
  343. Raises:
  344. ValueError if the property is missing
  345. """
  346. if prop_name not in self.props:
  347. raise ValueError("Fdt '%s', node '%s': Missing property '%s'" %
  348. (self._fdt._fname, self.path, prop_name))
  349. return self
  350. def SetInt(self, prop_name, val):
  351. """Update an integer property int the device tree.
  352. This is not allowed to change the size of the FDT.
  353. The device tree is marked dirty so that the value will be written to
  354. the blob on the next sync.
  355. Args:
  356. prop_name: Name of property
  357. val: Value to set
  358. """
  359. self._CheckProp(prop_name).props[prop_name].SetInt(val)
  360. def SetData(self, prop_name, val):
  361. """Set the data value of a property
  362. The device tree is marked dirty so that the value will be written to
  363. the blob on the next sync.
  364. Args:
  365. prop_name: Name of property to set
  366. val: Data value to set
  367. """
  368. self._CheckProp(prop_name).props[prop_name].SetData(val)
  369. def SetString(self, prop_name, val):
  370. """Set the string value of a property
  371. The device tree is marked dirty so that the value will be written to
  372. the blob on the next sync.
  373. Args:
  374. prop_name: Name of property to set
  375. val: String value to set (will be \0-terminated in DT)
  376. """
  377. if type(val) == str:
  378. val = val.encode('utf-8')
  379. self._CheckProp(prop_name).props[prop_name].SetData(val + b'\0')
  380. def AddData(self, prop_name, val):
  381. """Add a new property to a node
  382. The device tree is marked dirty so that the value will be written to
  383. the blob on the next sync.
  384. Args:
  385. prop_name: Name of property to add
  386. val: Bytes value of property
  387. Returns:
  388. Prop added
  389. """
  390. prop = Prop(self, None, prop_name, val)
  391. self.props[prop_name] = prop
  392. return prop
  393. def AddString(self, prop_name, val):
  394. """Add a new string property to a node
  395. The device tree is marked dirty so that the value will be written to
  396. the blob on the next sync.
  397. Args:
  398. prop_name: Name of property to add
  399. val: String value of property
  400. Returns:
  401. Prop added
  402. """
  403. val = bytes(val, 'utf-8')
  404. return self.AddData(prop_name, val + b'\0')
  405. def AddInt(self, prop_name, val):
  406. """Add a new integer property to a node
  407. The device tree is marked dirty so that the value will be written to
  408. the blob on the next sync.
  409. Args:
  410. prop_name: Name of property to add
  411. val: Integer value of property
  412. Returns:
  413. Prop added
  414. """
  415. return self.AddData(prop_name, struct.pack('>I', val))
  416. def AddSubnode(self, name):
  417. """Add a new subnode to the node
  418. Args:
  419. name: name of node to add
  420. Returns:
  421. New subnode that was created
  422. """
  423. path = self.path + '/' + name
  424. subnode = Node(self._fdt, self, None, name, path)
  425. self.subnodes.append(subnode)
  426. return subnode
  427. def Sync(self, auto_resize=False):
  428. """Sync node changes back to the device tree
  429. This updates the device tree blob with any changes to this node and its
  430. subnodes since the last sync.
  431. Args:
  432. auto_resize: Resize the device tree automatically if it does not
  433. have enough space for the update
  434. Returns:
  435. True if the node had to be added, False if it already existed
  436. Raises:
  437. FdtException if auto_resize is False and there is not enough space
  438. """
  439. added = False
  440. if self._offset is None:
  441. # The subnode doesn't exist yet, so add it
  442. fdt_obj = self._fdt._fdt_obj
  443. if auto_resize:
  444. while True:
  445. offset = fdt_obj.add_subnode(self.parent._offset, self.name,
  446. (libfdt.NOSPACE,))
  447. if offset != -libfdt.NOSPACE:
  448. break
  449. fdt_obj.resize(fdt_obj.totalsize() + 1024)
  450. else:
  451. offset = fdt_obj.add_subnode(self.parent._offset, self.name)
  452. self._offset = offset
  453. added = True
  454. # Sync the existing subnodes first, so that we can rely on the offsets
  455. # being correct. As soon as we add new subnodes, it pushes all the
  456. # existing subnodes up.
  457. for node in reversed(self.subnodes):
  458. if node._offset is not None:
  459. node.Sync(auto_resize)
  460. # Sync subnodes in reverse so that we get the expected order. Each
  461. # new node goes at the start of the subnode list. This avoids an O(n^2)
  462. # rescan of node offsets.
  463. num_added = 0
  464. for node in reversed(self.subnodes):
  465. if node.Sync(auto_resize):
  466. num_added += 1
  467. if num_added:
  468. # Reorder our list of nodes to put the new ones first, since that's
  469. # what libfdt does
  470. old_count = len(self.subnodes) - num_added
  471. subnodes = self.subnodes[old_count:] + self.subnodes[:old_count]
  472. self.subnodes = subnodes
  473. # Sync properties now, whose offsets should not have been disturbed,
  474. # since properties come before subnodes. This is done after all the
  475. # subnode processing above, since updating properties can disturb the
  476. # offsets of those subnodes.
  477. # Properties are synced in reverse order, with new properties added
  478. # before existing properties are synced. This ensures that the offsets
  479. # of earlier properties are not disturbed.
  480. # Note that new properties will have an offset of None here, which
  481. # Python cannot sort against int. So use a large value instead so that
  482. # new properties are added first.
  483. prop_list = sorted(self.props.values(),
  484. key=lambda prop: prop._offset or 1 << 31,
  485. reverse=True)
  486. for prop in prop_list:
  487. prop.Sync(auto_resize)
  488. return added
  489. class Fdt:
  490. """Provides simple access to a flat device tree blob using libfdts.
  491. Properties:
  492. fname: Filename of fdt
  493. _root: Root of device tree (a Node object)
  494. name: Helpful name for this Fdt for the user (useful when creating the
  495. DT from data rather than a file)
  496. """
  497. def __init__(self, fname):
  498. self._fname = fname
  499. self._cached_offsets = False
  500. self.phandle_to_node = {}
  501. self.name = ''
  502. if self._fname:
  503. self.name = self._fname
  504. self._fname = fdt_util.EnsureCompiled(self._fname)
  505. with open(self._fname, 'rb') as fd:
  506. self._fdt_obj = libfdt.Fdt(fd.read())
  507. @staticmethod
  508. def FromData(data, name=''):
  509. """Create a new Fdt object from the given data
  510. Args:
  511. data: Device-tree data blob
  512. name: Helpful name for this Fdt for the user
  513. Returns:
  514. Fdt object containing the data
  515. """
  516. fdt = Fdt(None)
  517. fdt._fdt_obj = libfdt.Fdt(bytes(data))
  518. fdt.name = name
  519. return fdt
  520. def LookupPhandle(self, phandle):
  521. """Look up a phandle
  522. Args:
  523. phandle: Phandle to look up (int)
  524. Returns:
  525. Node object the phandle points to
  526. """
  527. return self.phandle_to_node.get(phandle)
  528. def Scan(self, root='/'):
  529. """Scan a device tree, building up a tree of Node objects
  530. This fills in the self._root property
  531. Args:
  532. root: Ignored
  533. TODO(sjg@chromium.org): Implement the 'root' parameter
  534. """
  535. self._cached_offsets = True
  536. self._root = self.Node(self, None, 0, '/', '/')
  537. self._root.Scan()
  538. def GetRoot(self):
  539. """Get the root Node of the device tree
  540. Returns:
  541. The root Node object
  542. """
  543. return self._root
  544. def GetNode(self, path):
  545. """Look up a node from its path
  546. Args:
  547. path: Path to look up, e.g. '/microcode/update@0'
  548. Returns:
  549. Node object, or None if not found
  550. """
  551. node = self._root
  552. parts = path.split('/')
  553. if len(parts) < 2:
  554. return None
  555. if len(parts) == 2 and parts[1] == '':
  556. return node
  557. for part in parts[1:]:
  558. node = node.FindNode(part)
  559. if not node:
  560. return None
  561. return node
  562. def Flush(self):
  563. """Flush device tree changes back to the file
  564. If the device tree has changed in memory, write it back to the file.
  565. """
  566. with open(self._fname, 'wb') as fd:
  567. fd.write(self._fdt_obj.as_bytearray())
  568. def Sync(self, auto_resize=False):
  569. """Make sure any DT changes are written to the blob
  570. Args:
  571. auto_resize: Resize the device tree automatically if it does not
  572. have enough space for the update
  573. Raises:
  574. FdtException if auto_resize is False and there is not enough space
  575. """
  576. self.CheckCache()
  577. self._root.Sync(auto_resize)
  578. self.Refresh()
  579. def Pack(self):
  580. """Pack the device tree down to its minimum size
  581. When nodes and properties shrink or are deleted, wasted space can
  582. build up in the device tree binary.
  583. """
  584. CheckErr(self._fdt_obj.pack(), 'pack')
  585. self.Refresh()
  586. def GetContents(self):
  587. """Get the contents of the FDT
  588. Returns:
  589. The FDT contents as a string of bytes
  590. """
  591. return bytes(self._fdt_obj.as_bytearray())
  592. def GetFdtObj(self):
  593. """Get the contents of the FDT
  594. Returns:
  595. The FDT contents as a libfdt.Fdt object
  596. """
  597. return self._fdt_obj
  598. def GetProps(self, node):
  599. """Get all properties from a node.
  600. Args:
  601. node: Full path to node name to look in.
  602. Returns:
  603. A dictionary containing all the properties, indexed by node name.
  604. The entries are Prop objects.
  605. Raises:
  606. ValueError: if the node does not exist.
  607. """
  608. props_dict = {}
  609. poffset = self._fdt_obj.first_property_offset(node._offset,
  610. QUIET_NOTFOUND)
  611. while poffset >= 0:
  612. p = self._fdt_obj.get_property_by_offset(poffset)
  613. prop = Prop(node, poffset, p.name, p)
  614. props_dict[prop.name] = prop
  615. poffset = self._fdt_obj.next_property_offset(poffset,
  616. QUIET_NOTFOUND)
  617. return props_dict
  618. def Invalidate(self):
  619. """Mark our offset cache as invalid"""
  620. self._cached_offsets = False
  621. def CheckCache(self):
  622. """Refresh the offset cache if needed"""
  623. if self._cached_offsets:
  624. return
  625. self.Refresh()
  626. def Refresh(self):
  627. """Refresh the offset cache"""
  628. self._root.Refresh(0)
  629. self._cached_offsets = True
  630. def GetStructOffset(self, offset):
  631. """Get the file offset of a given struct offset
  632. Args:
  633. offset: Offset within the 'struct' region of the device tree
  634. Returns:
  635. Position of @offset within the device tree binary
  636. """
  637. return self._fdt_obj.off_dt_struct() + offset
  638. @classmethod
  639. def Node(self, fdt, parent, offset, name, path):
  640. """Create a new node
  641. This is used by Fdt.Scan() to create a new node using the correct
  642. class.
  643. Args:
  644. fdt: Fdt object
  645. parent: Parent node, or None if this is the root node
  646. offset: Offset of node
  647. name: Node name
  648. path: Full path to node
  649. """
  650. node = Node(fdt, parent, offset, name, path)
  651. return node
  652. def GetFilename(self):
  653. """Get the filename of the device tree
  654. Returns:
  655. String filename
  656. """
  657. return self._fname
  658. def FdtScan(fname):
  659. """Returns a new Fdt object"""
  660. dtb = Fdt(fname)
  661. dtb.Scan()
  662. return dtb