signrom.py 1.3 KB

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