0864cb2019713a7138923945018ad66424b34f1d
[goodfet] / 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, binascii, struct, time
13 from GoodFET import GoodFET
14 from intelhex import IntelHex
15
16
17 #Global Commands
18 READ  = 0x00
19 WRITE = 0x01
20 PEEK  = 0x02
21 POKE  = 0x03
22 SETUP = 0x10
23 START = 0x20
24 STOP  = 0x21
25 CALL  = 0x30
26 EXEC  = 0x31
27 NOK   = 0x7E
28 OK    = 0x7F
29
30 # ARM7TDMI JTAG commands
31 IR_SHIFT =                  0x80
32 DR_SHIFT =                  0x81
33 RESETTAP =                  0x82
34 RESETTARGET =               0x83
35 GET_REGISTER =              0x87
36 SET_REGISTER =              0x88
37 DEBUG_INSTR =               0x89
38 # Really ARM specific stuff
39 WAIT_DBG =                  0x91
40 CHAIN0 =                    0x93
41 SCANCHAIN1 =                0x94
42 EICE_READ =                 0x95
43 EICE_WRITE =                0x96
44
45 IR_EXTEST           =  0x0
46 IR_SCAN_N           =  0x2
47 IR_SAMPLE           =  0x3
48 IR_RESTART          =  0x4
49 IR_CLAMP            =  0x5
50 IR_HIGHZ            =  0x7
51 IR_CLAMPZ           =  0x9
52 IR_INTEST           =  0xC
53 IR_IDCODE           =  0xE
54 IR_BYPASS           =  0xF
55
56 DBG_DBGACK =    1
57 DBG_DBGRQ =     2
58 DBG_IFEN =      4
59 DBG_cgenL =     8
60 DBG_TBIT =      16
61
62
63 EICE_DBGCTRL =                     0  # read 3 bit - Debug Control
64 EICE_DBGCTRL_BITLEN =              3
65 EICE_DBGSTATUS =                   1  # read 5 bit - Debug Status
66 EICE_DBGSTATUS_BITLEN =            5
67 EICE_DBGCCR =                      4  # read 6 bit - Debug Comms Control Register
68 EICE_DBGCCR_BITLEN =               6
69 EICE_DBGCDR =                      5  # r/w 32 bit - Debug Comms Data Register
70 EICE_WP0ADDR =                     8  # r/w 32 bit - Watchpoint 0 Address
71 EICE_WP0ADDRMASK =                 9  # r/w 32 bit - Watchpoint 0 Addres Mask
72 EICE_WP0DATA =                     10 # r/w 32 bit - Watchpoint 0 Data
73 EICE_WP0DATAMASK =                 11 # r/w 32 bit - Watchpoint 0 Data Masl
74 EICE_WP0CTRL =                     12 # r/w 9 bit - Watchpoint 0 Control Value
75 EICE_WP0CTRLMASK =                 13 # r/w 8 bit - Watchpoint 0 Control Mask
76 EICE_WP1ADDR =                     16 # r/w 32 bit - Watchpoint 0 Address
77 EICE_WP1ADDRMASK =                 17 # r/w 32 bit - Watchpoint 0 Addres Mask
78 EICE_WP1DATA =                     18 # r/w 32 bit - Watchpoint 0 Data
79 EICE_WP1DATAMASK =                 19 # r/w 32 bit - Watchpoint 0 Data Masl
80 EICE_WP1CTRL =                     20 # r/w 9 bit - Watchpoint 0 Control Value
81 EICE_WP1CTRLMASK =                 21 # r/w 8 bit - Watchpoint 0 Control Mask
82
83 MSB         = 0
84 LSB         = 1
85 NOEND       = 2
86 NORETIDLE   = 4
87
88 F_TBIT      = 1<<40
89
90 PM_usr = 0b10000
91 PM_fiq = 0b10001
92 PM_irq = 0b10010
93 PM_svc = 0b10011
94 PM_abt = 0b10111
95 PM_und = 0b11011
96 PM_sys = 0b11111
97 proc_modes = {
98     0:      ("UNKNOWN, MESSED UP PROCESSOR MODE","fsck", "This should Never happen.  MCU is in funky state!"),
99     PM_usr: ("User Processor Mode", "usr", "Normal program execution mode"),
100     PM_fiq: ("FIQ Processor Mode", "fiq", "Supports a high-speed data transfer or channel process"),
101     PM_irq: ("IRQ Processor Mode", "irq", "Used for general-purpose interrupt handling"),
102     PM_svc: ("Supervisor Processor Mode", "svc", "A protected mode for the operating system"),
103     PM_abt: ("Abort Processor Mode", "abt", "Implements virtual memory and/or memory protection"),
104     PM_und: ("Undefined Processor Mode", "und", "Supports software emulation of hardware coprocessor"),
105     PM_sys: ("System Processor Mode", "sys", "Runs privileged operating system tasks (ARMv4 and above)"),
106 }
107
108 PSR_bits = [ 
109     None, None, None, None, None, "Thumb", "nFIQ_int", "nIRQ_int", 
110     "nImprDataAbort_int", "BIGendian", None, None, None, None, None, None, 
111     "GE_0", "GE_1", "GE_2", "GE_3", None, None, None, None, 
112     "Jazelle", None, None, "Q (DSP-overflow)", "oVerflow", "Carry", "Zero", "Neg",
113     ]
114
115 ARM_INSTR_NOP =             0xe1a00000L
116 ARM_INSTR_BX_R0 =           0xe12fff10L
117 ARM_INSTR_STR_Rx_r14 =      0xe58f0000L # from atmel docs
118 ARM_READ_REG =              ARM_INSTR_STR_Rx_r14
119 ARM_INSTR_LDR_Rx_r14 =      0xe59f0000L # from atmel docs
120 ARM_WRITE_REG =             ARM_INSTR_LDR_Rx_r14
121 ARM_INSTR_LDR_R1_r0_4 =     0xe4901004L
122 ARM_READ_MEM =              ARM_INSTR_LDR_R1_r0_4
123 ARM_INSTR_STR_R1_r0_4 =     0xe4801004L
124 ARM_WRITE_MEM =             ARM_INSTR_STR_R1_r0_4
125 ARM_INSTR_MRS_R0_CPSR =     0xe10f0000L
126 ARM_INSTR_MSR_cpsr_cxsf_R0 =0xe12ff000L
127 ARM_INSTR_STMIA_R14_r0_rx = 0xE88e0000L      # add up to 65k to indicate which registers...
128 ARM_INSTR_LDMIA_R14_r0_rx = 0xE89e0000L      # add up to 65k to indicate which registers...
129 ARM_STORE_MULTIPLE =        ARM_INSTR_STMIA_R14_r0_rx
130 ARM_INSTR_SKANKREGS =       0xE88F7fffL
131 ARM_INSTR_CLOBBEREGS =      0xE89F7fffL
132
133 ARM_INSTR_B_IMM =           0xea000000L
134 ARM_INSTR_B_PC =            0xea000000L
135 ARM_INSTR_BX_PC =           0xe1200010L      # need to set r0 to the desired address
136 THUMB_INSTR_LDR_R0_r0 =     0x68006800L
137 THUMB_WRITE_REG =           THUMB_INSTR_LDR_R0_r0
138 THUMB_INSTR_STR_R0_r0 =     0x60006000L
139 THUMB_READ_REG =            THUMB_INSTR_STR_R0_r0
140 THUMB_INSTR_MOV_R0_PC =     0x46b846b8L
141 THUMB_INSTR_MOV_PC_R0 =     0x46474647L
142 THUMB_INSTR_BX_PC =         0x47784778L
143 THUMB_INSTR_NOP =           0x1c001c00L
144 THUMB_INSTR_B_IMM =         0xe000e000L
145 ARM_REG_PC =                15
146
147 nRW         = 0
148 MAS0        = 1
149 MAS1        = 2
150 nOPC        = 3
151 nTRANS      = 4
152 EXTERN      = 5
153 CHAIN       = 6
154 RANGE       = 7
155 ENABLE      = 8
156
157 DBGCTRLBITS = {
158         'nRW':nRW,
159         'MAS0':MAS0,
160         'MAS1':MAS1,
161         'nOPC':nOPC,
162         'nTRANS':nTRANS,
163         'EXTERN':EXTERN,
164         'CHAIN':CHAIN,
165         'RANGE':RANGE,
166         'ENABLE':ENABLE,
167         1<<nRW:'nRW',
168         1<<MAS0:'MAS0',
169         1<<MAS1:'MAS1',
170         1<<nOPC:'nOPC',
171         1<<nTRANS:'nTRANS',
172         1<<EXTERN:'EXTERN',
173         1<<CHAIN:'CHAIN',
174         1<<RANGE:'RANGE',
175         1<<ENABLE:'ENABLE',
176         }
177
178 LDM_BITMASKS = [(1<<x)-1 for x in xrange(16)]
179 #### TOTALLY BROKEN, NEED VALIDATION AND TESTING
180 PCOFF_DBGRQ = 4 * 4
181 PCOFF_WATCH = 4 * 4
182 PCOFF_BREAK = 4 * 4
183
184
185 def debugstr(strng):
186     print >>sys.stderr,(strng)
187 def PSRdecode(psrval):
188     output = [ "(%s mode)"%proc_modes[psrval&0x1f][1] ]
189     for x in xrange(5,32):
190         if psrval & (1<<x):
191             output.append(PSR_bits[x])
192     return " ".join(output)
193    
194 fmt = [None, "B", "<H", None, "<L", None, None, None, "<Q"]
195 def chop(val,byts):
196     s = struct.pack(fmt[byts], val)
197     return [ord(b) for b in s ]
198         
199 class GoodFETARM(GoodFET):
200     """A GoodFET variant for use with ARM7TDMI microprocessor."""
201     def __init__(self):
202         GoodFET.__init__(self)
203         self.storedPC =         0xffffffff
204         self.current_dbgstate = 0xffffffff
205         self.flags =            0xffffffff
206         self.nothing =          0xffffffff
207     def __del__(self):
208         try:
209             if (self.ARMget_dbgstate()&9) == 9:
210                 self.resume()
211         except:
212             sys.excepthook(*sys.exc_info())
213     def setup(self):
214         """Move the FET into the JTAG ARM application."""
215         #print "Initializing ARM."
216         self.writecmd(0x13,SETUP,0,self.data)
217     def getpc(self):
218         return self.ARMgetPC()
219     def flash(self,file):
220         """Flash an intel hex file to code memory."""
221         print "Flash not implemented.";
222     def dump(self,file,start=0,stop=0xffff):
223         """Dump an intel hex file from code memory."""
224         print "Dump not implemented.";
225     def ARMshift_IR(self, IR, noretidle=0):
226         self.writecmd(0x13,IR_SHIFT,2, [IR, LSB|noretidle])
227         return self.data
228     def ARMshift_DR(self, data, bits, flags):
229         self.writecmd(0x13,DR_SHIFT,8,[bits&0xff, flags&0xff, 0, 0, data&0xff,(data>>8)&0xff,(data>>16)&0xff,(data>>24)&0xff])
230         return self.data
231     def ARMwaitDBG(self, timeout=0xff):
232         self.current_dbgstate = self.ARMget_dbgstate()
233         while ( not ((self.current_dbgstate & 9L) == 9)):
234             timeout -=1
235             self.current_dbgstate = self.ARMget_dbgstate()
236         return timeout
237     def ARMident(self):
238         """Get an ARM's ID."""
239         self.ARMshift_IR(IR_IDCODE,0)
240         self.ARMshift_DR(0,32,LSB)
241         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
242         return retval
243     def ARMidentstr(self):
244         ident=self.ARMident()
245         ver     = (ident >> 28)
246         partno  = (ident >> 12) & 0xffff
247         mfgid   = (ident >> 1)  & 0x7ff
248         return "Chip IDCODE: 0x%x\n\tver: %x\n\tpartno: %x\n\tmfgid: %x\n" % (ident, ver, partno, mfgid); 
249     def ARMeice_write(self, reg, val):
250         data = chop(val,4)
251         data.extend([reg])
252         retval = self.writecmd(0x13, EICE_WRITE, 5, data)
253         return retval
254     def ARMeice_read(self, reg):
255         self.writecmd(0x13, EICE_READ, 1, [reg])
256         retval, = struct.unpack("<L",self.data)
257         return retval
258     def ARMget_dbgstate(self):
259         """Read the config register of an ARM."""
260         self.ARMeice_read(EICE_DBGSTATUS)
261         self.current_dbgstate = struct.unpack("<L", self.data[:4])[0]
262         return self.current_dbgstate
263     status = ARMget_dbgstate
264     def statusstr(self):
265         """Check the status as a string."""
266         status=self.status()
267         str=""
268         i=1
269         while i<0x20:
270             if(status&i):
271                 str="%s %s" %(self.ARMstatusbits[i],str)
272             i*=2
273         return str
274     def ARMget_dbgctrl(self):
275         """Read the config register of an ARM."""
276         self.ARMeice_read(EICE_DBGCTRL)
277         retval = struct.unpack("<L", self.data[:4])[0]
278         return retval
279     def ARMset_dbgctrl(self,config):
280         """Write the config register of an ARM."""
281         self.ARMeice_write(EICE_DBGCTRL, config&7)
282     def ARMgetPC(self):
283         """Get an ARM's PC. Note: real PC gets all wonky in debug mode, this is the "saved" PC"""
284         return self.storedPC
285     def ARMsetPC(self, val):
286         """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"""
287         self.storedPC = val
288     def ARMget_register(self, reg):
289         """Get an ARM's Register"""
290         self.writecmd(0x13,GET_REGISTER,1,[reg&0xf])
291         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
292         return retval
293     def ARMset_register(self, reg, val):
294         """Get an ARM's Register"""
295         self.writecmd(0x13,SET_REGISTER,8,[val&0xff, (val>>8)&0xff, (val>>16)&0xff, val>>24, reg,0,0,0])
296         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
297         return retval
298     def ARMget_registers(self):
299         """Get ARM Registers"""
300         regs = [ self.ARMget_register(x) for x in range(15) ]
301         regs.append(self.ARMgetPC())            # make sure we snag the "static" version of PC
302         return regs
303     def ARMset_registers(self, regs, mask):
304         """Set ARM Registers"""
305         for x in xrange(15):
306           if (1<<x) & mask:
307             self.ARMset_register(x,regs.pop(0))
308         if (1<<15) & mask:                      # make sure we set the "static" version of PC or changes will be lost
309           self.ARMsetPC(regs.pop(0))
310     def ARMdebuginstr(self,instr,bkpt):
311         if type (instr) == int or type(instr) == long:
312             instr = struct.pack("<L", instr)
313         instr = [int("0x%x"%ord(x),16) for x in instr]
314         instr.extend([bkpt])
315         self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
316         return (self.data)
317     def ARM_nop(self, bkpt=0):
318         if self.status() & DBG_TBIT:
319             return self.ARMdebuginstr(THUMB_INSTR_NOP, bkpt)
320         return self.ARMdebuginstr(ARM_INSTR_NOP, bkpt)
321     def ARMrestart(self):
322         self.ARMshift_IR(IR_RESTART)
323     def ARMset_watchpoint0(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
324         self.ARMeice_write(EICE_WP0ADDR, addr);           # write 0 in watchpoint 0 address
325         self.ARMeice_write(EICE_WP0ADDRMASK, addrmask);   # write 0xffffffff in watchpoint 0 address mask
326         self.ARMeice_write(EICE_WP0DATA, data);           # write 0 in watchpoint 0 data
327         self.ARMeice_write(EICE_WP0DATAMASK, datamask);   # write 0xffffffff in watchpoint 0 data mask
328         self.ARMeice_write(EICE_WP0CTRL, ctrl);           # write 0x00000100 in watchpoint 0 control value register (enables watchpoint)
329         self.ARMeice_write(EICE_WP0CTRLMASK, ctrlmask);   # write 0xfffffff7 in watchpoint 0 control mask - only detect the fetch instruction
330         return self.data
331     def ARMset_watchpoint1(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
332         self.ARMeice_write(EICE_WP1ADDR, addr);           # write 0 in watchpoint 1 address
333         self.ARMeice_write(EICE_WP1ADDRMASK, addrmask);   # write 0xffffffff in watchpoint 1 address mask
334         self.ARMeice_write(EICE_WP1DATA, data);           # write 0 in watchpoint 1 data
335         self.ARMeice_write(EICE_WP1DATAMASK, datamask);   # write 0xffffffff in watchpoint 1 data mask
336         self.ARMeice_write(EICE_WP1CTRL, ctrl);           # write 0x00000100 in watchpoint 1 control value register (enables watchpoint)
337         self.ARMeice_write(EICE_WP1CTRLMASK, ctrlmask);   # write 0xfffffff7 in watchpoint 1 control mask - only detect the fetch instruction
338         return self.data
339     def THUMBgetPC(self):
340         THUMB_INSTR_STR_R0_r0 =     0x60006000L
341         THUMB_INSTR_MOV_R0_PC =     0x46b846b8L
342         THUMB_INSTR_BX_PC =         0x47784778L
343         THUMB_INSTR_NOP =           0x1c001c00L
344
345         r0 = self.ARMget_register(0)
346         self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC, 0)
347         retval = self.ARMget_register(0)
348         self.ARMset_register(0,r0)
349         return retval
350     def ARMcapture_system_state(self, pcoffset):
351         if self.ARMget_dbgstate() & DBG_TBIT:
352             pcoffset += 8
353         else:
354             pcoffset += 4
355         self.storedPC = self.ARMget_register(15) + pcoffset
356         self.last_dbg_state = self.ARMget_dbgstate()
357     def ARMhaltcpu(self):
358         """Halt the CPU."""
359         if not(self.ARMget_dbgstate()&1):
360             self.ARMset_dbgctrl(2)
361             if (self.ARMwaitDBG() == 0):
362                 raise Exception("Timeout waiting to enter DEBUG mode on HALT")
363             self.ARMset_dbgctrl(0)
364             self.ARMcapture_system_state(PCOFF_DBGRQ)
365             if self.last_dbg_state&0x10:
366                 self.storedPC = self.THUMBgetPC()
367             else:
368                 self.storedPC = self.ARMget_register(15)
369         self.storedPC, self.flags, self.nothing = self.ARMchain0(0)
370         if self.ARMget_dbgstate() & DBG_TBIT:
371             self.ARMsetModeARM()
372             if self.storedPC ^ 4:
373                 self.ARMset_register(15,self.storedPC&0xfffffffc)
374         print "CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
375     halt = ARMhaltcpu
376     def ARMreleasecpu(self):
377         """Resume the CPU."""
378         # restore registers FIXME: DO THIS
379         if self.ARMget_dbgstate()&1 == 0:
380             return
381         currentPC, self.currentflags, nothing = self.ARMchain0(self.storedPC,self.flags)
382         if not(self.flags & F_TBIT):                                    # need to be in arm mode
383             if self.currentflags & F_TBIT:                              # currently in thumb mode
384                 self.ARMsetModeARM()
385             # branch to the right address
386             self.ARMset_register(15, self.storedPC)
387             print hex(self.storedPC)
388             print hex(self.ARMget_register(15))
389             print hex(self.ARMchain0(self.storedPC,self.flags)[0])
390             self.ARM_nop(0)
391             self.ARM_nop(1)
392             self.ARMdebuginstr(ARM_INSTR_B_IMM | 0xfffff0,0)
393             self.ARM_nop(0)
394             self.ARMrestart()
395
396         elif self.flags & F_TBIT:                                       # need to be in thumb mode
397             if not (self.currentflags & F_TBIT):                        # currently in arm mode
398                 self.ARMsetModeThumb()
399             r0=self.ARMget_register(0)
400             self.ARMset_register(0, self.storedPC)
401             self.ARMdebuginstr(THUMB_INSTR_MOV_PC_R0,0)
402             self.ARM_nop(0)
403             self.ARM_nop(1)
404             print hex(self.storedPC)
405             print hex(self.ARMget_register(15))
406             print hex(self.ARMchain0(self.storedPC,self.flags)[0])
407             self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc),0)
408             self.ARM_nop(0)
409             self.ARMrestart()
410
411
412     resume = ARMreleasecpu
413     def resettap(self):
414         self.writecmd(0x13, RESETTAP, 0,[])
415     def ARMsetModeARM(self):
416         r0 = None
417         if ((self.current_dbgstate & DBG_TBIT)):
418             debugstr("=== Switching to ARM mode ===")
419             self.ARM_nop(0)
420             self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
421             self.ARM_nop(0)
422             self.ARM_nop(0)
423         self.resettap()
424         self.current_dbgstate = self.ARMget_dbgstate();
425         return self.current_dbgstate
426     def ARMsetModeThumb(self):                               # needs serious work and truing
427         self.resettap()
428         debugstr("=== Switching to THUMB mode ===")
429         if ( not (self.current_dbgstate & DBG_TBIT)):
430             self.storedPC |= 1
431             r0 = self.ARMget_register(0)
432             self.ARMset_register(0, self.storedPC)
433             self.ARM_nop(0)
434             self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
435             self.ARM_nop(0)
436             self.ARM_nop(0)
437             self.resettap()
438             self.ARMset_register(0,r0)
439         self.current_dbgstate = self.ARMget_dbgstate();
440         return self.current_dbgstate
441     def ARMget_regCPSRstr(self):
442         psr = self.ARMget_regCPSR()
443         return hex(psr), PSRdecode(psr)
444     def ARMget_regCPSR(self):
445         """Get an ARM's Register"""
446         r0 = self.ARMget_register(0)
447         self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
448         self.ARMdebuginstr(ARM_INSTR_MRS_R0_CPSR, 0) # push MRS_R0, CPSR into pipeline - fetch
449         self.ARM_nop( 0) # push nop into pipeline - decoded
450         self.ARM_nop( 0) # push nop into pipeline - execute
451         retval = self.ARMget_register(0)
452         self.ARMset_register(0, r0)
453         return retval
454     def ARMset_regCPSR(self, val):
455         """Get an ARM's Register"""
456         r0 = self.ARMget_register(0)
457         self.ARMset_register(0, val)
458         self.ARM_nop( 0)        # push nop into pipeline - clean out the pipeline...
459         self.ARMdebuginstr(ARM_INSTR_MSR_cpsr_cxsf_R0, 0) # push MSR cpsr_cxsf, R0 into pipeline - fetch
460         self.ARM_nop( 0)        # push nop into pipeline - decoded
461         self.ARM_nop( 0)        # push nop into pipeline - execute
462         self.ARMset_register(0, r0)
463         return(val)
464     def ARMreadMem(self, adr, wrdcount=1):
465         retval = [] 
466         r0 = self.ARMget_register(0);        # store R0 and R1
467         r1 = self.ARMget_register(1);
468         #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
469         self.ARMset_register(0, adr);        # write address into R0
470         self.ARMset_register(1, 0xdeadbeef)
471         for word in range(adr, adr+(wrdcount*4), 4):
472             #sys.stdin.readline()
473             self.ARM_nop(0)
474             self.ARM_nop(1)
475             self.ARMdebuginstr(ARM_READ_MEM, 0); # push LDR R1, [R0], #4 into instruction pipeline  (autoincrements for consecutive reads)
476             self.ARM_nop(0)
477             self.ARMrestart()
478             self.ARMwaitDBG()
479             print hex(self.ARMget_register(1))
480
481             # FIXME: this may end up changing te current debug-state.  should we compare to current_dbgstate?
482             #print repr(self.data[4])
483             if (len(self.data)>4 and self.data[4] == '\x00'):
484               print >>sys.stderr,("FAILED TO READ MEMORY/RE-ENTER DEBUG MODE")
485               raise Exception("FAILED TO READ MEMORY/RE-ENTER DEBUG MODE")
486               return (-1);
487             else:
488               retval.append( self.ARMget_register(1) )  # read memory value from R1 register
489               #print >>sys.stderr,("CPSR: %x\t\tR0: %x\t\tR1: %x"%(self.ARMget_regCPSR(),self.ARMget_register(0),self.ARMget_register(1)))
490         self.ARMset_register(1, r1);       # restore R0 and R1 
491         self.ARMset_register(0, r0);
492         return retval
493     def ARMreadChunk(self, adr, wordcount):         
494         """ Only works in ARM mode currently
495         WARNING: Addresses must be word-aligned!
496         """
497         regs = self.ARMget_registers()
498         self.ARMset_registers([0xdeadbeef for x in xrange(14)], 0xe)
499         output = []
500         count = wordcount
501         while (wordcount > 0):
502             if (wordcount%64 == 0):  sys.stderr.write(".")
503             count = (wordcount, 0xe)[wordcount>0xd]
504             bitmask = LDM_BITMASKS[count]
505             self.ARMset_register(14,adr)
506             self.ARM_nop(1)
507             self.ARMdebuginstr(ARM_INSTR_LDMIA_R14_r0_rx | bitmask ,0)
508             #FIXME: do we need the extra nop here?
509             self.ARMrestart()
510             self.ARMwaitDBG()
511             output.extend([self.ARMget_register(x) for x in xrange(count)])
512             wordcount -= count
513             adr += count*4
514             #print hex(adr)
515         # FIXME: handle the rest of the wordcount here.
516         self.ARMset_registers(regs,0xe)
517         return output
518     def ARMreadStream(self, adr, bytecount):
519         data = [struct.unpack("<L", x) for x in self.ARMreadChunk(adr, (bytecount-1/4)+1)]
520         return "".join(data)[:bytecount]
521         
522     def ARMwriteChunk(self, adr, wordarray):         
523         """ Only works in ARM mode currently
524         WARNING: Addresses must be word-aligned!
525         """
526         regs = self.ARMget_registers()
527         wordcount = len(wordarray)
528         while (wordcount > 0):
529             if (wordcount%64 == 0):  sys.stderr.write(".")
530             count = (wordcount, 0xe)[wordcount>0xd]
531             bitmask = LDM_BITMASKS[count]
532             self.ARMset_register(14,adr)
533             #print len(wordarray),bin(bitmask)
534             self.ARMset_registers(wordarray[:count],bitmask)
535             self.ARM_nop(1)
536             self.ARMdebuginstr(ARM_INSTR_STMIA_R14_r0_rx | bitmask ,0)
537             #FIXME: do we need the extra nop here?
538             self.ARMrestart()
539             self.ARMwaitDBG()
540             wordarray = wordarray[count:]
541             wordcount -= count
542             adr += count*4
543             #print hex(adr)
544         # FIXME: handle the rest of the wordcount here.
545     def ARMwriteMem(self, adr, wordarray):
546         r0 = self.ARMget_register(0);        # store R0 and R1
547         r1 = self.ARMget_register(1);
548         #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
549         for widx in xrange(len(wordarray)):
550             address = adr + (widx*4)
551             word = wordarray[widx]
552             self.ARMset_register(0, address);        # write address into R0
553             self.ARMset_register(1, word);        # write address into R0
554             self.ARM_nop(0)
555             self.ARM_nop(1)
556             self.ARMdebuginstr(ARM_WRITE_MEM, 0); # push STR R1, [R0], #4 into instruction pipeline  (autoincrements for consecutive writes)
557             self.ARM_nop(0)
558             self.ARMrestart()
559             self.ARMwaitDBG()
560             print >>sys.stderr,hex(self.ARMget_register(1))
561         self.ARMset_register(1, r1);       # restore R0 and R1 
562         self.ARMset_register(0, r0);
563
564     ARMstatusbits={
565                   0x10 : "TBIT",
566                   0x08 : "cgenL",
567                   0x04 : "Interrupts Enabled (or not?)",
568                   0x02 : "DBGRQ",
569                   0x01 : "DGBACK"
570                   }
571     ARMctrlbits={
572                   0x04 : "disable interrupts",
573                   0x02 : "force dbgrq",
574                   0x01 : "force dbgack"
575                   }
576     def ARMresettarget(self, delay=10):
577         return self.writecmd(0x13,RESETTARGET,2, [ delay&0xff, (delay>>8)&0xff ] )
578     def ARMchain0(self, address, bits=0x819684c054, data=0):
579         bulk = chop(address,4)
580         bulk.extend(chop(bits,8))
581         bulk.extend(chop(data,4))
582         print >>sys.stderr,(repr(bulk))
583         self.writecmd(0x13,CHAIN0,16,bulk)
584         d1,b1,a1 = struct.unpack("<LQL",self.data)
585         return (a1,b1,d1)
586     def start(self):
587         """Start debugging."""
588         self.writecmd(0x13,START,0,self.data)
589         print >>sys.stderr,"Identifying Target:"
590         ident=self.ARMidentstr()
591         print >>sys.stderr,ident
592         print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
593
594     def stop(self):
595         """Stop debugging."""
596         self.writecmd(0x13,STOP,0,self.data)
597     #def ARMstep_instr(self):
598     #    """Step one instruction."""
599     #    self.writecmd(0x13,STEP_INSTR,0,self.data)
600     #def ARMflashpage(self,adr):
601     #    """Flash 2kB a page of flash from 0xF000 in XDATA"""
602     #    data=[adr&0xFF,
603     #          (adr>>8)&0xFF,
604     #          (adr>>16)&0xFF,
605     #          (adr>>24)&0xFF]
606     #    print "Flashing buffer to 0x%06x" % adr
607     #    self.writecmd(0x13,MASS_FLASH_PAGE,4,data)
608
609