fdt.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461
  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. import struct
  8. import sys
  9. import fdt_util
  10. import libfdt
  11. from libfdt import QUIET_NOTFOUND
  12. # This deals with a device tree, presenting it as an assortment of Node and
  13. # Prop objects, representing nodes and properties, respectively. This file
  14. # contains the base classes and defines the high-level API. You can use
  15. # FdtScan() as a convenience function to create and scan an Fdt.
  16. # This implementation uses a libfdt Python library to access the device tree,
  17. # so it is fairly efficient.
  18. # A list of types we support
  19. (TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL, TYPE_INT64) = range(5)
  20. def CheckErr(errnum, msg):
  21. if errnum:
  22. raise ValueError('Error %d: %s: %s' %
  23. (errnum, libfdt.fdt_strerror(errnum), msg))
  24. class Prop:
  25. """A device tree property
  26. Properties:
  27. name: Property name (as per the device tree)
  28. value: Property value as a string of bytes, or a list of strings of
  29. bytes
  30. type: Value type
  31. """
  32. def __init__(self, node, offset, name, bytes):
  33. self._node = node
  34. self._offset = offset
  35. self.name = name
  36. self.value = None
  37. self.bytes = str(bytes)
  38. if not bytes:
  39. self.type = TYPE_BOOL
  40. self.value = True
  41. return
  42. self.type, self.value = self.BytesToValue(bytes)
  43. def RefreshOffset(self, poffset):
  44. self._offset = poffset
  45. def Widen(self, newprop):
  46. """Figure out which property type is more general
  47. Given a current property and a new property, this function returns the
  48. one that is less specific as to type. The less specific property will
  49. be ble to represent the data in the more specific property. This is
  50. used for things like:
  51. node1 {
  52. compatible = "fred";
  53. value = <1>;
  54. };
  55. node1 {
  56. compatible = "fred";
  57. value = <1 2>;
  58. };
  59. He we want to use an int array for 'value'. The first property
  60. suggests that a single int is enough, but the second one shows that
  61. it is not. Calling this function with these two propertes would
  62. update the current property to be like the second, since it is less
  63. specific.
  64. """
  65. if newprop.type < self.type:
  66. self.type = newprop.type
  67. if type(newprop.value) == list and type(self.value) != list:
  68. self.value = [self.value]
  69. if type(self.value) == list and len(newprop.value) > len(self.value):
  70. val = self.GetEmpty(self.type)
  71. while len(self.value) < len(newprop.value):
  72. self.value.append(val)
  73. def BytesToValue(self, bytes):
  74. """Converts a string of bytes into a type and value
  75. Args:
  76. A string containing bytes
  77. Return:
  78. A tuple:
  79. Type of data
  80. Data, either a single element or a list of elements. Each element
  81. is one of:
  82. TYPE_STRING: string value from the property
  83. TYPE_INT: a byte-swapped integer stored as a 4-byte string
  84. TYPE_BYTE: a byte stored as a single-byte string
  85. """
  86. bytes = str(bytes)
  87. size = len(bytes)
  88. strings = bytes.split('\0')
  89. is_string = True
  90. count = len(strings) - 1
  91. if count > 0 and not strings[-1]:
  92. for string in strings[:-1]:
  93. if not string:
  94. is_string = False
  95. break
  96. for ch in string:
  97. if ch < ' ' or ch > '~':
  98. is_string = False
  99. break
  100. else:
  101. is_string = False
  102. if is_string:
  103. if count == 1:
  104. return TYPE_STRING, strings[0]
  105. else:
  106. return TYPE_STRING, strings[:-1]
  107. if size % 4:
  108. if size == 1:
  109. return TYPE_BYTE, bytes[0]
  110. else:
  111. return TYPE_BYTE, list(bytes)
  112. val = []
  113. for i in range(0, size, 4):
  114. val.append(bytes[i:i + 4])
  115. if size == 4:
  116. return TYPE_INT, val[0]
  117. else:
  118. return TYPE_INT, val
  119. @classmethod
  120. def GetEmpty(self, type):
  121. """Get an empty / zero value of the given type
  122. Returns:
  123. A single value of the given type
  124. """
  125. if type == TYPE_BYTE:
  126. return chr(0)
  127. elif type == TYPE_INT:
  128. return struct.pack('<I', 0);
  129. elif type == TYPE_STRING:
  130. return ''
  131. else:
  132. return True
  133. def GetOffset(self):
  134. """Get the offset of a property
  135. Returns:
  136. The offset of the property (struct fdt_property) within the file
  137. """
  138. self._node._fdt.CheckCache()
  139. return self._node._fdt.GetStructOffset(self._offset)
  140. class Node:
  141. """A device tree node
  142. Properties:
  143. offset: Integer offset in the device tree
  144. name: Device tree node tname
  145. path: Full path to node, along with the node name itself
  146. _fdt: Device tree object
  147. subnodes: A list of subnodes for this node, each a Node object
  148. props: A dict of properties for this node, each a Prop object.
  149. Keyed by property name
  150. """
  151. def __init__(self, fdt, parent, offset, name, path):
  152. self._fdt = fdt
  153. self.parent = parent
  154. self._offset = offset
  155. self.name = name
  156. self.path = path
  157. self.subnodes = []
  158. self.props = {}
  159. def _FindNode(self, name):
  160. """Find a node given its name
  161. Args:
  162. name: Node name to look for
  163. Returns:
  164. Node object if found, else None
  165. """
  166. for subnode in self.subnodes:
  167. if subnode.name == name:
  168. return subnode
  169. return None
  170. def Offset(self):
  171. """Returns the offset of a node, after checking the cache
  172. This should be used instead of self._offset directly, to ensure that
  173. the cache does not contain invalid offsets.
  174. """
  175. self._fdt.CheckCache()
  176. return self._offset
  177. def Scan(self):
  178. """Scan a node's properties and subnodes
  179. This fills in the props and subnodes properties, recursively
  180. searching into subnodes so that the entire tree is built.
  181. """
  182. fdt_obj = self._fdt._fdt_obj
  183. self.props = self._fdt.GetProps(self)
  184. phandle = fdt_obj.get_phandle(self.Offset())
  185. if phandle:
  186. self._fdt.phandle_to_node[phandle] = self
  187. offset = fdt_obj.first_subnode(self.Offset(), QUIET_NOTFOUND)
  188. while offset >= 0:
  189. sep = '' if self.path[-1] == '/' else '/'
  190. name = fdt_obj.get_name(offset)
  191. path = self.path + sep + name
  192. node = Node(self._fdt, self, offset, name, path)
  193. self.subnodes.append(node)
  194. node.Scan()
  195. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  196. def Refresh(self, my_offset):
  197. """Fix up the _offset for each node, recursively
  198. Note: This does not take account of property offsets - these will not
  199. be updated.
  200. """
  201. fdt_obj = self._fdt._fdt_obj
  202. if self._offset != my_offset:
  203. self._offset = my_offset
  204. offset = fdt_obj.first_subnode(self._offset, QUIET_NOTFOUND)
  205. for subnode in self.subnodes:
  206. if subnode.name != fdt_obj.get_name(offset):
  207. raise ValueError('Internal error, node name mismatch %s != %s' %
  208. (subnode.name, fdt_obj.get_name(offset)))
  209. subnode.Refresh(offset)
  210. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  211. if offset != -libfdt.FDT_ERR_NOTFOUND:
  212. raise ValueError('Internal error, offset == %d' % offset)
  213. poffset = fdt_obj.first_property_offset(self._offset, QUIET_NOTFOUND)
  214. while poffset >= 0:
  215. p = fdt_obj.get_property_by_offset(poffset)
  216. prop = self.props.get(p.name)
  217. if not prop:
  218. raise ValueError("Internal error, property '%s' missing, "
  219. 'offset %d' % (p.name, poffset))
  220. prop.RefreshOffset(poffset)
  221. poffset = fdt_obj.next_property_offset(poffset, QUIET_NOTFOUND)
  222. def DeleteProp(self, prop_name):
  223. """Delete a property of a node
  224. The property is deleted and the offset cache is invalidated.
  225. Args:
  226. prop_name: Name of the property to delete
  227. Raises:
  228. ValueError if the property does not exist
  229. """
  230. CheckErr(self._fdt._fdt_obj.delprop(self.Offset(), prop_name),
  231. "Node '%s': delete property: '%s'" % (self.path, prop_name))
  232. del self.props[prop_name]
  233. self._fdt.Invalidate()
  234. def AddZeroProp(self, prop_name):
  235. """Add a new property to the device tree with an integer value of 0.
  236. Args:
  237. prop_name: Name of property
  238. """
  239. fdt_obj = self._fdt._fdt_obj
  240. if fdt_obj.setprop_u32(self.Offset(), prop_name, 0,
  241. (libfdt.NOSPACE,)) == -libfdt.NOSPACE:
  242. fdt_obj.open_into(fdt_obj.totalsize() + 1024)
  243. fdt_obj.setprop_u32(self.Offset(), prop_name, 0)
  244. self.props[prop_name] = Prop(self, -1, prop_name, '\0' * 4)
  245. self._fdt.Invalidate()
  246. def SetInt(self, prop_name, val):
  247. """Update an integer property int the device tree.
  248. This is not allowed to change the size of the FDT.
  249. Args:
  250. prop_name: Name of property
  251. val: Value to set
  252. """
  253. fdt_obj = self._fdt._fdt_obj
  254. fdt_obj.setprop_u32(self.Offset(), prop_name, val)
  255. class Fdt:
  256. """Provides simple access to a flat device tree blob using libfdts.
  257. Properties:
  258. fname: Filename of fdt
  259. _root: Root of device tree (a Node object)
  260. """
  261. def __init__(self, fname):
  262. self._fname = fname
  263. self._cached_offsets = False
  264. self.phandle_to_node = {}
  265. if self._fname:
  266. self._fname = fdt_util.EnsureCompiled(self._fname)
  267. with open(self._fname) as fd:
  268. self._fdt_obj = libfdt.Fdt(fd.read())
  269. def Scan(self, root='/'):
  270. """Scan a device tree, building up a tree of Node objects
  271. This fills in the self._root property
  272. Args:
  273. root: Ignored
  274. TODO(sjg@chromium.org): Implement the 'root' parameter
  275. """
  276. self._cached_offsets = True
  277. self._root = self.Node(self, None, 0, '/', '/')
  278. self._root.Scan()
  279. def GetRoot(self):
  280. """Get the root Node of the device tree
  281. Returns:
  282. The root Node object
  283. """
  284. return self._root
  285. def GetNode(self, path):
  286. """Look up a node from its path
  287. Args:
  288. path: Path to look up, e.g. '/microcode/update@0'
  289. Returns:
  290. Node object, or None if not found
  291. """
  292. node = self._root
  293. parts = path.split('/')
  294. if len(parts) < 2:
  295. return None
  296. for part in parts[1:]:
  297. node = node._FindNode(part)
  298. if not node:
  299. return None
  300. return node
  301. def Flush(self):
  302. """Flush device tree changes back to the file
  303. If the device tree has changed in memory, write it back to the file.
  304. """
  305. with open(self._fname, 'wb') as fd:
  306. fd.write(self._fdt_obj.as_bytearray())
  307. def Pack(self):
  308. """Pack the device tree down to its minimum size
  309. When nodes and properties shrink or are deleted, wasted space can
  310. build up in the device tree binary.
  311. """
  312. CheckErr(self._fdt_obj.pack(), 'pack')
  313. self.Invalidate()
  314. def GetContents(self):
  315. """Get the contents of the FDT
  316. Returns:
  317. The FDT contents as a string of bytes
  318. """
  319. return self._fdt_obj.as_bytearray()
  320. def GetFdtObj(self):
  321. """Get the contents of the FDT
  322. Returns:
  323. The FDT contents as a libfdt.Fdt object
  324. """
  325. return self._fdt_obj
  326. def GetProps(self, node):
  327. """Get all properties from a node.
  328. Args:
  329. node: Full path to node name to look in.
  330. Returns:
  331. A dictionary containing all the properties, indexed by node name.
  332. The entries are Prop objects.
  333. Raises:
  334. ValueError: if the node does not exist.
  335. """
  336. props_dict = {}
  337. poffset = self._fdt_obj.first_property_offset(node._offset,
  338. QUIET_NOTFOUND)
  339. while poffset >= 0:
  340. p = self._fdt_obj.get_property_by_offset(poffset)
  341. prop = Prop(node, poffset, p.name, p)
  342. props_dict[prop.name] = prop
  343. poffset = self._fdt_obj.next_property_offset(poffset,
  344. QUIET_NOTFOUND)
  345. return props_dict
  346. def Invalidate(self):
  347. """Mark our offset cache as invalid"""
  348. self._cached_offsets = False
  349. def CheckCache(self):
  350. """Refresh the offset cache if needed"""
  351. if self._cached_offsets:
  352. return
  353. self.Refresh()
  354. self._cached_offsets = True
  355. def Refresh(self):
  356. """Refresh the offset cache"""
  357. self._root.Refresh(0)
  358. def GetStructOffset(self, offset):
  359. """Get the file offset of a given struct offset
  360. Args:
  361. offset: Offset within the 'struct' region of the device tree
  362. Returns:
  363. Position of @offset within the device tree binary
  364. """
  365. return self._fdt_obj.off_dt_struct() + offset
  366. @classmethod
  367. def Node(self, fdt, parent, offset, name, path):
  368. """Create a new node
  369. This is used by Fdt.Scan() to create a new node using the correct
  370. class.
  371. Args:
  372. fdt: Fdt object
  373. parent: Parent node, or None if this is the root node
  374. offset: Offset of node
  375. name: Node name
  376. path: Full path to node
  377. """
  378. node = Node(fdt, parent, offset, name, path)
  379. return node
  380. def FdtScan(fname):
  381. """Returns a new Fdt object"""
  382. dtb = Fdt(fname)
  383. dtb.Scan()
  384. return dtb