grml...
[seabios.git] / tools / buildrom.py
1 #!/usr/bin/env python
2 # Fill in checksum/size of an option rom, and pad it to proper length.
3 #
4 # Copyright (C) 2009  Kevin O'Connor <kevin@koconnor.net>
5 #
6 # This file may be distributed under the terms of the GNU GPLv3 license.
7
8 import sys
9
10 def alignpos(pos, alignbytes):
11     mask = alignbytes - 1
12     return (pos + mask) & ~mask
13
14 def checksum(data):
15     ords = map(ord, data)
16     return sum(ords)
17
18 def main():
19     inname = sys.argv[1]
20     outname = sys.argv[2]
21
22     # Read data in
23     f = open(inname, 'rb')
24     data = f.read()
25     count = len(data)
26
27     # Pad to a 512 byte boundary
28     data += "\0" * (alignpos(count, 512) - count)
29     count = len(data)
30
31     # Check if a pci header is present
32     pcidata = ord(data[24:25]) + (ord(data[25:26]) << 8)
33     if pcidata != 0:
34         data = data[:pcidata + 16] + chr(count/512) + chr(0) + data[pcidata + 18:]
35
36     # Fill in size field; clear checksum field
37     data = data[:2] + chr(count/512) + data[3:6] + "\0" + data[7:]
38
39     # Checksum rom
40     newsum = (256 - checksum(data)) & 0xff
41     data = data[:6] + chr(newsum) + data[7:]
42
43     # Write new rom
44     f = open(outname, 'wb')
45     f.write(data)
46
47 if __name__ == '__main__':
48     main()