blob: 313ee28a17753171d9e34b19479199b9fba4adf4 [file] [log] [blame]
Eduardo Habkostf03868b2018-06-08 09:29:43 -03001from __future__ import print_function
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +01002#
3# Option ROM signing utility
4#
5# Authors:
6# Jan Kiszka <jan.kiszka@siemens.com>
7#
8# This work is licensed under the terms of the GNU GPL, version 2 or later.
9# See the COPYING file in the top-level directory.
10
11import sys
12import struct
13
14if len(sys.argv) < 3:
15 print('usage: signrom.py input output')
16 sys.exit(1)
17
18fin = open(sys.argv[1], 'rb')
19fout = open(sys.argv[2], 'wb')
20
Richard W.M. Jonesfd289382016-05-11 22:06:46 +010021magic = fin.read(2)
Daniel P. Berrange31d8f922018-01-16 13:42:12 +000022if magic != b'\x55\xaa':
Richard W.M. Jonesfd289382016-05-11 22:06:46 +010023 sys.exit("%s: option ROM does not begin with magic 55 aa" % sys.argv[1])
24
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010025size_byte = ord(fin.read(1))
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +010026fin.seek(0)
Paolo Bonzini7f256922016-08-05 10:51:37 +020027data = fin.read()
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010028
Paolo Bonzini7f256922016-08-05 10:51:37 +020029size = size_byte * 512
30if len(data) > size:
31 sys.stderr.write('error: ROM is too large (%d > %d)\n' % (len(data), size))
32 sys.exit(1)
33elif len(data) < size:
34 # Add padding if necessary, rounding the whole input to a multiple of
35 # 512 bytes according to the third byte of the input.
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010036 # size-1 because a final byte is added below to store the checksum.
Daniel P. Berrange31d8f922018-01-16 13:42:12 +000037 data = data.ljust(size-1, b'\0')
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010038else:
Paolo Bonzini7f256922016-08-05 10:51:37 +020039 if ord(data[-1:]) != 0:
40 sys.stderr.write('WARNING: ROM includes nonzero checksum\n')
41 data = data[:size-1]
Richard W.M. Jones6f71b772016-05-11 22:06:45 +010042
Jan Kiszka0d6b9cc2012-01-27 19:44:53 +010043fout.write(data)
44
45checksum = 0
46for b in data:
47 # catch Python 2 vs. 3 differences
48 if isinstance(b, int):
49 checksum += b
50 else:
51 checksum += ord(b)
52checksum = (256 - checksum) % 256
53
54# Python 3 no longer allows chr(checksum)
55fout.write(struct.pack('B', checksum))
56
57fin.close()
58fout.close()