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