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