uboot-env.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. #!/usr/bin/env python3
  2. """Read a U-Boot environment file (uboot.env, non-redundant format).
  3. Format: 4-byte little-endian CRC32 of the data area, then NUL-terminated
  4. "name=value" strings, ended by an empty string. U-Boot reads CONFIG_ENV_SIZE
  5. bytes and computes the CRC over all of them but the first 4, so the file is
  6. only accepted by a U-Boot built with the size it was saved with.
  7. Usage:
  8. uboot-env.py check FILE ENV_SIZE exit 0 if a U-Boot with this
  9. CONFIG_ENV_SIZE accepts FILE, else 1
  10. uboot-env.py size FILE print the size the CRC is valid for
  11. (empty and exit 1 if none)
  12. uboot-env.py vars FILE print name=value per line (newlines in
  13. values become spaces); exit 1 if no size
  14. validates the CRC
  15. """
  16. import struct
  17. import sys
  18. import zlib
  19. def crc_ok(data, size):
  20. if len(data) < size or size <= 4:
  21. return False
  22. return zlib.crc32(data[4:size]) == struct.unpack("<I", data[:4])[0]
  23. def valid_size(data):
  24. size = 0x1000
  25. while size <= 0x100000:
  26. if crc_ok(data, size):
  27. return size
  28. size *= 2
  29. return None
  30. def main(argv):
  31. if len(argv) < 3:
  32. sys.stderr.write(__doc__)
  33. return 2
  34. cmd, path = argv[1], argv[2]
  35. with open(path, "rb") as f:
  36. data = f.read()
  37. if cmd == "check":
  38. return 0 if crc_ok(data, int(argv[3], 0)) else 1
  39. size = valid_size(data)
  40. if cmd == "size":
  41. if size is None:
  42. return 1
  43. print(hex(size))
  44. return 0
  45. if cmd == "vars":
  46. area = data[4:size] if size else data[4:]
  47. for entry in area.split(b"\0"):
  48. if not entry:
  49. break
  50. print(entry.decode("latin-1").replace("\n", " "))
  51. return 0 if size else 1
  52. sys.stderr.write(__doc__)
  53. return 2
  54. if __name__ == "__main__":
  55. sys.exit(main(sys.argv))