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