signrom.py 1.4 KB

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