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
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
188 print >>sys.stderr,(strng)
189 def PSRdecode(psrval):
190 output = [ "(%s mode)"%proc_modes[psrval&0x1f][1] ]
191 for x in xrange(5,32):
193 output.append(PSR_bits[x])
194 return " ".join(output)
196 fmt = [None, "B", "<H", None, "<L", None, None, None, "<Q"]
198 s = struct.pack(fmt[byts], val)
199 return [ord(b) for b in s ]
201 class GoodFETARM(GoodFET):
202 """A GoodFET variant for use with ARM7TDMI microprocessor."""
204 GoodFET.__init__(self)
205 self.storedPC = 0xffffffff
206 self.current_dbgstate = 0xffffffff
207 self.flags = 0xffffffff
208 self.nothing = 0xffffffff
211 if (self.ARMget_dbgstate()&9) == 9:
214 sys.excepthook(*sys.exc_info())
216 """Move the FET into the JTAG ARM application."""
217 #print "Initializing ARM."
218 self.writecmd(0x13,SETUP,0,self.data)
220 return self.ARMgetPC()
221 def flash(self,file):
222 """Flash an intel hex file to code memory."""
223 print "Flash not implemented.";
224 def dump(self,file,start=0,stop=0xffff):
225 """Dump an intel hex file from code memory."""
226 print "Dump not implemented.";
227 def ARMshift_IR(self, IR, noretidle=0):
228 self.writecmd(0x13,IR_SHIFT,2, [IR, LSB|noretidle])
230 def ARMshift_DR(self, data, bits, flags):
231 self.writecmd(0x13,DR_SHIFT,8,[bits&0xff, flags&0xff, 0, 0, data&0xff,(data>>8)&0xff,(data>>16)&0xff,(data>>24)&0xff])
233 def ARMwaitDBG(self, timeout=0xff):
234 self.current_dbgstate = self.ARMget_dbgstate()
235 while ( not ((self.current_dbgstate & 9L) == 9)):
237 self.current_dbgstate = self.ARMget_dbgstate()
240 """Get an ARM's ID."""
241 self.ARMshift_IR(IR_IDCODE,0)
242 self.ARMshift_DR(0,32,LSB)
243 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
245 def ARMidentstr(self):
246 ident=self.ARMident()
248 partno = (ident >> 12) & 0x10
249 mfgid = ident & 0xfff
250 return "mfg: %x\npartno: %x\nver: %x\n(%x)" % (ver, partno, mfgid, ident);
251 def ARMeice_write(self, reg, val):
254 retval = self.writecmd(0x13, EICE_WRITE, 5, data)
256 def ARMeice_read(self, reg):
257 self.writecmd(0x13, EICE_READ, 1, [reg])
258 retval, = struct.unpack("<L",self.data)
260 def ARMget_dbgstate(self):
261 """Read the config register of an ARM."""
262 self.ARMeice_read(EICE_DBGSTATUS)
263 self.current_dbgstate = struct.unpack("<L", self.data[:4])[0]
264 return self.current_dbgstate
265 status = ARMget_dbgstate
267 """Check the status as a string."""
273 str="%s %s" %(self.ARMstatusbits[i],str)
276 def ARMget_dbgctrl(self):
277 """Read the config register of an ARM."""
278 self.ARMeice_read(EICE_DBGCTRL)
279 retval = struct.unpack("<L", self.data[:4])[0]
281 def ARMset_dbgctrl(self,config):
282 """Write the config register of an ARM."""
283 self.ARMeice_write(EICE_DBGCTRL, config&7)
285 """Get an ARM's PC. Note: real PC gets all wonky in debug mode, this is the "saved" PC"""
287 def ARMsetPC(self, val):
288 """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"""
290 def ARMget_register(self, reg):
291 """Get an ARM's Register"""
292 self.writecmd(0x13,GET_REGISTER,1,[reg&0xff])
293 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
295 def ARMset_register(self, reg, val):
296 """Get an ARM's Register"""
297 self.writecmd(0x13,SET_REGISTER,8,[val&0xff, (val>>8)&0xff, (val>>16)&0xff, val>>24, reg,0,0,0])
298 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
300 def ARMget_registers(self):
301 """Get ARM Registers"""
302 regs = [ self.ARMget_register(x) for x in range(15) ]
303 regs.append(self.ARMgetPC()) # make sure we snag the "static" version of PC
305 def ARMset_registers(self, regs, mask):
306 """Set ARM Registers"""
309 self.ARMset_register(x,regs.pop())
310 if (1<<15) & mask: # make sure we set the "static" version of PC or changes will be lost
311 self.ARMsetPC(regs.pop())
312 def ARMdebuginstr(self,instr,bkpt):
313 if type (instr) == int or type(instr) == long:
314 instr = struct.pack("<L", instr)
315 instr = [int("0x%x"%ord(x),16) for x in instr]
317 self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
319 def ARM_nop(self, bkpt):
320 if self.status() & DBG_TBIT:
321 return self.ARMdebuginstr(THUMB_INSTR_NOP, bkpt)
322 return self.ARMdebuginstr(ARM_INSTR_NOP, bkpt)
323 def ARMrestart(self):
324 self.ARMshift_IR(IR_RESTART)
325 def ARMset_watchpoint0(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
326 self.ARMeice_write(EICE_WP0ADDR, addr); # write 0 in watchpoint 0 address
327 self.ARMeice_write(EICE_WP0ADDRMASK, addrmask); # write 0xffffffff in watchpoint 0 address mask
328 self.ARMeice_write(EICE_WP0DATA, data); # write 0 in watchpoint 0 data
329 self.ARMeice_write(EICE_WP0DATAMASK, datamask); # write 0xffffffff in watchpoint 0 data mask
330 self.ARMeice_write(EICE_WP0CTRL, ctrl); # write 0x00000100 in watchpoint 0 control value register (enables watchpoint)
331 self.ARMeice_write(EICE_WP0CTRLMASK, ctrlmask); # write 0xfffffff7 in watchpoint 0 control mask - only detect the fetch instruction
333 def ARMset_watchpoint1(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
334 self.ARMeice_write(EICE_WP1ADDR, addr); # write 0 in watchpoint 1 address
335 self.ARMeice_write(EICE_WP1ADDRMASK, addrmask); # write 0xffffffff in watchpoint 1 address mask
336 self.ARMeice_write(EICE_WP1DATA, data); # write 0 in watchpoint 1 data
337 self.ARMeice_write(EICE_WP1DATAMASK, datamask); # write 0xffffffff in watchpoint 1 data mask
338 self.ARMeice_write(EICE_WP1CTRL, ctrl); # write 0x00000100 in watchpoint 1 control value register (enables watchpoint)
339 self.ARMeice_write(EICE_WP1CTRLMASK, ctrlmask); # write 0xfffffff7 in watchpoint 1 control mask - only detect the fetch instruction
341 def THUMBgetPC(self):
342 r0 = self.ARMget_register(0)
343 self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC, 0)
344 retval = self.ARMget_register(0)
345 self.ARMset_register(0,r0)
347 def ARMhaltcpu(self):
349 if not(self.ARMget_dbgstate()&1):
350 self.ARMset_dbgctrl(2)
351 if (self.ARMwaitDBG() == 0):
352 raise Exception("Timeout waiting to enter DEBUG mode on HALT")
353 self.ARMset_dbgctrl(0)
354 self.last_dbg_state = self.ARMget_dbgstate()
355 if self.last_dbg_state&0x10:
356 self.storedPC = self.THUMBgetPC()
358 self.storedPC = self.ARMget_register(15)
359 self.storedPC, self.flags, self.nothing = self.ARMchain0(0)
360 if self.ARMget_dbgstate() & DBG_TBIT:
362 if self.storedPC ^ 4:
363 self.ARMset_register(15,self.storedPC&0xfffffffc)
364 print "CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
366 def ARMreleasecpu(self):
367 """Resume the CPU."""
368 # restore registers FIXME: DO THIS
369 if self.ARMget_dbgstate()&1 == 0:
371 currentPC, self.currentflags, nothing = self.ARMchain0(self.storedPC,self.flags)
372 if not(self.flags & F_TBIT): # need to be in arm mode
373 if self.currentflags & F_TBIT: # currently in thumb mode
375 # branch to the right address
376 self.ARMset_register(15, self.storedPC)
377 print hex(self.storedPC)
378 print hex(self.ARMget_register(15))
379 print hex(self.ARMchain0(self.storedPC,self.flags)[0])
382 self.ARMdebuginstr(ARM_INSTR_B_IMM | 0xfffff0,0)
386 elif self.flags & F_TBIT: # need to be in thumb mode
387 if not (self.currentflags & F_TBIT): # currently in arm mode
388 self.ARMsetModeThumb()
389 r0=self.ARMget_register(0)
390 self.ARMset_register(0, self.storedPC)
391 self.ARMdebuginstr(THUMB_INSTR_MOV_PC_R0,0)
394 print hex(self.storedPC)
395 print hex(self.ARMget_register(15))
396 print hex(self.ARMchain0(self.storedPC,self.flags)[0])
397 self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc))
402 resume = ARMreleasecpu
404 self.writecmd(0x13, RESETTAP, 0,[])
405 def ARMsetModeARM(self):
407 if ((self.current_dbgstate & DBG_TBIT)):
408 debugstr("=== Switching to ARM mode ===")
409 #r0 = self.ARMget_register(0)
411 #self.ARMdebuginstr(THUMB_INSTR_NOP,0)
412 #self.ARMdebuginstr(THUMB_INSTR_STR_R0_r0,0)
413 #self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC,0)
414 #self.ARMdebuginstr(THUMB_INSTR_STR_R0_r0,0)
415 self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
419 self.current_dbgstate = self.ARMget_dbgstate();
420 return self.current_dbgstate
421 def ARMsetModeThumb(self): # needs serious work and truing
423 debugstr("=== Switching to THUMB mode ===")
424 if ( not (self.current_dbgstate & DBG_TBIT)):
426 self.ARMset_register(0, self.storedPC)
428 self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
432 self.current_dbgstate = self.ARMget_dbgstate();
433 return self.current_dbgstate
434 def ARMget_regCPSRstr(self):
435 psr = self.ARMget_regCPSR()
436 return hex(psr), PSRdecode(psr)
437 def ARMget_regCPSR(self):
438 """Get an ARM's Register"""
439 r0 = self.ARMget_register(0)
440 self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
441 self.ARMdebuginstr(ARM_INSTR_MRS_R0_CPSR, 0) # push MRS_R0, CPSR into pipeline - fetch
442 self.ARM_nop( 0) # push nop into pipeline - decoded
443 self.ARM_nop( 0) # push nop into pipeline - execute
444 retval = self.ARMget_register(0)
445 self.ARMset_register(0, r0)
447 def ARMset_regCPSR(self, val):
448 """Get an ARM's Register"""
449 r0 = self.ARMget_register(0)
450 self.ARMset_register(0, val)
451 self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
452 self.ARMdebuginstr(ARM_INSTR_MSR_cpsr_cxsf_R0, 0) # push MSR cpsr_cxsf, R0 into pipeline - fetch
453 self.ARM_nop( 0) # push nop into pipeline - decoded
454 self.ARM_nop( 0) # push nop into pipeline - execute
455 self.ARMset_register(0, r0)
457 def ARMreadMem(self, adr, wrdcount=1):
459 r0 = self.ARMget_register(0); # store R0 and R1
460 r1 = self.ARMget_register(1);
461 #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
462 self.ARMset_register(0, adr); # write address into R0
463 self.ARMset_register(1, 0xdeadbeef)
464 for word in range(adr, adr+(wrdcount*4), 4):
465 #sys.stdin.readline()
468 self.ARMdebuginstr(ARM_READ_MEM, 0); # push LDR R1, [R0], #4 into instruction pipeline (autoincrements for consecutive reads)
472 print hex(self.ARMget_register(1))
474 # FIXME: this may end up changing te current debug-state. should we compare to current_dbgstate?
475 #print repr(self.data[4])
476 if (len(self.data)>4 and self.data[4] == '\x00'):
477 print >>sys.stderr,("FAILED TO READ MEMORY/RE-ENTER DEBUG MODE")
478 raise Exception("FAILED TO READ MEMORY/RE-ENTER DEBUG MODE")
481 retval.append( self.ARMget_register(1) ) # read memory value from R1 register
482 #print >>sys.stderr,("CPSR: %x\t\tR0: %x\t\tR1: %x"%(self.ARMget_regCPSR(),self.ARMget_register(0),self.ARMget_register(1)))
483 self.ARMset_register(1, r1); # restore R0 and R1
484 self.ARMset_register(0, r0);
487 def ARMwriteMem(self, adr, wordarray):
488 r0 = self.ARMget_register(0); # store R0 and R1
489 r1 = self.ARMget_register(1);
490 #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
491 for widx in xrange(len(wordarray)):
492 address = adr + (widx*4)
493 word = wordarray[widx]
494 self.ARMset_register(0, address); # write address into R0
495 self.ARMset_register(1, word); # write address into R0
498 self.ARMdebuginstr(ARM_WRITE_MEM, 0); # push STR R1, [R0], #4 into instruction pipeline (autoincrements for consecutive writes)
502 print hex(self.ARMget_register(1))
503 self.ARMset_register(1, r1); # restore R0 and R1
504 self.ARMset_register(0, r0);
509 0x04 : "Interrupts Enabled (or not?)",
514 0x04 : "disable interrupts",
515 0x02 : "force dbgrq",
516 0x01 : "force dbgack"
519 def ARMchain0(self, address, bits=0x819684c054, data=0):
520 bulk = chop(address,4)
521 bulk.extend(chop(bits,8))
522 bulk.extend(chop(data,4))
524 self.writecmd(0x13,CHAIN0,16,bulk)
525 d1,b1,a1 = struct.unpack("<LQL",self.data)
528 """Start debugging."""
529 self.writecmd(0x13,START,0,self.data)
530 ident=self.ARMidentstr()
531 print "Target identifies as %s." % ident
532 print "Debug Status: %s." % self.statusstr()
533 #print "System State: %x." % self.ARMget_regCPSRstr()
535 """Stop debugging."""
536 self.writecmd(0x13,STOP,0,self.data)
537 #def ARMstep_instr(self):
538 # """Step one instruction."""
539 # self.writecmd(0x13,STEP_INSTR,0,self.data)
540 #def ARMflashpage(self,adr):
541 # """Flash 2kB a page of flash from 0xF000 in XDATA"""
546 # print "Flashing buffer to 0x%06x" % adr
547 # self.writecmd(0x13,MASS_FLASH_PAGE,4,data)