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