2 # GoodFET ARM Client Library
5 # Good luck with alpha / beta code.
6 # Contributions and bug reports welcome.
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)
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
20 import sys, binascii, struct, time
21 import atlasutils.smartprint as asp
22 from GoodFET import GoodFET
23 from intelhex import IntelHex
39 # ARM7TDMI JTAG commands
47 # Really ARM specific stuff
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
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)"),
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",
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_STORE_MULTIPLE = ARM_INSTR_STMIA_R14_r0_rx
138 ARM_INSTR_SKANKREGS = 0xE88F7fffL
139 ARM_INSTR_CLOBBEREGS = 0xE89F7fffL
141 ARM_INSTR_B_IMM = 0xea000000L
142 ARM_INSTR_B_PC = 0xea000000L
143 ARM_INSTR_BX_PC = 0xe1200010L # need to set r0 to the desired address
144 THUMB_INSTR_LDR_R0_r0 = 0x68006800L
145 THUMB_WRITE_REG = THUMB_INSTR_LDR_R0_r0
146 THUMB_INSTR_STR_R0_r0 = 0x60006000L
147 THUMB_READ_REG = THUMB_INSTR_STR_R0_r0
148 THUMB_INSTR_MOV_R0_PC = 0x46b846b8L
149 THUMB_INSTR_MOV_PC_R0 = 0x46474647L
150 THUMB_INSTR_BX_PC = 0x47784778L
151 THUMB_INSTR_NOP = 0x1c001c00L
152 THUMB_INSTR_B_IMM = 0xe000e000L
186 #### TOTALLY BROKEN, NEED VALIDATION AND TESTING
193 print >>sys.stderr,(strng)
194 def PSRdecode(psrval):
195 output = [ "(%s mode)"%proc_modes[psrval&0x1f][1] ]
196 for x in xrange(5,32):
198 output.append(PSR_bits[x])
199 return " ".join(output)
201 fmt = [None, "B", "<H", None, "<L", None, None, None, "<Q"]
203 s = struct.pack(fmt[byts], val)
204 return [ord(b) for b in s ]
206 class GoodFETARM(GoodFET):
207 """A GoodFET variant for use with ARM7TDMI microprocessor."""
209 GoodFET.__init__(self)
210 self.storedPC = 0xffffffff
211 self.current_dbgstate = 0xffffffff
212 self.flags = 0xffffffff
213 self.nothing = 0xffffffff
216 if (self.ARMget_dbgstate()&9) == 9:
219 sys.excepthook(*sys.exc_info())
221 """Move the FET into the JTAG ARM application."""
222 #print "Initializing ARM."
223 self.writecmd(0x13,SETUP,0,self.data)
225 return self.ARMgetPC()
226 def flash(self,file):
227 """Flash an intel hex file to code memory."""
228 print "Flash not implemented.";
229 def dump(self,file,start=0,stop=0xffff):
230 """Dump an intel hex file from code memory."""
231 print "Dump not implemented.";
232 def ARMshift_IR(self, IR, noretidle=0):
233 self.writecmd(0x13,IR_SHIFT,2, [IR, LSB|noretidle])
235 def ARMshift_DR(self, data, bits, flags):
236 self.writecmd(0x13,DR_SHIFT,8,[bits&0xff, flags&0xff, 0, 0, data&0xff,(data>>8)&0xff,(data>>16)&0xff,(data>>24)&0xff])
238 def ARMwaitDBG(self, timeout=0xff):
239 self.current_dbgstate = self.ARMget_dbgstate()
240 while ( not ((self.current_dbgstate & 9L) == 9)):
242 self.current_dbgstate = self.ARMget_dbgstate()
245 """Get an ARM's ID."""
246 self.ARMshift_IR(IR_IDCODE,0)
247 self.ARMshift_DR(0,32,LSB)
248 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
250 def ARMidentstr(self):
251 ident=self.ARMident()
253 partno = (ident >> 12) & 0x10
254 mfgid = ident & 0xfff
255 return "mfg: %x\npartno: %x\nver: %x\n(%x)" % (ver, partno, mfgid, ident);
256 def ARMeice_write(self, reg, val):
259 retval = self.writecmd(0x13, EICE_WRITE, 5, data)
261 def ARMeice_read(self, reg):
262 self.writecmd(0x13, EICE_READ, 1, [reg])
263 retval, = struct.unpack("<L",self.data)
265 def ARMget_dbgstate(self):
266 """Read the config register of an ARM."""
267 self.ARMeice_read(EICE_DBGSTATUS)
268 self.current_dbgstate = struct.unpack("<L", self.data[:4])[0]
269 return self.current_dbgstate
270 status = ARMget_dbgstate
272 """Check the status as a string."""
278 str="%s %s" %(self.ARMstatusbits[i],str)
281 def ARMget_dbgctrl(self):
282 """Read the config register of an ARM."""
283 self.ARMeice_read(EICE_DBGCTRL)
284 retval = struct.unpack("<L", self.data[:4])[0]
286 def ARMset_dbgctrl(self,config):
287 """Write the config register of an ARM."""
288 self.ARMeice_write(EICE_DBGCTRL, config&7)
290 """Get an ARM's PC. Note: real PC gets all wonky in debug mode, this is the "saved" PC"""
292 def ARMsetPC(self, val):
293 """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"""
295 def ARMget_register(self, reg):
296 """Get an ARM's Register"""
297 self.writecmd(0x13,GET_REGISTER,1,[reg&0xf])
298 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
300 def ARMset_register(self, reg, val):
301 """Get an ARM's Register"""
302 self.writecmd(0x13,SET_REGISTER,8,[val&0xff, (val>>8)&0xff, (val>>16)&0xff, val>>24, reg,0,0,0])
303 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
305 def ARMget_registers(self):
306 """Get ARM Registers"""
307 # FIXME: should we clobber r15 first? if results get wonky, we will.
308 self.ARMdebuginstr(ARM_INSTR_SKANKREGS,0)
311 regs = [ struct.unpack("<L", self.ARM_nop(0))[0] for x in range(15) ]
312 regs.append(self.ARMgetPC()) # make sure we snag the "static" version of PC
314 def ARMset_registers(self, regs, mask):
315 """Set ARM Registers"""
318 self.ARMset_register(x,regs.pop())
319 if (1<<15) & mask: # make sure we set the "static" version of PC or changes will be lost
320 self.ARMsetPC(regs.pop())
321 def ARMdebuginstr(self,instr,bkpt):
322 if type (instr) == int or type(instr) == long:
323 instr = struct.pack("<L", instr)
324 instr = [int("0x%x"%ord(x),16) for x in instr]
326 self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
328 def ARM_nop(self, bkpt):
329 if self.status() & DBG_TBIT:
330 return self.ARMdebuginstr(THUMB_INSTR_NOP, bkpt)
331 return self.ARMdebuginstr(ARM_INSTR_NOP, bkpt)
332 def ARMrestart(self):
333 self.ARMshift_IR(IR_RESTART)
334 def ARMset_watchpoint0(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
335 self.ARMeice_write(EICE_WP0ADDR, addr); # write 0 in watchpoint 0 address
336 self.ARMeice_write(EICE_WP0ADDRMASK, addrmask); # write 0xffffffff in watchpoint 0 address mask
337 self.ARMeice_write(EICE_WP0DATA, data); # write 0 in watchpoint 0 data
338 self.ARMeice_write(EICE_WP0DATAMASK, datamask); # write 0xffffffff in watchpoint 0 data mask
339 self.ARMeice_write(EICE_WP0CTRL, ctrl); # write 0x00000100 in watchpoint 0 control value register (enables watchpoint)
340 self.ARMeice_write(EICE_WP0CTRLMASK, ctrlmask); # write 0xfffffff7 in watchpoint 0 control mask - only detect the fetch instruction
342 def ARMset_watchpoint1(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
343 self.ARMeice_write(EICE_WP1ADDR, addr); # write 0 in watchpoint 1 address
344 self.ARMeice_write(EICE_WP1ADDRMASK, addrmask); # write 0xffffffff in watchpoint 1 address mask
345 self.ARMeice_write(EICE_WP1DATA, data); # write 0 in watchpoint 1 data
346 self.ARMeice_write(EICE_WP1DATAMASK, datamask); # write 0xffffffff in watchpoint 1 data mask
347 self.ARMeice_write(EICE_WP1CTRL, ctrl); # write 0x00000100 in watchpoint 1 control value register (enables watchpoint)
348 self.ARMeice_write(EICE_WP1CTRLMASK, ctrlmask); # write 0xfffffff7 in watchpoint 1 control mask - only detect the fetch instruction
350 def THUMBgetPC(self):
351 THUMB_INSTR_STR_R0_r0 = 0x60006000L
352 THUMB_INSTR_MOV_R0_PC = 0x46b846b8L
353 THUMB_INSTR_BX_PC = 0x47784778L
354 THUMB_INSTR_NOP = 0x1c001c00L
356 r0 = self.ARMget_register(0)
357 self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC, 0)
358 retval = self.ARMget_register(0)
359 self.ARMset_register(0,r0)
361 def ARMcapture_system_state(self, pcoffset):
362 if self.ARMget_dbgstate() & DBG_TBIT:
366 self.storedPC = self.ARMget_register(15) + pcoffset
367 self.last_dbg_state = self.ARMget_dbgstate()
368 def ARMhaltcpu(self):
370 if not(self.ARMget_dbgstate()&1):
371 self.ARMset_dbgctrl(2)
372 if (self.ARMwaitDBG() == 0):
373 raise Exception("Timeout waiting to enter DEBUG mode on HALT")
374 self.ARMset_dbgctrl(0)
375 self.ARMcapture_system_state(PCOFF_DBGRQ)
376 if self.last_dbg_state&0x10:
377 self.storedPC = self.THUMBgetPC()
379 self.storedPC = self.ARMget_register(15)
380 self.storedPC, self.flags, self.nothing = self.ARMchain0(0)
381 if self.ARMget_dbgstate() & DBG_TBIT:
383 if self.storedPC ^ 4:
384 self.ARMset_register(15,self.storedPC&0xfffffffc)
385 print "CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
387 def ARMreleasecpu(self):
388 """Resume the CPU."""
389 # restore registers FIXME: DO THIS
390 if self.ARMget_dbgstate()&1 == 0:
392 currentPC, self.currentflags, nothing = self.ARMchain0(self.storedPC,self.flags)
393 if not(self.flags & F_TBIT): # need to be in arm mode
394 if self.currentflags & F_TBIT: # currently in thumb mode
396 # branch to the right address
397 self.ARMset_register(15, self.storedPC)
398 print hex(self.storedPC)
399 print hex(self.ARMget_register(15))
400 print hex(self.ARMchain0(self.storedPC,self.flags)[0])
403 self.ARMdebuginstr(ARM_INSTR_B_IMM | 0xfffff0,0)
407 elif self.flags & F_TBIT: # need to be in thumb mode
408 if not (self.currentflags & F_TBIT): # currently in arm mode
409 self.ARMsetModeThumb()
410 r0=self.ARMget_register(0)
411 self.ARMset_register(0, self.storedPC)
412 self.ARMdebuginstr(THUMB_INSTR_MOV_PC_R0,0)
415 print hex(self.storedPC)
416 print hex(self.ARMget_register(15))
417 print hex(self.ARMchain0(self.storedPC,self.flags)[0])
418 self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc),0)
423 resume = ARMreleasecpu
425 self.writecmd(0x13, RESETTAP, 0,[])
426 def ARMsetModeARM(self):
428 if ((self.current_dbgstate & DBG_TBIT)):
429 debugstr("=== Switching to ARM mode ===")
431 self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
435 self.current_dbgstate = self.ARMget_dbgstate();
436 return self.current_dbgstate
437 def ARMsetModeThumb(self): # needs serious work and truing
439 debugstr("=== Switching to THUMB mode ===")
440 if ( not (self.current_dbgstate & DBG_TBIT)):
442 r0 = self.ARMget_register(0)
443 self.ARMset_register(0, self.storedPC)
445 self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
449 self.ARMset_register(0,r0)
450 self.current_dbgstate = self.ARMget_dbgstate();
451 return self.current_dbgstate
452 def ARMget_regCPSRstr(self):
453 psr = self.ARMget_regCPSR()
454 return hex(psr), PSRdecode(psr)
455 def ARMget_regCPSR(self):
456 """Get an ARM's Register"""
457 r0 = self.ARMget_register(0)
458 self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
459 self.ARMdebuginstr(ARM_INSTR_MRS_R0_CPSR, 0) # push MRS_R0, CPSR into pipeline - fetch
460 self.ARM_nop( 0) # push nop into pipeline - decoded
461 self.ARM_nop( 0) # push nop into pipeline - execute
462 retval = self.ARMget_register(0)
463 self.ARMset_register(0, r0)
465 def ARMset_regCPSR(self, val):
466 """Get an ARM's Register"""
467 r0 = self.ARMget_register(0)
468 self.ARMset_register(0, val)
469 self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
470 self.ARMdebuginstr(ARM_INSTR_MSR_cpsr_cxsf_R0, 0) # push MSR cpsr_cxsf, R0 into pipeline - fetch
471 self.ARM_nop( 0) # push nop into pipeline - decoded
472 self.ARM_nop( 0) # push nop into pipeline - execute
473 self.ARMset_register(0, r0)
475 def ARMreadMem(self, adr, wrdcount=1):
477 r0 = self.ARMget_register(0); # store R0 and R1
478 r1 = self.ARMget_register(1);
479 #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
480 self.ARMset_register(0, adr); # write address into R0
481 self.ARMset_register(1, 0xdeadbeef)
482 for word in range(adr, adr+(wrdcount*4), 4):
483 #sys.stdin.readline()
486 self.ARMdebuginstr(ARM_READ_MEM, 0); # push LDR R1, [R0], #4 into instruction pipeline (autoincrements for consecutive reads)
490 print hex(self.ARMget_register(1))
492 # FIXME: this may end up changing te current debug-state. should we compare to current_dbgstate?
493 #print repr(self.data[4])
494 if (len(self.data)>4 and self.data[4] == '\x00'):
495 print >>sys.stderr,("FAILED TO READ MEMORY/RE-ENTER DEBUG MODE")
496 raise Exception("FAILED TO READ MEMORY/RE-ENTER DEBUG MODE")
499 retval.append( self.ARMget_register(1) ) # read memory value from R1 register
500 #print >>sys.stderr,("CPSR: %x\t\tR0: %x\t\tR1: %x"%(self.ARMget_regCPSR(),self.ARMget_register(0),self.ARMget_register(1)))
501 self.ARMset_register(1, r1); # restore R0 and R1
502 self.ARMset_register(0, r0);
505 def ARMwriteMem(self, adr, wordarray):
506 r0 = self.ARMget_register(0); # store R0 and R1
507 r1 = self.ARMget_register(1);
508 #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
509 for widx in xrange(len(wordarray)):
510 address = adr + (widx*4)
511 word = wordarray[widx]
512 self.ARMset_register(0, address); # write address into R0
513 self.ARMset_register(1, word); # write address into R0
516 self.ARMdebuginstr(ARM_WRITE_MEM, 0); # push STR R1, [R0], #4 into instruction pipeline (autoincrements for consecutive writes)
520 print hex(self.ARMget_register(1))
521 self.ARMset_register(1, r1); # restore R0 and R1
522 self.ARMset_register(0, r0);
527 0x04 : "Interrupts Enabled (or not?)",
532 0x04 : "disable interrupts",
533 0x02 : "force dbgrq",
534 0x01 : "force dbgack"
537 def ARMchain0(self, address, bits=0x819684c054, data=0):
538 bulk = chop(address,4)
539 bulk.extend(chop(bits,8))
540 bulk.extend(chop(data,4))
542 self.writecmd(0x13,CHAIN0,16,bulk)
543 d1,b1,a1 = struct.unpack("<LQL",self.data)
546 """Start debugging."""
547 self.writecmd(0x13,START,0,self.data)
548 ident=self.ARMidentstr()
549 print "Target identifies as %s." % ident
550 print "Debug Status: %s." % self.statusstr()
551 #print "System State: %x." % self.ARMget_regCPSRstr()
553 """Stop debugging."""
554 self.writecmd(0x13,STOP,0,self.data)
555 #def ARMstep_instr(self):
556 # """Step one instruction."""
557 # self.writecmd(0x13,STEP_INSTR,0,self.data)
558 #def ARMflashpage(self,adr):
559 # """Flash 2kB a page of flash from 0xF000 in XDATA"""
564 # print "Flashing buffer to 0x%06x" % adr
565 # self.writecmd(0x13,MASS_FLASH_PAGE,4,data)