Jan Kiszka | 0d6b9cc | 2012-01-27 19:44:53 +0100 | [diff] [blame] | 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 | |
| 10 | import sys |
| 11 | import struct |
| 12 | |
| 13 | if len(sys.argv) < 3: |
| 14 | print('usage: signrom.py input output') |
| 15 | sys.exit(1) |
| 16 | |
| 17 | fin = open(sys.argv[1], 'rb') |
| 18 | fout = open(sys.argv[2], 'wb') |
| 19 | |
Richard W.M. Jones | fd28938 | 2016-05-11 22:06:46 +0100 | [diff] [blame] | 20 | magic = fin.read(2) |
| 21 | if magic != '\x55\xaa': |
| 22 | sys.exit("%s: option ROM does not begin with magic 55 aa" % sys.argv[1]) |
| 23 | |
Richard W.M. Jones | 6f71b77 | 2016-05-11 22:06:45 +0100 | [diff] [blame] | 24 | size_byte = ord(fin.read(1)) |
Jan Kiszka | 0d6b9cc | 2012-01-27 19:44:53 +0100 | [diff] [blame] | 25 | fin.seek(0) |
Paolo Bonzini | 7f25692 | 2016-08-05 10:51:37 +0200 | [diff] [blame] | 26 | data = fin.read() |
Richard W.M. Jones | 6f71b77 | 2016-05-11 22:06:45 +0100 | [diff] [blame] | 27 | |
Paolo Bonzini | 7f25692 | 2016-08-05 10:51:37 +0200 | [diff] [blame] | 28 | size = size_byte * 512 |
| 29 | if len(data) > size: |
| 30 | sys.stderr.write('error: ROM is too large (%d > %d)\n' % (len(data), size)) |
| 31 | sys.exit(1) |
| 32 | elif len(data) < size: |
| 33 | # Add padding if necessary, rounding the whole input to a multiple of |
| 34 | # 512 bytes according to the third byte of the input. |
Richard W.M. Jones | 6f71b77 | 2016-05-11 22:06:45 +0100 | [diff] [blame] | 35 | # size-1 because a final byte is added below to store the checksum. |
| 36 | data = data.ljust(size-1, '\0') |
Richard W.M. Jones | 6f71b77 | 2016-05-11 22:06:45 +0100 | [diff] [blame] | 37 | else: |
Paolo Bonzini | 7f25692 | 2016-08-05 10:51:37 +0200 | [diff] [blame] | 38 | if ord(data[-1:]) != 0: |
| 39 | sys.stderr.write('WARNING: ROM includes nonzero checksum\n') |
| 40 | data = data[:size-1] |
Richard W.M. Jones | 6f71b77 | 2016-05-11 22:06:45 +0100 | [diff] [blame] | 41 | |
Jan Kiszka | 0d6b9cc | 2012-01-27 19:44:53 +0100 | [diff] [blame] | 42 | fout.write(data) |
| 43 | |
| 44 | checksum = 0 |
| 45 | for b in data: |
| 46 | # catch Python 2 vs. 3 differences |
| 47 | if isinstance(b, int): |
| 48 | checksum += b |
| 49 | else: |
| 50 | checksum += ord(b) |
| 51 | checksum = (256 - checksum) % 256 |
| 52 | |
| 53 | # Python 3 no longer allows chr(checksum) |
| 54 | fout.write(struct.pack('B', checksum)) |
| 55 | |
| 56 | fin.close() |
| 57 | fout.close() |