| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465 |
- #!/usr/bin/env python3
- """Read a U-Boot environment file (uboot.env, non-redundant format).
- Format: 4-byte little-endian CRC32 of the data area, then NUL-terminated
- "name=value" strings, ended by an empty string. U-Boot reads CONFIG_ENV_SIZE
- bytes and computes the CRC over all of them but the first 4, so the file is
- only accepted by a U-Boot built with the size it was saved with.
- Usage:
- uboot-env.py check FILE ENV_SIZE exit 0 if a U-Boot with this
- CONFIG_ENV_SIZE accepts FILE, else 1
- uboot-env.py size FILE print the size the CRC is valid for
- (empty and exit 1 if none)
- uboot-env.py vars FILE print name=value per line (newlines in
- values become spaces); exit 1 if no size
- validates the CRC
- """
- import struct
- import sys
- import zlib
- def crc_ok(data, size):
- if len(data) < size or size <= 4:
- return False
- return zlib.crc32(data[4:size]) == struct.unpack("<I", data[:4])[0]
- def valid_size(data):
- size = 0x1000
- while size <= 0x100000:
- if crc_ok(data, size):
- return size
- size *= 2
- return None
- def main(argv):
- if len(argv) < 3:
- sys.stderr.write(__doc__)
- return 2
- cmd, path = argv[1], argv[2]
- with open(path, "rb") as f:
- data = f.read()
- if cmd == "check":
- return 0 if crc_ok(data, int(argv[3], 0)) else 1
- size = valid_size(data)
- if cmd == "size":
- if size is None:
- return 1
- print(hex(size))
- return 0
- if cmd == "vars":
- area = data[4:size] if size else data[4:]
- for entry in area.split(b"\0"):
- if not entry:
- break
- print(entry.decode("latin-1").replace("\n", " "))
- return 0 if size else 1
- sys.stderr.write(__doc__)
- return 2
- if __name__ == "__main__":
- sys.exit(main(sys.argv))
|