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)
16 from GoodFET import GoodFET
17 from intelhex import IntelHex
33 # ARM7TDMI JTAG commands
42 # Really ARM specific stuff
69 EICE_DBGCTRL = 0 # read 3 bit - Debug Control
70 EICE_DBGCTRL_BITLEN = 3
71 EICE_DBGSTATUS = 1 # read 5 bit - Debug Status
72 EICE_DBGSTATUS_BITLEN = 5
73 EICE_DBGCCR = 4 # read 6 bit - Debug Comms Control Register
74 EICE_DBGCCR_BITLEN = 6
75 EICE_DBGCDR = 5 # r/w 32 bit - Debug Comms Data Register
76 EICE_WP0ADDR = 8 # r/w 32 bit - Watchpoint 0 Address
77 EICE_WP0ADDRMASK = 9 # r/w 32 bit - Watchpoint 0 Addres Mask
78 EICE_WP0DATA = 10 # r/w 32 bit - Watchpoint 0 Data
79 EICE_WP0DATAMASK = 11 # r/w 32 bit - Watchpoint 0 Data Masl
80 EICE_WP0CTRL = 12 # r/w 9 bit - Watchpoint 0 Control Value
81 EICE_WP0CTRLMASK = 13 # r/w 8 bit - Watchpoint 0 Control Mask
82 EICE_WP1ADDR = 16 # r/w 32 bit - Watchpoint 0 Address
83 EICE_WP1ADDRMASK = 17 # r/w 32 bit - Watchpoint 0 Addres Mask
84 EICE_WP1DATA = 18 # r/w 32 bit - Watchpoint 0 Data
85 EICE_WP1DATAMASK = 19 # r/w 32 bit - Watchpoint 0 Data Masl
86 EICE_WP1CTRL = 20 # r/w 9 bit - Watchpoint 0 Control Value
87 EICE_WP1CTRLMASK = 21 # r/w 8 bit - Watchpoint 0 Control Mask
105 0: ("UNKNOWN, MESSED UP PROCESSOR MODE","fsck", "This should Never happen. MCU is in funky state!"),
106 PM_usr: ("User Processor Mode", "usr", "Normal program execution mode"),
107 PM_fiq: ("FIQ Processor Mode", "fiq", "Supports a high-speed data transfer or channel process"),
108 PM_irq: ("IRQ Processor Mode", "irq", "Used for general-purpose interrupt handling"),
109 PM_svc: ("Supervisor Processor Mode", "svc", "A protected mode for the operating system"),
110 PM_abt: ("Abort Processor Mode", "abt", "Implements virtual memory and/or memory protection"),
111 PM_und: ("Undefined Processor Mode", "und", "Supports software emulation of hardware coprocessor"),
112 PM_sys: ("System Processor Mode", "sys", "Runs privileged operating system tasks (ARMv4 and above)"),
116 None, None, None, None, None, "Thumb", "nFIQ_int", "nIRQ_int",
117 "nImprDataAbort_int", "BIGendian", None, None, None, None, None, None,
118 "GE_0", "GE_1", "GE_2", "GE_3", None, None, None, None,
119 "Jazelle", None, None, "Q (DSP-overflow)", "oVerflow", "Carry", "Zero", "Neg",
122 ARM_INSTR_NOP = 0xe1a00000L
123 ARM_INSTR_BX_R0 = 0xe12fff10L
124 ARM_INSTR_STR_Rx_r14 = 0xe58f0000L # from atmel docs
125 ARM_READ_REG = ARM_INSTR_STR_Rx_r14
126 ARM_INSTR_LDR_Rx_r14 = 0xe59f0000L # from atmel docs
127 ARM_WRITE_REG = ARM_INSTR_LDR_Rx_r14
128 ARM_INSTR_LDR_R1_r0_4 = 0xe4901004L
129 ARM_READ_MEM = ARM_INSTR_LDR_R1_r0_4
130 ARM_INSTR_STR_R1_r0_4 = 0xe4801004L
131 ARM_WRITE_MEM = ARM_INSTR_STR_R1_r0_4
132 ARM_INSTR_STRB_R1_r0_1 = 0xe4c01001L
133 ARM_WRITE_MEM_BYTE = ARM_INSTR_STRB_R1_r0_1
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)
197 def PSRdecode(psrval):
198 output = [ "(%s mode)"%proc_modes[psrval&0x1f][1] ]
199 for x in xrange(5,32):
201 output.append(PSR_bits[x])
202 return " ".join(output)
204 fmt = [None, "B", "<H", None, "<L", None, None, None, "<Q"]
207 s = struct.pack(fmt[byts], val)
208 return [ord(b) for b in s ]
210 class GoodFETARM7(GoodFET):
211 """A GoodFET variant for use with ARM7TDMI microprocessor."""
213 GoodFET.__init__(self)
214 self.storedPC = 0xffffffff
215 self.current_dbgstate = 0xffffffff
216 self.flags = 0xffffffff
217 self.nothing = 0xffffffff
218 self.stored_regs = []
222 if (self.ARMget_dbgstate()&9) == 9:
225 sys.excepthook(*sys.exc_info())
228 """Move the FET into the JTAG ARM application."""
229 #print "Initializing ARM."
230 self.writecmd(0x13,SETUP,0,self.data)
232 def flash(self,file):
233 """Flash an intel hex file to code memory."""
234 print "Flash not implemented.";
236 def dump(self,fn,start=0,stop=0xffffffff):
237 """Dump an intel hex file from code memory."""
239 print "Dumping from %04x to %04x as %s." % (start,stop,f);
240 # FIXME: get mcu state and return it to that state
246 data=self.ARMreadChunk(i, 48, verbose=0);
247 print "Dumped %06x."%i;
249 if i<=stop and dword != 0xdeadbeef:
250 h.puts( i, struct.pack("<I", dword) )
252 # FIXME: get mcu state and return it to that state
254 h.write_hex_file(fn);
256 print "Dump not implemented.";
258 def ARMsetIRsize(self, size=4):
260 raise Exception("IR size cannot be >255!!")
261 self.writecmd(0x13, IR_SIZE, 1, [size])
263 def ARMsetSCANsize(self, size=4):
265 raise Exception("IR size cannot be >255!!")
266 self.writecmd(0x13, SCAN_N_SIZE, 1, [size])
268 def ARMshift_IR(self, IR, noretidle=0):
269 self.writecmd(0x13,IR_SHIFT,2, [IR, LSB|noretidle])
272 def ARMshift_DR(self, data, bits, flags):
273 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])
276 def ARMshift_DR_more(self, data, bits, flags):
277 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])
280 def ARMwaitDBG(self, timeout=0xff):
281 self.current_dbgstate = self.ARMget_dbgstate()
282 while ( not ((self.current_dbgstate & 9L) == 9)):
284 self.current_dbgstate = self.ARMget_dbgstate()
288 """Get an ARM's ID."""
289 self.ARMshift_IR(IR_IDCODE,0)
290 self.ARMshift_DR(0,32,LSB)
291 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
294 def ARMidentstr(self):
295 ident=self.ARMident()
297 partno = (ident >> 12) & 0xffff
298 mfgid = (ident >> 1) & 0x7ff
299 return "Chip IDCODE: 0x%x\tver: %x\tpartno: %x\tmfgid: %x" % (ident, ver, partno, mfgid);
301 def ARMeice_write(self, reg, val):
304 retval = self.writecmd(0x13, EICE_WRITE, 5, data)
307 def ARMeice_read(self, reg):
308 self.writecmd(0x13, EICE_READ, 1, [reg])
309 retval, = struct.unpack("<L",self.data)
312 def ARMget_dbgstate(self):
313 """Read the config register of an ARM."""
314 self.ARMeice_read(EICE_DBGSTATUS)
315 self.current_dbgstate = struct.unpack("<L", self.data[:4])[0]
316 return self.current_dbgstate
317 status = ARMget_dbgstate
320 """Check the status as a string."""
326 str="%s %s" %(self.ARMstatusbits[i],str)
330 def ARMget_dbgctrl(self):
331 """Read the config register of an ARM."""
332 self.ARMeice_read(EICE_DBGCTRL)
333 retval = struct.unpack("<L", self.data[:4])[0]
336 def ARMset_dbgctrl(self,config):
337 """Write the config register of an ARM."""
338 self.ARMeice_write(EICE_DBGCTRL, config&7)
341 """Get an ARM's PC. Note: real PC gets all wonky in debug mode, this is the "saved" PC"""
345 def ARMsetPC(self, val):
346 """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"""
349 def ARMget_register(self, reg):
350 """Get an ARM's Register"""
351 self.writecmd(0x13,GET_REGISTER,1,[reg&0xf])
352 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
355 def ARMset_register(self, reg, val):
356 """Get an ARM's Register"""
357 self.writecmd(0x13,SET_REGISTER,8,[val&0xff, (val>>8)&0xff, (val>>16)&0xff, val>>24, reg,0,0,0])
358 retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
361 def ARMget_registers(self):
362 """Get ARM Registers"""
363 regs = [ self.ARMget_register(x) for x in range(15) ]
364 regs.append(self.ARMgetPC()) # make sure we snag the "static" version of PC
367 def ARMset_registers(self, regs, mask):
368 """Set ARM Registers"""
371 self.ARMset_register(x,regs.pop(0))
372 if (1<<15) & mask: # make sure we set the "static" version of PC or changes will be lost
373 self.ARMsetPC(regs.pop(0))
375 def ARMdebuginstr(self,instr,bkpt):
376 if type (instr) == int or type(instr) == long:
377 instr = struct.pack("<L", instr)
378 instr = [int("0x%x"%ord(x),16) for x in instr]
380 self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
383 def ARM_nop(self, bkpt=0):
384 if self.status() & DBG_TBIT:
385 return self.ARMdebuginstr(THUMB_INSTR_NOP, bkpt)
386 return self.ARMdebuginstr(ARM_INSTR_NOP, bkpt)
388 def ARMrestart(self):
389 self.ARMshift_IR(IR_RESTART)
391 def ARMset_watchpoint0(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
392 self.ARMeice_write(EICE_WP0ADDR, addr); # write 0 in watchpoint 0 address
393 self.ARMeice_write(EICE_WP0ADDRMASK, addrmask); # write 0xffffffff in watchpoint 0 address mask
394 self.ARMeice_write(EICE_WP0DATA, data); # write 0 in watchpoint 0 data
395 self.ARMeice_write(EICE_WP0DATAMASK, datamask); # write 0xffffffff in watchpoint 0 data mask
396 self.ARMeice_write(EICE_WP0CTRL, ctrl); # write 0x00000100 in watchpoint 0 control value register (enables watchpoint)
397 self.ARMeice_write(EICE_WP0CTRLMASK, ctrlmask); # write 0xfffffff7 in watchpoint 0 control mask - only detect the fetch instruction
400 def ARMset_watchpoint1(self, addr, addrmask, data, datamask, ctrl, ctrlmask):
401 self.ARMeice_write(EICE_WP1ADDR, addr); # write 0 in watchpoint 1 address
402 self.ARMeice_write(EICE_WP1ADDRMASK, addrmask); # write 0xffffffff in watchpoint 1 address mask
403 self.ARMeice_write(EICE_WP1DATA, data); # write 0 in watchpoint 1 data
404 self.ARMeice_write(EICE_WP1DATAMASK, datamask); # write 0xffffffff in watchpoint 1 data mask
405 self.ARMeice_write(EICE_WP1CTRL, ctrl); # write 0x00000100 in watchpoint 1 control value register (enables watchpoint)
406 self.ARMeice_write(EICE_WP1CTRLMASK, ctrlmask); # write 0xfffffff7 in watchpoint 1 control mask - only detect the fetch instruction
409 def THUMBgetPC(self):
410 THUMB_INSTR_STR_R0_r0 = 0x60006000L
411 THUMB_INSTR_MOV_R0_PC = 0x46b846b8L
412 THUMB_INSTR_BX_PC = 0x47784778L
413 THUMB_INSTR_NOP = 0x1c001c00L
415 r0 = self.ARMget_register(0)
416 self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC, 0)
417 retval = self.ARMget_register(0)
418 self.ARMset_register(0,r0)
421 def ARMcapture_system_state(self, pcoffset):
422 self.c0Data, self.flags, self.c0Addr = self.ARMchain0(0)
423 if self.ARMget_dbgstate() & DBG_TBIT:
427 self.storedPC = self.ARMget_register(15) + pcoffset
428 self.last_dbg_state = self.ARMget_dbgstate()
429 self.cpsr = self.ARMget_regCPSR()
430 #print "ARMcapture_system_state: stored pc: 0x%x last_dbg_state: 0x%x" % (self.storedPC, self.last_dbg_state)
434 if self.ARMget_dbgstate()&DBG_DBGACK:
435 if not len(self.stored_regs):
436 #print "stored regs: " + repr(self.stored_regs)
437 self.stored_regs = self.ARMget_registers()[:15]
438 print self.print_stored_registers()
441 self.ARMset_dbgctrl(2)
442 if (self.ARMwaitDBG() == 0):
443 raise Exception("Timeout waiting to enter DEBUG mode on HALT")
444 self.ARMset_dbgctrl(0)
446 self.ARMcapture_system_state(PCOFF_DBGRQ)
447 #print "storedPC: %x (%x) flags: %x nothing: %x" % (self.storedPC, self.c0Data, self.flags, self.c0Addr)
448 if self.ARMget_dbgstate() & DBG_TBIT:
450 if self.storedPC ^ 4:
451 self.ARMset_register(15,self.storedPC&0xfffffffc)
452 self.stored_regs = self.ARMget_registers()[:15]
453 #print "stored regs: " + repr(self.stored_regs)
454 #print self.print_stored_registers()
455 #print "CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
458 """Resume the CPU."""
459 # FIXME: restore CPSR
460 # FIXME: true up PC to exactly where we left off...
461 if not self.ARMget_dbgstate()&DBG_DBGACK:
464 if len(self.stored_regs):
465 #print self.print_stored_registers()
466 self.ARMset_registers(self.stored_regs, 0x7fff)
468 print "skipping restore of stored registers due to empty list ? WTFO?"
470 currentPC, self.currentflags, nothing = self.ARMchain0(self.storedPC,self.flags, self.c0Addr)
471 if not(self.flags & F_TBIT): # need to be in arm mode
472 if self.currentflags & F_TBIT: # currently in thumb mode
474 # branch to the right address
475 self.ARMset_register(15, self.storedPC)
476 #print hex(self.storedPC)
477 #print hex(self.ARMget_register(15))
478 #print hex(self.ARMchain0(self.storedPC,self.flags)[0])
479 self.ARMchain0(self.storedPC,self.flags)
482 self.ARMdebuginstr(ARM_INSTR_B_IMM | 0xfffff0,0)
486 elif self.flags & F_TBIT: # need to be in thumb mode
487 if not (self.currentflags & F_TBIT): # currently in arm mode
488 self.ARMsetModeThumb()
489 r0=self.ARMget_register(0)
490 self.ARMset_register(0, self.storedPC)
491 self.ARMdebuginstr(THUMB_INSTR_MOV_PC_R0,0)
494 #print hex(self.storedPC)
495 #print hex(self.ARMget_register(15))
496 #print hex(self.ARMchain0(self.storedPC,self.flags)[0])
497 self.ARMchain0(self.storedPC,self.flags)[0]
498 self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc),0)
502 #print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
503 #print >>sys.stderr,"CPSR: (%s) %s"%(self.ARMget_regCPSRstr())
506 self.writecmd(0x13, RESETTAP, 0,[])
508 def ARMsetModeARM(self):
510 if ((self.current_dbgstate & DBG_TBIT)):
511 #debugstr("=== Switching to ARM mode ===")
513 self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
517 self.current_dbgstate = self.ARMget_dbgstate();
518 return self.current_dbgstate
520 def ARMsetModeThumb(self): # needs serious work and truing
522 #debugstr("=== Switching to THUMB mode ===")
523 if ( not (self.current_dbgstate & DBG_TBIT)):
525 r0 = self.ARMget_register(0)
526 self.ARMset_register(0, self.storedPC)
528 self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
532 self.ARMset_register(0,r0)
533 self.current_dbgstate = self.ARMget_dbgstate();
534 return self.current_dbgstate
536 def ARMget_regCPSRstr(self):
537 psr = self.ARMget_regCPSR()
538 return hex(psr), PSRdecode(psr)
540 def ARMget_regCPSR(self):
541 """Get an ARM's Register"""
542 r0 = self.ARMget_register(0)
543 self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
544 self.ARMdebuginstr(ARM_INSTR_MRS_R0_CPSR, 0) # push MRS_R0, CPSR into pipeline - fetch
545 self.ARM_nop( 0) # push nop into pipeline - decoded
546 self.ARM_nop( 0) # push nop into pipeline - execute
547 retval = self.ARMget_register(0)
548 self.ARMset_register(0, r0)
551 def ARMset_regCPSR(self, val):
552 """Get an ARM's Register"""
553 r0 = self.ARMget_register(0)
554 self.ARMset_register(0, val)
555 self.ARM_nop( 0) # push nop into pipeline - clean out the pipeline...
556 self.ARMdebuginstr(ARM_INSTR_MSR_cpsr_cxsf_R0, 0) # push MSR cpsr_cxsf, R0 into pipeline - fetch
557 self.ARM_nop( 0) # push nop into pipeline - decoded
558 self.ARM_nop( 0) # push nop into pipeline - execute
559 self.ARMset_register(0, r0)
562 def ARMreadStream(self, addr, bytecount):
563 baseaddr = addr & 0xfffffffc
564 endaddr = ((addr + bytecount + 3) & 0xfffffffc)
565 diffstart = 4 - (addr - baseaddr)
566 diffend = 4 - (endaddr - (addr + bytecount ))
570 data = [ x for x in self.ARMreadChunk( baseaddr, ((endaddr-baseaddr) / 4) ) ]
571 #print data, hex(baseaddr), hex(diffstart), hex(endaddr), hex(diffend)
573 #print "single dword"
574 out.append( struct.pack("<I", data.pop(0)) [4-diffstart:diffend] )
576 #print "%d dwords" % len(data)
578 out.append( struct.pack("<I", data.pop(0)) [4-diffstart:] )
579 bytecount -= (diffstart)
582 for ent in data[:-1]:
583 out.append( struct.pack("<I", data.pop(0) ) )
587 if diffend and bytecount>0:
588 out.append( struct.pack("<I", data.pop(0)) [:diffend] )
592 def ARMprintChunk(self, adr, wordcount=1, verbose=False, width=8):
593 for string in self.ARMreprChunk(adr, wordcount, verbose=False, width=8):
594 sys.stdout.write(string)
596 def ARMreprChunk(self, adr, wordcount=1, verbose=False, width=8):
598 endva = adr + (4*wordcount)
599 output = [ "Dwords from 0x%x through 0x%x" % (adr, endva) ]
601 for data in self.ARMreadChunk(adr, wordcount, verbose):
602 if (idx % width) == 0:
603 yield ( "\n0x%.8x\t" % (adr + (4*idx)) )
604 yield ( "%.8x " % (data) )
609 def ARMreadChunk(self, adr, wordcount=1, verbose=True):
610 """ Only works in ARM mode currently
611 WARNING: Addresses must be word-aligned!
613 regs = self.ARMget_registers()
614 self.ARMset_registers([0xdeadbeef for x in xrange(14)], 0xe)
616 while (wordcount > 0):
617 if (verbose and wordcount%64 == 0): sys.stderr.write(".")
618 count = (wordcount, 0xe)[wordcount>0xd]
619 bitmask = LDM_BITMASKS[count]
620 self.ARMset_register(14,adr)
622 self.ARMdebuginstr(ARM_INSTR_LDMIA_R14_r0_rx | bitmask ,0)
623 #FIXME: do we need the extra nop here?
626 for x in range(count):
627 yield self.ARMget_register(x)
631 # FIXME: handle the rest of the wordcount here.
632 self.ARMset_registers(regs,0xe)
634 ARMreadMem = ARMreadChunk
637 def ARMwriteChunk(self, adr, wordarray):
638 """ Only works in ARM mode currently
639 WARNING: Addresses must be word-aligned!
641 regs = self.ARMget_registers()
642 wordcount = len(wordarray)
643 while (wordcount > 0):
644 if (wordcount%64 == 0): sys.stderr.write(".")
645 count = (wordcount, 0xe)[wordcount>0xd]
646 bitmask = LDM_BITMASKS[count]
647 self.ARMset_register(14,adr)
648 #print len(wordarray),bin(bitmask)
649 self.ARMset_registers(wordarray[:count],bitmask)
651 self.ARMdebuginstr(ARM_INSTR_STMIA_R14_r0_rx | bitmask ,0)
652 #FIXME: do we need the extra nop here?
655 wordarray = wordarray[count:]
659 # FIXME: handle the rest of the wordcount here.
660 ARMwriteMem = ARMwriteChunk
662 def ARMwriteStream(self, addr, datastr):
663 #bytecount = len(datastr)
664 #baseaddr = addr & 0xfffffffc
665 #diffstart = addr - baseaddr
666 #endaddr = ((addr + bytecount) & 0xfffffffc) + 4
667 #diffend = 4 - (endaddr - (addr+bytecount))
668 bytecount = len(datastr)
669 baseaddr = addr & 0xfffffffc
670 endaddr = ((addr + bytecount + 3) & 0xfffffffc)
671 diffstart = 4 - (addr - baseaddr)
672 diffend = 4 - (endaddr - (addr + bytecount ))
674 print hex(baseaddr), hex(diffstart), hex(endaddr), hex(diffend)
677 dword = self.ARMreadChunk(baseaddr, 1)[0] & (0xffffffff>>(8*diffstart))
678 dst = "\x00" * (4-diffstart) + datastr[:diffstart]; print hex(dword), repr(dst)
679 datachk = struct.unpack("<I", dst)[0]
680 out.append( dword+datachk )
681 datastr = datastr[diffstart:]
682 bytecount -= diffstart
683 for ent in xrange(baseaddr+4, endaddr-4, 4):
685 dword = struct.unpack("<I", datastr[:4])[0]
687 datastr = datastr[4:]
689 if diffend and bytecount:
690 dword = self.ARMreadChunk(endaddr-4, 1)[0] & (0xffffffff<<(8*diffend))
691 dst = datastr + "\x00" * (4-diffend); print hex(dword), repr(dst)
692 datachk = struct.unpack("<I", dst)[0]
693 out.append( dword+datachk )
694 print repr([hex(x) for x in out])
695 return self.ARMwriteChunk(baseaddr, out)
698 def writeMemByte(self, adr, byte):
699 self.ARMwriteMem(adr, byte, ARM_WRITE_MEM_BYTE)
705 0x04 : "Interrupts Enabled (or not?)",
710 0x04 : "disable interrupts",
711 0x02 : "force dbgrq",
712 0x01 : "force dbgack"
714 def ARMresettarget(self, delay=1000):
715 return self.writecmd(0x13,RESETTARGET,2, [ delay&0xff, (delay>>8)&0xff ] )
717 def ARMchain0(self, address, bits=0x819684c054, data=0):
718 bulk = chop(address,4)
719 bulk.extend(chop(bits,8))
720 bulk.extend(chop(data,4))
721 #print >>sys.stderr,(repr(bulk))
722 self.writecmd(0x13,CHAIN0,16,bulk)
723 d1,b1,a1 = struct.unpack("<LQL",self.data)
726 def start(self, ident=False):
727 """Start debugging."""
728 self.writecmd(0x13,START,0,self.data)
730 print >>sys.stderr,"Identifying Target:"
731 print >>sys.stderr, self.ARMidentstr()
732 print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
735 """Stop debugging."""
736 self.writecmd(0x13,STOP,0,self.data)
737 #def ARMstep_instr(self):
738 # """Step one instruction."""
739 # self.writecmd(0x13,STEP_INSTR,0,self.data)
740 #def ARMflashpage(self,adr):
741 # """Flash 2kB a page of flash from 0xF000 in XDATA"""
746 # print "Flashing buffer to 0x%06x" % adr
747 # self.writecmd(0x13,MASS_FLASH_PAGE,4,data)
749 def print_registers(self):
750 return [ hex(x) for x in self.ARMget_registers() ]
752 def print_stored_registers(self):
753 return [ hex(x) for x in self.stored_regs ]
757 ######### command line stuff #########
758 from intelhex import IntelHex16bit, IntelHex
761 print "Usage: %s verb [objects]\n" % sys.argv[0]
762 print "%s info" % sys.argv[0]
763 print "%s dump $foo.hex [0x$start 0x$stop]" % sys.argv[0]
764 print "%s erase" % sys.argv[0]
765 print "%s eraseinfo" % sys.argv[0]
766 print "%s flash $foo.hex [0x$start 0x$stop]" % sys.argv[0]
767 print "%s verify $foo.hex [0x$start 0x$stop]" % sys.argv[0]
768 print "%s poke 0x$adr 0x$val" % sys.argv[0]
769 print "%s peek 0x$start [0x$stop]" % sys.argv[0]
770 print "%s reset" % sys.argv[0]
774 ''' this function should be called from command line app '''
776 #Initialize FET and set baud rate
783 arm7_cli_handler(client, sys.argv)
785 def arm7_cli_handler(client, argv):
788 print >>sys.stderr, client.ARMidentstr()
789 print >>sys.stderr,"Debug Status:\t%s" % client.statusstr()
790 print >>sys.stderr,"CPSR: (%s) %s\n"%(client.ARMget_regCPSRstr())
799 start=int(sys.argv[3],16)
801 stop=int(sys.argv[4],16)
803 print "Dumping from %04x to %04x as %s." % (start,stop,f)
804 #h = IntelHex16bit(None)
805 # FIXME: get mcu state and return it to that state
812 #data=client.ARMreadMem(i, 48)
813 data=client.ARMreadChunk(i, 48, verbose=0)
814 print "Dumped %06x."%i
816 if i<=stop and dword != 0xdeadbeef:
817 h.puts( i, struct.pack("<I", dword) )
819 # FIXME: get mcu state and return it to that state
821 print "Unknown error during read. Writing results to output file."
822 print "Rename file with last address dumped %06x."%i
829 if(sys.argv[1]=="erase"):
830 print "Erasing main flash memory."
831 client.ARMmasserase()
833 if(sys.argv[1]=="eraseinfo"):
834 print "Erasing info memory."
835 client.ARMinfoerase()
839 if(sys.argv[1]=="ivt"):
841 client.ARMprintChunk(0x0,0x20)
844 if(sys.argv[1]=="regs"):
846 for i in range(0,16):
847 print "r%i=%04x" % (i,client.ARMget_register(i))
850 if(sys.argv[1]=="flash"):
855 start=int(sys.argv[3],16)
857 stop=int(sys.argv[4],16)
862 #Should this be default?
863 #Makes flashing multiple images inconvenient.
864 #client.ARMmasserase()
866 count=0; #Bytes in commit.
869 last=0; #Last address committed.
870 for i in h._buf.keys():
871 if((count>0x40 or last+2!=i) and count>0 and i&1==0):
872 #print "%i, %x, %x" % (len(vals), last, i)
873 client.ARMpokeflashblock(first,vals)
878 if(i>=start and i<stop and i&1==0):
884 vals+=[val&0xff,(val&0xff00)>>8]
887 if count>0: #last commit, ivt
888 client.ARMpokeflashblock(first,vals)
891 if(sys.argv[1]=="verify"):
896 start=int(sys.argv[3],16)
898 stop=int(sys.argv[4],16)
902 for i in h._buf.keys():
903 if(i>=start and i<stop and i&1==0):
906 print "ERROR at %04x, found %04x not %04x"%(i,peek,h[i>>1])
912 if(sys.argv[1]=="peek"):
915 start=int(sys.argv[2],16)
919 stop=int(sys.argv[3],16)
921 print "Peeking from %04x to %04x." % (start,stop)
923 for dword in client.ARMreadChunk(start, (stop-start)/4, verbose=0):
924 print "%.4x: %.8x" % (start, dword)
928 if(sys.argv[1]=="poke"):
932 start=int(sys.argv[2],16)
934 val=int(sys.argv[3],16)
936 print "Poking %06x to become %04x." % (start,val)
938 #???while client.ARMreadMem(start)[0]&(~val)>0:
939 client.ARMwriteChunk(start, [val])
940 print "Poked to %.8x" % client.ARMreadMem(start)[0]
944 if(sys.argv[1]=="reset"):
945 #Set PC to RESET vector's value.
947 #client.ARMsetPC(0x00000000)
948 #client.ARMset_regCPSR(0)
949 #client.ARMreleasecpu()
950 client.ARMresettarget(1000)
952 #client.ARMreleasecpu()