change number of failures to mean the number actually injected as opposed to the...
[IRC.git] / Robust / src / Runtime / runtime.c
1 #include "runtime.h"
2 #include "structdefs.h"
3 #include <string.h>
4 #include <signal.h>
5 #include "mem.h"
6 #include<fcntl.h>
7 #include<sys/types.h>
8 #include<sys/mman.h>
9 #include<errno.h>
10 #include<signal.h>
11 #include<stdio.h>
12
13 extern int classsize[];
14 jmp_buf error_handler;
15 int instructioncount;
16
17 #ifdef TASK
18 #include "checkpoint.h"
19 #include "Queue.h"
20 #include "SimpleHash.h"
21 #include "GenericHashtable.h"
22 #include <sys/select.h>
23
24 #ifdef CONSCHECK
25 #include "instrument.h"
26 #endif
27
28 struct Queue * activetasks;
29 struct parameterwrapper * objectqueues[NUMCLASSES];
30 struct genhashtable * failedtasks;
31 /*struct genhashtable * failedobjects;*/
32 extern char ** environ;
33 char *options;
34 int injectfailures=0;
35 float failurechance=0;
36 int debugtask=0;
37 int injectinstructionfailures;
38 int failurecount;
39 float instfailurechance=0;
40 int numfailures;
41 int instaccum=0;
42
43 void processOptions() {
44   int i;
45   options=NULL;
46   for(i=0;environ[i]!=0;i++) {
47     if (strncmp(environ[i],"BRISTLECONE=",12)==0) {
48       options=environ[i]+12;
49       break;
50     }
51   }
52   
53   while(options!=NULL) {
54     if (strncmp(options,"-injectfailures",sizeof("-injectfailures")-1)==0) {
55       options=strchr(options,' ');
56       if (options!=NULL) options++;
57       if (options==NULL)
58         break;
59       sscanf(options, "%f", &failurechance);
60       injectfailures=1;
61       printf("Injecting errors with chance=%f\n",failurechance);
62       options=strchr(options,' ');
63       if (options!=NULL) options++;
64     } else if (strncmp(options,"-injectinstructionfailures",sizeof("-injectinstructionfailures")-1)==0) {
65       options=strchr(options,' ');
66       if (options!=NULL) options++;
67       if (options==NULL)
68         break;
69       sscanf(options, "%d", &failurecount);
70       options=strchr(options,' ');
71       if (options!=NULL) options++;
72       if (options==NULL)
73         break;
74
75       sscanf(options, "%f", &instfailurechance);
76       options=strchr(options,' ');
77       if (options!=NULL) options++;
78       if (options==NULL)
79         break;
80
81       sscanf(options, "%d", &numfailures);
82       options=strchr(options,' ');
83       if (options!=NULL) options++;
84
85       instaccum=failurecount;
86       instructioncount=failurecount;
87       injectinstructionfailures=1;
88       printf("Number of failures=%d\n",numfailures);
89       printf("Injecting errors with count=%d\n",failurecount);
90       printf("Injecting errors with chance=%f\n",instfailurechance);
91     } else if (strncmp(options, "-debugtask",sizeof("-debugtask")-1)==0) {
92       options=strchr(options,' ');
93       if (options!=NULL) options++;
94       debugtask=1;
95       printf("Debug task option on.\n");
96     } else if (strncmp(options, "-initializerandom", sizeof("-initializerandom")-1)==0) {
97       options=strchr(options,' ');
98       if (options!=NULL) options++;
99       printf("Initializing random number generator.\n");
100       srandomdev();
101     } else
102       break;
103   }
104 }
105
106 int main(int argc, char **argv) {
107   GC_init(); // Initialize the garbage collector
108 #ifdef CONSCHECK
109   initializemmap();
110 #endif
111   processOptions();
112
113   {
114   int i;
115   /* Allocate startup object */
116   struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(STARTUPTYPE);
117   struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1); 
118   failedtasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, 
119                                    (int (*)(void *,void *)) &comparetpd);
120   /*  failedobjects=genallocatehashtable(NULL,NULL);*/
121   
122   activetasks=createQueue();
123
124   /* Set flags */
125   processtasks();
126   flagorand(startupobject,1,0xFFFFFFFF);
127
128   /* Build array of strings */
129
130   startupobject->___parameters___=stringarray;
131
132   for(i=1;i<argc;i++) {
133     int length=strlen(argv[i]);
134     struct ___String___ *newstring=NewString(argv[i],length);
135     ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;
136   }
137   executetasks();
138   }
139 }
140
141 int hashCodetpd(struct taskparamdescriptor *ftd) {
142   int hash=(int)ftd->task;
143   int i;
144   for(i=0;i<ftd->numParameters;i++) {
145     hash^=(int)ftd->parameterArray[i];
146   }
147   return hash;
148 }
149
150 int comparetpd(struct taskparamdescriptor *ftd1, struct taskparamdescriptor *ftd2) {
151   int i;
152   if (ftd1->task!=ftd2->task)
153     return 0;
154   for(i=0;i<ftd1->numParameters;i++)
155     if (ftd1->parameterArray[i]!=ftd2->parameterArray[i])
156       return 0;
157   return 1;
158 }
159
160 void flagorand(void * ptr, int ormask, int andmask) {
161   int flag=((int *)ptr)[1];
162   struct RuntimeHash *flagptr=(struct RuntimeHash *)(((int*)ptr)[2]);
163   flag|=ormask;
164   flag&=andmask;
165   ((int*)ptr)[1]=flag;
166   /*Remove from all queues */
167   while(flagptr!=NULL) {
168     struct RuntimeHash *next;
169     RuntimeHashget(flagptr, (int) ptr, (int *) &next);
170     RuntimeHashremove(flagptr, (int)ptr, (int) next);
171     flagptr=next;
172   }
173   
174   {
175     struct QueueItem *tmpptr;
176     struct parameterwrapper * parameter=objectqueues[((int *)ptr)[0]];
177     int i;
178     struct RuntimeHash * prevptr=NULL;
179     while(parameter!=NULL) {
180       for(i=0;i<parameter->numberofterms;i++) {
181         int andmask=parameter->intarray[i*2];
182         int checkmask=parameter->intarray[i*2+1];
183         if ((flag&andmask)==checkmask) {
184           RuntimeHashadd(parameter->objectset, (int) ptr, (int) prevptr);
185           prevptr=parameter->objectset;
186           {
187             struct RuntimeIterator iteratorarray[MAXTASKPARAMS];
188             void * taskpointerarray[MAXTASKPARAMS];
189             int j;
190             int numparams=parameter->task->numParameters;
191             int done=1;
192             struct taskdescriptor * task=parameter->task;
193             int newindex=-1;
194             for(j=0;j<numparams;j++) {
195               struct parameterwrapper *pw=(struct parameterwrapper *)task->descriptorarray[j]->queue;
196               if (parameter==pw) {
197                 taskpointerarray[j]=ptr;
198                 newindex=j;
199               } else {
200                 RuntimeHashiterator(pw->objectset, &iteratorarray[j]);
201                 if (RunhasNext(&iteratorarray[j])) {
202                   taskpointerarray[j]=(void *) Runkey(&iteratorarray[j]);
203                   Runnext(&iteratorarray[j]);
204                 } else {
205                   done=0;
206                   break; /* No tasks to dispatch */
207                 }
208               }
209             }
210             /* Queue task items... */
211
212             while(done) {
213               struct taskparamdescriptor *tpd=RUNMALLOC(sizeof(struct taskparamdescriptor));
214               tpd->task=task;
215               tpd->numParameters=numparams;
216               tpd->parameterArray=RUNMALLOC(sizeof(void *)*numparams);
217               for(j=0;j<numparams;j++)
218                 tpd->parameterArray[j]=taskpointerarray[j];
219               /* Queue task */
220               if (!gencontains(failedtasks, tpd))
221                 addNewItem(activetasks, tpd);
222               
223               /* This loop iterates to the next parameter combination */
224               for(j=0;j<numparams;j++) {
225                 if (j==newindex) {
226                   if ((j+1)==numparams)
227                     done=0;
228                   continue;
229                 }
230                 if (RunhasNext(&iteratorarray[j])) {
231                   taskpointerarray[j]=(void *) Runkey(&iteratorarray[j]);
232                   Runnext(&iteratorarray[j]);
233                   break;
234                 } else if ((j+1)!=numparams) {
235                   RuntimeHashiterator(task->descriptorarray[j]->queue, &iteratorarray[j]);
236                 } else {
237                   done=0;
238                   break;
239                 }
240               }
241             }
242           }
243           break;
244         }
245       }
246       parameter=parameter->next;
247     }
248     ((struct RuntimeHash **)ptr)[2]=prevptr;
249   }
250 }
251
252 /* Handler for signals. The signals catch null pointer errors and
253    arithmatic errors. */
254 void myhandler(int sig, siginfo_t *info, void *uap) {
255 #ifdef DEBUG
256   printf("sig=%d\n",sig);
257   printf("signal\n");
258 #endif
259   longjmp(error_handler,1);
260 }
261
262 fd_set readfds;
263 int maxreadfd;
264 struct RuntimeHash *fdtoobject;
265
266 void addreadfd(int fd) {
267   if (fd>=maxreadfd)
268     maxreadfd=fd+1;
269   FD_SET(fd, &readfds);
270 }
271
272 void removereadfd(int fd) {
273   FD_CLR(fd, &readfds);
274   if (maxreadfd==(fd+1)) {
275     maxreadfd--;
276     while(maxreadfd>0&&!FD_ISSET(maxreadfd-1, &readfds))
277       maxreadfd--;
278   }
279 }
280
281 /*
282 void restoreObject(void * obj) {
283   if (gencontains(failedobjects, obj)) {
284     struct tpdlist *tpd=gengettable(failedobjects, obj);
285     genfreekey(failedobjects, obj);
286     while(tpd!=NULL) {
287       int i;
288       struct taskparamdescriptor *task=tpd->task;
289       genfreekey(failedtasks, task);
290       for(i=0;i<task->numParameters;i++) {
291         void *objother=task->parameterArray[i];
292         struct tpdlist *tpdother=gengettable(failedobjects, objother);
293         struct tpdlist *tmpptr;
294         genfreekey(failedobjects, objother);
295         struct tpdlist **tpdptr=&tpdother;
296         while((*tpdptr)->task!=task)
297           tpdptr=&((*tpdptr)->next);
298         tmpptr=*tpdptr;
299         (*tpdptr)=(*tpdptr)->next;
300         RUNFREE(tmpptr);
301         if (tpdother!=NULL)
302           genputtable(failedobjects, objother, tpdother);
303       }
304       RUNFREE(task);
305       {
306         struct tpdlist *old=tpd;
307         tpd=tpd->next;
308         RUNFREE(old);
309       }
310     }
311   }
312 }
313 */
314
315 void executetasks() {
316   void * taskpointerarray[MAXTASKPARAMS];
317
318   /* Set up signal handlers */
319   struct sigaction sig;
320   sig.sa_sigaction=&myhandler;
321   sig.sa_flags=SA_SIGINFO;
322   sigemptyset(&sig.sa_mask);
323
324   /* Catch bus errors, segmentation faults, and floating point exceptions*/
325   sigaction(SIGBUS,&sig,0);
326   sigaction(SIGSEGV,&sig,0);
327   sigaction(SIGFPE,&sig,0);
328
329   /* Zero fd set */
330   FD_ZERO(&readfds);
331   maxreadfd=0;
332   fdtoobject=allocateRuntimeHash(100);
333
334   /* Map first block of memory to protected, anonymous page */
335   mmap(0, 0x1000, 0, MAP_SHARED|MAP_FIXED|MAP_ANON, -1, 0);
336
337   newtask:
338   while(!isEmpty(activetasks)||(maxreadfd>0)) {
339
340     /* Check if any filedescriptors have IO pending */
341     if (maxreadfd>0) {
342       int i;
343       struct timeval timeout={0,0};
344       fd_set tmpreadfds;
345       int numselect;
346       tmpreadfds=readfds;
347       numselect=select(maxreadfd, &tmpreadfds, NULL, NULL, &timeout);
348       if (numselect>0) {
349         /* Process ready fd's */
350         int fd;
351         for(fd=0;fd<maxreadfd;fd++) {
352           if (FD_ISSET(fd, &tmpreadfds)) {
353             /* Set ready flag on object */
354             void * objptr;
355             if (RuntimeHashget(fdtoobject, fd,(int *) &objptr)) {
356               flagorand(objptr,1,0xFFFFFFFF); /* Set the first flag to 1 */
357             }
358           }
359         }
360       }
361     }
362
363     /* See if there are any active tasks */
364     if (!isEmpty(activetasks)) {
365       int i;
366       struct QueueItem * qi=(struct QueueItem *) getTail(activetasks);
367       struct taskparamdescriptor *tpd=(struct taskparamdescriptor *) qi->objectptr;
368       removeItem(activetasks, qi);
369
370       /* Check if this task has failed */
371       if (gencontains(failedtasks, tpd))
372         goto newtask;
373       
374       /* Make sure that the parameters are still in the queues */
375       for(i=0;i<tpd->task->numParameters;i++) {
376         void * parameter=tpd->parameterArray[i];
377         struct parameterdescriptor * pd=tpd->task->descriptorarray[i];
378         struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
379         if (!RuntimeHashcontainskey(pw->objectset, (int) parameter))
380           goto newtask;
381         taskpointerarray[i]=parameter;
382       }
383       {
384         /* Checkpoint the state */
385         struct RuntimeHash * forward=allocateRuntimeHash(100);
386         struct RuntimeHash * reverse=allocateRuntimeHash(100);
387         void ** checkpoint=makecheckpoint(tpd->task->numParameters, taskpointerarray, forward, reverse);
388         int x;
389         if (x=setjmp(error_handler)) {
390           /* Recover */
391           int h;
392 #ifdef DEBUG
393           printf("Fatal Error=%d, Recovering!\n",x);
394 #endif
395           genputtable(failedtasks,tpd,tpd);
396        /* for(i=0;i<tpd->task->numParameters;i++) {
397             void *parameter=tpd->parameterArray[i];
398             {
399               // Create mapping from object -> failed tasks 
400               struct tpdlist * tpnew=RUNMALLOC(sizeof(struct tpdlist));
401               tpnew->task=tpd;
402               if (gencontains(failedobjects, parameter)) {
403                 struct tpdlist * tpdptr=gengettable(failedobjects, parameter);
404                 tpnew->next=tpdptr->next;
405                 tpdptr->next=tpnew;
406               } else {
407                 tpnew->next=NULL;
408                 genputtable(failedobjects, parameter, tpnew);
409               }
410             }
411           }  */
412           restorecheckpoint(tpd->task->numParameters, taskpointerarray, checkpoint, forward, reverse);
413         } else {
414           if (injectfailures) {
415             if ((((double)random())/RAND_MAX)<failurechance) {
416               printf("\nINJECTING TASK FAILURE to %s\n", tpd->task->name);
417               longjmp(error_handler,10);
418             }
419           }
420           /* Actually call task */
421           if (debugtask) {
422             printf("ENTER %s count=%d\n",tpd->task->name, (instaccum-instructioncount));
423             ((void (*) (void **)) tpd->task->taskptr)(taskpointerarray);
424             printf("EXIT %s count=%d\n",tpd->task->name, (instaccum-instructioncount));
425           } else
426             ((void (*) (void **)) tpd->task->taskptr)(taskpointerarray);
427         }
428       }
429     }
430   }
431 }
432
433 /* This function processes the task information to create queues for
434    each parameter type. */
435
436 void processtasks() {
437   int i;
438   for(i=0;i<numtasks;i++) {
439     struct taskdescriptor * task=taskarray[i];
440     int j;
441
442     for(j=0;j<task->numParameters;j++) {
443       struct parameterdescriptor *param=task->descriptorarray[j];
444       struct parameterwrapper * parameter=RUNMALLOC(sizeof(struct parameterwrapper));
445       struct parameterwrapper ** ptr=&objectqueues[param->type];
446
447       param->queue=parameter;
448       parameter->objectset=allocateRuntimeHash(10);
449       parameter->numberofterms=param->numberterms;
450       parameter->intarray=param->intarray;
451       parameter->task=task;
452       /* Link new queue in */
453       while((*ptr)!=NULL)
454         ptr=&((*ptr)->next);
455       (*ptr)=parameter;
456     }
457   }
458 }
459
460 #endif
461
462 /* This function inject failures */
463
464 void injectinstructionfailure() {
465 #ifdef TASK
466   if (injectinstructionfailures) {
467     if (numfailures==0)
468       return;
469     instructioncount=failurecount;    
470     instaccum+=failurecount;
471     if ((((double)random())/RAND_MAX)<instfailurechance) {
472       if (numfailures>0)
473         numfailures--;
474       printf("FAILURE!!!\n");
475       longjmp(error_handler,11);
476     }
477   }
478 #else
479 #endif
480 }
481
482 int ___Object______hashCode____(struct ___Object___ * ___this___) {
483   return (int) ___this___;
484 }
485
486 int ___Object______getType____(struct ___Object___ * ptr) {
487   return ((int *)ptr)[0];
488 }
489
490 void ___System______printString____L___String___(struct ___String___ * s) {
491     struct ArrayObject * chararray=s->___value___;
492     int i;
493     int offset=s->___offset___;
494     for(i=0;i<s->___count___;i++) {
495         short s= ((short *)(((char *)& chararray->___length___)+sizeof(int)))[i+offset];
496         putchar(s);
497     }
498 }
499
500 void * allocate_new(int type) {
501   void * v=FREEMALLOC(classsize[type]);
502   *((int *)v)=type;
503   return v;
504 }
505
506 struct ArrayObject * allocate_newarray(int type, int length) {
507   struct ArrayObject * v=FREEMALLOC(sizeof(struct ArrayObject)+length*classsize[type]);
508   v->type=type;
509   v->___length___=length;
510   return v;
511 }
512
513 struct ___String___ * NewString(const char *str,int length) {
514   struct ArrayObject * chararray=allocate_newarray(CHARARRAYTYPE, length);
515   struct ___String___ * strobj=allocate_new(STRINGTYPE);
516   int i;
517   strobj->___value___=chararray;
518   strobj->___count___=length;
519   strobj->___offset___=0;
520
521   for(i=0;i<length;i++) {
522     ((short *)(((char *)& chararray->___length___)+sizeof(int)))[i]=(short)str[i];  }
523   return strobj;
524 }
525
526 /* Generated code calls this if we fail a bounds check */
527 void failedboundschk() {
528 #ifndef TASK
529   printf("Array out of bounds\n");
530   exit(-1);
531 #else
532   longjmp(error_handler,2);
533 #endif
534 }
535
536 void abort_task() {
537 #ifdef TASK
538   longjmp(error_handler,4);
539 #else
540   printf("Aborting\n");
541   exit(-1);
542 #endif
543 }