|
2 | 2 | # fix_checksum.py - compute LPC vector table checksum |
3 | 3 | # |
4 | 4 | # The LPC54S018 boot ROM requires that vector table entries 0-7 sum to zero. |
5 | | -# The vector table starts at offset 0x200 in the binary (after the 512-byte |
6 | | -# SPIFI configuration block). |
7 | | -# |
8 | | -# This script patches entry[7] so that sum(entries[0:8]) == 0 (mod 2^32). |
| 5 | +# Auto-detects whether vector table is at offset 0 (RAM build) or 0x200 |
| 6 | +# (SPIFI flash build with 512-byte config block). |
9 | 7 |
|
10 | 8 | import struct |
11 | 9 | import sys |
12 | 10 |
|
13 | | -SPIFI_CONFIG_SIZE = 0x200 # 512-byte SPIFI config block before vector table |
| 11 | +def find_vector_offset(data): |
| 12 | + """Detect vector table offset by checking for valid SP.""" |
| 13 | + for off in (0, 0x200): |
| 14 | + if off + 32 > len(data): |
| 15 | + continue |
| 16 | + sp = struct.unpack_from('<I', data, off)[0] |
| 17 | + if 0x20000000 <= sp <= 0x20030000: |
| 18 | + return off |
| 19 | + return 0 |
14 | 20 |
|
15 | 21 | def main(): |
16 | 22 | if len(sys.argv) != 2: |
17 | | - print(f"Usage: {sys.argv[0]} <app.bin>") |
| 23 | + print("Usage: %s <app.bin>" % sys.argv[0]) |
18 | 24 | sys.exit(1) |
19 | 25 |
|
20 | 26 | fname = sys.argv[1] |
21 | 27 | with open(fname, 'r+b') as f: |
22 | | - f.seek(SPIFI_CONFIG_SIZE) |
23 | | - data = f.read(32) |
24 | | - if len(data) < 32: |
25 | | - print(f"Error: file too small (need at least {SPIFI_CONFIG_SIZE + 32} bytes)") |
| 28 | + data = f.read() |
| 29 | + off = find_vector_offset(data) |
| 30 | + |
| 31 | + if off + 32 > len(data): |
| 32 | + print("Error: file too small") |
26 | 33 | sys.exit(1) |
27 | 34 |
|
28 | | - vecs = list(struct.unpack('<8I', data)) |
29 | | - # Compute checksum: entry[7] = -(sum of entries 0-6) mod 2^32 |
| 35 | + vecs = list(struct.unpack_from('<8I', data, off)) |
30 | 36 | partial_sum = sum(vecs[:7]) & 0xFFFFFFFF |
31 | 37 | cksum = (0x100000000 - partial_sum) & 0xFFFFFFFF |
32 | | - vecs[7] = cksum |
33 | 38 |
|
34 | | - # Write back |
35 | | - f.seek(SPIFI_CONFIG_SIZE + 7 * 4) |
| 39 | + f.seek(off + 7 * 4) |
36 | 40 | f.write(struct.pack('<I', cksum)) |
37 | 41 |
|
38 | | - # Verify |
39 | 42 | with open(fname, 'rb') as f: |
40 | | - f.seek(SPIFI_CONFIG_SIZE) |
| 43 | + f.seek(off) |
41 | 44 | vecs = struct.unpack('<8I', f.read(32)) |
42 | 45 | total = sum(vecs) & 0xFFFFFFFF |
43 | 46 | if total != 0: |
44 | | - print(f"ERROR: checksum verification failed (sum=0x{total:08X})") |
| 47 | + print("ERROR: checksum verification failed (sum=0x%08X)" % total) |
45 | 48 | sys.exit(1) |
46 | 49 |
|
47 | | - print(f"Vector checksum patched: entry[7]=0x{cksum:08X}") |
| 50 | + print("Vector checksum patched: offset=0x%X entry[7]=0x%08X" % (off, cksum)) |
48 | 51 |
|
49 | 52 | if __name__ == '__main__': |
50 | 53 | main() |
0 commit comments