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