change
[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 extern int errors;
20
21 #ifdef CONSCHECK
22 #include "instrument.h"
23 #endif
24
25 struct genhashtable * activetasks;
26 struct parameterwrapper * objectqueues[NUMCLASSES];
27 struct genhashtable * failedtasks;
28 struct taskparamdescriptor * currtpd;
29 struct ctable * forward;
30 struct ctable * reverse;
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   /* Process task information */
49   processtasks();
50
51   /* Create startup object */
52   createstartupobject(argc, argv);
53
54   /* Start executing the tasks */
55   executetasks();
56 }
57
58 void createstartupobject(int argc, char ** argv) {
59   int i;
60
61   /* Allocate startup object     */
62 #ifdef PRECISE_GC
63   struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(NULL, STARTUPTYPE);
64   struct ArrayObject * stringarray=allocate_newarray(NULL, STRINGARRAYTYPE, argc-1);
65 #else
66   struct ___StartupObject___ *startupobject=(struct ___StartupObject___*) allocate_new(STARTUPTYPE);
67   struct ArrayObject * stringarray=allocate_newarray(STRINGARRAYTYPE, argc-1);
68 #endif
69   /* Build array of strings */
70   startupobject->___parameters___=stringarray;
71   for(i=1; i<argc; i++) {
72     int length=strlen(argv[i]);
73 #ifdef PRECISE_GC
74     struct ___String___ *newstring=NewString(NULL, argv[i],length);
75 #else
76     struct ___String___ *newstring=NewString(argv[i],length);
77 #endif
78     ((void **)(((char *)&stringarray->___length___)+sizeof(int)))[i-1]=newstring;
79   }
80
81   /* Set initialized flag for startup object */
82   flagorand(startupobject,1,0xFFFFFFFF);
83   enqueueObject(startupobject);
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 #ifdef OPTIONAL
103   for(i=0; i<ftd1->numParameters; i++) {
104     if(ftd1->failed[i]!=ftd2->failed[i])
105       return 0;
106   }
107 #endif
108   return 1;
109 }
110
111 /* This function sets a tag. */
112 #ifdef PRECISE_GC
113 void tagset(void *ptr, struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
114 #else
115 void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
116 #endif
117   struct ___Object___ * tagptr=obj->___tags___;
118   if (tagptr==NULL) {
119     obj->___tags___=(struct ___Object___ *)tagd;
120   } else {
121     /* Have to check if it is already set */
122     if (tagptr->type==TAGTYPE) {
123       struct ___TagDescriptor___ * td=(struct ___TagDescriptor___ *) tagptr;
124       if (td==tagd)
125         return;
126 #ifdef PRECISE_GC
127       int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
128       struct ArrayObject * ao=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL);
129       obj=(struct ___Object___ *)ptrarray[2];
130       tagd=(struct ___TagDescriptor___ *)ptrarray[3];
131       td=(struct ___TagDescriptor___ *) obj->___tags___;
132 #else
133       struct ArrayObject * ao=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL);
134 #endif
135       ARRAYSET(ao, struct ___TagDescriptor___ *, 0, td);
136       ARRAYSET(ao, struct ___TagDescriptor___ *, 1, tagd);
137       obj->___tags___=(struct ___Object___ *) ao;
138       ao->___cachedCode___=2;
139     } else {
140       /* Array Case */
141       int i;
142       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
143       for(i=0; i<ao->___cachedCode___; i++) {
144         struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i);
145         if (td==tagd)
146           return;
147       }
148       if (ao->___cachedCode___<ao->___length___) {
149         ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd);
150         ao->___cachedCode___++;
151       } else {
152 #ifdef PRECISE_GC
153         int ptrarray[]={2,(int) ptr, (int) obj, (int) tagd};
154         struct ArrayObject * aonew=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
155         obj=(struct ___Object___ *)ptrarray[2];
156         tagd=(struct ___TagDescriptor___ *) ptrarray[3];
157         ao=(struct ArrayObject *)obj->___tags___;
158 #else
159         struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
160 #endif
161         aonew->___cachedCode___=ao->___length___+1;
162         for(i=0; i<ao->___length___; i++) {
163           ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i));
164         }
165         ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd);
166       }
167     }
168   }
169
170   {
171     struct ___Object___ * tagset=tagd->flagptr;
172     if(tagset==NULL) {
173       tagd->flagptr=obj;
174     } else if (tagset->type!=OBJECTARRAYTYPE) {
175 #ifdef PRECISE_GC
176       int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
177       struct ArrayObject * ao=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
178       obj=(struct ___Object___ *)ptrarray[2];
179       tagd=(struct ___TagDescriptor___ *)ptrarray[3];
180 #else
181       struct ArrayObject * ao=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
182 #endif
183       ARRAYSET(ao, struct ___Object___ *, 0, tagd->flagptr);
184       ARRAYSET(ao, struct ___Object___ *, 1, obj);
185       ao->___cachedCode___=2;
186       tagd->flagptr=(struct ___Object___ *)ao;
187     } else {
188       struct ArrayObject *ao=(struct ArrayObject *) tagset;
189       if (ao->___cachedCode___<ao->___length___) {
190         ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj);
191       } else {
192         int i;
193 #ifdef PRECISE_GC
194         int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
195         struct ArrayObject * aonew=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL+ao->___length___);
196         obj=(struct ___Object___ *)ptrarray[2];
197         tagd=(struct ___TagDescriptor___ *)ptrarray[3];
198         ao=(struct ArrayObject *)tagd->flagptr;
199 #else
200         struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
201 #endif
202         aonew->___cachedCode___=ao->___cachedCode___+1;
203         for(i=0; i<ao->___length___; i++) {
204           ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i));
205         }
206         ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj);
207         tagd->flagptr=(struct ___Object___ *) aonew;
208       }
209     }
210   }
211 }
212
213 /* This function clears a tag. */
214 #ifdef PRECISE_GC
215 void tagclear(void *ptr, struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
216 #else
217 void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
218 #endif
219   /* We'll assume that tag is alway there.
220      Need to statically check for this of course. */
221   struct ___Object___ * tagptr=obj->___tags___;
222
223   if (tagptr->type==TAGTYPE) {
224     if ((struct ___TagDescriptor___ *)tagptr==tagd)
225       obj->___tags___=NULL;
226     else
227       printf("ERROR 1 in tagclear\n");
228   } else {
229     struct ArrayObject *ao=(struct ArrayObject *) tagptr;
230     int i;
231     for(i=0; i<ao->___cachedCode___; i++) {
232       struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i);
233       if (td==tagd) {
234         ao->___cachedCode___--;
235         if (i<ao->___cachedCode___)
236           ARRAYSET(ao, struct ___TagDescriptor___ *, i, ARRAYGET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___));
237         ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, NULL);
238         if (ao->___cachedCode___==0)
239           obj->___tags___=NULL;
240         goto PROCESSCLEAR;
241       }
242     }
243     printf("ERROR 2 in tagclear\n");
244   }
245 PROCESSCLEAR:
246   {
247     struct ___Object___ *tagset=tagd->flagptr;
248     if (tagset->type!=OBJECTARRAYTYPE) {
249       if (tagset==obj)
250         tagd->flagptr=NULL;
251       else
252         printf("ERROR 3 in tagclear\n");
253     } else {
254       struct ArrayObject *ao=(struct ArrayObject *) tagset;
255       int i;
256       for(i=0; i<ao->___cachedCode___; i++) {
257         struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i);
258         if (tobj==obj) {
259           ao->___cachedCode___--;
260           if (i<ao->___cachedCode___)
261             ARRAYSET(ao, struct ___Object___ *, i, ARRAYGET(ao, struct ___Object___ *, ao->___cachedCode___));
262           ARRAYSET(ao, struct ___Object___ *, ao->___cachedCode___, NULL);
263           if (ao->___cachedCode___==0)
264             tagd->flagptr=NULL;
265           goto ENDCLEAR;
266         }
267       }
268       printf("ERROR 4 in tagclear\n");
269     }
270   }
271 ENDCLEAR:
272   return;
273 }
274
275 /* This function allocates a new tag. */
276 #ifdef PRECISE_GC
277 struct ___TagDescriptor___ * allocate_tag(void *ptr, int index) {
278   struct ___TagDescriptor___ * v=(struct ___TagDescriptor___ *) mygcmalloc((struct garbagelist *) ptr, classsize[TAGTYPE]);
279 #else
280 struct ___TagDescriptor___ * allocate_tag(int index) {
281   struct ___TagDescriptor___ * v=FREEMALLOC(classsize[TAGTYPE]);
282 #endif
283   v->type=TAGTYPE;
284   v->flag=index;
285   return v;
286 }
287
288
289
290 /* This function updates the flag for object ptr.  It or's the flag
291    with the or mask and and's it with the andmask. */
292
293 void flagbody(struct ___Object___ *ptr, int flag);
294 #ifdef OPTIONAL
295 void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * failedfses, struct taskdescriptor * task, int index);
296 #endif
297
298 int flagcomp(const int *val1, const int *val2) {
299   return (*val1)-(*val2);
300 }
301
302 void flagorand(void * ptr, int ormask, int andmask) {
303 #ifdef OPTIONAL
304   struct ___Object___ * obj = (struct ___Object___ *)ptr;
305   if(obj->numfses) { /*store the information about fses*/
306     int flag, i, j,counter, offset=0;
307     for(i=0; i<obj->numfses; i++) {
308       int oldoffset;
309       counter=obj->fses[offset++];
310       oldoffset=offset;
311       for(j=0; j<counter; j++) {
312         flag=obj->fses[offset];
313         obj->fses[offset++]=(flag|ormask)&andmask;
314       }
315       qsort(&obj->fses[oldoffset], sizeof(int), counter, (int(*) (const void *, const void *)) &flagcomp);
316     }
317     enqueueoptional(obj, 0, NULL, NULL, 0);
318   } else
319 #endif
320   {
321     int oldflag=((int *)ptr)[1];
322     int flag=ormask|oldflag;
323     flag&=andmask;
324     flagbody(ptr, flag);
325   }
326 }
327
328 bool intflagorand(void * ptr, int ormask, int andmask) {
329 #ifdef OPTIONAL
330   struct ___Object___ * obj = (struct ___Object___ *)ptr;
331   if(obj->numfses) { /*store the information about fses*/
332     int flag, i, j,counter, offset=0;
333     for(i=0; i<obj->numfses; i++) {
334       int oldoffset;
335       counter=obj->fses[offset++];
336       oldoffset=offset;
337       for(j=0; j<counter; j++) {
338         flag=obj->fses[offset];
339         obj->fses[offset++]=(flag|ormask)&andmask;
340       }
341       qsort(&obj->fses[oldoffset], sizeof(int), counter, (int(*) (const void *, const void *)) &flagcomp);
342     }
343     enqueueoptional(obj, 0, NULL, NULL, 0);
344   } else
345 #endif
346   {
347     int oldflag=((int *)ptr)[1];
348     int flag=ormask|oldflag;
349     flag&=andmask;
350     if (flag==oldflag)   /* Don't do anything */
351       return false;
352     else {
353       flagbody(ptr, flag);
354       return true;
355     }
356   }
357 }
358
359 void flagorandinit(void * ptr, int ormask, int andmask) {
360   int oldflag=((int *)ptr)[1];
361   int flag=ormask|oldflag;
362   flag&=andmask;
363   flagbody(ptr,flag);
364 }
365
366 void flagbody(struct ___Object___ *ptr, int flag) {
367   struct parameterwrapper *flagptr=(struct parameterwrapper *)ptr->flagptr;
368   ptr->flag=flag;
369
370   /*Remove object from all queues */
371   while(flagptr!=NULL) {
372     struct parameterwrapper *next;
373     int UNUSED, UNUSED2;
374     int * enterflags;
375     ObjectHashget(flagptr->objectset, (int) ptr, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2);
376     ObjectHashremove(flagptr->objectset, (int)ptr);
377     if (enterflags!=NULL)
378       free(enterflags);
379     flagptr=next;
380   }
381 }
382
383 void enqueueObject(void *vptr) {
384   struct ___Object___ *ptr = (struct ___Object___ *)vptr;
385
386   {
387     struct QueueItem *tmpptr;
388     struct parameterwrapper * parameter=objectqueues[ptr->type];
389     int i;
390     struct parameterwrapper * prevptr=NULL;
391     struct ___Object___ *tagptr=ptr->___tags___;
392
393     /* Outer loop iterates through all parameter queues an object of
394        this type could be in.  */
395
396     while(parameter!=NULL) {
397       /* Check tags */
398       if (parameter->numbertags>0) {
399         if (tagptr==NULL)
400           goto nextloop; //that means the object has no tag but that param needs tag
401         else if(tagptr->type==TAGTYPE) { //one tag
402           struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr;
403           for(i=0; i<parameter->numbertags; i++) {
404             //slotid is parameter->tagarray[2*i];
405             int tagid=parameter->tagarray[2*i+1];
406             if (tagid!=tagptr->flag)
407               goto nextloop; /*We don't have this tag */
408           }
409         } else { //multiple tags
410           struct ArrayObject * ao=(struct ArrayObject *) tagptr;
411           for(i=0; i<parameter->numbertags; i++) {
412             //slotid is parameter->tagarray[2*i];
413             int tagid=parameter->tagarray[2*i+1];
414             int j;
415             for(j=0; j<ao->___cachedCode___; j++) {
416               if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, j)->flag)
417                 goto foundtag;
418             }
419             goto nextloop;
420 foundtag:
421             ;
422           }
423         }
424       }
425
426       /* Check flags */
427       for(i=0; i<parameter->numberofterms; i++) {
428         int andmask=parameter->intarray[i*2];
429         int checkmask=parameter->intarray[i*2+1];
430         if ((ptr->flag&andmask)==checkmask) {
431           enqueuetasks(parameter, prevptr, ptr, NULL, 0);
432           prevptr=parameter;
433           break;
434         }
435       }
436 nextloop:
437       parameter=parameter->next;
438     }
439     ptr->flagptr=prevptr;
440   }
441 }
442
443 #ifdef OPTIONAL
444
445 int checktags(struct ___Object___ * currobj, struct fsanalysiswrapper * fswrapper) {
446   /* Check Tags */
447   struct ___Object___ * tagptr = currobj->___tags___;
448   if(fswrapper->numtags>0) {
449     if (tagptr==NULL)
450       return 0; //that means the object has no tag but that param
451     //needs tag
452     else if(tagptr->type==TAGTYPE) { //one tag
453       if(fswrapper->numtags!=1)
454         return 0; //we don't have the right number of tags
455       struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr;
456       if (fswrapper->tags[0]!=tagptr->flag)
457         return 0;
458     } else {  //multiple tags
459       struct ArrayObject * ao=(struct ArrayObject *) tagptr;
460       int tag_counter=0;
461       int foundtag=0;
462
463       if(ao->___length___!=fswrapper->numtags)
464         return 0; //we don't have the right number of tags
465       for(tag_counter=0; tag_counter<fswrapper->numtags; tag_counter++) {
466         int tagid=fswrapper->tags[tag_counter];
467         int j;
468         for(j=0; j<ao->___cachedCode___; j++) {
469           if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, tag_counter)->flag)
470             return 1;
471         }
472         return 0;
473       }
474     }
475   }
476   return 1;
477 }
478
479 int getlength(int *flist, int len) {
480   int count=0;
481   int i;
482   for(i=0; i<len; i++) {
483     int size=flist[count];
484     count+=1+size;
485   }
486   return count;
487 }
488
489 int * domergeor(int *flist1, int len1, int *flist2, int len2) {
490   int size1=getlength(flist1, len1);
491   int size2=getlength(flist2, len2);
492   int *merge=RUNMALLOC((size1+size2)*sizeof(int));
493   memcpy(merge, flist1, size1*sizeof(int));
494   memcpy(&merge[size1], flist2, size2*sizeof(int));
495   return merge;
496 }
497
498 int domerge(int * flist1, int len1, int *flist2, int len2, int *merge) {
499   int count=0;
500   int i=0;
501   int j=0;
502   while(i<len1||j<len2) {
503     if (i<len1&&(j==len2||flist1[i]<flist2[j])) {
504       if(merge!=NULL) {
505         merge[count]=flist1[i];
506       }
507       i++;
508       count++;
509     } else if (j<len2&&(i==len1||flist2[j]<flist1[i])) {
510       if(merge!=NULL) {
511         merge[count]=flist2[j];
512       }
513       j++;
514       count++;
515     } else if (i<len1&&j<len2&&flist1[i]==flist2[j]) {
516       if(merge!=NULL) {
517         merge[count]=flist1[i];
518       }
519       i++;
520       j++;
521       count++;
522     }
523   }
524   return count;
525 }
526
527 /* Merge flags from ftlmerge into ftl. */
528 void mergeitems(struct failedtasklist *ftl, struct failedtasklist *ftlmerge) {
529   int length=0;
530   int i,j;
531   int *mergedlist;
532   int offset=0;
533   for(i=0; i<ftl->numflags; i++) {
534     int len=ftl->flags[offset++];
535     int offsetmerge=0;
536     for(j=0; j<ftlmerge->numflags; j++) {
537       int lenmerge=ftlmerge->flags[offsetmerge++];
538       length+=1+domerge(&ftl->flags[offset],len,&ftlmerge->flags[offsetmerge],lenmerge, NULL);
539       offsetmerge+=lenmerge;
540     }
541     offset+=len;
542   }
543   mergedlist=RUNMALLOC(sizeof(int)*length);
544
545   offset=0;
546   length=0;
547   for(i=0; i<ftl->numflags; i++) {
548     int len=ftl->flags[offset++];
549     int offsetmerge=0;
550     for(j=0; j<ftlmerge->numflags; j++) {
551       int lenmerge=ftlmerge->flags[offsetmerge++];
552       int size=domerge(&ftl->flags[offset],len,&ftlmerge->flags[offsetmerge],lenmerge,&mergedlist[length+1]);
553       mergedlist[length]=size;
554       length+=size+1;
555     }
556   }
557   RUNFREE(ftl->flags);
558   ftl->flags=mergedlist;
559   ftl->numflags*=ftlmerge->numflags;
560 }
561
562 void mergefailedlists(struct failedtasklist **andlist, struct failedtasklist *list) {
563   struct failedtasklist *tmpptr;
564   while((*andlist)!=NULL) {
565     struct failedtasklist *searchftl=list;
566     while(searchftl!=NULL) {
567       if ((*andlist)->task==searchftl->task&&
568           (*andlist)->index==searchftl->index) {
569         mergeitems(*andlist, searchftl);
570         break;
571       }
572       searchftl=searchftl->next;
573     }
574     if (searchftl==NULL) {
575       //didn't find andlist
576       tmpptr=*andlist;
577       *andlist=(*andlist)->next; //splice item out of list
578       RUNFREE(tmpptr->flags); //free the item
579       RUNFREE(tmpptr);
580     } else {
581       andlist=&((*andlist)->next); //iterate to next item
582     }
583   }
584   //free the list we're searching
585   while(list!=NULL) {
586     tmpptr=list->next;
587     RUNFREE(list->flags);
588     RUNFREE(list);
589     list=tmpptr;
590   }
591 }
592
593 struct failedtasklist * processfailstate(struct classanalysiswrapper * classwrapper, struct taskdescriptor *task, int index, struct ___Object___ * currobj, int flagstate) {
594   struct failedtasklist *list=NULL;
595   int i,h;
596   struct fsanalysiswrapper *fswrapper=NULL;
597   for(h=0; h<classwrapper->numfsanalysiswrappers; h++) {
598     struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h];
599     if (tmp->flags==flagstate&&checktags(currobj, tmp)) {
600       //we only match exactly here
601       fswrapper=tmp;
602       break;
603     }
604   }
605   if (fswrapper==NULL)
606     return list;
607   for(i=0; i<fswrapper->numtaskfailures; i++) {
608     int j;
609     struct taskfailure * taskfail=fswrapper->taskfailurearray[i];
610     if (taskfail->task==task&&taskfail->index==index) {
611       int start=0;
612       while(start<taskfail->numoptionaltaskdescriptors) {
613         struct taskdescriptor *currtask=NULL;
614         struct failedtasklist *tmpftl;
615         int currindex;
616         int totallength=0;
617         int *enterflags;
618         int numenterflags, offset;
619         struct parameterwrapper *pw;
620         for(j=start; j<taskfail->numoptionaltaskdescriptors; j++) {
621           struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[j];
622           if(currtask==NULL) {
623             currtask=otd->task;
624             currindex=otd->index;
625           } else if (currtask!=otd->task||currindex!=otd->index)
626             break;
627           totallength+=otd->numenterflags;
628         }
629         pw=currtask->descriptorarray[currindex]->queue;
630         enterflags=RUNMALLOC(totallength*sizeof(int));
631         numenterflags=j-start;
632         offset=0;
633         for(start; start<j; start++) {
634           struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[start];
635           enterflags[offset++]=otd->numenterflags;
636           memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
637           offset+=otd->numenterflags;
638         }
639         tmpftl=RUNMALLOC(sizeof(struct failedtasklist));
640         tmpftl->next=list;
641         tmpftl->task=currtask;
642         tmpftl->numflags=numenterflags;
643         tmpftl->flags=enterflags;
644         list=tmpftl;
645       }
646     }
647   }
648   return list;
649 }
650
651 struct failedtasklist * processnormfailstate(struct classanalysiswrapper * classwrapper, struct ___Object___ * currobj, int flagstate) {
652   struct failedtasklist *list=NULL;
653   int i,h;
654   int start=0;
655   struct fsanalysiswrapper *fswrapper=NULL;
656   for(h=0; h<classwrapper->numfsanalysiswrappers; h++) {
657     struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h];
658     if (tmp->flags==flagstate&&checktags(currobj, tmp)) {
659       //we only match exactly here
660       fswrapper=tmp;
661       break;
662     }
663   }
664   if(fswrapper==NULL)
665     return NULL;
666
667   while(start<fswrapper->numoptionaltaskdescriptors) {
668     struct taskdescriptor *currtask=NULL;
669     struct failedtasklist *tmpftl;
670     int j;
671     int currindex;
672     int totallength=0;
673     int *enterflags;
674     int numenterflags, offset;
675     struct parameterwrapper *pw;
676     for(j=start; j<fswrapper->numoptionaltaskdescriptors; j++) {
677       struct optionaltaskdescriptor *otd=fswrapper->optionaltaskdescriptorarray[j];
678       if(currtask==NULL) {
679         currtask=otd->task;
680         currindex=otd->index;
681       } else if (currtask!=otd->task||currindex!=otd->index)
682         break;
683       totallength+=otd->numenterflags;
684     }
685     pw=currtask->descriptorarray[currindex]->queue;
686     enterflags=RUNMALLOC(totallength*sizeof(int));
687     numenterflags=j-start;
688     offset=0;
689     for(start; start<j; start++) {
690       struct optionaltaskdescriptor *otd=fswrapper->optionaltaskdescriptorarray[start];
691       enterflags[offset++]=otd->numenterflags;
692       memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
693       offset+=otd->numenterflags;
694     }
695     tmpftl=RUNMALLOC(sizeof(struct failedtasklist));
696     tmpftl->next=list;
697     tmpftl->task=currtask;
698     tmpftl->numflags=numenterflags;
699     tmpftl->flags=enterflags;
700     list=tmpftl;
701   }
702   return list;
703 }
704
705
706
707 void enqueuelist(struct ___Object___ * currobj, struct failedtasklist * andlist) {
708   while(andlist!=NULL) {
709     struct failedtasklist *tmp=andlist;
710     struct parameterwrapper *pw=andlist->task->descriptorarray[andlist->index]->queue;
711     struct parmaeterwrapper *next;
712     int * flags;
713     int numflags;
714     int isnonfailed;
715
716     if (enqueuetasks(pw, currobj->flagptr, currobj, tmp->flags, tmp->numflags))
717       currobj->flagptr=pw;
718
719     andlist=andlist->next;
720     RUNFREE(tmp);
721   }
722 }
723
724 void enqueueoptional(struct ___Object___ * currobj, int numfailedfses, int * failedfses, struct taskdescriptor * task, int index) {
725   struct classanalysiswrapper * classwrapper=NULL;
726
727   /*test what optionaltaskdescriptors are available, find the class
728      corresponding*/
729   if (classanalysiswrapperarray[currobj->type]!=NULL) {
730     classwrapper = classanalysiswrapperarray[currobj->type];
731   } else
732     return;
733
734   if(task!=NULL) {
735     /* We have a failure */
736     if (failedfses==NULL) {
737       /* Failed in normal state */
738       /*first time the method is invoked*/
739       int i,h;
740       struct fsanalysiswrapper *fswrapper=NULL;
741
742       for(h=0; h<classwrapper->numfsanalysiswrappers; h++) {
743         struct fsanalysiswrapper * tmp=classwrapper->fsanalysiswrapperarray[h];
744         if (tmp->flags==currobj->flag&&checktags(currobj, tmp)) {
745           //we only match exactly here
746           fswrapper=tmp;
747           break;
748         }
749       }
750       if(fswrapper==NULL) //nothing to do in this state
751         return;
752       for(i=0; i<fswrapper->numtaskfailures; i++) {
753         int j;
754         struct taskfailure * taskfail=fswrapper->taskfailurearray[i];
755         if (taskfail->task==task&&taskfail->index==index) {
756           int start=0;
757           while(start<taskfail->numoptionaltaskdescriptors) {
758             struct taskdescriptor *currtask=NULL;
759             int currindex;
760             int totallength=0;
761             int *enterflags;
762             int numenterflags, offset;
763             struct parameterwrapper *pw;
764             for(j=start; j<taskfail->numoptionaltaskdescriptors; j++) {
765               struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[j];
766               if(currtask==NULL) {
767                 currtask=otd->task;
768                 currindex=otd->index;
769               } else if (currtask!=otd->task||currindex!=otd->index)
770                 break;
771               totallength+=otd->numenterflags; //1 is to store the lengths
772             }
773             pw=currtask->descriptorarray[currindex]->queue;
774             numenterflags=j-start;
775             enterflags=RUNMALLOC((totallength+numenterflags)*sizeof(int));
776
777             offset=0;
778             for(start; start<j; start++) {
779               struct optionaltaskdescriptor *otd=taskfail->optionaltaskdescriptorarray[start];
780               enterflags[offset++]=otd->numenterflags;
781               memcpy(&enterflags[offset], otd->enterflags, otd->numenterflags*sizeof(int));
782               offset+=otd->numenterflags;
783             }
784             //Enqueue this one
785             if (enqueuetasks(pw, currobj->flagptr, currobj, enterflags, numenterflags))
786               currobj->flagptr=pw;
787           }
788         }
789       }
790     } else {
791       /* Failed in failed state */
792       int i;
793       int offset=0;
794       for(i=0; i<numfailedfses; i++) {
795         int numfses=failedfses[offset++];
796         int j;
797         struct failedtasklist *andlist=NULL;
798         for(j=0; j<numfses; j++) {
799           int flagstate=failedfses[offset++];
800           struct failedtasklist *currlist=processfailstate(classwrapper, task, index, currobj, flagstate);
801           if (andlist==NULL)
802             andlist=currlist;
803           else
804             mergefailedlists(&andlist, currlist);
805         }
806         enqueuelist(currobj, andlist);
807       }
808     }
809   } else {
810     /* No failure, but we are in a failed state */
811     struct parameterwrapper *flagptr=(struct parameterwrapper *)currobj->flagptr;
812
813     /*Remove object from all queues */
814     while(flagptr!=NULL) {
815       struct parameterwrapper *next;
816       int UNUSED, UNUSED2;
817       int * enterflags;
818       ObjectHashget(flagptr->objectset, (int) currobj, (int *) &next, (int *) &enterflags, &UNUSED, &UNUSED2);
819       ObjectHashremove(flagptr->objectset, (int)currobj);
820       if (enterflags!=NULL)
821         free(enterflags);
822       flagptr=next;
823     }
824
825     /* Failed in failed state */
826     int i;
827     int offset=0;
828     for(i=0; i<currobj->numfses; i++) {
829       int numfses=currobj->fses[offset++];
830       int j;
831       struct failedtasklist *andlist=NULL;
832       for(j=0; j<numfses; j++) {
833         int flagstate=currobj->fses[offset++];
834         struct failedtasklist *currlist=processnormfailstate(classwrapper, currobj, flagstate);
835         if (andlist==NULL)
836           andlist=currlist;
837         else
838           mergefailedlists(&andlist, currlist);
839       }
840       enqueuelist(currobj, andlist);
841     }
842   }
843 }
844
845
846 #endif
847
848 int enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *prevptr, struct ___Object___ *ptr, int * enterflags, int numenterflags) {
849   void * taskpointerarray[MAXTASKPARAMS];
850 #ifdef OPTIONAL
851   int failed[MAXTASKPARAMS];
852 #endif
853   int j;
854   int numparams=parameter->task->numParameters;
855   int numiterators=parameter->task->numTotal-1;
856   int retval=1;
857   int addnormal=1;
858   int adderror=1;
859
860   struct taskdescriptor * task=parameter->task;
861
862 #ifdef OPTIONAL
863   if (ObjectHashcontainskey(parameter->objectset, (int) ptr)) {
864     /* The object is already here...or it with the existing item */
865     int * oldflags;
866     int oldnumflags;
867     int oldptr;
868     int oldstatus;
869     int *mergedflags;
870     ObjectHashget(parameter->objectset, (int) ptr, &oldptr, (int *) &oldflags, &oldnumflags, &oldstatus);
871     mergedflags=domergeor(oldflags, oldnumflags, enterflags, numenterflags);
872     ObjectHashupdate(parameter->objectset, (int) ptr, oldptr, mergedflags, oldnumflags+numenterflags, oldstatus||(enterflags==NULL));
873
874     RUNFREE(oldflags);
875     RUNFREE(enterflags);
876
877     //only add if truly needed
878     if (oldstatus)
879       addnormal=0;
880     if (oldnumflags>0)
881       adderror=0;
882
883     retval=0;
884   } else {
885 #endif
886   ObjectHashadd(parameter->objectset, (int) ptr, (int) prevptr, (int) enterflags, numenterflags, enterflags==NULL);  //this add the object to parameterwrapper
887 #ifdef OPTIONAL
888 }
889 #endif
890
891   /* Add enqueued object to parameter vector */
892   taskpointerarray[parameter->slot]=ptr;
893 #ifdef OPTIONAL
894   failed[parameter->slot]=(enterflags!=NULL);
895 #endif
896
897   /* Reset iterators */
898   for(j=0; j<numiterators; j++) {
899     toiReset(&parameter->iterators[j]);
900   }
901
902   /* Find initial state */
903   for(j=0; j<numiterators; j++) {
904 backtrackinit:
905     if(toiHasNext(&parameter->iterators[j], taskpointerarray OPTARG(failed))) {
906       toiNext(&parameter->iterators[j], taskpointerarray OPTARG(failed));
907     } else if (j>0) {
908       /* Need to backtrack */
909       toiReset(&parameter->iterators[j]);
910       j--;
911       goto backtrackinit;
912     } else {
913       /* Nothing to enqueue */
914       return retval;
915     }
916   }
917
918
919   while(1) {
920     /* Enqueue current state */
921     int launch = 0;
922     struct taskparamdescriptor *tpd=RUNMALLOC(sizeof(struct taskparamdescriptor));
923     tpd->task=task;
924     tpd->numParameters=numiterators+1;
925     tpd->parameterArray=RUNMALLOC(sizeof(void *)*(numiterators+1));
926 #ifdef OPTIONAL
927     tpd->failed=RUNMALLOC(sizeof(int)*(numiterators+1));
928 #endif
929     for(j=0; j<=numiterators; j++) {
930       tpd->parameterArray[j]=taskpointerarray[j]; //store the actual parameters
931 #ifdef OPTIONAL
932       tpd->failed[j]=failed[j];
933       if (failed[j]!=0&&failed[j]!=1) {
934         printf("BAD\n");
935       }
936 #endif
937     }
938     /* Enqueue task */
939     if ((!gencontains(failedtasks, tpd)&&!gencontains(activetasks,tpd))) {
940       genputtable(activetasks, tpd, tpd);
941     } else {
942       RUNFREE(tpd->parameterArray);
943 #ifdef OPTIONAL
944       RUNFREE(tpd->failed);
945 #endif
946       RUNFREE(tpd);
947     }
948
949     /* This loop iterates to the next parameter combination */
950     if (numiterators==0)
951       return retval;
952
953     for(j=numiterators-1; j<numiterators; j++) {
954 backtrackinc:
955       if(toiHasNext(&parameter->iterators[j], taskpointerarray OPTARG(failed))) {
956         toiNext(&parameter->iterators[j], taskpointerarray OPTARG(failed));
957       } else if (j>0) {
958         /* Need to backtrack */
959         toiReset(&parameter->iterators[j]);
960         j--;
961         goto backtrackinc;
962       } else {
963         /* Nothing more to enqueue */
964         return retval;
965       }
966     }
967   }
968   return retval;
969 }
970
971 /* Handler for signals. The signals catch null pointer errors and
972    arithmatic errors. */
973
974 void myhandler(int sig, siginfo_t *info, void *uap) {
975   sigset_t toclear;
976 #ifdef DEBUG
977   printf("sig=%d\n",sig);
978   printf("signal\n");
979 #endif
980   sigemptyset(&toclear);
981   sigaddset(&toclear, sig);
982   sigprocmask(SIG_UNBLOCK, &toclear,NULL);
983   longjmp(error_handler,1);
984 }
985
986 fd_set readfds;
987 int maxreadfd;
988 struct RuntimeHash *fdtoobject;
989
990 void addreadfd(int fd) {
991   if (fd>=maxreadfd)
992     maxreadfd=fd+1;
993   FD_SET(fd, &readfds);
994 }
995
996 void removereadfd(int fd) {
997   FD_CLR(fd, &readfds);
998   if (maxreadfd==(fd+1)) {
999     maxreadfd--;
1000     while(maxreadfd>0&&!FD_ISSET(maxreadfd-1, &readfds))
1001       maxreadfd--;
1002   }
1003 }
1004
1005 #ifdef PRECISE_GC
1006 #define OFFSET 2
1007 #else
1008 #define OFFSET 0
1009 #endif
1010
1011 #ifdef OPTIONAL
1012 int * fsescopy(int *src, int len) {
1013   int *dst;
1014   if (src==NULL)
1015     return NULL;
1016   dst=RUNMALLOC(len*sizeof(int));
1017   memcpy(dst, src, len*sizeof(int));
1018   return dst;
1019 }
1020 #endif
1021
1022 void executetasks() {
1023   void * taskpointerarray[MAXTASKPARAMS+OFFSET];
1024 #ifdef OPTIONAL
1025   int * fsesarray[MAXTASKPARAMS];
1026   int * oldfsesarray[MAXTASKPARAMS];
1027   int numfsesarray[MAXTASKPARAMS];
1028 #endif
1029
1030   /* Set up signal handlers */
1031   struct sigaction sig;
1032   sig.sa_sigaction=&myhandler;
1033   sig.sa_flags=SA_SIGINFO;
1034   sigemptyset(&sig.sa_mask);
1035
1036   /* Catch bus errors, segmentation faults, and floating point exceptions*/
1037   if (!errors) {
1038     sigaction(SIGBUS,&sig,0);
1039     sigaction(SIGSEGV,&sig,0);
1040     sigaction(SIGFPE,&sig,0);
1041     sigaction(SIGPIPE,&sig,0);
1042   }
1043
1044   /* Zero fd set */
1045   FD_ZERO(&readfds);
1046   maxreadfd=0;
1047   fdtoobject=allocateRuntimeHash(100);
1048
1049   /* Map first block of memory to protected, anonymous page */
1050   mmap(0, 0x1000, 0, MAP_SHARED|MAP_FIXED|MAP_ANON, -1, 0);
1051
1052 newtask:
1053   while((hashsize(activetasks)>0)||(maxreadfd>0)) {
1054
1055     /* Check if any filedescriptors have IO pending */
1056     if (maxreadfd>0) {
1057       int i;
1058       struct timeval timeout={0,0};
1059       fd_set tmpreadfds;
1060       int numselect;
1061       tmpreadfds=readfds;
1062       numselect=select(maxreadfd, &tmpreadfds, NULL, NULL, &timeout);
1063       if (numselect>0) {
1064         /* Process ready fd's */
1065         int fd;
1066         for(fd=0; fd<maxreadfd; fd++) {
1067           if (FD_ISSET(fd, &tmpreadfds)) {
1068             /* Set ready flag on object */
1069             void * objptr;
1070             //      printf("Setting fd %d\n",fd);
1071             if (RuntimeHashget(fdtoobject, fd,(int *) &objptr)) {
1072               if(intflagorand(objptr,1,0xFFFFFFFF)) { /* Set the first flag to 1 */
1073                 enqueueObject(objptr);
1074               }
1075             }
1076           }
1077         }
1078       }
1079     }
1080
1081     /* See if there are any active tasks */
1082     if (hashsize(activetasks)>0) {
1083       int i;
1084       currtpd=(struct taskparamdescriptor *) getfirstkey(activetasks);
1085       genfreekey(activetasks, currtpd);
1086
1087       /* Check if this task has failed, allow a task that contains optional objects to fire */
1088       if (gencontains(failedtasks, currtpd)) {
1089         // Free up task parameter descriptor
1090         RUNFREE(currtpd->parameterArray);
1091 #ifdef OPTIONAL
1092         RUNFREE(currtpd->failed);
1093 #endif
1094         RUNFREE(currtpd);
1095         goto newtask;
1096       }
1097       int numparams=currtpd->task->numParameters;
1098       int numtotal=currtpd->task->numTotal;
1099
1100       /* Make sure that the parameters are still in the queues */
1101       for(i=0; i<numparams; i++) {
1102         void * parameter=currtpd->parameterArray[i];
1103         struct parameterdescriptor * pd=currtpd->task->descriptorarray[i];
1104         struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
1105         int j;
1106         /* Check that object is still in queue */
1107 #ifdef OPTIONAL
1108         {
1109           int UNUSED, UNUSED2;
1110           int *flags;
1111           int numflags, isnonfailed;
1112           int failed=currtpd->failed[i];
1113           if (!ObjectHashget(pw->objectset, (int) parameter, &UNUSED, (int *) &flags, &numflags, &isnonfailed)) {
1114             RUNFREE(currtpd->parameterArray);
1115             RUNFREE(currtpd->failed);
1116             RUNFREE(currtpd);
1117             goto newtask;
1118           } else {
1119             if (failed&&(flags!=NULL)) {
1120               //Failed parameter
1121               fsesarray[i]=flags;
1122               numfsesarray[i]=numflags;
1123             } else if (!failed && isnonfailed) {
1124               //Non-failed parameter
1125               fsesarray[i]=NULL;
1126               numfsesarray[i]=0;
1127             } else {
1128               RUNFREE(currtpd->parameterArray);
1129               RUNFREE(currtpd->failed);
1130               RUNFREE(currtpd);
1131               goto newtask;
1132             }
1133           }
1134         }
1135 #else
1136         {
1137           if (!ObjectHashcontainskey(pw->objectset, (int) parameter)) {
1138             RUNFREE(currtpd->parameterArray);
1139             RUNFREE(currtpd);
1140             goto newtask;
1141           }
1142         }
1143 #endif
1144 parameterpresent:
1145         ;
1146         /* Check that object still has necessary tags */
1147         for(j=0; j<pd->numbertags; j++) {
1148           int slotid=pd->tagarray[2*j]+numparams;
1149           struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid];
1150           if (!containstag(parameter, tagd)) {
1151             RUNFREE(currtpd->parameterArray);
1152 #ifdef OPTIONAL
1153             RUNFREE(currtpd->failed);
1154 #endif
1155             RUNFREE(currtpd);
1156             goto newtask;
1157           }
1158         }
1159
1160         taskpointerarray[i+OFFSET]=parameter;
1161       }
1162       /* Copy the tags */
1163       for(; i<numtotal; i++) {
1164         taskpointerarray[i+OFFSET]=currtpd->parameterArray[i];
1165       }
1166
1167       {
1168         /* Checkpoint the state */
1169         forward=cCreate(256, 0.4);
1170         reverse=cCreate(256, 0.4);
1171         void ** checkpoint=makecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, forward, reverse);
1172         int x;
1173         if (x=setjmp(error_handler)) {
1174           int counter;
1175           /* Recover */
1176 #ifdef DEBUG
1177           printf("Fatal Error=%d, Recovering!\n",x);
1178 #endif
1179           genputtable(failedtasks,currtpd,currtpd);
1180           restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse);
1181
1182 #ifdef OPTIONAL
1183           for(counter=0; counter<currtpd->task->numParameters; counter++) {
1184             //enqueue as failed
1185             enqueueoptional(currtpd->parameterArray[counter], numfsesarray[counter], fsesarray[counter], currtpd->task, counter);
1186
1187             //free fses copies
1188             if (fsesarray[counter]!=NULL)
1189               RUNFREE(fsesarray[counter]);
1190           }
1191 #endif
1192           cDelete(forward);
1193           cDelete(reverse);
1194           freemalloc();
1195           forward=NULL;
1196           reverse=NULL;
1197         } else {
1198           if (injectfailures) {
1199             if ((((double)random())/RAND_MAX)<failurechance) {
1200               printf("\nINJECTING TASK FAILURE to %s\n", currtpd->task->name);
1201               longjmp(error_handler,10);
1202             }
1203           }
1204           /* Actually call task */
1205 #ifdef PRECISE_GC
1206                                                                             ((int *)taskpointerarray)[0]=currtpd->numParameters;
1207           taskpointerarray[1]=NULL;
1208 #endif
1209 #ifdef OPTIONAL
1210           //get the task flags set
1211           for(i=0; i<numparams; i++) {
1212             oldfsesarray[i]=((struct ___Object___ *)taskpointerarray[i+OFFSET])->fses;
1213             fsesarray[i]=fsescopy(fsesarray[i], numfsesarray[i]);
1214             ((struct ___Object___ *)taskpointerarray[i+OFFSET])->fses=fsesarray[i];
1215           }
1216 #endif
1217           if(debugtask) {
1218             printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
1219             ((void(*) (void **))currtpd->task->taskptr)(taskpointerarray);
1220             printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
1221           } else
1222             ((void(*) (void **))currtpd->task->taskptr)(taskpointerarray);
1223
1224 #ifdef OPTIONAL
1225           for(i=0; i<numparams; i++) {
1226             //free old fses
1227             if(oldfsesarray[i]!=NULL)
1228               RUNFREE(oldfsesarray[i]);
1229           }
1230 #endif
1231
1232           cDelete(forward);
1233           cDelete(reverse);
1234           freemalloc();
1235           // Free up task parameter descriptor
1236           RUNFREE(currtpd->parameterArray);
1237 #ifdef OPTIONAL
1238           RUNFREE(currtpd->failed);
1239 #endif
1240           RUNFREE(currtpd);
1241           forward=NULL;
1242           reverse=NULL;
1243         }
1244       }
1245     }
1246   }
1247 }
1248
1249 /* This function processes an objects tags */
1250 void processtags(struct parameterdescriptor *pd, int index, struct parameterwrapper *parameter, int * iteratorcount, int *statusarray, int numparams) {
1251   int i;
1252
1253   for(i=0; i<pd->numbertags; i++) {
1254     int slotid=pd->tagarray[2*i];
1255     int tagid=pd->tagarray[2*i+1];
1256
1257     if (statusarray[slotid+numparams]==0) {
1258       parameter->iterators[*iteratorcount].istag=1;
1259       parameter->iterators[*iteratorcount].tagid=tagid;
1260       parameter->iterators[*iteratorcount].slot=slotid+numparams;
1261       parameter->iterators[*iteratorcount].tagobjectslot=index;
1262       statusarray[slotid+numparams]=1;
1263       (*iteratorcount)++;
1264     }
1265   }
1266 }
1267
1268
1269 void processobject(struct parameterwrapper *parameter, int index, struct parameterdescriptor *pd, int *iteratorcount, int * statusarray, int numparams) {
1270   int i;
1271   int tagcount=0;
1272   struct ObjectHash * objectset=((struct parameterwrapper *)pd->queue)->objectset;
1273
1274   parameter->iterators[*iteratorcount].istag=0;
1275   parameter->iterators[*iteratorcount].slot=index;
1276   parameter->iterators[*iteratorcount].objectset=objectset;
1277   statusarray[index]=1;
1278
1279   for(i=0; i<pd->numbertags; i++) {
1280     int slotid=pd->tagarray[2*i];
1281     int tagid=pd->tagarray[2*i+1];
1282     if (statusarray[slotid+numparams]!=0) {
1283       /* This tag has already been enqueued, use it to narrow search */
1284       parameter->iterators[*iteratorcount].tagbindings[tagcount]=slotid+numparams;
1285       tagcount++;
1286     }
1287   }
1288   parameter->iterators[*iteratorcount].numtags=tagcount;
1289
1290   (*iteratorcount)++;
1291 }
1292
1293 /* This function builds the iterators for a task & parameter */
1294
1295 void builditerators(struct taskdescriptor * task, int index, struct parameterwrapper * parameter) {
1296   int statusarray[MAXTASKPARAMS];
1297   int i;
1298   int numparams=task->numParameters;
1299   int iteratorcount=0;
1300   for(i=0; i<MAXTASKPARAMS; i++) statusarray[i]=0;
1301
1302   statusarray[index]=1; /* Initial parameter */
1303   /* Process tags for initial iterator */
1304
1305   processtags(task->descriptorarray[index], index, parameter, &iteratorcount, statusarray, numparams);
1306
1307   while(1) {
1308 loopstart:
1309     /* Check for objects with existing tags */
1310     for(i=0; i<numparams; i++) {
1311       if (statusarray[i]==0) {
1312         struct parameterdescriptor *pd=task->descriptorarray[i];
1313         int j;
1314         for(j=0; j<pd->numbertags; j++) {
1315           int slotid=pd->tagarray[2*j];
1316           if(statusarray[slotid+numparams]!=0) {
1317             processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
1318             processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
1319             goto loopstart;
1320           }
1321         }
1322       }
1323     }
1324
1325     /* Next do objects w/ unbound tags*/
1326
1327     for(i=0; i<numparams; i++) {
1328       if (statusarray[i]==0) {
1329         struct parameterdescriptor *pd=task->descriptorarray[i];
1330         if (pd->numbertags>0) {
1331           processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
1332           processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
1333           goto loopstart;
1334         }
1335       }
1336     }
1337
1338     /* Nothing with a tag enqueued */
1339
1340     for(i=0; i<numparams; i++) {
1341       if (statusarray[i]==0) {
1342         struct parameterdescriptor *pd=task->descriptorarray[i];
1343         processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
1344         processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
1345         goto loopstart;
1346       }
1347     }
1348
1349     /* Nothing left */
1350     return;
1351   }
1352 }
1353
1354 void printdebug() {
1355   int i;
1356   int j;
1357   for(i=0; i<numtasks; i++) {
1358     struct taskdescriptor * task=taskarray[i];
1359     printf("%s\n", task->name);
1360     for(j=0; j<task->numParameters; j++) {
1361       struct parameterdescriptor *param=task->descriptorarray[j];
1362       struct parameterwrapper *parameter=param->queue;
1363       struct ObjectHash * set=parameter->objectset;
1364       struct ObjectIterator objit;
1365       printf("  Parameter %d\n", j);
1366       ObjectHashiterator(set, &objit);
1367       while(ObjhasNext(&objit)) {
1368         struct ___Object___ * obj=(struct ___Object___ *)Objkey(&objit);
1369         struct ___Object___ * tagptr=obj->___tags___;
1370         int nonfailed=Objdata4(&objit);
1371         int numflags=Objdata3(&objit);
1372         int flags=Objdata2(&objit);
1373         Objnext(&objit);
1374         printf("    Contains %lx\n", obj);
1375         printf("      flag=%d\n", obj->flag);
1376 #ifdef OPTIONAL
1377         printf("      flagsstored=%x\n",flags);
1378         printf("      numflags=%d\n", numflags);
1379         printf("      nonfailed=%d\n",nonfailed);
1380 #endif
1381         if (tagptr==NULL) {
1382         } else if (tagptr->type==TAGTYPE) {
1383           printf("      tag=%lx\n",tagptr);
1384         } else {
1385           int tagindex=0;
1386           struct ArrayObject *ao=(struct ArrayObject *)tagptr;
1387           for(; tagindex<ao->___cachedCode___; tagindex++) {
1388             printf("      tag=%lx\n",ARRAYGET(ao, struct ___TagDescriptor___*, tagindex));
1389           }
1390         }
1391       }
1392     }
1393   }
1394 }
1395
1396
1397 /* This function processes the task information to create queues for
1398    each parameter type. */
1399
1400 void processtasks() {
1401   int i;
1402   for(i=0; i<numtasks; i++) {
1403     struct taskdescriptor * task=taskarray[i];
1404     int j;
1405
1406     for(j=0; j<task->numParameters; j++) {
1407       struct parameterdescriptor *param=task->descriptorarray[j];
1408       struct parameterwrapper * parameter=RUNMALLOC(sizeof(struct parameterwrapper));
1409       struct parameterwrapper ** ptr=&objectqueues[param->type];
1410
1411       param->queue=parameter;
1412       parameter->objectset=allocateObjectHash(10);
1413       parameter->numberofterms=param->numberterms;
1414       parameter->intarray=param->intarray;
1415       parameter->numbertags=param->numbertags;
1416       parameter->tagarray=param->tagarray;
1417       parameter->task=task;
1418       parameter->slot=j;
1419       /* Link new queue in */
1420       while((*ptr)!=NULL)
1421         ptr=&((*ptr)->next);
1422       (*ptr)=parameter;
1423     }
1424
1425     /* Build iterators for parameters */
1426     for(j=0; j<task->numParameters; j++) {
1427       struct parameterdescriptor *param=task->descriptorarray[j];
1428       struct parameterwrapper *parameter=param->queue;
1429       builditerators(task, j, parameter);
1430     }
1431   }
1432 }
1433
1434 void toiReset(struct tagobjectiterator * it) {
1435   if (it->istag) {
1436     it->tagobjindex=0;
1437   } else if (it->numtags>0) {
1438     it->tagobjindex=0;
1439 #ifdef OPTIONAL
1440     it->failedstate=0;
1441 #endif
1442   } else {
1443     ObjectHashiterator(it->objectset, &it->it);
1444 #ifdef OPTIONAL
1445     it->failedstate=0;
1446 #endif
1447   }
1448 }
1449
1450 int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * failed)) {
1451   if (it->istag) {
1452     /* Iterate tag */
1453     /* Get object with tags */
1454     struct ___Object___ *obj=objectarray[it->tagobjectslot];
1455     struct ___Object___ *tagptr=obj->___tags___;
1456     if (tagptr->type==TAGTYPE) {
1457       if ((it->tagobjindex==0)&& /* First object */
1458           (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */
1459         return 1;
1460       else
1461         return 0;
1462     } else {
1463       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
1464       int tagindex=it->tagobjindex;
1465       for(; tagindex<ao->___cachedCode___; tagindex++) {
1466         struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex);
1467         if (td->flag==it->tagid) {
1468           it->tagobjindex=tagindex; /* Found right type of tag */
1469           return 1;
1470         }
1471       }
1472       return 0;
1473     }
1474   } else if (it->numtags>0) {
1475     /* Use tags to locate appropriate objects */
1476     struct ___TagDescriptor___ *tag=objectarray[it->tagbindings[0]];
1477     struct ___Object___ *objptr=tag->flagptr;
1478     int i;
1479     if (objptr->type!=OBJECTARRAYTYPE) {
1480       if (it->tagobjindex>0)
1481         return 0;
1482       if (!ObjectHashcontainskey(it->objectset, (int) objptr))
1483         return 0;
1484       for(i=1; i<it->numtags; i++) {
1485         struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
1486         if (!containstag(objptr,tag2))
1487           return 0;
1488       }
1489 #ifdef OPTIONAL
1490       if (it->failedstate==1) {
1491         int UNUSED, UNUSED2;
1492         int * flags;
1493         int isnonfailed;
1494         ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
1495         if (flags!=NULL) {
1496           return 1;
1497         } else {
1498           it->tagobjindex++;
1499           it->failedstate=0;
1500           return 0;
1501         }
1502       } else {
1503         int UNUSED, UNUSED2;
1504         int * flags;
1505         int isnonfailed;
1506         ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
1507         if (!isnonfailed) {
1508           it->failedstate=1;
1509         }
1510         return 1;
1511       }
1512 #endif
1513       return 1;
1514     } else {
1515       struct ArrayObject *ao=(struct ArrayObject *) objptr;
1516       int tagindex;
1517       int i;
1518 #ifdef OPTIONAL
1519       if (it->failedstate==1) {
1520         int UNUSED, UNUSED2;
1521         int * flags;
1522         int isnonfailed;
1523         struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, it->tagobjindex);
1524         ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
1525         if (flags!=NULL) {
1526           return 1;
1527         } else {
1528           it->failedstate=0;
1529           it->tagobjindex++;
1530         }
1531       }
1532 #endif
1533       for(tagindex=it->tagobjindex; tagindex<ao->___cachedCode___; tagindex++) {
1534         struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
1535         if (!ObjectHashcontainskey(it->objectset, (int) objptr))
1536           continue;
1537         for(i=1; i<it->numtags; i++) {
1538           struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
1539           if (!containstag(objptr,tag2))
1540             goto nexttag;
1541         }
1542 #ifdef OPTIONAL
1543         {
1544           int UNUSED, UNUSED2;
1545           int flags, isnonfailed;
1546           struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
1547           ObjectHashget(it->objectset, (int) objptr, &UNUSED, &flags, &UNUSED2, &isnonfailed);
1548           if (!isnonfailed) {
1549             it->failedstate=1;
1550           }
1551         }
1552 #endif
1553         it->tagobjindex=tagindex;
1554         return 1;
1555 nexttag:
1556         ;
1557       }
1558       it->tagobjindex=tagindex;
1559       return 0;
1560     }
1561   } else {
1562 #ifdef OPTIONAL
1563     if (it->failedstate==1) {
1564       if (Objdata2(&it->it))
1565         return 1;
1566       else {
1567         it->failedstate=0;
1568         Objnext(&it->it);
1569       }
1570     }
1571     if (ObjhasNext(&it->it)) {
1572       if (!Objdata4(&it->it)) {
1573         //failed state only
1574         it->failedstate=1;
1575       }
1576       return 1;
1577     } else
1578       return 0;
1579 #else
1580     return ObjhasNext(&it->it);
1581 #endif
1582   }
1583 }
1584
1585 int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) {
1586   int j;
1587   struct ___Object___ * objptr=tag->flagptr;
1588   if (objptr->type==OBJECTARRAYTYPE) {
1589     struct ArrayObject *ao=(struct ArrayObject *)objptr;
1590     for(j=0; j<ao->___cachedCode___; j++) {
1591       if (ptr==ARRAYGET(ao, struct ___Object___*, j))
1592         return 1;
1593     }
1594     return 0;
1595   } else
1596     return objptr==ptr;
1597 }
1598
1599 void toiNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * failed)) {
1600   /* hasNext has all of the intelligence */
1601   if(it->istag) {
1602     /* Iterate tag */
1603     /* Get object with tags */
1604     struct ___Object___ *obj=objectarray[it->tagobjectslot];
1605     struct ___Object___ *tagptr=obj->___tags___;
1606 #ifdef OPTIONAL
1607     failed[it->slot]=0; //have to set it to something
1608 #endif
1609     if (tagptr->type==TAGTYPE) {
1610       it->tagobjindex++;
1611       objectarray[it->slot]=tagptr;
1612     } else {
1613       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
1614       objectarray[it->slot]=ARRAYGET(ao, struct ___TagDescriptor___ *, it->tagobjindex++);
1615     }
1616   } else if (it->numtags>0) {
1617     /* Use tags to locate appropriate objects */
1618     struct ___TagDescriptor___ *tag=objectarray[it->tagbindings[0]];
1619     struct ___Object___ *objptr=tag->flagptr;
1620     if (objptr->type!=OBJECTARRAYTYPE) {
1621 #ifdef OPTIONAL
1622       failed[it->slot]=it->failedstate;
1623       objectarray[it->slot]=objptr;
1624       if (it->failedstate==0) {
1625         it->failedstate=1;
1626       } else {
1627         it->failedstate=0;
1628         it->tagobjindex++;
1629       }
1630 #else
1631       it->tagobjindex++;
1632       objectarray[it->slot]=objptr;
1633 #endif
1634     } else {
1635       struct ArrayObject *ao=(struct ArrayObject *) objptr;
1636 #ifdef OPTIONAL
1637       failed[it->slot]=it->failedstate;
1638       objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex);
1639       if (it->failedstate==0) {
1640         it->failedstate=1;
1641       } else {
1642         it->failedstate=0;
1643         it->tagobjindex++;
1644       }
1645 #else
1646       objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex++);
1647 #endif
1648     }
1649   } else {
1650     /* Iterate object */
1651     void * tmpp = (void *) Objkey(&it->it);
1652     objectarray[it->slot]=tmpp;
1653 #ifdef OPTIONAL
1654     failed[it->slot]=it->failedstate;
1655     if (it->failedstate==0) {
1656       it->failedstate=1;
1657     } else {
1658       it->failedstate=0;
1659       Objnext(&it->it);
1660     }
1661 #else
1662     Objnext(&it->it);
1663 #endif
1664   }
1665 }
1666 #endif