more bugs
[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       if (failed[j]!=0&&failed[j]!=1) {
921         printf("BAD\n");
922       }
923 #endif
924     }
925     /* Enqueue task */
926     if ((!gencontains(failedtasks, tpd)&&!gencontains(activetasks,tpd))) {
927       genputtable(activetasks, tpd, tpd);
928     } else {
929       RUNFREE(tpd->parameterArray);
930 #ifdef OPTIONAL
931       RUNFREE(tpd->failed);
932 #endif
933       RUNFREE(tpd);
934     }
935     
936     /* This loop iterates to the next parameter combination */
937     if (numiterators==0)
938       return retval;
939
940     for(j=numiterators-1; j<numiterators;j++) {
941     backtrackinc:
942       if(toiHasNext(&parameter->iterators[j], taskpointerarray OPTARG(failed)))
943         toiNext(&parameter->iterators[j], taskpointerarray OPTARG(failed));
944       else if (j>0) {
945         /* Need to backtrack */
946         toiReset(&parameter->iterators[j]);
947         j--;
948         goto backtrackinc;
949       } else {
950         /* Nothing more to enqueue */
951         return retval;
952       }
953     }
954   }
955   return retval;
956 }
957  
958 /* Handler for signals. The signals catch null pointer errors and
959    arithmatic errors. */
960
961 void myhandler(int sig, siginfo_t *info, void *uap) {
962   sigset_t toclear;
963 #ifdef DEBUG
964   printf("sig=%d\n",sig);
965   printf("signal\n");
966 #endif
967   sigemptyset(&toclear);
968   sigaddset(&toclear, sig);
969   sigprocmask(SIG_UNBLOCK, &toclear,NULL); 
970   longjmp(error_handler,1);
971 }
972
973 fd_set readfds;
974 int maxreadfd;
975 struct RuntimeHash *fdtoobject;
976
977 void addreadfd(int fd) {
978   if (fd>=maxreadfd)
979     maxreadfd=fd+1;
980   FD_SET(fd, &readfds);
981 }
982
983 void removereadfd(int fd) {
984   FD_CLR(fd, &readfds);
985   if (maxreadfd==(fd+1)) {
986     maxreadfd--;
987     while(maxreadfd>0&&!FD_ISSET(maxreadfd-1, &readfds))
988       maxreadfd--;
989   }
990 }
991
992 #ifdef PRECISE_GC
993 #define OFFSET 2
994 #else
995 #define OFFSET 0
996 #endif
997
998 #ifdef OPTIONAL
999  int * fsescopy(int *src, int len) {
1000    int *dst;
1001    if (src==NULL)
1002      return NULL;
1003    dst=RUNMALLOC(len*sizeof(int));
1004    memcpy(dst, src, len*sizeof(int));
1005    return dst;
1006  }
1007 #endif
1008
1009 void executetasks() {
1010   void * taskpointerarray[MAXTASKPARAMS+OFFSET];
1011 #ifdef OPTIONAL
1012   int * fsesarray[MAXTASKPARAMS];
1013   int * oldfsesarray[MAXTASKPARAMS];
1014   int numfsesarray[MAXTASKPARAMS];
1015 #endif  
1016
1017   /* Set up signal handlers */
1018   struct sigaction sig;
1019   sig.sa_sigaction=&myhandler;
1020   sig.sa_flags=SA_SIGINFO;
1021   sigemptyset(&sig.sa_mask);
1022
1023   /* Catch bus errors, segmentation faults, and floating point exceptions*/
1024   sigaction(SIGBUS,&sig,0);
1025   sigaction(SIGSEGV,&sig,0);
1026   sigaction(SIGFPE,&sig,0);
1027   sigaction(SIGPIPE,&sig,0);
1028
1029   /* Zero fd set */
1030   FD_ZERO(&readfds);
1031   maxreadfd=0;
1032   fdtoobject=allocateRuntimeHash(100);
1033
1034   /* Map first block of memory to protected, anonymous page */
1035   mmap(0, 0x1000, 0, MAP_SHARED|MAP_FIXED|MAP_ANON, -1, 0);
1036
1037   newtask:
1038   while((hashsize(activetasks)>0)||(maxreadfd>0)) {
1039
1040     /* Check if any filedescriptors have IO pending */
1041     if (maxreadfd>0) {
1042       int i;
1043       struct timeval timeout={0,0};
1044       fd_set tmpreadfds;
1045       int numselect;
1046       tmpreadfds=readfds;
1047       numselect=select(maxreadfd, &tmpreadfds, NULL, NULL, &timeout);
1048       if (numselect>0) {
1049         /* Process ready fd's */
1050         int fd;
1051         for(fd=0;fd<maxreadfd;fd++) {
1052           if (FD_ISSET(fd, &tmpreadfds)) {
1053             /* Set ready flag on object */
1054             void * objptr;
1055             //      printf("Setting fd %d\n",fd);
1056             if (RuntimeHashget(fdtoobject, fd,(int *) &objptr)) {
1057               intflagorand(objptr,1,0xFFFFFFFF); /* Set the first flag to 1 */
1058             }
1059           }
1060         }
1061       }
1062     }
1063
1064     /* See if there are any active tasks */
1065     if (hashsize(activetasks)>0) {
1066       int i;
1067       currtpd=(struct taskparamdescriptor *) getfirstkey(activetasks);
1068       genfreekey(activetasks, currtpd);
1069       
1070       /* Check if this task has failed, allow a task that contains optional objects to fire */
1071       if (gencontains(failedtasks, currtpd)) {
1072         // Free up task parameter descriptor
1073         RUNFREE(currtpd->parameterArray);
1074         RUNFREE(currtpd);
1075         goto newtask;
1076       }
1077       int numparams=currtpd->task->numParameters;
1078       int numtotal=currtpd->task->numTotal;
1079       
1080       /* Make sure that the parameters are still in the queues */
1081       for(i=0;i<numparams;i++) {
1082         void * parameter=currtpd->parameterArray[i];
1083         struct parameterdescriptor * pd=currtpd->task->descriptorarray[i];
1084         struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
1085         int j;
1086         /* Check that object is still in queue */
1087 #ifdef OPTIONAL
1088         {
1089           int UNUSED, UNUSED2;
1090           int *flags;
1091           int numflags, isnonfailed;
1092           int failed=currtpd->failed[i];
1093           if (!ObjectHashget(pw->objectset, (int) parameter, &UNUSED, (int *) &flags, &numflags, &isnonfailed)) {
1094             RUNFREE(currtpd->parameterArray);
1095             RUNFREE(currtpd->failed);
1096             RUNFREE(currtpd);
1097             goto newtask;
1098           } else {
1099             if (failed&&(flags!=NULL)) {
1100               //Failed parameter
1101               fsesarray[i]=flags;
1102               numfsesarray[i]=numflags;
1103             } else if (!failed && isnonfailed) {
1104               //Non-failed parameter
1105               fsesarray[i]=NULL;
1106               numfsesarray[i]=0;
1107             } else {
1108               RUNFREE(currtpd->parameterArray);
1109               RUNFREE(currtpd->failed);
1110               RUNFREE(currtpd);
1111               goto newtask;
1112             }
1113           }
1114         }
1115 #else
1116         {
1117           if (!ObjectHashcontainskey(pw->objectset, (int) parameter)) {
1118             RUNFREE(currtpd->parameterArray);
1119             RUNFREE(currtpd);
1120             goto newtask;
1121           }
1122         }
1123 #endif
1124       parameterpresent:
1125         ;
1126         /* Check that object still has necessary tags */
1127         for(j=0;j<pd->numbertags;j++) {
1128           int slotid=pd->tagarray[2*j]+numparams;
1129           struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid];
1130           if (!containstag(parameter, tagd)) {
1131             RUNFREE(currtpd->parameterArray);
1132             RUNFREE(currtpd);
1133             goto newtask;
1134           }
1135         }
1136         
1137         taskpointerarray[i+OFFSET]=parameter;
1138       }
1139       /* Copy the tags */
1140       for(;i<numtotal;i++) {
1141         taskpointerarray[i+OFFSET]=currtpd->parameterArray[i];
1142       }
1143
1144       {
1145         /* Checkpoint the state */
1146         forward=allocateRuntimeHash(100);
1147         reverse=allocateRuntimeHash(100);
1148         void ** checkpoint=makecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, forward, reverse);
1149         int x;
1150         if (x=setjmp(error_handler)) {
1151           int counter;
1152           /* Recover */
1153 #ifdef DEBUG
1154           printf("Fatal Error=%d, Recovering!\n",x);
1155 #endif
1156           genputtable(failedtasks,currtpd,currtpd);
1157           restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse);
1158
1159 #ifdef OPTIONAL
1160           for(counter=0; counter<currtpd->task->numParameters; counter++){
1161             //enqueue as failed
1162             enqueueoptional(currtpd->parameterArray[counter], numfsesarray[counter], fsesarray[counter], currtpd->task, counter);
1163
1164             //free fses copies
1165             if (fsesarray[counter]!=NULL)
1166               RUNFREE(fsesarray[counter]);
1167           }
1168 #endif
1169           freeRuntimeHash(forward);
1170           freeRuntimeHash(reverse);
1171           freemalloc();
1172           forward=NULL;
1173           reverse=NULL;
1174         } else {
1175           if (injectfailures) {
1176             if ((((double)random())/RAND_MAX)<failurechance) {
1177               printf("\nINJECTING TASK FAILURE to %s\n", currtpd->task->name);
1178               longjmp(error_handler,10);
1179             }
1180           }
1181           /* Actually call task */
1182 #ifdef PRECISE_GC
1183           ((int *)taskpointerarray)[0]=currtpd->numParameters;
1184           taskpointerarray[1]=NULL;
1185 #endif
1186 #ifdef OPTIONAL
1187           //get the task flags set
1188           for(i=0;i<numparams;i++) {
1189             oldfsesarray[i]=((struct ___Object___ *)taskpointerarray[i+OFFSET])->fses;
1190             fsesarray[i]=fsescopy(fsesarray[i], numfsesarray[i]);
1191             ((struct ___Object___ *)taskpointerarray[i+OFFSET])->fses=fsesarray[i];         
1192           }
1193 #endif
1194           if(debugtask){
1195             printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
1196             {
1197               int i;
1198               printf("[%x]\n",currtpd);
1199               for(i=0;i<currtpd->numParameters;i++) {
1200                 printf("%x ", currtpd->parameterArray[i]);
1201               }
1202               printf("\n");
1203             }
1204             ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray);
1205             printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
1206           } else
1207             ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray);
1208
1209 #ifdef OPTIONAL
1210           for(i=0;i<numparams;i++) {
1211             //free old fses
1212             if(oldfsesarray[i]!=NULL)
1213               RUNFREE(oldfsesarray[i]);
1214           }
1215 #endif
1216           
1217           freeRuntimeHash(forward);
1218           freeRuntimeHash(reverse);
1219           freemalloc();
1220           // Free up task parameter descriptor
1221           RUNFREE(currtpd->parameterArray);
1222           RUNFREE(currtpd);
1223           forward=NULL;
1224           reverse=NULL;
1225         }
1226       }
1227     }
1228   }
1229 }
1230  
1231 /* This function processes an objects tags */
1232 void processtags(struct parameterdescriptor *pd, int index, struct parameterwrapper *parameter, int * iteratorcount, int *statusarray, int numparams) {
1233   int i;
1234   
1235   for(i=0;i<pd->numbertags;i++) {
1236     int slotid=pd->tagarray[2*i];
1237     int tagid=pd->tagarray[2*i+1];
1238     
1239     if (statusarray[slotid+numparams]==0) {
1240       parameter->iterators[*iteratorcount].istag=1;
1241       parameter->iterators[*iteratorcount].tagid=tagid;
1242       parameter->iterators[*iteratorcount].slot=slotid+numparams;
1243       parameter->iterators[*iteratorcount].tagobjectslot=index;
1244       statusarray[slotid+numparams]=1;
1245       (*iteratorcount)++;
1246     }
1247   }
1248 }
1249
1250
1251 void processobject(struct parameterwrapper *parameter, int index, struct parameterdescriptor *pd, int *iteratorcount, int * statusarray, int numparams) {
1252   int i;
1253   int tagcount=0;
1254   struct ObjectHash * objectset=((struct parameterwrapper *)pd->queue)->objectset;
1255
1256   parameter->iterators[*iteratorcount].istag=0;
1257   parameter->iterators[*iteratorcount].slot=index;
1258   parameter->iterators[*iteratorcount].objectset=objectset;
1259   statusarray[index]=1;
1260
1261   for(i=0;i<pd->numbertags;i++) {
1262     int slotid=pd->tagarray[2*i];
1263     int tagid=pd->tagarray[2*i+1];
1264     if (statusarray[slotid+numparams]!=0) {
1265       /* This tag has already been enqueued, use it to narrow search */
1266       parameter->iterators[*iteratorcount].tagbindings[tagcount]=slotid+numparams;
1267       tagcount++;
1268     }
1269   }
1270   parameter->iterators[*iteratorcount].numtags=tagcount;
1271
1272   (*iteratorcount)++;
1273 }
1274
1275 /* This function builds the iterators for a task & parameter */
1276
1277 void builditerators(struct taskdescriptor * task, int index, struct parameterwrapper * parameter) {
1278   int statusarray[MAXTASKPARAMS];
1279   int i;
1280   int numparams=task->numParameters;
1281   int iteratorcount=0;
1282   for(i=0;i<MAXTASKPARAMS;i++) statusarray[i]=0;
1283
1284   statusarray[index]=1; /* Initial parameter */
1285   /* Process tags for initial iterator */
1286   
1287   processtags(task->descriptorarray[index], index, parameter, & iteratorcount, statusarray, numparams);
1288   
1289   while(1) {
1290   loopstart:
1291     /* Check for objects with existing tags */
1292     for(i=0;i<numparams;i++) {
1293       if (statusarray[i]==0) {
1294         struct parameterdescriptor *pd=task->descriptorarray[i];
1295         int j;
1296         for(j=0;j<pd->numbertags;j++) {
1297           int slotid=pd->tagarray[2*j];
1298           if(statusarray[slotid+numparams]!=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
1307     /* Next do objects w/ unbound tags*/
1308
1309     for(i=0;i<numparams;i++) {
1310       if (statusarray[i]==0) {
1311         struct parameterdescriptor *pd=task->descriptorarray[i];
1312         if (pd->numbertags>0) {
1313           processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
1314           processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
1315           goto loopstart;
1316         }
1317       }
1318     }
1319
1320     /* Nothing with a tag enqueued */
1321
1322     for(i=0;i<numparams;i++) {
1323       if (statusarray[i]==0) {
1324         struct parameterdescriptor *pd=task->descriptorarray[i];
1325         processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
1326         processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
1327         goto loopstart;
1328       }
1329     }
1330
1331     /* Nothing left */
1332     return;
1333   }
1334 }
1335
1336  void printdebug() {
1337    int i;
1338    int j;
1339    for(i=0;i<numtasks;i++) {
1340      struct taskdescriptor * task=taskarray[i];
1341      printf("%s\n", task->name);
1342      for(j=0;j<task->numParameters;j++) {
1343        struct parameterdescriptor *param=task->descriptorarray[j];
1344        struct parameterwrapper *parameter=param->queue;
1345        struct ObjectHash * set=parameter->objectset;
1346        struct ObjectIterator objit;
1347        printf("  Parameter %d\n", j);
1348        ObjectHashiterator(set, &objit);
1349        while(ObjhasNext(&objit)) {
1350          struct ___Object___ * obj=(struct ___Object___ *)Objkey(&objit);
1351          struct ___Object___ * tagptr=obj->___tags___;
1352          Objnext(&objit);
1353          printf("    Contains %lx\n", obj);
1354          printf("      flag=%d\n", obj->flag); 
1355          if (tagptr==NULL) {
1356          } else if (tagptr->type==TAGTYPE) {
1357            printf("      tag=%lx\n",tagptr);
1358          } else {
1359            int tagindex=0;
1360            struct ArrayObject *ao=(struct ArrayObject *)tagptr;
1361            for(;tagindex<ao->___cachedCode___;tagindex++) {
1362              printf("      tag=%lx\n",ARRAYGET(ao, struct ___TagDescriptor___*, tagindex));
1363            }
1364          }
1365        }
1366      }
1367    }
1368  }
1369  
1370
1371 /* This function processes the task information to create queues for
1372    each parameter type. */
1373
1374 void processtasks() {
1375   int i;
1376   for(i=0;i<numtasks;i++) {
1377     struct taskdescriptor * task=taskarray[i];
1378     int j;
1379
1380     for(j=0;j<task->numParameters;j++) {
1381       struct parameterdescriptor *param=task->descriptorarray[j];
1382       struct parameterwrapper * parameter=RUNMALLOC(sizeof(struct parameterwrapper));
1383       struct parameterwrapper ** ptr=&objectqueues[param->type];
1384
1385       param->queue=parameter;
1386       parameter->objectset=allocateObjectHash(10);
1387       parameter->numberofterms=param->numberterms;
1388       parameter->intarray=param->intarray;
1389       parameter->numbertags=param->numbertags;
1390       parameter->tagarray=param->tagarray;
1391       parameter->task=task;
1392       /* Link new queue in */
1393       while((*ptr)!=NULL)
1394         ptr=&((*ptr)->next);
1395       (*ptr)=parameter;
1396     }
1397
1398     /* Build iterators for parameters */
1399     for(j=0;j<task->numParameters;j++) {
1400       struct parameterdescriptor *param=task->descriptorarray[j];
1401       struct parameterwrapper *parameter=param->queue;      
1402       parameter->slot=j;
1403       builditerators(task, j, parameter);
1404     }
1405   }
1406 }
1407
1408 void toiReset(struct tagobjectiterator * it) {
1409   if (it->istag) {
1410     it->tagobjindex=0;
1411   } else if (it->numtags>0) {
1412     it->tagobjindex=0;
1413 #ifdef OPTIONAL
1414     it->failedstate=0;
1415 #endif
1416   } else {
1417     ObjectHashiterator(it->objectset, &it->it);
1418 #ifdef OPTIONAL
1419     it->failedstate=0;
1420 #endif
1421   }
1422 }
1423
1424 int toiHasNext(struct tagobjectiterator *it, void ** objectarray OPTARG(int * failed)) {
1425   if (it->istag) {
1426     /* Iterate tag */
1427     /* Get object with tags */
1428     struct ___Object___ *obj=objectarray[it->tagobjectslot];
1429     struct ___Object___ *tagptr=obj->___tags___;
1430     if (tagptr->type==TAGTYPE) {
1431       if ((it->tagobjindex==0)&& /* First object */
1432           (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */
1433         return 1;
1434       else
1435         return 0;
1436     } else {
1437       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
1438       int tagindex=it->tagobjindex;
1439       for(;tagindex<ao->___cachedCode___;tagindex++) {
1440         struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex);
1441         if (td->flag==it->tagid) {
1442           it->tagobjindex=tagindex; /* Found right type of tag */
1443           return 1;
1444         }
1445       }
1446       return 0;
1447     }
1448   } else if (it->numtags>0) {
1449     /* Use tags to locate appropriate objects */
1450     struct ___TagDescriptor___ *tag=objectarray[it->tagbindings[0]];
1451     struct ___Object___ *objptr=tag->flagptr;
1452     int i;
1453     if (objptr->type!=OBJECTARRAYTYPE) {
1454       if (it->tagobjindex>0)
1455         return 0;
1456       if (!ObjectHashcontainskey(it->objectset, (int) objptr))
1457         return 0;
1458       for(i=1;i<it->numtags;i++) {
1459         struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
1460         if (!containstag(objptr,tag2))
1461           return 0;
1462       }
1463 #ifdef OPTIONAL
1464       if (it->failedstate==1) {
1465         int UNUSED, UNUSED2;
1466         int * flags;
1467         int isnonfailed;
1468         ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
1469         if (flags!=NULL) {
1470           return 1;
1471         } else {
1472           it->tagobjindex++;
1473           it->failedstate=0;
1474           return 0;
1475         }
1476       } else {
1477         int UNUSED, UNUSED2;
1478         int * flags;
1479         int isnonfailed;
1480         ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
1481         if (!isnonfailed) {
1482           it->failedstate=1;
1483         }
1484         return 1;
1485       }
1486 #endif      
1487       return 1;
1488     } else {
1489       struct ArrayObject *ao=(struct ArrayObject *) objptr;
1490       int tagindex;
1491       int i;
1492 #ifdef OPTIONAL
1493       if (it->failedstate==1) {
1494         int UNUSED, UNUSED2;
1495         int * flags;
1496         int isnonfailed;
1497         struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, it->tagobjindex);
1498         ObjectHashget(it->objectset, (int) objptr, &UNUSED, (int *) &flags, &UNUSED2, &isnonfailed);
1499         if (flags!=NULL) {
1500           return 1;
1501         } else {
1502           it->failedstate=0;
1503           it->tagobjindex++;
1504         }
1505       }
1506 #endif
1507       for(tagindex=it->tagobjindex;tagindex<ao->___cachedCode___;tagindex++) {
1508         struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
1509         if (!ObjectHashcontainskey(it->objectset, (int) objptr))
1510           continue;
1511         for(i=1;i<it->numtags;i++) {
1512           struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
1513           if (!containstag(objptr,tag2))
1514             goto nexttag;
1515         }
1516 #ifdef OPTIONAL
1517         {
1518           int UNUSED, UNUSED2;
1519           int flags, isnonfailed;
1520           struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
1521           ObjectHashget(it->objectset, (int) objptr, &UNUSED, &flags, &UNUSED2, &isnonfailed);
1522           if (!isnonfailed) {
1523             it->failedstate=1;
1524           }
1525         }
1526 #endif
1527         it->tagobjindex=tagindex;
1528         return 1;
1529       nexttag:
1530         ;
1531       }
1532       it->tagobjindex=tagindex;
1533       return 0;
1534     }
1535   } else {
1536 #ifdef OPTIONAL
1537     if (it->failedstate==1) {
1538       if (Objdata2(&it->it))
1539         return 1;
1540       else {
1541         it->failedstate=0;
1542         Objnext(&it->it);
1543       }
1544     }
1545     if (ObjhasNext(&it->it)) {
1546       if (!Objdata4(&it->it)) {
1547         //failed state only
1548         it->failedstate=1;
1549       }
1550       return 1;
1551     } else
1552       return 0;
1553 #else
1554     return ObjhasNext(&it->it);
1555 #endif
1556   }
1557 }
1558
1559 int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) {
1560   int j;
1561   struct ___Object___ * objptr=tag->flagptr;
1562   if (objptr->type==OBJECTARRAYTYPE) {
1563     struct ArrayObject *ao=(struct ArrayObject *)objptr;
1564     for(j=0;j<ao->___cachedCode___;j++) {
1565       if (ptr==ARRAYGET(ao, struct ___Object___*, j))
1566         return 1;
1567     }
1568     return 0;
1569   } else
1570     return objptr==ptr;
1571 }
1572
1573 void toiNext(struct tagobjectiterator *it , void ** objectarray OPTARG(int * failed)) {
1574   /* hasNext has all of the intelligence */
1575   if(it->istag) {
1576     /* Iterate tag */
1577     /* Get object with tags */
1578     struct ___Object___ *obj=objectarray[it->tagobjectslot];
1579     struct ___Object___ *tagptr=obj->___tags___;
1580 #ifdef OPTIONAL
1581     failed[it->slot]=0; //have to set it to something
1582 #endif
1583     if (tagptr->type==TAGTYPE) {
1584       it->tagobjindex++;
1585       objectarray[it->slot]=tagptr;
1586     } else {
1587       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
1588       objectarray[it->slot]=ARRAYGET(ao, struct ___TagDescriptor___ *, it->tagobjindex++);
1589     }
1590   } else if (it->numtags>0) {
1591     /* Use tags to locate appropriate objects */
1592     struct ___TagDescriptor___ *tag=objectarray[it->tagbindings[0]];
1593     struct ___Object___ *objptr=tag->flagptr;
1594     if (objptr->type!=OBJECTARRAYTYPE) {
1595 #ifdef OPTIONAL
1596     failed[it->slot]=it->failedstate;
1597     objectarray[it->slot]=objptr;
1598     if (it->failedstate==0) {
1599       it->failedstate=1;
1600     } else {
1601       it->failedstate=0;
1602       it->tagobjindex++;
1603     }
1604 #else
1605       it->tagobjindex++;
1606       objectarray[it->slot]=objptr;
1607 #endif
1608     } else {
1609       struct ArrayObject *ao=(struct ArrayObject *) objptr;
1610 #ifdef OPTIONAL
1611     failed[it->slot]=it->failedstate;
1612     objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex);
1613     if (it->failedstate==0) {
1614       it->failedstate=1;
1615     } else {
1616       it->failedstate=0;
1617       it->tagobjindex++;
1618     }
1619 #else
1620       objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex++);
1621 #endif
1622     }
1623   } else {
1624     /* Iterate object */
1625     objectarray[it->slot]=(void *)Objkey(&it->it);
1626 #ifdef OPTIONAL
1627     failed[it->slot]=it->failedstate;
1628     if (it->failedstate==0) {
1629       it->failedstate=1;
1630     } else {
1631       it->failedstate=0;
1632       Objnext(&it->it);
1633     }
1634 #else
1635     Objnext(&it->it);
1636 #endif
1637   }
1638 }
1639 #endif