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) |
Richard W.M. Jones | 6f71b77 | 2016-05-11 22:06:45 +0100 | [diff] [blame] | 26 | |
| 27 | if size_byte == 0: |
| 28 | # If the caller left the size field blank then we will fill it in, |
| 29 | # also rounding the whole input to a multiple of 512 bytes. |
| 30 | data = fin.read() |
| 31 | # +1 because we need a byte to store the checksum. |
| 32 | size = len(data) + 1 |
| 33 | # Round up to next multiple of 512. |
| 34 | size += 511 |
| 35 | size -= size % 512 |
| 36 | if size >= 65536: |
| 37 | sys.exit("%s: option ROM size too large" % sys.argv[1]) |
| 38 | # size-1 because a final byte is added below to store the checksum. |
| 39 | data = data.ljust(size-1, '\0') |
| 40 | data = data[:2] + chr(size/512) + data[3:] |
| 41 | else: |
| 42 | # Otherwise the input file specifies the size so use it. |
| 43 | # -1 because we overwrite the last byte of the file with the checksum. |
| 44 | size = size_byte * 512 - 1 |
| 45 | data = fin.read(size) |
| 46 | |
Jan Kiszka | 0d6b9cc | 2012-01-27 19:44:53 +0100 | [diff] [blame] | 47 | fout.write(data) |
| 48 | |
| 49 | checksum = 0 |
| 50 | for b in data: |
| 51 | # catch Python 2 vs. 3 differences |
| 52 | if isinstance(b, int): |
| 53 | checksum += b |
| 54 | else: |
| 55 | checksum += ord(b) |
| 56 | checksum = (256 - checksum) % 256 |
| 57 | |
| 58 | # Python 3 no longer allows chr(checksum) |
| 59 | fout.write(struct.pack('B', checksum)) |
| 60 | |
| 61 | fin.close() |
| 62 | fout.close() |