Shellcode is now only loaded when
[goodfet] / client / GoodFETCC.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;
9 import binascii;
10
11 from GoodFET import GoodFET;
12 from intelhex import IntelHex;
13
14 import xml.dom.minidom, time;
15
16 class GoodFETCC(GoodFET):
17     """A GoodFET variant for use with Chipcon 8051 Zigbee SoC."""
18     APP=0x30;
19     
20     
21     
22     
23     smartrfpath="/opt/smartrf7";
24     def loadsymbols(self):
25         try: self.SRF_loadsymbols();
26         except:
27             if self.verbose>0: print "SmartRF not found at %s." % self.smartrfpath;
28     def SRF_chipdom(self,chip="cc1110", doc="register_definition.xml"):
29         fn="%s/config/xml/%s/%s" % (self.smartrfpath,chip,doc);
30         #print "Opening %s" % fn;
31         return xml.dom.minidom.parse(fn)
32         
33     def CMDrs(self,args=[]):
34         """Chip command to grab the radio state."""
35         try:
36             self.SRF_radiostate();
37         except:
38             print "Error printing radio state.";
39             print "SmartRF not found at %s." % self.smartrfpath;
40     def SRF_bitfieldstr(self,bf):
41         name="unused";
42         start=0;
43         stop=0;
44         access="";
45         reset="0x00";
46         description="";
47         for e in bf.childNodes:
48             if e.localName=="Name" and e.childNodes: name= e.childNodes[0].nodeValue;
49             elif e.localName=="Start": start=e.childNodes[0].nodeValue;
50             elif e.localName=="Stop": stop=e.childNodes[0].nodeValue;
51         return "   [%s:%s] %30s " % (start,stop,name);
52     def SRF_radiostate(self):
53         ident=self.CCident();
54         chip=self.CCversions.get(ident&0xFF00);
55         dom=self.SRF_chipdom(chip,"register_definition.xml");
56         for e in dom.getElementsByTagName("registerdefinition"):
57             for f in e.childNodes:
58                 if f.localName=="DeviceName":
59                     print "// %s RadioState" % (f.childNodes[0].nodeValue);
60                 elif f.localName=="Register":
61                     name="unknownreg";
62                     address="0xdead";
63                     description="";
64                     bitfields="";
65                     for g in f.childNodes:
66                         if g.localName=="Name":
67                             name=g.childNodes[0].nodeValue;
68                         elif g.localName=="Address":
69                             address=g.childNodes[0].nodeValue;
70                         elif g.localName=="Description":
71                             if g.childNodes:
72                                 description=g.childNodes[0].nodeValue;
73                         elif g.localName=="Bitfield":
74                             bitfields+="%17s/* %-50s */\n" % ("",self.SRF_bitfieldstr(g));
75                     #print "SFRX(%10s, %s); /* %50s */" % (name,address, description);
76                     print "%-10s=0x%02x; /* %-50s */" % (
77                         name,self.CCpeekdatabyte(eval(address)), description);
78                     if bitfields!="": print bitfields.rstrip();
79     def RF_setfreq(self,frequency):
80         """Set the frequency in Hz."""
81         #FIXME CC1110 specific
82         #Some frequencies fail, probably and FSCAL thing.
83         
84         hz=frequency;
85         freq=int(hz/396.728515625);
86         
87         freq0=freq&0xFF;
88         freq1=(freq&0xFF00)>>8;
89         freq2=(freq&0xFF0000)>>16;
90         
91         self.pokebysym("FREQ2",freq2);
92         self.pokebysym("FREQ1",freq1);
93         self.pokebysym("FREQ0",freq0);
94         
95         self.pokebysym("TEST1",0x31);
96         self.pokebysym("TEST0",0x09);
97         
98         #self.pokebysym("PA_TABLE0" ,   0x60);  #above mid
99         
100         #self.pokebysym("FSCAL2" ,   0x2A);  #above mid
101         self.pokebysym("FSCAL2" ,   0x0A);  #beneath mid
102         
103         #self.CC_RFST_CAL(); #SCAL
104         #time.sleep(1);
105     
106         
107     def RF_getfreq(self):
108         """Get the frequency in Hz."""
109         #FIXME CC1110 specific
110         
111         #return (2400+self.peek(0x05))*10**6
112         #self.poke(0x05,chan);
113         
114         #freq2=self.CCpeekdatabyte(0xdf09);
115         #freq1=self.CCpeekdatabyte(0xdf0a);
116         #freq0=self.CCpeekdatabyte(0xdf0b);
117         freq=0;
118         try:
119             freq2=self.peekbysym("FREQ2");
120             freq1=self.peekbysym("FREQ1");
121             freq0=self.peekbysym("FREQ0");
122             freq=(freq2<<16)+(freq1<<8)+freq0;
123         except:
124             freq=0;
125             
126         hz=freq*396.728515625;
127         
128         return hz;
129     lastshellcode="none";
130     def shellcodefile(self,filename,wait=1):
131         """Run a fragment of shellcode by name."""
132         #FIXME: should identify chip model number, use shellcode for that chip.
133         
134         if self.lastshellcode!=filename:
135             self.lastshellcode=filename;
136             file=__file__;
137             file=file.replace("GoodFETCC.pyc","GoodFETCC.py");
138             path=file.replace("client/GoodFETCC.py","shellcode/chipcon/cc1110/");
139             filename=path+filename;
140         
141             #Load the shellcode.
142             h=IntelHex(filename);
143             for i in h._buf.keys():
144                 self.CCpokedatabyte(i,h[i]);
145         
146         #Execute it.
147         self.CCdebuginstr([0x02, 0xf0, 0x00]); #ljmp 0xF000
148         self.resume();
149         while wait>0 and (0==self.CCstatus()&0x20):
150             a=1;
151             #time.sleep(0.1);
152             #print "Waiting for shell code to return.";
153         return;
154     def ishalted(self):
155         return self.CCstatus()&0x20;
156     def shellcode(self,code,wait=1):
157         """Copy a block of code into RAM and execute it."""
158         i=0;
159         ram=0xF000;
160         for byte in code:
161             self.pokebyte(0xF000+i,byte);
162             i=i+1;
163         #print "Code loaded, executing."
164         self.CCdebuginstr([0x02, 0xf0, 0x00]); #ljmp 0xF000
165         self.resume();
166         while wait>0 and (0==self.CCstatus()&0x20):
167             a=1;
168             #time.sleep(0.1);
169             #print "Waiting for shell code to return.";
170         return;
171     def CC1110_crystal(self):
172         """Start the main crystal of the CC1110 oscillating, needed for radio use."""
173         code=[0x53, 0xBE, 0xFB, #anl SLEEP, #0xFB
174               #one:
175               0xE5, 0xBE,       #mov a,SLEEP
176               0x30, 0xE6, 0xFB, #jnb acc.6, back
177               0x53, 0xc6, 0xB8, #anl CLKCON, #0xB8
178               #two
179               0xE5, 0xC6,       #mov a,CLKCON
180               0x20, 0xE6, 0xFB, #jb acc.6, two
181               0x43, 0xBE, 0x04, #orl SLEEP, #0x04
182               0xA5,             #HALT
183               ];
184         self.shellcode(code);
185         
186         #Slower to load, but produced from C.
187         #self.shellcodefile("crystal.ihx");
188         return;
189     def RF_idle(self):
190         """Move the radio to its idle state."""
191         self.CC_RFST_IDLE();
192         return;
193     
194     #Chipcon RF strobes.  CC1110 specific
195     RFST_IDLE=0x04;
196     RFST_RX=0x02;
197     RFST_TX=0x03;
198     RFST_CAL=0x01;
199     def CC_RFST_IDLE(self):
200         """Switch the radio to idle mode, clearing overflows and errors."""
201         self.CC_RFST(self.RFST_IDLE);
202     def CC_RFST_TX(self):
203         """Switch the radio to TX mode."""
204         self.CC_RFST(self.RFST_TX);
205     def CC_RFST_RX(self):
206         """Switch the radio to RX mode."""
207         self.CC_RFST(self.RFST_RX);
208     def CC_RFST_CAL(self):
209         """Calibrate strobe the radio."""
210         self.CC_RFST(self.RFST_CAL);
211     def CC_RFST(self,state=RFST_IDLE):
212         RFST=0xDFE1
213         self.pokebyte(RFST,state); #Return to idle state.
214         return;
215         
216     def config_simpliciti(self,band="none"):
217         self.pokebysym("FSCTRL1"  , 0x08)   # Frequency synthesizer control.
218         self.pokebysym("FSCTRL0"  , 0x00)   # Frequency synthesizer control.
219         
220         #Don't change these while the radio is active.
221         self.pokebysym("FSCAL3"   , 0xEA)   # Frequency synthesizer calibration.
222         self.pokebysym("FSCAL2"   , 0x2A)   # Frequency synthesizer calibration.
223         self.pokebysym("FSCAL1"   , 0x00)   # Frequency synthesizer calibration.
224         self.pokebysym("FSCAL0"   , 0x1F)   # Frequency synthesizer calibration.
225         
226         if band=="ismeu" or band=="eu":
227             self.pokebysym("FREQ2"    , 0x21)   # Frequency control word, high byte.
228             self.pokebysym("FREQ1"    , 0x71)   # Frequency control word, middle byte.
229             self.pokebysym("FREQ0"    , 0x7a)   # Frequency control word, low byte.
230         elif band=="ismus" or band=="us":
231             self.pokebysym("FREQ2"    , 0x22)   # Frequency control word, high byte.
232             self.pokebysym("FREQ1"    , 0xB1)   # Frequency control word, middle byte.
233             self.pokebysym("FREQ0"    , 0x3B)   # Frequency control word, low byte.
234         elif band=="ismlf" or band=="lf":
235             self.pokebysym("FREQ2"    , 0x10)   # Frequency control word, high byte.
236             self.pokebysym("FREQ1"    , 0xB0)   # Frequency control word, middle byte.
237             self.pokebysym("FREQ0"    , 0x71)   # Frequency control word, low byte.
238         elif band=="none":
239             band="none";
240         else:
241             #Got a frequency, not a band.
242             self.RF_setfreq(eval(band));
243         self.pokebysym("MDMCFG4"  , 0x7B)   # Modem configuration.
244         self.pokebysym("MDMCFG3"  , 0x83)   # Modem configuration.
245         self.pokebysym("MDMCFG2"  , 0x13)   # Modem configuration.
246         self.pokebysym("MDMCFG1"  , 0x22)   # Modem configuration.
247         self.pokebysym("MDMCFG0"  , 0xF8)   # Modem configuration.
248         if band=="ismus" or band=="us":
249             self.pokebysym("CHANNR"   , 20)   # Channel number.
250         else:
251             self.pokebysym("CHANNR"   , 0x00)   # Channel number.
252         self.pokebysym("DEVIATN"  , 0x42)   # Modem deviation setting (when FSK modulation is enabled).
253         
254         self.pokebysym("FREND1"   , 0xB6)   # Front end RX configuration.
255         self.pokebysym("FREND0"   , 0x10)   # Front end RX configuration.
256         self.pokebysym("MCSM0"    , 0x18)   # Main Radio Control State Machine configuration.
257         self.pokebysym("FOCCFG"   , 0x1D)   # Frequency Offset Compensation Configuration.
258         self.pokebysym("BSCFG"    , 0x1C)   # Bit synchronization Configuration.
259         
260         self.pokebysym("AGCCTRL2" , 0xC7)   # AGC control.
261         self.pokebysym("AGCCTRL1" , 0x00)   # AGC control.
262         self.pokebysym("AGCCTRL0" , 0xB2)   # AGC control.
263         
264         self.pokebysym("TEST2"    , 0x81)   # Various test settings.
265         self.pokebysym("TEST1"    , 0x35)   # Various test settings.
266         self.pokebysym("TEST0"    , 0x09)   # Various test settings.
267         self.pokebysym("PA_TABLE0", 0xC0)   # PA output power setting.
268         self.pokebysym("PKTCTRL1" , 0x04)   # Packet automation control, w/ lqi
269         #self.pokebysym("PKTCTRL1" , 0x00)   # Packet automation control. w/o lqi
270         self.pokebysym("PKTCTRL0" , 0x05)   # Packet automation control, w/ checksum.
271         #self.pokebysym("PKTCTRL0" , 0x00)   # Packet automation control, w/o checksum, fixed length
272         self.pokebysym("ADDR"     , 0x01)   # Device address.
273         self.pokebysym("PKTLEN"   , 0xFF)   # Packet length.
274         
275         self.pokebysym("SYNC1",0xD3);
276         self.pokebysym("SYNC0",0x91);
277         
278     def RF_carrier(self):
279         """Hold a carrier wave on the present frequency."""
280         
281         self.CC1110_crystal(); #FIXME, '1110 specific.
282         self.RF_idle();
283         
284         
285         RFST=0xDFE1;
286         
287         self.config_simpliciti();
288         
289         #Don't change these while the radio is active.
290         #self.pokebysym("FSCAL3"   , 0xA9)   # Frequency synthesizer calibration.
291         #self.pokebysym("FSCAL2"   , 0x0A)   # Frequency synthesizer calibration.
292         #self.pokebysym("FSCAL1"   , 0x00)   # Frequency synthesizer calibration.
293         #self.pokebysym("FSCAL0"   , 0x11)   # Frequency synthesizer calibration.
294         
295         #Ramp up the power.
296         #self.pokebysym("PA_TABLE0", 0xFF)   # PA output power setting.
297         
298         #This is what drops to OOK.
299         #Comment to keep GFSK, might be better at jamming.
300         self.pokebysym("MDMCFG4"  , 0x86)   # Modem configuration.
301         self.pokebysym("MDMCFG3"  , 0x83)   # Modem configuration.
302         self.pokebysym("MDMCFG2"  , 0x30)   # Modem configuration.
303         self.pokebysym("MDMCFG1"  , 0x22)   # Modem configuration.
304         self.pokebysym("MDMCFG0"  , 0xF8)   # Modem configuration.
305         
306         
307         self.pokebysym("SYNC1",0xAA);
308         self.pokebysym("SYNC0",0xAA);
309         
310         
311         
312         #while ((MARCSTATE & MARCSTATE_MARC_STATE) != MARC_STATE_TX); 
313         state=0;
314         
315         while((state!=0x13)):
316             self.pokebyte(RFST,0x03); #RFST=RFST_STX
317             time.sleep(0.1);
318             state=self.peekbysym("MARCSTATE")&0x1F;
319             #print "state=%02x" % state;
320         print "Holding a carrier on %f MHz." % (self.RF_getfreq()/10**6);
321         
322         return;
323             
324     def RF_getsmac(self):
325         """Return the source MAC address."""
326         
327         #Register 0A is RX_ADDR_P0, five bytes.
328         mac=self.peekbysym("ADDR");
329         return mac;
330     def RF_setsmac(self,mac):
331         """Set the source MAC address."""
332         self.pokebysym("ADDR",mac);
333         return 0;
334     def RF_gettmac(self):
335         """Return the target MAC address."""
336         return 0;
337     def RF_settmac(self,mac):
338         """Set the target MAC address."""
339         return 0;
340     def RF_rxpacket(self):
341         """Get a packet from the radio.  Returns None if none is waiting."""
342         self.shellcodefile("rxpacket.ihx");
343         len=self.peek8(0xFE00,"xdata");
344         return self.peekblock(0xFE00,len+1,"data");
345     def RF_txpacket(self,packet):
346         """Transmit a packet.  Untested."""
347         
348         self.pokeblock(0xFE00,packet,"data");
349         self.shellcodefile("txpacket.ihx");
350         return;
351     def RF_txrxpacket(self,packet):
352         """Transmit a packet.  Untested."""
353         
354         self.pokeblock(0xFE00,packet,"data");
355         self.shellcodefile("txrxpacket.ihx");
356         len=self.peek8(0xFE00,"xdata");
357         return self.peekblock(0xFE00,len+1,"data");
358
359     def RF_getrssi(self):
360         """Returns the received signal strenght, with a weird offset."""
361         try:
362             rssireg=self.symbols.get("RSSI");
363             return self.CCpeekdatabyte(rssireg)^0x80;
364         except:
365             if self.verbose>0: print "RSSI reg doesn't exist.";
366         try:
367             #RSSI doesn't exist on 2.4GHz devices.  Maybe RSSIL and RSSIH?
368             rssilreg=self.symbols.get("RSSIL");
369             rssil=self.CCpeekdatabyte(rssilreg);
370             rssihreg=self.symbols.get("RSSIL");
371             rssih=self.CCpeekdatabyte(rssihreg);
372             return (rssih<<8)|rssil;
373         except:
374             if self.verbose>0: print "RSSIL/RSSIH regs don't exist.";
375         
376         return 0;
377     
378     
379     
380     def SRF_loadsymbols(self):
381         ident=self.CCident();
382         chip=self.CCversions.get(ident&0xFF00);
383         dom=self.SRF_chipdom(chip,"register_definition.xml");
384         for e in dom.getElementsByTagName("registerdefinition"):
385             for f in e.childNodes:
386                 if f.localName=="Register":
387                     name="unknownreg";
388                     address="0xdead";
389                     description="";
390                     bitfields="";
391                     for g in f.childNodes:
392                         if g.localName=="Name":
393                             name=g.childNodes[0].nodeValue;
394                         elif g.localName=="Address":
395                             address=g.childNodes[0].nodeValue;
396                         elif g.localName=="Description":
397                             if g.childNodes:
398                                 description=g.childNodes[0].nodeValue;
399                         elif g.localName=="Bitfield":
400                             bitfields+="%17s/* %-50s */\n" % ("",self.SRF_bitfieldstr(g));
401                     #print "SFRX(%10s, %s); /* %50s */" % (name,address, description);
402                     self.symbols.define(eval(address),name,description,"data");
403     def halt(self):
404         """Halt the CPU."""
405         self.CChaltcpu();
406     def CChaltcpu(self):
407         """Halt the CPU."""
408         self.writecmd(self.APP,0x86,0,self.data);
409     def resume(self):
410         self.CCreleasecpu();
411     def CCreleasecpu(self):
412         """Resume the CPU."""
413         self.writecmd(self.APP,0x87,0,self.data);
414     def test(self):
415         self.CCreleasecpu();
416         self.CChaltcpu();
417         #print "Status: %s" % self.CCstatusstr();
418         
419         #Grab ident three times, should be equal.
420         ident1=self.CCident();
421         ident2=self.CCident();
422         ident3=self.CCident();
423         if(ident1!=ident2 or ident2!=ident3):
424             print "Error, repeated ident attempts unequal."
425             print "%04x, %04x, %04x" % (ident1, ident2, ident3);
426         
427         #Single step, printing PC.
428         print "Tracing execution at startup."
429         for i in range(1,15):
430             pc=self.CCgetPC();
431             byte=self.CCpeekcodebyte(i);
432             #print "PC=%04x, %02x" % (pc, byte);
433             self.CCstep_instr();
434         
435         print "Verifying that debugging a NOP doesn't affect the PC."
436         for i in range(1,15):
437             pc=self.CCgetPC();
438             self.CCdebuginstr([0x00]);
439             if(pc!=self.CCgetPC()):
440                 print "ERROR: PC changed during CCdebuginstr([NOP])!";
441         
442         print "Checking pokes to XRAM."
443         for i in range(0xf000,0xf020):
444             self.CCpokedatabyte(i,0xde);
445             if(self.CCpeekdatabyte(i)!=0xde):
446                 print "Error in XDATA at 0x%04x" % i;
447         
448         #print "Status: %s." % self.CCstatusstr();
449         #Exit debugger
450         self.stop();
451         print "Done.";
452
453     def setup(self):
454         """Move the FET into the CC2430/CC2530 application."""
455         #print "Initializing Chipcon.";
456         self.writecmd(self.APP,0x10,0,self.data);
457     def CCrd_config(self):
458         """Read the config register of a Chipcon."""
459         self.writecmd(self.APP,0x82,0,self.data);
460         return ord(self.data[0]);
461     def CCwr_config(self,config):
462         """Write the config register of a Chipcon."""
463         self.writecmd(self.APP,0x81,1,[config&0xFF]);
464     def CClockchip(self):
465         """Set the flash lock bit in info mem."""
466         self.writecmd(self.APP, 0x9A, 0, None);
467     def lock(self):
468         """Set the flash lock bit in info mem."""
469         self.CClockchip();
470     
471
472     CCversions={0x0100:"cc1110",
473                 0x1100:"cc1111",
474                 0x8500:"cc2430",
475                 0x8900:"cc2431",
476                 0x8100:"cc2510",
477                 0x9100:"cc2511",
478                 0xA500:"cc2530", #page 52 of SWRU191
479                 0xB500:"cc2531",
480                 0xFF00:"CCmissing"};
481     CCpagesizes={0x01: 1024, #"CC1110",
482                  0x11: 1024, #"CC1111",
483                  0x85: 2048, #"CC2430",
484                  0x89: 2048, #"CC2431",
485                  0x81: 1024, #"CC2510",
486                  0x91: 1024, #"CC2511",
487                  0xA5: 2048, #"CC2530", #page 52 of SWRU191
488                  0xB5: 2048, #"CC2531",
489                  0xFF: 0    } #"CCmissing"};
490     def infostring(self):
491         return self.CCidentstr();
492     def CCidentstr(self):
493         ident=self.CCident();
494         chip=self.CCversions.get(ident&0xFF00);
495         pagesize=self.CCpagesizes.get(ident>0xFF);
496         try:
497             return "%s/r%0.4x/ps0x%0.4x" % (chip, ident, pagesize); 
498         except:
499             return "%04x" % ident;
500     def CCident(self):
501         """Get a chipcon's ID."""
502         self.writecmd(self.APP,0x8B,0,None);
503         chip=ord(self.data[0]);
504         rev=ord(self.data[1]);
505         return (chip<<8)+rev;
506     def CCpagesize(self):
507         """Get a chipcon's ID."""
508         self.writecmd(self.APP,0x8B,0,None);
509         chip=ord(self.data[0]);
510         size=self.CCpagesizes.get(chip);
511         if(size<10):
512             print "ERROR: Pagesize undefined.";
513             print "chip=%0.4x" %chip;
514             sys.exit(1);
515             #return 2048;
516         return size;
517     def getpc(self):
518         return self.CCgetPC();
519     def CCgetPC(self):
520         """Get a chipcon's PC."""
521         self.writecmd(self.APP,0x83,0,None);
522         hi=ord(self.data[0]);
523         lo=ord(self.data[1]);
524         return (hi<<8)+lo;
525     def CCcmd(self,phrase):
526         self.writecmd(self.APP,0x00,len(phrase),phrase);
527         val=ord(self.data[0]);
528         print "Got %02x" % val;
529         return val;
530     def CCdebuginstr(self,instr):
531         self.writecmd(self.APP,0x88,len(instr),instr);
532         return ord(self.data[0]);
533     #def peekblock(self,adr,length,memory="vn"):
534     #    """Return a block of data, broken"""
535     #    data=[adr&0xff, (adr&0xff00)>>8,
536     #          length&0xFF,(length&0xFF00)>>8];
537     #    self.writecmd(self.APP,0x91,4,data);
538     #    return [ord(x) for x in self.data]
539     def peek8(self,address, memory="code"):
540         if(memory=="code" or memory=="flash" or memory=="vn"):
541             return self.CCpeekcodebyte(address);
542         elif(memory=="data" or memory=="xdata" or memory=="ram"):
543             return self.CCpeekdatabyte(address);
544         elif(memory=="idata" or memory=="iram"):
545             return self.CCpeekirambyte(address);
546         print "%s is an unknown memory." % memory;
547         return 0xdead;
548     def CCpeekcodebyte(self,adr):
549         """Read the contents of code memory at an address."""
550         self.data=[adr&0xff, (adr&0xff00)>>8];
551         self.writecmd(self.APP,0x90,2,self.data);
552         return ord(self.data[0]);
553     def CCpeekdatabyte(self,adr):
554         """Read the contents of data memory at an address."""
555         self.data=[adr&0xff, (adr&0xff00)>>8];
556         self.writecmd(self.APP,0x91, 2, self.data);
557         return ord(self.data[0]);
558     def CCpeekirambyte(self,adr):
559         """Read the contents of IRAM at an address."""
560         self.data=[adr&0xff];
561         self.writecmd(self.APP,0x02, 1, self.data);
562         return ord(self.data[0]);
563     def CCpeekiramword(self,adr):
564         """Read the little-endian contents of IRAM at an address."""
565         return self.CCpeekirambyte(adr)+(
566             self.CCpeekirambyte(adr+1)<<8);
567     def CCpokeiramword(self,adr,val):
568         self.CCpokeirambyte(adr,val&0xff);
569         self.CCpokeirambyte(adr+1,(val>>8)&0xff);
570     def CCpokeirambyte(self,adr,val):
571         """Write the contents of IRAM at an address."""
572         self.data=[adr&0xff, val&0xff];
573         self.writecmd(self.APP,0x02, 2, self.data);
574         return ord(self.data[0]);
575     def pokebyte(self,adr,val,mem="xdata"):
576         self.CCpokedatabyte(adr,val);
577     def CCpokedatabyte(self,adr,val):
578         """Write a byte to data memory."""
579         self.data=[adr&0xff, (adr&0xff00)>>8, val];
580         self.writecmd(self.APP, 0x92, 3, self.data);
581         return ord(self.data[0]);
582     def CCchiperase(self):
583         """Erase all of the target's memory."""
584         self.writecmd(self.APP,0x80,0,None);
585     def erase(self):
586         """Erase all of the target's memory."""
587         self.CCchiperase();
588         self.start();
589     
590     def CCstatus(self):
591         """Check the status."""
592         self.writecmd(self.APP,0x84,0,None);
593         return ord(self.data[0])
594     #Same as CC2530
595     CCstatusbits={0x80 : "erase_busy",
596                   0x40 : "pcon_idle",
597                   0x20 : "cpu_halted",
598                   0x10 : "pm0",
599                   0x08 : "halt_status",
600                   0x04 : "locked",
601                   0x02 : "oscstable",
602                   0x01 : "overflow"
603                   };
604     CCconfigbits={0x20 : "soft_power_mode",   #new for CC2530
605                   0x08 : "timers_off",
606                   0x04 : "dma_pause",
607                   0x02 : "timer_suspend",
608                   0x01 : "sel_flash_info_page" #stricken from CC2530
609                   };
610                   
611     def status(self):
612         """Check the status as a string."""
613         status=self.CCstatus();
614         str="";
615         i=1;
616         while i<0x100:
617             if(status&i):
618                 str="%s %s" %(self.CCstatusbits[i],str);
619             i*=2;
620         return str;
621     def start(self):
622         """Start debugging."""
623         self.setup();
624         self.writecmd(self.APP,0x20,0,self.data);
625         ident=self.CCidentstr();
626         #print "Target identifies as %s." % ident;
627         #print "Status: %s." % self.status();
628         self.CCreleasecpu();
629         self.CChaltcpu();
630         #Get SmartRF Studio regs if they exist.
631         self.loadsymbols(); 
632         
633     def stop(self):
634         """Stop debugging."""
635         self.writecmd(self.APP,0x21,0,self.data);
636     def CCstep_instr(self):
637         """Step one instruction."""
638         self.writecmd(self.APP,0x89,0,self.data);
639     def CCeraseflashbuffer(self):
640         """Erase the 2kB flash buffer"""
641         self.writecmd(self.APP,0x99);
642     def CCflashpage(self,adr):
643         """Flash 2kB a page of flash from 0xF000 in XDATA"""
644         data=[adr&0xFF,
645               (adr>>8)&0xFF,
646               (adr>>16)&0xFF,
647               (adr>>24)&0xFF];
648         print "Flashing buffer to 0x%06x" % adr;
649         self.writecmd(self.APP,0x95,4,data);
650     
651     def setsecret(self,value):
652         """Set a secret word for later retreival.  Used by glitcher."""
653         page = 0x0000;
654         pagelen = self.CCpagesize(); #Varies by chip.
655         print "page=%04x, pagelen=%04x" % (page,pagelen);
656         
657         self.CCeraseflashbuffer();
658         print "Setting secret to %x" % value;
659         self.CCpokedatabyte(0xF000,value);
660         self.CCpokedatabyte(0xF800,value);
661         print "Setting secret to %x==%x" % (value,
662                                             self.CCpeekdatabyte(0xf000));
663         self.CCflashpage(0);
664         print "code[0]=%x" % self.CCpeekcodebyte(0);
665     def getsecret(self):
666         """Get a secret word.  Used by glitcher."""
667         secret=self.CCpeekcodebyte(0);
668         #print "Got secret %02x" % secret;
669         return secret;
670     
671     def dump(self,file,start=0,stop=0xffff):
672         """Dump an intel hex file from code memory."""
673         print "Dumping code from %04x to %04x as %s." % (start,stop,file);
674         h = IntelHex(None);
675         i=start;
676         while i<=stop:
677             h[i]=self.CCpeekcodebyte(i);
678             if(i%0x100==0):
679                 print "Dumped %04x."%i;
680                 h.write_hex_file(file); #buffer to disk.
681             i+=1;
682         h.write_hex_file(file);
683
684     def flash(self,file):
685         """Flash an intel hex file to code memory."""
686         print "Flashing %s" % file;
687         
688         h = IntelHex(file);
689         page = 0x0000;
690         pagelen = self.CCpagesize(); #Varies by chip.
691         
692         #print "page=%04x, pagelen=%04x" % (page,pagelen);
693         
694         bcount = 0;
695         
696         #Wipe the RAM buffer for the next flash page.
697         self.CCeraseflashbuffer();
698         for i in h._buf.keys():
699             while(i>=page+pagelen):
700                 if bcount>0:
701                     self.CCflashpage(page);
702                     #client.CCeraseflashbuffer();
703                     bcount=0;
704                     print "Flashed page at %06x" % page
705                 page+=pagelen;
706                     
707             #Place byte into buffer.
708             self.CCpokedatabyte(0xF000+i-page,
709                                 h[i]);
710             bcount+=1;
711             if(i%0x100==0):
712                 print "Buffering %04x toward %06x" % (i,page);
713         #last page
714         self.CCflashpage(page);
715         print "Flashed final page at %06x" % page;
716