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