-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTIZ80Arch.py
440 lines (363 loc) · 17.9 KB
/
TIZ80Arch.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
#####################################################################################################
# #
# Architecture is pulled from the Vector35 Z80 Architecture plugin and modified for the TI calls #
# https://github.com/Vector35/Z80/blob/master/Z80Arch.py #
# #
# Changes made: #
# - Added code to get_instruction_info that checks if the command is RST, if it is then set #
# length to 3. #
# - Added code to get_instruction_text that checks if the command is RST, if it is then #
# parse the next two bytes and lookup the associated romcall. Then set the name. #
# #
#####################################################################################################
import re
from binaryninja.architecture import Architecture
from binaryninja.function import RegisterInfo, InstructionInfo, InstructionTextToken
from binaryninja.enums import InstructionTextTokenType, BranchType, FlagRole, LowLevelILFlagCondition, Endianness
from .rom_calls import *
from z80dis.z80 import *
CC_TO_STR = {
CC.ALWAYS:'1', CC.NOT_N:'nn', CC.N:'n', CC.NOT_Z:'nz', CC.Z:'z',
CC.NOT_C:'nc', CC.C:'c', CC.NOT_P:'po', CC.P:'pe', CC.NOT_S:'p', CC.S:'m',
CC.NOT_H:'nh', CC.H:'h'
}
class TIZ80(Architecture):
name = 'TI-Z80'
address_size = 2
default_int_size = 1
instr_alignment = 1
max_instr_length = 4
endianness = Endianness.LittleEndian
# register related stuff
regs = {
# main registers
'AF': RegisterInfo('AF', 2),
'BC': RegisterInfo('BC', 2),
'DE': RegisterInfo('DE', 2),
'HL': RegisterInfo('HL', 2),
# alternate registers
"AF'": RegisterInfo("AF'", 2),
"BC'": RegisterInfo("BC'", 2),
"DE'": RegisterInfo("DE'", 2),
"HL'": RegisterInfo("HL'", 2),
# main registers (sub)
"A": RegisterInfo("AF", 1, 1),
"F": RegisterInfo("AF", 1, 0),
"B": RegisterInfo("BC", 1, 1),
"C": RegisterInfo("BC", 1, 0),
"D": RegisterInfo("DE", 1, 1),
"E": RegisterInfo("DE", 1, 0),
"H": RegisterInfo("HL", 1, 1),
"L": RegisterInfo("HL", 1, 0),
"Flags": RegisterInfo("AF", 0),
# alternate registers (sub)
"A'": RegisterInfo("AF'", 1, 1),
"F'": RegisterInfo("AF'", 1, 0),
"B'": RegisterInfo("BC'", 1, 1),
"C'": RegisterInfo("BC'", 1, 0),
"D'": RegisterInfo("DE'", 1, 1),
"E'": RegisterInfo("DE'", 1, 0),
"H'": RegisterInfo("HL'", 1, 1),
"L'": RegisterInfo("HL'", 1, 0),
"Flags'": RegisterInfo("AF'", 0),
# index registers
'IX': RegisterInfo('IX', 2),
'IY': RegisterInfo('IY', 2),
'SP': RegisterInfo('SP', 2),
# other registers
'I': RegisterInfo('I', 1),
'R': RegisterInfo('R', 1),
# program counter
'PC': RegisterInfo('PC', 2),
# status
'status': RegisterInfo('status', 1)
}
stack_pointer = "SP"
#------------------------------------------------------------------------------
# FLAG fun
#------------------------------------------------------------------------------
flags = ['s', 'z', 'h', 'pv', 'n', 'c']
# remember, class None is default/integer
semantic_flag_classes = ['class_bitstuff']
# flag write types and their mappings
flag_write_types = ['dummy', '*', 'c', 'z', 'cszpv', 'not_c']
flags_written_by_flag_write_type = {
'dummy': [],
'*': ['s', 'z', 'h', 'pv', 'n', 'c'],
'c': ['c'],
'z': ['z'],
'not_c': ['s', 'z', 'h', 'pv', 'n'] # eg: z80's DEC
}
semantic_class_for_flag_write_type = {
# by default, everything is type None (integer)
# '*': 'class_integer',
# 'c': 'class_integer',
# 'z': 'class_integer',
# 'cszpv': 'class_integer',
# 'not_c': 'class_integer'
}
# groups and their mappings
semantic_flag_groups = ['group_e', 'group_ne', 'group_lt']
flags_required_for_semantic_flag_group = {
'group_lt': ['c'],
'group_e': ['z'],
'group_ne': ['z']
}
flag_conditions_for_semantic_flag_group = {
#'group_e': {None: LowLevelILFlagCondition.LLFC_E},
#'group_ne': {None: LowLevelILFlagCondition.LLFC_NE}
}
# roles
flag_roles = {
's': FlagRole.NegativeSignFlagRole,
'z': FlagRole.ZeroFlagRole,
'h': FlagRole.HalfCarryFlagRole,
'pv': FlagRole.OverflowFlagRole, # actually overflow or parity: TODO: implement later
'n': FlagRole.SpecialFlagRole, # set if last instruction was a subtraction (incl. CP)
'c': FlagRole.CarryFlagRole
}
# MAP (condition x class) -> flags
def get_flags_required_for_flag_condition(self, cond, sem_class):
#LogDebug('incoming cond: %s, incoming sem_class: %s' % (str(cond), str(sem_class)))
if sem_class == None:
lookup = {
# Z, zero flag for == and !=
LowLevelILFlagCondition.LLFC_E: ['z'],
LowLevelILFlagCondition.LLFC_NE: ['z'],
# S, sign flag is in NEG and POS
LowLevelILFlagCondition.LLFC_NEG: ['s'],
# Z, zero flag for == and !=
LowLevelILFlagCondition.LLFC_E: ['z'],
LowLevelILFlagCondition.LLFC_NE: ['z'],
# H, half carry for ???
# P, parity for ???
# s> s>= s< s<= done by sub and overflow test
#if cond == LowLevelILFlagCondition.LLFC_SGT:
#if cond == LowLevelILFlagCondition.LLFC_SGE:
#if cond == LowLevelILFlagCondition.LLFC_SLT:
#if cond == LowLevelILFlagCondition.LLFC_SLE:
# C, for these
LowLevelILFlagCondition.LLFC_UGE: ['c'],
LowLevelILFlagCondition.LLFC_ULT: ['c']
}
if cond in lookup:
return lookup[cond]
return []
#------------------------------------------------------------------------------
# CFG building
#------------------------------------------------------------------------------
def get_instruction_info(self, data, addr):
decoded = decode(data, addr)
# on error, return nothing
if decoded.status == DECODE_STATUS.ERROR or decoded.len == 0:
return None
# on non-branching, return length
result = InstructionInfo()
result.length = decoded.len
# changes for the TI from Z80
if decoded.op.name == "RST" and decoded.operands[0][1] == 0x28:
result.length = 3
return result
if decoded.typ != INSTRTYPE.JUMP_CALL_RETURN:
return result
# jp has several variations
if decoded.op == OP.JP:
(oper_type, oper_val) = decoded.operands[0]
# jp pe,0xDEAD
if oper_type == OPER_TYPE.COND:
assert decoded.operands[1][0] == OPER_TYPE.ADDR
result.add_branch(BranchType.TrueBranch, decoded.operands[1][1])
result.add_branch(BranchType.FalseBranch, addr + decoded.len)
# jp (hl); jp (ix); jp (iy)
elif oper_type in [OPER_TYPE.REG_DEREF, OPER_TYPE.MEM_DISPL_IX, OPER_TYPE.MEM_DISPL_IY]:
result.add_branch(BranchType.IndirectBranch)
# jp 0xDEAD
elif oper_type == OPER_TYPE.ADDR:
result.add_branch(BranchType.UnconditionalBranch, oper_val)
else:
raise Exception('handling JP')
# jr can be conditional
elif decoded.op == OP.JR:
(oper_type, oper_val) = decoded.operands[0]
# jr c,0xdf07
if oper_type == OPER_TYPE.COND:
assert decoded.operands[1][0] == OPER_TYPE.ADDR
result.add_branch(BranchType.TrueBranch, decoded.operands[1][1])
result.add_branch(BranchType.FalseBranch, addr + decoded.len)
# jr 0xdf07
elif oper_type == OPER_TYPE.ADDR:
result.add_branch(BranchType.UnconditionalBranch, oper_val)
else:
raise Exception('handling JR')
# djnz is implicitly conditional
elif decoded.op == OP.DJNZ:
(oper_type, oper_val) = decoded.operands[0]
assert oper_type == OPER_TYPE.ADDR
result.add_branch(BranchType.TrueBranch, oper_val)
result.add_branch(BranchType.FalseBranch, addr + decoded.len)
# call can be conditional
elif decoded.op == OP.CALL:
(oper_type, oper_val) = decoded.operands[0]
# call c,0xdf07
if oper_type == OPER_TYPE.COND:
assert decoded.operands[1][0] == OPER_TYPE.ADDR
result.add_branch(BranchType.CallDestination, decoded.operands[1][1])
# call 0xdf07
elif oper_type == OPER_TYPE.ADDR:
result.add_branch(BranchType.CallDestination, oper_val)
else:
raise Exception('handling CALL')
# ret can be conditional
elif decoded.op == OP.RET:
if decoded.operands and decoded.operands[0][0] == OPER_TYPE.COND:
# conditional returns dont' end block
pass
else:
result.add_branch(BranchType.FunctionReturn)
# ret from interrupts
elif decoded.op == OP.RETI or decoded.op == OP.RETN:
result.add_branch(BranchType.FunctionReturn)
return result
#------------------------------------------------------------------------------
# STRING building, disassembly
#------------------------------------------------------------------------------
def reg2str(self, r):
reg_name = r.name
return reg_name if reg_name[-1] != '_' else reg_name[:-1]+"'"
# from api/python/function.py:
#
# TextToken Text that doesn't fit into the other tokens
# InstructionToken The instruction mnemonic
# OperandSeparatorToken The comma or whatever else separates tokens
# RegisterToken Registers
# IntegerToken Integers
# PossibleAddressToken Integers that are likely addresses
# BeginMemoryOperandToken The start of memory operand
# EndMemoryOperandToken The end of a memory operand
# FloatingPointToken Floating point number
def get_instruction_text(self, data, addr):
decoded = decode(data, addr)
if decoded.status != DECODE_STATUS.OK or decoded.len == 0:
print(decoded.op.name, data, addr)
return None
result = []
# changes from TI for z80
if decoded.op.name == "RST" and decoded.operands[0][1] == 0x28:
result.append(InstructionTextToken(InstructionTextTokenType.TextToken, 'BCALL'))
result.append(InstructionTextToken(InstructionTextTokenType.TextToken, ' '))
# get the corresponding rom call for the ti
result.append(InstructionTextToken(InstructionTextTokenType.TextToken, rom_calls[int.from_bytes(data[1:3], "little")]))
return result, 3
else:
# opcode
result.append(InstructionTextToken( \
InstructionTextTokenType.InstructionToken, decoded.op.name))
# space for operand
if decoded.operands:
result.append(InstructionTextToken(InstructionTextTokenType.TextToken, ' '))
# operands
for i, operand in enumerate(decoded.operands):
(oper_type, oper_val) = operand
if oper_type == OPER_TYPE.REG:
result.append(InstructionTextToken( \
InstructionTextTokenType.RegisterToken, self.reg2str(oper_val)))
elif oper_type == OPER_TYPE.REG_DEREF:
result.append(InstructionTextToken( \
InstructionTextTokenType.BeginMemoryOperandToken, '('))
result.append(InstructionTextToken( \
InstructionTextTokenType.RegisterToken, self.reg2str(oper_val)))
result.append(InstructionTextToken( \
InstructionTextTokenType.EndMemoryOperandToken, ')'))
elif oper_type == OPER_TYPE.ADDR:
if oper_val < 0:
oper_val = oper_val & 0xFFFF
txt = '0x%04x' % oper_val
result.append(InstructionTextToken( \
InstructionTextTokenType.PossibleAddressToken, txt, oper_val))
elif oper_type == OPER_TYPE.ADDR_DEREF:
result.append(InstructionTextToken( \
InstructionTextTokenType.BeginMemoryOperandToken, '('))
txt = '0x%04x' % oper_val
result.append(InstructionTextToken( \
InstructionTextTokenType.PossibleAddressToken, txt, oper_val))
result.append(InstructionTextToken( \
InstructionTextTokenType.EndMemoryOperandToken, ')'))
elif oper_type in [OPER_TYPE.MEM_DISPL_IX, OPER_TYPE.MEM_DISPL_IY]:
result.append(InstructionTextToken( \
InstructionTextTokenType.BeginMemoryOperandToken, '('))
txt = 'IX' if oper_type == OPER_TYPE.MEM_DISPL_IX else 'IY'
result.append(InstructionTextToken( \
InstructionTextTokenType.RegisterToken, txt))
if oper_val == 0:
# omit displacement of 0
pass
elif oper_val >= 16:
# (iy+0x28)
result.append(InstructionTextToken( \
InstructionTextTokenType.TextToken, '+'))
result.append(InstructionTextToken( \
InstructionTextTokenType.IntegerToken, '0x%X' % oper_val, oper_val))
elif oper_val > 0:
result.append(InstructionTextToken( \
InstructionTextTokenType.TextToken, '+'))
result.append(InstructionTextToken( \
InstructionTextTokenType.IntegerToken, '%d' % oper_val, oper_val))
elif oper_val <= -16:
# adc a,(ix-0x55)
result.append(InstructionTextToken( \
InstructionTextTokenType.TextToken, '-'))
result.append(InstructionTextToken( \
InstructionTextTokenType.IntegerToken, '0x%X' % (-oper_val), oper_val))
else:
result.append(InstructionTextToken( \
InstructionTextTokenType.IntegerToken, '%d' % oper_val, oper_val))
result.append(InstructionTextToken( \
InstructionTextTokenType.EndMemoryOperandToken, ')'))
elif oper_type == OPER_TYPE.IMM:
if oper_val == 0:
txt = '0'
elif oper_val >= 16:
txt = '0x%x' % oper_val
else:
txt = '%d' % oper_val
result.append(InstructionTextToken( \
InstructionTextTokenType.IntegerToken, txt, oper_val))
elif oper_type == OPER_TYPE.COND:
txt = CC_TO_STR[oper_val]
result.append(InstructionTextToken( \
InstructionTextTokenType.TextToken, txt))
elif oper_type in [OPER_TYPE.REG_C_DEREF, OPER_TYPE.REG_BC_DEREF, OPER_TYPE.REG_DE_DEREF, \
OPER_TYPE.REG_HL_DEREF, OPER_TYPE.REG_SP_DEREF]:
result.append(InstructionTextToken( \
InstructionTextTokenType.BeginMemoryOperandToken, '('))
result.append(InstructionTextToken( \
InstructionTextTokenType.RegisterToken, self.reg2str(oper_val)))
result.append(InstructionTextToken( \
InstructionTextTokenType.EndMemoryOperandToken, ')'))
else:
raise Exception('unknown operand type: ' + str(oper_type))
# if this isn't the last operand, add comma
if i < len(decoded.operands)-1:
result.append(InstructionTextToken( \
InstructionTextTokenType.OperandSeparatorToken, ','))
if decoded.metaLoad:
extras = []
(oper_type, oper_val) = decoded.metaLoad
assert oper_type == OPER_TYPE.REG
extras.append(InstructionTextToken( \
InstructionTextTokenType.InstructionToken, 'ld'))
extras.append(InstructionTextToken( \
InstructionTextTokenType.TextToken, ' '))
extras.append(InstructionTextToken( \
InstructionTextTokenType.RegisterToken, self.reg2str(oper_val)))
extras.append(InstructionTextToken( \
InstructionTextTokenType.OperandSeparatorToken, ','))
result = extras + result
return result, decoded.len
#------------------------------------------------------------------------------
# LIFTING
#------------------------------------------------------------------------------
def get_flag_write_low_level_il(self, op, size, write_type, flag, operands, il):
pass
def get_instruction_low_level_il(self, data, addr, il):
pass