signrom.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. fin.seek(2)
  17. size_byte = ord(fin.read(1))
  18. fin.seek(0)
  19. if size_byte == 0:
  20. # If the caller left the size field blank then we will fill it in,
  21. # also rounding the whole input to a multiple of 512 bytes.
  22. data = fin.read()
  23. # +1 because we need a byte to store the checksum.
  24. size = len(data) + 1
  25. # Round up to next multiple of 512.
  26. size += 511
  27. size -= size % 512
  28. if size >= 65536:
  29. sys.exit("%s: option ROM size too large" % sys.argv[1])
  30. # size-1 because a final byte is added below to store the checksum.
  31. data = data.ljust(size-1, '\0')
  32. data = data[:2] + chr(size/512) + data[3:]
  33. else:
  34. # Otherwise the input file specifies the size so use it.
  35. # -1 because we overwrite the last byte of the file with the checksum.
  36. size = size_byte * 512 - 1
  37. data = fin.read(size)
  38. fout.write(data)
  39. checksum = 0
  40. for b in data:
  41. # catch Python 2 vs. 3 differences
  42. if isinstance(b, int):
  43. checksum += b
  44. else:
  45. checksum += ord(b)
  46. checksum = (256 - checksum) % 256
  47. # Python 3 no longer allows chr(checksum)
  48. fout.write(struct.pack('B', checksum))
  49. fin.close()
  50. fout.close()