fdt.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414
  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. # This deals with a device tree, presenting it as an assortment of Node and
  12. # Prop objects, representing nodes and properties, respectively. This file
  13. # contains the base classes and defines the high-level API. You can use
  14. # FdtScan() as a convenience function to create and scan an Fdt.
  15. # This implementation uses a libfdt Python library to access the device tree,
  16. # so it is fairly efficient.
  17. # A list of types we support
  18. (TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL, TYPE_INT64) = range(5)
  19. def CheckErr(errnum, msg):
  20. if errnum:
  21. raise ValueError('Error %d: %s: %s' %
  22. (errnum, libfdt.fdt_strerror(errnum), msg))
  23. class Prop:
  24. """A device tree property
  25. Properties:
  26. name: Property name (as per the device tree)
  27. value: Property value as a string of bytes, or a list of strings of
  28. bytes
  29. type: Value type
  30. """
  31. def __init__(self, node, offset, name, bytes):
  32. self._node = node
  33. self._offset = offset
  34. self.name = name
  35. self.value = None
  36. self.bytes = str(bytes)
  37. if not bytes:
  38. self.type = TYPE_BOOL
  39. self.value = True
  40. return
  41. self.type, self.value = self.BytesToValue(bytes)
  42. def GetPhandle(self):
  43. """Get a (single) phandle value from a property
  44. Gets the phandle valuie from a property and returns it as an integer
  45. """
  46. return fdt_util.fdt32_to_cpu(self.value[:4])
  47. def Widen(self, newprop):
  48. """Figure out which property type is more general
  49. Given a current property and a new property, this function returns the
  50. one that is less specific as to type. The less specific property will
  51. be ble to represent the data in the more specific property. This is
  52. used for things like:
  53. node1 {
  54. compatible = "fred";
  55. value = <1>;
  56. };
  57. node1 {
  58. compatible = "fred";
  59. value = <1 2>;
  60. };
  61. He we want to use an int array for 'value'. The first property
  62. suggests that a single int is enough, but the second one shows that
  63. it is not. Calling this function with these two propertes would
  64. update the current property to be like the second, since it is less
  65. specific.
  66. """
  67. if newprop.type < self.type:
  68. self.type = newprop.type
  69. if type(newprop.value) == list and type(self.value) != list:
  70. self.value = [self.value]
  71. if type(self.value) == list and len(newprop.value) > len(self.value):
  72. val = self.GetEmpty(self.type)
  73. while len(self.value) < len(newprop.value):
  74. self.value.append(val)
  75. def BytesToValue(self, bytes):
  76. """Converts a string of bytes into a type and value
  77. Args:
  78. A string containing bytes
  79. Return:
  80. A tuple:
  81. Type of data
  82. Data, either a single element or a list of elements. Each element
  83. is one of:
  84. TYPE_STRING: string value from the property
  85. TYPE_INT: a byte-swapped integer stored as a 4-byte string
  86. TYPE_BYTE: a byte stored as a single-byte string
  87. """
  88. bytes = str(bytes)
  89. size = len(bytes)
  90. strings = bytes.split('\0')
  91. is_string = True
  92. count = len(strings) - 1
  93. if count > 0 and not strings[-1]:
  94. for string in strings[:-1]:
  95. if not string:
  96. is_string = False
  97. break
  98. for ch in string:
  99. if ch < ' ' or ch > '~':
  100. is_string = False
  101. break
  102. else:
  103. is_string = False
  104. if is_string:
  105. if count == 1:
  106. return TYPE_STRING, strings[0]
  107. else:
  108. return TYPE_STRING, strings[:-1]
  109. if size % 4:
  110. if size == 1:
  111. return TYPE_BYTE, bytes[0]
  112. else:
  113. return TYPE_BYTE, list(bytes)
  114. val = []
  115. for i in range(0, size, 4):
  116. val.append(bytes[i:i + 4])
  117. if size == 4:
  118. return TYPE_INT, val[0]
  119. else:
  120. return TYPE_INT, val
  121. def GetEmpty(self, type):
  122. """Get an empty / zero value of the given type
  123. Returns:
  124. A single value of the given type
  125. """
  126. if type == TYPE_BYTE:
  127. return chr(0)
  128. elif type == TYPE_INT:
  129. return struct.pack('<I', 0);
  130. elif type == TYPE_STRING:
  131. return ''
  132. else:
  133. return True
  134. def GetOffset(self):
  135. """Get the offset of a property
  136. Returns:
  137. The offset of the property (struct fdt_property) within the file
  138. """
  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. self.props = self._fdt.GetProps(self)
  183. phandle = self.props.get('phandle')
  184. if phandle:
  185. val = fdt_util.fdt32_to_cpu(phandle.value)
  186. self._fdt.phandle_to_node[val] = self
  187. offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self.Offset())
  188. while offset >= 0:
  189. sep = '' if self.path[-1] == '/' else '/'
  190. name = self._fdt._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 = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
  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. if self._offset != my_offset:
  202. #print '%s: %d -> %d\n' % (self.path, self._offset, my_offset)
  203. self._offset = my_offset
  204. offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset)
  205. for subnode in self.subnodes:
  206. subnode.Refresh(offset)
  207. offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
  208. def DeleteProp(self, prop_name):
  209. """Delete a property of a node
  210. The property is deleted and the offset cache is invalidated.
  211. Args:
  212. prop_name: Name of the property to delete
  213. Raises:
  214. ValueError if the property does not exist
  215. """
  216. CheckErr(libfdt.fdt_delprop(self._fdt.GetFdt(), self.Offset(), prop_name),
  217. "Node '%s': delete property: '%s'" % (self.path, prop_name))
  218. del self.props[prop_name]
  219. self._fdt.Invalidate()
  220. class Fdt:
  221. """Provides simple access to a flat device tree blob using libfdts.
  222. Properties:
  223. fname: Filename of fdt
  224. _root: Root of device tree (a Node object)
  225. """
  226. def __init__(self, fname):
  227. self._fname = fname
  228. self._cached_offsets = False
  229. self.phandle_to_node = {}
  230. if self._fname:
  231. self._fname = fdt_util.EnsureCompiled(self._fname)
  232. with open(self._fname) as fd:
  233. self._fdt = bytearray(fd.read())
  234. self._fdt_obj = libfdt.Fdt(self._fdt)
  235. def Scan(self, root='/'):
  236. """Scan a device tree, building up a tree of Node objects
  237. This fills in the self._root property
  238. Args:
  239. root: Ignored
  240. TODO(sjg@chromium.org): Implement the 'root' parameter
  241. """
  242. self._root = self.Node(self, None, 0, '/', '/')
  243. self._root.Scan()
  244. def GetRoot(self):
  245. """Get the root Node of the device tree
  246. Returns:
  247. The root Node object
  248. """
  249. return self._root
  250. def GetNode(self, path):
  251. """Look up a node from its path
  252. Args:
  253. path: Path to look up, e.g. '/microcode/update@0'
  254. Returns:
  255. Node object, or None if not found
  256. """
  257. node = self._root
  258. for part in path.split('/')[1:]:
  259. node = node._FindNode(part)
  260. if not node:
  261. return None
  262. return node
  263. def Flush(self):
  264. """Flush device tree changes back to the file
  265. If the device tree has changed in memory, write it back to the file.
  266. """
  267. with open(self._fname, 'wb') as fd:
  268. fd.write(self._fdt)
  269. def Pack(self):
  270. """Pack the device tree down to its minimum size
  271. When nodes and properties shrink or are deleted, wasted space can
  272. build up in the device tree binary.
  273. """
  274. CheckErr(libfdt.fdt_pack(self._fdt), 'pack')
  275. fdt_len = libfdt.fdt_totalsize(self._fdt)
  276. del self._fdt[fdt_len:]
  277. def GetFdt(self):
  278. """Get the contents of the FDT
  279. Returns:
  280. The FDT contents as a string of bytes
  281. """
  282. return self._fdt
  283. def CheckErr(errnum, msg):
  284. if errnum:
  285. raise ValueError('Error %d: %s: %s' %
  286. (errnum, libfdt.fdt_strerror(errnum), msg))
  287. def GetProps(self, node):
  288. """Get all properties from a node.
  289. Args:
  290. node: Full path to node name to look in.
  291. Returns:
  292. A dictionary containing all the properties, indexed by node name.
  293. The entries are Prop objects.
  294. Raises:
  295. ValueError: if the node does not exist.
  296. """
  297. props_dict = {}
  298. poffset = libfdt.fdt_first_property_offset(self._fdt, node._offset)
  299. while poffset >= 0:
  300. p = self._fdt_obj.get_property_by_offset(poffset)
  301. prop = Prop(node, poffset, p.name, p.value)
  302. props_dict[prop.name] = prop
  303. poffset = libfdt.fdt_next_property_offset(self._fdt, poffset)
  304. return props_dict
  305. def Invalidate(self):
  306. """Mark our offset cache as invalid"""
  307. self._cached_offsets = False
  308. def CheckCache(self):
  309. """Refresh the offset cache if needed"""
  310. if self._cached_offsets:
  311. return
  312. self.Refresh()
  313. self._cached_offsets = True
  314. def Refresh(self):
  315. """Refresh the offset cache"""
  316. self._root.Refresh(0)
  317. def GetStructOffset(self, offset):
  318. """Get the file offset of a given struct offset
  319. Args:
  320. offset: Offset within the 'struct' region of the device tree
  321. Returns:
  322. Position of @offset within the device tree binary
  323. """
  324. return libfdt.fdt_off_dt_struct(self._fdt) + offset
  325. @classmethod
  326. def Node(self, fdt, parent, offset, name, path):
  327. """Create a new node
  328. This is used by Fdt.Scan() to create a new node using the correct
  329. class.
  330. Args:
  331. fdt: Fdt object
  332. parent: Parent node, or None if this is the root node
  333. offset: Offset of node
  334. name: Node name
  335. path: Full path to node
  336. """
  337. node = Node(fdt, parent, offset, name, path)
  338. return node
  339. def FdtScan(fname):
  340. """Returns a new Fdt object from the implementation we are using"""
  341. dtb = Fdt(fname)
  342. dtb.Scan()
  343. return dtb