5a23466b373f9ec114a86f8a4c2a053d6a8bbaae
[goodfet] / client / GoodFETARM7.py
1 #!/usr/bin/env python
2 # GoodFET ARM Client Library
3
4 # Contributions and bug reports welcome.
5 #
6 # todo:
7 #  * full cycle debugging.. halt to resume
8 #  * ensure correct PC handling
9 #  * flash manipulation (probably need to get the specific chip for this one)
10 #  * set security (chip-specific)
11
12 import sys
13 import time
14 import struct
15
16 from GoodFET import GoodFET
17 from intelhex import IntelHex
18
19
20 #Global Commands
21 READ  = 0x00
22 WRITE = 0x01
23 PEEK  = 0x02
24 POKE  = 0x03
25 SETUP = 0x10
26 START = 0x20
27 STOP  = 0x21
28 CALL  = 0x30
29 EXEC  = 0x31
30 NOK   = 0x7E
31 OK    = 0x7F
32
33 # ARM7TDMI JTAG commands
34 IR_SHIFT =                  0x80
35 DR_SHIFT =                  0x81
36 RESETTAP =                  0x82
37 RESETTARGET =               0x83
38 DR_SHIFT_MORE =             0x87
39 GET_REGISTER =              0x8d
40 SET_REGISTER =              0x8e
41 DEBUG_INSTR =               0x8f
42 # Really ARM specific stuff
43 WAIT_DBG =                  0x91
44 CHAIN0 =                    0x93
45 SCANCHAIN1 =                0x94
46 EICE_READ =                 0x95
47 EICE_WRITE =                0x96
48 SCAN_N_SIZE =               0x9e
49 IR_SIZE =                   0x9f
50
51 IR_EXTEST           =  0x0
52 IR_SCAN_N           =  0x2
53 IR_SAMPLE           =  0x3
54 IR_RESTART          =  0x4
55 IR_CLAMP            =  0x5
56 IR_HIGHZ            =  0x7
57 IR_CLAMPZ           =  0x9
58 IR_INTEST           =  0xC
59 IR_IDCODE           =  0xE
60 IR_BYPASS           =  0xF
61
62 DBG_DBGACK =    1
63 DBG_DBGRQ =     2
64 DBG_IFEN =      4
65 DBG_cgenL =     8
66 DBG_TBIT =      16
67
68
69 EICE_DBGCTRL =                     0  # read 3 bit - Debug Control
70 EICE_DBGCTRL_BITLEN =              3
71 EICE_DBGSTATUS =                   1  # read 5 bit - Debug Status
72 EICE_DBGSTATUS_BITLEN =            5
73 EICE_DBGCCR =                      4  # read 6 bit - Debug Comms Control Register
74 EICE_DBGCCR_BITLEN =               6
75 EICE_DBGCDR =                      5  # r/w 32 bit - Debug Comms Data Register
76 EICE_WP0ADDR =                     8  # r/w 32 bit - Watchpoint 0 Address
77 EICE_WP0ADDRMASK =                 9  # r/w 32 bit - Watchpoint 0 Addres Mask
78 EICE_WP0DATA =                     10 # r/w 32 bit - Watchpoint 0 Data
79 EICE_WP0DATAMASK =                 11 # r/w 32 bit - Watchpoint 0 Data Masl
80 EICE_WP0CTRL =                     12 # r/w 9 bit - Watchpoint 0 Control Value
81 EICE_WP0CTRLMASK =                 13 # r/w 8 bit - Watchpoint 0 Control Mask
82 EICE_WP1ADDR =                     16 # r/w 32 bit - Watchpoint 0 Address
83 EICE_WP1ADDRMASK =                 17 # r/w 32 bit - Watchpoint 0 Addres Mask
84 EICE_WP1DATA =                     18 # r/w 32 bit - Watchpoint 0 Data
85 EICE_WP1DATAMASK =                 19 # r/w 32 bit - Watchpoint 0 Data Masl
86 EICE_WP1CTRL =                     20 # r/w 9 bit - Watchpoint 0 Control Value
87 EICE_WP1CTRLMASK =                 21 # r/w 8 bit - Watchpoint 0 Control Mask
88
89 MSB         = 0
90 LSB         = 1
91 NOEND       = 2
92 NORETIDLE   = 4
93
94 F_TBIT      = 1<<40
95
96 PM_usr = 0b10000
97 PM_fiq = 0b10001
98 PM_irq = 0b10010
99 PM_svc = 0b10011
100 PM_abt = 0b10111
101 PM_und = 0b11011
102 PM_sys = 0b11111
103
104 proc_modes = {
105     0:      ("UNKNOWN, MESSED UP PROCESSOR MODE","fsck", "This should Never happen.  MCU is in funky state!"),
106     PM_usr: ("User Processor Mode", "usr", "Normal program execution mode"),
107     PM_fiq: ("FIQ Processor Mode", "fiq", "Supports a high-speed data transfer or channel process"),
108     PM_irq: ("IRQ Processor Mode", "irq", "Used for general-purpose interrupt handling"),
109     PM_svc: ("Supervisor Processor Mode", "svc", "A protected mode for the operating system"),
110     PM_abt: ("Abort Processor Mode", "abt", "Implements virtual memory and/or memory protection"),
111     PM_und: ("Undefined Processor Mode", "und", "Supports software emulation of hardware coprocessor"),
112     PM_sys: ("System Processor Mode", "sys", "Runs privileged operating system tasks (ARMv4 and above)"),
113 }
114
115 PSR_bits = [ 
116     None, None, None, None, None, "Thumb", "nFIQ_int", "nIRQ_int", 
117     "nImprDataAbort_int", "BIGendian", None, None, None, None, None, None, 
118     "GE_0", "GE_1", "GE_2", "GE_3", None, None, None, None, 
119     "Jazelle", None, None, "Q (DSP-overflow)", "oVerflow", "Carry", "Zero", "Neg",
120     ]
121
122 ARM_INSTR_NOP =             0xe1a00000L
123 ARM_INSTR_BX_R0 =           0xe12fff10L
124 ARM_INSTR_STR_Rx_r14 =      0xe58f0000L # from atmel docs
125 ARM_READ_REG =              ARM_INSTR_STR_Rx_r14
126 ARM_INSTR_LDR_Rx_r14 =      0xe59f0000L # from atmel docs
127 ARM_WRITE_REG =             ARM_INSTR_LDR_Rx_r14
128 ARM_INSTR_LDR_R1_r0_4 =     0xe4901004L
129 ARM_READ_MEM =              ARM_INSTR_LDR_R1_r0_4
130 ARM_INSTR_STR_R1_r0_4 =     0xe4801004L
131 ARM_WRITE_MEM =             ARM_INSTR_STR_R1_r0_4
132 ARM_INSTR_STRB_R1_r0_1 =    0xe4c01001L
133 ARM_WRITE_MEM_BYTE =        ARM_INSTR_STRB_R1_r0_1
134 ARM_INSTR_MRS_R0_CPSR =     0xe10f0000L
135 ARM_INSTR_MSR_cpsr_cxsf_R0 =0xe12ff000L
136 ARM_INSTR_STMIA_R14_r0_rx = 0xE88e0000L      # add up to 65k to indicate which registers...
137 ARM_INSTR_LDMIA_R14_r0_rx = 0xE89e0000L      # add up to 65k to indicate which registers...
138 ARM_STORE_MULTIPLE =        ARM_INSTR_STMIA_R14_r0_rx
139 ARM_INSTR_SKANKREGS =       0xE88F7fffL
140 ARM_INSTR_CLOBBEREGS =      0xE89F7fffL
141
142 ARM_INSTR_B_IMM =           0xea000000L
143 ARM_INSTR_B_PC =            0xea000000L
144 ARM_INSTR_BX_PC =           0xe1200010L      # need to set r0 to the desired address
145 THUMB_INSTR_LDR_R0_r0 =     0x68006800L
146 THUMB_WRITE_REG =           THUMB_INSTR_LDR_R0_r0
147 THUMB_INSTR_STR_R0_r0 =     0x60006000L
148 THUMB_READ_REG =            THUMB_INSTR_STR_R0_r0
149 THUMB_INSTR_MOV_R0_PC =     0x46b846b8L
150 THUMB_INSTR_MOV_PC_R0 =     0x46474647L
151 THUMB_INSTR_BX_PC =         0x47784778L
152 THUMB_INSTR_NOP =           0x1c001c00L
153 THUMB_INSTR_B_IMM =         0xe000e000L
154 ARM_REG_PC =                15
155
156 nRW         = 0
157 MAS0        = 1
158 MAS1        = 2
159 nOPC        = 3
160 nTRANS      = 4
161 EXTERN      = 5
162 CHAIN       = 6
163 RANGE       = 7
164 ENABLE      = 8
165
166 DBGCTRLBITS = {
167         'nRW':nRW,
168         'MAS0':MAS0,
169         'MAS1':MAS1,
170         'nOPC':nOPC,
171         'nTRANS':nTRANS,
172         'EXTERN':EXTERN,
173         'CHAIN':CHAIN,
174         'RANGE':RANGE,
175         'ENABLE':ENABLE,
176         1<<nRW:'nRW',
177         1<<MAS0:'MAS0',
178         1<<MAS1:'MAS1',
179         1<<nOPC:'nOPC',
180         1<<nTRANS:'nTRANS',
181         1<<EXTERN:'EXTERN',
182         1<<CHAIN:'CHAIN',
183         1<<RANGE:'RANGE',
184         1<<ENABLE:'ENABLE',
185         }
186
187 LDM_BITMASKS = [(1<<x)-1 for x in xrange(16)]
188 #### TOTALLY BROKEN, NEED VALIDATION AND TESTING
189 PCOFF_DBGRQ = 4 * 4
190 PCOFF_WATCH = 4 * 4
191 PCOFF_BREAK = 4 * 4
192
193
194 def debugstr(strng):
195     print >>sys.stderr,(strng)
196
197 def PSRdecode(psrval):
198     output = [ "(%s mode)"%proc_modes[psrval&0x1f][1] ]
199     for x in xrange(5,32):
200         if psrval & (1<<x):
201             output.append(PSR_bits[x])
202     return " ".join(output)
203    
204 fmt = [None, "B", "<H", None, "<L", None, None, None, "<Q"]
205
206 def chop(val,byts):
207     s = struct.pack(fmt[byts], val)
208     return [ord(b) for b in s ]
209         
210 class GoodFETARM7(GoodFET):
211     """A GoodFET variant for use with ARM7TDMI microprocessor."""
212     def __init__(self):
213         GoodFET.__init__(self)
214         self.storedPC =         0xffffffff
215         self.current_dbgstate = 0xffffffff
216         self.flags =            0xffffffff
217         self.nothing =          0xffffffff
218         self.stored_regs = []
219
220     def __del__(self):
221         try:
222             if (self.ARMget_dbgstate()&9) == 9:
223                 self.resume()
224         except:
225             sys.excepthook(*sys.exc_info())
226
227     def setup(self):
228         """Move the FET into the JTAG ARM application."""
229         #print "Initializing ARM."
230         self.writecmd(0x13,SETUP,0,self.data)
231
232     def flash(self,file):
233         """Flash an intel hex file to code memory."""
234         print "Flash not implemented.";
235
236     def dump(self,fn,start=0,stop=0xffffffff):
237         """Dump an intel hex file from code memory."""
238         
239         print "Dumping from %04x to %04x as %s." % (start,stop,f);
240         # FIXME: get mcu state and return it to that state
241         self.halt()
242
243         h = IntelHex(None);
244         i=start;
245         while i<=stop:
246             data=self.ARMreadChunk(i, 48, verbose=0);
247             print "Dumped %06x."%i;
248             for dword in data:
249                 if i<=stop and dword != 0xdeadbeef:
250                     h.puts( i, struct.pack("<I", dword) )
251                 i+=4;
252         # FIXME: get mcu state and return it to that state
253         self.resume()
254         h.write_hex_file(fn);
255
256         print "Dump not implemented.";
257
258     def ARMsetIRsize(self, size=4):
259         if size > 255:
260             raise Exception("IR size cannot be >255!!")
261         self.writecmd(0x13, IR_SIZE, 1, [size])
262
263     def ARMsetSCANsize(self, size=4):
264         if size > 255:
265             raise Exception("IR size cannot be >255!!")
266         self.writecmd(0x13, SCAN_N_SIZE, 1, [size])
267
268     def ARMshift_IR(self, IR, noretidle=0):
269         self.writecmd(0x13,IR_SHIFT,2, [IR, LSB|noretidle])
270         return self.data
271
272     def ARMshift_DR(self, data, bits, flags):
273         self.writecmd(0x13,DR_SHIFT,14,[bits&0xff, flags&0xff, 0, 0, data&0xff,(data>>8)&0xff,(data>>16)&0xff,(data>>24)&0xff, (data>>32)&0xff,(data>>40)&0xff,(data>>48)&0xff,(data>>56)&0xff,(data>>64)&0xff,(data>>72)&0xff])
274         return self.data
275
276     def ARMshift_DR_more(self, data, bits, flags):
277         self.writecmd(0x13,DR_SHIFT_MORE,14,[bits&0xff, flags&0xff, 0, 0, data&0xff,(data>>8)&0xff,(data>>16)&0xff,(data>>24)&0xff, (data>>32)&0xff,(data>>40)&0xff,(data>>48)&0xff,(data>>56)&0xff,(data>>64)&0xff,(data>>72)&0xff])
278         return self.data
279
280     def ARMwaitDBG(self, timeout=0xff):
281         self.current_dbgstate = self.ARMget_dbgstate()
282         while ( not ((self.current_dbgstate & 9L) == 9)):
283             timeout -=1
284             self.current_dbgstate = self.ARMget_dbgstate()
285         return timeout
286
287     def ARMident(self):
288         """Get an ARM's ID."""
289         self.ARMshift_IR(IR_IDCODE,0)
290         self.ARMshift_DR(0,32,LSB)
291         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
292         return retval
293
294     def ARMidentstr(self):
295         ident=self.ARMident()
296         ver     = (ident >> 28)
297         partno  = (ident >> 12) & 0xffff
298         mfgid   = (ident >> 1)  & 0x7ff
299         return "Chip IDCODE:    0x%x\tver: %x\tpartno: %x\tmfgid: %x" % (ident, ver, partno, mfgid); 
300
301     def ARMeice_write(self, reg, val):
302         data = chop(val,4)
303         data.extend([reg])
304         retval = self.writecmd(0x13, EICE_WRITE, 5, data)
305         return retval
306
307     def ARMeice_read(self, reg):
308         self.writecmd(0x13, EICE_READ, 1, [reg])
309         retval, = struct.unpack("<L",self.data)
310         return retval
311
312     def ARMget_dbgstate(self):
313         """Read the config register of an ARM."""
314         self.ARMeice_read(EICE_DBGSTATUS)
315         self.current_dbgstate = struct.unpack("<L", self.data[:4])[0]
316         return self.current_dbgstate
317     status = ARMget_dbgstate
318
319     def statusstr(self):
320         """Check the status as a string."""
321         status=self.status()
322         str=""
323         i=1
324         while i<0x20:
325             if(status&i):
326                 str="%s %s" %(self.ARMstatusbits[i],str)
327             i*=2
328         return str
329
330     def ARMget_dbgctrl(self):
331         """Read the config register of an ARM."""
332         self.ARMeice_read(EICE_DBGCTRL)
333         retval = struct.unpack("<L", self.data[:4])[0]
334         return retval
335
336     def ARMset_dbgctrl(self,config):
337         """Write the config register of an ARM."""
338         self.ARMeice_write(EICE_DBGCTRL, config&7)
339
340     def ARMgetPC(self):
341         """Get an ARM's PC. Note: real PC gets all wonky in debug mode, this is the "saved" PC"""
342         return self.storedPC
343     getpc = ARMgetPC
344     
345     def ARMsetPC(self, val):
346         """Set an ARM's PC.  Note: real PC gets all wonky in debug mode, this changes the "saved" PC which is used when exiting debug mode"""
347         self.storedPC = val
348
349     def ARMget_register(self, reg):
350         """Get an ARM's Register"""
351         self.writecmd(0x13,GET_REGISTER,1,[reg&0xf])
352         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
353         return retval
354
355     def ARMset_register(self, reg, val):
356         """Get an ARM's Register"""
357         self.writecmd(0x13,SET_REGISTER,8,[val&0xff, (val>>8)&0xff, (val>>16)&0xff, val>>24, reg,0,0,0])
358         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
359         return retval
360
361     def ARMget_registers(self):
362         """Get ARM Registers"""
363         regs = [ self.ARMget_register(x) for x in range(15) ]
364         regs.append(self.ARMgetPC())            # make sure we snag the "static" version of PC
365         return regs
366
367     def ARMset_registers(self, regs, mask):
368         """Set ARM Registers"""
369         for x in xrange(15):
370           if (1<<x) & mask:
371             self.ARMset_register(x,regs.pop(0))
372         if (1<<15) & mask:                      # make sure we set the "static" version of PC or changes will be lost
373           self.ARMsetPC(regs.pop(0))
374
375     def ARMdebuginstr(self,instr,bkpt):
376         if type (instr) == int or type(instr) == long:
377             instr = struct.pack("<L", instr)
378         instr = [int("0x%x"%ord(x),16) for x in instr]
379         instr.extend([bkpt])
380         self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
381         return (self.data)
382
383     def ARM_nop(self, bkpt=0):
384         if self.status() & DBG_TBIT:
385             return self.ARMdebuginstr(THUMB_INSTR_NOP, bkpt)
386         return self.ARMdebuginstr(ARM_INSTR_NOP, bkpt)
387
388     def ARMrestart(self):
389         self.ARMshift_IR(IR_RESTART)
390
391     def ARMset_watchpoint0(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
392         self.ARMeice_write(EICE_WP0ADDR, addr);           # write 0 in watchpoint 0 address
393         self.ARMeice_write(EICE_WP0ADDRMASK, addrmask);   # write 0xffffffff in watchpoint 0 address mask
394         self.ARMeice_write(EICE_WP0DATA, data);           # write 0 in watchpoint 0 data
395         self.ARMeice_write(EICE_WP0DATAMASK, datamask);   # write 0xffffffff in watchpoint 0 data mask
396         self.ARMeice_write(EICE_WP0CTRL, ctrl);           # write 0x00000100 in watchpoint 0 control value register (enables watchpoint)
397         self.ARMeice_write(EICE_WP0CTRLMASK, ctrlmask);   # write 0xfffffff7 in watchpoint 0 control mask - only detect the fetch instruction
398         return self.data
399
400     def ARMset_watchpoint1(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
401         self.ARMeice_write(EICE_WP1ADDR, addr);           # write 0 in watchpoint 1 address
402         self.ARMeice_write(EICE_WP1ADDRMASK, addrmask);   # write 0xffffffff in watchpoint 1 address mask
403         self.ARMeice_write(EICE_WP1DATA, data);           # write 0 in watchpoint 1 data
404         self.ARMeice_write(EICE_WP1DATAMASK, datamask);   # write 0xffffffff in watchpoint 1 data mask
405         self.ARMeice_write(EICE_WP1CTRL, ctrl);           # write 0x00000100 in watchpoint 1 control value register (enables watchpoint)
406         self.ARMeice_write(EICE_WP1CTRLMASK, ctrlmask);   # write 0xfffffff7 in watchpoint 1 control mask - only detect the fetch instruction
407         return self.data
408
409     def THUMBgetPC(self):
410         THUMB_INSTR_STR_R0_r0 =     0x60006000L
411         THUMB_INSTR_MOV_R0_PC =     0x46b846b8L
412         THUMB_INSTR_BX_PC =         0x47784778L
413         THUMB_INSTR_NOP =           0x1c001c00L
414
415         r0 = self.ARMget_register(0)
416         self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC, 0)
417         retval = self.ARMget_register(0)
418         self.ARMset_register(0,r0)
419         return retval
420
421     def ARMcapture_system_state(self, pcoffset):
422         self.c0Data, self.flags, self.c0Addr = self.ARMchain0(0)
423         if self.ARMget_dbgstate() & DBG_TBIT:
424             pcoffset += 8
425         else:
426             pcoffset += 4
427         self.storedPC = self.ARMget_register(15) + pcoffset
428         self.last_dbg_state = self.ARMget_dbgstate()
429         self.cpsr = self.ARMget_regCPSR()
430         #print "ARMcapture_system_state: stored pc: 0x%x  last_dbg_state: 0x%x" % (self.storedPC, self.last_dbg_state)
431
432     def halt(self):
433         """Halt the CPU."""
434         if self.ARMget_dbgstate()&DBG_DBGACK:
435             if not len(self.stored_regs):
436                 #print "stored regs: " + repr(self.stored_regs)
437                 self.stored_regs = self.ARMget_registers()[:15]
438                 print self.print_stored_registers()
439             return
440         print "halting cpu"
441         self.ARMset_dbgctrl(2)
442         if (self.ARMwaitDBG() == 0):
443             raise Exception("Timeout waiting to enter DEBUG mode on HALT")
444         self.ARMset_dbgctrl(0)
445
446         self.ARMcapture_system_state(PCOFF_DBGRQ)
447         #print "storedPC: %x (%x)      flags: %x    nothing: %x" % (self.storedPC, self.c0Data, self.flags, self.c0Addr)
448         if self.ARMget_dbgstate() & DBG_TBIT:
449             self.ARMsetModeARM()
450             if self.storedPC ^ 4:
451                 self.ARMset_register(15,self.storedPC&0xfffffffc)
452         self.stored_regs = self.ARMget_registers()[:15]
453         #print "stored regs: " + repr(self.stored_regs)
454         #print self.print_stored_registers()
455         #print "CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
456
457     def resume(self):
458         """Resume the CPU."""
459         # FIXME: restore CPSR
460         # FIXME: true up PC to exactly where we left off...
461         if not self.ARMget_dbgstate()&DBG_DBGACK:
462             return
463         print "resume"
464         if len(self.stored_regs):
465             #print self.print_stored_registers()
466             self.ARMset_registers(self.stored_regs, 0x7fff)
467         else:
468             print "skipping restore of stored registers due to empty list ?  WTFO?"
469
470         currentPC, self.currentflags, nothing = self.ARMchain0(self.storedPC,self.flags, self.c0Addr)
471         if not(self.flags & F_TBIT):                                    # need to be in arm mode
472             if self.currentflags & F_TBIT:                              # currently in thumb mode
473                 self.ARMsetModeARM()
474             # branch to the right address
475             self.ARMset_register(15, self.storedPC)
476             #print hex(self.storedPC)
477             #print hex(self.ARMget_register(15))
478             #print hex(self.ARMchain0(self.storedPC,self.flags)[0])
479             self.ARMchain0(self.storedPC,self.flags)
480             self.ARM_nop(0)
481             self.ARM_nop(1)
482             self.ARMdebuginstr(ARM_INSTR_B_IMM | 0xfffff0,0)
483             self.ARM_nop(0)
484             self.ARMrestart()
485
486         elif self.flags & F_TBIT:                                       # need to be in thumb mode
487             if not (self.currentflags & F_TBIT):                        # currently in arm mode
488                 self.ARMsetModeThumb()
489             r0=self.ARMget_register(0)
490             self.ARMset_register(0, self.storedPC)
491             self.ARMdebuginstr(THUMB_INSTR_MOV_PC_R0,0)
492             self.ARM_nop(0)
493             self.ARM_nop(1)
494             #print hex(self.storedPC)
495             #print hex(self.ARMget_register(15))
496             #print hex(self.ARMchain0(self.storedPC,self.flags)[0])
497             self.ARMchain0(self.storedPC,self.flags)[0]
498             self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc),0)
499             self.ARM_nop(0)
500             self.ARMrestart()
501
502         #print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
503         #print >>sys.stderr,"CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
504
505     def resettap(self):
506         self.writecmd(0x13, RESETTAP, 0,[])
507
508     def ARMsetModeARM(self):
509         r0 = None
510         if ((self.current_dbgstate & DBG_TBIT)):
511             #debugstr("=== Switching to ARM mode ===")
512             self.ARM_nop(0)
513             self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
514             self.ARM_nop(0)
515             self.ARM_nop(0)
516         self.resettap()
517         self.current_dbgstate = self.ARMget_dbgstate();
518         return self.current_dbgstate
519
520     def ARMsetModeThumb(self):                               # needs serious work and truing
521         self.resettap()
522         #debugstr("=== Switching to THUMB mode ===")
523         if ( not (self.current_dbgstate & DBG_TBIT)):
524             self.storedPC |= 1
525             r0 = self.ARMget_register(0)
526             self.ARMset_register(0, self.storedPC)
527             self.ARM_nop(0)
528             self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
529             self.ARM_nop(0)
530             self.ARM_nop(0)
531             self.resettap()
532             self.ARMset_register(0,r0)
533         self.current_dbgstate = self.ARMget_dbgstate();
534         return self.current_dbgstate
535
536     def ARMget_regCPSRstr(self):
537         psr = self.ARMget_regCPSR()
538         return hex(psr), PSRdecode(psr)
539
540     def ARMget_regCPSR(self):
541         """Get an ARM's Register"""
542         r0 = self.ARMget_register(0)
543         self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
544         self.ARMdebuginstr(ARM_INSTR_MRS_R0_CPSR, 0) # push MRS_R0, CPSR into pipeline - fetch
545         self.ARM_nop( 0) # push nop into pipeline - decoded
546         self.ARM_nop( 0) # push nop into pipeline - execute
547         retval = self.ARMget_register(0)
548         self.ARMset_register(0, r0)
549         return retval
550
551     def ARMset_regCPSR(self, val):
552         """Get an ARM's Register"""
553         r0 = self.ARMget_register(0)
554         self.ARMset_register(0, val)
555         self.ARM_nop( 0)        # push nop into pipeline - clean out the pipeline...
556         self.ARMdebuginstr(ARM_INSTR_MSR_cpsr_cxsf_R0, 0) # push MSR cpsr_cxsf, R0 into pipeline - fetch
557         self.ARM_nop( 0)        # push nop into pipeline - decoded
558         self.ARM_nop( 0)        # push nop into pipeline - execute
559         self.ARMset_register(0, r0)
560         return(val)
561         
562     def ARMreadStream(self, addr, bytecount):
563         baseaddr    = addr & 0xfffffffc
564         endaddr     = ((addr + bytecount + 3) & 0xfffffffc)
565         diffstart   = 4 - (addr - baseaddr)
566         diffend     = 4 - (endaddr - (addr + bytecount ))
567         
568         
569         out = []
570         data = [ x for x in self.ARMreadChunk( baseaddr, ((endaddr-baseaddr) / 4) ) ]
571         #print data, hex(baseaddr), hex(diffstart), hex(endaddr), hex(diffend)
572         if len(data) == 1:
573             #print "single dword"
574             out.append( struct.pack("<I", data.pop(0)) [4-diffstart:diffend] )
575         else:
576             #print "%d dwords" % len(data)
577             if diffstart:
578                 out.append( struct.pack("<I", data.pop(0)) [4-diffstart:] )
579                 bytecount -= (diffstart)
580                 #print out
581                 
582             for ent in data[:-1]:
583                 out.append( struct.pack("<I", data.pop(0) ) )
584                 bytecount -= 4
585                 #print out
586                 
587             if diffend and bytecount>0:
588                 out.append( struct.pack("<I", data.pop(0)) [:diffend] ) 
589                 #print out
590         return ''.join(out)        
591
592     def ARMprintChunk(self, adr, wordcount=1, verbose=False, width=8):
593         for string in self.ARMreprChunk(adr, wordcount, verbose=False, width=8):
594             sys.stdout.write(string)
595
596     def ARMreprChunk(self, adr, wordcount=1, verbose=False, width=8):
597         adr &= 0xfffffffc
598         endva = adr + (4*wordcount)
599         output = [ "Dwords from 0x%x through 0x%x" % (adr, endva) ]
600         idx = 0
601         for data in self.ARMreadChunk(adr, wordcount, verbose):
602             if (idx % width) == 0:
603                 yield ( "\n0x%.8x\t" % (adr + (4*idx)) )
604             yield ( "%.8x   " % (data) )
605             idx += 1
606
607         yield("\n")
608
609     def ARMreadChunk(self, adr, wordcount=1, verbose=True):
610         """ Only works in ARM mode currently
611         WARNING: Addresses must be word-aligned!
612         """
613         regs = self.ARMget_registers()
614         self.ARMset_registers([0xdeadbeef for x in xrange(14)], 0xe)
615         count = wordcount
616         while (wordcount > 0):
617             if (verbose and wordcount%64 == 0):  sys.stderr.write(".")
618             count = (wordcount, 0xe)[wordcount>0xd]
619             bitmask = LDM_BITMASKS[count]
620             self.ARMset_register(14,adr)
621             self.ARM_nop(1)
622             self.ARMdebuginstr(ARM_INSTR_LDMIA_R14_r0_rx | bitmask ,0)
623             #FIXME: do we need the extra nop here?
624             self.ARMrestart()
625             self.ARMwaitDBG()
626             for x in range(count):
627                 yield self.ARMget_register(x)
628             wordcount -= count
629             adr += count*4
630             #print hex(adr)
631         # FIXME: handle the rest of the wordcount here.
632         self.ARMset_registers(regs,0xe)
633
634     ARMreadMem = ARMreadChunk
635     peek = ARMreadMem
636
637     def ARMwriteChunk(self, adr, wordarray):         
638         """ Only works in ARM mode currently
639         WARNING: Addresses must be word-aligned!
640         """
641         regs = self.ARMget_registers()
642         wordcount = len(wordarray)
643         while (wordcount > 0):
644             if (wordcount%64 == 0):  sys.stderr.write(".")
645             count = (wordcount, 0xe)[wordcount>0xd]
646             bitmask = LDM_BITMASKS[count]
647             self.ARMset_register(14,adr)
648             #print len(wordarray),bin(bitmask)
649             self.ARMset_registers(wordarray[:count],bitmask)
650             self.ARM_nop(1)
651             self.ARMdebuginstr(ARM_INSTR_STMIA_R14_r0_rx | bitmask ,0)
652             #FIXME: do we need the extra nop here?
653             self.ARMrestart()
654             self.ARMwaitDBG()
655             wordarray = wordarray[count:]
656             wordcount -= count
657             adr += count*4
658             #print hex(adr)
659         # FIXME: handle the rest of the wordcount here.
660     ARMwriteMem = ARMwriteChunk
661         
662     def ARMwriteStream(self, addr, datastr):
663         #bytecount = len(datastr)
664         #baseaddr    = addr & 0xfffffffc
665         #diffstart   = addr - baseaddr
666         #endaddr     = ((addr + bytecount) & 0xfffffffc) + 4
667         #diffend     = 4 - (endaddr - (addr+bytecount))
668         bytecount = len(datastr)
669         baseaddr    = addr & 0xfffffffc
670         endaddr     = ((addr + bytecount + 3) & 0xfffffffc)
671         diffstart   = 4 - (addr - baseaddr)
672         diffend     = 4 - (endaddr - (addr + bytecount ))
673                 
674         print hex(baseaddr), hex(diffstart), hex(endaddr), hex(diffend)
675         out = []
676         if diffstart:
677             dword = self.ARMreadChunk(baseaddr, 1)[0] & (0xffffffff>>(8*diffstart))
678             dst = "\x00" * (4-diffstart) + datastr[:diffstart]; print hex(dword), repr(dst)
679             datachk = struct.unpack("<I", dst)[0]
680             out.append( dword+datachk )
681             datastr = datastr[diffstart:]
682             bytecount -= diffstart
683         for ent in xrange(baseaddr+4, endaddr-4, 4):
684             print repr(datastr)
685             dword = struct.unpack("<I", datastr[:4])[0]
686             out.append( dword )
687             datastr = datastr[4:]
688             bytecount -= 4
689         if diffend and bytecount:
690             dword = self.ARMreadChunk(endaddr-4, 1)[0] & (0xffffffff<<(8*diffend))
691             dst = datastr + "\x00" * (4-diffend); print hex(dword), repr(dst)
692             datachk = struct.unpack("<I", dst)[0]
693             out.append( dword+datachk )
694         print repr([hex(x) for x in out])
695         return self.ARMwriteChunk(baseaddr, out)
696         
697         
698     def writeMemByte(self, adr, byte):
699         self.ARMwriteMem(adr, byte, ARM_WRITE_MEM_BYTE)
700
701
702     ARMstatusbits={
703                   0x10 : "TBIT",
704                   0x08 : "cgenL",
705                   0x04 : "Interrupts Enabled (or not?)",
706                   0x02 : "DBGRQ",
707                   0x01 : "DGBACK"
708                   }
709     ARMctrlbits={
710                   0x04 : "disable interrupts",
711                   0x02 : "force dbgrq",
712                   0x01 : "force dbgack"
713                   }
714     def ARMresettarget(self, delay=1000):
715         return self.writecmd(0x13,RESETTARGET,2, [ delay&0xff, (delay>>8)&0xff ] )
716
717     def ARMchain0(self, address, bits=0x819684c054, data=0):
718         bulk = chop(address,4)
719         bulk.extend(chop(bits,8))
720         bulk.extend(chop(data,4))
721         #print >>sys.stderr,(repr(bulk))
722         self.writecmd(0x13,CHAIN0,16,bulk)
723         d1,b1,a1 = struct.unpack("<LQL",self.data)
724         return (a1,b1,d1)
725
726     def start(self, ident=False):
727         """Start debugging."""
728         self.writecmd(0x13,START,0,self.data)
729         if ident:
730             print >>sys.stderr,"Identifying Target:"
731             print >>sys.stderr, self.ARMidentstr()
732             print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
733
734     def stop(self):
735         """Stop debugging."""
736         self.writecmd(0x13,STOP,0,self.data)
737     #def ARMstep_instr(self):
738     #    """Step one instruction."""
739     #    self.writecmd(0x13,STEP_INSTR,0,self.data)
740     #def ARMflashpage(self,adr):
741     #    """Flash 2kB a page of flash from 0xF000 in XDATA"""
742     #    data=[adr&0xFF,
743     #          (adr>>8)&0xFF,
744     #          (adr>>16)&0xFF,
745     #          (adr>>24)&0xFF]
746     #    print "Flashing buffer to 0x%06x" % adr
747     #    self.writecmd(0x13,MASS_FLASH_PAGE,4,data)
748
749     def print_registers(self):
750         return [ hex(x) for x in self.ARMget_registers() ]
751
752     def print_stored_registers(self):
753         return [ hex(x) for x in self.stored_regs ]
754
755
756
757 ######### command line stuff #########
758 from intelhex import IntelHex16bit, IntelHex
759
760 def arm7_syntax():
761     print "Usage: %s verb [objects]\n" % sys.argv[0]
762     print "%s info" % sys.argv[0]
763     print "%s dump $foo.hex [0x$start 0x$stop]" % sys.argv[0]
764     print "%s erase" % sys.argv[0]
765     print "%s eraseinfo" % sys.argv[0]
766     print "%s flash $foo.hex [0x$start 0x$stop]" % sys.argv[0]
767     print "%s verify $foo.hex [0x$start 0x$stop]" % sys.argv[0]
768     print "%s poke 0x$adr 0x$val" % sys.argv[0]
769     print "%s peek 0x$start [0x$stop]" % sys.argv[0]
770     print "%s reset" % sys.argv[0]
771     sys.exit()
772
773 def arm7_main():
774     ''' this function should be called from command line app '''
775
776     #Initialize FET and set baud rate
777     client=GoodFETARM7()
778     client.serInit()
779
780     client.setup()
781     client.start()
782
783     arm7_cli_handler(client, sys.argv)
784
785 def arm7_cli_handler(client, argv):
786     if(argv[1]=="info"):
787         client.halt()
788         print >>sys.stderr, client.ARMidentstr()
789         print >>sys.stderr,"Debug Status:\t%s" % client.statusstr()
790         print >>sys.stderr,"CPSR: (%s) %s\n"%(client.ARMget_regCPSRstr())
791         client.resume()
792
793
794     if(argv[1]=="dump"):
795         f = sys.argv[2]
796         start=0x00000000
797         stop=0xFFFFFFFF
798         if(len(sys.argv)>3):
799             start=int(sys.argv[3],16)
800         if(len(sys.argv)>4):
801             stop=int(sys.argv[4],16)
802         
803         print "Dumping from %04x to %04x as %s." % (start,stop,f)
804         #h = IntelHex16bit(None)
805         # FIXME: get mcu state and return it to that state
806         client.halt()
807
808         try:
809             h = IntelHex(None)
810             i=start
811             while i<=stop:
812                 #data=client.ARMreadMem(i, 48)
813                 data=client.ARMreadChunk(i, 48, verbose=0)
814                 print "Dumped %06x."%i
815                 for dword in data:
816                     if i<=stop and dword != 0xdeadbeef:
817                         h.puts( i, struct.pack("<I", dword) )
818                     i+=4
819             # FIXME: get mcu state and return it to that state
820         except:
821             print "Unknown error during read. Writing results to output file."
822             print "Rename file with last address dumped %06x."%i
823             pass
824
825         client.resume()
826         h.write_hex_file(f)
827
828     '''
829     if(sys.argv[1]=="erase"):
830         print "Erasing main flash memory."
831         client.ARMmasserase()
832
833     if(sys.argv[1]=="eraseinfo"):
834         print "Erasing info memory."
835         client.ARMinfoerase()
836
837         
838     '''
839     if(sys.argv[1]=="ivt"):
840         client.halt()
841         client.ARMprintChunk(0x0,0x20)
842         client.resume()
843
844     if(sys.argv[1]=="regs"):
845         client.halt()
846         for i in range(0,16):
847             print "r%i=%04x" % (i,client.ARMget_register(i))
848         client.resume()
849
850     if(sys.argv[1]=="flash"):
851         f=sys.argv[2]
852         start=0
853         stop=0x10000
854         if(len(sys.argv)>3):
855             start=int(sys.argv[3],16)
856         if(len(sys.argv)>4):
857             stop=int(sys.argv[4],16)
858         
859         client.halt()
860         h = IntelHex16bit(f)
861         
862         #Should this be default?
863         #Makes flashing multiple images inconvenient.
864         #client.ARMmasserase()
865         
866         count=0; #Bytes in commit.
867         first=0
868         vals=[]
869         last=0;  #Last address committed.
870         for i in h._buf.keys():
871             if((count>0x40 or last+2!=i) and count>0 and i&1==0):
872                 #print "%i, %x, %x" % (len(vals), last, i)
873                 client.ARMpokeflashblock(first,vals)
874                 count=0
875                 first=0
876                 last=0
877                 vals=[]
878             if(i>=start and i<stop  and i&1==0):
879                 val=h[i>>1]
880                 if(count==0):
881                     first=i
882                 last=i
883                 count+=2
884                 vals+=[val&0xff,(val&0xff00)>>8]
885                 if(i%0x100==0):
886                     print "%04x" % i
887         if count>0: #last commit, ivt
888             client.ARMpokeflashblock(first,vals)
889         client.resume()
890
891     if(sys.argv[1]=="verify"):
892         f=sys.argv[2]
893         start=0
894         stop=0xFFFF
895         if(len(sys.argv)>3):
896             start=int(sys.argv[3],16)
897         if(len(sys.argv)>4):
898             stop=int(sys.argv[4],16)
899         
900         client.halt()
901         h = IntelHex16bit(f)
902         for i in h._buf.keys():
903             if(i>=start and i<stop and i&1==0):
904                 peek=client.peek(i)
905                 if(h[i>>1]!=peek):
906                     print "ERROR at %04x, found %04x not %04x"%(i,peek,h[i>>1])
907                 if(i%0x100==0):
908                     print "%04x" % i
909         client.resume()
910
911
912     if(sys.argv[1]=="peek"):
913         start = 0x0000
914         if(len(sys.argv)>2):
915             start=int(sys.argv[2],16)
916
917         stop = start+4
918         if(len(sys.argv)>3):
919             stop=int(sys.argv[3],16)
920
921         print "Peeking from %04x to %04x." % (start,stop)
922         client.halt()
923         for dword in client.ARMreadChunk(start, (stop-start)/4, verbose=0):
924             print "%.4x: %.8x" % (start, dword)
925             start += 4
926         client.resume()
927
928     if(sys.argv[1]=="poke"):
929         start=0x0000
930         val=0x00
931         if(len(sys.argv)>2):
932             start=int(sys.argv[2],16)
933         if(len(sys.argv)>3):
934             val=int(sys.argv[3],16)
935         
936         print "Poking %06x to become %04x." % (start,val)
937         client.halt()
938         #???while client.ARMreadMem(start)[0]&(~val)>0:
939         client.ARMwriteChunk(start, [val])
940         print "Poked to %.8x" % client.ARMreadMem(start)[0]
941         client.resume()
942
943
944     if(sys.argv[1]=="reset"):
945         #Set PC to RESET vector's value.
946         
947         #client.ARMsetPC(0x00000000)
948         #client.ARMset_regCPSR(0)
949         #client.ARMreleasecpu()
950         client.ARMresettarget(1000)
951
952     #client.ARMreleasecpu()
953     #client.ARMstop()
954