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