summaryrefslogtreecommitdiff
path: root/source/notes/pic-mcu/pickit2/pk2cmd-stuff/hexdisasm.py
blob: 0c86592a82453c5050686c8bffaafe62bd86dda9 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
import pic24
import pic18
import pic16
import sys

arch = "pic18"

hexfile = '../pk2cmd/pk2cmd/PK2V023200.hex'

if len(sys.argv) > 1:
    hexfile = sys.argv[1]

    if len(sys.argv) > 2:
        arch = sys.argv[2]

if arch == "pic24":
    arch = pic24
elif arch == "pic18":
    arch = pic18
elif arch == "pic16":
    arch = pic16
else:
    raise Exception("Invalid arch " + arch)

lines = open(hexfile).readlines()

def read_hex(lines):
    regions = { 0: [0] * 0x10000 }
    curr_region = regions[0]

    for line in lines:
        if not line.startswith(':'):
            continue
#            raise Exception("invalid hex line, needs to start with a ':', but was: " + line)
        bytecount = int(line[1:3], 16)
        addr = int(line[3:7], 16)
        rec_type = int(line[7:9], 16)
        data_end = bytecount * 2 + 9
        data = line[9:data_end]
        # ignoring checksum because lazy

        if rec_type == 4:
            ext_linear_addr = int(data, 16)
            if ext_linear_addr not in regions:
                regions[ext_linear_addr] = [0] * 0x10000

            curr_region = regions[ext_linear_addr]
        elif rec_type == 0:
            for i in range(bytecount):
                curr_region[addr + i] = int(data[i*2:i*2 + 2], 16)
        elif rec_type == 1:
            print("Read HEX file")
            return regions
        else:
            raise Exception("Unsupported record type: " + str(rec_type))


memory_regions = read_hex(lines)

i = 0

coderegion = memory_regions[0]

while i < len(coderegion):
    (i, instr) = arch.disassemble(coderegion, i)
    if "Unknown instr" in instr:
        print(instr)
    elif 'op' not in instr:
        print(instr['mnemonic'])
    else:
        print("{} {}".format(instr['mnemonic'], instr['op']))