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