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_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
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
187 LDM_BITMASKS = [(1<<x)-1 for x in xrange(16)]
188 #### TOTALLY BROKEN, NEED VALIDATION AND TESTING
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):
200 output.append(PSR_bits[x])
201 return " ".join(output)
203 fmt = [None, "B", "<H", None, "<L", None, None, None, "<Q"]
205 s = struct.pack(fmt[byts], val)
206 return [ord(b) for b in s ]
208 class GoodFETARM(GoodFET):
209 """A GoodFET variant for use with ARM7TDMI microprocessor."""
211 GoodFET.__init__(self)
212 self.storedPC = 0xffffffff
213 self.current_dbgstate = 0xffffffff
214 self.flags = 0xffffffff
215 self.nothing = 0xffffffff
218 if (self.ARMget_dbgstate()&9) == 9:
221 sys.excepthook(*sys.exc_info())
223 """Move the FET into the JTAG ARM application."""
224 #print "Initializing ARM."
225 self.writecmd(0x13,SETUP,0,self.data)
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])
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])
240 def ARMwaitDBG(self, timeout=0xff):
241 self.current_dbgstate = self.ARMget_dbgstate()
242 while ( not ((self.current_dbgstate & 9L) == 9)):
244 self.current_dbgstate = self.ARMget_dbgstate()
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]
252 def ARMidentstr(self):
253 ident=self.ARMident()
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):
261 retval = self.writecmd(0x13, EICE_WRITE, 5, data)
263 def ARMeice_read(self, reg):
264 self.writecmd(0x13, EICE_READ, 1, [reg])
265 retval, = struct.unpack("<L",self.data)
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
274 """Check the status as a string."""
280 str="%s %s" %(self.ARMstatusbits[i],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]
288 def ARMset_dbgctrl(self,config):
289 """Write the config register of an ARM."""
290 self.ARMeice_write(EICE_DBGCTRL, config&7)
292 """Get an ARM's PC. Note: real PC gets all wonky in debug mode, this is the "saved" PC"""
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"""
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]
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]
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
312 def ARMset_registers(self, regs, mask):
313 """Set ARM Registers"""
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]
324 self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
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
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
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
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)
359 def ARMcapture_system_state(self, pcoffset):
360 if self.ARMget_dbgstate() & DBG_TBIT:
364 self.storedPC = self.ARMget_register(15) + pcoffset
365 self.last_dbg_state = self.ARMget_dbgstate()
366 def ARMhaltcpu(self):
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()
377 self.storedPC = self.ARMget_register(15)
378 self.storedPC, self.flags, self.nothing = self.ARMchain0(0)
379 if self.ARMget_dbgstate() & DBG_TBIT:
381 if self.storedPC ^ 4:
382 self.ARMset_register(15,self.storedPC&0xfffffffc)
383 print "CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
385 def ARMreleasecpu(self):
386 """Resume the CPU."""
387 # restore registers FIXME: DO THIS
388 if self.ARMget_dbgstate()&1 == 0:
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
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])
401 self.ARMdebuginstr(ARM_INSTR_B_IMM | 0xfffff0,0)
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)
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)
421 resume = ARMreleasecpu
423 self.writecmd(0x13, RESETTAP, 0,[])
424 def ARMsetModeARM(self):
426 if ((self.current_dbgstate & DBG_TBIT)):
427 debugstr("=== Switching to ARM mode ===")
429 self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
433 self.current_dbgstate = self.ARMget_dbgstate();
434 return self.current_dbgstate
435 def ARMsetModeThumb(self): # needs serious work and truing
437 debugstr("=== Switching to THUMB mode ===")
438 if ( not (self.current_dbgstate & DBG_TBIT)):
440 r0 = self.ARMget_register(0)
441 self.ARMset_register(0, self.storedPC)
443 self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
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)
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)
473 def ARMreadMem(self, adr, wrdcount=1):
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()
484 self.ARMdebuginstr(ARM_READ_MEM, 0); # push LDR R1, [R0], #4 into instruction pipeline (autoincrements for consecutive reads)
488 print hex(self.ARMget_register(1))
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")
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);
502 def ARMreadChunk(self, adr, wordcount):
503 """ Only works in ARM mode currently
504 WARNING: Addresses must be word-aligned!
506 regs = self.ARMget_registers()
509 while (wordcount > 0):
510 count = (wordcount, 0xe)[wordcount>0xd]
511 bitmask = LDM_BITMASKS[count]
512 self.ARMset_register(14,adr)
514 self.ARMdebuginstr(ARM_INSTR_LDMIA_R14_r0_rx | bitmask ,0)
515 #FIXME: do we need the extra nop here?
518 output.extend([self.ARMget_register(x) for x in xrange(count)])
522 # FIXME: handle the rest of the wordcount here.
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
535 self.ARMdebuginstr(ARM_WRITE_MEM, 0); # push STR R1, [R0], #4 into instruction pipeline (autoincrements for consecutive writes)
539 print hex(self.ARMget_register(1))
540 self.ARMset_register(1, r1); # restore R0 and R1
541 self.ARMset_register(0, r0);
546 0x04 : "Interrupts Enabled (or not?)",
551 0x04 : "disable interrupts",
552 0x02 : "force dbgrq",
553 0x01 : "force dbgack"
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))
561 self.writecmd(0x13,CHAIN0,16,bulk)
562 d1,b1,a1 = struct.unpack("<LQL",self.data)
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()
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"""
583 # print "Flashing buffer to 0x%06x" % adr
584 # self.writecmd(0x13,MASS_FLASH_PAGE,4,data)