3807e6458083c6da271faf18d3bdd9b84515a0e5
[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         #print data
296
297         self.writecmd(0x13,DR_SHIFT_MANY, len(darry)+2, data )
298
299         #print repr(self.data[2:])
300         data = self.data[2:]
301         print repr(data)
302         out = 0
303         tbits = bits
304
305         # peal it off LSB again....
306         while (tbits>0):
307             #print tbits
308             out <<= 8
309             out += ord(data[-1])
310             data = data[:-1]
311             #print hex(out)
312             tbits -= 8
313
314         return out
315
316     def ARMwaitDBG(self, timeout=0xff):
317         self.current_dbgstate = self.ARMget_dbgstate()
318         while ( not ((self.current_dbgstate & 9L) == 9)):
319             timeout -=1
320             self.current_dbgstate = self.ARMget_dbgstate()
321         return timeout
322
323     def ARMident(self):
324         """Get an ARM's ID."""
325         self.ARMshift_IR(IR_IDCODE,0)
326         self.ARMshift_DR(0,32,LSB)
327         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
328         return retval
329
330     def ARMidentstr(self):
331         ident=self.ARMident()
332         ver     = (ident >> 28)
333         partno  = (ident >> 12) & 0xffff
334         mfgid   = (ident >> 1)  & 0x7ff
335         return "Chip IDCODE:    0x%x\tver: %x\tpartno: %x\tmfgid: %x" % (ident, ver, partno, mfgid); 
336
337     def ARMeice_write(self, reg, val):
338         data = chop(val,4)
339         data.extend([reg])
340         retval = self.writecmd(0x13, EICE_WRITE, 5, data)
341         return retval
342
343     def ARMeice_read(self, reg):
344         self.writecmd(0x13, EICE_READ, 1, [reg])
345         retval, = struct.unpack("<L",self.data)
346         return retval
347
348     def ARMget_dbgstate(self):
349         """Read the config register of an ARM."""
350         self.ARMeice_read(EICE_DBGSTATUS)
351         self.current_dbgstate = struct.unpack("<L", self.data[:4])[0]
352         return self.current_dbgstate
353     status = ARMget_dbgstate
354
355     def statusstr(self):
356         """Check the status as a string."""
357         status=self.status()
358         str=""
359         i=1
360         while i<0x20:
361             if(status&i):
362                 str="%s %s" %(self.ARMstatusbits[i],str)
363             i*=2
364         return str
365
366     def ARMget_dbgctrl(self):
367         """Read the config register of an ARM."""
368         self.ARMeice_read(EICE_DBGCTRL)
369         retval = struct.unpack("<L", self.data[:4])[0]
370         return retval
371
372     def ARMset_dbgctrl(self,config):
373         """Write the config register of an ARM."""
374         self.ARMeice_write(EICE_DBGCTRL, config&7)
375
376     def ARMgetPC(self):
377         """Get an ARM's PC. Note: real PC gets all wonky in debug mode, this is the "saved" PC"""
378         return self.storedPC
379     getpc = ARMgetPC
380     
381     def ARMsetPC(self, val):
382         """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"""
383         self.storedPC = val
384
385     def ARMget_register(self, reg):
386         """Get an ARM's Register"""
387         self.writecmd(0x13,GET_REGISTER,1,[reg&0xf])
388         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
389         return retval
390
391     def ARMset_register(self, reg, val):
392         """Get an ARM's Register"""
393         self.writecmd(0x13,SET_REGISTER,8,[val&0xff, (val>>8)&0xff, (val>>16)&0xff, val>>24, reg,0,0,0])
394         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
395         return retval
396
397     def ARMget_registers(self):
398         """Get ARM Registers"""
399         regs = [ self.ARMget_register(x) for x in range(15) ]
400         regs.append(self.ARMgetPC())            # make sure we snag the "static" version of PC
401         return regs
402
403     def ARMset_registers(self, regs, mask):
404         """Set ARM Registers"""
405         for x in xrange(15):
406           if (1<<x) & mask:
407             self.ARMset_register(x,regs.pop(0))
408         if (1<<15) & mask:                      # make sure we set the "static" version of PC or changes will be lost
409           self.ARMsetPC(regs.pop(0))
410
411     def ARMdebuginstr(self,instr,bkpt):
412         if type (instr) == int or type(instr) == long:
413             instr = struct.pack("<L", instr)
414         instr = [int("0x%x"%ord(x),16) for x in instr]
415         instr.extend([bkpt])
416         self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
417         return (self.data)
418
419     def ARM_nop(self, bkpt=0):
420         if self.status() & DBG_TBIT:
421             return self.ARMdebuginstr(THUMB_INSTR_NOP, bkpt)
422         return self.ARMdebuginstr(ARM_INSTR_NOP, bkpt)
423
424     def ARMrestart(self):
425         self.ARMshift_IR(IR_RESTART)
426
427     def ARMset_watchpoint0(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
428         self.ARMeice_write(EICE_WP0ADDR, addr);           # write 0 in watchpoint 0 address
429         self.ARMeice_write(EICE_WP0ADDRMASK, addrmask);   # write 0xffffffff in watchpoint 0 address mask
430         self.ARMeice_write(EICE_WP0DATA, data);           # write 0 in watchpoint 0 data
431         self.ARMeice_write(EICE_WP0DATAMASK, datamask);   # write 0xffffffff in watchpoint 0 data mask
432         self.ARMeice_write(EICE_WP0CTRL, ctrl);           # write 0x00000100 in watchpoint 0 control value register (enables watchpoint)
433         self.ARMeice_write(EICE_WP0CTRLMASK, ctrlmask);   # write 0xfffffff7 in watchpoint 0 control mask - only detect the fetch instruction
434         return self.data
435
436     def ARMset_watchpoint1(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
437         self.ARMeice_write(EICE_WP1ADDR, addr);           # write 0 in watchpoint 1 address
438         self.ARMeice_write(EICE_WP1ADDRMASK, addrmask);   # write 0xffffffff in watchpoint 1 address mask
439         self.ARMeice_write(EICE_WP1DATA, data);           # write 0 in watchpoint 1 data
440         self.ARMeice_write(EICE_WP1DATAMASK, datamask);   # write 0xffffffff in watchpoint 1 data mask
441         self.ARMeice_write(EICE_WP1CTRL, ctrl);           # write 0x00000100 in watchpoint 1 control value register (enables watchpoint)
442         self.ARMeice_write(EICE_WP1CTRLMASK, ctrlmask);   # write 0xfffffff7 in watchpoint 1 control mask - only detect the fetch instruction
443         return self.data
444
445     def THUMBgetPC(self):
446         THUMB_INSTR_STR_R0_r0 =     0x60006000L
447         THUMB_INSTR_MOV_R0_PC =     0x46b846b8L
448         THUMB_INSTR_BX_PC =         0x47784778L
449         THUMB_INSTR_NOP =           0x1c001c00L
450
451         r0 = self.ARMget_register(0)
452         self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC, 0)
453         retval = self.ARMget_register(0)
454         self.ARMset_register(0,r0)
455         return retval
456
457     def ARMcapture_system_state(self, pcoffset):
458         self.c0Data, self.flags, self.c0Addr = self.ARMchain0(0)
459         if self.ARMget_dbgstate() & DBG_TBIT:
460             pcoffset += 8
461         else:
462             pcoffset += 4
463         self.storedPC = self.ARMget_register(15) + pcoffset
464         self.last_dbg_state = self.ARMget_dbgstate()
465         self.cpsr = self.ARMget_regCPSR()
466         #print "ARMcapture_system_state: stored pc: 0x%x  last_dbg_state: 0x%x" % (self.storedPC, self.last_dbg_state)
467
468     def halt(self):
469         """Halt the CPU."""
470         if self.ARMget_dbgstate()&DBG_DBGACK:
471             if not len(self.stored_regs):
472                 #print "stored regs: " + repr(self.stored_regs)
473                 self.stored_regs = self.ARMget_registers()[:15]
474                 print self.print_stored_registers()
475             return
476         print "halting cpu"
477         self.ARMset_dbgctrl(2)
478         if (self.ARMwaitDBG() == 0):
479             raise Exception("Timeout waiting to enter DEBUG mode on HALT")
480         self.ARMset_dbgctrl(0)
481
482         self.ARMcapture_system_state(PCOFF_DBGRQ)
483         #print "storedPC: %x (%x)      flags: %x    nothing: %x" % (self.storedPC, self.c0Data, self.flags, self.c0Addr)
484         if self.ARMget_dbgstate() & DBG_TBIT:
485             self.ARMsetModeARM()
486             if self.storedPC ^ 4:
487                 self.ARMset_register(15,self.storedPC&0xfffffffc)
488         self.stored_regs = self.ARMget_registers()[:15]
489         #print "stored regs: " + repr(self.stored_regs)
490         #print self.print_stored_registers()
491         #print "CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
492
493     def resume(self):
494         """Resume the CPU."""
495         # FIXME: restore CPSR
496         # FIXME: true up PC to exactly where we left off...
497         if not self.ARMget_dbgstate()&DBG_DBGACK:
498             return
499         print "resume"
500         if len(self.stored_regs):
501             #print self.print_stored_registers()
502             self.ARMset_registers(self.stored_regs, 0x7fff)
503         else:
504             print "skipping restore of stored registers due to empty list ?  WTFO?"
505
506         currentPC, self.currentflags, nothing = self.ARMchain0(self.storedPC,self.flags, self.c0Addr)
507         if not(self.flags & F_TBIT):                                    # need to be in arm mode
508             if self.currentflags & F_TBIT:                              # currently in thumb mode
509                 self.ARMsetModeARM()
510             # branch to the right address
511             self.ARMset_register(15, self.storedPC)
512             #print hex(self.storedPC)
513             #print hex(self.ARMget_register(15))
514             #print hex(self.ARMchain0(self.storedPC,self.flags)[0])
515             self.ARMchain0(self.storedPC,self.flags)
516             self.ARM_nop(0)
517             self.ARM_nop(1)
518             self.ARMdebuginstr(ARM_INSTR_B_IMM | 0xfffff0,0)
519             self.ARM_nop(0)
520             self.ARMrestart()
521
522         elif self.flags & F_TBIT:                                       # need to be in thumb mode
523             if not (self.currentflags & F_TBIT):                        # currently in arm mode
524                 self.ARMsetModeThumb()
525             r0=self.ARMget_register(0)
526             self.ARMset_register(0, self.storedPC)
527             self.ARMdebuginstr(THUMB_INSTR_MOV_PC_R0,0)
528             self.ARM_nop(0)
529             self.ARM_nop(1)
530             #print hex(self.storedPC)
531             #print hex(self.ARMget_register(15))
532             #print hex(self.ARMchain0(self.storedPC,self.flags)[0])
533             self.ARMchain0(self.storedPC,self.flags)[0]
534             self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc),0)
535             self.ARM_nop(0)
536             self.ARMrestart()
537
538         #print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
539         #print >>sys.stderr,"CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
540
541     def resettap(self):
542         self.writecmd(0x13, RESETTAP, 0,[])
543
544     def ARMsetModeARM(self):
545         r0 = None
546         if ((self.current_dbgstate & DBG_TBIT)):
547             #debugstr("=== Switching to ARM mode ===")
548             self.ARM_nop(0)
549             self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
550             self.ARM_nop(0)
551             self.ARM_nop(0)
552         self.resettap()
553         self.current_dbgstate = self.ARMget_dbgstate();
554         return self.current_dbgstate
555
556     def ARMsetModeThumb(self):                               # needs serious work and truing
557         self.resettap()
558         #debugstr("=== Switching to THUMB mode ===")
559         if ( not (self.current_dbgstate & DBG_TBIT)):
560             self.storedPC |= 1
561             r0 = self.ARMget_register(0)
562             self.ARMset_register(0, self.storedPC)
563             self.ARM_nop(0)
564             self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
565             self.ARM_nop(0)
566             self.ARM_nop(0)
567             self.resettap()
568             self.ARMset_register(0,r0)
569         self.current_dbgstate = self.ARMget_dbgstate();
570         return self.current_dbgstate
571
572     def ARMget_regCPSRstr(self):
573         psr = self.ARMget_regCPSR()
574         return hex(psr), PSRdecode(psr)
575
576     def ARMget_regCPSR(self):
577         """Get an ARM's Register"""
578         r0 = self.ARMget_register(0)
579         self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
580         self.ARMdebuginstr(ARM_INSTR_MRS_R0_CPSR, 0) # push MRS_R0, CPSR into pipeline - fetch
581         self.ARM_nop( 0) # push nop into pipeline - decoded
582         self.ARM_nop( 0) # push nop into pipeline - execute
583         retval = self.ARMget_register(0)
584         self.ARMset_register(0, r0)
585         return retval
586
587     def ARMset_regCPSR(self, val):
588         """Get an ARM's Register"""
589         r0 = self.ARMget_register(0)
590         self.ARMset_register(0, val)
591         self.ARM_nop( 0)        # push nop into pipeline - clean out the pipeline...
592         self.ARMdebuginstr(ARM_INSTR_MSR_cpsr_cxsf_R0, 0) # push MSR cpsr_cxsf, R0 into pipeline - fetch
593         self.ARM_nop( 0)        # push nop into pipeline - decoded
594         self.ARM_nop( 0)        # push nop into pipeline - execute
595         self.ARMset_register(0, r0)
596         return(val)
597         
598     def ARMreadStream(self, addr, bytecount):
599         baseaddr    = addr & 0xfffffffc
600         endaddr     = ((addr + bytecount + 3) & 0xfffffffc)
601         diffstart   = 4 - (addr - baseaddr)
602         diffend     = 4 - (endaddr - (addr + bytecount ))
603         
604         
605         out = []
606         data = [ x for x in self.ARMreadChunk( baseaddr, ((endaddr-baseaddr) / 4) ) ]
607         #print data, hex(baseaddr), hex(diffstart), hex(endaddr), hex(diffend)
608         if len(data) == 1:
609             #print "single dword"
610             out.append( struct.pack("<I", data.pop(0)) [4-diffstart:diffend] )
611         else:
612             #print "%d dwords" % len(data)
613             if diffstart:
614                 out.append( struct.pack("<I", data.pop(0)) [4-diffstart:] )
615                 bytecount -= (diffstart)
616                 #print out
617                 
618             for ent in data[:-1]:
619                 out.append( struct.pack("<I", data.pop(0) ) )
620                 bytecount -= 4
621                 #print out
622                 
623             if diffend and bytecount>0:
624                 out.append( struct.pack("<I", data.pop(0)) [:diffend] ) 
625                 #print out
626         return ''.join(out)        
627
628     def ARMprintChunk(self, adr, wordcount=1, verbose=False, width=8):
629         for string in self.ARMreprChunk(adr, wordcount, verbose=False, width=8):
630             sys.stdout.write(string)
631
632     def ARMreprChunk(self, adr, wordcount=1, verbose=False, width=8):
633         adr &= 0xfffffffc
634         endva = adr + (4*wordcount)
635         output = [ "Dwords from 0x%x through 0x%x" % (adr, endva) ]
636         idx = 0
637         for data in self.ARMreadChunk(adr, wordcount, verbose):
638             if (idx % width) == 0:
639                 yield ( "\n0x%.8x\t" % (adr + (4*idx)) )
640             yield ( "%.8x   " % (data) )
641             idx += 1
642
643         yield("\n")
644
645     def ARMreadChunk(self, adr, wordcount=1, verbose=True):
646         """ Only works in ARM mode currently
647         WARNING: Addresses must be word-aligned!
648         """
649         regs = self.ARMget_registers()
650         self.ARMset_registers([0xdeadbeef for x in xrange(14)], 0xe)
651         count = wordcount
652         while (wordcount > 0):
653             if (verbose and wordcount%64 == 0):  sys.stderr.write(".")
654             count = (wordcount, 0xe)[wordcount>0xd]
655             bitmask = LDM_BITMASKS[count]
656             self.ARMset_register(14,adr)
657             self.ARM_nop(1)
658             self.ARMdebuginstr(ARM_INSTR_LDMIA_R14_r0_rx | bitmask ,0)
659             #FIXME: do we need the extra nop here?
660             self.ARMrestart()
661             self.ARMwaitDBG()
662             for x in range(count):
663                 yield self.ARMget_register(x)
664             wordcount -= count
665             adr += count*4
666             #print hex(adr)
667         # FIXME: handle the rest of the wordcount here.
668         self.ARMset_registers(regs,0xe)
669
670     ARMreadMem = ARMreadChunk
671     peek = ARMreadMem
672
673     def ARMwriteChunk(self, adr, wordarray):         
674         """ Only works in ARM mode currently
675         WARNING: Addresses must be word-aligned!
676         """
677         regs = self.ARMget_registers()
678         wordcount = len(wordarray)
679         while (wordcount > 0):
680             if (wordcount%64 == 0):  sys.stderr.write(".")
681             count = (wordcount, 0xe)[wordcount>0xd]
682             bitmask = LDM_BITMASKS[count]
683             self.ARMset_register(14,adr)
684             #print len(wordarray),bin(bitmask)
685             self.ARMset_registers(wordarray[:count],bitmask)
686             self.ARM_nop(1)
687             self.ARMdebuginstr(ARM_INSTR_STMIA_R14_r0_rx | bitmask ,0)
688             #FIXME: do we need the extra nop here?
689             self.ARMrestart()
690             self.ARMwaitDBG()
691             wordarray = wordarray[count:]
692             wordcount -= count
693             adr += count*4
694             #print hex(adr)
695         # FIXME: handle the rest of the wordcount here.
696     ARMwriteMem = ARMwriteChunk
697         
698     def ARMwriteStream(self, addr, datastr):
699         #bytecount = len(datastr)
700         #baseaddr    = addr & 0xfffffffc
701         #diffstart   = addr - baseaddr
702         #endaddr     = ((addr + bytecount) & 0xfffffffc) + 4
703         #diffend     = 4 - (endaddr - (addr+bytecount))
704         bytecount = len(datastr)
705         baseaddr    = addr & 0xfffffffc
706         endaddr     = ((addr + bytecount + 3) & 0xfffffffc)
707         diffstart   = 4 - (addr - baseaddr)
708         diffend     = 4 - (endaddr - (addr + bytecount ))
709                 
710         print hex(baseaddr), hex(diffstart), hex(endaddr), hex(diffend)
711         out = []
712         if diffstart:
713             dword = self.ARMreadChunk(baseaddr, 1)[0] & (0xffffffff>>(8*diffstart))
714             dst = "\x00" * (4-diffstart) + datastr[:diffstart]; print hex(dword), repr(dst)
715             datachk = struct.unpack("<I", dst)[0]
716             out.append( dword+datachk )
717             datastr = datastr[diffstart:]
718             bytecount -= diffstart
719         for ent in xrange(baseaddr+4, endaddr-4, 4):
720             print repr(datastr)
721             dword = struct.unpack("<I", datastr[:4])[0]
722             out.append( dword )
723             datastr = datastr[4:]
724             bytecount -= 4
725         if diffend and bytecount:
726             dword = self.ARMreadChunk(endaddr-4, 1)[0] & (0xffffffff<<(8*diffend))
727             dst = datastr + "\x00" * (4-diffend); print hex(dword), repr(dst)
728             datachk = struct.unpack("<I", dst)[0]
729             out.append( dword+datachk )
730         print repr([hex(x) for x in out])
731         return self.ARMwriteChunk(baseaddr, out)
732         
733         
734     def writeMemByte(self, adr, byte):
735         self.ARMwriteMem(adr, byte, ARM_WRITE_MEM_BYTE)
736
737
738     ARMstatusbits={
739                   0x10 : "TBIT",
740                   0x08 : "cgenL",
741                   0x04 : "Interrupts Enabled (or not?)",
742                   0x02 : "DBGRQ",
743                   0x01 : "DGBACK"
744                   }
745     ARMctrlbits={
746                   0x04 : "disable interrupts",
747                   0x02 : "force dbgrq",
748                   0x01 : "force dbgack"
749                   }
750     def ARMresettarget(self, delay=1000):
751         return self.writecmd(0x13,RESETTARGET,2, [ delay&0xff, (delay>>8)&0xff ] )
752
753     def ARMchain0(self, address, bits=0x819684c054, data=0):
754         bulk = chop(address,4)
755         bulk.extend(chop(bits,8))
756         bulk.extend(chop(data,4))
757         #print >>sys.stderr,(repr(bulk))
758         self.writecmd(0x13,CHAIN0,16,bulk)
759         d1,b1,a1 = struct.unpack("<LQL",self.data)
760         return (a1,b1,d1)
761
762     def start(self, ident=False):
763         """Start debugging."""
764         self.writecmd(0x13,START,0,self.data)
765         if ident:
766             print >>sys.stderr,"Identifying Target:"
767             print >>sys.stderr, self.ARMidentstr()
768             print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
769
770     def stop(self):
771         """Stop debugging."""
772         self.writecmd(0x13,STOP,0,self.data)
773     #def ARMstep_instr(self):
774     #    """Step one instruction."""
775     #    self.writecmd(0x13,STEP_INSTR,0,self.data)
776     #def ARMflashpage(self,adr):
777     #    """Flash 2kB a page of flash from 0xF000 in XDATA"""
778     #    data=[adr&0xFF,
779     #          (adr>>8)&0xFF,
780     #          (adr>>16)&0xFF,
781     #          (adr>>24)&0xFF]
782     #    print "Flashing buffer to 0x%06x" % adr
783     #    self.writecmd(0x13,MASS_FLASH_PAGE,4,data)
784
785     def print_registers(self):
786         return [ hex(x) for x in self.ARMget_registers() ]
787
788     def print_stored_registers(self):
789         return [ hex(x) for x in self.stored_regs ]
790
791
792
793 ######### command line stuff #########
794 from intelhex import IntelHex16bit, IntelHex
795
796 def arm7_syntax():
797     print "Usage: %s verb [objects]\n" % sys.argv[0]
798     print "%s info" % sys.argv[0]
799     print "%s dump $foo.hex [0x$start 0x$stop]" % sys.argv[0]
800     print "%s erase" % sys.argv[0]
801     print "%s eraseinfo" % sys.argv[0]
802     print "%s flash $foo.hex [0x$start 0x$stop]" % sys.argv[0]
803     print "%s verify $foo.hex [0x$start 0x$stop]" % sys.argv[0]
804     print "%s poke 0x$adr 0x$val" % sys.argv[0]
805     print "%s peek 0x$start [0x$stop]" % sys.argv[0]
806     print "%s reset" % sys.argv[0]
807     sys.exit()
808
809 def arm7_main():
810     ''' this function should be called from command line app '''
811
812     #Initialize FET and set baud rate
813     client=GoodFETARM7()
814     client.serInit()
815
816     client.setup()
817     client.start()
818
819     arm7_cli_handler(client, sys.argv)
820
821 def arm7_cli_handler(client, argv):
822     if(argv[1]=="info"):
823         client.halt()
824         print >>sys.stderr, client.ARMidentstr()
825         print >>sys.stderr,"Debug Status:\t%s" % client.statusstr()
826         print >>sys.stderr,"CPSR: (%s) %s\n"%(client.ARMget_regCPSRstr())
827         client.resume()
828
829
830     if(argv[1]=="dump"):
831         f = sys.argv[2]
832         start=0x00000000
833         stop=0xFFFFFFFF
834         if(len(sys.argv)>3):
835             start=int(sys.argv[3],16)
836         if(len(sys.argv)>4):
837             stop=int(sys.argv[4],16)
838         
839         print "Dumping from %04x to %04x as %s." % (start,stop,f)
840         #h = IntelHex16bit(None)
841         # FIXME: get mcu state and return it to that state
842         client.halt()
843
844         try:
845             h = IntelHex(None)
846             i=start
847             while i<=stop:
848                 #data=client.ARMreadMem(i, 48)
849                 data=client.ARMreadChunk(i, 48, verbose=0)
850                 print "Dumped %06x."%i
851                 for dword in data:
852                     if i<=stop and dword != 0xdeadbeef:
853                         h.puts( i, struct.pack("<I", dword) )
854                     i+=4
855             # FIXME: get mcu state and return it to that state
856         except:
857             print "Unknown error during read. Writing results to output file."
858             print "Rename file with last address dumped %06x."%i
859             pass
860
861         client.resume()
862         h.write_hex_file(f)
863
864     '''
865     if(sys.argv[1]=="erase"):
866         print "Erasing main flash memory."
867         client.ARMmasserase()
868
869     if(sys.argv[1]=="eraseinfo"):
870         print "Erasing info memory."
871         client.ARMinfoerase()
872
873         
874     '''
875     if(sys.argv[1]=="ivt"):
876         client.halt()
877         client.ARMprintChunk(0x0,0x20)
878         client.resume()
879
880     if(sys.argv[1]=="regs"):
881         client.halt()
882         for i in range(0,16):
883             print "r%i=%04x" % (i,client.ARMget_register(i))
884         client.resume()
885
886     if(sys.argv[1]=="flash"):
887         f=sys.argv[2]
888         start=0
889         stop=0x10000
890         if(len(sys.argv)>3):
891             start=int(sys.argv[3],16)
892         if(len(sys.argv)>4):
893             stop=int(sys.argv[4],16)
894         
895         client.halt()
896         h = IntelHex16bit(f)
897         
898         #Should this be default?
899         #Makes flashing multiple images inconvenient.
900         #client.ARMmasserase()
901         
902         count=0; #Bytes in commit.
903         first=0
904         vals=[]
905         last=0;  #Last address committed.
906         for i in h._buf.keys():
907             if((count>0x40 or last+2!=i) and count>0 and i&1==0):
908                 #print "%i, %x, %x" % (len(vals), last, i)
909                 client.ARMpokeflashblock(first,vals)
910                 count=0
911                 first=0
912                 last=0
913                 vals=[]
914             if(i>=start and i<stop  and i&1==0):
915                 val=h[i>>1]
916                 if(count==0):
917                     first=i
918                 last=i
919                 count+=2
920                 vals+=[val&0xff,(val&0xff00)>>8]
921                 if(i%0x100==0):
922                     print "%04x" % i
923         if count>0: #last commit, ivt
924             client.ARMpokeflashblock(first,vals)
925         client.resume()
926
927     if(sys.argv[1]=="verify"):
928         f=sys.argv[2]
929         start=0
930         stop=0xFFFF
931         if(len(sys.argv)>3):
932             start=int(sys.argv[3],16)
933         if(len(sys.argv)>4):
934             stop=int(sys.argv[4],16)
935         
936         client.halt()
937         h = IntelHex16bit(f)
938         for i in h._buf.keys():
939             if(i>=start and i<stop and i&1==0):
940                 peek=client.peek(i)
941                 if(h[i>>1]!=peek):
942                     print "ERROR at %04x, found %04x not %04x"%(i,peek,h[i>>1])
943                 if(i%0x100==0):
944                     print "%04x" % i
945         client.resume()
946
947
948     if(sys.argv[1]=="peek"):
949         start = 0x0000
950         if(len(sys.argv)>2):
951             start=int(sys.argv[2],16)
952
953         stop = start+4
954         if(len(sys.argv)>3):
955             stop=int(sys.argv[3],16)
956
957         print "Peeking from %04x to %04x." % (start,stop)
958         client.halt()
959         for dword in client.ARMreadChunk(start, (stop-start)/4, verbose=0):
960             print "%.4x: %.8x" % (start, dword)
961             start += 4
962         client.resume()
963
964     if(sys.argv[1]=="poke"):
965         start=0x0000
966         val=0x00
967         if(len(sys.argv)>2):
968             start=int(sys.argv[2],16)
969         if(len(sys.argv)>3):
970             val=int(sys.argv[3],16)
971         
972         print "Poking %06x to become %04x." % (start,val)
973         client.halt()
974         #???while client.ARMreadMem(start)[0]&(~val)>0:
975         client.ARMwriteChunk(start, [val])
976         print "Poked to %.8x" % client.ARMreadMem(start)[0]
977         client.resume()
978
979
980     if(sys.argv[1]=="reset"):
981         #Set PC to RESET vector's value.
982         
983         #client.ARMsetPC(0x00000000)
984         #client.ARMset_regCPSR(0)
985         #client.ARMreleasecpu()
986         client.ARMresettarget(1000)
987
988     #client.ARMreleasecpu()
989     #client.ARMstop()
990