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