fdt.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270
  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. # 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. Most of the
  14. # implementation is in the FdtFallback and FdtNormal subclasses. See
  15. # fdt_select.py for how to create an Fdt object.
  16. # A list of types we support
  17. (TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL) = range(4)
  18. def CheckErr(errnum, msg):
  19. if errnum:
  20. raise ValueError('Error %d: %s: %s' %
  21. (errnum, libfdt.fdt_strerror(errnum), msg))
  22. class PropBase:
  23. """A device tree property
  24. Properties:
  25. name: Property name (as per the device tree)
  26. value: Property value as a string of bytes, or a list of strings of
  27. bytes
  28. type: Value type
  29. """
  30. def __init__(self, node, offset, name):
  31. self._node = node
  32. self._offset = offset
  33. self.name = name
  34. self.value = None
  35. def GetPhandle(self):
  36. """Get a (single) phandle value from a property
  37. Gets the phandle valuie from a property and returns it as an integer
  38. """
  39. return fdt_util.fdt32_to_cpu(self.value[:4])
  40. def Widen(self, newprop):
  41. """Figure out which property type is more general
  42. Given a current property and a new property, this function returns the
  43. one that is less specific as to type. The less specific property will
  44. be ble to represent the data in the more specific property. This is
  45. used for things like:
  46. node1 {
  47. compatible = "fred";
  48. value = <1>;
  49. };
  50. node1 {
  51. compatible = "fred";
  52. value = <1 2>;
  53. };
  54. He we want to use an int array for 'value'. The first property
  55. suggests that a single int is enough, but the second one shows that
  56. it is not. Calling this function with these two propertes would
  57. update the current property to be like the second, since it is less
  58. specific.
  59. """
  60. if newprop.type < self.type:
  61. self.type = newprop.type
  62. if type(newprop.value) == list and type(self.value) != list:
  63. self.value = [self.value]
  64. if type(self.value) == list and len(newprop.value) > len(self.value):
  65. val = self.GetEmpty(self.type)
  66. while len(self.value) < len(newprop.value):
  67. self.value.append(val)
  68. def BytesToValue(self, bytes):
  69. """Converts a string of bytes into a type and value
  70. Args:
  71. A string containing bytes
  72. Return:
  73. A tuple:
  74. Type of data
  75. Data, either a single element or a list of elements. Each element
  76. is one of:
  77. TYPE_STRING: string value from the property
  78. TYPE_INT: a byte-swapped integer stored as a 4-byte string
  79. TYPE_BYTE: a byte stored as a single-byte string
  80. """
  81. bytes = str(bytes)
  82. size = len(bytes)
  83. strings = bytes.split('\0')
  84. is_string = True
  85. count = len(strings) - 1
  86. if count > 0 and not strings[-1]:
  87. for string in strings[:-1]:
  88. if not string:
  89. is_string = False
  90. break
  91. for ch in string:
  92. if ch < ' ' or ch > '~':
  93. is_string = False
  94. break
  95. else:
  96. is_string = False
  97. if is_string:
  98. if count == 1:
  99. return TYPE_STRING, strings[0]
  100. else:
  101. return TYPE_STRING, strings[:-1]
  102. if size % 4:
  103. if size == 1:
  104. return TYPE_BYTE, bytes[0]
  105. else:
  106. return TYPE_BYTE, list(bytes)
  107. val = []
  108. for i in range(0, size, 4):
  109. val.append(bytes[i:i + 4])
  110. if size == 4:
  111. return TYPE_INT, val[0]
  112. else:
  113. return TYPE_INT, val
  114. def GetEmpty(self, type):
  115. """Get an empty / zero value of the given type
  116. Returns:
  117. A single value of the given type
  118. """
  119. if type == TYPE_BYTE:
  120. return chr(0)
  121. elif type == TYPE_INT:
  122. return struct.pack('<I', 0);
  123. elif type == TYPE_STRING:
  124. return ''
  125. else:
  126. return True
  127. def GetOffset(self):
  128. """Get the offset of a property
  129. This can be implemented by subclasses.
  130. Returns:
  131. The offset of the property (struct fdt_property) within the
  132. file, or None if not known.
  133. """
  134. return None
  135. class NodeBase:
  136. """A device tree node
  137. Properties:
  138. offset: Integer offset in the device tree
  139. name: Device tree node tname
  140. path: Full path to node, along with the node name itself
  141. _fdt: Device tree object
  142. subnodes: A list of subnodes for this node, each a Node object
  143. props: A dict of properties for this node, each a Prop object.
  144. Keyed by property name
  145. """
  146. def __init__(self, fdt, offset, name, path):
  147. self._fdt = fdt
  148. self._offset = offset
  149. self.name = name
  150. self.path = path
  151. self.subnodes = []
  152. self.props = {}
  153. def _FindNode(self, name):
  154. """Find a node given its name
  155. Args:
  156. name: Node name to look for
  157. Returns:
  158. Node object if found, else None
  159. """
  160. for subnode in self.subnodes:
  161. if subnode.name == name:
  162. return subnode
  163. return None
  164. def Scan(self):
  165. """Scan the subnodes of a node
  166. This should be implemented by subclasses
  167. """
  168. raise NotImplementedError()
  169. def DeleteProp(self, prop_name):
  170. """Delete a property of a node
  171. This should be implemented by subclasses
  172. Args:
  173. prop_name: Name of the property to delete
  174. """
  175. raise NotImplementedError()
  176. class Fdt:
  177. """Provides simple access to a flat device tree blob.
  178. Properties:
  179. fname: Filename of fdt
  180. _root: Root of device tree (a Node object)
  181. """
  182. def __init__(self, fname):
  183. self._fname = fname
  184. def Scan(self, root='/'):
  185. """Scan a device tree, building up a tree of Node objects
  186. This fills in the self._root property
  187. Args:
  188. root: Ignored
  189. TODO(sjg@chromium.org): Implement the 'root' parameter
  190. """
  191. self._root = self.Node(self, 0, '/', '/')
  192. self._root.Scan()
  193. def GetRoot(self):
  194. """Get the root Node of the device tree
  195. Returns:
  196. The root Node object
  197. """
  198. return self._root
  199. def GetNode(self, path):
  200. """Look up a node from its path
  201. Args:
  202. path: Path to look up, e.g. '/microcode/update@0'
  203. Returns:
  204. Node object, or None if not found
  205. """
  206. node = self._root
  207. for part in path.split('/')[1:]:
  208. node = node._FindNode(part)
  209. if not node:
  210. return None
  211. return node
  212. def Flush(self):
  213. """Flush device tree changes back to the file
  214. If the device tree has changed in memory, write it back to the file.
  215. Subclasses can implement this if needed.
  216. """
  217. pass
  218. def Pack(self):
  219. """Pack the device tree down to its minimum size
  220. When nodes and properties shrink or are deleted, wasted space can
  221. build up in the device tree binary. Subclasses can implement this
  222. to remove that spare space.
  223. """
  224. pass