signrom.py 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. #!/usr/bin/env python3
  2. #
  3. # Option ROM signing utility
  4. #
  5. # Authors:
  6. # Jan Kiszka <jan.kiszka@siemens.com>
  7. #
  8. # This work is licensed under the terms of the GNU GPL, version 2 or later.
  9. # See the COPYING file in the top-level directory.
  10. import sys
  11. import struct
  12. if len(sys.argv) < 3:
  13. print('usage: signrom.py input output')
  14. sys.exit(1)
  15. fin = open(sys.argv[1], 'rb')
  16. fout = open(sys.argv[2], 'wb')
  17. magic = fin.read(2)
  18. if magic != b'\x55\xaa':
  19. sys.exit("%s: option ROM does not begin with magic 55 aa" % sys.argv[1])
  20. size_byte = ord(fin.read(1))
  21. fin.seek(0)
  22. data = fin.read()
  23. size = size_byte * 512
  24. if len(data) > size:
  25. sys.stderr.write('error: ROM is too large (%d > %d)\n' % (len(data), size))
  26. sys.exit(1)
  27. elif len(data) < size:
  28. # Add padding if necessary, rounding the whole input to a multiple of
  29. # 512 bytes according to the third byte of the input.
  30. # size-1 because a final byte is added below to store the checksum.
  31. data = data.ljust(size-1, b'\0')
  32. else:
  33. if ord(data[-1:]) != 0:
  34. sys.stderr.write('WARNING: ROM includes nonzero checksum\n')
  35. data = data[:size-1]
  36. fout.write(data)
  37. checksum = 0
  38. for b in data:
  39. checksum = (checksum - b) & 255
  40. fout.write(struct.pack('B', checksum))
  41. fin.close()
  42. fout.close()