fdt.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415
  1. #!/usr/bin/python
  2. #
  3. # Copyright (C) 2016 Google, Inc
  4. # Written by Simon Glass <sjg@chromium.org>
  5. #
  6. # SPDX-License-Identifier: GPL-2.0+
  7. #
  8. import struct
  9. import sys
  10. import fdt_util
  11. import libfdt
  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 GetPhandle(self):
  44. """Get a (single) phandle value from a property
  45. Gets the phandle valuie from a property and returns it as an integer
  46. """
  47. return fdt_util.fdt32_to_cpu(self.value[:4])
  48. def Widen(self, newprop):
  49. """Figure out which property type is more general
  50. Given a current property and a new property, this function returns the
  51. one that is less specific as to type. The less specific property will
  52. be ble to represent the data in the more specific property. This is
  53. used for things like:
  54. node1 {
  55. compatible = "fred";
  56. value = <1>;
  57. };
  58. node1 {
  59. compatible = "fred";
  60. value = <1 2>;
  61. };
  62. He we want to use an int array for 'value'. The first property
  63. suggests that a single int is enough, but the second one shows that
  64. it is not. Calling this function with these two propertes would
  65. update the current property to be like the second, since it is less
  66. specific.
  67. """
  68. if newprop.type < self.type:
  69. self.type = newprop.type
  70. if type(newprop.value) == list and type(self.value) != list:
  71. self.value = [self.value]
  72. if type(self.value) == list and len(newprop.value) > len(self.value):
  73. val = self.GetEmpty(self.type)
  74. while len(self.value) < len(newprop.value):
  75. self.value.append(val)
  76. def BytesToValue(self, bytes):
  77. """Converts a string of bytes into a type and value
  78. Args:
  79. A string containing bytes
  80. Return:
  81. A tuple:
  82. Type of data
  83. Data, either a single element or a list of elements. Each element
  84. is one of:
  85. TYPE_STRING: string value from the property
  86. TYPE_INT: a byte-swapped integer stored as a 4-byte string
  87. TYPE_BYTE: a byte stored as a single-byte string
  88. """
  89. bytes = str(bytes)
  90. size = len(bytes)
  91. strings = bytes.split('\0')
  92. is_string = True
  93. count = len(strings) - 1
  94. if count > 0 and not strings[-1]:
  95. for string in strings[:-1]:
  96. if not string:
  97. is_string = False
  98. break
  99. for ch in string:
  100. if ch < ' ' or ch > '~':
  101. is_string = False
  102. break
  103. else:
  104. is_string = False
  105. if is_string:
  106. if count == 1:
  107. return TYPE_STRING, strings[0]
  108. else:
  109. return TYPE_STRING, strings[:-1]
  110. if size % 4:
  111. if size == 1:
  112. return TYPE_BYTE, bytes[0]
  113. else:
  114. return TYPE_BYTE, list(bytes)
  115. val = []
  116. for i in range(0, size, 4):
  117. val.append(bytes[i:i + 4])
  118. if size == 4:
  119. return TYPE_INT, val[0]
  120. else:
  121. return TYPE_INT, val
  122. def GetEmpty(self, type):
  123. """Get an empty / zero value of the given type
  124. Returns:
  125. A single value of the given type
  126. """
  127. if type == TYPE_BYTE:
  128. return chr(0)
  129. elif type == TYPE_INT:
  130. return struct.pack('<I', 0);
  131. elif type == TYPE_STRING:
  132. return ''
  133. else:
  134. return True
  135. def GetOffset(self):
  136. """Get the offset of a property
  137. Returns:
  138. The offset of the property (struct fdt_property) within the file
  139. """
  140. return self._node._fdt.GetStructOffset(self._offset)
  141. class Node:
  142. """A device tree node
  143. Properties:
  144. offset: Integer offset in the device tree
  145. name: Device tree node tname
  146. path: Full path to node, along with the node name itself
  147. _fdt: Device tree object
  148. subnodes: A list of subnodes for this node, each a Node object
  149. props: A dict of properties for this node, each a Prop object.
  150. Keyed by property name
  151. """
  152. def __init__(self, fdt, parent, offset, name, path):
  153. self._fdt = fdt
  154. self.parent = parent
  155. self._offset = offset
  156. self.name = name
  157. self.path = path
  158. self.subnodes = []
  159. self.props = {}
  160. def _FindNode(self, name):
  161. """Find a node given its name
  162. Args:
  163. name: Node name to look for
  164. Returns:
  165. Node object if found, else None
  166. """
  167. for subnode in self.subnodes:
  168. if subnode.name == name:
  169. return subnode
  170. return None
  171. def Offset(self):
  172. """Returns the offset of a node, after checking the cache
  173. This should be used instead of self._offset directly, to ensure that
  174. the cache does not contain invalid offsets.
  175. """
  176. self._fdt.CheckCache()
  177. return self._offset
  178. def Scan(self):
  179. """Scan a node's properties and subnodes
  180. This fills in the props and subnodes properties, recursively
  181. searching into subnodes so that the entire tree is built.
  182. """
  183. self.props = self._fdt.GetProps(self)
  184. phandle = self.props.get('phandle')
  185. if phandle:
  186. val = fdt_util.fdt32_to_cpu(phandle.value)
  187. self._fdt.phandle_to_node[val] = self
  188. offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self.Offset())
  189. while offset >= 0:
  190. sep = '' if self.path[-1] == '/' else '/'
  191. name = self._fdt._fdt_obj.get_name(offset)
  192. path = self.path + sep + name
  193. node = Node(self._fdt, self, offset, name, path)
  194. self.subnodes.append(node)
  195. node.Scan()
  196. offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
  197. def Refresh(self, my_offset):
  198. """Fix up the _offset for each node, recursively
  199. Note: This does not take account of property offsets - these will not
  200. be updated.
  201. """
  202. if self._offset != my_offset:
  203. #print '%s: %d -> %d\n' % (self.path, self._offset, my_offset)
  204. self._offset = my_offset
  205. offset = libfdt.fdt_first_subnode(self._fdt.GetFdt(), self._offset)
  206. for subnode in self.subnodes:
  207. subnode.Refresh(offset)
  208. offset = libfdt.fdt_next_subnode(self._fdt.GetFdt(), offset)
  209. def DeleteProp(self, prop_name):
  210. """Delete a property of a node
  211. The property is deleted and the offset cache is invalidated.
  212. Args:
  213. prop_name: Name of the property to delete
  214. Raises:
  215. ValueError if the property does not exist
  216. """
  217. CheckErr(libfdt.fdt_delprop(self._fdt.GetFdt(), self.Offset(), prop_name),
  218. "Node '%s': delete property: '%s'" % (self.path, prop_name))
  219. del self.props[prop_name]
  220. self._fdt.Invalidate()
  221. class Fdt:
  222. """Provides simple access to a flat device tree blob using libfdts.
  223. Properties:
  224. fname: Filename of fdt
  225. _root: Root of device tree (a Node object)
  226. """
  227. def __init__(self, fname):
  228. self._fname = fname
  229. self._cached_offsets = False
  230. self.phandle_to_node = {}
  231. if self._fname:
  232. self._fname = fdt_util.EnsureCompiled(self._fname)
  233. with open(self._fname) as fd:
  234. self._fdt = bytearray(fd.read())
  235. self._fdt_obj = libfdt.Fdt(self._fdt)
  236. def Scan(self, root='/'):
  237. """Scan a device tree, building up a tree of Node objects
  238. This fills in the self._root property
  239. Args:
  240. root: Ignored
  241. TODO(sjg@chromium.org): Implement the 'root' parameter
  242. """
  243. self._root = self.Node(self, None, 0, '/', '/')
  244. self._root.Scan()
  245. def GetRoot(self):
  246. """Get the root Node of the device tree
  247. Returns:
  248. The root Node object
  249. """
  250. return self._root
  251. def GetNode(self, path):
  252. """Look up a node from its path
  253. Args:
  254. path: Path to look up, e.g. '/microcode/update@0'
  255. Returns:
  256. Node object, or None if not found
  257. """
  258. node = self._root
  259. for part in path.split('/')[1:]:
  260. node = node._FindNode(part)
  261. if not node:
  262. return None
  263. return node
  264. def Flush(self):
  265. """Flush device tree changes back to the file
  266. If the device tree has changed in memory, write it back to the file.
  267. """
  268. with open(self._fname, 'wb') as fd:
  269. fd.write(self._fdt)
  270. def Pack(self):
  271. """Pack the device tree down to its minimum size
  272. When nodes and properties shrink or are deleted, wasted space can
  273. build up in the device tree binary.
  274. """
  275. CheckErr(libfdt.fdt_pack(self._fdt), 'pack')
  276. fdt_len = libfdt.fdt_totalsize(self._fdt)
  277. del self._fdt[fdt_len:]
  278. def GetFdt(self):
  279. """Get the contents of the FDT
  280. Returns:
  281. The FDT contents as a string of bytes
  282. """
  283. return self._fdt
  284. def CheckErr(errnum, msg):
  285. if errnum:
  286. raise ValueError('Error %d: %s: %s' %
  287. (errnum, libfdt.fdt_strerror(errnum), msg))
  288. def GetProps(self, node):
  289. """Get all properties from a node.
  290. Args:
  291. node: Full path to node name to look in.
  292. Returns:
  293. A dictionary containing all the properties, indexed by node name.
  294. The entries are Prop objects.
  295. Raises:
  296. ValueError: if the node does not exist.
  297. """
  298. props_dict = {}
  299. poffset = libfdt.fdt_first_property_offset(self._fdt, node._offset)
  300. while poffset >= 0:
  301. p = self._fdt_obj.get_property_by_offset(poffset)
  302. prop = Prop(node, poffset, p.name, p.value)
  303. props_dict[prop.name] = prop
  304. poffset = libfdt.fdt_next_property_offset(self._fdt, poffset)
  305. return props_dict
  306. def Invalidate(self):
  307. """Mark our offset cache as invalid"""
  308. self._cached_offsets = False
  309. def CheckCache(self):
  310. """Refresh the offset cache if needed"""
  311. if self._cached_offsets:
  312. return
  313. self.Refresh()
  314. self._cached_offsets = True
  315. def Refresh(self):
  316. """Refresh the offset cache"""
  317. self._root.Refresh(0)
  318. def GetStructOffset(self, offset):
  319. """Get the file offset of a given struct offset
  320. Args:
  321. offset: Offset within the 'struct' region of the device tree
  322. Returns:
  323. Position of @offset within the device tree binary
  324. """
  325. return libfdt.fdt_off_dt_struct(self._fdt) + offset
  326. @classmethod
  327. def Node(self, fdt, parent, offset, name, path):
  328. """Create a new node
  329. This is used by Fdt.Scan() to create a new node using the correct
  330. class.
  331. Args:
  332. fdt: Fdt object
  333. parent: Parent node, or None if this is the root node
  334. offset: Offset of node
  335. name: Node name
  336. path: Full path to node
  337. """
  338. node = Node(fdt, parent, offset, name, path)
  339. return node
  340. def FdtScan(fname):
  341. """Returns a new Fdt object from the implementation we are using"""
  342. dtb = Fdt(fname)
  343. dtb.Scan()
  344. return dtb