Bug fixes for allowing multiple task parameters
[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
16 #ifdef TASK
17 #include "checkpoint.h"
18 #include "Queue.h"
19 #include "SimpleHash.h"
20 #include "GenericHashtable.h"
21 #include <sys/select.h>
22 #include <sys/socket.h>
23 #include <fcntl.h>
24 #include <arpa/inet.h>
25
26 #ifdef CONSCHECK
27 #include "instrument.h"
28 #endif
29
30 struct Queue * activetasks;
31 struct parameterwrapper * objectqueues[NUMCLASSES];
32 struct genhashtable * failedtasks;
33
34 int main(int argc, char **argv) {
35   GC_init();
36 #ifdef CONSCHECK
37   initializemmap();
38 #endif
39   {
40   int i;
41   /* Allocate startup object */
42   struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(STARTUPTYPE);
43   struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1); 
44   failedtasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, 
45                                    (int (*)(void *,void *)) &comparetpd);
46   
47   activetasks=createQueue();
48
49   /* Set flags */
50   processtasks();
51   flagorand(startupobject,1,0xFFFFFFFF);
52
53   /* Build array of strings */
54
55   startupobject->___parameters___=stringarray;
56
57   for(i=1;i<argc;i++) {
58     int length=strlen(argv[i]);
59     struct ___String___ *newstring=NewString(argv[i],length);
60     ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;
61   }
62   executetasks();
63   }
64 }
65
66 int hashCodetpd(struct taskparamdescriptor *ftd) {
67   int hash=(int)ftd->task;
68   int i;
69   for(i=0;i<ftd->numParameters;i++) {
70     hash^=(int)ftd->parameterArray[i];
71   }
72   return hash;
73 }
74
75 int comparetpd(struct taskparamdescriptor *ftd1, struct taskparamdescriptor *ftd2) {
76   int i;
77   if (ftd1->task!=ftd2->task)
78     return 0;
79   for(i=0;i<ftd1->numParameters;i++)
80     if (ftd1->parameterArray[i]!=ftd2->parameterArray[i])
81       return 0;
82   return 1;
83 }
84
85 void flagorand(void * ptr, int ormask, int andmask) {
86   int flag=((int *)ptr)[1];
87   struct RuntimeHash *flagptr=(struct RuntimeHash *)(((int*)ptr)[2]);
88   flag|=ormask;
89   flag&=andmask;
90   ((int*)ptr)[1]=flag;
91   /*Remove from all queues */
92   while(flagptr!=NULL) {
93     struct RuntimeHash *next;
94     RuntimeHashget(flagptr, (int) ptr, (int *) &next);
95     RuntimeHashremove(flagptr, (int)ptr, (int) next);
96     flagptr=next;
97   }
98   
99   {
100     struct QueueItem *tmpptr;
101     struct parameterwrapper * parameter=objectqueues[((int *)ptr)[0]];
102     int i;
103     struct RuntimeHash * prevptr=NULL;
104     while(parameter!=NULL) {
105       for(i=0;i<parameter->numberofterms;i++) {
106         int andmask=parameter->intarray[i*2];
107         int checkmask=parameter->intarray[i*2+1];
108         if ((flag&andmask)==checkmask) {
109           RuntimeHashadd(parameter->objectset, (int) ptr, (int) prevptr);
110           prevptr=parameter->objectset;
111           {
112             struct RuntimeIterator iteratorarray[MAXTASKPARAMS];
113             void * taskpointerarray[MAXTASKPARAMS];
114             int j;
115             int numparams=parameter->task->numParameters;
116             int done=1;
117             struct taskdescriptor * task=parameter->task;
118             int newindex=-1;
119             for(j=0;j<numparams;j++) {
120               struct parameterwrapper *pw=(struct parameterwrapper *)task->descriptorarray[j]->queue;
121               if (parameter==pw) {
122                 taskpointerarray[j]=ptr;
123                 newindex=j;
124               } else {
125                 RuntimeHashiterator(pw->objectset, &iteratorarray[j]);
126                 if (RunhasNext(&iteratorarray[j])) {
127                   taskpointerarray[j]=(void *) Runkey(&iteratorarray[j]);
128                   Runnext(&iteratorarray[j]);
129                 } else {
130                   done=0;
131                   break; /* No tasks to dispatch */
132                 }
133               }
134             }
135             /* Queue task items... */
136
137             while(done) {
138               struct taskparamdescriptor *tpd=RUNMALLOC(sizeof(struct taskparamdescriptor));
139               tpd->task=task;
140               tpd->numParameters=numparams;
141               tpd->parameterArray=RUNMALLOC(sizeof(void *)*numparams);
142               for(j=0;j<numparams;j++)
143                 tpd->parameterArray[j]=taskpointerarray[j];
144               /* Queue task */
145               if (!gencontains(failedtasks, tpd))
146                 addNewItem(activetasks, tpd);
147               
148               /* This loop iterates to the next parameter combination */
149               for(j=0;j<numparams;j++) {
150                 if (j==newindex) {
151                   if ((j+1)==numparams)
152                     done=0;
153                   continue;
154                 }
155                 if (RunhasNext(&iteratorarray[j])) {
156                   taskpointerarray[j]=(void *) Runkey(&iteratorarray[j]);
157                   Runnext(&iteratorarray[j]);
158                   break;
159                 } else if ((j+1)!=numparams) {
160                   RuntimeHashiterator(task->descriptorarray[j]->queue, &iteratorarray[j]);
161                 } else {
162                   done=0;
163                   break;
164                 }
165               }
166             }
167           }
168           break;
169         }
170       }
171       parameter=parameter->next;
172     }
173     ((struct RuntimeHash **)ptr)[2]=prevptr;
174   }
175 }
176
177 /* Handler for signals */
178 void myhandler(int sig, struct __siginfo *info, void *uap) {
179 #ifdef DEBUG
180   printf("sig=%d\n",sig);
181   printf("signal\n");
182 #endif
183   longjmp(error_handler,1);
184 }
185
186
187 fd_set readfds;
188 int maxreadfd;
189 struct RuntimeHash *fdtoobject;
190
191 void addreadfd(int fd) {
192   if (fd>=maxreadfd)
193     maxreadfd=fd+1;
194   FD_SET(fd, &readfds);
195 }
196
197 void removereadfd(int fd) {
198   FD_CLR(fd, &readfds);
199   if (maxreadfd==(fd+1)) {
200     maxreadfd--;
201     while(maxreadfd>0&&!FD_ISSET(maxreadfd-1, &readfds))
202       maxreadfd--;
203   }
204 }
205
206 void executetasks() {
207   void * taskpointerarray[MAXTASKPARAMS];
208
209   /* Set up signal handlers */
210   struct sigaction sig;
211   sig.sa_sigaction=&myhandler;
212   sig.sa_flags=SA_SIGINFO;
213   sigemptyset(&sig.sa_mask);
214
215   /* Catch bus errors, segmentation faults, and floating point exceptions*/
216   sigaction(SIGBUS,&sig,0);
217   sigaction(SIGSEGV,&sig,0);
218   sigaction(SIGFPE,&sig,0);
219
220   /* Zero fd set */
221   FD_ZERO(&readfds);
222   maxreadfd=0;
223   fdtoobject=allocateRuntimeHash(100);
224
225   /* Map first block of memory to protected, anonymous page */
226   mmap(0, 0x1000, 0, MAP_SHARED|MAP_FIXED|MAP_ANON, -1, 0);
227
228   newtask:
229   while(!isEmpty(activetasks)||(maxreadfd>0)) {
230
231     if (maxreadfd>0) {
232       int i;
233       struct timeval timeout={0,0};
234       fd_set tmpreadfds;
235       int numselect;
236       FD_COPY(&readfds, &tmpreadfds);
237       numselect=select(maxreadfd, &tmpreadfds, NULL, NULL, &timeout);
238       if (numselect>0) {
239         /* Process ready fd's */
240         int fd;
241         for(fd=0;fd<maxreadfd;fd++) {
242           if (FD_ISSET(fd, &tmpreadfds)) {
243             /* Set ready flag on object */
244             void * objptr;
245             if (RuntimeHashget(fdtoobject, fd,(int *) &objptr)) {
246               flagorand(objptr,1,0xFFFFFFFF); /* Set the first flag to 1 */
247             }
248           }
249         }
250       }
251     }
252
253     if (!isEmpty(activetasks)) {
254       int i;
255       struct QueueItem * qi=(struct QueueItem *) getTail(activetasks);
256       struct taskparamdescriptor *tpd=(struct taskparamdescriptor *) qi->objectptr;
257       removeItem(activetasks, qi);
258       
259       for(i=0;i<tpd->task->numParameters;i++) {
260         void * parameter=tpd->parameterArray[i];
261         struct parameterdescriptor * pd=tpd->task->descriptorarray[i];
262         struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
263         if (!RuntimeHashcontainskey(pw->objectset, (int) parameter))
264           goto newtask;
265         taskpointerarray[i]=parameter;
266       }
267       {
268         struct RuntimeHash * forward=allocateRuntimeHash(100);
269         struct RuntimeHash * reverse=allocateRuntimeHash(100);
270         void ** checkpoint=makecheckpoint(tpd->task->numParameters, taskpointerarray, forward, reverse);
271         if (setjmp(error_handler)) {
272           /* Recover */
273           int h;
274 #ifdef DEBUG
275           printf("Recovering\n");
276 #endif
277           genputtable(failedtasks,tpd,tpd);
278           restorecheckpoint(tpd->task->numParameters, taskpointerarray, checkpoint, forward, reverse);
279         } else {
280           /* Actually call task */
281           ((void (*) (void **)) tpd->task->taskptr)(taskpointerarray);
282         }
283       }
284     }
285   }
286 }
287
288 void processtasks() {
289   int i;
290   for(i=0;i<numtasks;i++) {
291     struct taskdescriptor * task=taskarray[i];
292     int j;
293
294     for(j=0;j<task->numParameters;j++) {
295       struct parameterdescriptor *param=task->descriptorarray[j];
296       struct parameterwrapper * parameter=RUNMALLOC(sizeof(struct parameterwrapper));
297       struct parameterwrapper ** ptr=&objectqueues[param->type];
298
299       param->queue=parameter;
300       parameter->objectset=allocateRuntimeHash(10);
301       parameter->numberofterms=param->numberterms;
302       parameter->intarray=param->intarray;
303       parameter->task=task;
304       /* Link new queue in */
305       while((*ptr)!=NULL)
306         ptr=&((*ptr)->next);
307       (*ptr)=parameter;
308     }
309   }
310 }
311
312
313
314 int ___ServerSocket______createSocket____I(struct ___ServerSocket___ * sock, int port) {
315   int fd;
316
317   int n=1;
318   struct sockaddr_in sin;
319
320   bzero (&sin, sizeof (sin));
321   sin.sin_family = AF_INET;
322   sin.sin_port = htons (port);
323   sin.sin_addr.s_addr = htonl (INADDR_ANY);
324   fd=socket(AF_INET, SOCK_STREAM, 0);
325   if (fd<0) {
326 #ifdef DEBUG
327     perror(NULL);
328     printf("createSocket error #1\n");
329 #endif
330     longjmp(error_handler,5);
331   }
332
333   if (setsockopt (fd, SOL_SOCKET, SO_REUSEADDR, (char *)&n, sizeof (n)) < 0) {
334     close(fd);
335 #ifdef DEBUG
336     perror(NULL);
337     printf("createSocket error #2\n");
338 #endif
339     longjmp(error_handler, 6);
340   }
341   fcntl(fd, F_SETFD, 1);
342   fcntl(fd, F_SETFL, fcntl(fd, F_GETFL)|O_NONBLOCK);
343
344   /* bind to port */
345   if (bind(fd, (struct sockaddr *) &sin, sizeof(sin))<0) { 
346     close (fd);
347 #ifdef DEBUG
348     perror(NULL);
349     printf("createSocket error #3\n");
350 #endif
351     longjmp(error_handler, 7);
352   }
353
354   /* listen */
355   if (listen(fd, 5)<0) { 
356     close (fd);
357 #ifdef DEBUG
358     perror(NULL);
359     printf("createSocket error #4\n");
360 #endif
361     longjmp(error_handler, 8);
362   }
363
364   /* Store the fd/socket object mapping */
365   RuntimeHashadd(fdtoobject, fd, (int) sock);
366   addreadfd(fd);
367   return fd;
368 }
369
370 int ___ServerSocket______nativeaccept____L___Socket___(struct ___ServerSocket___ * serversock, struct ___Socket___ * sock) {
371   struct sockaddr_in sin;
372   unsigned int sinlen=sizeof(sin);
373   int fd=serversock->___fd___;
374   int newfd;
375   newfd=accept(fd, (struct sockaddr *)&sin, &sinlen);
376
377
378   if (newfd<0) { 
379 #ifdef DEBUG
380     perror(NULL);
381     printf("acceptSocket error #1\n");
382 #endif
383     longjmp(error_handler, 9);
384   }
385   fcntl(newfd, F_SETFL, fcntl(fd, F_GETFL)|O_NONBLOCK);
386
387   RuntimeHashadd(fdtoobject, newfd, (int) sock);
388   addreadfd(newfd);
389   flagorand(serversock,0,0xFFFFFFFE);
390   return newfd;
391 }
392
393
394 void ___Socket______nativeWrite_____AR_B(struct ___Socket___ * sock, struct ArrayObject * ao) {
395   int fd=sock->___fd___;
396   int length=ao->___length___;
397   char * charstr=((char *)& ao->___length___)+sizeof(int);
398   int bytewritten=write(fd, charstr, length);
399   if (bytewritten!=length) {
400     printf("ERROR IN NATIVEWRITE\n");
401   }
402   flagorand(sock,0,0xFFFFFFFE);
403 }
404
405 int ___Socket______nativeRead_____AR_B(struct ___Socket___ * sock, struct ArrayObject * ao) {
406   int fd=sock->___fd___;
407   int length=ao->___length___;
408   char * charstr=((char *)& ao->___length___)+sizeof(int);
409   int byteread=read(fd, charstr, length);
410   
411   if (byteread<0) {
412     printf("ERROR IN NATIVEREAD\n");
413   }
414   flagorand(sock,0,0xFFFFFFFE);
415   return byteread;
416 }
417
418 void ___Socket______nativeClose____(struct ___Socket___ * sock) {
419   int fd=sock->___fd___;
420   int data;
421   RuntimeHashget(fdtoobject, fd, &data);
422   RuntimeHashremove(fdtoobject, fd, data);
423   removereadfd(fd);
424   close(fd);
425   flagorand(sock,0,0xFFFFFFFE);
426 }
427 #endif
428
429 int ___Object______hashcode____(struct ___Object___ * ___this___) {
430   return (int) ___this___;
431 }
432
433 void ___System______printString____L___String___(struct ___String___ * s) {
434     struct ArrayObject * chararray=s->___value___;
435     int i;
436     int offset=s->___offset___;
437     for(i=0;i<s->___count___;i++) {
438         short s= ((short *)(((char *)& chararray->___length___)+sizeof(int)))[i+offset];
439         putchar(s);
440     }
441 }
442
443 void * allocate_new(int type) {
444   void * v=FREEMALLOC(classsize[type]);
445   *((int *)v)=type;
446   return v;
447 }
448
449 struct ArrayObject * allocate_newarray(int type, int length) {
450   struct ArrayObject * v=FREEMALLOC(sizeof(struct ArrayObject)+length*classsize[type]);
451   v->type=type;
452   v->___length___=length;
453   return v;
454 }
455
456 struct ___String___ * NewString(const char *str,int length) {
457   struct ArrayObject * chararray=allocate_newarray(CHARARRAYTYPE, length);
458   struct ___String___ * strobj=allocate_new(STRINGTYPE);
459   int i;
460   strobj->___value___=chararray;
461   strobj->___count___=length;
462   strobj->___offset___=0;
463
464   for(i=0;i<length;i++) {
465     ((short *)(((char *)& chararray->___length___)+sizeof(int)))[i]=(short)str[i];  }
466   return strobj;
467 }
468
469 void failedboundschk() {
470 #ifndef TASK
471   printf("Array out of bounds\n");
472   exit(-1);
473 #else
474   longjmp(error_handler,2);
475 #endif
476 }
477
478 void failednullptr() {
479 #ifndef TASK
480   printf("Dereferenced a null pointer\n");
481   exit(-1);
482 #else
483   longjmp(error_handler,3);
484 #endif
485 }
486
487 void abort_task() {
488 #ifndef TASK
489   printf("Aborting\n");
490   exit(-1);
491 #else
492   longjmp(error_handler,4);
493 #endif
494 }