2 # GoodFET Client Library
4 # (C) 2009 Travis Goodspeed <travis at radiantmachines.com>
6 # This code is being rewritten and refactored. You've been warned!
8 import sys, time, string, cStringIO, struct, glob, serial, os;
11 fmt = ("B", "<H", None, "<L")
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();
21 print "Unsupported target: %s" % name;
25 """GoodFET Symbol Table"""
26 db=sqlite3.connect(":memory:");
28 def __init__(self, *args, **kargs):
29 self.db.execute("create table if not exists symbols(adr,name,memory,size,comment);");
34 c.execute("select adr,memory from symbols where name=?",(name,));
40 except:# sqlite3.OperationalError:
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);
51 """GoodFET Client Library"""
61 symbols=SymbolTable();
63 def __init__(self, *args, **kargs):
66 from GoodFETConsole import GoodFETConsole;
67 return GoodFETConsole(self);
68 def name2adr(self,name):
69 return self.symbols.get(name);
72 def serInit(self, port=None, timeout=None):
73 """Open the serial port"""
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:
80 glob_list = glob.glob("/dev/tty.usbserial*");
81 if len(glob_list) > 0:
84 glob_list = glob.glob("/dev/ttyUSB*");
85 if len(glob_list) > 0:
88 self.serialport = serial.Serial(
92 parity = serial.PARITY_NONE,
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()
104 #Read and handle the initial command.
106 self.readcmd(); #Read the first command.
108 print "Verb %02x is wrong. Incorrect firmware or bad Info guess?" % self.verb;
109 print "http://goodfet.sf.net/faq/";
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));
120 # count=len(data); #Initial count ignored.
122 #print "TX %02x %02x %04x" % (app,verb,count);
124 #little endian 16-bit length
125 self.serialport.write(chr(count&0xFF));
126 self.serialport.write(chr(count>>8));
129 print "Tx: ( 0x%02x, 0x%02x, 0x%04x )" % ( app, verb, count )
131 #print "count=%02x, len(data)=%04x" % (count,len(data));
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]);
139 outstr=''.join(data);
140 self.serialport.write(outstr);
141 if not self.besilent:
142 return self.readcmd()
147 """Read a reply from the GoodFET."""
148 while 1:#self.serialport.inWaiting(): # Loop while input data is available
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;
156 ord(self.serialport.read(1))
157 +(ord(self.serialport.read(1))<<8)
161 print "Rx: ( 0x%02x, 0x%02x, 0x%04x )" % ( self.app, self.verb, self.count )
163 #Debugging string; print, but wait.
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]
171 self.data=self.serialport.read(self.count);
174 print "Error: waiting for serial read timed out (most likely)."
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,
212 #return ord(self.data[0]);
216 def silent(self,s=0):
217 """Transmissions halted when 1."""
219 print "besilent is %i" % self.besilent;
220 self.writecmd(0,0xB0,1,[s]);
223 """Write a byte to P5OUT."""
224 self.writecmd(0,0xA1,1,[byte]);
226 """Write a byte to P5DIR."""
227 self.writecmd(0,0xA0,1,[byte]);
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),
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);
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):
253 print "%04x %04x" % (i, self.peekword(i));
255 def monitor_ram_pattern(self):
256 """Overwrite all of RAM with 0xBEEF."""
257 self.writecmd(0,0x90,0,self.data);
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);
271 def setBaud(self,baud):
272 """Change the baud rate. TODO fix this."""
273 rates=self.baudrates;
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));
281 print "Changed host baud."
282 self.serialport.setBaudrate(rates[baud]);
284 self.serialport.flushInput()
285 self.serialport.flushOutput()
287 print "Baud is now %i." % rates[baud];
290 return ord(self.serialport.read(1));
292 for r in self.baudrates:
293 print "\nTrying %i" % r;
294 self.serialport.setBaudrate(r);
296 self.serialport.flushInput()
297 self.serialport.flushOutput()
299 for i in range(1,10):
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.";
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
315 print "Self-test complete.";
318 # The following functions ought to be implemented in
321 def infostring(self):
322 a=self.peekbyte(0xff0);
323 b=self.peekbyte(0xff1);
324 return "%02x%02x" % (a,b);
326 print "Locking Unsupported.";
328 print "Erasure Unsupported.";
334 print "Unimplemented.";
337 print "Unimplemented.";
340 print "Unimplemented.";
343 print "Unimplemented.";
346 print "Unimplemented.";
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.";
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):