blob: 43693dba56f7c28bb1072f0b3683e6552b8cf48e [file] [log] [blame]
Paolo Bonzinib38c2452020-02-04 17:00:28 +01001#!/usr/bin/env python3
2
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +01003#
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
12import sys
13import struct
14
15if len(sys.argv) < 3:
16 print('usage: signrom.py input output')
17 sys.exit(1)
18
19fin = open(sys.argv[1], 'rb')
20fout = open(sys.argv[2], 'wb')
21
Richard W.M. Jonesfd289382016-05-11 22:06:46 +010022magic = fin.read(2)
Daniel P. Berrange31d8f922018-01-16 13:42:12 +000023if magic != b'\x55\xaa':
Richard W.M. Jonesfd289382016-05-11 22:06:46 +010024 sys.exit("%s: option ROM does not begin with magic 55 aa" % sys.argv[1])
25
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010026size_byte = ord(fin.read(1))
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +010027fin.seek(0)
Paolo Bonzini7f256922016-08-05 10:51:37 +020028data = fin.read()
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010029
Paolo Bonzini7f256922016-08-05 10:51:37 +020030size = size_byte * 512
31if len(data) > size:
32 sys.stderr.write('error: ROM is too large (%d > %d)\n' % (len(data), size))
33 sys.exit(1)
34elif len(data) < size:
35 # Add padding if necessary, rounding the whole input to a multiple of
36 # 512 bytes according to the third byte of the input.
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010037 # size-1 because a final byte is added below to store the checksum.
Daniel P. Berrange31d8f922018-01-16 13:42:12 +000038 data = data.ljust(size-1, b'\0')
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010039else:
Paolo Bonzini7f256922016-08-05 10:51:37 +020040 if ord(data[-1:]) != 0:
41 sys.stderr.write('WARNING: ROM includes nonzero checksum\n')
42 data = data[:size-1]
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010043
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +010044fout.write(data)
45
46checksum = 0
47for b in data:
Paolo Bonzinib38c2452020-02-04 17:00:28 +010048 checksum = (checksum - b) & 255
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +010049
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +010050fout.write(struct.pack('B', checksum))
51
52fin.close()
53fout.close()