fdt.py 6.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242
  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. class NodeBase:
  127. """A device tree node
  128. Properties:
  129. offset: Integer offset in the device tree
  130. name: Device tree node tname
  131. path: Full path to node, along with the node name itself
  132. _fdt: Device tree object
  133. subnodes: A list of subnodes for this node, each a Node object
  134. props: A dict of properties for this node, each a Prop object.
  135. Keyed by property name
  136. """
  137. def __init__(self, fdt, offset, name, path):
  138. self._fdt = fdt
  139. self._offset = offset
  140. self.name = name
  141. self.path = path
  142. self.subnodes = []
  143. self.props = {}
  144. def _FindNode(self, name):
  145. """Find a node given its name
  146. Args:
  147. name: Node name to look for
  148. Returns:
  149. Node object if found, else None
  150. """
  151. for subnode in self.subnodes:
  152. if subnode.name == name:
  153. return subnode
  154. return None
  155. def Scan(self):
  156. """Scan the subnodes of a node
  157. This should be implemented by subclasses
  158. """
  159. raise NotImplementedError()
  160. def DeleteProp(self, prop_name):
  161. """Delete a property of a node
  162. This should be implemented by subclasses
  163. Args:
  164. prop_name: Name of the property to delete
  165. """
  166. raise NotImplementedError()
  167. class Fdt:
  168. """Provides simple access to a flat device tree blob.
  169. Properties:
  170. fname: Filename of fdt
  171. _root: Root of device tree (a Node object)
  172. """
  173. def __init__(self, fname):
  174. self._fname = fname
  175. def Scan(self, root='/'):
  176. """Scan a device tree, building up a tree of Node objects
  177. This fills in the self._root property
  178. Args:
  179. root: Ignored
  180. TODO(sjg@chromium.org): Implement the 'root' parameter
  181. """
  182. self._root = self.Node(self, 0, '/', '/')
  183. self._root.Scan()
  184. def GetRoot(self):
  185. """Get the root Node of the device tree
  186. Returns:
  187. The root Node object
  188. """
  189. return self._root
  190. def GetNode(self, path):
  191. """Look up a node from its path
  192. Args:
  193. path: Path to look up, e.g. '/microcode/update@0'
  194. Returns:
  195. Node object, or None if not found
  196. """
  197. node = self._root
  198. for part in path.split('/')[1:]:
  199. node = node._FindNode(part)
  200. if not node:
  201. return None
  202. return node