fdt.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480
  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 GetFdt(self):
  160. """Get the Fdt object for this node
  161. Returns:
  162. Fdt object
  163. """
  164. return self._fdt
  165. def FindNode(self, name):
  166. """Find a node given its name
  167. Args:
  168. name: Node name to look for
  169. Returns:
  170. Node object if found, else None
  171. """
  172. for subnode in self.subnodes:
  173. if subnode.name == name:
  174. return subnode
  175. return None
  176. def Offset(self):
  177. """Returns the offset of a node, after checking the cache
  178. This should be used instead of self._offset directly, to ensure that
  179. the cache does not contain invalid offsets.
  180. """
  181. self._fdt.CheckCache()
  182. return self._offset
  183. def Scan(self):
  184. """Scan a node's properties and subnodes
  185. This fills in the props and subnodes properties, recursively
  186. searching into subnodes so that the entire tree is built.
  187. """
  188. fdt_obj = self._fdt._fdt_obj
  189. self.props = self._fdt.GetProps(self)
  190. phandle = fdt_obj.get_phandle(self.Offset())
  191. if phandle:
  192. self._fdt.phandle_to_node[phandle] = self
  193. offset = fdt_obj.first_subnode(self.Offset(), QUIET_NOTFOUND)
  194. while offset >= 0:
  195. sep = '' if self.path[-1] == '/' else '/'
  196. name = fdt_obj.get_name(offset)
  197. path = self.path + sep + name
  198. node = Node(self._fdt, self, offset, name, path)
  199. self.subnodes.append(node)
  200. node.Scan()
  201. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  202. def Refresh(self, my_offset):
  203. """Fix up the _offset for each node, recursively
  204. Note: This does not take account of property offsets - these will not
  205. be updated.
  206. """
  207. fdt_obj = self._fdt._fdt_obj
  208. if self._offset != my_offset:
  209. self._offset = my_offset
  210. offset = fdt_obj.first_subnode(self._offset, QUIET_NOTFOUND)
  211. for subnode in self.subnodes:
  212. if subnode.name != fdt_obj.get_name(offset):
  213. raise ValueError('Internal error, node name mismatch %s != %s' %
  214. (subnode.name, fdt_obj.get_name(offset)))
  215. subnode.Refresh(offset)
  216. offset = fdt_obj.next_subnode(offset, QUIET_NOTFOUND)
  217. if offset != -libfdt.FDT_ERR_NOTFOUND:
  218. raise ValueError('Internal error, offset == %d' % offset)
  219. poffset = fdt_obj.first_property_offset(self._offset, QUIET_NOTFOUND)
  220. while poffset >= 0:
  221. p = fdt_obj.get_property_by_offset(poffset)
  222. prop = self.props.get(p.name)
  223. if not prop:
  224. raise ValueError("Internal error, property '%s' missing, "
  225. 'offset %d' % (p.name, poffset))
  226. prop.RefreshOffset(poffset)
  227. poffset = fdt_obj.next_property_offset(poffset, QUIET_NOTFOUND)
  228. def DeleteProp(self, prop_name):
  229. """Delete a property of a node
  230. The property is deleted and the offset cache is invalidated.
  231. Args:
  232. prop_name: Name of the property to delete
  233. Raises:
  234. ValueError if the property does not exist
  235. """
  236. CheckErr(self._fdt._fdt_obj.delprop(self.Offset(), prop_name),
  237. "Node '%s': delete property: '%s'" % (self.path, prop_name))
  238. del self.props[prop_name]
  239. self._fdt.Invalidate()
  240. def AddZeroProp(self, prop_name):
  241. """Add a new property to the device tree with an integer value of 0.
  242. Args:
  243. prop_name: Name of property
  244. """
  245. fdt_obj = self._fdt._fdt_obj
  246. if fdt_obj.setprop_u32(self.Offset(), prop_name, 0,
  247. (libfdt.NOSPACE,)) == -libfdt.NOSPACE:
  248. fdt_obj.open_into(fdt_obj.totalsize() + 1024)
  249. fdt_obj.setprop_u32(self.Offset(), prop_name, 0)
  250. self.props[prop_name] = Prop(self, -1, prop_name, '\0' * 4)
  251. self._fdt.Invalidate()
  252. def SetInt(self, prop_name, val):
  253. """Update an integer property int the device tree.
  254. This is not allowed to change the size of the FDT.
  255. Args:
  256. prop_name: Name of property
  257. val: Value to set
  258. """
  259. fdt_obj = self._fdt._fdt_obj
  260. fdt_obj.setprop_u32(self.Offset(), prop_name, val)
  261. class Fdt:
  262. """Provides simple access to a flat device tree blob using libfdts.
  263. Properties:
  264. fname: Filename of fdt
  265. _root: Root of device tree (a Node object)
  266. """
  267. def __init__(self, fname):
  268. self._fname = fname
  269. self._cached_offsets = False
  270. self.phandle_to_node = {}
  271. if self._fname:
  272. self._fname = fdt_util.EnsureCompiled(self._fname)
  273. with open(self._fname) as fd:
  274. self._fdt_obj = libfdt.Fdt(fd.read())
  275. def LookupPhandle(self, phandle):
  276. """Look up a phandle
  277. Args:
  278. phandle: Phandle to look up (int)
  279. Returns:
  280. Node object the phandle points to
  281. """
  282. return self.phandle_to_node.get(phandle)
  283. def Scan(self, root='/'):
  284. """Scan a device tree, building up a tree of Node objects
  285. This fills in the self._root property
  286. Args:
  287. root: Ignored
  288. TODO(sjg@chromium.org): Implement the 'root' parameter
  289. """
  290. self._cached_offsets = True
  291. self._root = self.Node(self, None, 0, '/', '/')
  292. self._root.Scan()
  293. def GetRoot(self):
  294. """Get the root Node of the device tree
  295. Returns:
  296. The root Node object
  297. """
  298. return self._root
  299. def GetNode(self, path):
  300. """Look up a node from its path
  301. Args:
  302. path: Path to look up, e.g. '/microcode/update@0'
  303. Returns:
  304. Node object, or None if not found
  305. """
  306. node = self._root
  307. parts = path.split('/')
  308. if len(parts) < 2:
  309. return None
  310. for part in parts[1:]:
  311. node = node.FindNode(part)
  312. if not node:
  313. return None
  314. return node
  315. def Flush(self):
  316. """Flush device tree changes back to the file
  317. If the device tree has changed in memory, write it back to the file.
  318. """
  319. with open(self._fname, 'wb') as fd:
  320. fd.write(self._fdt_obj.as_bytearray())
  321. def Pack(self):
  322. """Pack the device tree down to its minimum size
  323. When nodes and properties shrink or are deleted, wasted space can
  324. build up in the device tree binary.
  325. """
  326. CheckErr(self._fdt_obj.pack(), 'pack')
  327. self.Invalidate()
  328. def GetContents(self):
  329. """Get the contents of the FDT
  330. Returns:
  331. The FDT contents as a string of bytes
  332. """
  333. return self._fdt_obj.as_bytearray()
  334. def GetFdtObj(self):
  335. """Get the contents of the FDT
  336. Returns:
  337. The FDT contents as a libfdt.Fdt object
  338. """
  339. return self._fdt_obj
  340. def GetProps(self, node):
  341. """Get all properties from a node.
  342. Args:
  343. node: Full path to node name to look in.
  344. Returns:
  345. A dictionary containing all the properties, indexed by node name.
  346. The entries are Prop objects.
  347. Raises:
  348. ValueError: if the node does not exist.
  349. """
  350. props_dict = {}
  351. poffset = self._fdt_obj.first_property_offset(node._offset,
  352. QUIET_NOTFOUND)
  353. while poffset >= 0:
  354. p = self._fdt_obj.get_property_by_offset(poffset)
  355. prop = Prop(node, poffset, p.name, p)
  356. props_dict[prop.name] = prop
  357. poffset = self._fdt_obj.next_property_offset(poffset,
  358. QUIET_NOTFOUND)
  359. return props_dict
  360. def Invalidate(self):
  361. """Mark our offset cache as invalid"""
  362. self._cached_offsets = False
  363. def CheckCache(self):
  364. """Refresh the offset cache if needed"""
  365. if self._cached_offsets:
  366. return
  367. self.Refresh()
  368. self._cached_offsets = True
  369. def Refresh(self):
  370. """Refresh the offset cache"""
  371. self._root.Refresh(0)
  372. def GetStructOffset(self, offset):
  373. """Get the file offset of a given struct offset
  374. Args:
  375. offset: Offset within the 'struct' region of the device tree
  376. Returns:
  377. Position of @offset within the device tree binary
  378. """
  379. return self._fdt_obj.off_dt_struct() + offset
  380. @classmethod
  381. def Node(self, fdt, parent, offset, name, path):
  382. """Create a new node
  383. This is used by Fdt.Scan() to create a new node using the correct
  384. class.
  385. Args:
  386. fdt: Fdt object
  387. parent: Parent node, or None if this is the root node
  388. offset: Offset of node
  389. name: Node name
  390. path: Full path to node
  391. """
  392. node = Node(fdt, parent, offset, name, path)
  393. return node
  394. def FdtScan(fname):
  395. """Returns a new Fdt object"""
  396. dtb = Fdt(fname)
  397. dtb.Scan()
  398. return dtb