-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdisasm51.py
executable file
·144 lines (133 loc) · 4.53 KB
/
disasm51.py
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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
#!/usr/bin/env python3
#
# Disassembler 8051/8052
#
# Copyright (c) 2022 Aleksander Mazur
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys, argparse, re, enum
import addresses, instructions, codeanalyzer, utils
MAX_ROM_SIZE = 0x10000
# Parse arguments
def auto_int(x):
return int(x, 0)
def convert_array(x):
result = list(map(auto_int, x.split(':')))
if len(result) == 2:
result.append(2)
if (len(result) == 3) and (result[1] > result[0]) and (result[2] > 0):
return result
def auto_array(x):
result = convert_array(x)
if result:
return result
raise ValueError()
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version='%(prog)s 1.0')
parser.add_argument('--include', action='append', help='include .mcu file')
parser.add_argument('--entry', action='append', help='entry points (where code execution might begin)')
parser.add_argument('--offset', type=auto_int, default=0, help='where ROM is mapped in the address space')
parser.add_argument('--no-return-from', type=auto_int, action='append', help='no return from call to this address')
parser.add_argument('--indirect', type=auto_array, action='append', help='array of indirect jump addresses')
parser.add_argument('--force', action='store_true', help='treat whole ROM as code (disassemble everything)')
parser.add_argument('bin', help='binary dump of program memory (ROM)')
args = parser.parse_args()
if not args.entry:
# Default entry point
args.entry = ['RESET']
# Start generating output
print('; Generated by disasm51.py')
print('; Copyright (c) 2022 Aleksander Mazur')
print('; https://github.com/OlekMazur/disasm51')
print(';')
print('; Source file: %s' % args.bin)
# Prepare opcodes database
instructions = instructions.Instructions()
# Prepare addresses database
addresses = addresses.Addresses()
# Prepare database of known possible entry points
known_eps = { 'RESET': 0 }
# Process include files
if args.include:
print('\n$nomod51')
for include in args.include:
print('$include (%s)' % include)
with open(include, 'r') as f:
known_eps.update(addresses.include(f))
# Load ROM binary file
with open(args.bin, 'r') as f:
rom = f.buffer.read(MAX_ROM_SIZE)
# Collect entry points
entrypoints = []
for ep in args.entry:
if ep in known_eps:
ep = known_eps[ep]
else:
array = convert_array(ep)
if array:
[address, end, increment] = array
if end >= len(rom):
end = len(rom)
while address < end:
entrypoints.append(address)
address += increment
continue
else:
ep = int(ep, 0)
if ep < len(rom):
entrypoints.append(ep)
else:
print('warning: entry point %s beyond %s' % (utils.int2hex(ep), args.bin), file=sys.stderr)
indirect = {}
if args.indirect:
for [address, end, increment] in args.indirect:
while address < end:
if address + 1 < len(rom):
indirect[address] = True
entrypoints.append((rom[address] << 8) | rom[address + 1])
address += increment
# Start code segment
print('\ncseg')
# Initialize code analyzer
analyzer = codeanalyzer.CodeAnalyzer(instructions, rom, addresses, args.force, args.offset, args.no_return_from, indirect)
# Extract addresses of code blocks by analyzing jumps, starting from known entry points
code_blocks: dict[int, int] = {} # key=address, value=length
while len(entrypoints) > 0:
pc = entrypoints[0]
entrypoints = entrypoints[1:]
end = analyzer.analyze_jumps(pc, entrypoints, args.force)
if end != pc:
code_blocks[pc] = end - pc
# Automatic labels
analyzer.give_auto_labels()
# Process code blocks in the order of ascending addresses
starts = sorted(code_blocks.keys())
starts.append(len(rom))
end = 0 # where last block ended
for i in range(0, len(starts)):
start = starts[i]
if start in code_blocks:
length = code_blocks[start]
if i + 1 < len(starts):
start_next = starts[i + 1]
if length > start_next - start:
length = start_next - start
else:
length = 0
if start < end:
print('; overlapping %d byte(s)' % (end - start))
else:
end = analyzer.dump_binary_block(end, start, False)
if length:
end = analyzer.disassemble_code_block(start, start + length, start < end)
print('\nend')