Merge remote-tracking branch 'remotes/dagrh/tags/pull-virtiofs-20211026' into staging
[qemu.git] / scripts / signrom.py
1 #!/usr/bin/env python3
2
3 #
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
12 import sys
13 import struct
14
15 if len(sys.argv) < 3:
16 print('usage: signrom.py input output')
17 sys.exit(1)
18
19 fin = open(sys.argv[1], 'rb')
20 fout = open(sys.argv[2], 'wb')
21
22 magic = fin.read(2)
23 if magic != b'\x55\xaa':
24 sys.exit("%s: option ROM does not begin with magic 55 aa" % sys.argv[1])
25
26 size_byte = ord(fin.read(1))
27 fin.seek(0)
28 data = fin.read()
29
30 size = size_byte * 512
31 if len(data) > size:
32 sys.stderr.write('error: ROM is too large (%d > %d)\n' % (len(data), size))
33 sys.exit(1)
34 elif 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.
37 # size-1 because a final byte is added below to store the checksum.
38 data = data.ljust(size-1, b'\0')
39 else:
40 if ord(data[-1:]) != 0:
41 sys.stderr.write('WARNING: ROM includes nonzero checksum\n')
42 data = data[:size-1]
43
44 fout.write(data)
45
46 checksum = 0
47 for b in data:
48 checksum = (checksum - b) & 255
49
50 fout.write(struct.pack('B', checksum))
51
52 fin.close()
53 fout.close()