fdt_util.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 os
  9. import struct
  10. import sys
  11. import tempfile
  12. import command
  13. import tools
  14. def fdt32_to_cpu(val):
  15. """Convert a device tree cell to an integer
  16. Args:
  17. Value to convert (4-character string representing the cell value)
  18. Return:
  19. A native-endian integer value
  20. """
  21. if sys.version_info > (3, 0):
  22. val = val.encode('raw_unicode_escape')
  23. return struct.unpack('>I', val)[0]
  24. def EnsureCompiled(fname):
  25. """Compile an fdt .dts source file into a .dtb binary blob if needed.
  26. Args:
  27. fname: Filename (if .dts it will be compiled). It not it will be
  28. left alone
  29. Returns:
  30. Filename of resulting .dtb file
  31. """
  32. _, ext = os.path.splitext(fname)
  33. if ext != '.dts':
  34. return fname
  35. dts_input = tools.GetOutputFilename('source.dts')
  36. dtb_output = tools.GetOutputFilename('source.dtb')
  37. search_paths = [os.path.join(os.getcwd(), 'include')]
  38. root, _ = os.path.splitext(fname)
  39. args = ['-E', '-P', '-x', 'assembler-with-cpp', '-D__ASSEMBLY__']
  40. args += ['-Ulinux']
  41. for path in search_paths:
  42. args.extend(['-I', path])
  43. args += ['-o', dts_input, fname]
  44. command.Run('cc', *args)
  45. # If we don't have a directory, put it in the tools tempdir
  46. search_list = []
  47. for path in search_paths:
  48. search_list.extend(['-i', path])
  49. args = ['-I', 'dts', '-o', dtb_output, '-O', 'dtb']
  50. args.extend(search_list)
  51. args.append(dts_input)
  52. command.Run('dtc', *args)
  53. return dtb_output
  54. def GetInt(node, propname, default=None):
  55. prop = node.props.get(propname)
  56. if not prop:
  57. return default
  58. value = fdt32_to_cpu(prop.value)
  59. if type(value) == type(list):
  60. raise ValueError("Node '%s' property '%' has list value: expecting"
  61. "a single integer" % (node.name, propname))
  62. return value
  63. def GetString(node, propname, default=None):
  64. prop = node.props.get(propname)
  65. if not prop:
  66. return default
  67. value = prop.value
  68. if type(value) == type(list):
  69. raise ValueError("Node '%s' property '%' has list value: expecting"
  70. "a single string" % (node.name, propname))
  71. return value
  72. def GetBool(node, propname, default=False):
  73. if propname in node.props:
  74. return True
  75. return default