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