8b188085c2cf1b3c3d73ec8b5e4ab5d105827840
[cacao.git] / src / mm / boehm-gc / tests / test.c
1 /* 
2  * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
3  * Copyright (c) 1991-1994 by Xerox Corporation.  All rights reserved.
4  * Copyright (c) 1996 by Silicon Graphics.  All rights reserved.
5  *
6  * THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
7  * OR IMPLIED.  ANY USE IS AT YOUR OWN RISK.
8  *
9  * Permission is hereby granted to use or copy this program
10  * for any purpose,  provided the above notices are retained on all copies.
11  * Permission to modify the code and to distribute modified code is granted,
12  * provided the above notices are retained, and a notice that the code was
13  * modified is included with the above copyright notice.
14  */
15 /* An incomplete test for the garbage collector.                */
16 /* Some more obscure entry points are not tested at all.        */
17 /* This must be compiled with the same flags used to build the  */
18 /* GC.  It uses GC internals to allow more precise results      */
19 /* checking for some of the tests.                              */
20
21 # undef GC_BUILD
22
23 #include "config.h"
24
25 #if defined(DBG_HDRS_ALL) || defined(MAKE_BACK_GRAPH)
26 #  define GC_DEBUG
27 #endif
28
29 # if defined(mips) && defined(SYSTYPE_BSD43)
30     /* MIPS RISCOS 4 */
31 # else
32 #   include <stdlib.h>
33 # endif
34 # include <stdio.h>
35 # ifdef _WIN32_WCE
36 #   include <winbase.h>
37 #   define assert ASSERT
38 # else
39 #   include <assert.h>        /* Not normally used, but handy for debugging. */
40 # endif
41 # include "gc.h"
42 # include "gc_typed.h"
43 # include "private/gc_priv.h"   /* For output, locking, MIN_WORDS,      */
44                                 /* and some statistics, and gcconfig.h. */
45
46 # if defined(MSWIN32) || defined(MSWINCE)
47 #   include <windows.h>
48 #   ifdef GC_DLL
49 #     define GC_print_stats 0   /* Not exported from DLL */
50                                 /* Redefine to 1 to generate output. */
51 #   endif
52 # endif
53
54 # ifdef PCR
55 #   include "th/PCR_ThCrSec.h"
56 #   include "th/PCR_Th.h"
57 #   define GC_printf printf
58 # endif
59
60 # if defined(GC_PTHREADS)
61 #   include <pthread.h>
62 # endif
63
64 # if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
65     static CRITICAL_SECTION incr_cs;
66 # endif
67
68 #ifdef __STDC__
69 # include <stdarg.h>
70 #endif
71
72 /* Call GC_INIT only on platforms on which we think we really need it,  */
73 /* so that we can test automatic initialization on the rest.            */
74 #if defined(CYGWIN32) || defined (AIX) || defined(DARWIN)
75 #  define GC_COND_INIT() GC_INIT()
76 #else
77 #  define GC_COND_INIT()
78 #endif
79
80 /* Allocation Statistics */
81 int stubborn_count = 0;
82 int uncollectable_count = 0;
83 int collectable_count = 0;
84 int atomic_count = 0;
85 int realloc_count = 0;
86
87 #if defined(GC_AMIGA_FASTALLOC) && defined(AMIGA)
88
89   extern void GC_amiga_free_all_mem(void);
90   void Amiga_Fail(void){GC_amiga_free_all_mem();abort();}
91 # define FAIL (void)Amiga_Fail()
92   void *GC_amiga_gctest_malloc_explicitly_typed(size_t lb, GC_descr d){
93     void *ret=GC_malloc_explicitly_typed(lb,d);
94     if(ret==NULL){
95                 if(!GC_dont_gc){
96               GC_gcollect();
97               ret=GC_malloc_explicitly_typed(lb,d);
98                 }
99       if(ret==NULL){
100         GC_printf("Out of memory, (typed allocations are not directly "
101                   "supported with the GC_AMIGA_FASTALLOC option.)\n");
102         FAIL;
103       }
104     }
105     return ret;
106   }
107   void *GC_amiga_gctest_calloc_explicitly_typed(size_t a,size_t lb, GC_descr d){
108     void *ret=GC_calloc_explicitly_typed(a,lb,d);
109     if(ret==NULL){
110                 if(!GC_dont_gc){
111               GC_gcollect();
112               ret=GC_calloc_explicitly_typed(a,lb,d);
113                 }
114       if(ret==NULL){
115         GC_printf("Out of memory, (typed allocations are not directly "
116                   "supported with the GC_AMIGA_FASTALLOC option.)\n");
117         FAIL;
118       }
119     }
120     return ret;
121   }
122 # define GC_malloc_explicitly_typed(a,b) GC_amiga_gctest_malloc_explicitly_typed(a,b) 
123 # define GC_calloc_explicitly_typed(a,b,c) GC_amiga_gctest_calloc_explicitly_typed(a,b,c) 
124
125 #else /* !AMIGA_FASTALLOC */
126
127 # ifdef PCR
128 #   define FAIL (void)abort()
129 # else
130 #   ifdef MSWINCE
131 #     define FAIL DebugBreak()
132 #   else
133 #     define FAIL GC_abort("Test failed");
134 #   endif
135 # endif
136
137 #endif /* !AMIGA_FASTALLOC */
138
139 /* AT_END may be defined to exercise the interior pointer test  */
140 /* if the collector is configured with ALL_INTERIOR_POINTERS.   */
141 /* As it stands, this test should succeed with either           */
142 /* configuration.  In the FIND_LEAK configuration, it should    */
143 /* find lots of leaks, since we free almost nothing.            */
144
145 struct SEXPR {
146     struct SEXPR * sexpr_car;
147     struct SEXPR * sexpr_cdr;
148 };
149
150
151 typedef struct SEXPR * sexpr;
152
153 # define INT_TO_SEXPR(x) ((sexpr)(GC_word)(x))
154 # define SEXPR_TO_INT(x) ((int)(GC_word)(x))
155
156 # undef nil
157 # define nil (INT_TO_SEXPR(0))
158 # define car(x) ((x) -> sexpr_car)
159 # define cdr(x) ((x) -> sexpr_cdr)
160 # define is_nil(x) ((x) == nil)
161
162
163 int extra_count = 0;        /* Amount of space wasted in cons node */
164
165 /* Silly implementation of Lisp cons. Intentionally wastes lots of space */
166 /* to test collector.                                                    */
167 # ifdef VERY_SMALL_CONFIG
168 #   define cons small_cons
169 # else
170 sexpr cons (sexpr x, sexpr y)
171 {
172     sexpr r;
173     int *p;
174     int my_extra = extra_count;
175     
176     stubborn_count++;
177     r = (sexpr) GC_MALLOC_STUBBORN(sizeof(struct SEXPR) + my_extra);
178     if (r == 0) {
179         (void)GC_printf("Out of memory\n");
180         exit(1);
181     }
182     for (p = (int *)r;
183          ((char *)p) < ((char *)r) + my_extra + sizeof(struct SEXPR); p++) {
184         if (*p) {
185             (void)GC_printf("Found nonzero at %p - allocator is broken\n", p);
186             FAIL;
187         }
188         *p = (int)((13 << 12) + ((p - (int *)r) & 0xfff));
189     }
190 #   ifdef AT_END
191         r = (sexpr)((char *)r + (my_extra & ~7));
192 #   endif
193     r -> sexpr_car = x;
194     r -> sexpr_cdr = y;
195     my_extra++;
196     if ( my_extra >= 5000 ) {
197         extra_count = 0;
198     } else {
199         extra_count = my_extra;
200     }
201     GC_END_STUBBORN_CHANGE((char *)r);
202     return(r);
203 }
204 # endif
205
206 #ifdef GC_GCJ_SUPPORT
207
208 #include "gc_mark.h"
209 #include "gc_gcj.h"
210
211 /* The following struct emulates the vtable in gcj.     */
212 /* This assumes the default value of MARK_DESCR_OFFSET. */
213 struct fake_vtable {
214   void * dummy;         /* class pointer in real gcj.   */
215   size_t descr;
216 };
217
218 struct fake_vtable gcj_class_struct1 = { 0, sizeof(struct SEXPR)
219                                             + sizeof(struct fake_vtable *) };
220                         /* length based descriptor.     */
221 struct fake_vtable gcj_class_struct2 =
222                                 { 0, (3l << (CPP_WORDSZ - 3)) | GC_DS_BITMAP};
223                         /* Bitmap based descriptor.     */
224
225 struct GC_ms_entry * fake_gcj_mark_proc(word * addr,
226                                         struct GC_ms_entry *mark_stack_ptr,
227                                         struct GC_ms_entry *mark_stack_limit,
228                                         word env   )
229 {
230     sexpr x;
231     if (1 == env) {
232         /* Object allocated with debug allocator.       */
233         addr = (word *)GC_USR_PTR_FROM_BASE(addr);
234     }
235     x = (sexpr)(addr + 1); /* Skip the vtable pointer. */
236     mark_stack_ptr = GC_MARK_AND_PUSH(
237                               (void *)(x -> sexpr_cdr), mark_stack_ptr,
238                               mark_stack_limit, (void * *)&(x -> sexpr_cdr));
239     mark_stack_ptr = GC_MARK_AND_PUSH(
240                               (void *)(x -> sexpr_car), mark_stack_ptr,
241                               mark_stack_limit, (void * *)&(x -> sexpr_car));
242     return(mark_stack_ptr);
243 }
244
245 #endif /* GC_GCJ_SUPPORT */
246
247
248 sexpr small_cons (sexpr x, sexpr y)
249 {
250     sexpr r;
251     
252     collectable_count++;
253     r = (sexpr) GC_MALLOC(sizeof(struct SEXPR));
254     if (r == 0) {
255         (void)GC_printf("Out of memory\n");
256         exit(1);
257     }
258     r -> sexpr_car = x;
259     r -> sexpr_cdr = y;
260     return(r);
261 }
262
263 sexpr small_cons_uncollectable (sexpr x, sexpr y)
264 {
265     sexpr r;
266     
267     uncollectable_count++;
268     r = (sexpr) GC_MALLOC_UNCOLLECTABLE(sizeof(struct SEXPR));
269     if (r == 0) {
270         (void)GC_printf("Out of memory\n");
271         exit(1);
272     }
273     r -> sexpr_car = x;
274     r -> sexpr_cdr = (sexpr)(~(GC_word)y);
275     return(r);
276 }
277
278 #ifdef GC_GCJ_SUPPORT
279
280
281 sexpr gcj_cons(sexpr x, sexpr y)
282 {
283     GC_word * r;
284     sexpr result;
285     static int count = 0;
286     
287     r = (GC_word *) GC_GCJ_MALLOC(sizeof(struct SEXPR)
288                                   + sizeof(struct fake_vtable*),
289                                    &gcj_class_struct2);
290     if (r == 0) {
291         (void)GC_printf("Out of memory\n");
292         exit(1);
293     }
294     result = (sexpr)(r + 1);
295     result -> sexpr_car = x;
296     result -> sexpr_cdr = y;
297     return(result);
298 }
299 #endif
300
301 /* Return reverse(x) concatenated with y */
302 sexpr reverse1(sexpr x, sexpr y)
303 {
304     if (is_nil(x)) {
305         return(y);
306     } else {
307         return( reverse1(cdr(x), cons(car(x), y)) );
308     }
309 }
310
311 sexpr reverse(sexpr x)
312 {
313 #   ifdef TEST_WITH_SYSTEM_MALLOC
314       malloc(100000);
315 #   endif
316     return( reverse1(x, nil) );
317 }
318
319 sexpr ints(int low, int up)
320 {
321     if (low > up) {
322         return(nil);
323     } else {
324         return(small_cons(small_cons(INT_TO_SEXPR(low), nil), ints(low+1, up)));
325     }
326 }
327
328 #ifdef GC_GCJ_SUPPORT
329 /* Return reverse(x) concatenated with y */
330 sexpr gcj_reverse1(sexpr x, sexpr y)
331 {
332     if (is_nil(x)) {
333         return(y);
334     } else {
335         return( gcj_reverse1(cdr(x), gcj_cons(car(x), y)) );
336     }
337 }
338
339 sexpr gcj_reverse(sexpr x)
340 {
341     return( gcj_reverse1(x, nil) );
342 }
343
344 sexpr gcj_ints(int low, int up)
345 {
346     if (low > up) {
347         return(nil);
348     } else {
349         return(gcj_cons(gcj_cons(INT_TO_SEXPR(low), nil), gcj_ints(low+1, up)));
350     }
351 }
352 #endif /* GC_GCJ_SUPPORT */
353
354 /* To check uncollectable allocation we build lists with disguised cdr  */
355 /* pointers, and make sure they don't go away.                          */
356 sexpr uncollectable_ints(int low, int up)
357 {
358     if (low > up) {
359         return(nil);
360     } else {
361         return(small_cons_uncollectable(small_cons(INT_TO_SEXPR(low), nil),
362                uncollectable_ints(low+1, up)));
363     }
364 }
365
366 void check_ints(sexpr list, int low, int up)
367 {
368     if (SEXPR_TO_INT(car(car(list))) != low) {
369         (void)GC_printf(
370            "List reversal produced incorrect list - collector is broken\n");
371         FAIL;
372     }
373     if (low == up) {
374         if (cdr(list) != nil) {
375            (void)GC_printf("List too long - collector is broken\n");
376            FAIL;
377         }
378     } else {
379         check_ints(cdr(list), low+1, up);
380     }
381 }
382
383 # define UNCOLLECTABLE_CDR(x) (sexpr)(~(GC_word)(cdr(x)))
384
385 void check_uncollectable_ints(sexpr list, int low, int up)
386 {
387     if (SEXPR_TO_INT(car(car(list))) != low) {
388         (void)GC_printf(
389            "Uncollectable list corrupted - collector is broken\n");
390         FAIL;
391     }
392     if (low == up) {
393         if (UNCOLLECTABLE_CDR(list) != nil) {
394            (void)GC_printf("Uncollectable list too long - collector is broken\n");
395            FAIL;
396         }
397     } else {
398         check_uncollectable_ints(UNCOLLECTABLE_CDR(list), low+1, up);
399     }
400 }
401
402 /* Not used, but useful for debugging: */
403 void print_int_list(sexpr x)
404 {
405     if (is_nil(x)) {
406         (void)GC_printf("NIL\n");
407     } else {
408         (void)GC_printf("(%d)", SEXPR_TO_INT(car(car(x))));
409         if (!is_nil(cdr(x))) {
410             (void)GC_printf(", ");
411             (void)print_int_list(cdr(x));
412         } else {
413             (void)GC_printf("\n");
414         }
415     }
416 }
417
418 /* ditto: */
419 void check_marks_int_list(sexpr x)
420 {
421     if (!GC_is_marked((ptr_t)x))
422         GC_printf("[unm:%p]", x);
423     else
424         GC_printf("[mkd:%p]", x);
425     if (is_nil(x)) {
426         (void)GC_printf("NIL\n");
427     } else {
428         if (!GC_is_marked((ptr_t)car(x))) GC_printf("[unm car:%p]", car(x));
429         (void)GC_printf("(%d)", SEXPR_TO_INT(car(car(x))));
430         if (!is_nil(cdr(x))) {
431             (void)GC_printf(", ");
432             (void)check_marks_int_list(cdr(x));
433         } else {
434             (void)GC_printf("\n");
435         }
436     }
437 }
438
439 /*
440  * A tiny list reversal test to check thread creation.
441  */
442 #ifdef THREADS
443
444 # if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
445     DWORD  __stdcall tiny_reverse_test(void * arg)
446 # else
447     void * tiny_reverse_test(void * arg)
448 # endif
449 {
450     int i;
451     for (i = 0; i < 5; ++i) {
452       check_ints(reverse(reverse(ints(1,10))), 1, 10);
453     }
454     return 0;
455 }
456
457 # if defined(GC_PTHREADS)
458     void fork_a_thread()
459     {
460       pthread_t t;
461       int code;
462       if ((code = pthread_create(&t, 0, tiny_reverse_test, 0)) != 0) {
463         (void)GC_printf("Small thread creation failed %d\n", code);
464         FAIL;
465       }
466       if ((code = pthread_join(t, 0)) != 0) {
467         (void)GC_printf("Small thread join failed %d\n", code);
468         FAIL;
469       }
470     }
471
472 # elif defined(GC_WIN32_THREADS)
473     void fork_a_thread()
474     {
475         DWORD thread_id;
476         HANDLE h;
477         h = GC_CreateThread(NULL, 0, tiny_reverse_test, 0, 0, &thread_id);
478         if (h == (HANDLE)NULL) {
479             (void)GC_printf("Small thread creation failed %d\n",
480                             GetLastError());
481             FAIL;
482         }
483         if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
484             (void)GC_printf("Small thread wait failed %d\n",
485                             GetLastError());
486             FAIL;
487         }
488     }
489
490 # else
491
492 #   define fork_a_thread()
493
494 # endif
495
496 #else
497
498 # define fork_a_thread()
499
500 #endif 
501
502 /* Try to force a to be strangely aligned */
503 struct {
504   char dummy;
505   sexpr aa;
506 } A;
507 #define a A.aa
508
509 /*
510  * Repeatedly reverse lists built out of very different sized cons cells.
511  * Check that we didn't lose anything.
512  */
513 void reverse_test()
514 {
515     int i;
516     sexpr b;
517     sexpr c;
518     sexpr d;
519     sexpr e;
520     sexpr *f, *g, *h;
521 #   if defined(MSWIN32) || defined(MACOS)
522       /* Win32S only allows 128K stacks */
523 #     define BIG 1000
524 #   else
525 #     if defined PCR
526         /* PCR default stack is 100K.  Stack frames are up to 120 bytes. */
527 #       define BIG 700
528 #     else
529 #       if defined MSWINCE
530           /* WinCE only allows 64K stacks */
531 #         define BIG 500
532 #       else
533 #         if defined(OSF1)
534             /* OSF has limited stack space by default, and large frames. */
535 #           define BIG 200
536 #         else
537 #           define BIG 4500
538 #         endif
539 #       endif
540 #     endif
541 #   endif
542
543     A.dummy = 17;
544     a = ints(1, 49);
545     b = ints(1, 50);
546     c = ints(1, BIG);
547     d = uncollectable_ints(1, 100);
548     e = uncollectable_ints(1, 1);
549     /* Check that realloc updates object descriptors correctly */
550     collectable_count++;
551     f = (sexpr *)GC_MALLOC(4 * sizeof(sexpr));
552     realloc_count++;
553     f = (sexpr *)GC_REALLOC((void *)f, 6 * sizeof(sexpr));
554     f[5] = ints(1,17);
555     collectable_count++;
556     g = (sexpr *)GC_MALLOC(513 * sizeof(sexpr));
557     realloc_count++;
558     g = (sexpr *)GC_REALLOC((void *)g, 800 * sizeof(sexpr));
559     g[799] = ints(1,18);
560     collectable_count++;
561     h = (sexpr *)GC_MALLOC(1025 * sizeof(sexpr));
562     realloc_count++;
563     h = (sexpr *)GC_REALLOC((void *)h, 2000 * sizeof(sexpr));
564 #   ifdef GC_GCJ_SUPPORT
565       h[1999] = gcj_ints(1,200);
566       for (i = 0; i < 51; ++i) 
567         h[1999] = gcj_reverse(h[1999]);
568       /* Leave it as the reveresed list for now. */
569 #   else
570       h[1999] = ints(1,200);
571 #   endif
572     /* Try to force some collections and reuse of small list elements */
573       for (i = 0; i < 10; i++) {
574         (void)ints(1, BIG);
575       }
576     /* Superficially test interior pointer recognition on stack */
577       c = (sexpr)((char *)c + sizeof(char *));
578       d = (sexpr)((char *)d + sizeof(char *));
579
580 #   ifdef __STDC__
581         GC_FREE((void *)e);
582 #   else
583         GC_FREE((char *)e);
584 #   endif
585     check_ints(b,1,50);
586     check_ints(a,1,49);
587     for (i = 0; i < 50; i++) {
588         check_ints(b,1,50);
589         b = reverse(reverse(b));
590     }
591     check_ints(b,1,50);
592     check_ints(a,1,49);
593     for (i = 0; i < 60; i++) {
594         if (i % 10 == 0) fork_a_thread();
595         /* This maintains the invariant that a always points to a list of */
596         /* 49 integers.  Thus this is thread safe without locks,          */
597         /* assuming atomic pointer assignments.                           */
598         a = reverse(reverse(a));
599 #       if !defined(AT_END) && !defined(THREADS)
600           /* This is not thread safe, since realloc explicitly deallocates */
601           if (i & 1) {
602             a = (sexpr)GC_REALLOC((void *)a, 500);
603           } else {
604             a = (sexpr)GC_REALLOC((void *)a, 8200);
605           }
606 #       endif
607     }
608     check_ints(a,1,49);
609     check_ints(b,1,50);
610     c = (sexpr)((char *)c - sizeof(char *));
611     d = (sexpr)((char *)d - sizeof(char *));
612     check_ints(c,1,BIG);
613     check_uncollectable_ints(d, 1, 100);
614     check_ints(f[5], 1,17);
615     check_ints(g[799], 1,18);
616 #   ifdef GC_GCJ_SUPPORT
617       h[1999] = gcj_reverse(h[1999]);
618 #   endif
619     check_ints(h[1999], 1,200);
620 #   ifndef THREADS
621         a = 0;
622 #   endif  
623     b = c = 0;
624 }
625
626 #undef a
627
628 /*
629  * The rest of this builds balanced binary trees, checks that they don't
630  * disappear, and tests finalization.
631  */
632 typedef struct treenode {
633     int level;
634     struct treenode * lchild;
635     struct treenode * rchild;
636 } tn;
637
638 int finalizable_count = 0;
639 int finalized_count = 0;
640 volatile int dropped_something = 0;
641
642 # ifdef __STDC__
643   void finalizer(void * obj, void * client_data)
644 # else
645   void finalizer(obj, client_data)
646   char * obj;
647   char * client_data;
648 # endif
649 {
650   tn * t = (tn *)obj;
651
652 # ifdef PCR
653      PCR_ThCrSec_EnterSys();
654 # endif
655 # if defined(GC_PTHREADS)
656     static pthread_mutex_t incr_lock = PTHREAD_MUTEX_INITIALIZER;
657     pthread_mutex_lock(&incr_lock);
658 # elif defined(GC_WIN32_THREADS)
659     EnterCriticalSection(&incr_cs);
660 # endif
661   if ((int)(GC_word)client_data != t -> level) {
662      (void)GC_printf("Wrong finalization data - collector is broken\n");
663      FAIL;
664   }
665   finalized_count++;
666   t -> level = -1;      /* detect duplicate finalization immediately */
667 # ifdef PCR
668     PCR_ThCrSec_ExitSys();
669 # endif
670 # if defined(GC_PTHREADS)
671     pthread_mutex_unlock(&incr_lock);
672 # elif defined(GC_WIN32_THREADS)
673     LeaveCriticalSection(&incr_cs);
674 # endif
675 }
676
677 size_t counter = 0;
678
679 # define MAX_FINALIZED 8000
680
681 # if !defined(MACOS)
682   GC_FAR GC_word live_indicators[MAX_FINALIZED] = {0};
683 #else
684   /* Too big for THINK_C. have to allocate it dynamically. */
685   GC_word *live_indicators = 0;
686 #endif
687
688 int live_indicators_count = 0;
689
690 tn * mktree(int n)
691 {
692     tn * result = (tn *)GC_MALLOC(sizeof(tn));
693     
694     collectable_count++;
695 #   if defined(MACOS)
696         /* get around static data limitations. */
697         if (!live_indicators)
698                 live_indicators =
699                     (GC_word*)NewPtrClear(MAX_FINALIZED * sizeof(GC_word));
700         if (!live_indicators) {
701           (void)GC_printf("Out of memory\n");
702           exit(1);
703         }
704 #   endif
705     if (n == 0) return(0);
706     if (result == 0) {
707         (void)GC_printf("Out of memory\n");
708         exit(1);
709     }
710     result -> level = n;
711     result -> lchild = mktree(n-1);
712     result -> rchild = mktree(n-1);
713     if (counter++ % 17 == 0 && n >= 2) {
714         tn * tmp = result -> lchild -> rchild;
715         
716         result -> lchild -> rchild = result -> rchild -> lchild;
717         result -> rchild -> lchild = tmp;
718     }
719     if (counter++ % 119 == 0) {
720         int my_index;
721         
722         {
723 #         ifdef PCR
724             PCR_ThCrSec_EnterSys();
725 #         endif
726 #         if defined(GC_PTHREADS)
727             static pthread_mutex_t incr_lock = PTHREAD_MUTEX_INITIALIZER;
728             pthread_mutex_lock(&incr_lock);
729 #         elif defined(GC_WIN32_THREADS)
730             EnterCriticalSection(&incr_cs);
731 #         endif
732                 /* Losing a count here causes erroneous report of failure. */
733           finalizable_count++;
734           my_index = live_indicators_count++;
735 #         ifdef PCR
736             PCR_ThCrSec_ExitSys();
737 #         endif
738 #         if defined(GC_PTHREADS)
739             pthread_mutex_unlock(&incr_lock);
740 #         elif defined(GC_WIN32_THREADS)
741             LeaveCriticalSection(&incr_cs);
742 #         endif
743         }
744
745         GC_REGISTER_FINALIZER((void *)result, finalizer, (void *)(GC_word)n,
746                               (GC_finalization_proc *)0, (void * *)0);
747         if (my_index >= MAX_FINALIZED) {
748                 GC_printf("live_indicators overflowed\n");
749                 FAIL;
750         }
751         live_indicators[my_index] = 13;
752         if (GC_GENERAL_REGISTER_DISAPPEARING_LINK(
753                 (void * *)(&(live_indicators[my_index])),
754                 (void *)result) != 0) {
755                 GC_printf("GC_general_register_disappearing_link failed\n");
756                 FAIL;
757         }
758         if (GC_unregister_disappearing_link(
759                 (void * *)
760                    (&(live_indicators[my_index]))) == 0) {
761                 GC_printf("GC_unregister_disappearing_link failed\n");
762                 FAIL;
763         }
764         if (GC_GENERAL_REGISTER_DISAPPEARING_LINK(
765                 (void * *)(&(live_indicators[my_index])),
766                 (void *)result) != 0) {
767                 GC_printf("GC_general_register_disappearing_link failed 2\n");
768                 FAIL;
769         }
770         GC_reachable_here(result);
771     }
772     return(result);
773 }
774
775 void chktree(tn *t, int n)
776 {
777     if (n == 0 && t != 0) {
778         (void)GC_printf("Clobbered a leaf - collector is broken\n");
779         FAIL;
780     }
781     if (n == 0) return;
782     if (t -> level != n) {
783         (void)GC_printf("Lost a node at level %d - collector is broken\n", n);
784         FAIL;
785     }
786     if (counter++ % 373 == 0) {
787         collectable_count++;
788         (void) GC_MALLOC(counter%5001);
789     }
790     chktree(t -> lchild, n-1);
791     if (counter++ % 73 == 0) {
792         collectable_count++;
793         (void) GC_MALLOC(counter%373);
794     }
795     chktree(t -> rchild, n-1);
796 }
797
798
799 #if defined(GC_PTHREADS)
800 pthread_key_t fl_key;
801
802 void * alloc8bytes()
803 {
804 # if defined(SMALL_CONFIG) || defined(GC_DEBUG)
805     collectable_count++;
806     return(GC_MALLOC(8));
807 # else
808     void ** my_free_list_ptr;
809     void * my_free_list;
810     
811     my_free_list_ptr = (void **)pthread_getspecific(fl_key);
812     if (my_free_list_ptr == 0) {
813         uncollectable_count++;
814         my_free_list_ptr = GC_NEW_UNCOLLECTABLE(void *);
815         if (pthread_setspecific(fl_key, my_free_list_ptr) != 0) {
816             (void)GC_printf("pthread_setspecific failed\n");
817             FAIL;
818         }
819     }
820     my_free_list = *my_free_list_ptr;
821     if (my_free_list == 0) {
822         my_free_list = GC_malloc_many(8);
823         if (my_free_list == 0) {
824             (void)GC_printf("alloc8bytes out of memory\n");
825             FAIL;
826         }
827     }
828     *my_free_list_ptr = GC_NEXT(my_free_list);
829     GC_NEXT(my_free_list) = 0;
830     collectable_count++;
831     return(my_free_list);
832 # endif
833 }
834
835 #else
836 #   define alloc8bytes() GC_MALLOC_ATOMIC(8)
837 #endif
838
839 void alloc_small(int n)
840 {
841     int i;
842     
843     for (i = 0; i < n; i += 8) {
844         atomic_count++;
845         if (alloc8bytes() == 0) {
846             (void)GC_printf("Out of memory\n");
847             FAIL;
848         }
849     }
850 }
851
852 # if defined(THREADS) && defined(GC_DEBUG)
853 #   ifdef VERY_SMALL_CONFIG
854 #     define TREE_HEIGHT 12
855 #   else
856 #     define TREE_HEIGHT 15
857 #   endif
858 # else
859 #   ifdef VERY_SMALL_CONFIG
860 #     define TREE_HEIGHT 13
861 #   else
862 #     define TREE_HEIGHT 16
863 #   endif
864 # endif
865 void tree_test()
866 {
867     tn * root;
868     int i;
869     
870     root = mktree(TREE_HEIGHT);
871 #   ifndef VERY_SMALL_CONFIG
872       alloc_small(5000000);
873 #   endif
874     chktree(root, TREE_HEIGHT);
875     if (finalized_count && ! dropped_something) {
876         (void)GC_printf("Premature finalization - collector is broken\n");
877         FAIL;
878     }
879     dropped_something = 1;
880     GC_noop(root);      /* Root needs to remain live until      */
881                         /* dropped_something is set.            */
882     root = mktree(TREE_HEIGHT);
883     chktree(root, TREE_HEIGHT);
884     for (i = TREE_HEIGHT; i >= 0; i--) {
885         root = mktree(i);
886         chktree(root, i);
887     }
888 #   ifndef VERY_SMALL_CONFIG
889       alloc_small(5000000);
890 #   endif
891 }
892
893 unsigned n_tests = 0;
894
895 GC_word bm_huge[10] = {
896     0xffffffff,
897     0xffffffff,
898     0xffffffff,
899     0xffffffff,
900     0xffffffff,
901     0xffffffff,
902     0xffffffff,
903     0xffffffff,
904     0xffffffff,
905     0x00ffffff,
906 };
907
908 /* A very simple test of explicitly typed allocation    */
909 void typed_test()
910 {
911     GC_word * old, * new;
912     GC_word bm3 = 0x3;
913     GC_word bm2 = 0x2;
914     GC_word bm_large = 0xf7ff7fff;
915     GC_descr d1 = GC_make_descriptor(&bm3, 2);
916     GC_descr d2 = GC_make_descriptor(&bm2, 2);
917     GC_descr d3 = GC_make_descriptor(&bm_large, 32);
918     GC_descr d4 = GC_make_descriptor(bm_huge, 320);
919     GC_word * x = (GC_word *)GC_malloc_explicitly_typed(2000, d4);
920     int i;
921     
922 #   ifndef LINT
923       (void)GC_make_descriptor(&bm_large, 32);
924 #   endif
925     collectable_count++;
926     old = 0;
927     for (i = 0; i < 4000; i++) {
928         collectable_count++;
929         new = (GC_word *) GC_malloc_explicitly_typed(4 * sizeof(GC_word), d1);
930         if (0 != new[0] || 0 != new[1]) {
931             GC_printf("Bad initialization by GC_malloc_explicitly_typed\n");
932             FAIL;
933         }
934         new[0] = 17;
935         new[1] = (GC_word)old;
936         old = new;
937         collectable_count++;
938         new = (GC_word *) GC_malloc_explicitly_typed(4 * sizeof(GC_word), d2);
939         new[0] = 17;
940         new[1] = (GC_word)old;
941         old = new;
942         collectable_count++;
943         new = (GC_word *) GC_malloc_explicitly_typed(33 * sizeof(GC_word), d3);
944         new[0] = 17;
945         new[1] = (GC_word)old;
946         old = new;
947         collectable_count++;
948         new = (GC_word *) GC_calloc_explicitly_typed(4, 2 * sizeof(GC_word),
949                                                      d1);
950         new[0] = 17;
951         new[1] = (GC_word)old;
952         old = new;
953         collectable_count++;
954         if (i & 0xff) {
955           new = (GC_word *) GC_calloc_explicitly_typed(7, 3 * sizeof(GC_word),
956                                                      d2);
957         } else {
958           new = (GC_word *) GC_calloc_explicitly_typed(1001,
959                                                        3 * sizeof(GC_word),
960                                                        d2);
961           if (0 != new[0] || 0 != new[1]) {
962             GC_printf("Bad initialization by GC_malloc_explicitly_typed\n");
963             FAIL;
964           }
965         }
966         new[0] = 17;
967         new[1] = (GC_word)old;
968         old = new;
969     }
970     for (i = 0; i < 20000; i++) {
971         if (new[0] != 17) {
972             (void)GC_printf("typed alloc failed at %lu\n",
973                             (unsigned long)i);
974             FAIL;
975         }
976         new[0] = 0;
977         old = new;
978         new = (GC_word *)(old[1]);
979     }
980     GC_gcollect();
981     GC_noop(x);
982 }
983
984 int fail_count = 0;
985
986 #ifndef __STDC__
987 /*ARGSUSED*/
988 void fail_proc1(x)
989 void * x;
990 {
991     fail_count++;
992 }
993
994 #else
995
996 /*ARGSUSED*/
997 void fail_proc1(void * x)
998 {
999     fail_count++;
1000 }   
1001
1002 static void uniq(void *p, ...) {
1003   va_list a;
1004   void *q[100];
1005   int n = 0, i, j;
1006   q[n++] = p;
1007   va_start(a,p);
1008   for (;(q[n] = va_arg(a,void *));n++) ;
1009   va_end(a);
1010   for (i=0; i<n; i++)
1011     for (j=0; j<i; j++)
1012       if (q[i] == q[j]) {
1013         GC_printf(
1014               "Apparently failed to mark from some function arguments.\n"
1015               "Perhaps GC_push_regs was configured incorrectly?\n"
1016         );
1017         FAIL;
1018       }
1019 }
1020
1021 #endif /* __STDC__ */
1022
1023 #ifdef THREADS
1024 #   define TEST_FAIL_COUNT(n) 1
1025 #else 
1026 #   define TEST_FAIL_COUNT(n) (fail_count >= (n))
1027 #endif
1028
1029 void run_one_test()
1030 {
1031     char *x;
1032     char **z;
1033 #   ifdef LINT
1034         char *y = 0;
1035 #   else
1036         char *y = (char *)(size_t)fail_proc1;
1037 #   endif
1038     CLOCK_TYPE start_time;
1039     CLOCK_TYPE reverse_time;
1040     CLOCK_TYPE typed_time;
1041     CLOCK_TYPE tree_time;
1042     unsigned long time_diff;
1043     DCL_LOCK_STATE;
1044     
1045 #   ifdef FIND_LEAK
1046         GC_printf(
1047                 "This test program is not designed for leak detection mode\n");
1048         GC_printf("Expect lots of problems.\n");
1049 #   endif
1050     GC_FREE(0);
1051 #   ifndef DBG_HDRS_ALL
1052       collectable_count += 3;
1053       if ((GC_size(GC_malloc(7)) != 8 &&
1054            GC_size(GC_malloc(7)) != MIN_WORDS * sizeof(GC_word))
1055         || GC_size(GC_malloc(15)) != 16) {
1056             GC_printf("GC_size produced unexpected results\n");
1057             FAIL;
1058       }
1059       collectable_count += 1;
1060       if (GC_size(GC_malloc(0)) != MIN_WORDS * sizeof(GC_word)) {
1061         GC_printf("GC_malloc(0) failed: GC_size returns %ld\n",
1062                         (unsigned long)GC_size(GC_malloc(0)));
1063         FAIL;
1064       }
1065       collectable_count += 1;
1066       if (GC_size(GC_malloc_uncollectable(0)) != MIN_WORDS * sizeof(GC_word)) {
1067         GC_printf("GC_malloc_uncollectable(0) failed\n");
1068         FAIL;
1069       }
1070       GC_is_valid_displacement_print_proc = fail_proc1;
1071       GC_is_visible_print_proc = fail_proc1;
1072       collectable_count += 1;
1073       x = GC_malloc(16);
1074       if (GC_base(x + 13) != x) {
1075         GC_printf("GC_base(heap ptr) produced incorrect result\n");
1076         FAIL;
1077       }
1078 #     ifndef PCR
1079         if (GC_base(y) != 0) {
1080           GC_printf("GC_base(fn_ptr) produced incorrect result\n");
1081           FAIL;
1082         }
1083 #     endif
1084       if (GC_same_obj(x+5, x) != x + 5) {
1085         GC_printf("GC_same_obj produced incorrect result\n");
1086         FAIL;
1087       }
1088       if (GC_is_visible(y) != y || GC_is_visible(x) != x) {
1089         GC_printf("GC_is_visible produced incorrect result\n");
1090         FAIL;
1091       }
1092       z = GC_malloc(8);
1093       GC_PTR_STORE(z, x);
1094       if (*z != x) {
1095         GC_printf("GC_PTR_STORE failed: %p != %p\n", *z, x);
1096         FAIL;
1097       }
1098       if (!TEST_FAIL_COUNT(1)) {
1099 #       if!(defined(POWERPC) || defined(IA64)) || defined(M68K)
1100           /* On POWERPCs function pointers point to a descriptor in the */
1101           /* data segment, so there should have been no failures.       */
1102           /* The same applies to IA64.  Something similar seems to      */
1103           /* be going on with NetBSD/M68K.                              */
1104           GC_printf("GC_is_visible produced wrong failure indication\n");
1105           FAIL;
1106 #       endif
1107       }
1108       if (GC_is_valid_displacement(y) != y
1109         || GC_is_valid_displacement(x) != x
1110         || GC_is_valid_displacement(x + 3) != x + 3) {
1111         GC_printf(
1112                 "GC_is_valid_displacement produced incorrect result\n");
1113         FAIL;
1114       }
1115 #     if defined(__STDC__) && !defined(MSWIN32) && !defined(MSWINCE)
1116         /* Harder to test under Windows without a gc.h declaration.  */
1117         {
1118           size_t i;
1119           extern void *GC_memalign();
1120
1121           GC_malloc(17);
1122           for (i = sizeof(GC_word); i < 512; i *= 2) {
1123             GC_word result = (GC_word) GC_memalign(i, 17);
1124             if (result % i != 0 || result == 0 || *(int *)result != 0) FAIL;
1125           } 
1126         }
1127 #     endif
1128 #     ifndef ALL_INTERIOR_POINTERS
1129 #      if defined(RS6000) || defined(POWERPC)
1130         if (!TEST_FAIL_COUNT(1)) {
1131 #      else
1132         if (GC_all_interior_pointers && !TEST_FAIL_COUNT(1)
1133             || !GC_all_interior_pointers && !TEST_FAIL_COUNT(2)) {
1134 #      endif
1135           GC_printf("GC_is_valid_displacement produced wrong failure indication\n");
1136           FAIL;
1137         }
1138 #     endif
1139 #   endif /* DBG_HDRS_ALL */
1140     /* Test floating point alignment */
1141         collectable_count += 2;
1142         *(double *)GC_MALLOC(sizeof(double)) = 1.0;
1143         *(double *)GC_MALLOC(sizeof(double)) = 1.0;
1144     /* Test size 0 allocation a bit more */
1145         {
1146            size_t i;
1147            for (i = 0; i < 10000; ++i) {
1148              GC_MALLOC(0);
1149              GC_FREE(GC_MALLOC(0));
1150              GC_MALLOC_ATOMIC(0);
1151              GC_FREE(GC_MALLOC_ATOMIC(0));
1152            }
1153          }
1154 #   ifdef GC_GCJ_SUPPORT
1155       GC_REGISTER_DISPLACEMENT(sizeof(struct fake_vtable *));
1156       GC_init_gcj_malloc(0, (void *)fake_gcj_mark_proc);
1157 #   endif
1158     /* Make sure that fn arguments are visible to the collector.        */
1159 #   ifdef __STDC__
1160       uniq(
1161         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1162         (GC_gcollect(),GC_malloc(12)),
1163         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1164         (GC_gcollect(),GC_malloc(12)),
1165         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1166         (GC_gcollect(),GC_malloc(12)),
1167         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1168         (GC_gcollect(),GC_malloc(12)),
1169         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1170         (GC_gcollect(),GC_malloc(12)),
1171         (void *)0);
1172 #   endif
1173     /* GC_malloc(0) must return NULL or something we can deallocate. */
1174         GC_free(GC_malloc(0));
1175         GC_free(GC_malloc_atomic(0));
1176         GC_free(GC_malloc(0));
1177         GC_free(GC_malloc_atomic(0));
1178     /* Repeated list reversal test. */
1179         GET_TIME(start_time);
1180         reverse_test();
1181         if (GC_print_stats) {
1182           GET_TIME(reverse_time);
1183           time_diff = MS_TIME_DIFF(reverse_time, start_time);
1184           GC_log_printf("-------------Finished reverse_test at time %u (%p)\n",
1185                         (unsigned) time_diff, &start_time);
1186         }
1187 #   ifndef DBG_HDRS_ALL
1188       typed_test();
1189       if (GC_print_stats) {
1190         GET_TIME(typed_time);
1191         time_diff = MS_TIME_DIFF(typed_time, start_time);
1192         GC_log_printf("-------------Finished typed_test at time %u (%p)\n",
1193                       (unsigned) time_diff, &start_time);
1194       }
1195 #   endif /* DBG_HDRS_ALL */
1196     tree_test();
1197     if (GC_print_stats) {
1198       GET_TIME(tree_time);
1199       time_diff = MS_TIME_DIFF(tree_time, start_time);
1200       GC_log_printf("-------------Finished tree_test at time %u (%p)\n",
1201                       (unsigned) time_diff, &start_time);
1202     }
1203     LOCK();
1204     n_tests++;
1205     UNLOCK();
1206 #   if defined(THREADS) && defined(HANDLE_FORK)
1207       if (fork() == 0) {
1208         GC_gcollect();
1209         tiny_reverse_test(0);
1210         GC_gcollect();
1211         if (GC_print_stats)
1212           GC_log_printf("Finished a child process\n");
1213         exit(0);
1214       }
1215 #   endif
1216     if (GC_print_stats)
1217       GC_log_printf("Finished %p\n", &start_time);
1218 }
1219
1220 void check_heap_stats()
1221 {
1222     size_t max_heap_sz;
1223     int i;
1224     int still_live;
1225     int late_finalize_count = 0;
1226     
1227 #   ifdef VERY_SMALL_CONFIG
1228     /* these are something of a guess */
1229     if (sizeof(char *) > 4) {
1230         max_heap_sz = 4500000;
1231     } else {
1232         max_heap_sz = 2800000;
1233     }
1234 #   else
1235     if (sizeof(char *) > 4) {
1236         max_heap_sz = 19000000;
1237     } else {
1238         max_heap_sz = 11000000;
1239     }
1240 #   endif
1241 #   ifdef GC_DEBUG
1242         max_heap_sz *= 2;
1243 #       ifdef SAVE_CALL_CHAIN
1244             max_heap_sz *= 3;
1245 #           ifdef SAVE_CALL_COUNT
1246                 max_heap_sz += max_heap_sz * SAVE_CALL_COUNT/4;
1247 #           endif
1248 #       endif
1249 #   endif
1250     /* Garbage collect repeatedly so that all inaccessible objects      */
1251     /* can be finalized.                                                */
1252       while (GC_collect_a_little()) { }
1253       for (i = 0; i < 16; i++) {
1254         GC_gcollect();
1255         late_finalize_count += GC_invoke_finalizers();
1256       }
1257     (void)GC_printf("Completed %u tests\n", n_tests);
1258     (void)GC_printf("Allocated %d collectable objects\n", collectable_count);
1259     (void)GC_printf("Allocated %d uncollectable objects\n",
1260                     uncollectable_count);
1261     (void)GC_printf("Allocated %d atomic objects\n", atomic_count);
1262     (void)GC_printf("Allocated %d stubborn objects\n", stubborn_count);
1263     (void)GC_printf("Finalized %d/%d objects - ",
1264                     finalized_count, finalizable_count);
1265 #   ifdef FINALIZE_ON_DEMAND
1266         if (finalized_count != late_finalize_count) {
1267             (void)GC_printf("Demand finalization error\n");
1268             FAIL;
1269         }
1270 #   endif
1271     if (finalized_count > finalizable_count
1272         || finalized_count < finalizable_count/2) {
1273         (void)GC_printf("finalization is probably broken\n");
1274         FAIL;
1275     } else {
1276         (void)GC_printf("finalization is probably ok\n");
1277     }
1278     still_live = 0;
1279     for (i = 0; i < MAX_FINALIZED; i++) {
1280         if (live_indicators[i] != 0) {
1281             still_live++;
1282         }
1283     }
1284     i = finalizable_count - finalized_count - still_live;
1285     if (0 != i) {
1286         GC_printf("%d disappearing links remain and %d more objects "
1287                   "were not finalized\n", still_live, i);
1288         if (i > 10) {
1289             GC_printf("\tVery suspicious!\n");
1290         } else {
1291             GC_printf("\tSlightly suspicious, but probably OK.\n");
1292         }
1293     }
1294     (void)GC_printf("Total number of bytes allocated is %lu\n",
1295                 (unsigned long)
1296                    (GC_bytes_allocd + GC_bytes_allocd_before_gc));
1297     (void)GC_printf("Final heap size is %lu bytes\n",
1298                     (unsigned long)GC_get_heap_size());
1299     if (GC_bytes_allocd + GC_bytes_allocd_before_gc
1300 #   ifdef VERY_SMALL_CONFIG
1301         < 2700000*n_tests) {
1302 #   else
1303         < 33500000*n_tests) {
1304 #   endif
1305         (void)GC_printf("Incorrect execution - missed some allocations\n");
1306         FAIL;
1307     }
1308     if (GC_get_heap_size() > max_heap_sz*n_tests) {
1309         (void)GC_printf("Unexpected heap growth - collector may be broken\n");
1310         FAIL;
1311     }
1312     (void)GC_printf("Collector appears to work\n");
1313 }
1314
1315 #if defined(MACOS)
1316 void SetMinimumStack(long minSize)
1317 {
1318         long newApplLimit;
1319
1320         if (minSize > LMGetDefltStack())
1321         {
1322                 newApplLimit = (long) GetApplLimit()
1323                                 - (minSize - LMGetDefltStack());
1324                 SetApplLimit((Ptr) newApplLimit);
1325                 MaxApplZone();
1326         }
1327 }
1328
1329 #define cMinStackSpace (512L * 1024L)
1330
1331 #endif
1332
1333 #ifdef __STDC__
1334     void warn_proc(char *msg, GC_word p)
1335 #else
1336     void warn_proc(msg, p)
1337     char *msg;
1338     GC_word p;
1339 #endif
1340 {
1341     GC_printf(msg, (unsigned long)p);
1342     /*FAIL;*/
1343 }
1344
1345
1346 #if !defined(PCR) \
1347     && !defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS) \
1348     || defined(LINT)
1349 #if defined(MSWIN32) && !defined(__MINGW32__)
1350   int APIENTRY WinMain(HINSTANCE instance, HINSTANCE prev, LPTSTR cmd, int n)
1351 #else
1352   int main()
1353 #endif
1354 {
1355 #   if defined(DJGPP)
1356         int dummy;
1357 #   endif
1358     n_tests = 0;
1359     
1360 #   if defined(DJGPP)
1361         /* No good way to determine stack base from library; do it */
1362         /* manually on this platform.                              */
1363         GC_stackbottom = (void *)(&dummy);
1364 #   endif
1365 #   if defined(MACOS)
1366         /* Make sure we have lots and lots of stack space.      */
1367         SetMinimumStack(cMinStackSpace);
1368         /* Cheat and let stdio initialize toolbox for us.       */
1369         printf("Testing GC Macintosh port.\n");
1370 #   endif
1371     GC_COND_INIT();
1372     GC_set_warn_proc(warn_proc);
1373 #   if (defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(GWW_VDB)) \
1374           && !defined(MAKE_BACK_GRAPH) && !defined(NO_INCREMENTAL)
1375       GC_enable_incremental();
1376       GC_printf("Switched to incremental mode\n");
1377 #     if defined(MPROTECT_VDB)
1378         GC_printf("Emulating dirty bits with mprotect/signals\n");
1379 #     else
1380 #       ifdef PROC_VDB
1381           GC_printf("Reading dirty bits from /proc\n");
1382 #       else
1383           GC_printf("Using DEFAULT_VDB dirty bit implementation\n");
1384 #       endif
1385 #      endif
1386 #   endif
1387     run_one_test();
1388     check_heap_stats();
1389 #   ifndef MSWINCE
1390       fflush(stdout);
1391 #   endif
1392 #   ifdef LINT
1393         /* Entry points we should be testing, but aren't.                  */
1394         /* Some can be tested by defining GC_DEBUG at the top of this file */
1395         /* This is a bit SunOS4 specific.                                  */                   
1396         GC_noop(GC_expand_hp, GC_add_roots, GC_clear_roots,
1397                 GC_register_disappearing_link,
1398                 GC_register_finalizer_ignore_self,
1399                 GC_debug_register_displacement,
1400                 GC_print_obj, GC_debug_change_stubborn,
1401                 GC_debug_end_stubborn_change, GC_debug_malloc_uncollectable,
1402                 GC_debug_free, GC_debug_realloc, GC_generic_malloc_words_small,
1403                 GC_init, GC_make_closure, GC_debug_invoke_finalizer,
1404                 GC_page_was_ever_dirty, GC_is_fresh,
1405                 GC_malloc_ignore_off_page, GC_malloc_atomic_ignore_off_page,
1406                 GC_set_max_heap_size, GC_get_bytes_since_gc,
1407                 GC_get_total_bytes, GC_pre_incr, GC_post_incr);
1408 #   endif
1409 #   ifdef MSWIN32
1410       GC_win32_free_heap();
1411 #   endif
1412     return(0);
1413 }
1414 # endif
1415
1416 #if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
1417
1418 DWORD __stdcall thr_run_one_test(void *arg)
1419 {
1420   run_one_test();
1421   return 0;
1422 }
1423
1424 #ifdef MSWINCE
1425 HANDLE win_created_h;
1426 HWND win_handle;
1427
1428 LRESULT CALLBACK window_proc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1429 {
1430   LRESULT ret = 0;
1431   switch (uMsg) {
1432     case WM_HIBERNATE:
1433       GC_printf("Received WM_HIBERNATE, calling GC_gcollect\n");
1434       GC_gcollect();
1435       break;
1436     case WM_CLOSE:
1437       GC_printf("Received WM_CLOSE, closing window\n");
1438       DestroyWindow(hwnd);
1439       break;
1440     case WM_DESTROY:
1441       PostQuitMessage(0);
1442       break;
1443     default:
1444       ret = DefWindowProc(hwnd, uMsg, wParam, lParam);
1445       break;
1446   }
1447   return ret;
1448 }
1449
1450 DWORD __stdcall thr_window(void *arg)
1451 {
1452   WNDCLASS win_class = {
1453     CS_NOCLOSE,
1454     window_proc,
1455     0,
1456     0,
1457     GetModuleHandle(NULL),
1458     NULL,
1459     NULL,
1460     (HBRUSH)(COLOR_APPWORKSPACE+1),
1461     NULL,
1462     L"GCtestWindow"
1463   };
1464   MSG msg;
1465
1466   if (!RegisterClass(&win_class))
1467     FAIL;
1468
1469   win_handle = CreateWindowEx(
1470     0,
1471     L"GCtestWindow",
1472     L"GCtest",
1473     0,
1474     CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
1475     NULL,
1476     NULL,
1477     GetModuleHandle(NULL),
1478     NULL);
1479
1480   if (win_handle == NULL)
1481     FAIL;
1482
1483   SetEvent(win_created_h);
1484
1485   ShowWindow(win_handle, SW_SHOW);
1486   UpdateWindow(win_handle);
1487
1488   while (GetMessage(&msg, NULL, 0, 0)) {
1489     TranslateMessage(&msg);
1490     DispatchMessage(&msg);
1491   }
1492
1493   return 0;
1494 }
1495 #endif
1496
1497 #define NTEST 2
1498
1499 # ifdef MSWINCE
1500 int APIENTRY GC_WinMain(HINSTANCE instance, HINSTANCE prev, LPWSTR cmd, int n)
1501 #   else
1502 int APIENTRY WinMain(HINSTANCE instance, HINSTANCE prev, LPSTR cmd, int n)
1503 # endif
1504 {
1505 # if NTEST > 0
1506    HANDLE h[NTEST];
1507    int i;
1508 # endif
1509 # ifdef MSWINCE
1510     HANDLE win_thr_h;
1511 # endif
1512   DWORD thread_id;
1513
1514 # ifdef GC_DLL
1515     GC_use_DllMain();  /* Test with implicit thread registration if possible. */
1516     GC_printf("Using DllMain to track threads\n");
1517 # endif
1518   GC_COND_INIT();
1519 # ifndef NO_INCREMENTAL
1520     GC_enable_incremental();
1521 # endif
1522   InitializeCriticalSection(&incr_cs);
1523   (void) GC_set_warn_proc(warn_proc);
1524 # ifdef MSWINCE
1525     win_created_h = CreateEvent(NULL, FALSE, FALSE, NULL);
1526     if (win_created_h == (HANDLE)NULL) {
1527       (void)GC_printf("Event creation failed %\n", GetLastError());
1528       FAIL;
1529     }
1530     win_thr_h = GC_CreateThread(NULL, 0, thr_window, 0, 0, &thread_id);
1531     if (win_thr_h == (HANDLE)NULL) {
1532       (void)GC_printf("Thread creation failed %d\n", GetLastError());
1533       FAIL;
1534     }
1535     if (WaitForSingleObject(win_created_h, INFINITE) != WAIT_OBJECT_0)
1536       FAIL;
1537     CloseHandle(win_created_h);
1538 # endif
1539 # if NTEST > 0
1540    for (i = 0; i < NTEST; i++) {
1541     h[i] = GC_CreateThread(NULL, 0, thr_run_one_test, 0, 0, &thread_id);
1542     if (h[i] == (HANDLE)NULL) {
1543       (void)GC_printf("Thread creation failed %d\n", GetLastError());
1544       FAIL;
1545     }
1546    }
1547 # endif /* NTEST > 0 */
1548   run_one_test();
1549 # if NTEST > 0
1550    for (i = 0; i < NTEST; i++) {
1551     if (WaitForSingleObject(h[i], INFINITE) != WAIT_OBJECT_0) {
1552       (void)GC_printf("Thread wait failed %d\n", GetLastError());
1553       FAIL;
1554     }
1555    }
1556 # endif /* NTEST > 0 */
1557 # ifdef MSWINCE
1558     PostMessage(win_handle, WM_CLOSE, 0, 0);
1559     if (WaitForSingleObject(win_thr_h, INFINITE) != WAIT_OBJECT_0)
1560       FAIL;
1561 # endif
1562   check_heap_stats();
1563   return(0);
1564 }
1565
1566 #endif /* GC_WIN32_THREADS */
1567
1568
1569 #ifdef PCR
1570 test()
1571 {
1572     PCR_Th_T * th1;
1573     PCR_Th_T * th2;
1574     int code;
1575
1576     n_tests = 0;
1577     /* GC_enable_incremental(); */
1578     (void) GC_set_warn_proc(warn_proc);
1579     th1 = PCR_Th_Fork(run_one_test, 0);
1580     th2 = PCR_Th_Fork(run_one_test, 0);
1581     run_one_test();
1582     if (PCR_Th_T_Join(th1, &code, NIL, PCR_allSigsBlocked, PCR_waitForever)
1583         != PCR_ERes_okay || code != 0) {
1584         (void)GC_printf("Thread 1 failed\n");
1585     }
1586     if (PCR_Th_T_Join(th2, &code, NIL, PCR_allSigsBlocked, PCR_waitForever)
1587         != PCR_ERes_okay || code != 0) {
1588         (void)GC_printf("Thread 2 failed\n");
1589     }
1590     check_heap_stats();
1591     return(0);
1592 }
1593 #endif
1594
1595 #if defined(GC_PTHREADS)
1596 void * thr_run_one_test(void * arg)
1597 {
1598     run_one_test();
1599     return(0);
1600 }
1601
1602 #ifdef GC_DEBUG
1603 #  define GC_free GC_debug_free
1604 #endif
1605
1606 int main()
1607 {
1608     pthread_t th1;
1609     pthread_t th2;
1610     pthread_attr_t attr;
1611     int code;
1612 #   ifdef GC_IRIX_THREADS
1613         /* Force a larger stack to be preallocated      */
1614         /* Since the initial cant always grow later.    */
1615         *((volatile char *)&code - 1024*1024) = 0;      /* Require 1 Mb */
1616 #   endif /* GC_IRIX_THREADS */
1617 #   if defined(GC_HPUX_THREADS)
1618         /* Default stack size is too small, especially with the 64 bit ABI */
1619         /* Increase it.                                                    */
1620         if (pthread_default_stacksize_np(1024*1024, 0) != 0) {
1621           (void)GC_printf("pthread_default_stacksize_np failed.\n");
1622         }
1623 #   endif       /* GC_HPUX_THREADS */
1624 #   ifdef PTW32_STATIC_LIB
1625         pthread_win32_process_attach_np ();
1626         pthread_win32_thread_attach_np ();
1627 #   endif
1628     GC_COND_INIT();
1629
1630     pthread_attr_init(&attr);
1631 #   if defined(GC_IRIX_THREADS) || defined(GC_FREEBSD_THREADS) \
1632         || defined(GC_DARWIN_THREADS) || defined(GC_AIX_THREADS)
1633         pthread_attr_setstacksize(&attr, 1000000);
1634 #   endif
1635     n_tests = 0;
1636 #   if (defined(MPROTECT_VDB)) \
1637             && !defined(PARALLEL_MARK) &&!defined(REDIRECT_MALLOC) \
1638             && !defined(MAKE_BACK_GRAPH) && !defined(USE_PROC_FOR_LIBRARIES) \
1639             && !defined(NO_INCREMENTAL)
1640         GC_enable_incremental();
1641         (void) GC_printf("Switched to incremental mode\n");
1642 #     if defined(MPROTECT_VDB)
1643         (void)GC_printf("Emulating dirty bits with mprotect/signals\n");
1644 #     else
1645 #       ifdef PROC_VDB
1646             (void)GC_printf("Reading dirty bits from /proc\n");
1647 #       else
1648             (void)GC_printf("Using DEFAULT_VDB dirty bit implementation\n");
1649 #       endif
1650 #     endif
1651 #   endif
1652     (void) GC_set_warn_proc(warn_proc);
1653     if ((code = pthread_key_create(&fl_key, 0)) != 0) {
1654         (void)GC_printf("Key creation failed %d\n", code);
1655         FAIL;
1656     }
1657     if ((code = pthread_create(&th1, &attr, thr_run_one_test, 0)) != 0) {
1658         (void)GC_printf("Thread 1 creation failed %d\n", code);
1659         FAIL;
1660     }
1661     if ((code = pthread_create(&th2, &attr, thr_run_one_test, 0)) != 0) {
1662         (void)GC_printf("Thread 2 creation failed %d\n", code);
1663         FAIL;
1664     }
1665     run_one_test();
1666     if ((code = pthread_join(th1, 0)) != 0) {
1667         (void)GC_printf("Thread 1 failed %d\n", code);
1668         FAIL;
1669     }
1670     if (pthread_join(th2, 0) != 0) {
1671         (void)GC_printf("Thread 2 failed %d\n", code);
1672         FAIL;
1673     }
1674     check_heap_stats();
1675     (void)fflush(stdout);
1676     pthread_attr_destroy(&attr);
1677     GC_printf("Completed %d collections\n", GC_gc_no);
1678 #   ifdef PTW32_STATIC_LIB
1679         pthread_win32_thread_detach_np ();
1680         pthread_win32_process_detach_np ();
1681 #   endif
1682     return(0);
1683 }
1684 #endif /* GC_PTHREADS */