2 # GoodFET ARM Client Library
4 # Contributions and bug reports welcome.
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)
12 import sys, binascii, struct, time
13 import atlasutils.smartprint as asp
14 from GoodFET import GoodFET
15 from intelhex import IntelHex
31 # ARM7TDMI JTAG commands
39 # Really ARM specific stuff
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
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)"),
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",
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_MRS_R0_CPSR = 0xe10f0000L
127 ARM_INSTR_MSR_cpsr_cxsf_R0 =0xe12ff000L
128 ARM_INSTR_STMIA_R14_r0_rx = 0xE88e0000L # add up to 65k to indicate which registers...
129 ARM_INSTR_LDMIA_R14_r0_rx = 0xE89e0000L # add up to 65k to indicate which registers...
130 ARM_STORE_MULTIPLE = ARM_INSTR_STMIA_R14_r0_rx
131 ARM_INSTR_SKANKREGS = 0xE88F7fffL
132 ARM_INSTR_CLOBBEREGS = 0xE89F7fffL
134 ARM_INSTR_B_IMM = 0xea000000L
135 ARM_INSTR_B_PC = 0xea000000L
136 ARM_INSTR_BX_PC = 0xe1200010L # need to set r0 to the desired address
137 THUMB_INSTR_LDR_R0_r0 = 0x68006800L
138 THUMB_WRITE_REG = THUMB_INSTR_LDR_R0_r0
139 THUMB_INSTR_STR_R0_r0 = 0x60006000L
140 THUMB_READ_REG = THUMB_INSTR_STR_R0_r0
141 THUMB_INSTR_MOV_R0_PC = 0x46b846b8L
142 THUMB_INSTR_MOV_PC_R0 = 0x46474647L
143 THUMB_INSTR_BX_PC = 0x47784778L
144 THUMB_INSTR_NOP = 0x1c001c00L
145 THUMB_INSTR_B_IMM = 0xe000e000L
179 LDM_BITMASKS = [(1<<x)-1 for x in xrange(16)]
180 #### TOTALLY BROKEN, NEED VALIDATION AND TESTING
187 print >>sys.stderr,(strng)
188 def PSRdecode(psrval):
189 output = [ "(%s mode)"%proc_modes[psrval&0x1f][1] ]
190 for x in xrange(5,32):
192 output.append(PSR_bits[x])
193 return " ".join(output)
195 fmt = [None, "B", "<H", None, "<L", None, None, None, "<Q"]
197 s = struct.pack(fmt[byts], val)
198 return [ord(b) for b in s ]
200 class GoodFETARM(GoodFET):
201 """A GoodFET variant for use with ARM7TDMI microprocessor."""
203 GoodFET.__init__(self)
204 self.storedPC = 0xffffffff
205 self.current_dbgstate = 0xffffffff
206 self.flags = 0xffffffff
207 self.nothing = 0xffffffff
210 if (self.ARMget_dbgstate()&9) == 9:
213 sys.excepthook(*sys.exc_info())
215 """Move the FET into the JTAG ARM application."""
216 #print "Initializing ARM."
217 self.writecmd(0x13,SETUP,0,self.data)
219 return self.ARMgetPC()
220 def flash(self,file):
221 """Flash an intel hex file to code memory."""
222 print "Flash not implemented.";
223 def dump(self,file,start=0,stop=0xffff):
224 """Dump an intel hex file from code memory."""
225 print "Dump not implemented.";
226 def ARMshift_IR(self, IR, noretidle=0):
227 self.writecmd(0x13,IR_SHIFT,2, [IR, LSB|noretidle])
229 def ARMshift_DR(self, data, bits, flags):
230 self.writecmd(0x13,DR_SHIFT,8,[bits&0xff, flags&0xff, 0, 0, data&0xff,(data>>8)&0xff,(data>>16)&0xff,(data>>24)&0xff])
232 def ARMwaitDBG(self, timeout=0xff):
233 self.current_dbgstate = self.ARMget_dbgstate()
234 while ( not ((self.current_dbgstate & 9L) == 9)):
236 self.current_dbgstate = self.ARMget_dbgstate()
239 """Get an ARM's ID."""
240 self.ARMshift_IR(IR_IDCODE,0)
241 self.ARMshift_DR(0,32,LSB)
242 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
244 def ARMidentstr(self):
245 ident=self.ARMident()
247 partno = (ident >> 12) & 0xffff
248 mfgid = (ident >> 1) & 0x7ff
249 return "Chip IDCODE: 0x%x\n\tver: %x\n\tpartno: %x\n\tmfgid: %x\n" % (ident, ver, partno, mfgid);
250 def ARMeice_write(self, reg, val):
253 retval = self.writecmd(0x13, EICE_WRITE, 5, data)
255 def ARMeice_read(self, reg):
256 self.writecmd(0x13, EICE_READ, 1, [reg])
257 retval, = struct.unpack("<L",self.data)
259 def ARMget_dbgstate(self):
260 """Read the config register of an ARM."""
261 self.ARMeice_read(EICE_DBGSTATUS)
262 self.current_dbgstate = struct.unpack("<L", self.data[:4])[0]
263 return self.current_dbgstate
264 status = ARMget_dbgstate
266 """Check the status as a string."""
272 str="%s %s" %(self.ARMstatusbits[i],str)
275 def ARMget_dbgctrl(self):
276 """Read the config register of an ARM."""
277 self.ARMeice_read(EICE_DBGCTRL)
278 retval = struct.unpack("<L", self.data[:4])[0]
280 def ARMset_dbgctrl(self,config):
281 """Write the config register of an ARM."""
282 self.ARMeice_write(EICE_DBGCTRL, config&7)
284 """Get an ARM's PC. Note: real PC gets all wonky in debug mode, this is the "saved" PC"""
286 def ARMsetPC(self, val):
287 """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"""
289 def ARMget_register(self, reg):
290 """Get an ARM's Register"""
291 self.writecmd(0x13,GET_REGISTER,1,[reg&0xf])
292 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
294 def ARMset_register(self, reg, val):
295 """Get an ARM's Register"""
296 self.writecmd(0x13,SET_REGISTER,8,[val&0xff, (val>>8)&0xff, (val>>16)&0xff, val>>24, reg,0,0,0])
297 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
299 def ARMget_registers(self):
300 """Get ARM Registers"""
301 regs = [ self.ARMget_register(x) for x in range(15) ]
302 regs.append(self.ARMgetPC()) # make sure we snag the "static" version of PC
304 def ARMset_registers(self, regs, mask):
305 """Set ARM Registers"""
308 self.ARMset_register(x,regs.pop(0))
309 if (1<<15) & mask: # make sure we set the "static" version of PC or changes will be lost
310 self.ARMsetPC(regs.pop(0))
311 def ARMdebuginstr(self,instr,bkpt):
312 if type (instr) == int or type(instr) == long:
313 instr = struct.pack("<L", instr)
314 instr = [int("0x%x"%ord(x),16) for x in instr]
316 self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
318 def ARM_nop(self, bkpt=0):
319 if self.status() & DBG_TBIT:
320 return self.ARMdebuginstr(THUMB_INSTR_NOP, bkpt)
321 return self.ARMdebuginstr(ARM_INSTR_NOP, bkpt)
322 def ARMrestart(self):
323 self.ARMshift_IR(IR_RESTART)
324 def ARMset_watchpoint0(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
325 self.ARMeice_write(EICE_WP0ADDR, addr); # write 0 in watchpoint 0 address
326 self.ARMeice_write(EICE_WP0ADDRMASK, addrmask); # write 0xffffffff in watchpoint 0 address mask
327 self.ARMeice_write(EICE_WP0DATA, data); # write 0 in watchpoint 0 data
328 self.ARMeice_write(EICE_WP0DATAMASK, datamask); # write 0xffffffff in watchpoint 0 data mask
329 self.ARMeice_write(EICE_WP0CTRL, ctrl); # write 0x00000100 in watchpoint 0 control value register (enables watchpoint)
330 self.ARMeice_write(EICE_WP0CTRLMASK, ctrlmask); # write 0xfffffff7 in watchpoint 0 control mask - only detect the fetch instruction
332 def ARMset_watchpoint1(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
333 self.ARMeice_write(EICE_WP1ADDR, addr); # write 0 in watchpoint 1 address
334 self.ARMeice_write(EICE_WP1ADDRMASK, addrmask); # write 0xffffffff in watchpoint 1 address mask
335 self.ARMeice_write(EICE_WP1DATA, data); # write 0 in watchpoint 1 data
336 self.ARMeice_write(EICE_WP1DATAMASK, datamask); # write 0xffffffff in watchpoint 1 data mask
337 self.ARMeice_write(EICE_WP1CTRL, ctrl); # write 0x00000100 in watchpoint 1 control value register (enables watchpoint)
338 self.ARMeice_write(EICE_WP1CTRLMASK, ctrlmask); # write 0xfffffff7 in watchpoint 1 control mask - only detect the fetch instruction
340 def THUMBgetPC(self):
341 THUMB_INSTR_STR_R0_r0 = 0x60006000L
342 THUMB_INSTR_MOV_R0_PC = 0x46b846b8L
343 THUMB_INSTR_BX_PC = 0x47784778L
344 THUMB_INSTR_NOP = 0x1c001c00L
346 r0 = self.ARMget_register(0)
347 self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC, 0)
348 retval = self.ARMget_register(0)
349 self.ARMset_register(0,r0)
351 def ARMcapture_system_state(self, pcoffset):
352 if self.ARMget_dbgstate() & DBG_TBIT:
356 self.storedPC = self.ARMget_register(15) + pcoffset
357 self.last_dbg_state = self.ARMget_dbgstate()
358 def ARMhaltcpu(self):
360 if not(self.ARMget_dbgstate()&1):
361 self.ARMset_dbgctrl(2)
362 if (self.ARMwaitDBG() == 0):
363 raise Exception("Timeout waiting to enter DEBUG mode on HALT")
364 self.ARMset_dbgctrl(0)
365 self.ARMcapture_system_state(PCOFF_DBGRQ)
366 if self.last_dbg_state&0x10:
367 self.storedPC = self.THUMBgetPC()
369 self.storedPC = self.ARMget_register(15)
370 self.storedPC, self.flags, self.nothing = self.ARMchain0(0)
371 if self.ARMget_dbgstate() & DBG_TBIT:
373 if self.storedPC ^ 4:
374 self.ARMset_register(15,self.storedPC&0xfffffffc)
375 print "CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
377 def ARMreleasecpu(self):
378 """Resume the CPU."""
379 # restore registers FIXME: DO THIS
380 if self.ARMget_dbgstate()&1 == 0:
382 currentPC, self.currentflags, nothing = self.ARMchain0(self.storedPC,self.flags)
383 if not(self.flags & F_TBIT): # need to be in arm mode
384 if self.currentflags & F_TBIT: # currently in thumb mode
386 # branch to the right address
387 self.ARMset_register(15, self.storedPC)
388 print hex(self.storedPC)
389 print hex(self.ARMget_register(15))
390 print hex(self.ARMchain0(self.storedPC,self.flags)[0])
393 self.ARMdebuginstr(ARM_INSTR_B_IMM | 0xfffff0,0)
397 elif self.flags & F_TBIT: # need to be in thumb mode
398 if not (self.currentflags & F_TBIT): # currently in arm mode
399 self.ARMsetModeThumb()
400 r0=self.ARMget_register(0)
401 self.ARMset_register(0, self.storedPC)
402 self.ARMdebuginstr(THUMB_INSTR_MOV_PC_R0,0)
405 print hex(self.storedPC)
406 print hex(self.ARMget_register(15))
407 print hex(self.ARMchain0(self.storedPC,self.flags)[0])
408 self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc),0)
413 resume = ARMreleasecpu
415 self.writecmd(0x13, RESETTAP, 0,[])
416 def ARMsetModeARM(self):
418 if ((self.current_dbgstate & DBG_TBIT)):
419 debugstr("=== Switching to ARM mode ===")
421 self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
425 self.current_dbgstate = self.ARMget_dbgstate();
426 return self.current_dbgstate
427 def ARMsetModeThumb(self): # needs serious work and truing
429 debugstr("=== Switching to THUMB mode ===")
430 if ( not (self.current_dbgstate & DBG_TBIT)):
432 r0 = self.ARMget_register(0)
433 self.ARMset_register(0, self.storedPC)
435 self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
439 self.ARMset_register(0,r0)
440 self.current_dbgstate = self.ARMget_dbgstate();
441 return self.current_dbgstate
442 def ARMget_regCPSRstr(self):
443 psr = self.ARMget_regCPSR()
444 return hex(psr), PSRdecode(psr)
445 def ARMget_regCPSR(self):
446 """Get an ARM's Register"""
447 r0 = self.ARMget_register(0)
448 self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
449 self.ARMdebuginstr(ARM_INSTR_MRS_R0_CPSR, 0) # push MRS_R0, CPSR into pipeline - fetch
450 self.ARM_nop( 0) # push nop into pipeline - decoded
451 self.ARM_nop( 0) # push nop into pipeline - execute
452 retval = self.ARMget_register(0)
453 self.ARMset_register(0, r0)
455 def ARMset_regCPSR(self, val):
456 """Get an ARM's Register"""
457 r0 = self.ARMget_register(0)
458 self.ARMset_register(0, val)
459 self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
460 self.ARMdebuginstr(ARM_INSTR_MSR_cpsr_cxsf_R0, 0) # push MSR cpsr_cxsf, R0 into pipeline - fetch
461 self.ARM_nop( 0) # push nop into pipeline - decoded
462 self.ARM_nop( 0) # push nop into pipeline - execute
463 self.ARMset_register(0, r0)
465 def ARMreadMem(self, adr, wrdcount=1):
467 r0 = self.ARMget_register(0); # store R0 and R1
468 r1 = self.ARMget_register(1);
469 #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
470 self.ARMset_register(0, adr); # write address into R0
471 self.ARMset_register(1, 0xdeadbeef)
472 for word in range(adr, adr+(wrdcount*4), 4):
473 #sys.stdin.readline()
476 self.ARMdebuginstr(ARM_READ_MEM, 0); # push LDR R1, [R0], #4 into instruction pipeline (autoincrements for consecutive reads)
480 print hex(self.ARMget_register(1))
482 # FIXME: this may end up changing te current debug-state. should we compare to current_dbgstate?
483 #print repr(self.data[4])
484 if (len(self.data)>4 and self.data[4] == '\x00'):
485 print >>sys.stderr,("FAILED TO READ MEMORY/RE-ENTER DEBUG MODE")
486 raise Exception("FAILED TO READ MEMORY/RE-ENTER DEBUG MODE")
489 retval.append( self.ARMget_register(1) ) # read memory value from R1 register
490 #print >>sys.stderr,("CPSR: %x\t\tR0: %x\t\tR1: %x"%(self.ARMget_regCPSR(),self.ARMget_register(0),self.ARMget_register(1)))
491 self.ARMset_register(1, r1); # restore R0 and R1
492 self.ARMset_register(0, r0);
494 def ARMreadChunk(self, adr, wordcount):
495 """ Only works in ARM mode currently
496 WARNING: Addresses must be word-aligned!
498 regs = self.ARMget_registers()
499 self.ARMset_registers([0xdeadbeef for x in xrange(14)], 0xe)
502 while (wordcount > 0):
503 if (wordcount%64 == 0): sys.stderr.write(".")
504 count = (wordcount, 0xe)[wordcount>0xd]
505 bitmask = LDM_BITMASKS[count]
506 self.ARMset_register(14,adr)
508 self.ARMdebuginstr(ARM_INSTR_LDMIA_R14_r0_rx | bitmask ,0)
509 #FIXME: do we need the extra nop here?
512 output.extend([self.ARMget_register(x) for x in xrange(count)])
516 # FIXME: handle the rest of the wordcount here.
517 self.ARMset_registers(regs,0xe)
519 def ARMreadStream(self, adr, bytecount):
520 data = [struct.unpack("<L", x) for x in self.ARMreadChunk(adr, (bytecount-1/4)+1)]
521 return "".join(data)[:bytecount]
523 def ARMwriteChunk(self, adr, wordarray):
524 """ Only works in ARM mode currently
525 WARNING: Addresses must be word-aligned!
527 regs = self.ARMget_registers()
528 wordcount = len(wordarray)
529 while (wordcount > 0):
530 if (wordcount%64 == 0): sys.stderr.write(".")
531 count = (wordcount, 0xe)[wordcount>0xd]
532 bitmask = LDM_BITMASKS[count]
533 self.ARMset_register(14,adr)
534 #print len(wordarray),bin(bitmask)
535 self.ARMset_registers(wordarray[:count],bitmask)
537 self.ARMdebuginstr(ARM_INSTR_STMIA_R14_r0_rx | bitmask ,0)
538 #FIXME: do we need the extra nop here?
541 wordarray = wordarray[count:]
545 # FIXME: handle the rest of the wordcount here.
546 def ARMwriteMem(self, adr, wordarray):
547 r0 = self.ARMget_register(0); # store R0 and R1
548 r1 = self.ARMget_register(1);
549 #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
550 for widx in xrange(len(wordarray)):
551 address = adr + (widx*4)
552 word = wordarray[widx]
553 self.ARMset_register(0, address); # write address into R0
554 self.ARMset_register(1, word); # write address into R0
557 self.ARMdebuginstr(ARM_WRITE_MEM, 0); # push STR R1, [R0], #4 into instruction pipeline (autoincrements for consecutive writes)
561 print >>sys.stderr,hex(self.ARMget_register(1))
562 self.ARMset_register(1, r1); # restore R0 and R1
563 self.ARMset_register(0, r0);
568 0x04 : "Interrupts Enabled (or not?)",
573 0x04 : "disable interrupts",
574 0x02 : "force dbgrq",
575 0x01 : "force dbgack"
577 def ARMresettarget(self, delay=10):
578 return self.writecmd(0x13,RESETTARGET,2, [ delay&0xff, (delay>>8)&0xff ] )
579 def ARMchain0(self, address, bits=0x819684c054, data=0):
580 bulk = chop(address,4)
581 bulk.extend(chop(bits,8))
582 bulk.extend(chop(data,4))
583 print >>sys.stderr,(repr(bulk))
584 self.writecmd(0x13,CHAIN0,16,bulk)
585 d1,b1,a1 = struct.unpack("<LQL",self.data)
588 """Start debugging."""
589 self.writecmd(0x13,START,0,self.data)
590 print >>sys.stderr,"Identifying Target:"
591 ident=self.ARMidentstr()
592 print >>sys.stderr,ident
593 print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
596 """Stop debugging."""
597 self.writecmd(0x13,STOP,0,self.data)
598 #def ARMstep_instr(self):
599 # """Step one instruction."""
600 # self.writecmd(0x13,STEP_INSTR,0,self.data)
601 #def ARMflashpage(self,adr):
602 # """Flash 2kB a page of flash from 0xF000 in XDATA"""
607 # print "Flashing buffer to 0x%06x" % adr
608 # self.writecmd(0x13,MASS_FLASH_PAGE,4,data)