blob: 6c8b9bf40653c82c729b9af1e1ff48664346692a [file] [log] [blame]
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +01001#
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
10import sys
11import struct
12
13if len(sys.argv) < 3:
14 print('usage: signrom.py input output')
15 sys.exit(1)
16
17fin = open(sys.argv[1], 'rb')
18fout = open(sys.argv[2], 'wb')
19
20fin.seek(2)
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010021size_byte = ord(fin.read(1))
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +010022fin.seek(0)
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010023
24if size_byte == 0:
25 # If the caller left the size field blank then we will fill it in,
26 # also rounding the whole input to a multiple of 512 bytes.
27 data = fin.read()
28 # +1 because we need a byte to store the checksum.
29 size = len(data) + 1
30 # Round up to next multiple of 512.
31 size += 511
32 size -= size % 512
33 if size >= 65536:
34 sys.exit("%s: option ROM size too large" % sys.argv[1])
35 # size-1 because a final byte is added below to store the checksum.
36 data = data.ljust(size-1, '\0')
37 data = data[:2] + chr(size/512) + data[3:]
38else:
39 # Otherwise the input file specifies the size so use it.
40 # -1 because we overwrite the last byte of the file with the checksum.
41 size = size_byte * 512 - 1
42 data = fin.read(size)
43
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +010044fout.write(data)
45
46checksum = 0
47for b in data:
48 # catch Python 2 vs. 3 differences
49 if isinstance(b, int):
50 checksum += b
51 else:
52 checksum += ord(b)
53checksum = (256 - checksum) % 256
54
55# Python 3 no longer allows chr(checksum)
56fout.write(struct.pack('B', checksum))
57
58fin.close()
59fout.close()