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