fdt_util.py 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  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. # A list of types we support
  10. (TYPE_BYTE, TYPE_INT, TYPE_STRING, TYPE_BOOL) = range(4)
  11. def BytesToValue(bytes):
  12. """Converts a string of bytes into a type and value
  13. Args:
  14. A string containing bytes
  15. Return:
  16. A tuple:
  17. Type of data
  18. Data, either a single element or a list of elements. Each element
  19. is one of:
  20. TYPE_STRING: string value from the property
  21. TYPE_INT: a byte-swapped integer stored as a 4-byte string
  22. TYPE_BYTE: a byte stored as a single-byte string
  23. """
  24. size = len(bytes)
  25. strings = bytes.split('\0')
  26. is_string = True
  27. count = len(strings) - 1
  28. if count > 0 and not strings[-1]:
  29. for string in strings[:-1]:
  30. if not string:
  31. is_string = False
  32. break
  33. for ch in string:
  34. if ch < ' ' or ch > '~':
  35. is_string = False
  36. break
  37. else:
  38. is_string = False
  39. if is_string:
  40. if count == 1:
  41. return TYPE_STRING, strings[0]
  42. else:
  43. return TYPE_STRING, strings[:-1]
  44. if size % 4:
  45. if size == 1:
  46. return TYPE_BYTE, bytes[0]
  47. else:
  48. return TYPE_BYTE, list(bytes)
  49. val = []
  50. for i in range(0, size, 4):
  51. val.append(bytes[i:i + 4])
  52. if size == 4:
  53. return TYPE_INT, val[0]
  54. else:
  55. return TYPE_INT, val
  56. def GetEmpty(type):
  57. """Get an empty / zero value of the given type
  58. Returns:
  59. A single value of the given type
  60. """
  61. if type == TYPE_BYTE:
  62. return chr(0)
  63. elif type == TYPE_INT:
  64. return struct.pack('<I', 0);
  65. elif type == TYPE_STRING:
  66. return ''
  67. else:
  68. return True
  69. def fdt32_to_cpu(val):
  70. """Convert a device tree cell to an integer
  71. Args:
  72. Value to convert (4-character string representing the cell value)
  73. Return:
  74. A native-endian integer value
  75. """
  76. return struct.unpack(">I", val)[0]