Updates to ARM7TDMI JTAG app and optimizations for debughex() and added debughex32...
[goodfet] / client / GoodFET.py
1 #!/usr/bin/env python
2 # GoodFET Client Library
3
4 # (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
5 #
6 # This code is being rewritten and refactored.  You've been warned!
7
8 import sys, time, string, cStringIO, struct, glob, serial, os;
9 import sqlite3;
10
11 fmt = ("B", "<H", None, "<L")
12
13 def getClient(name="GoodFET"):
14     import GoodFET, GoodFETCC, GoodFETAVR, GoodFETSPI, GoodFETMSP430;
15     if(name=="GoodFET" or name=="monitor"): return GoodFET.GoodFET();
16     elif name=="cc" or name=="chipcon": return GoodFETCC.GoodFETCC();
17     elif name=="avr": return GoodFETAVR.GoodFETAVR();
18     elif name=="spi": return GoodFETSPI.GoodFETSPI();
19     elif name=="msp430": return GoodFETMSP430.GoodFETMSP430();
20     
21     print "Unsupported target: %s" % name;
22     sys.exit(0);
23
24 class SymbolTable:
25     """GoodFET Symbol Table"""
26     db=sqlite3.connect(":memory:");
27     
28     def __init__(self, *args, **kargs):
29         self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
30     def get(self,name):
31         self.db.commit();
32         c=self.db.cursor();
33         try:
34             c.execute("select adr,memory from symbols where name=?",(name,));
35             for row in c:
36                 #print "Found it.";
37                 sys.stdout.flush();
38                 return row[0];
39             #print "No dice.";
40         except:# sqlite3.OperationalError:
41             #print "SQL error.";
42             return eval(name);
43         return eval(name);
44     def define(self,adr,name,comment="",memory="vn",size=16):
45         self.db.execute("insert into symbols(adr,name,memory,size,comment)"
46                         "values(?,?,?,?,?);", (
47                 adr,name,memory,size,comment));
48         #print "Set %s=%s." % (name,adr);
49
50 class GoodFET:
51     """GoodFET Client Library"""
52
53     besilent=0;
54     app=0;
55     verb=0;
56     count=0;
57     data="";
58     verbose=False
59     
60     GLITCHAPP=0x71;
61     symbols=SymbolTable();
62     
63     def __init__(self, *args, **kargs):
64         self.data=[0];
65     def getConsole(self):
66         from GoodFETConsole import GoodFETConsole;
67         return GoodFETConsole(self);
68     def name2adr(self,name):
69         return self.symbols.get(name);
70     def timeout(self):
71         print "timeout\n";
72     def serInit(self, port=None, timeout=None):
73         """Open the serial port"""
74         
75         if port is None and os.environ.get("GOODFET")!=None:
76             glob_list = glob.glob(os.environ.get("GOODFET"));
77             if len(glob_list) > 0:
78                 port = glob_list[0];
79         if port is None:
80             glob_list = glob.glob("/dev/tty.usbserial*");
81             if len(glob_list) > 0:
82                 port = glob_list[0];
83         if port is None:
84             glob_list = glob.glob("/dev/ttyUSB*");
85             if len(glob_list) > 0:
86                 port = glob_list[0];
87         
88         self.serialport = serial.Serial(
89             port,
90             #9600,
91             115200,
92             parity = serial.PARITY_NONE,
93             timeout=timeout
94             )
95         
96         #Explicitly set RTS and DTR to halt board.
97         self.serialport.setRTS(1);
98         self.serialport.setDTR(1);
99         #Drop DTR, which is !RST, low to begin the app.
100         self.serialport.setDTR(0);
101         self.serialport.flushInput()
102         self.serialport.flushOutput()
103         
104         #Read and handle the initial command.
105         #time.sleep(1);
106         self.readcmd(); #Read the first command.
107         if(self.verb!=0x7F):
108             print "Verb %02x is wrong.  Incorrect firmware or bad Info guess?" % self.verb;
109             print "http://goodfet.sf.net/faq/";
110         #print "Connected."
111     def getbuffer(self,size=0x1c00):
112         writecmd(0,0xC2,[size&0xFF,(size>>16)&0xFF]);
113         print "Got %02x%02x buffer size." % (self.data[1],self.data[0]);
114     def writecmd(self, app, verb, count=0, data=[]):
115         """Write a command and some data to the GoodFET."""
116         self.serialport.write(chr(app));
117         self.serialport.write(chr(verb));
118         
119         #if data!=None:
120         #    count=len(data); #Initial count ignored.
121         
122         #print "TX %02x %02x %04x" % (app,verb,count);
123         
124         #little endian 16-bit length
125         self.serialport.write(chr(count&0xFF));
126         self.serialport.write(chr(count>>8));
127
128         if self.verbose:
129             print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
130         
131         #print "count=%02x, len(data)=%04x" % (count,len(data));
132         
133         if count!=0:
134             if(isinstance(data,list)):
135                 for i in range(0,count):
136                 #print "Converting %02x at %i" % (data[i],i)
137                     data[i]=chr(data[i]);
138             #print type(data);
139             outstr=''.join(data);
140             self.serialport.write(outstr);
141         if not self.besilent:
142             return self.readcmd()
143         else:
144             return []
145
146     def readcmd(self):
147         """Read a reply from the GoodFET."""
148         while 1:#self.serialport.inWaiting(): # Loop while input data is available
149             try:
150                 #print "Reading...";
151                 self.app=ord(self.serialport.read(1));
152                 #print "APP=%2x" % self.app;
153                 self.verb=ord(self.serialport.read(1));
154                 #print "VERB=%02x" % self.verb;
155                 self.count=(
156                     ord(self.serialport.read(1))
157                     +(ord(self.serialport.read(1))<<8)
158                     );
159
160                 if self.verbose:
161                     print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
162             
163                 #Debugging string; print, but wait.
164                 if self.app==0xFF:
165                     if self.verb==0xFF:
166                         print "# DEBUG %s" % self.serialport.read(self.count)
167                     elif self.verb==0xFE:
168                         print "# DEBUG 0x%x" % struct.unpack(fmt[self.count-1], self.serialport.read(self.count))[0]
169                     sys.stdout.flush();
170                 else:
171                     self.data=self.serialport.read(self.count);
172                     return self.data;
173             except TypeError:
174                 print "Error: waiting for serial read timed out (most likely)."
175                 sys.exit(-1)
176
177     #Glitching stuff.
178     def glitchApp(self,app):
179         """Glitch into a device by its application."""
180         self.data=[app&0xff];
181         self.writecmd(self.GLITCHAPP,0x80,1,self.data);
182         #return ord(self.data[0]);
183     def glitchVerb(self,app,verb,data):
184         """Glitch during a transaction."""
185         if data==None: data=[];
186         self.data=[app&0xff, verb&0xFF]+data;
187         self.writecmd(self.GLITCHAPP,0x81,len(self.data),self.data);
188         #return ord(self.data[0]);
189     def glitchstart(self):
190         """Glitch into the AVR application."""
191         self.glitchVerb(self.APP,0x20,None);
192     def glitchstarttime(self):
193         """Measure the timer of the START verb."""
194         return self.glitchTime(self.APP,0x20,None);
195     def glitchTime(self,app,verb,data):
196         """Time the execution of a verb."""
197         if data==None: data=[];
198         self.data=[app&0xff, verb&0xFF]+data;
199         self.writecmd(self.GLITCHAPP,0x82,len(self.data),self.data);
200         return ord(self.data[0])+(ord(self.data[1])<<8);
201     def glitchVoltages(self,low=0x0880, high=0x0fff):
202         """Set glitching voltages. (0x0fff is max.)"""
203         self.data=[low&0xff, (low>>8)&0xff,
204                    high&0xff, (high>>8)&0xff];
205         self.writecmd(self.GLITCHAPP,0x90,4,self.data);
206         #return ord(self.data[0]);
207     def glitchRate(self,count=0x0800):
208         """Set glitching count period."""
209         self.data=[count&0xff, (count>>8)&0xff];
210         self.writecmd(self.GLITCHAPP,0x91,2,
211                       self.data);
212         #return ord(self.data[0]);
213     
214     
215     #Monitor stuff
216     def silent(self,s=0):
217         """Transmissions halted when 1."""
218         self.besilent=s;
219         print "besilent is %i" % self.besilent;
220         self.writecmd(0,0xB0,1,[s]);
221         
222     def out(self,byte):
223         """Write a byte to P5OUT."""
224         self.writecmd(0,0xA1,1,[byte]);
225     def dir(self,byte):
226         """Write a byte to P5DIR."""
227         self.writecmd(0,0xA0,1,[byte]);
228     def call(self,adr):
229         """Call to an address."""
230         self.writecmd(0,0x30,2,
231                       [adr&0xFF,(adr>>8)&0xFF]);
232     def execute(self,code):
233         """Execute supplied code."""
234         self.writecmd(0,0x31,2,#len(code),
235                       code);
236     def peekbyte(self,address):
237         """Read a byte of memory from the monitor."""
238         self.data=[address&0xff,address>>8];
239         self.writecmd(0,0x02,2,self.data);
240         #self.readcmd();
241         return ord(self.data[0]);
242     def peekword(self,address):
243         """Read a word of memory from the monitor."""
244         return self.peekbyte(address)+(self.peekbyte(address+1)<<8);
245     def pokebyte(self,address,value):
246         """Set a byte of memory by the monitor."""
247         self.data=[address&0xff,address>>8,value];
248         self.writecmd(0,0x03,3,self.data);
249         return ord(self.data[0]);
250     def dumpmem(self,begin,end):
251         i=begin;
252         while i<end:
253             print "%04x %04x" % (i, self.peekword(i));
254             i+=2;
255     def monitor_ram_pattern(self):
256         """Overwrite all of RAM with 0xBEEF."""
257         self.writecmd(0,0x90,0,self.data);
258         return;
259     def monitor_ram_depth(self):
260         """Determine how many bytes of RAM are unused by looking for 0xBEEF.."""
261         self.writecmd(0,0x91,0,self.data);
262         return ord(self.data[0])+(ord(self.data[1])<<8);
263     
264     #Baud rates.
265     baudrates=[115200, 
266                9600,
267                19200,
268                38400,
269                57600,
270                115200];
271     def setBaud(self,baud):
272         """Change the baud rate.  TODO fix this."""
273         rates=self.baudrates;
274         self.data=[baud];
275         print "Changing FET baud."
276         self.serialport.write(chr(0x00));
277         self.serialport.write(chr(0x80));
278         self.serialport.write(chr(1));
279         self.serialport.write(chr(baud));
280         
281         print "Changed host baud."
282         self.serialport.setBaudrate(rates[baud]);
283         time.sleep(1);
284         self.serialport.flushInput()
285         self.serialport.flushOutput()
286         
287         print "Baud is now %i." % rates[baud];
288         return;
289     def readbyte(self):
290         return ord(self.serialport.read(1));
291     def findbaud(self):
292         for r in self.baudrates:
293             print "\nTrying %i" % r;
294             self.serialport.setBaudrate(r);
295             #time.sleep(1);
296             self.serialport.flushInput()
297             self.serialport.flushOutput()
298             
299             for i in range(1,10):
300                 self.readbyte();
301             
302             print "Read %02x %02x %02x %02x" % (
303                 self.readbyte(),self.readbyte(),self.readbyte(),self.readbyte());
304     def monitortest(self):
305         """Self-test several functions through the monitor."""
306         print "Performing monitor self-test.";
307         
308         if self.peekword(0x0c00)!=0x0c04 and self.peekword(0x0c00)!=0x0c06:
309             print "ERROR Fetched wrong value from 0x0c04.";
310         self.pokebyte(0x0021,0); #Drop LED
311         if self.peekbyte(0x0021)!=0:
312             print "ERROR, P1OUT not cleared.";
313         self.pokebyte(0x0021,1); #Light LED
314         
315         print "Self-test complete.";
316     
317     
318     # The following functions ought to be implemented in
319     # every client.
320
321     def infostring(self):
322         a=self.peekbyte(0xff0);
323         b=self.peekbyte(0xff1);
324         return "%02x%02x" % (a,b);
325     def lock(self):
326         print "Locking Unsupported.";
327     def erase(self):
328         print "Erasure Unsupported.";
329     def setup(self):
330         return;
331     def start(self):
332         return;
333     def test(self):
334         print "Unimplemented.";
335         return;
336     def status(self):
337         print "Unimplemented.";
338         return;
339     def halt(self):
340         print "Unimplemented.";
341         return;
342     def resume(self):
343         print "Unimplemented.";
344         return;
345     def getpc(self):
346         print "Unimplemented.";
347         return 0xdead;
348     def flash(self,file):
349         """Flash an intel hex file to code memory."""
350         print "Flash not implemented.";
351     def dump(self,file,start=0,stop=0xffff):
352         """Dump an intel hex file from code memory."""
353         print "Dump not implemented.";
354
355     def peek32(self,address, memory="vn"):
356         return (self.peek16(address,memory)+
357                 (self.peek16(address+2,memory)<<16));
358     def peek16(self,address, memory="vn"):
359         return (self.peek8(address,memory)+
360                 (self.peek8(address+1,memory)<<8));
361     def peek8(self,address, memory="vn"):
362         return self.peekbyte(address); #monitor
363     def loadsymbols(self):
364         return;