add another field
[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   return 1;
101 }
102
103 /* This function sets a tag. */
104 #ifdef PRECISE_GC
105 void tagset(void *ptr, struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
106 #else
107 void tagset(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
108 #endif
109   struct ___Object___ * tagptr=obj->___tags___;
110   if (tagptr==NULL) {
111     obj->___tags___=(struct ___Object___ *)tagd;
112   } else {
113     /* Have to check if it is already set */
114     if (tagptr->type==TAGTYPE) {
115       struct ___TagDescriptor___ * td=(struct ___TagDescriptor___ *) tagptr;
116       if (td==tagd)
117         return;
118 #ifdef PRECISE_GC
119       int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
120       struct ArrayObject * ao=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL);
121       obj=(struct ___Object___ *)ptrarray[2];
122       tagd=(struct ___TagDescriptor___ *)ptrarray[3];
123       td=(struct ___TagDescriptor___ *) obj->___tags___;
124 #else
125       struct ArrayObject * ao=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL);
126 #endif
127       ARRAYSET(ao, struct ___TagDescriptor___ *, 0, td);
128       ARRAYSET(ao, struct ___TagDescriptor___ *, 1, tagd);
129       obj->___tags___=(struct ___Object___ *) ao;
130       ao->___cachedCode___=2;
131     } else {
132       /* Array Case */
133       int i;
134       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
135       for(i=0;i<ao->___cachedCode___;i++) {
136         struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___*, i);
137         if (td==tagd)
138           return;
139       }
140       if (ao->___cachedCode___<ao->___length___) {
141         ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, tagd);
142         ao->___cachedCode___++;
143       } else {
144 #ifdef PRECISE_GC
145         int ptrarray[]={2,(int) ptr, (int) obj, (int) tagd};
146         struct ArrayObject * aonew=allocate_newarray(&ptrarray,TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
147         obj=(struct ___Object___ *)ptrarray[2];
148         tagd=(struct ___TagDescriptor___ *) ptrarray[3];
149         ao=(struct ArrayObject *)obj->___tags___;
150 #else
151         struct ArrayObject * aonew=allocate_newarray(TAGARRAYTYPE,TAGARRAYINTERVAL+ao->___length___);
152 #endif
153         aonew->___cachedCode___=ao->___length___+1;
154         for(i=0;i<ao->___length___;i++) {
155           ARRAYSET(aonew, struct ___TagDescriptor___*, i, ARRAYGET(ao, struct ___TagDescriptor___*, i));
156         }
157         ARRAYSET(aonew, struct ___TagDescriptor___ *, ao->___length___, tagd);
158       }
159     }
160   }
161
162   {
163     struct ___Object___ * tagset=tagd->flagptr;
164     
165     if(tagset==NULL) {
166       tagd->flagptr=obj;
167     } else if (tagset->type!=OBJECTARRAYTYPE) {
168 #ifdef PRECISE_GC
169       int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
170       struct ArrayObject * ao=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
171       obj=(struct ___Object___ *)ptrarray[2];
172       tagd=(struct ___TagDescriptor___ *)ptrarray[3];
173 #else
174       struct ArrayObject * ao=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
175 #endif
176       ARRAYSET(ao, struct ___Object___ *, 0, tagd->flagptr);
177       ARRAYSET(ao, struct ___Object___ *, 1, obj);
178       ao->___cachedCode___=2;
179       tagd->flagptr=(struct ___Object___ *)ao;
180     } else {
181       struct ArrayObject *ao=(struct ArrayObject *) tagset;
182       if (ao->___cachedCode___<ao->___length___) {
183         ARRAYSET(ao, struct ___Object___*, ao->___cachedCode___++, obj);
184       } else {
185         int i;
186 #ifdef PRECISE_GC
187         int ptrarray[]={2, (int) ptr, (int) obj, (int)tagd};
188         struct ArrayObject * aonew=allocate_newarray(&ptrarray,OBJECTARRAYTYPE,OBJECTARRAYINTERVAL+ao->___length___);
189         obj=(struct ___Object___ *)ptrarray[2];
190         tagd=(struct ___TagDescriptor___ *)ptrarray[3];
191         ao=(struct ArrayObject *)tagd->flagptr;
192 #else
193         struct ArrayObject * aonew=allocate_newarray(OBJECTARRAYTYPE,OBJECTARRAYINTERVAL);
194 #endif
195         aonew->___cachedCode___=ao->___cachedCode___+1;
196         for(i=0;i<ao->___length___;i++) {
197           ARRAYSET(aonew, struct ___Object___*, i, ARRAYGET(ao, struct ___Object___*, i));
198         }
199         ARRAYSET(aonew, struct ___Object___ *, ao->___cachedCode___, obj);
200         tagd->flagptr=(struct ___Object___ *) ao;
201       }
202     }
203   }
204 }
205
206 /* This function clears a tag. */
207 #ifdef PRECISE_GC
208 void tagclear(void *ptr, struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
209 #else
210 void tagclear(struct ___Object___ * obj, struct ___TagDescriptor___ * tagd) {
211 #endif
212   /* We'll assume that tag is alway there.
213      Need to statically check for this of course. */
214   struct ___Object___ * tagptr=obj->___tags___;
215
216   if (tagptr->type==TAGTYPE) {
217     if ((struct ___TagDescriptor___ *)tagptr==tagd)
218       obj->___tags___=NULL;
219     else
220       printf("ERROR 1 in tagclear\n");
221   } else {
222     struct ArrayObject *ao=(struct ArrayObject *) tagptr;
223     int i;
224     for(i=0;i<ao->___cachedCode___;i++) {
225       struct ___TagDescriptor___ * td=ARRAYGET(ao, struct ___TagDescriptor___ *, i);
226       if (td==tagd) {
227         ao->___cachedCode___--;
228         if (i<ao->___cachedCode___)
229           ARRAYSET(ao, struct ___TagDescriptor___ *, i, ARRAYGET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___));
230         ARRAYSET(ao, struct ___TagDescriptor___ *, ao->___cachedCode___, NULL);
231         if (ao->___cachedCode___==0)
232           obj->___tags___=NULL;
233         goto PROCESSCLEAR;
234       }
235     }
236     printf("ERROR 2 in tagclear\n");
237   }
238  PROCESSCLEAR:
239   {
240     struct ___Object___ *tagset=tagd->flagptr;
241     if (tagset->type!=OBJECTARRAYTYPE) {
242       if (tagset==obj)
243         tagd->flagptr=NULL;
244       else
245         printf("ERROR 3 in tagclear\n");
246     } else {
247       struct ArrayObject *ao=(struct ArrayObject *) tagset;
248       int i;
249       for(i=0;i<ao->___cachedCode___;i++) {
250         struct ___Object___ * tobj=ARRAYGET(ao, struct ___Object___ *, i);
251         if (tobj==obj) {
252           ao->___cachedCode___--;
253           if (i<ao->___cachedCode___)
254             ARRAYSET(ao, struct ___Object___ *, i, ARRAYGET(ao, struct ___Object___ *, ao->___cachedCode___));
255           ARRAYSET(ao, struct ___Object___ *, ao->___cachedCode___, NULL);
256           if (ao->___cachedCode___==0)
257             tagd->flagptr=NULL;
258           goto ENDCLEAR;
259         }
260       }
261       printf("ERROR 4 in tagclear\n");
262     }
263   }
264  ENDCLEAR:
265   return;
266   
267 }
268  
269 /* This function allocates a new tag. */
270 #ifdef PRECISE_GC
271 struct ___TagDescriptor___ * allocate_tag(void *ptr, int index) {
272   struct ___TagDescriptor___ * v=(struct ___TagDescriptor___ *) mygcmalloc((struct garbagelist *) ptr, classsize[TAGTYPE]);
273 #else
274 struct ___TagDescriptor___ * allocate_tag(int index) {
275   struct ___TagDescriptor___ * v=FREEMALLOC(classsize[TAGTYPE]);
276 #endif
277   v->type=TAGTYPE;
278   v->flag=index;
279   return v;
280
281
282
283
284 /* This function updates the flag for object ptr.  It or's the flag
285    with the or mask and and's it with the andmask. */
286
287 void flagbody(struct ___Object___ *ptr, int flag);
288 #ifdef OPTIONAL
289 void enqueueoptional(struct ___Object___ * currobj);
290
291 struct optionaltaskdescriptor *** makeintersectionotd(int num, struct fsanalysiswrapper ** wrapperarray, int *result){
292   int i,j,k;
293   (*result)=0;
294   struct optionaltaskdescriptor *** bigtmparray = RUNMALLOC(sizeof(struct optionaltaskdescriptor **)*maxotd);
295   struct fsanalysiswrapper * tmpwrapper;
296   struct fsanalysiswrapper * firstwrapper = wrapperarray[0];/*we are sure that num>0*/
297   /*we check if the otd of the first wrapper is contained in all others*/
298   for(i=0; i<firstwrapper->numoptionaltaskdescriptors; i++){
299     struct optionaltaskdescriptor ** tmparray = RUNMALLOC(sizeof(struct optionaltaskdescriptor *) * num);
300     struct optionaltaskdescriptor * otd = firstwrapper->optionaltaskdescriptorarray[i];
301     tmparray[0]=otd;
302     for(j=1; j<num; j++){
303       tmpwrapper = wrapperarray[j];
304       for(k=0; k<tmpwrapper->numoptionaltaskdescriptors; k++){
305         struct optionaltaskdescriptor * tmpotd=tmpwrapper->optionaltaskdescriptorarray[k];
306         if(otd->task->name == tmpotd->task->name){
307           tmparray[j]=tmpotd;
308           goto nextwrapper;
309         }
310         RUNFREE(tmparray);
311         goto nextotd;
312       }
313     nextwrapper:
314       ;
315     }
316     bigtmparray[(*result)]=tmparray;
317     (*result)++;          
318   nextotd:
319     ;
320   }
321   
322   {/*now allocate the good size for otdarray and put the otds*/
323     struct optionaltaskdescriptor *** otdarray = RUNMALLOC(sizeof(struct optionaltaskdescriptor *) * (*result));
324     for(i=0; i<(*result); i++)     
325       otdarray[i]=bigtmparray[i];
326     
327     RUNFREE(bigtmparray);
328     return otdarray;
329   }
330 }
331 #endif
332  
333
334 void flagorand(void * ptr, int ormask, int andmask) {
335   int oldflag=((int *)ptr)[1];
336   int flag=ormask|oldflag;
337 #ifdef OPTIONAL
338   struct ___Object___ * obj = (struct ___Object___ *)ptr;
339   if(obj->failedstatus==1){/*store the information about exitfses*/
340     int i,j,counter=0, offset=0;
341     for(i=0; i<obj->numotds; i++){
342       counter+=obj->otds[i]->numenterflags;
343     }
344     obj->numexitfses=counter;
345     if(obj->exitfses!=NULL) RUNFREE(obj->exitfses);
346     obj->exitfses= RUNMALLOC(sizeof(int) * counter);
347     for(i=0; i<obj->numotds; i++){
348       for(j=0; j<obj->otds[i]->numenterflags; j++){
349         oldflag=obj->otds[i]->enterflags[j];
350         flag=ormask|oldflag;
351         flag&=andmask;
352         obj->exitfses[j+offset]=flag;
353       }
354       offset+=obj->otds[i]->numenterflags;
355     }
356     enqueueoptional(ptr);
357   }
358   else
359 #endif
360     {
361     flag&=andmask;
362     // Not sure why this was necessary
363     //  if (flag==oldflag) /* Don't do anything */
364     //  return;
365     //else 
366     flagbody(ptr, flag);
367     }
368 }
369  
370 void intflagorand(void * ptr, int ormask, int andmask) {
371   int oldflag=((int *)ptr)[1];
372   int flag=ormask|oldflag;
373 #ifdef OPTIONAL
374   struct ___Object___ * obj = (struct ___Object___ *)ptr;
375   if(obj->failedstatus==1){/*store the information about exitfses*/
376     int i,j,counter=0, offset=0;
377     for(i=0; i<obj->numotds; i++){
378       counter+=obj->otds[i]->numenterflags;
379     }
380     obj->numexitfses=counter;
381     if(obj->exitfses!=NULL) RUNFREE(obj->exitfses);
382     obj->exitfses= RUNMALLOC(sizeof(int) * counter);
383     for(i=0; i<obj->numotds; i++){
384       for(j=0; j<obj->otds[i]->numenterflags; j++){
385         oldflag=obj->otds[i]->enterflags[j];
386         flag=ormask|oldflag;
387         flag&=andmask;
388         obj->exitfses[j+offset]=flag;
389       }
390       offset+=obj->otds[i]->numenterflags;
391     }
392     enqueueoptional(ptr);
393   }
394   else
395 #endif
396     {
397     flag&=andmask;
398     if (flag==oldflag) /* Don't do anything */
399       return;
400     else flagbody(ptr, flag);
401     }
402 }
403
404 void flagorandinit(void * ptr, int ormask, int andmask) {
405   int oldflag=((int *)ptr)[1];
406   int flag=ormask|oldflag;
407 #ifdef OPTIONAL
408   struct ___Object___ * obj = (struct ___Object___ *)ptr;
409   if(obj->failedstatus==1){/*store the information about exitfses*/
410     int i,j,counter=0, offset=0;
411     for(i=0; i<obj->numotds; i++){
412       counter+=obj->otds[i]->numenterflags;
413     }
414     obj->numexitfses=counter;
415     if(obj->exitfses!=NULL) RUNFREE(obj->exitfses);
416     obj->exitfses= RUNMALLOC(sizeof(int) * counter);
417     for(i=0; i<obj->numotds; i++){
418       for(j=0; j<obj->otds[i]->numenterflags; j++){
419         oldflag=obj->otds[i]->enterflags[j];
420         flag=ormask|oldflag;
421         flag&=andmask;
422         obj->exitfses[j+offset]=flag;
423       }
424       offset+=obj->otds[i]->numenterflags;
425     }
426     enqueueoptional(ptr);
427   }
428   else
429 #endif
430     {
431     flag&=andmask;
432     flagbody(ptr,flag);
433     }
434 }
435
436 #ifdef OPTIONAL
437  removeoptionalfromqueues(int hashcode, struct ___Object___ * currobj, struct parameterwrapper * flagptr){/*find a better way to free the useless instances of the object*/
438    while(flagptr!=NULL) {
439      struct ___Object___ *temp=NULL;
440      struct parameterwrapper *ptr;
441      struct RuntimeNode * node = flagptr->objectset->listhead;
442      while(node!=NULL){
443        temp=(struct ___Object___ *)node->key;
444        if(temp->failedstatus==1 && temp->hashcode==currobj->hashcode){
445          if(temp!=currobj){
446            RuntimeHashget(flagptr->objectset, (int)temp, (int *) &ptr);
447            RuntimeHashremove(flagptr->objectset, (int)temp, (int) ptr);//remove from wrapper
448            //delete the fields that wont be removed by the GC.
449            if(temp->exitfses!=NULL) RUNFREE(temp->exitfses);
450            if(temp->otds!=NULL) RUNFREE(temp->otds);
451            goto nextwrapper;
452          }
453          else{
454            //remove from wrapper
455            RuntimeHashget(flagptr->objectset, (int)temp, (int *) &ptr);
456            RuntimeHashremove(flagptr->objectset, (int)temp, (int) ptr);
457            goto nextwrapper;
458          }
459        }
460        node=node->next;
461      }
462    nextwrapper:
463      ;
464      flagptr=flagptr->next;
465    }
466  } 
467 #endif
468  
469  void flagbody(struct ___Object___ *ptr, int flag) {
470    struct parameterwrapper *flagptr=(struct parameterwrapper *)ptr->flagptr;
471    ptr->flag=flag;
472    
473    /*Remove object from all queues */
474    while(flagptr!=NULL) {
475      struct parameterwrapper *next;
476      struct ___Object___ * tag=ptr->___tags___;
477      RuntimeHashget(flagptr->objectset, (int) ptr, (int *) &next);
478      RuntimeHashremove(flagptr->objectset, (int)ptr, (int) next);
479      flagptr=next;
480    }
481    
482    {
483      struct QueueItem *tmpptr;
484      struct parameterwrapper * parameter=objectqueues[ptr->type];
485      int i;
486      struct parameterwrapper * prevptr=NULL;
487      struct ___Object___ *tagptr=ptr->___tags___;
488      
489      /* Outer loop iterates through all parameter queues an object of
490         this type could be in.  */
491      
492      while(parameter!=NULL) {
493        /* Check tags */
494        if (parameter->numbertags>0) {
495          if (tagptr==NULL)
496            goto nextloop;//that means the object has no tag but that param needs tag
497          else if(tagptr->type==TAGTYPE) {//one tag
498            struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr;
499            for(i=0;i<parameter->numbertags;i++) {
500              //slotid is parameter->tagarray[2*i];
501              int tagid=parameter->tagarray[2*i+1];
502              if (tagid!=tagptr->flag)
503                goto nextloop; /*We don't have this tag */         
504            }
505          } else {//multiple tags
506            struct ArrayObject * ao=(struct ArrayObject *) tagptr;
507            for(i=0;i<parameter->numbertags;i++) {
508              //slotid is parameter->tagarray[2*i];
509              int tagid=parameter->tagarray[2*i+1];
510              int j;
511              for(j=0;j<ao->___cachedCode___;j++) {
512                if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, i)->flag)
513                  goto foundtag;
514              }
515              goto nextloop;
516            foundtag:
517              ;
518            }
519          }
520        }
521        
522        /* Check flags */
523        for(i=0;i<parameter->numberofterms;i++) {
524          int andmask=parameter->intarray[i*2];
525          int checkmask=parameter->intarray[i*2+1];
526          if ((flag&andmask)==checkmask) {
527            enqueuetasks(parameter, prevptr, ptr);
528            prevptr=parameter;
529            break;
530          }
531        }
532      nextloop:
533        parameter=parameter->next;
534      }
535      ptr->flagptr=prevptr;
536    }
537  }
538  
539 #ifdef OPTIONAL
540  
541  void enqueueoptional(struct ___Object___ * currobj){
542    
543    struct classanalysiswrapper * classwrapper=NULL; 
544    struct fsanalysiswrapper * fswrapper=NULL;
545    int counter=0;
546    int numoptionaltaskdescriptors=0;
547    struct optionaltaskdescriptor *** optionaltaskdescriptorarray=NULL;
548    struct fsanalysiswrapper ** goodfswrappersarray=NULL;
549    int numgoodfswrappers=0;
550 #ifdef DEBUG
551    if(currobj->numexitfses==0)
552      printf("Handling failed object\nType : %i\nFlag : 0x%x\n", currobj->type, currobj->flag);
553    else{
554      printf("Handling failed object\nType : %i\n", currobj->type);
555      int fscount=0;
556      for(fscount=0; fscount<currobj->numexitfses; fscount++)
557        printf("Flag : 0x%x\n", currobj->exitfses[fscount]);
558    }
559    struct ___Object___ * tagptr = currobj->___tags___;
560    if(tagptr!=NULL){
561      if(tagptr->type==TAGTYPE) {
562        printf("Tag : %i\n", tagptr->flag);}
563      else {
564        struct ArrayObject * ao=(struct ArrayObject *) tagptr;
565        int numbertags = ao->___length___;
566        for(counter=0; counter<numbertags; counter++){
567          printf("Tag : %i\n", ao[counter].flag);
568        } 
569      }
570    }
571 #endif    
572    /*set the object as failed*/
573    currobj->failedstatus = 1;
574    
575    /*test what optionaltaskdescriptors are available,
576      find the class corresponding*/
577    
578    for(counter = 0; counter<numclasses; counter++){
579      classwrapper = classanalysiswrapperarray[counter];
580      if(classwrapper == NULL){
581        fprintf(stderr, "ERROR : \"struct classanalysiswrapper * classwraper\" is a NULL pointer\n, Analysis has been skipped, check Runtime/task.c, function enqueueoptional\n");
582        goto nothingtodo;
583      }
584      /*check object type*/
585      if( currobj->type == classwrapper->type)
586        goto classchecked;
587    }
588 #ifdef DEBUG
589    printf("No task will use this parameter as optional\n");
590 #endif
591    removeoptionalfromqueues(currobj->hashcode,currobj, objectqueues[currobj->type]);
592    goto nothingtodo;
593  classchecked:
594    ;
595 #ifdef DEBUG
596    printf("Found the class, search through fses\n");
597 #endif        
598    /*search through fses*/
599    goodfswrappersarray = RUNMALLOC(sizeof(struct fsanalysiswrapper *) * classwrapper->numfsanalysiswrappers); /*max number of good fswrappers*/
600    if(goodfswrappersarray == NULL){
601      fprintf(stderr, "ERROR : \"struct fsanalysiswrapper ** goodfswrappersarray\" is a NULL pointer\n, Analysis has been skipped, check Runtime/task.c, function enqueueoptional\n");
602      removeoptionalfromqueues(currobj->hashcode,currobj, objectqueues[currobj->type]);
603      goto nothingtodo;
604    }
605    for(counter = 0; counter<classwrapper->numfsanalysiswrappers; counter++){
606      /*test the FS of the object (include flags and tags)*/
607      fswrapper = classwrapper->fsanalysiswrapperarray[counter];
608      if(fswrapper == NULL){
609        fprintf(stderr, "ERROR : struct fsanalysiswrapper * is a NULL pointer\n, Analysis has been skipped, check Runtime/task.c, function enqueueoptional\n");
610        removeoptionalfromqueues(currobj->hashcode,currobj, objectqueues[currobj->type]);
611        goto nothingtodo;
612      }
613      /*check tags*/
614      struct ___Object___ * tagptr = currobj->___tags___;
615      if(fswrapper->numtags>0){
616        if (tagptr==NULL)
617          goto nextloop;//that means the object has no tag but that param needs tag
618        else if(tagptr->type==TAGTYPE) {//one tag
619          if(fswrapper->numtags!=1) goto nextloop;//we don't have the right number of tags
620          struct ___TagDescriptor___ * tag=(struct ___TagDescriptor___*) tagptr;
621          if (fswrapper->tags[0]!=tagptr->flag)
622            goto nextloop; 
623        }          
624        else {//multiple tags
625          struct ArrayObject * ao=(struct ArrayObject *) tagptr;
626          int tag_counter=0;
627          if(ao->___length___!=fswrapper->numtags) goto nextloop;//we don't have the right number of tags
628          for(tag_counter=0;tag_counter<fswrapper->numtags;tag_counter++) {
629            int tagid=fswrapper->tags[tag_counter];
630            int j;
631            for(j=0;j<ao->___cachedCode___;j++) {
632              if (tagid==ARRAYGET(ao, struct ___TagDescriptor___*, tag_counter)->flag)
633                goto foundtag;
634            }
635            goto nextloop;
636          foundtag:
637            ;                  ;
638          }
639        }
640      }
641      
642      //check flags
643      if(currobj->numexitfses==0){/*first time the method is invoqued*/
644        if( currobj->flag == fswrapper->flags){
645          int otdc;
646          optionaltaskdescriptorarray = RUNMALLOC(sizeof(struct optionaltaskdescriptor **) * fswrapper->numoptionaltaskdescriptors);
647          numoptionaltaskdescriptors = fswrapper->numoptionaltaskdescriptors;
648          for(otdc = 0; otdc<fswrapper->numoptionaltaskdescriptors; otdc++){
649            struct optionaltaskdescriptor ** tmpptr = RUNMALLOC(sizeof(struct optionaltaskdescriptor *));
650            tmpptr[0] = fswrapper->optionaltaskdescriptorarray[otdc];
651            optionaltaskdescriptorarray[otdc] = tmpptr;
652          }
653          numgoodfswrappers=1;
654          goto fschecked;
655        }
656      }
657      else if(currobj->numexitfses==1){/*one fs exit*/
658        if(currobj->exitfses[0] == fswrapper->flags){
659          int otdc;
660          optionaltaskdescriptorarray = RUNMALLOC(sizeof(struct optionaltaskdescriptor **) * fswrapper->numoptionaltaskdescriptors);
661          numoptionaltaskdescriptors = fswrapper->numoptionaltaskdescriptors;
662          for(otdc = 0; otdc<fswrapper->numoptionaltaskdescriptors; otdc++){
663            struct optionaltaskdescriptor ** tmpptr = RUNMALLOC(sizeof(struct optionaltaskdescriptor *));
664            tmpptr[0] = fswrapper->optionaltaskdescriptorarray[otdc];
665            optionaltaskdescriptorarray[otdc] = tmpptr;
666          }
667          numgoodfswrappers=1;
668          goto fschecked;
669        }
670      }
671      else{
672        int fscount=0;
673        for(fscount=0; fscount<currobj->numexitfses; fscount++){
674          
675          if( currobj->exitfses[fscount] == fswrapper->flags ){/*see if the fswraper correspond to one of the fses*/
676            goodfswrappersarray[numgoodfswrappers]=fswrapper;
677            numgoodfswrappers++;
678          }
679        }
680        if(counter==classwrapper->numfsanalysiswrappers-1) goto makeintersection; /*last fswrapper*/
681      }
682    nextloop:
683      ;
684    }
685  nofs:
686    ;
687 #ifdef DEBUG
688    printf("FS not found, Nothing more to do\n");
689 #endif
690    removeoptionalfromqueues(currobj->hashcode,currobj, objectqueues[currobj->type]);
691    goto nothingtodo;
692  makeintersection:
693    ;
694    if(numgoodfswrappers==0 || numgoodfswrappers==1) goto nofs; /*nothing has been found, we expect more than one wrapper for multiple flags*/
695    optionaltaskdescriptorarray = makeintersectionotd(numgoodfswrappers, goodfswrappersarray, &numoptionaltaskdescriptors);
696    if(optionaltaskdescriptorarray==NULL){
697      fprintf(stderr, "ERROR : struct optionaltaskdescriptor ** is a NULL pointer\n, Analysis has been skipped, check Runtime/task.c, function enqueueoptional\n");
698      goto nothingtodo;
699    }
700    
701   fschecked:
702    ;
703 #ifdef DEBUG
704    printf("FS(es) found, intersection created, %i potential tasks :\n", numoptionaltaskdescriptors);
705    
706    
707    /*find the parameterwrapper corresponding to the potential task*/
708    for(counter = 0; counter<numoptionaltaskdescriptors; counter++){
709      struct optionaltaskdescriptor ** tmpptr = optionaltaskdescriptorarray[counter];
710      printf("Task %s\n", tmpptr[0]->task->name);
711    }
712    
713 #endif
714    {            
715      struct parameterwrapper * prevptr = NULL;
716      struct parameterwrapper * flagptr = objectqueues[currobj->type];
717      removeoptionalfromqueues(currobj->hashcode,currobj, flagptr);
718      /*process for each otd*/
719      for(counter = 0; counter<numoptionaltaskdescriptors; counter++){
720        struct parameterwrapper * parameter = objectqueues[currobj->type];
721        struct optionaltaskdescriptor ** tmpptr = optionaltaskdescriptorarray[counter];
722        struct optionaltaskdescriptor * currotd = tmpptr[0];
723        int otd_counter=0;
724        while(parameter->task != currotd->task)
725          parameter=parameter->next;
726 #ifdef DEBUG
727        printf("found parameterwrapper for task : %s\n", parameter->task->name);
728 #endif
729        
730        struct ___Object___ * newobj = RUNMALLOC(sizeof(struct ___Object___));
731        (*newobj)=(*currobj);
732        newobj->numotds=numgoodfswrappers;
733        newobj->otds=RUNMALLOC(sizeof(struct optionaltaskdescriptor *) * numgoodfswrappers);
734        for(otd_counter=0; otd_counter<numgoodfswrappers; otd_counter++){
735          newobj->otds[otd_counter]=tmpptr[otd_counter];
736        }
737        enqueuetasks(parameter, prevptr, newobj);
738        prevptr = parameter;
739        
740      nextotd:
741        ;
742      }
743      
744    }
745  nothingtodo:
746    
747    /*if(currobj->exitfses!=NULL) RUNFREE(currobj->exitfses);
748      if(currobj->otds!=NULL) RUNFREE(currobj->otds);*///there has been a problem just before the program exit, maybe due to the GC ?
749    RUNFREE(optionaltaskdescriptorarray);
750    ;
751  }
752
753  /*we need to check if the object is optional, in this case, test the predicate*/
754  /*here is the code for predicate checking*/
755  /*The code has not been tested. I don't even know if it is working or efficient but it is a lead...
756    if(currotd->numpredicatemembers == 0){
757    printf("this task can be fired\n");
758    goto enqueuetask;
759    }
760    else{
761    int pred_counter;
762    int predicatetrue = 0;
763    for(pred_counter = 0; pred_counter<currotd->numpredicatemembers; pred_counter++){
764    struct predicatemember * currpred = currotd->predicatememberarray[pred_counter];
765    printf("predicate type : %i\n", currpred->type);
766    
767    //test if the predicate member is true
768    struct parameterwrapper * paramwrapper = objectqueues[currpred->type];
769    while(paramwrapper!=NULL){
770    struct RuntimeIterator * it = allocateRuntimeIterator(paramwrapper->objectset->listhead);
771    do{
772    struct ___Object___ * obj = (struct ___Object___ *)Runkey(it);
773    printf("obj type : %i\n", obj->type);
774    if(obj->type == currpred->type){
775    //test the predicate
776    printf("predicate to test\n");
777    //only if good
778    goto enqueuetask;
779    }
780    Runnext(it);
781    }while(RunhasNext(it));
782    paramwrapper=paramwrapper->next;
783    }
784    printf("not the good predicate");
785    //goto endanalysis
786    }
787    //the predicate members have to be all true
788    }*/
789  
790 #endif
791  
792  void enqueuetasks(struct parameterwrapper *parameter, struct parameterwrapper *prevptr, struct ___Object___ *ptr) {
793   void * taskpointerarray[MAXTASKPARAMS];
794   int j;
795   int numparams=parameter->task->numParameters;
796   int numiterators=parameter->task->numTotal-1;
797
798   struct taskdescriptor * task=parameter->task;
799   
800   RuntimeHashadd(parameter->objectset, (int) ptr, (int) prevptr);//this add the object to parameterwrapper
801   
802   /* Add enqueued object to parameter vector */
803   taskpointerarray[parameter->slot]=ptr;
804
805   /* Reset iterators */
806   for(j=0;j<numiterators;j++) {
807     toiReset(&parameter->iterators[j]);
808   }
809
810   /* Find initial state */
811   for(j=0;j<numiterators;j++) {
812   backtrackinit:
813     if(toiHasNext(&parameter->iterators[j], taskpointerarray))
814       toiNext(&parameter->iterators[j], taskpointerarray);
815     else if (j>0) {
816       /* Need to backtrack */
817       toiReset(&parameter->iterators[j]);
818       j--;
819       goto backtrackinit;
820     } else {
821       /* Nothing to enqueue */
822       return;
823     }
824   }
825
826   
827   while(1) {
828     /* Enqueue current state */
829     int launch = 0;
830     struct taskparamdescriptor *tpd=RUNMALLOC(sizeof(struct taskparamdescriptor));
831     tpd->task=task;
832     tpd->numParameters=numiterators+1;
833     tpd->parameterArray=RUNMALLOC(sizeof(void *)*(numiterators+1));
834     for(j=0;j<=numiterators;j++){
835 #ifdef OPTIONAL
836 #ifdef DEBUG
837       struct ___Object___ * obj = (struct ___Object___ *)taskpointerarray[j];
838       if(obj->failedstatus==1)
839         printf("parameter %i used as optional for task %s\n", obj->type, task->name);
840 #endif
841 #endif
842       tpd->parameterArray[j]=taskpointerarray[j];//store the actual parameters
843     }
844     /* Enqueue task */
845     if ((!gencontains(failedtasks, tpd)&&!gencontains(activetasks,tpd))) {
846       genputtable(activetasks, tpd, tpd);
847     } else {
848       RUNFREE(tpd->parameterArray);
849       RUNFREE(tpd);
850     }
851     
852     /* This loop iterates to the next parameter combination */
853     if (numiterators==0)
854       return;
855
856     for(j=numiterators-1; j<numiterators;j++) {
857     backtrackinc:
858       if(toiHasNext(&parameter->iterators[j], taskpointerarray))
859         toiNext(&parameter->iterators[j], taskpointerarray);
860       else if (j>0) {
861         /* Need to backtrack */
862         toiReset(&parameter->iterators[j]);
863         j--;
864         goto backtrackinc;
865       } else {
866         /* Nothing more to enqueue */
867         return;
868       }
869     }
870   }
871 }
872  
873 /* Handler for signals. The signals catch null pointer errors and
874    arithmatic errors. */
875
876 void myhandler(int sig, siginfo_t *info, void *uap) {
877   sigset_t toclear;
878 #ifdef DEBUG
879   printf("sig=%d\n",sig);
880   printf("signal\n");
881 #endif
882   sigemptyset(&toclear);
883   sigaddset(&toclear, sig);
884   sigprocmask(SIG_UNBLOCK, &toclear,NULL); 
885   longjmp(error_handler,1);
886 }
887
888 fd_set readfds;
889 int maxreadfd;
890 struct RuntimeHash *fdtoobject;
891
892 void addreadfd(int fd) {
893   if (fd>=maxreadfd)
894     maxreadfd=fd+1;
895   FD_SET(fd, &readfds);
896 }
897
898 void removereadfd(int fd) {
899   FD_CLR(fd, &readfds);
900   if (maxreadfd==(fd+1)) {
901     maxreadfd--;
902     while(maxreadfd>0&&!FD_ISSET(maxreadfd-1, &readfds))
903       maxreadfd--;
904   }
905 }
906
907 #ifdef PRECISE_GC
908 #define OFFSET 2
909 #else
910 #define OFFSET 0
911 #endif
912
913 void executetasks() {
914   void * taskpointerarray[MAXTASKPARAMS+OFFSET];
915
916   /* Set up signal handlers */
917   struct sigaction sig;
918   sig.sa_sigaction=&myhandler;
919   sig.sa_flags=SA_SIGINFO;
920   sigemptyset(&sig.sa_mask);
921
922   /* Catch bus errors, segmentation faults, and floating point exceptions*/
923   sigaction(SIGBUS,&sig,0);
924   sigaction(SIGSEGV,&sig,0);
925   sigaction(SIGFPE,&sig,0);
926   sigaction(SIGPIPE,&sig,0);
927
928   /* Zero fd set */
929   FD_ZERO(&readfds);
930   maxreadfd=0;
931   fdtoobject=allocateRuntimeHash(100);
932
933   /* Map first block of memory to protected, anonymous page */
934   mmap(0, 0x1000, 0, MAP_SHARED|MAP_FIXED|MAP_ANON, -1, 0);
935
936   newtask:
937   while((hashsize(activetasks)>0)||(maxreadfd>0)) {
938
939     /* Check if any filedescriptors have IO pending */
940     if (maxreadfd>0) {
941       int i;
942       struct timeval timeout={0,0};
943       fd_set tmpreadfds;
944       int numselect;
945       tmpreadfds=readfds;
946       numselect=select(maxreadfd, &tmpreadfds, NULL, NULL, &timeout);
947       if (numselect>0) {
948         /* Process ready fd's */
949         int fd;
950         for(fd=0;fd<maxreadfd;fd++) {
951           if (FD_ISSET(fd, &tmpreadfds)) {
952             /* Set ready flag on object */
953             void * objptr;
954             //      printf("Setting fd %d\n",fd);
955             if (RuntimeHashget(fdtoobject, fd,(int *) &objptr)) {
956               intflagorand(objptr,1,0xFFFFFFFF); /* Set the first flag to 1 */
957             }
958           }
959         }
960       }
961     }
962
963     /* See if there are any active tasks */
964     if (hashsize(activetasks)>0) {
965       int i;
966       currtpd=(struct taskparamdescriptor *) getfirstkey(activetasks);
967       genfreekey(activetasks, currtpd);
968       
969       /* Check if this task has failed, allow a task that contains optional objects to fire */
970       if (gencontains(failedtasks, currtpd)) {
971         // Free up task parameter descriptor
972         RUNFREE(currtpd->parameterArray);
973         RUNFREE(currtpd);
974         goto newtask;
975       }
976       int numparams=currtpd->task->numParameters;
977       int numtotal=currtpd->task->numTotal;
978       
979       /* Make sure that the parameters are still in the queues */
980       for(i=0;i<numparams;i++) {
981         void * parameter=currtpd->parameterArray[i];
982         struct parameterdescriptor * pd=currtpd->task->descriptorarray[i];
983         struct parameterwrapper *pw=(struct parameterwrapper *) pd->queue;
984         int j;
985         /* Check that object is still in queue */
986 #ifdef OPTIONAL
987         struct ___Object___ * obj = (struct ___Object___ *)parameter;
988         if(obj->failedstatus==1){
989           struct ___Object___ *temp=NULL;
990           struct parameterwrapper * ptr;
991           struct RuntimeNode * node = pw->objectset->listhead;
992           while(node!=NULL){
993             temp=(struct ___Object___ *)node->key;
994             if(temp->failedstatus==1 && temp->hashcode==obj->hashcode){
995               if(temp==obj)
996                 goto parameterpresent;
997             }
998             node=node->next;
999           }
1000           RUNFREE(currtpd->parameterArray);
1001           RUNFREE(currtpd);
1002           goto newtask;
1003         }
1004         else
1005 #endif
1006         {
1007           if (!RuntimeHashcontainskey(pw->objectset, (int) parameter)) {
1008             RUNFREE(currtpd->parameterArray);
1009             RUNFREE(currtpd);
1010             goto newtask;
1011           }
1012         }
1013       parameterpresent:
1014         ;
1015         /* Check that object still has necessary tags */
1016         for(j=0;j<pd->numbertags;j++) {
1017           int slotid=pd->tagarray[2*j]+numparams;
1018           struct ___TagDescriptor___ *tagd=currtpd->parameterArray[slotid];
1019           if (!containstag(parameter, tagd)) {
1020             RUNFREE(currtpd->parameterArray);
1021             RUNFREE(currtpd);
1022             goto newtask;
1023           }
1024         }
1025         
1026         taskpointerarray[i+OFFSET]=parameter;
1027       }
1028       /* Copy the tags */
1029       for(;i<numtotal;i++) {
1030         taskpointerarray[i+OFFSET]=currtpd->parameterArray[i];
1031       }
1032
1033       {
1034         /* Checkpoint the state */
1035         forward=allocateRuntimeHash(100);
1036         reverse=allocateRuntimeHash(100);
1037         void ** checkpoint=makecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, forward, reverse);
1038         int x;
1039         if (x=setjmp(error_handler)) {
1040           int counter;
1041           /* Recover */
1042 #ifdef DEBUG
1043           printf("Fatal Error=%d, Recovering!\n",x);
1044 #endif
1045           genputtable(failedtasks,currtpd,currtpd);
1046           restorecheckpoint(currtpd->task->numParameters, currtpd->parameterArray, checkpoint, forward, reverse);
1047
1048 #ifdef OPTIONAL
1049 #ifdef DEBUG      
1050           printf("%i object(s) restored\n", currtpd->task->numParameters);
1051 #endif 
1052           
1053           for(counter=0; counter<currtpd->task->numParameters; counter++){
1054             //remove the object from the previous parameterwrapper (maybe not necessary)
1055             //do a new instance of the object. It allows the restored object to be used by other tasks as a non optional arg.
1056             struct ___Object___ * currobj = RUNMALLOC(sizeof(struct ___Object___));
1057             (*currobj)=(*(struct ___Object___ *)currtpd->parameterArray[counter]);
1058             currobj->numexitfses = 0;
1059             currobj->exitfses = NULL;
1060             currobj->otds=NULL;
1061             currobj->hashcode=(int)currobj;
1062             enqueueoptional( currobj );
1063           }
1064 #endif
1065           freeRuntimeHash(forward);
1066           freeRuntimeHash(reverse);
1067           freemalloc();
1068           forward=NULL;
1069           reverse=NULL;
1070         } else {
1071           if (injectfailures) {
1072             if ((((double)random())/RAND_MAX)<failurechance) {
1073               printf("\nINJECTING TASK FAILURE to %s\n", currtpd->task->name);
1074               longjmp(error_handler,10);
1075             }
1076           }
1077           /* Actually call task */
1078 #ifdef PRECISE_GC
1079           ((int *)taskpointerarray)[0]=currtpd->task->numParameters;
1080           taskpointerarray[1]=NULL;
1081 #endif
1082           if(debugtask){
1083             printf("ENTER %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
1084             ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray);
1085             printf("EXIT %s count=%d\n",currtpd->task->name, (instaccum-instructioncount));
1086           } else
1087             ((void (*) (void **)) currtpd->task->taskptr)(taskpointerarray);
1088             
1089           freeRuntimeHash(forward);
1090           freeRuntimeHash(reverse);
1091           freemalloc();
1092           // Free up task parameter descriptor
1093           RUNFREE(currtpd->parameterArray);
1094           RUNFREE(currtpd);
1095           forward=NULL;
1096           reverse=NULL;
1097         }
1098       }
1099     }
1100   }
1101 }
1102  
1103 /* This function processes an objects tags */
1104 void processtags(struct parameterdescriptor *pd, int index, struct parameterwrapper *parameter, int * iteratorcount, int *statusarray, int numparams) {
1105   int i;
1106   
1107   for(i=0;i<pd->numbertags;i++) {
1108     int slotid=pd->tagarray[2*i];
1109     int tagid=pd->tagarray[2*i+1];
1110     
1111     if (statusarray[slotid+numparams]==0) {
1112       parameter->iterators[*iteratorcount].istag=1;
1113       parameter->iterators[*iteratorcount].tagid=tagid;
1114       parameter->iterators[*iteratorcount].slot=slotid+numparams;
1115       parameter->iterators[*iteratorcount].tagobjectslot=index;
1116       statusarray[slotid+numparams]=1;
1117       (*iteratorcount)++;
1118     }
1119   }
1120 }
1121
1122
1123 void processobject(struct parameterwrapper *parameter, int index, struct parameterdescriptor *pd, int *iteratorcount, int * statusarray, int numparams) {
1124   int i;
1125   int tagcount=0;
1126   struct RuntimeHash * objectset=((struct parameterwrapper *)pd->queue)->objectset;
1127
1128   parameter->iterators[*iteratorcount].istag=0;
1129   parameter->iterators[*iteratorcount].slot=index;
1130   parameter->iterators[*iteratorcount].objectset=objectset;
1131   statusarray[index]=1;
1132
1133   for(i=0;i<pd->numbertags;i++) {
1134     int slotid=pd->tagarray[2*i];
1135     int tagid=pd->tagarray[2*i+1];
1136     if (statusarray[slotid+numparams]!=0) {
1137       /* This tag has already been enqueued, use it to narrow search */
1138       parameter->iterators[*iteratorcount].tagbindings[tagcount]=slotid+numparams;
1139       tagcount++;
1140     }
1141   }
1142   parameter->iterators[*iteratorcount].numtags=tagcount;
1143
1144   (*iteratorcount)++;
1145 }
1146
1147 /* This function builds the iterators for a task & parameter */
1148
1149 void builditerators(struct taskdescriptor * task, int index, struct parameterwrapper * parameter) {
1150   int statusarray[MAXTASKPARAMS];
1151   int i;
1152   int numparams=task->numParameters;
1153   int iteratorcount=0;
1154   for(i=0;i<MAXTASKPARAMS;i++) statusarray[i]=0;
1155
1156   statusarray[index]=1; /* Initial parameter */
1157   /* Process tags for initial iterator */
1158   
1159   processtags(task->descriptorarray[index], index, parameter, & iteratorcount, statusarray, numparams);
1160   
1161   while(1) {
1162   loopstart:
1163     /* Check for objects with existing tags */
1164     for(i=0;i<numparams;i++) {
1165       if (statusarray[i]==0) {
1166         struct parameterdescriptor *pd=task->descriptorarray[i];
1167         int j;
1168         for(j=0;j<pd->numbertags;j++) {
1169           int slotid=pd->tagarray[2*j];
1170           if(statusarray[slotid+numparams]!=0) {
1171             processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
1172             processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
1173             goto loopstart;
1174           }
1175         }
1176       }
1177     }
1178
1179     /* Next do objects w/ unbound tags*/
1180
1181     for(i=0;i<numparams;i++) {
1182       if (statusarray[i]==0) {
1183         struct parameterdescriptor *pd=task->descriptorarray[i];
1184         if (pd->numbertags>0) {
1185           processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
1186           processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
1187           goto loopstart;
1188         }
1189       }
1190     }
1191
1192     /* Nothing with a tag enqueued */
1193
1194     for(i=0;i<numparams;i++) {
1195       if (statusarray[i]==0) {
1196         struct parameterdescriptor *pd=task->descriptorarray[i];
1197         processobject(parameter, i, pd, &iteratorcount, statusarray, numparams);
1198         processtags(pd, i, parameter, &iteratorcount, statusarray, numparams);
1199         goto loopstart;
1200       }
1201     }
1202
1203     /* Nothing left */
1204     return;
1205   }
1206 }
1207
1208
1209  
1210
1211 /* This function processes the task information to create queues for
1212    each parameter type. */
1213
1214 void processtasks() {
1215   int i;
1216   for(i=0;i<numtasks;i++) {
1217     struct taskdescriptor * task=taskarray[i];
1218     int j;
1219
1220     for(j=0;j<task->numParameters;j++) {
1221       struct parameterdescriptor *param=task->descriptorarray[j];
1222       struct parameterwrapper * parameter=RUNMALLOC(sizeof(struct parameterwrapper));
1223       struct parameterwrapper ** ptr=&objectqueues[param->type];
1224
1225       param->queue=parameter;
1226       parameter->objectset=allocateRuntimeHash(10);
1227       parameter->numberofterms=param->numberterms;
1228       parameter->intarray=param->intarray;
1229       parameter->numbertags=param->numbertags;
1230       parameter->tagarray=param->tagarray;
1231       parameter->task=task;
1232       /* Link new queue in */
1233       while((*ptr)!=NULL)
1234         ptr=&((*ptr)->next);
1235       (*ptr)=parameter;
1236     }
1237
1238     /* Build iterators for parameters */
1239     for(j=0;j<task->numParameters;j++) {
1240       struct parameterdescriptor *param=task->descriptorarray[j];
1241       struct parameterwrapper *parameter=param->queue;      
1242       parameter->slot=j;
1243       builditerators(task, j, parameter);
1244     }
1245   }
1246 }
1247
1248 void toiReset(struct tagobjectiterator * it) {
1249   if (it->istag) {
1250     it->tagobjindex=0;
1251   } else if (it->numtags>0) {
1252     it->tagobjindex=0;
1253   } else {
1254     RuntimeHashiterator(it->objectset, &it->it);
1255   }
1256 }
1257
1258 int toiHasNext(struct tagobjectiterator *it, void ** objectarray) {
1259   if (it->istag) {
1260     /* Iterate tag */
1261     /* Get object with tags */
1262     struct ___Object___ *obj=objectarray[it->tagobjectslot];
1263     struct ___Object___ *tagptr=obj->___tags___;
1264     if (tagptr->type==TAGTYPE) {
1265       if ((it->tagobjindex==0)&& /* First object */
1266           (it->tagid==((struct ___TagDescriptor___ *)tagptr)->flag)) /* Right tag type */
1267         return 1;
1268       else
1269         return 0;
1270     } else {
1271       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
1272       int tagindex=it->tagobjindex;
1273       for(;tagindex<ao->___cachedCode___;tagindex++) {
1274         struct ___TagDescriptor___ *td=ARRAYGET(ao, struct ___TagDescriptor___ *, tagindex);
1275         if (td->flag==it->tagid) {
1276           it->tagobjindex=tagindex; /* Found right type of tag */
1277           return 1;
1278         }
1279       }
1280       return 0;
1281     }
1282   } else if (it->numtags>0) {
1283     /* Use tags to locate appropriate objects */
1284     struct ___TagDescriptor___ *tag=objectarray[it->tagbindings[0]];
1285     struct ___Object___ *objptr=tag->flagptr;
1286     int i;
1287     if (objptr->type!=OBJECTARRAYTYPE) {
1288       if (it->tagobjindex>0)
1289         return 0;
1290       if (!RuntimeHashcontainskey(it->objectset, (int) objptr))
1291         return 0;
1292       for(i=1;i<it->numtags;i++) {
1293         struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
1294         if (!containstag(objptr,tag2))
1295           return 0;
1296       }
1297       return 1;
1298     } else {
1299       struct ArrayObject *ao=(struct ArrayObject *) objptr;
1300       int tagindex;
1301       int i;
1302       for(tagindex=it->tagobjindex;tagindex<ao->___cachedCode___;tagindex++) {
1303         struct ___Object___ *objptr=ARRAYGET(ao, struct ___Object___*, tagindex);
1304         if (!RuntimeHashcontainskey(it->objectset, (int) objptr))
1305           continue;
1306         for(i=1;i<it->numtags;i++) {
1307           struct ___TagDescriptor___ *tag2=objectarray[it->tagbindings[i]];
1308           if (!containstag(objptr,tag2))
1309             goto nexttag;
1310         }
1311         return 1;
1312       nexttag:
1313         ;
1314       }
1315       it->tagobjindex=tagindex;
1316       return 0;
1317     }
1318   } else {
1319     return RunhasNext(&it->it);
1320   }
1321 }
1322
1323 int containstag(struct ___Object___ *ptr, struct ___TagDescriptor___ *tag) {
1324   int j;
1325   struct ___Object___ * objptr=tag->flagptr;
1326   if (objptr->type==OBJECTARRAYTYPE) {
1327     struct ArrayObject *ao=(struct ArrayObject *)objptr;
1328     for(j=0;j<ao->___cachedCode___;j++) {
1329       if (ptr==ARRAYGET(ao, struct ___Object___*, j))
1330         return 1;
1331     }
1332     return 0;
1333   } else
1334     return objptr==ptr;
1335 }
1336
1337 void toiNext(struct tagobjectiterator *it , void ** objectarray) {
1338   /* hasNext has all of the intelligence */
1339   if(it->istag) {
1340     /* Iterate tag */
1341     /* Get object with tags */
1342     struct ___Object___ *obj=objectarray[it->tagobjectslot];
1343     struct ___Object___ *tagptr=obj->___tags___;
1344     if (tagptr->type==TAGTYPE) {
1345       it->tagobjindex++;
1346       objectarray[it->slot]=tagptr;
1347     } else {
1348       struct ArrayObject *ao=(struct ArrayObject *) tagptr;
1349       objectarray[it->slot]=ARRAYGET(ao, struct ___TagDescriptor___ *, it->tagobjindex++);
1350     }
1351   } else if (it->numtags>0) {
1352     /* Use tags to locate appropriate objects */
1353     struct ___TagDescriptor___ *tag=objectarray[it->tagbindings[0]];
1354     struct ___Object___ *objptr=tag->flagptr;
1355     if (objptr->type!=OBJECTARRAYTYPE) {
1356       it->tagobjindex++;
1357       objectarray[it->slot]=objptr;
1358     } else {
1359       struct ArrayObject *ao=(struct ArrayObject *) objptr;
1360       objectarray[it->slot]=ARRAYGET(ao, struct ___Object___ *, it->tagobjindex++);
1361     }
1362   } else {
1363     /* Iterate object */
1364     objectarray[it->slot]=(void *)Runkey(&it->it);
1365     Runnext(&it->it);
1366   }
1367 }
1368
1369
1370 #endif