Added /dev/ttyU0 to the glob list for OpenBSD.
[goodfet] / client / GoodFETARM7.py
index be1c953..206c820 100644 (file)
@@ -1,8 +1,6 @@
 #!/usr/bin/env python
 # GoodFET ARM Client Library
 # 
-#
-# Good luck with alpha / beta code.
 # Contributions and bug reports welcome.
 #
 # todo:
@@ -10,15 +8,8 @@
 #  * ensure correct PC handling
 #  * flash manipulation (probably need to get the specific chip for this one)
 #  * set security (chip-specific)
-#  * -ancilary/faster- ldm/stm versions of memory access  (had trouble in past, possibly also due to haphazard abuse of DCLK)
-#  
-# fixme now stuff:
-#  * thumb mode get/set_register
-#  * thumb to arm mode
-#  * rethink the whole python/c trade-off for cross-python session debugging
 
 import sys, binascii, struct, time
-import atlasutils.smartprint as asp
 from GoodFET import GoodFET
 from intelhex import IntelHex
 
@@ -40,7 +31,7 @@ OK    = 0x7F
 IR_SHIFT =                  0x80
 DR_SHIFT =                  0x81
 RESETTAP =                  0x82
-RESETTARGET =               0x86
+RESETTARGET =               0x83
 GET_REGISTER =              0x87
 SET_REGISTER =              0x88
 DEBUG_INSTR =               0x89
@@ -131,9 +122,12 @@ ARM_INSTR_LDR_R1_r0_4 =     0xe4901004L
 ARM_READ_MEM =              ARM_INSTR_LDR_R1_r0_4
 ARM_INSTR_STR_R1_r0_4 =     0xe4801004L
 ARM_WRITE_MEM =             ARM_INSTR_STR_R1_r0_4
+ARM_INSTR_STRB_R1_r0_1 =    0xe4c01001L
+ARM_WRITE_MEM_BYTE =        ARM_INSTR_STRB_R1_r0_1
 ARM_INSTR_MRS_R0_CPSR =     0xe10f0000L
 ARM_INSTR_MSR_cpsr_cxsf_R0 =0xe12ff000L
-ARM_INSTR_STMIA_R14_r0_rx = 0xE88E0000L      # add up to 65k to indicate which registers...
+ARM_INSTR_STMIA_R14_r0_rx = 0xE88e0000L      # add up to 65k to indicate which registers...
+ARM_INSTR_LDMIA_R14_r0_rx = 0xE89e0000L      # add up to 65k to indicate which registers...
 ARM_STORE_MULTIPLE =        ARM_INSTR_STMIA_R14_r0_rx
 ARM_INSTR_SKANKREGS =       0xE88F7fffL
 ARM_INSTR_CLOBBEREGS =      0xE89F7fffL
@@ -183,6 +177,12 @@ DBGCTRLBITS = {
         1<<ENABLE:'ENABLE',
         }
 
+LDM_BITMASKS = [(1<<x)-1 for x in xrange(16)]
+#### TOTALLY BROKEN, NEED VALIDATION AND TESTING
+PCOFF_DBGRQ = 4 * 4
+PCOFF_WATCH = 4 * 4
+PCOFF_BREAK = 4 * 4
+
 
 def debugstr(strng):
     print >>sys.stderr,(strng)
@@ -244,10 +244,10 @@ class GoodFETARM(GoodFET):
         return retval
     def ARMidentstr(self):
         ident=self.ARMident()
-        ver     = ident >> 28
-        partno  = (ident >> 12) & 0x10
-        mfgid   = ident & 0xfff
-        return "mfg: %x\npartno: %x\nver: %x\n(%x)" % (ver, partno, mfgid, ident); 
+        ver     = (ident >> 28)
+        partno  = (ident >> 12) & 0xffff
+        mfgid   = (ident >> 1)  & 0x7ff
+        return "Chip IDCODE: 0x%x\n\tver: %x\n\tpartno: %x\n\tmfgid: %x\n" % (ident, ver, partno, mfgid); 
     def ARMeice_write(self, reg, val):
         data = chop(val,4)
         data.extend([reg])
@@ -289,7 +289,7 @@ class GoodFETARM(GoodFET):
         self.storedPC = val
     def ARMget_register(self, reg):
         """Get an ARM's Register"""
-        self.writecmd(0x13,GET_REGISTER,1,[reg&0xff])
+        self.writecmd(0x13,GET_REGISTER,1,[reg&0xf])
         retval = struct.unpack("<L", "".join(self.data[0:4]))[0]
         return retval
     def ARMset_register(self, reg, val):
@@ -306,9 +306,9 @@ class GoodFETARM(GoodFET):
         """Set ARM Registers"""
         for x in xrange(15):
           if (1<<x) & mask:
-            self.ARMset_register(x,regs.pop())
+            self.ARMset_register(x,regs.pop(0))
         if (1<<15) & mask:                      # make sure we set the "static" version of PC or changes will be lost
-          self.ARMsetPC(regs.pop())
+          self.ARMsetPC(regs.pop(0))
     def ARMdebuginstr(self,instr,bkpt):
         if type (instr) == int or type(instr) == long:
             instr = struct.pack("<L", instr)
@@ -316,7 +316,7 @@ class GoodFETARM(GoodFET):
         instr.extend([bkpt])
         self.writecmd(0x13,DEBUG_INSTR,len(instr),instr)
         return (self.data)
-    def ARM_nop(self, bkpt):
+    def ARM_nop(self, bkpt=0):
         if self.status() & DBG_TBIT:
             return self.ARMdebuginstr(THUMB_INSTR_NOP, bkpt)
         return self.ARMdebuginstr(ARM_INSTR_NOP, bkpt)
@@ -339,11 +339,23 @@ class GoodFETARM(GoodFET):
         self.ARMeice_write(EICE_WP1CTRLMASK, ctrlmask);   # write 0xfffffff7 in watchpoint 1 control mask - only detect the fetch instruction
         return self.data
     def THUMBgetPC(self):
+        THUMB_INSTR_STR_R0_r0 =     0x60006000L
+        THUMB_INSTR_MOV_R0_PC =     0x46b846b8L
+        THUMB_INSTR_BX_PC =         0x47784778L
+        THUMB_INSTR_NOP =           0x1c001c00L
+
         r0 = self.ARMget_register(0)
         self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC, 0)
         retval = self.ARMget_register(0)
         self.ARMset_register(0,r0)
         return retval
+    def ARMcapture_system_state(self, pcoffset):
+        if self.ARMget_dbgstate() & DBG_TBIT:
+            pcoffset += 8
+        else:
+            pcoffset += 4
+        self.storedPC = self.ARMget_register(15) + pcoffset
+        self.last_dbg_state = self.ARMget_dbgstate()
     def ARMhaltcpu(self):
         """Halt the CPU."""
         if not(self.ARMget_dbgstate()&1):
@@ -351,7 +363,7 @@ class GoodFETARM(GoodFET):
             if (self.ARMwaitDBG() == 0):
                 raise Exception("Timeout waiting to enter DEBUG mode on HALT")
             self.ARMset_dbgctrl(0)
-            self.last_dbg_state = self.ARMget_dbgstate()
+            self.ARMcapture_system_state(PCOFF_DBGRQ)
             if self.last_dbg_state&0x10:
                 self.storedPC = self.THUMBgetPC()
             else:
@@ -394,8 +406,8 @@ class GoodFETARM(GoodFET):
             print hex(self.storedPC)
             print hex(self.ARMget_register(15))
             print hex(self.ARMchain0(self.storedPC,self.flags)[0])
-            self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc))
-            self.ARM_nop()
+            self.ARMdebuginstr(THUMB_INSTR_B_IMM | (0x7fc07fc),0)
+            self.ARM_nop(0)
             self.ARMrestart()
 
 
@@ -406,12 +418,7 @@ class GoodFETARM(GoodFET):
         r0 = None
         if ((self.current_dbgstate & DBG_TBIT)):
             debugstr("=== Switching to ARM mode ===")
-            #r0 = self.ARMget_register(0)
             self.ARM_nop(0)
-            #self.ARMdebuginstr(THUMB_INSTR_NOP,0)
-            #self.ARMdebuginstr(THUMB_INSTR_STR_R0_r0,0)
-            #self.ARMdebuginstr(THUMB_INSTR_MOV_R0_PC,0)
-            #self.ARMdebuginstr(THUMB_INSTR_STR_R0_r0,0)
             self.ARMdebuginstr(THUMB_INSTR_BX_PC,0)
             self.ARM_nop(0)
             self.ARM_nop(0)
@@ -423,12 +430,14 @@ class GoodFETARM(GoodFET):
         debugstr("=== Switching to THUMB mode ===")
         if ( not (self.current_dbgstate & DBG_TBIT)):
             self.storedPC |= 1
+            r0 = self.ARMget_register(0)
             self.ARMset_register(0, self.storedPC)
             self.ARM_nop(0)
             self.ARMdebuginstr(ARM_INSTR_BX_R0,0)
             self.ARM_nop(0)
             self.ARM_nop(0)
             self.resettap()
+            self.ARMset_register(0,r0)
         self.current_dbgstate = self.ARMget_dbgstate();
         return self.current_dbgstate
     def ARMget_regCPSRstr(self):
@@ -483,8 +492,59 @@ class GoodFETARM(GoodFET):
         self.ARMset_register(1, r1);       # restore R0 and R1 
         self.ARMset_register(0, r0);
         return retval
-
-    def ARMwriteMem(self, adr, wordarray):
+    def ARMreadChunk(self, adr, wordcount):         
+        """ Only works in ARM mode currently
+        WARNING: Addresses must be word-aligned!
+        """
+        regs = self.ARMget_registers()
+        self.ARMset_registers([0xdeadbeef for x in xrange(14)], 0xe)
+        output = []
+        count = wordcount
+        while (wordcount > 0):
+            if (wordcount%64 == 0):  sys.stderr.write(".")
+            count = (wordcount, 0xe)[wordcount>0xd]
+            bitmask = LDM_BITMASKS[count]
+            self.ARMset_register(14,adr)
+            self.ARM_nop(1)
+            self.ARMdebuginstr(ARM_INSTR_LDMIA_R14_r0_rx | bitmask ,0)
+            #FIXME: do we need the extra nop here?
+            self.ARMrestart()
+            self.ARMwaitDBG()
+            output.extend([self.ARMget_register(x) for x in xrange(count)])
+            wordcount -= count
+            adr += count*4
+            #print hex(adr)
+        # FIXME: handle the rest of the wordcount here.
+        self.ARMset_registers(regs,0xe)
+        return output
+    def ARMreadStream(self, adr, bytecount):
+        data = [struct.unpack("<L", x) for x in self.ARMreadChunk(adr, (bytecount-1/4)+1)]
+        return "".join(data)[:bytecount]
+        
+    def ARMwriteChunk(self, adr, wordarray):         
+        """ Only works in ARM mode currently
+        WARNING: Addresses must be word-aligned!
+        """
+        regs = self.ARMget_registers()
+        wordcount = len(wordarray)
+        while (wordcount > 0):
+            if (wordcount%64 == 0):  sys.stderr.write(".")
+            count = (wordcount, 0xe)[wordcount>0xd]
+            bitmask = LDM_BITMASKS[count]
+            self.ARMset_register(14,adr)
+            #print len(wordarray),bin(bitmask)
+            self.ARMset_registers(wordarray[:count],bitmask)
+            self.ARM_nop(1)
+            self.ARMdebuginstr(ARM_INSTR_STMIA_R14_r0_rx | bitmask ,0)
+            #FIXME: do we need the extra nop here?
+            self.ARMrestart()
+            self.ARMwaitDBG()
+            wordarray = wordarray[count:]
+            wordcount -= count
+            adr += count*4
+            #print hex(adr)
+        # FIXME: handle the rest of the wordcount here.
+    def ARMwriteMem(self, adr, wordarray, instr=ARM_WRITE_MEM):
         r0 = self.ARMget_register(0);        # store R0 and R1
         r1 = self.ARMget_register(1);
         #print >>sys.stderr,("CPSR:\t%x"%self.ARMget_regCPSR())
@@ -495,13 +555,16 @@ class GoodFETARM(GoodFET):
             self.ARMset_register(1, word);        # write address into R0
             self.ARM_nop(0)
             self.ARM_nop(1)
-            self.ARMdebuginstr(ARM_WRITE_MEM, 0); # push STR R1, [R0], #4 into instruction pipeline  (autoincrements for consecutive writes)
+            self.ARMdebuginstr(instr, 0); # push STR R1, [R0], #4 into instruction pipeline  (autoincrements for consecutive writes)
             self.ARM_nop(0)
             self.ARMrestart()
             self.ARMwaitDBG()
-            print hex(self.ARMget_register(1))
+            print >>sys.stderr,hex(self.ARMget_register(1))
         self.ARMset_register(1, r1);       # restore R0 and R1 
         self.ARMset_register(0, r0);
+    def writeMemByte(self, adr, byte):
+        self.ARMwriteMem(adr, byte, ARM_WRITE_MEM_BYTE)
+
 
     ARMstatusbits={
                   0x10 : "TBIT",
@@ -515,22 +578,24 @@ class GoodFETARM(GoodFET):
                   0x02 : "force dbgrq",
                   0x01 : "force dbgack"
                   }
-                  
+    def ARMresettarget(self, delay=10):
+        return self.writecmd(0x13,RESETTARGET,2, [ delay&0xff, (delay>>8)&0xff ] )
     def ARMchain0(self, address, bits=0x819684c054, data=0):
         bulk = chop(address,4)
         bulk.extend(chop(bits,8))
         bulk.extend(chop(data,4))
-        print (repr(bulk))
+        print >>sys.stderr,(repr(bulk))
         self.writecmd(0x13,CHAIN0,16,bulk)
         d1,b1,a1 = struct.unpack("<LQL",self.data)
         return (a1,b1,d1)
     def start(self):
         """Start debugging."""
         self.writecmd(0x13,START,0,self.data)
+        print >>sys.stderr,"Identifying Target:"
         ident=self.ARMidentstr()
-        print "Target identifies as %s." % ident
-        print "Debug Status: %s." % self.statusstr()
-        #print "System State: %x." % self.ARMget_regCPSRstr()
+        print >>sys.stderr,ident
+        print >>sys.stderr,"Debug Status:\t%s\n" % self.statusstr()
+
     def stop(self):
         """Stop debugging."""
         self.writecmd(0x13,STOP,0,self.data)