fdt.py 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  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. size = len(bytes)
  82. strings = bytes.split('\0')
  83. is_string = True
  84. count = len(strings) - 1
  85. if count > 0 and not strings[-1]:
  86. for string in strings[:-1]:
  87. if not string:
  88. is_string = False
  89. break
  90. for ch in string:
  91. if ch < ' ' or ch > '~':
  92. is_string = False
  93. break
  94. else:
  95. is_string = False
  96. if is_string:
  97. if count == 1:
  98. return TYPE_STRING, strings[0]
  99. else:
  100. return TYPE_STRING, strings[:-1]
  101. if size % 4:
  102. if size == 1:
  103. return TYPE_BYTE, bytes[0]
  104. else:
  105. return TYPE_BYTE, list(bytes)
  106. val = []
  107. for i in range(0, size, 4):
  108. val.append(bytes[i:i + 4])
  109. if size == 4:
  110. return TYPE_INT, val[0]
  111. else:
  112. return TYPE_INT, val
  113. def GetEmpty(self, type):
  114. """Get an empty / zero value of the given type
  115. Returns:
  116. A single value of the given type
  117. """
  118. if type == TYPE_BYTE:
  119. return chr(0)
  120. elif type == TYPE_INT:
  121. return struct.pack('<I', 0);
  122. elif type == TYPE_STRING:
  123. return ''
  124. else:
  125. return True
  126. def GetOffset(self):
  127. """Get the offset of a property
  128. This can be implemented by subclasses.
  129. Returns:
  130. The offset of the property (struct fdt_property) within the
  131. file, or None if not known.
  132. """
  133. return None
  134. class NodeBase:
  135. """A device tree node
  136. Properties:
  137. offset: Integer offset in the device tree
  138. name: Device tree node tname
  139. path: Full path to node, along with the node name itself
  140. _fdt: Device tree object
  141. subnodes: A list of subnodes for this node, each a Node object
  142. props: A dict of properties for this node, each a Prop object.
  143. Keyed by property name
  144. """
  145. def __init__(self, fdt, offset, name, path):
  146. self._fdt = fdt
  147. self._offset = offset
  148. self.name = name
  149. self.path = path
  150. self.subnodes = []
  151. self.props = {}
  152. def _FindNode(self, name):
  153. """Find a node given its name
  154. Args:
  155. name: Node name to look for
  156. Returns:
  157. Node object if found, else None
  158. """
  159. for subnode in self.subnodes:
  160. if subnode.name == name:
  161. return subnode
  162. return None
  163. def Scan(self):
  164. """Scan the subnodes of a node
  165. This should be implemented by subclasses
  166. """
  167. raise NotImplementedError()
  168. def DeleteProp(self, prop_name):
  169. """Delete a property of a node
  170. This should be implemented by subclasses
  171. Args:
  172. prop_name: Name of the property to delete
  173. """
  174. raise NotImplementedError()
  175. class Fdt:
  176. """Provides simple access to a flat device tree blob.
  177. Properties:
  178. fname: Filename of fdt
  179. _root: Root of device tree (a Node object)
  180. """
  181. def __init__(self, fname):
  182. self._fname = fname
  183. def Scan(self, root='/'):
  184. """Scan a device tree, building up a tree of Node objects
  185. This fills in the self._root property
  186. Args:
  187. root: Ignored
  188. TODO(sjg@chromium.org): Implement the 'root' parameter
  189. """
  190. self._root = self.Node(self, 0, '/', '/')
  191. self._root.Scan()
  192. def GetRoot(self):
  193. """Get the root Node of the device tree
  194. Returns:
  195. The root Node object
  196. """
  197. return self._root
  198. def GetNode(self, path):
  199. """Look up a node from its path
  200. Args:
  201. path: Path to look up, e.g. '/microcode/update@0'
  202. Returns:
  203. Node object, or None if not found
  204. """
  205. node = self._root
  206. for part in path.split('/')[1:]:
  207. node = node._FindNode(part)
  208. if not node:
  209. return None
  210. return node
  211. def Flush(self):
  212. """Flush device tree changes back to the file
  213. If the device tree has changed in memory, write it back to the file.
  214. Subclasses can implement this if needed.
  215. """
  216. pass
  217. def Pack(self):
  218. """Pack the device tree down to its minimum size
  219. When nodes and properties shrink or are deleted, wasted space can
  220. build up in the device tree binary. Subclasses can implement this
  221. to remove that spare space.
  222. """
  223. pass