signrom.py 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. from __future__ import print_function
  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. # catch Python 2 vs. 3 differences
  40. if isinstance(b, int):
  41. checksum += b
  42. else:
  43. checksum += ord(b)
  44. checksum = (256 - checksum) % 256
  45. # Python 3 no longer allows chr(checksum)
  46. fout.write(struct.pack('B', checksum))
  47. fin.close()
  48. fout.close()