]> sigrok.org Git - libsigrokdecode.git/blob - decoders/z80/pd.py
z80: Format hex numbers with leading zero if necessary.
[libsigrokdecode.git] / decoders / z80 / pd.py
1 ##
2 ## This file is part of the libsigrokdecode project.
3 ##
4 ## Copyright (C) 2014 Daniel Elstner <daniel.kitta@gmail.com>
5 ##
6 ## This program is free software; you can redistribute it and/or modify
7 ## it under the terms of the GNU General Public License as published by
8 ## the Free Software Foundation; either version 3 of the License, or
9 ## (at your option) any later version.
10 ##
11 ## This program is distributed in the hope that it will be useful,
12 ## but WITHOUT ANY WARRANTY; without even the implied warranty of
13 ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14 ## GNU General Public License for more details.
15 ##
16 ## You should have received a copy of the GNU General Public License
17 ## along with this program; if not, see <http://www.gnu.org/licenses/>.
18 ##
19
20 import sigrokdecode as srd
21 from functools import reduce
22 from .tables import instr_table_by_prefix
23 import string
24
25 class Ann:
26     ADDR, MEMRD, MEMWR, IORD, IOWR, INSTR, ROP, WOP, WARN = range(9)
27 class Row:
28     ADDRBUS, DATABUS, INSTRUCTIONS, OPERANDS, WARNINGS = range(5)
29 class Pin:
30     D0, D7 = 0, 7
31     M1, RD, WR, MREQ, IORQ = range(8, 13)
32     A0, A15 = 13, 28
33 class Cycle:
34     NONE, MEMRD, MEMWR, IORD, IOWR, FETCH, INTACK = range(7)
35
36 class OpState:
37     IDLE    = 'IDLE'    # no current instruction
38     PRE1    = 'PRE1'    # first prefix
39     PRE2    = 'PRE2'    # second prefix
40     PREDIS  = 'PREDIS'  # pre-opcode displacement
41     OPCODE  = 'OPCODE'  # opcode byte
42     POSTDIS = 'POSTDIS' # post-opcode displacement
43     IMM1    = 'IMM1'    # first byte of immediate
44     IMM2    = 'IMM2'    # second byte of immediate
45     ROP1    = 'ROP1'    # first byte of read operand
46     ROP2    = 'ROP2'    # second byte of read operand
47     WOP1    = 'WOP1'    # first byte of write operand
48     WOP2    = 'WOP2'    # second byte of write operand
49     RESTART = 'RESTART' # restart instruction decoding
50
51 # Provide custom format type 'H' for hexadecimal output
52 # with leading decimal digit (assembler syntax).
53 class AsmFormatter(string.Formatter):
54     def format_field(self, value, format_spec):
55         if format_spec.endswith('H'):
56             result = format(value, format_spec[:-1] + 'X')
57             return result if result[0] in string.digits else '0' + result
58         else:
59             return format(value, format_spec)
60
61 formatter = AsmFormatter()
62
63 ann_data_cycle_map = {
64     Cycle.MEMRD:  Ann.MEMRD,
65     Cycle.MEMWR:  Ann.MEMWR,
66     Cycle.IORD:   Ann.IORD,
67     Cycle.IOWR:   Ann.IOWR,
68     Cycle.FETCH:  Ann.MEMRD,
69     Cycle.INTACK: Ann.IORD,
70 }
71
72 def reduce_bus(bus):
73     if 0xFF in bus:
74         return None # unassigned bus probes
75     else:
76         return reduce(lambda a, b: (a << 1) | b, reversed(bus))
77
78 def signed_byte(byte):
79     return byte if byte < 128 else byte - 256
80
81 class Decoder(srd.Decoder):
82     api_version = 1
83     id          = 'z80'
84     name        = 'Z80'
85     longname    = 'Zilog Z80 CPU'
86     desc        = 'Zilog Z80 microprocessor disassembly.'
87     license     = 'gplv2+'
88     inputs      = ['logic']
89     outputs     = ['z80']
90     probes = [
91         {'id': 'd%d' % i, 'name': 'D%d' % i, 'desc': 'Data bus line %d' % i}
92             for i in range(8)
93     ] + [
94         {'id': 'm1', 'name': '/M1', 'desc': 'Machine cycle 1'},
95         {'id': 'rd', 'name': '/RD', 'desc': 'Memory or I/O read'},
96         {'id': 'wr', 'name': '/WR', 'desc': 'Memory or I/O write'},
97     ]
98     optional_probes = [
99         {'id': 'mreq', 'name': '/MREQ', 'desc': 'Memory request'},
100         {'id': 'iorq', 'name': '/IORQ', 'desc': 'I/O request'},
101     ] + [
102         {'id': 'a%d' % i, 'name': 'A%d' % i, 'desc': 'Address bus line %d' % i}
103             for i in range(16)
104     ]
105     options = {}
106     annotations = [
107         ['addr',    'Memory or I/O address'],
108         ['memrd',   'Byte read from memory'],
109         ['memwr',   'Byte written to memory'],
110         ['iord',    'Byte read from I/O port'],
111         ['iowr',    'Byte written to I/O port'],
112         ['instr',   'Z80 CPU instruction'],
113         ['rop',     'Value of input operand'],
114         ['wop',     'Value of output operand'],
115         ['warning', 'Warning message'],
116     ]
117     annotation_rows = (
118         ('addrbus', 'Address bus', (Ann.ADDR,)),
119         ('databus', 'Data bus', (Ann.MEMRD, Ann.MEMWR, Ann.IORD, Ann.IOWR)),
120         ('instructions', 'Instructions', (Ann.INSTR,)),
121         ('operands', 'Operands', (Ann.ROP, Ann.WOP)),
122         ('warnings', 'Warnings', (Ann.WARN,))
123     )
124
125     def __init__(self, **kwargs):
126         self.prev_cycle = Cycle.NONE
127         self.op_state   = OpState.IDLE
128
129     def start(self):
130         self.out_ann    = self.register(srd.OUTPUT_ANN)
131         self.bus_data   = None
132         self.samplenum  = None
133         self.addr_start = None
134         self.data_start = None
135         self.dasm_start = None
136         self.pend_addr  = None
137         self.pend_data  = None
138         self.ann_data   = None
139         self.ann_dasm   = None
140         self.prev_cycle = Cycle.NONE
141         self.op_state   = OpState.IDLE
142
143     def decode(self, ss, es, data):
144         for (self.samplenum, pins) in data:
145             cycle = Cycle.NONE
146             if pins[Pin.MREQ] != 1: # default to asserted
147                 if pins[Pin.RD] == 0:
148                     cycle = Cycle.FETCH if pins[Pin.M1] == 0 else Cycle.MEMRD
149                 elif pins[Pin.WR] == 0:
150                     cycle = Cycle.MEMWR
151             elif pins[Pin.IORQ] == 0: # default to not asserted
152                 if pins[Pin.M1] == 0:
153                     cycle = Cycle.INTACK
154                 elif pins[Pin.RD] == 0:
155                     cycle = Cycle.IORD
156                 elif pins[Pin.WR] == 0:
157                     cycle = Cycle.IOWR
158
159             if cycle != Cycle.NONE:
160                 self.bus_data = reduce_bus(pins[Pin.D0:Pin.D7+1])
161             if cycle != self.prev_cycle:
162                 if self.prev_cycle == Cycle.NONE:
163                     self.on_cycle_begin(reduce_bus(pins[Pin.A0:Pin.A15+1]))
164                 elif cycle == Cycle.NONE:
165                     self.on_cycle_end()
166                 else:
167                     self.on_cycle_trans()
168             self.prev_cycle = cycle
169
170     def on_cycle_begin(self, bus_addr):
171         if self.pend_addr is not None:
172             self.put_text(self.addr_start, Ann.ADDR,
173                           '{:04X}'.format(self.pend_addr))
174         self.addr_start = self.samplenum
175         self.pend_addr  = bus_addr
176
177     def on_cycle_end(self):
178         self.op_state = getattr(self, 'on_state_' + self.op_state)()
179         if self.ann_dasm is not None:
180             self.put_disasm()
181         if self.op_state == OpState.RESTART:
182             self.op_state = self.on_state_IDLE()
183
184         if self.ann_data is not None:
185             self.put_text(self.data_start, self.ann_data,
186                           '{:02X}'.format(self.pend_data))
187         self.data_start = self.samplenum
188         self.pend_data  = self.bus_data
189         self.ann_data   = ann_data_cycle_map[self.prev_cycle]
190
191     def on_cycle_trans(self):
192         self.put_text(self.samplenum - 1, Ann.WARN,
193                       'Illegal transition between control states')
194         self.pend_addr = None
195         self.ann_data  = None
196         self.ann_dasm  = None
197
198     def put_disasm(self):
199         text = formatter.format(self.mnemonic, r=self.arg_reg,
200                                 d=self.arg_dis, i=self.arg_imm,
201                                 ro=self.arg_read, wo=self.arg_write)
202         self.put_text(self.dasm_start, self.ann_dasm, text)
203         self.ann_dasm   = None
204         self.dasm_start = self.samplenum
205
206     def put_text(self, ss, ann_idx, ann_text):
207         self.put(ss, self.samplenum, self.out_ann, [ann_idx, [ann_text]])
208
209     def on_state_IDLE(self):
210         if self.prev_cycle != Cycle.FETCH:
211             return OpState.IDLE
212         self.want_dis   = 0
213         self.want_imm   = 0
214         self.want_read  = 0
215         self.want_write = 0
216         self.want_wr_be = False
217         self.op_repeat  = False
218         self.arg_dis    = 0
219         self.arg_imm    = 0
220         self.arg_read   = 0
221         self.arg_write  = 0
222         self.arg_reg    = ''
223         self.mnemonic   = ''
224         self.instr_pend = False
225         self.read_pend  = False
226         self.write_pend = False
227         self.dasm_start = self.samplenum
228         self.op_prefix  = 0
229         if self.bus_data in (0xCB, 0xED, 0xDD, 0xFD):
230             return OpState.PRE1
231         else:
232             return OpState.OPCODE
233
234     def on_state_PRE1(self):
235         if self.prev_cycle != Cycle.FETCH:
236             self.mnemonic = 'Prefix not followed by fetch'
237             self.ann_dasm = Ann.WARN
238             return OpState.RESTART
239         self.op_prefix = self.pend_data
240         if self.op_prefix in (0xDD, 0xFD):
241             if self.bus_data == 0xCB:
242                 return OpState.PRE2
243             if self.bus_data in (0xDD, 0xED, 0xFD):
244                 return OpState.PRE1
245         return OpState.OPCODE
246
247     def on_state_PRE2(self):
248         if self.prev_cycle != Cycle.MEMRD:
249             self.mnemonic = 'Missing displacement'
250             self.ann_dasm = Ann.WARN
251             return OpState.RESTART
252         self.op_prefix = (self.op_prefix << 8) | self.pend_data
253         return OpState.PREDIS
254
255     def on_state_PREDIS(self):
256         if self.prev_cycle != Cycle.MEMRD:
257             self.mnemonic = 'Missing opcode'
258             self.ann_dasm = Ann.WARN
259             return OpState.RESTART
260         self.arg_dis = signed_byte(self.pend_data)
261         return OpState.OPCODE
262
263     def on_state_OPCODE(self):
264         (table, self.arg_reg) = instr_table_by_prefix[self.op_prefix]
265         self.op_prefix = 0
266         instruction = table.get(self.pend_data, None)
267         if instruction is None:
268             self.mnemonic = 'Invalid instruction'
269             self.ann_dasm = Ann.WARN
270             return OpState.RESTART
271         (self.want_dis, self.want_imm, self.want_read, want_write,
272                 self.op_repeat, self.mnemonic) = instruction
273         self.want_write = abs(want_write)
274         self.want_wr_be = (want_write < 0)
275         if self.want_dis > 0:
276             return OpState.POSTDIS
277         if self.want_imm > 0:
278             return OpState.IMM1
279         self.ann_dasm = Ann.INSTR
280         if self.want_read > 0 and self.prev_cycle in (Cycle.MEMRD, Cycle.IORD):
281             return OpState.ROP1
282         if self.want_write > 0 and self.prev_cycle in (Cycle.MEMWR, Cycle.IOWR):
283             return OpState.WOP1
284         return OpState.RESTART
285
286     def on_state_POSTDIS(self):
287         self.arg_dis = signed_byte(self.pend_data)
288         if self.want_imm > 0:
289             return OpState.IMM1
290         self.ann_dasm = Ann.INSTR
291         if self.want_read > 0:
292             return OpState.ROP1
293         if self.want_write > 0:
294             return OpState.WOP1
295         return OpState.RESTART
296
297     def on_state_IMM1(self):
298         self.arg_imm = self.pend_data
299         if self.want_imm > 1:
300             return OpState.IMM2
301         self.ann_dasm = Ann.INSTR
302         if self.want_read > 0:
303             return OpState.ROP1
304         if self.want_write > 0:
305             return OpState.WOP1
306         return OpState.RESTART
307
308     def on_state_IMM2(self):
309         self.arg_imm |= self.pend_data << 8
310         self.ann_dasm = Ann.INSTR
311         if self.want_read > 0:
312             return OpState.ROP1
313         if self.want_write > 0:
314             return OpState.WOP1
315         return OpState.RESTART
316
317     def on_state_ROP1(self):
318         self.arg_read = self.pend_data
319         if self.want_write > 0:
320             return OpState.WOP1
321         if self.want_read > 1:
322             return OpState.ROP2
323         if self.op_repeat and self.prev_cycle in (Cycle.MEMRD, Cycle.IORD):
324             return OpState.ROP1
325         self.mnemonic = '{ro:02X}'
326         self.ann_dasm = Ann.ROP
327         return OpState.RESTART
328
329     def on_state_ROP2(self):
330         self.arg_read |= self.pend_data << 8
331         self.mnemonic = '{ro:04X}'
332         self.ann_dasm = Ann.ROP
333         if self.want_write > 0:
334             return OpState.WOP1
335         return OpState.RESTART
336
337     def on_state_WOP1(self):
338         self.arg_write = self.pend_data
339         if self.want_read > 1:
340             return OpState.ROP2
341         if self.want_write > 1:
342             return OpState.WOP2
343         if self.want_read > 0 and self.op_repeat and \
344                 self.prev_cycle in (Cycle.MEMRD, Cycle.IORD):
345             return OpState.ROP1
346         self.mnemonic = '{wo:02X}'
347         self.ann_dasm = Ann.WOP
348         return OpState.RESTART
349
350     def on_state_WOP2(self):
351         if self.want_wr_be:
352             self.arg_write = (self.arg_write << 8) | self.pend_data
353         else:
354             self.arg_write |= self.pend_data << 8
355         self.mnemonic = '{wo:04X}'
356         self.ann_dasm = Ann.WOP
357         return OpState.RESTART