forgot include
[IRC.git] / Robust / src / Runtime / task.c
1 #ifdef TASK
2 #include "runtime.h"
3 #include "structdefs.h"
4 #include "mem.h"
5 #include "checkpoint.h"
6 #include "Queue.h"
7 #include "SimpleHash.h"
8 #include "GenericHashtable.h"
9 #include <sys/select.h>
10 #include <sys/types.h>
11 #include <sys/mman.h>
12 #include <string.h>
13 #include <signal.h>
14
15 extern int injectfailures;
16 extern float failurechance;
17 extern int debugtask;
18 extern int instaccum;
19
20 #ifdef CONSCHECK
21 #include "instrument.h"
22 #endif
23
24 struct genhashtable * activetasks;
25 struct parameterwrapper * objectqueues[NUMCLASSES];
26 struct genhashtable * failedtasks;
27 struct taskparamdescriptor * currtpd;
28 struct RuntimeHash * forward;
29 struct RuntimeHash * reverse;
30
31
32 int main(int argc, char **argv) {
33 #ifdef BOEHM_GC
34   GC_init(); // Initialize the garbage collector
35 #endif
36 #ifdef CONSCHECK
37   initializemmap();
38 #endif
39   processOptions();
40   initializeexithandler();
41   /* Create table for failed tasks */
42   failedtasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, 
43                                    (int (*)(void *,void *)) &comparetpd);
44   /* Create queue of active tasks */
45   activetasks=genallocatehashtable((unsigned int (*)(void *)) &hashCodetpd, 
46                                    (int (*)(void *,void *)) &comparetpd);
47
48
49   /* Process task information */
50   processtasks();
51
52   /* Create startup object */
53   createstartupobject(argc, argv);
54
55   /* Start executing the tasks */
56   executetasks();
57 }
58
59 void createstartupobject(int argc, char ** argv) {
60   int i;
61   
62   /* Allocate startup object     */
63 #ifdef PRECISE_GC
64   struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(NULL, STARTUPTYPE);
65   struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1); 
66 #else
67   struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(STARTUPTYPE);
68   struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1); 
69 #endif
70   /* Build array of strings */
71   startupobject->___parameters___=stringarray;
72   for(i=1;i<argc;i++) {
73     int length=strlen(argv[i]);
74 #ifdef PRECISE_GC
75     struct ___String___ *newstring=NewString(NULL, argv[i],length);
76 #else
77     struct ___String___ *newstring=NewString(argv[i],length);
78 #endif
79     ((void **)(((char *)& stringarray->___length___)+sizeof(int)))[i-1]=newstring;
80   }
81   
82   /* Set initialized flag for startup object */
83   flagorand(startupobject,1,0xFFFFFFFF);
84 }
85
86 int hashCodetpd(struct taskparamdescriptor *ftd) {
87   int hash=(int)ftd->task;
88   int i;
89   for(i=0;i<ftd->numParameters;i++) {
90     hash^=(int)ftd->parameterArray[i];
91   }
92   return hash;
93 }
94
95 int comparetpd(struct taskparamdescriptor *ftd1, struct taskparamdescriptor *ftd2) {
96   int i;
97   if (ftd1->task!=ftd2->task)
98     return 0;
99   for(i=0;i<ftd1->numParameters;i++)
100     if (ftd1->parameterArray[i]!=ftd2->parameterArray[i])
101       return 0;
102   return 1;
103 }
104
105
106 /* This function sets a tag. */
107 #ifdef PRECISE_GC
108 void tagset(void *ptr, struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
109 #else
110 void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
111 #endif
112   struct ___Object___ * tagptr=obj->___tags___;
113   if (tagptr==NULL) {
114     obj->___tags___=(struct ___Object___ *)tagd;
115   } else {
116     /* Have to check if it is already set */
117     if (tagptr->type==TAGTYPE) {
118       struct ___TagDescriptor___ * td=(struct ___TagDescriptor___ *) tagptr;
119       if (td==tagd)
120         return;
121 #ifdef PRECISE_GC
122       int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
123       struct ArrayObject * ao=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL);
124       obj=(struct ___Object___ *)ptrarray[2];
125       tagd=(struct ___TagDescriptor___ *)ptrarray[3];
126       td=(struct ___TagDescriptor___ *) obj->___tags___;
127 #else
128       struct ArrayObject * ao=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL);
129 #endif
130       ARRAYSET(ao, struct ___TagDescriptor___ *, 0, td);
131       ARRAYSET(ao, struct ___TagDescriptor___ *, 1, tagd);
132       obj->___tags___=(struct ___Object___ *) ao;
133       ao->___cachedCode___=2;
134     } else {
135       /* Array Case */
136       int i;
137       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
138       for(i=0;i<ao->___cachedCode___;i++) {
139         struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i);
140         if (td==tagd)
141           return;
142       }
143       if (ao->___cachedCode___<ao->___length___) {
144         ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd);
145         ao->___cachedCode___++;
146       } else {
147 #ifdef PRECISE_GC
148         int ptrarray[]={2,(int) ptr, (int) obj, (int) tagd};
149         struct ArrayObject * aonew=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
150         obj=(struct ___Object___ *)ptrarray[2];
151         tagd=(struct ___TagDescriptor___ *) ptrarray[3];
152         ao=(struct ArrayObject *)obj->___tags___;
153 #else
154         struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
155 #endif
156         aonew->___cachedCode___=ao->___length___+1;
157         for(i=0;i<ao->___length___;i++) {
158           ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i));
159         }
160         ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd);
161       }
162     }
163   }
164
165   {
166     struct ___Object___ * tagset=tagd->flagptr;
167     
168     if(tagset==NULL) {
169       tagd->flagptr=obj;
170     } else if (tagset->type!=OBJECTARRAYTYPE) {
171 #ifdef PRECISE_GC
172       int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
173       struct ArrayObject * ao=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
174       obj=(struct ___Object___ *)ptrarray[2];
175       tagd=(struct ___TagDescriptor___ *)ptrarray[3];
176 #else
177       struct ArrayObject * ao=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
178 #endif
179       ARRAYSET(ao, struct ___Object___ *, 0, tagd->flagptr);
180       ARRAYSET(ao, struct ___Object___ *, 1, obj);
181       ao->___cachedCode___=2;
182       tagd->flagptr=(struct ___Object___ *)ao;
183     } else {
184       struct ArrayObject *ao=(struct ArrayObject *) tagset;
185       if (ao->___cachedCode___<ao->___length___) {
186         ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj);
187       } else {
188         int i;
189 #ifdef PRECISE_GC
190         int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
191         struct ArrayObject * aonew=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL+ao->___length___);
192         obj=(struct ___Object___ *)ptrarray[2];
193         tagd=(struct ___TagDescriptor___ *)ptrarray[3];
194         ao=(struct ArrayObject *)tagd->flagptr;
195 #else
196         struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
197 #endif
198         aonew->___cachedCode___=ao->___cachedCode___+1;
199         for(i=0;i<ao->___length___;i++) {
200           ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i));
201         }
202         ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj);
203         tagd->flagptr=(struct ___Object___ *) ao;
204       }
205     }
206   }
207 }
208
209 /* This function clears a tag. */
210 #ifdef PRECISE_GC
211 void tagclear(void *ptr, struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
212 #else
213 void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
214 #endif
215   /* We'll assume that tag is alway there.
216      Need to statically check for this of course. */
217   struct ___Object___ * tagptr=obj->___tags___;
218
219   if (tagptr->type==TAGTYPE) {
220     if ((struct ___TagDescriptor___ *)tagptr==tagd)
221       obj->___tags___=NULL;
222     else
223       printf("ERROR 1 in tagclear\n");
224   } else {
225     struct ArrayObject *ao=(struct ArrayObject *) tagptr;
226     int i;
227     for(i=0;i<ao->___cachedCode___;i++) {
228       struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i);
229       if (td==tagd) {
230         ao->___cachedCode___--;
231         if (i<ao->___cachedCode___)
232           ARRAYSET(ao, struct ___TagDescriptor___ *, i, ARRAYGET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___));
233         ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, NULL);
234         if (ao->___cachedCode___==0)
235           obj->___tags___=NULL;
236         goto PROCESSCLEAR;
237       }
238     }
239     printf("ERROR 2 in tagclear\n");
240   }
241  PROCESSCLEAR:
242   {
243     struct ___Object___ *tagset=tagd->flagptr;
244     if (tagset->type!=OBJECTARRAYTYPE) {
245       if (tagset==obj)
246         tagd->flagptr=NULL;
247       else
248         printf("ERROR 3 in tagclear\n");
249     } else {
250       struct ArrayObject *ao=(struct ArrayObject *) tagset;
251       int i;
252       for(i=0;i<ao->___cachedCode___;i++) {
253         struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i);
254         if (tobj==obj) {
255           ao->___cachedCode___--;
256           if (i<ao->___cachedCode___)
257             ARRAYSET(ao, struct ___Object___ *, i, ARRAYGET(ao, struct ___Object___ *, ao->___cachedCode___));
258           ARRAYSET(ao, struct ___Object___ *, ao->___cachedCode___, NULL);
259           if (ao->___cachedCode___==0)
260             tagd->flagptr=NULL;
261           goto ENDCLEAR;
262         }
263       }
264       printf("ERROR 4 in tagclear\n");
265     }
266   }
267  ENDCLEAR:
268   return;
269   
270 }
271  
272 /* This function allocates a new tag. */
273 #ifdef PRECISE_GC
274 struct ___TagDescriptor___ * allocate_tag(void *ptr, int index) {
275   struct ___TagDescriptor___ * v=(struct ___TagDescriptor___ *) mygcmalloc((struct garbagelist *) ptr, classsize[TAGTYPE]);
276 #else
277 struct ___TagDescriptor___ * allocate_tag(int index) {
278   struct ___TagDescriptor___ * v=FREEMALLOC(classsize[TAGTYPE]);
279 #endif
280   v->type=TAGTYPE;
281   v->flag=index;
282   return v;
283
284
285
286
287 /* This function updates the flag for object ptr.  It or's the flag
288    with the or mask and and's it with the andmask. */
289
290 void flagbody(struct ___Object___ *ptr, int flag);
291
292 void flagorand(void * ptr, int ormask, int andmask) {
293   int oldflag=((int *)ptr)[1];
294   int flag=ormask|oldflag;
295   flag&=andmask;
296   // Not sure why this was necessary
297   //  if (flag==oldflag) /* Don't do anything */
298   //  return;
299   //else 
300   flagbody(ptr, flag);
301 }
302
303 void intflagorand(void * ptr, int ormask, int andmask) {
304   int oldflag=((int *)ptr)[1];
305   int flag=ormask|oldflag;
306   flag&=andmask;
307   if (flag==oldflag) /* Don't do anything */
308     return;
309   else flagbody(ptr, flag);
310 }
311
312 void flagorandinit(void * ptr, int ormask, int andmask) {
313   int oldflag=((int *)ptr)[1];
314   int flag=ormask|oldflag;
315   flag&=andmask;
316   flagbody(ptr,flag);
317 }
318
319 void flagbody(struct ___Object___ *ptr, int flag) {
320   struct parameterwrapper *flagptr=(struct parameterwrapper *)ptr->flagptr;
321   ptr->flag=flag;
322   
323   /*Remove object from all queues */
324   while(flagptr!=NULL) {
325     struct parameterwrapper *next;
326     struct ___Object___ * tag=ptr->___tags___;
327     RuntimeHashget(flagptr->objectset, (int) ptr, (int *) &next);
328     RuntimeHashremove(flagptr->objectset, (int)ptr, (int) next);
329     flagptr=next;
330   }
331   
332   {
333     struct QueueItem *tmpptr;
334     struct parameterwrapper * parameter=objectqueues[ptr->type];
335     int i;
336     struct parameterwrapper * prevptr=NULL;
337     struct ___Object___ *tagptr=ptr->___tags___;
338       
339     /* Outer loop iterates through all parameter queues an object of
340        this type could be in.  */
341
342     while(parameter!=NULL) {
343       /* Check tags */
344       if (parameter->numbertags>0) {
345         if (tagptr==NULL)
346           goto nextloop;
347         else if(tagptr->type==TAGTYPE) {
348           struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr;
349           for(i=0;i<parameter->numbertags;i++) {
350             //slotid is parameter->tagarray[2*i];
351             int tagid=parameter->tagarray[2*i+1];
352             if (tagid!=tagptr->flag)
353               goto nextloop; /*We don't have this tag */          
354           }
355         } else {
356           struct ArrayObject * ao=(struct ArrayObject *) tagptr;
357           for(i=0;i<parameter->numbertags;i++) {
358             //slotid is parameter->tagarray[2*i];
359             int tagid=parameter->tagarray[2*i+1];
360             int j;
361             for(j=0;j<ao->___cachedCode___;j++) {
362               if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, i)->flag)
363                 goto foundtag;
364             }
365             goto nextloop;
366           foundtag:
367             ;
368           }
369         }
370       }
371
372       /* Check flags */
373       for(i=0;i<parameter->numberofterms;i++) {
374         int andmask=parameter->intarray[i*2];
375         int checkmask=parameter->intarray[i*2+1];
376         if ((flag&andmask)==checkmask) {
377           enqueuetasks(parameter, prevptr, ptr);
378           prevptr=parameter;
379           break;
380         }
381       }
382     nextloop:
383       parameter=parameter->next;
384     }
385     ptr->flagptr=prevptr;
386   }
387 }
388   
389 void enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *prevptr, struct ___Object___ *ptr) {
390   void * taskpointerarray[MAXTASKPARAMS];
391   int j;
392   int numparams=parameter->task->numParameters;
393   int numiterators=parameter->task->numTotal-1;
394
395   struct taskdescriptor * task=parameter->task;
396   
397   RuntimeHashadd(parameter->objectset, (int) ptr, (int) prevptr);
398   
399   /* Add enqueued object to parameter vector */
400   taskpointerarray[parameter->slot]=ptr;
401
402   /* Reset iterators */
403   for(j=0;j<numiterators;j++) {
404     toiReset(&parameter->iterators[j]);
405   }
406
407   /* Find initial state */
408   for(j=0;j<numiterators;j++) {
409   backtrackinit:
410     if(toiHasNext(&parameter->iterators[j], taskpointerarray))
411       toiNext(&parameter->iterators[j], taskpointerarray);
412     else if (j>0) {
413       /* Need to backtrack */
414       toiReset(&parameter->iterators[j]);
415       j--;
416       goto backtrackinit;
417     } else {
418       /* Nothing to enqueue */
419       return;
420     }
421   }
422
423   
424   while(1) {
425     /* Enqueue current state */
426     struct taskparamdescriptor *tpd=RUNMALLOC(sizeof(struct taskparamdescriptor));
427     tpd->task=task;
428     tpd->numParameters=numiterators+1;
429     tpd->parameterArray=RUNMALLOC(sizeof(void *)*(numiterators+1));
430     for(j=0;j<=numiterators;j++)
431       tpd->parameterArray[j]=taskpointerarray[j];
432     
433     /* Enqueue task */
434     if (!gencontains(failedtasks, tpd)&&!gencontains(activetasks,tpd)) {
435       genputtable(activetasks, tpd, tpd);
436     } else {
437       RUNFREE(tpd->parameterArray);
438       RUNFREE(tpd);
439     }
440     
441     /* This loop iterates to the next parameter combination */
442     if (numiterators==0)
443       return;
444
445     for(j=numiterators-1; j<numiterators;j++) {
446     backtrackinc:
447       if(toiHasNext(&parameter->iterators[j], taskpointerarray))
448         toiNext(&parameter->iterators[j], taskpointerarray);
449       else if (j>0) {
450         /* Need to backtrack */
451         toiReset(&parameter->iterators[j]);
452         j--;
453         goto backtrackinc;
454       } else {
455         /* Nothing more to enqueue */
456         return;
457       }
458     }
459   }
460 }
461  
462 /* Handler for signals. The signals catch null pointer errors and
463    arithmatic errors. */
464
465 void myhandler(int sig, siginfo_t *info, void *uap) {
466 #ifdef DEBUG
467   printf("sig=%d\n",sig);
468   printf("signal\n");
469 #endif
470   longjmp(error_handler,1);
471 }
472
473 fd_set readfds;
474 int maxreadfd;
475 struct RuntimeHash *fdtoobject;
476
477 void addreadfd(int fd) {
478   if (fd>=maxreadfd)
479     maxreadfd=fd+1;
480   FD_SET(fd, &readfds);
481 }
482
483 void removereadfd(int fd) {
484   FD_CLR(fd, &readfds);
485   if (maxreadfd==(fd+1)) {
486     maxreadfd--;
487     while(maxreadfd>0&&!FD_ISSET(maxreadfd-1, &readfds))
488       maxreadfd--;
489   }
490 }
491
492 #ifdef PRECISE_GC
493 #define OFFSET 2
494 #else
495 #define OFFSET 0
496 #endif
497
498 void executetasks() {
499   void * taskpointerarray[MAXTASKPARAMS+OFFSET];
500
501   /* Set up signal handlers */
502   struct sigaction sig;
503   sig.sa_sigaction=&myhandler;
504   sig.sa_flags=SA_SIGINFO;
505   sigemptyset(&sig.sa_mask);
506
507   /* Catch bus errors, segmentation faults, and floating point exceptions*/
508   sigaction(SIGBUS,&sig,0);
509   sigaction(SIGSEGV,&sig,0);
510   sigaction(SIGFPE,&sig,0);
511   sigaction(SIGPIPE,&sig,0);
512
513   /* Zero fd set */
514   FD_ZERO(&readfds);
515   maxreadfd=0;
516   fdtoobject=allocateRuntimeHash(100);
517
518   /* Map first block of memory to protected, anonymous page */
519   mmap(0, 0x1000, 0, MAP_SHARED|MAP_FIXED|MAP_ANON, -1, 0);
520
521   newtask:
522   while((hashsize(activetasks)>0)||(maxreadfd>0)) {
523
524     /* Check if any filedescriptors have IO pending */
525     if (maxreadfd>0) {
526       int i;
527       struct timeval timeout={0,0};
528       fd_set tmpreadfds;
529       int numselect;
530       tmpreadfds=readfds;
531       numselect=select(maxreadfd, &tmpreadfds, NULL, NULL, &timeout);
532       if (numselect>0) {
533         /* Process ready fd's */
534         int fd;
535         for(fd=0;fd<maxreadfd;fd++) {
536           if (FD_ISSET(fd, &tmpreadfds)) {
537             /* Set ready flag on object */
538             void * objptr;
539             //      printf("Setting fd %d\n",fd);
540             if (RuntimeHashget(fdtoobject, fd,(int *) &objptr)) {
541               intflagorand(objptr,1,0xFFFFFFFF); /* Set the first flag to 1 */
542             }
543           }
544         }
545       }
546     }
547
548     /* See if there are any active tasks */
549     if (hashsize(activetasks)>0) {
550       int i;
551       currtpd=(struct taskparamdescriptor *) getfirstkey(activetasks);
552       genfreekey(activetasks, currtpd);
553
554       /* Check if this task has failed */
555       if (gencontains(failedtasks, currtpd)) {
556         // Free up task parameter descriptor
557         RUNFREE(currtpd->parameterArray);
558         RUNFREE(currtpd);
559         goto newtask;
560       }
561       int numparams=currtpd->task->numParameters;
562       int numtotal=currtpd->task->numTotal;
563
564       /* Make sure that the parameters are still in the queues */
565       for(i=0;i<numparams;i++) {
566         void * parameter=currtpd->parameterArray[i];
567         struct parameterdescriptor * pd=currtpd->task->descriptorarray[i];
568         struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
569         int j;
570         /* Check that object is still in queue */
571         if (!RuntimeHashcontainskey(pw->objectset, (int) parameter)) {
572           RUNFREE(currtpd->parameterArray);
573           RUNFREE(currtpd);
574           goto newtask;
575         }
576         /* Check that object still has necessary tags */
577         for(j=0;j<pd->numbertags;j++) {
578           int slotid=pd->tagarray[2*j]+numparams;
579           struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid];
580           if (!containstag(parameter, tagd)) {
581             RUNFREE(currtpd->parameterArray);
582             RUNFREE(currtpd);
583             goto newtask;
584           }
585         }
586         
587         taskpointerarray[i+OFFSET]=parameter;
588       }
589       /* Copy the tags */
590       for(;i<numtotal;i++) {
591         taskpointerarray[i+OFFSET]=currtpd->parameterArray[i];
592       }
593
594       {
595         /* Checkpoint the state */
596         forward=allocateRuntimeHash(100);
597         reverse=allocateRuntimeHash(100);
598         void ** checkpoint=makecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, forward, reverse);
599         int x;
600         if (x=setjmp(error_handler)) {
601           /* Recover */
602           int h;
603 #ifdef DEBUG
604           printf("Fatal Error=%d, Recovering!\n",x);
605 #endif
606           genputtable(failedtasks,currtpd,currtpd);
607           restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse);
608           freeRuntimeHash(forward);
609           freeRuntimeHash(reverse);
610           freemalloc();
611           forward=NULL;
612           reverse=NULL;
613         } else {
614           if (injectfailures) {
615             if ((((double)random())/RAND_MAX)<failurechance) {
616               printf("\nINJECTING TASK FAILURE to %s\n", currtpd->task->name);
617               longjmp(error_handler,10);
618             }
619           }
620           /* Actually call task */
621 #ifdef PRECISE_GC
622           ((int *)taskpointerarray)[0]=currtpd->task->numParameters;
623           taskpointerarray[1]=NULL;
624 #endif
625
626           if (debugtask) {
627             printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
628             ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray);
629             printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
630           } else
631             ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray);
632           freeRuntimeHash(forward);
633           freeRuntimeHash(reverse);
634           freemalloc();
635           // Free up task parameter descriptor
636           RUNFREE(currtpd->parameterArray);
637           RUNFREE(currtpd);
638           forward=NULL;
639           reverse=NULL;
640         }
641       }
642     }
643   }
644 }
645
646 /* This function processes an objects tags */
647 void processtags(struct parameterdescriptor *pd, int index, struct parameterwrapper *parameter, int * iteratorcount, int *statusarray, int numparams) {
648   int i;
649
650   for(i=0;i<pd->numbertags;i++) {
651     int slotid=pd->tagarray[2*i];
652     int tagid=pd->tagarray[2*i+1];
653     
654     if (statusarray[slotid+numparams]==0) {
655       parameter->iterators[*iteratorcount].istag=1;
656       parameter->iterators[*iteratorcount].tagid=tagid;
657       parameter->iterators[*iteratorcount].slot=slotid+numparams;
658       parameter->iterators[*iteratorcount].tagobjectslot=index;
659       statusarray[slotid+numparams]=1;
660       (*iteratorcount)++;
661     }
662   }
663 }
664
665
666 void processobject(struct parameterwrapper *parameter, int index, struct parameterdescriptor *pd, int *iteratorcount, int * statusarray, int numparams) {
667   int i;
668   int tagcount=0;
669   struct RuntimeHash * objectset=((struct parameterwrapper *)pd->queue)->objectset;
670
671   parameter->iterators[*iteratorcount].istag=0;
672   parameter->iterators[*iteratorcount].slot=index;
673   parameter->iterators[*iteratorcount].objectset=objectset;
674   statusarray[index]=1;
675
676   for(i=0;i<pd->numbertags;i++) {
677     int slotid=pd->tagarray[2*i];
678     int tagid=pd->tagarray[2*i+1];
679     if (statusarray[slotid+numparams]!=0) {
680       /* This tag has already been enqueued, use it to narrow search */
681       parameter->iterators[*iteratorcount].tagbindings[tagcount]=slotid+numparams;
682       tagcount++;
683     }
684   }
685   parameter->iterators[*iteratorcount].numtags=tagcount;
686
687   (*iteratorcount)++;
688 }
689
690 /* This function builds the iterators for a task & parameter */
691
692 void builditerators(struct taskdescriptor * task, int index, struct parameterwrapper * parameter) {
693   int statusarray[MAXTASKPARAMS];
694   int i;
695   int numparams=task->numParameters;
696   int iteratorcount=0;
697   for(i=0;i<MAXTASKPARAMS;i++) statusarray[i]=0;
698
699   statusarray[index]=1; /* Initial parameter */
700   /* Process tags for initial iterator */
701   
702   processtags(task->descriptorarray[index], index, parameter, & iteratorcount, statusarray, numparams);
703   
704   while(1) {
705   loopstart:
706     /* Check for objects with existing tags */
707     for(i=0;i<numparams;i++) {
708       if (statusarray[i]==0) {
709         struct parameterdescriptor *pd=task->descriptorarray[i];
710         int j;
711         for(j=0;j<pd->numbertags;j++) {
712           int slotid=pd->tagarray[2*j];
713           if(statusarray[slotid+numparams]!=0) {
714             processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
715             processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
716             goto loopstart;
717           }
718         }
719       }
720     }
721
722     /* Next do objects w/ unbound tags*/
723
724     for(i=0;i<numparams;i++) {
725       if (statusarray[i]==0) {
726         struct parameterdescriptor *pd=task->descriptorarray[i];
727         if (pd->numbertags>0) {
728           processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
729           processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
730           goto loopstart;
731         }
732       }
733     }
734
735     /* Nothing with a tag enqueued */
736
737     for(i=0;i<numparams;i++) {
738       if (statusarray[i]==0) {
739         struct parameterdescriptor *pd=task->descriptorarray[i];
740         processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
741         processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
742         goto loopstart;
743       }
744     }
745
746     /* Nothing left */
747     return;
748   }
749 }
750
751
752  
753
754 /* This function processes the task information to create queues for
755    each parameter type. */
756
757 void processtasks() {
758   int i;
759   for(i=0;i<numtasks;i++) {
760     struct taskdescriptor * task=taskarray[i];
761     int j;
762
763     for(j=0;j<task->numParameters;j++) {
764       struct parameterdescriptor *param=task->descriptorarray[j];
765       struct parameterwrapper * parameter=RUNMALLOC(sizeof(struct parameterwrapper));
766       struct parameterwrapper ** ptr=&objectqueues[param->type];
767
768       param->queue=parameter;
769       parameter->objectset=allocateRuntimeHash(10);
770       parameter->numberofterms=param->numberterms;
771       parameter->intarray=param->intarray;
772       parameter->numbertags=param->numbertags;
773       parameter->tagarray=param->tagarray;
774       parameter->task=task;
775       /* Link new queue in */
776       while((*ptr)!=NULL)
777         ptr=&((*ptr)->next);
778       (*ptr)=parameter;
779     }
780
781     /* Build iterators for parameters */
782     for(j=0;j<task->numParameters;j++) {
783       struct parameterdescriptor *param=task->descriptorarray[j];
784       struct parameterwrapper *parameter=param->queue;      
785       parameter->slot=j;
786       builditerators(task, j, parameter);
787     }
788   }
789 }
790
791 void toiReset(struct tagobjectiterator * it) {
792   if (it->istag) {
793     it->tagobjindex=0;
794   } else if (it->numtags>0) {
795     it->tagobjindex=0;
796   } else {
797     RuntimeHashiterator(it->objectset, &it->it);
798   }
799 }
800
801 int toiHasNext(struct tagobjectiterator *it, void ** objectarray) {
802   if (it->istag) {
803     /* Iterate tag */
804     /* Get object with tags */
805     struct ___Object___ *obj=objectarray[it->tagobjectslot];
806     struct ___Object___ *tagptr=obj->___tags___;
807     if (tagptr->type==TAGTYPE) {
808       if ((it->tagobjindex==0)&& /* First object */
809           (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */
810         return 1;
811       else
812         return 0;
813     } else {
814       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
815       int tagindex=it->tagobjindex;
816       for(;tagindex<ao->___cachedCode___;tagindex++) {
817         struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex);
818         if (td->flag==it->tagid) {
819           it->tagobjindex=tagindex; /* Found right type of tag */
820           return 1;
821         }
822       }
823       return 0;
824     }
825   } else if (it->numtags>0) {
826     /* Use tags to locate appropriate objects */
827     struct ___TagDescriptor___ *tag=objectarray[it->tagbindings[0]];
828     struct ___Object___ *objptr=tag->flagptr;
829     int i;
830     if (objptr->type!=OBJECTARRAYTYPE) {
831       if (it->tagobjindex>0)
832         return 0;
833       if (!RuntimeHashcontainskey(it->objectset, (int) objptr))
834         return 0;
835       for(i=1;i<it->numtags;i++) {
836         struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
837         if (!containstag(objptr,tag2))
838           return 0;
839       }
840       return 1;
841     } else {
842       struct ArrayObject *ao=(struct ArrayObject *) objptr;
843       int tagindex;
844       int i;
845       for(tagindex=it->tagobjindex;tagindex<ao->___cachedCode___;tagindex++) {
846         struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
847         if (!RuntimeHashcontainskey(it->objectset, (int) objptr))
848           continue;
849         for(i=1;i<it->numtags;i++) {
850           struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
851           if (!containstag(objptr,tag2))
852             goto nexttag;
853         }
854         return 1;
855       nexttag:
856         ;
857       }
858       it->tagobjindex=tagindex;
859       return 0;
860     }
861   } else {
862     return RunhasNext(&it->it);
863   }
864 }
865
866 int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) {
867   int j;
868   struct ___Object___ * objptr=tag->flagptr;
869   if (objptr->type==OBJECTARRAYTYPE) {
870     struct ArrayObject *ao=(struct ArrayObject *)objptr;
871     for(j=0;j<ao->___cachedCode___;j++) {
872       if (ptr==ARRAYGET(ao, struct ___Object___*, j))
873         return 1;
874     }
875     return 0;
876   } else
877     return objptr==ptr;
878 }
879
880 void toiNext(struct tagobjectiterator *it , void ** objectarray) {
881   /* hasNext has all of the intelligence */
882   if(it->istag) {
883     /* Iterate tag */
884     /* Get object with tags */
885     struct ___Object___ *obj=objectarray[it->tagobjectslot];
886     struct ___Object___ *tagptr=obj->___tags___;
887     if (tagptr->type==TAGTYPE) {
888       it->tagobjindex++;
889       objectarray[it->slot]=tagptr;
890     } else {
891       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
892       objectarray[it->slot]=ARRAYGET(ao, struct ___TagDescriptor___ *, it->tagobjindex++);
893     }
894   } else if (it->numtags>0) {
895     /* Use tags to locate appropriate objects */
896     struct ___TagDescriptor___ *tag=objectarray[it->tagbindings[0]];
897     struct ___Object___ *objptr=tag->flagptr;
898     if (objptr->type!=OBJECTARRAYTYPE) {
899       it->tagobjindex++;
900       objectarray[it->slot]=objptr;
901     } else {
902       struct ArrayObject *ao=(struct ArrayObject *) objptr;
903       objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex++);
904     }
905   } else {
906     /* Iterate object */
907     objectarray[it->slot]=(void *)Runkey(&it->it);
908     Runnext(&it->it);
909   }
910 }
911
912
913 #endif