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 # ifdef HAVE_CONFIG_H
22 #   include "config.h"
23 # endif
24 
25 # undef GC_BUILD
26 
27 #if (defined(DBG_HDRS_ALL) || defined(MAKE_BACK_GRAPH)) \
28     && !defined(GC_DEBUG) && !defined(CPPCHECK)
29 #  define GC_DEBUG
30 #endif
31 
32 #ifdef DEFAULT_VDB /* specified manually (e.g. passed to CFLAGS) */
33 # define TEST_DEFAULT_VDB
34 #endif
35 
36 #if defined(CPPCHECK) && defined(GC_PTHREADS) && !defined(_GNU_SOURCE)
37 # define _GNU_SOURCE 1
38 #endif
39 #undef GC_NO_THREAD_REDIRECTS
40 #include "gc.h"
41 
42 #ifndef NTHREADS /* Number of additional threads to fork. */
43 #  define NTHREADS 5 /* excludes main thread, which also runs a test. */
44         /* Not respected by PCR test. */
45 #endif
46 
47 # if defined(mips) && defined(SYSTYPE_BSD43)
48     /* MIPS RISCOS 4 */
49 # else
50 #   include <stdlib.h>
51 # endif
52 # include <stdio.h>
53 # if defined(_WIN32_WCE) && !defined(__GNUC__)
54 #   include <winbase.h>
55 /* #   define assert ASSERT */
56 # else
57 #   include <assert.h>  /* Not normally used, but handy for debugging.  */
58 # endif
59 
60 #ifndef NO_TYPED_TEST
61 # include "gc_typed.h"
62 #endif
63 
64 #include "private/gc_priv.h"    /* For output, locking,                 */
65                                 /* some statistics and gcconfig.h.      */
66 
67 #if defined(MSWIN32) || defined(MSWINCE)
68 # ifndef WIN32_LEAN_AND_MEAN
69 #   define WIN32_LEAN_AND_MEAN 1
70 # endif
71 # define NOSERVICE
72 # include <windows.h>
73 #endif /* MSWIN32 || MSWINCE */
74 
75 #ifdef GC_PRINT_VERBOSE_STATS
76 # define print_stats VERBOSE
77 # define INIT_PRINT_STATS /* empty */
78 #else
79   /* Use own variable as GC_print_stats might not be exported.  */
80   static int print_stats = 0;
81 # ifdef GC_READ_ENV_FILE
82     /* GETENV uses GC internal function in this case.   */
83 #   define INIT_PRINT_STATS /* empty */
84 # else
85 #   define INIT_PRINT_STATS \
86         { \
87           if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) \
88             print_stats = VERBOSE; \
89           else if (0 != GETENV("GC_PRINT_STATS")) \
90             print_stats = 1; \
91         }
92 # endif
93 #endif /* !GC_PRINT_VERBOSE_STATS */
94 
95 # ifdef PCR
96 #   include "th/PCR_ThCrSec.h"
97 #   include "th/PCR_Th.h"
98 #   define GC_printf printf
99 # endif
100 
101 # if defined(GC_PTHREADS) && !defined(GC_WIN32_PTHREADS)
102 #   include <pthread.h>
103 # else
104 #   define NO_TEST_HANDLE_FORK
105 # endif
106 
107 # if (!defined(THREADS) || !defined(HANDLE_FORK) \
108       || (defined(DARWIN) && defined(MPROTECT_VDB) \
109           && !defined(NO_INCREMENTAL) && !defined(MAKE_BACK_GRAPH))) \
110      && !defined(NO_TEST_HANDLE_FORK) && !defined(TEST_HANDLE_FORK) \
111      && !defined(TEST_FORK_WITHOUT_ATFORK)
112 #   define NO_TEST_HANDLE_FORK
113 # endif
114 
115 # ifndef NO_TEST_HANDLE_FORK
116 #   include <unistd.h>
117 #   include <sys/types.h>
118 #   include <sys/wait.h>
119 #   if defined(HANDLE_FORK) && defined(CAN_CALL_ATFORK)
120 #     define INIT_FORK_SUPPORT GC_set_handle_fork(1)
121                 /* Causes abort in GC_init on pthread_atfork failure.   */
122 #   elif !defined(TEST_FORK_WITHOUT_ATFORK)
123 #     define INIT_FORK_SUPPORT GC_set_handle_fork(-1)
124                 /* Passing -1 implies fork() should be as well manually */
125                 /* surrounded with GC_atfork_prepare/parent/child.      */
126 #   endif
127 # endif
128 
129 # ifndef INIT_FORK_SUPPORT
130 #   define INIT_FORK_SUPPORT /* empty */
131 # endif
132 
133 #ifdef PCR
134 # define FINALIZER_LOCK() PCR_ThCrSec_EnterSys()
135 # define FINALIZER_UNLOCK() PCR_ThCrSec_ExitSys()
136 #elif defined(GC_PTHREADS)
137   static pthread_mutex_t incr_lock = PTHREAD_MUTEX_INITIALIZER;
138 # define FINALIZER_LOCK() pthread_mutex_lock(&incr_lock)
139 # define FINALIZER_UNLOCK() pthread_mutex_unlock(&incr_lock)
140 #elif defined(GC_WIN32_THREADS)
141   static CRITICAL_SECTION incr_cs;
142 # define FINALIZER_LOCK() EnterCriticalSection(&incr_cs)
143 # define FINALIZER_UNLOCK() LeaveCriticalSection(&incr_cs)
144 #else
145 # define FINALIZER_LOCK() (void)0
146 # define FINALIZER_UNLOCK() (void)0
147 #endif /* !THREADS */
148 
149 #include <stdarg.h>
150 
151 #ifdef TEST_MANUAL_VDB
152 # define INIT_MANUAL_VDB_ALLOWED GC_set_manual_vdb_allowed(1)
153 #elif !defined(SMALL_CONFIG)
154 # define INIT_MANUAL_VDB_ALLOWED GC_set_manual_vdb_allowed(0)
155 #else
156 # define INIT_MANUAL_VDB_ALLOWED /* empty */
157 #endif
158 
159 #ifdef TEST_PAGES_EXECUTABLE
160 # define INIT_PAGES_EXECUTABLE GC_set_pages_executable(1)
161 #else
162 # define INIT_PAGES_EXECUTABLE (void)0
163 #endif
164 
165 #define CHECK_GCLIB_VERSION \
166             if (GC_get_version() != ((GC_VERSION_MAJOR<<16) \
167                                     | (GC_VERSION_MINOR<<8) \
168                                     | GC_VERSION_MICRO)) { \
169               GC_printf("libgc version mismatch\n"); \
170               exit(1); \
171             }
172 
173 /* Call GC_INIT only on platforms on which we think we really need it,  */
174 /* so that we can test automatic initialization on the rest.            */
175 #if defined(TEST_EXPLICIT_GC_INIT) || defined(AIX) || defined(CYGWIN32) \
176         || defined(DARWIN) || defined(HOST_ANDROID) \
177         || (defined(MSWINCE) && !defined(GC_WINMAIN_REDIRECT))
178 #  define GC_OPT_INIT GC_INIT()
179 #else
180 #  define GC_OPT_INIT /* empty */
181 #endif
182 
183 #define INIT_FIND_LEAK \
184     if (!GC_get_find_leak()) {} else \
185       GC_printf("This test program is not designed for leak detection mode\n")
186 
187 #ifdef NO_CLOCK
188 # define INIT_PERF_MEASUREMENT (void)0
189 #else
190 # define INIT_PERF_MEASUREMENT GC_start_performance_measurement()
191 #endif
192 
193 #define GC_COND_INIT() \
194     INIT_FORK_SUPPORT; INIT_MANUAL_VDB_ALLOWED; INIT_PAGES_EXECUTABLE; \
195     GC_OPT_INIT; CHECK_GCLIB_VERSION; \
196     INIT_PRINT_STATS; INIT_FIND_LEAK; INIT_PERF_MEASUREMENT
197 
198 #define CHECK_OUT_OF_MEMORY(p) \
199             if ((p) == NULL) { \
200               GC_printf("Out of memory\n"); \
201               exit(1); \
202             }
203 
204 /* Define AO primitives for a single-threaded mode. */
205 #ifndef AO_HAVE_compiler_barrier
206   /* AO_t not defined. */
207 # define AO_t GC_word
208 #endif
209 #ifndef AO_HAVE_load_acquire
AO_load_acquire(const volatile AO_t * addr)210   static AO_t AO_load_acquire(const volatile AO_t *addr)
211   {
212     AO_t result;
213 
214     FINALIZER_LOCK();
215     result = *addr;
216     FINALIZER_UNLOCK();
217     return result;
218   }
219 #endif
220 #ifndef AO_HAVE_store_release
221   /* Not a macro as new_val argument should be evaluated before the lock. */
AO_store_release(volatile AO_t * addr,AO_t new_val)222   static void AO_store_release(volatile AO_t *addr, AO_t new_val)
223   {
224     FINALIZER_LOCK();
225     *addr = new_val;
226     FINALIZER_UNLOCK();
227   }
228 #endif
229 #ifndef AO_HAVE_fetch_and_add1
230 # define AO_fetch_and_add1(p) ((*(p))++)
231                 /* This is used only to update counters.        */
232 #endif
233 
234 /* Allocation Statistics.  Synchronization is not strictly necessary.   */
235 volatile AO_t uncollectable_count = 0;
236 volatile AO_t collectable_count = 0;
237 volatile AO_t atomic_count = 0;
238 volatile AO_t realloc_count = 0;
239 
240 volatile AO_t extra_count = 0;  /* Amount of space wasted in cons node; */
241                                 /* also used in gcj_cons, mktree and    */
242                                 /* chktree (for other purposes).        */
243 
244 #if defined(GC_AMIGA_FASTALLOC) && defined(AMIGA)
245   EXTERN_C_BEGIN
246   void GC_amiga_free_all_mem(void);
247   EXTERN_C_END
248 
Amiga_Fail(void)249   void Amiga_Fail(void){GC_amiga_free_all_mem();abort();}
250 # define FAIL Amiga_Fail()
251 #ifndef NO_TYPED_TEST
GC_amiga_gctest_malloc_explicitly_typed(size_t lb,GC_descr d)252   void *GC_amiga_gctest_malloc_explicitly_typed(size_t lb, GC_descr d){
253     void *ret=GC_malloc_explicitly_typed(lb,d);
254     if(ret==NULL){
255               GC_gcollect();
256               ret=GC_malloc_explicitly_typed(lb,d);
257       if(ret==NULL){
258         GC_printf("Out of memory, (typed allocations are not directly "
259                       "supported with the GC_AMIGA_FASTALLOC option.)\n");
260         FAIL;
261       }
262     }
263     return ret;
264   }
GC_amiga_gctest_calloc_explicitly_typed(size_t a,size_t lb,GC_descr d)265   void *GC_amiga_gctest_calloc_explicitly_typed(size_t a,size_t lb, GC_descr d){
266     void *ret=GC_calloc_explicitly_typed(a,lb,d);
267     if(ret==NULL){
268               GC_gcollect();
269               ret=GC_calloc_explicitly_typed(a,lb,d);
270       if(ret==NULL){
271         GC_printf("Out of memory, (typed allocations are not directly "
272                       "supported with the GC_AMIGA_FASTALLOC option.)\n");
273         FAIL;
274       }
275     }
276     return ret;
277   }
278 # define GC_malloc_explicitly_typed(a,b) GC_amiga_gctest_malloc_explicitly_typed(a,b)
279 # define GC_calloc_explicitly_typed(a,b,c) GC_amiga_gctest_calloc_explicitly_typed(a,b,c)
280 #endif /* !NO_TYPED_TEST */
281 
282 #else /* !AMIGA_FASTALLOC */
283 
284 # if defined(PCR) || defined(LINT2)
285 #   define FAIL abort()
286 # else
287 #   define FAIL ABORT("Test failed")
288 # endif
289 
290 #endif /* !AMIGA_FASTALLOC */
291 
292 /* AT_END may be defined to exercise the interior pointer test  */
293 /* if the collector is configured with ALL_INTERIOR_POINTERS.   */
294 /* As it stands, this test should succeed with either           */
295 /* configuration.  In the FIND_LEAK configuration, it should    */
296 /* find lots of leaks, since we free almost nothing.            */
297 
298 struct SEXPR {
299     struct SEXPR * sexpr_car;
300     struct SEXPR * sexpr_cdr;
301 };
302 
303 
304 typedef struct SEXPR * sexpr;
305 
306 # define INT_TO_SEXPR(x) ((sexpr)(GC_word)(x))
307 # define SEXPR_TO_INT(x) ((int)(GC_word)(x))
308 
309 # undef nil
310 # define nil (INT_TO_SEXPR(0))
311 # define car(x) ((x) -> sexpr_car)
312 # define cdr(x) ((x) -> sexpr_cdr)
313 # define is_nil(x) ((x) == nil)
314 
315 /* Silly implementation of Lisp cons. Intentionally wastes lots of space */
316 /* to test collector.                                                    */
317 # ifdef VERY_SMALL_CONFIG
318 #   define cons small_cons
319 # else
cons(sexpr x,sexpr y)320 sexpr cons (sexpr x, sexpr y)
321 {
322     sexpr r;
323     int *p;
324     unsigned my_extra = (unsigned)AO_fetch_and_add1(&extra_count) % 5000;
325 
326     r = (sexpr)GC_MALLOC(sizeof(struct SEXPR) + my_extra);
327     CHECK_OUT_OF_MEMORY(r);
328     AO_fetch_and_add1(&collectable_count);
329     for (p = (int *)r;
330          (word)p < (word)r + my_extra + sizeof(struct SEXPR); p++) {
331         if (*p) {
332             GC_printf("Found nonzero at %p - allocator is broken\n",
333                       (void *)p);
334             FAIL;
335         }
336         *p = (int)((13 << 12) + ((p - (int *)r) & 0xfff));
337     }
338 #   ifdef AT_END
339         r = (sexpr)((char *)r + (my_extra & ~7));
340 #   endif
341     r -> sexpr_car = x;
342     GC_PTR_STORE_AND_DIRTY(&r->sexpr_cdr, y);
343     GC_reachable_here(x);
344     return r;
345 }
346 # endif
347 
348 #include "gc_mark.h"
349 
350 #ifdef GC_GCJ_SUPPORT
351 
352 #include "gc_gcj.h"
353 
354 /* The following struct emulates the vtable in gcj.     */
355 /* This assumes the default value of MARK_DESCR_OFFSET. */
356 struct fake_vtable {
357   void * dummy;         /* class pointer in real gcj.   */
358   GC_word descr;
359 };
360 
361 struct fake_vtable gcj_class_struct1 = { 0, sizeof(struct SEXPR)
362                                             + sizeof(struct fake_vtable *) };
363                         /* length based descriptor.     */
364 struct fake_vtable gcj_class_struct2 =
365                         { 0, ((GC_word)3 << (CPP_WORDSZ - 3)) | GC_DS_BITMAP};
366                         /* Bitmap based descriptor.     */
367 
fake_gcj_mark_proc(word * addr,struct GC_ms_entry * mark_stack_ptr,struct GC_ms_entry * mark_stack_limit,word env)368 struct GC_ms_entry * fake_gcj_mark_proc(word * addr,
369                                         struct GC_ms_entry *mark_stack_ptr,
370                                         struct GC_ms_entry *mark_stack_limit,
371                                         word env   )
372 {
373     sexpr x;
374     if (1 == env) {
375         /* Object allocated with debug allocator.       */
376         addr = (word *)GC_USR_PTR_FROM_BASE(addr);
377     }
378     x = (sexpr)(addr + 1); /* Skip the vtable pointer. */
379     mark_stack_ptr = GC_MARK_AND_PUSH(
380                               (void *)(x -> sexpr_cdr), mark_stack_ptr,
381                               mark_stack_limit, (void * *)&(x -> sexpr_cdr));
382     mark_stack_ptr = GC_MARK_AND_PUSH(
383                               (void *)(x -> sexpr_car), mark_stack_ptr,
384                               mark_stack_limit, (void * *)&(x -> sexpr_car));
385     return(mark_stack_ptr);
386 }
387 
388 #endif /* GC_GCJ_SUPPORT */
389 
390 
small_cons(sexpr x,sexpr y)391 sexpr small_cons (sexpr x, sexpr y)
392 {
393     sexpr r = GC_NEW(struct SEXPR);
394 
395     CHECK_OUT_OF_MEMORY(r);
396     AO_fetch_and_add1(&collectable_count);
397     r -> sexpr_car = x;
398     GC_PTR_STORE_AND_DIRTY(&r->sexpr_cdr, y);
399     GC_reachable_here(x);
400     return r;
401 }
402 
403 #ifdef NO_CONS_ATOMIC_LEAF
404 # define small_cons_leaf(x) small_cons(INT_TO_SEXPR(x), nil)
405 #else
small_cons_leaf(int x)406   sexpr small_cons_leaf(int x)
407   {
408     sexpr r = (sexpr)GC_MALLOC_ATOMIC(sizeof(struct SEXPR));
409 
410     CHECK_OUT_OF_MEMORY(r);
411     AO_fetch_and_add1(&atomic_count);
412     r -> sexpr_car = INT_TO_SEXPR(x);
413     r -> sexpr_cdr = nil;
414     return r;
415   }
416 #endif
417 
small_cons_uncollectable(sexpr x,sexpr y)418 sexpr small_cons_uncollectable (sexpr x, sexpr y)
419 {
420     sexpr r = (sexpr)GC_MALLOC_UNCOLLECTABLE(sizeof(struct SEXPR));
421 
422     CHECK_OUT_OF_MEMORY(r);
423     AO_fetch_and_add1(&uncollectable_count);
424     r -> sexpr_cdr = (sexpr)(~(GC_word)y);
425     GC_PTR_STORE_AND_DIRTY(&r->sexpr_car, x);
426     return r;
427 }
428 
429 #ifdef GC_GCJ_SUPPORT
gcj_cons(sexpr x,sexpr y)430   sexpr gcj_cons(sexpr x, sexpr y)
431   {
432     sexpr result;
433     GC_word * r = (GC_word *)GC_GCJ_MALLOC(
434                         sizeof(struct SEXPR) + sizeof(struct fake_vtable*),
435                         (AO_fetch_and_add1(&extra_count) & 1) != 0
436                                                 ? &gcj_class_struct1
437                                                 : &gcj_class_struct2);
438 
439     CHECK_OUT_OF_MEMORY(r);
440     result = (sexpr)(r + 1);
441     result -> sexpr_car = x;
442     GC_PTR_STORE_AND_DIRTY(&result->sexpr_cdr, y);
443     GC_reachable_here(x);
444     return result;
445   }
446 #endif /* GC_GCJ_SUPPORT */
447 
448 /* Return reverse(x) concatenated with y */
reverse1(sexpr x,sexpr y)449 sexpr reverse1(sexpr x, sexpr y)
450 {
451     if (is_nil(x)) {
452         return(y);
453     } else {
454         return( reverse1(cdr(x), cons(car(x), y)) );
455     }
456 }
457 
reverse(sexpr x)458 sexpr reverse(sexpr x)
459 {
460 #   ifdef TEST_WITH_SYSTEM_MALLOC
461       GC_noop1(GC_HIDE_POINTER(malloc(100000)));
462 #   endif
463     return( reverse1(x, nil) );
464 }
465 
ints(int low,int up)466 sexpr ints(int low, int up)
467 {
468     if (low > up) {
469         return(nil);
470     } else {
471         return small_cons(small_cons_leaf(low), ints(low + 1, up));
472     }
473 }
474 
475 #ifdef GC_GCJ_SUPPORT
476 /* Return reverse(x) concatenated with y */
gcj_reverse1(sexpr x,sexpr y)477 sexpr gcj_reverse1(sexpr x, sexpr y)
478 {
479     if (is_nil(x)) {
480         return(y);
481     } else {
482         return( gcj_reverse1(cdr(x), gcj_cons(car(x), y)) );
483     }
484 }
485 
gcj_reverse(sexpr x)486 sexpr gcj_reverse(sexpr x)
487 {
488     return( gcj_reverse1(x, nil) );
489 }
490 
gcj_ints(int low,int up)491 sexpr gcj_ints(int low, int up)
492 {
493     if (low > up) {
494         return(nil);
495     } else {
496         return(gcj_cons(gcj_cons(INT_TO_SEXPR(low), nil), gcj_ints(low+1, up)));
497     }
498 }
499 #endif /* GC_GCJ_SUPPORT */
500 
501 /* To check uncollectible allocation we build lists with disguised cdr  */
502 /* pointers, and make sure they don't go away.                          */
uncollectable_ints(int low,int up)503 sexpr uncollectable_ints(int low, int up)
504 {
505     if (low > up) {
506         return(nil);
507     } else {
508         return(small_cons_uncollectable(small_cons_leaf(low),
509                uncollectable_ints(low+1, up)));
510     }
511 }
512 
check_ints(sexpr list,int low,int up)513 void check_ints(sexpr list, int low, int up)
514 {
515     if (is_nil(list)) {
516         GC_printf("list is nil\n");
517         FAIL;
518     }
519     if (SEXPR_TO_INT(car(car(list))) != low) {
520         GC_printf(
521            "List reversal produced incorrect list - collector is broken\n");
522         FAIL;
523     }
524     if (low == up) {
525         if (cdr(list) != nil) {
526            GC_printf("List too long - collector is broken\n");
527            FAIL;
528         }
529     } else {
530         check_ints(cdr(list), low+1, up);
531     }
532 }
533 
534 # define UNCOLLECTABLE_CDR(x) (sexpr)(~(GC_word)(cdr(x)))
535 
check_uncollectable_ints(sexpr list,int low,int up)536 void check_uncollectable_ints(sexpr list, int low, int up)
537 {
538     if (SEXPR_TO_INT(car(car(list))) != low) {
539         GC_printf("Uncollectable list corrupted - collector is broken\n");
540         FAIL;
541     }
542     if (low == up) {
543       if (UNCOLLECTABLE_CDR(list) != nil) {
544         GC_printf("Uncollectable list too long - collector is broken\n");
545         FAIL;
546       }
547     } else {
548         check_uncollectable_ints(UNCOLLECTABLE_CDR(list), low+1, up);
549     }
550 }
551 
552 /* Not used, but useful for debugging: */
print_int_list(sexpr x)553 void print_int_list(sexpr x)
554 {
555     if (is_nil(x)) {
556         GC_printf("NIL\n");
557     } else {
558         GC_printf("(%d)", SEXPR_TO_INT(car(car(x))));
559         if (!is_nil(cdr(x))) {
560             GC_printf(", ");
561             print_int_list(cdr(x));
562         } else {
563             GC_printf("\n");
564         }
565     }
566 }
567 
568 /* ditto: */
check_marks_int_list(sexpr x)569 void check_marks_int_list(sexpr x)
570 {
571     if (!GC_is_marked(x))
572         GC_printf("[unm:%p]", (void *)x);
573     else
574         GC_printf("[mkd:%p]", (void *)x);
575     if (is_nil(x)) {
576         GC_printf("NIL\n");
577     } else {
578         if (!GC_is_marked(car(x)))
579           GC_printf("[unm car:%p]", (void *)car(x));
580         GC_printf("(%d)", SEXPR_TO_INT(car(car(x))));
581         if (!is_nil(cdr(x))) {
582             GC_printf(", ");
583             check_marks_int_list(cdr(x));
584         } else {
585             GC_printf("\n");
586         }
587     }
588 }
589 
590 /*
591  * A tiny list reversal test to check thread creation.
592  */
593 #ifdef THREADS
594 
595 # ifdef VERY_SMALL_CONFIG
596 #   define TINY_REVERSE_UPPER_VALUE 4
597 # else
598 #   define TINY_REVERSE_UPPER_VALUE 10
599 # endif
600 
601 # if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
tiny_reverse_test(void * arg GC_ATTR_UNUSED)602     DWORD  __stdcall tiny_reverse_test(void * arg GC_ATTR_UNUSED)
603 # else
604     void * tiny_reverse_test(void * arg GC_ATTR_UNUSED)
605 # endif
606 {
607     int i;
608     for (i = 0; i < 5; ++i) {
609       check_ints(reverse(reverse(ints(1, TINY_REVERSE_UPPER_VALUE))),
610                  1, TINY_REVERSE_UPPER_VALUE);
611     }
612 #   if defined(GC_ENABLE_SUSPEND_THREAD)
613       /* Force collection from a thread. */
614       GC_gcollect();
615 #   endif
616     return 0;
617 }
618 
619 # if defined(GC_PTHREADS)
620 #   if defined(GC_ENABLE_SUSPEND_THREAD)
621 #     include "javaxfc.h"
622 #   endif
623 
fork_a_thread(void)624     void fork_a_thread(void)
625     {
626       pthread_t t;
627       int code;
628 
629       code = pthread_create(&t, NULL, tiny_reverse_test, 0);
630       if (code != 0) {
631         GC_printf("Small thread creation failed %d\n", code);
632         FAIL;
633       }
634 #     if defined(GC_ENABLE_SUSPEND_THREAD) && !defined(GC_DARWIN_THREADS) \
635          && !defined(GC_OPENBSD_UTHREADS) && !defined(GC_WIN32_THREADS) \
636          && !defined(NACL) && !defined(GC_OSF1_THREADS)
637         if (GC_is_thread_suspended(t)) {
638           GC_printf("Running thread should be not suspended\n");
639           FAIL;
640         }
641         /* Thread could be running or already terminated (but not joined). */
642         GC_suspend_thread(t);
643         if (!GC_is_thread_suspended(t)) {
644           GC_printf("Thread expected to be suspended\n");
645           FAIL;
646         }
647         GC_suspend_thread(t); /* should be no-op */
648         GC_resume_thread(t);
649         if (GC_is_thread_suspended(t)) {
650           GC_printf("Resumed thread should be not suspended\n");
651           FAIL;
652         }
653         GC_resume_thread(t); /* should be no-op */
654 #     endif
655       if ((code = pthread_join(t, 0)) != 0) {
656         GC_printf("Small thread join failed %d\n", code);
657         FAIL;
658       }
659     }
660 
661 # elif defined(GC_WIN32_THREADS)
fork_a_thread(void)662     void fork_a_thread(void)
663     {
664         DWORD thread_id;
665         HANDLE h;
666         h = GC_CreateThread((SECURITY_ATTRIBUTES *)NULL, (word)0,
667                             tiny_reverse_test, NULL, (DWORD)0, &thread_id);
668                                 /* Explicitly specify types of the      */
669                                 /* arguments to test the prototype.     */
670         if (h == (HANDLE)NULL) {
671             GC_printf("Small thread creation failed %d\n",
672                           (int)GetLastError());
673             FAIL;
674         }
675         if (WaitForSingleObject(h, INFINITE) != WAIT_OBJECT_0) {
676             GC_printf("Small thread wait failed %d\n",
677                           (int)GetLastError());
678             FAIL;
679         }
680     }
681 
682 # endif
683 
684 #endif
685 
test_generic_malloc_or_special(void * p)686 void test_generic_malloc_or_special(void *p) {
687   size_t size;
688   int kind = GC_get_kind_and_size(p, &size);
689   void *p2;
690 
691   if (size != GC_size(p)) {
692     GC_printf("GC_get_kind_and_size returned size not matching GC_size\n");
693     FAIL;
694   }
695   p2 = GC_GENERIC_OR_SPECIAL_MALLOC(10, kind);
696   CHECK_OUT_OF_MEMORY(p2);
697   if (GC_get_kind_and_size(p2, NULL) != kind) {
698     GC_printf("GC_generic_or_special_malloc:"
699               " unexpected kind of returned object\n");
700     FAIL;
701   }
702   GC_FREE(p2);
703 }
704 
705 /* Try to force a to be strangely aligned */
706 volatile struct A_s {
707   char dummy;
708   AO_t aa;
709 } A;
710 #define a_set(p) AO_store_release(&A.aa, (AO_t)(p))
711 #define a_get() (sexpr)AO_load_acquire(&A.aa)
712 
713 /*
714  * Repeatedly reverse lists built out of very different sized cons cells.
715  * Check that we didn't lose anything.
716  */
reverse_test_inner(void * data)717 void *GC_CALLBACK reverse_test_inner(void *data)
718 {
719     int i;
720     sexpr b;
721     sexpr c;
722     sexpr d;
723     sexpr e;
724     sexpr *f, *g, *h;
725 
726     if (data == 0) {
727       /* This stack frame is not guaranteed to be scanned. */
728       return GC_call_with_gc_active(reverse_test_inner, (void*)(word)1);
729     }
730 
731 #   if defined(MACOS) \
732        || (defined(UNIX_LIKE) && defined(NO_GETCONTEXT)) /* e.g. musl */
733       /* Assume 128K stacks at least. */
734 #     define BIG 1000
735 #   elif defined(PCR)
736       /* PCR default stack is 100K.  Stack frames are up to 120 bytes. */
737 #     define BIG 700
738 #   elif defined(MSWINCE) || defined(RTEMS)
739       /* WinCE only allows 64K stacks */
740 #     define BIG 500
741 #   elif defined(OSF1)
742       /* OSF has limited stack space by default, and large frames. */
743 #     define BIG 200
744 #   elif defined(__MACH__) && defined(__ppc64__)
745 #     define BIG 2500
746 #   else
747 #     define BIG 4500
748 #   endif
749 
750     a_set(ints(1, 49));
751     b = ints(1, 50);
752     c = ints(1, BIG);
753     d = uncollectable_ints(1, 100);
754     test_generic_malloc_or_special(d);
755     e = uncollectable_ints(1, 1);
756     /* Check that realloc updates object descriptors correctly */
757     AO_fetch_and_add1(&collectable_count);
758     f = (sexpr *)GC_MALLOC(4 * sizeof(sexpr));
759     f = (sexpr *)GC_REALLOC((void *)f, 6 * sizeof(sexpr));
760     CHECK_OUT_OF_MEMORY(f);
761     AO_fetch_and_add1(&realloc_count);
762     GC_PTR_STORE_AND_DIRTY(f + 5, ints(1, 17));
763     AO_fetch_and_add1(&collectable_count);
764     g = (sexpr *)GC_MALLOC(513 * sizeof(sexpr));
765     test_generic_malloc_or_special(g);
766     g = (sexpr *)GC_REALLOC((void *)g, 800 * sizeof(sexpr));
767     CHECK_OUT_OF_MEMORY(g);
768     AO_fetch_and_add1(&realloc_count);
769     GC_PTR_STORE_AND_DIRTY(g + 799, ints(1, 18));
770     AO_fetch_and_add1(&collectable_count);
771     h = (sexpr *)GC_MALLOC(1025 * sizeof(sexpr));
772     h = (sexpr *)GC_REALLOC((void *)h, 2000 * sizeof(sexpr));
773     CHECK_OUT_OF_MEMORY(h);
774     AO_fetch_and_add1(&realloc_count);
775 #   ifdef GC_GCJ_SUPPORT
776       GC_PTR_STORE_AND_DIRTY(h + 1999, gcj_ints(1, 200));
777       for (i = 0; i < 51; ++i) {
778         GC_PTR_STORE_AND_DIRTY(h + 1999, gcj_reverse(h[1999]));
779       }
780       /* Leave it as the reversed list for now. */
781 #   else
782       GC_PTR_STORE_AND_DIRTY(h + 1999, ints(1, 200));
783 #   endif
784     /* Try to force some collections and reuse of small list elements */
785     for (i = 0; i < 10; i++) {
786       (void)ints(1, BIG);
787     }
788     /* Superficially test interior pointer recognition on stack */
789     c = (sexpr)((char *)c + sizeof(char *));
790     d = (sexpr)((char *)d + sizeof(char *));
791 
792     GC_FREE((void *)e);
793 
794     check_ints(b,1,50);
795     check_ints(a_get(),1,49);
796     for (i = 0; i < 50; i++) {
797         check_ints(b,1,50);
798         b = reverse(reverse(b));
799     }
800     check_ints(b,1,50);
801     check_ints(a_get(),1,49);
802     for (i = 0; i < 60; i++) {
803 #       if (defined(GC_PTHREADS) || defined(GC_WIN32_THREADS)) \
804            && (NTHREADS > 0)
805             if (i % 10 == 0) fork_a_thread();
806 #       endif
807         /* This maintains the invariant that a always points to a list  */
808         /* of 49 integers.  Thus, this is thread safe without locks,    */
809         /* assuming acquire/release barriers in a_get/set() and atomic  */
810         /* pointer assignments (otherwise, e.g., check_ints() may see   */
811         /* an uninitialized object returned by GC_MALLOC).              */
812         a_set(reverse(reverse(a_get())));
813 #       if !defined(AT_END) && !defined(THREADS)
814           /* This is not thread safe, since realloc explicitly deallocates */
815           a_set(GC_REALLOC(a_get(), (i & 1) != 0 ? 500 : 8200));
816           AO_fetch_and_add1(&realloc_count);
817 #       endif
818     }
819     check_ints(a_get(),1,49);
820     check_ints(b,1,50);
821 
822     /* Restore c and d values. */
823     c = (sexpr)((char *)c - sizeof(char *));
824     d = (sexpr)((char *)d - sizeof(char *));
825 
826     check_ints(c,1,BIG);
827     check_uncollectable_ints(d, 1, 100);
828     check_ints(f[5], 1,17);
829     check_ints(g[799], 1,18);
830 #   ifdef GC_GCJ_SUPPORT
831       GC_PTR_STORE_AND_DIRTY(h + 1999, gcj_reverse(h[1999]));
832 #   endif
833     check_ints(h[1999], 1,200);
834 #   ifndef THREADS
835       a_set(NULL);
836 #   endif
837     *(sexpr volatile *)&b = 0;
838     *(sexpr volatile *)&c = 0;
839     return 0;
840 }
841 
reverse_test(void)842 void reverse_test(void)
843 {
844     /* Test GC_do_blocking/GC_call_with_gc_active. */
845     (void)GC_do_blocking(reverse_test_inner, 0);
846 }
847 
848 /*
849  * The rest of this builds balanced binary trees, checks that they don't
850  * disappear, and tests finalization.
851  */
852 typedef struct treenode {
853     int level;
854     struct treenode * lchild;
855     struct treenode * rchild;
856 } tn;
857 
858 int finalizable_count = 0;
859 int finalized_count = 0;
860 int dropped_something = 0;
861 
finalizer(void * obj,void * client_data)862 void GC_CALLBACK finalizer(void * obj, void * client_data)
863 {
864   tn * t = (tn *)obj;
865 
866   FINALIZER_LOCK();
867   if ((int)(GC_word)client_data != t -> level) {
868      GC_printf("Wrong finalization data - collector is broken\n");
869      FAIL;
870   }
871   finalized_count++;
872   t -> level = -1;      /* detect duplicate finalization immediately */
873   FINALIZER_UNLOCK();
874 }
875 
876 # define MAX_FINALIZED ((NTHREADS+1)*4000)
877 
878 # if !defined(MACOS)
879   GC_FAR GC_word live_indicators[MAX_FINALIZED] = {0};
880 # ifndef GC_LONG_REFS_NOT_NEEDED
881     GC_FAR void *live_long_refs[MAX_FINALIZED] = { NULL };
882 # endif
883 #else
884   /* Too big for THINK_C. have to allocate it dynamically. */
885   GC_word *live_indicators = 0;
886 # ifndef GC_LONG_REFS_NOT_NEEDED
887 #   define GC_LONG_REFS_NOT_NEEDED
888 # endif
889 #endif
890 
891 int live_indicators_count = 0;
892 
mktree(int n)893 tn * mktree(int n)
894 {
895     tn * result = GC_NEW(tn);
896     tn * left, * right;
897 
898     AO_fetch_and_add1(&collectable_count);
899 #   if defined(MACOS)
900         /* get around static data limitations. */
901         if (!live_indicators) {
902           live_indicators =
903                     (GC_word*)NewPtrClear(MAX_FINALIZED * sizeof(GC_word));
904           CHECK_OUT_OF_MEMORY(live_indicators);
905         }
906 #   endif
907     if (n == 0) return(0);
908     CHECK_OUT_OF_MEMORY(result);
909     result -> level = n;
910     result -> lchild = left = mktree(n - 1);
911     result -> rchild = right = mktree(n - 1);
912     if (AO_fetch_and_add1(&extra_count) % 17 == 0 && n >= 2) {
913         tn * tmp;
914 
915         CHECK_OUT_OF_MEMORY(left);
916         tmp = left -> rchild;
917         CHECK_OUT_OF_MEMORY(right);
918         GC_PTR_STORE_AND_DIRTY(&left->rchild, right->lchild);
919         GC_PTR_STORE_AND_DIRTY(&right->lchild, tmp);
920     }
921     if (AO_fetch_and_add1(&extra_count) % 119 == 0) {
922 #       ifndef GC_NO_FINALIZATION
923           int my_index;
924           void *new_link;
925 #       endif
926 
927         {
928           FINALIZER_LOCK();
929                 /* Losing a count here causes erroneous report of failure. */
930           finalizable_count++;
931 #         ifndef GC_NO_FINALIZATION
932             my_index = live_indicators_count++;
933 #         endif
934           FINALIZER_UNLOCK();
935         }
936 
937 #   ifndef GC_NO_FINALIZATION
938       if (!GC_get_find_leak()) {
939         GC_REGISTER_FINALIZER((void *)result, finalizer, (void *)(GC_word)n,
940                               (GC_finalization_proc *)0, (void * *)0);
941         if (my_index >= MAX_FINALIZED) {
942                 GC_printf("live_indicators overflowed\n");
943                 FAIL;
944         }
945         live_indicators[my_index] = 13;
946         if (GC_GENERAL_REGISTER_DISAPPEARING_LINK(
947             (void * *)(&(live_indicators[my_index])), result) != 0) {
948                 GC_printf("GC_general_register_disappearing_link failed\n");
949                 FAIL;
950         }
951         if (GC_move_disappearing_link((void **)(&(live_indicators[my_index])),
952                    (void **)(&(live_indicators[my_index]))) != GC_SUCCESS) {
953                 GC_printf("GC_move_disappearing_link(link,link) failed\n");
954                 FAIL;
955         }
956         new_link = (void *)live_indicators[my_index];
957         if (GC_move_disappearing_link((void **)(&(live_indicators[my_index])),
958                                       &new_link) != GC_SUCCESS) {
959                 GC_printf("GC_move_disappearing_link(new_link) failed\n");
960                 FAIL;
961         }
962         if (GC_unregister_disappearing_link(&new_link) == 0) {
963                 GC_printf("GC_unregister_disappearing_link failed\n");
964                 FAIL;
965         }
966         if (GC_move_disappearing_link((void **)(&(live_indicators[my_index])),
967                                       &new_link) != GC_NOT_FOUND) {
968                 GC_printf("GC_move_disappearing_link(new_link) failed 2\n");
969                 FAIL;
970         }
971         if (GC_GENERAL_REGISTER_DISAPPEARING_LINK(
972             (void * *)(&(live_indicators[my_index])), result) != 0) {
973                 GC_printf("GC_general_register_disappearing_link failed 2\n");
974                 FAIL;
975         }
976 #       ifndef GC_LONG_REFS_NOT_NEEDED
977           if (GC_REGISTER_LONG_LINK(&live_long_refs[my_index], result) != 0) {
978             GC_printf("GC_register_long_link failed\n");
979             FAIL;
980           }
981           if (GC_move_long_link(&live_long_refs[my_index],
982                                 &live_long_refs[my_index]) != GC_SUCCESS) {
983             GC_printf("GC_move_long_link(link,link) failed\n");
984             FAIL;
985           }
986           new_link = live_long_refs[my_index];
987           if (GC_move_long_link(&live_long_refs[my_index],
988                                 &new_link) != GC_SUCCESS) {
989             GC_printf("GC_move_long_link(new_link) failed\n");
990             FAIL;
991           }
992           if (GC_unregister_long_link(&new_link) == 0) {
993             GC_printf("GC_unregister_long_link failed\n");
994             FAIL;
995           }
996           if (GC_move_long_link(&live_long_refs[my_index],
997                                 &new_link) != GC_NOT_FOUND) {
998             GC_printf("GC_move_long_link(new_link) failed 2\n");
999             FAIL;
1000           }
1001           if (GC_REGISTER_LONG_LINK(&live_long_refs[my_index], result) != 0) {
1002             GC_printf("GC_register_long_link failed 2\n");
1003             FAIL;
1004           }
1005 #       endif
1006       }
1007 #   endif
1008       GC_reachable_here(result);
1009     }
1010     GC_END_STUBBORN_CHANGE(result);
1011     GC_reachable_here(left);
1012     GC_reachable_here(right);
1013     return(result);
1014 }
1015 
chktree(tn * t,int n)1016 void chktree(tn *t, int n)
1017 {
1018     if (0 == n) {
1019         if (NULL == t) /* is a leaf? */
1020             return;
1021         GC_printf("Clobbered a leaf - collector is broken\n");
1022         FAIL;
1023     }
1024     if (t -> level != n) {
1025         GC_printf("Lost a node at level %d - collector is broken\n", n);
1026         FAIL;
1027     }
1028     if (AO_fetch_and_add1(&extra_count) % 373 == 0) {
1029         (void)GC_MALLOC((unsigned)AO_fetch_and_add1(&extra_count) % 5001);
1030         AO_fetch_and_add1(&collectable_count);
1031     }
1032     chktree(t -> lchild, n-1);
1033     if (AO_fetch_and_add1(&extra_count) % 73 == 0) {
1034         (void)GC_MALLOC((unsigned)AO_fetch_and_add1(&extra_count) % 373);
1035         AO_fetch_and_add1(&collectable_count);
1036     }
1037     chktree(t -> rchild, n-1);
1038 }
1039 
1040 
1041 #if defined(GC_PTHREADS)
1042 pthread_key_t fl_key;
1043 
alloc8bytes(void)1044 void * alloc8bytes(void)
1045 {
1046 # if defined(SMALL_CONFIG) || defined(GC_DEBUG)
1047     AO_fetch_and_add1(&collectable_count);
1048     return(GC_MALLOC(8));
1049 # else
1050     void ** my_free_list_ptr;
1051     void * my_free_list;
1052     void * next;
1053 
1054     my_free_list_ptr = (void **)pthread_getspecific(fl_key);
1055     if (my_free_list_ptr == 0) {
1056         my_free_list_ptr = GC_NEW_UNCOLLECTABLE(void *);
1057         CHECK_OUT_OF_MEMORY(my_free_list_ptr);
1058         AO_fetch_and_add1(&uncollectable_count);
1059         if (pthread_setspecific(fl_key, my_free_list_ptr) != 0) {
1060             GC_printf("pthread_setspecific failed\n");
1061             FAIL;
1062         }
1063     }
1064     my_free_list = *my_free_list_ptr;
1065     if (my_free_list == 0) {
1066         my_free_list = GC_malloc_many(8);
1067         CHECK_OUT_OF_MEMORY(my_free_list);
1068     }
1069     next = GC_NEXT(my_free_list);
1070     GC_PTR_STORE_AND_DIRTY(my_free_list_ptr, next);
1071     GC_NEXT(my_free_list) = 0;
1072     AO_fetch_and_add1(&collectable_count);
1073     return(my_free_list);
1074 # endif
1075 }
1076 
1077 #else
1078 #   define alloc8bytes() GC_MALLOC_ATOMIC(8)
1079 #endif
1080 
1081 #include "gc_inline.h"
1082 
test_tinyfl(void)1083 void test_tinyfl(void)
1084 {
1085   void *results[3];
1086   void *tfls[3][GC_TINY_FREELISTS];
1087 
1088 # ifndef DONT_ADD_BYTE_AT_END
1089     if (GC_get_all_interior_pointers()) return; /* skip */
1090 # endif
1091   BZERO(tfls, sizeof(tfls));
1092   /* TODO: Improve testing of FAST_MALLOC functionality. */
1093   GC_MALLOC_WORDS(results[0], 11, tfls[0]);
1094   GC_MALLOC_ATOMIC_WORDS(results[1], 20, tfls[1]);
1095   GC_CONS(results[2], results[0], results[1], tfls[2]);
1096 }
1097 
alloc_small(int n)1098 void alloc_small(int n)
1099 {
1100     int i;
1101 
1102     for (i = 0; i < n; i += 8) {
1103         if (alloc8bytes() == 0) {
1104             GC_printf("Out of memory\n");
1105             FAIL;
1106         }
1107         AO_fetch_and_add1(&atomic_count);
1108     }
1109 }
1110 
1111 # if defined(THREADS) && defined(GC_DEBUG)
1112 #   ifdef VERY_SMALL_CONFIG
1113 #     define TREE_HEIGHT 12
1114 #   else
1115 #     define TREE_HEIGHT 15
1116 #   endif
1117 # else
1118 #   ifdef VERY_SMALL_CONFIG
1119 #     define TREE_HEIGHT 13
1120 #   else
1121 #     define TREE_HEIGHT 16
1122 #   endif
1123 # endif
tree_test(void)1124 void tree_test(void)
1125 {
1126     tn * root;
1127     int i;
1128 
1129     root = mktree(TREE_HEIGHT);
1130 #   ifndef VERY_SMALL_CONFIG
1131       alloc_small(5000000);
1132 #   endif
1133     chktree(root, TREE_HEIGHT);
1134     FINALIZER_LOCK();
1135     if (finalized_count && !dropped_something) {
1136         GC_printf("Premature finalization - collector is broken\n");
1137         FAIL;
1138     }
1139     dropped_something = 1;
1140     FINALIZER_UNLOCK();
1141     GC_reachable_here(root);    /* Root needs to remain live until      */
1142                                 /* dropped_something is set.            */
1143     root = mktree(TREE_HEIGHT);
1144     chktree(root, TREE_HEIGHT);
1145     for (i = TREE_HEIGHT; i >= 0; i--) {
1146         root = mktree(i);
1147         chktree(root, i);
1148     }
1149 #   ifndef VERY_SMALL_CONFIG
1150       alloc_small(5000000);
1151 #   endif
1152 }
1153 
1154 unsigned n_tests = 0;
1155 
1156 #ifndef NO_TYPED_TEST
1157 const GC_word bm_huge[320 / CPP_WORDSZ] = {
1158 # if CPP_WORDSZ == 32
1159     0xffffffff,
1160     0xffffffff,
1161     0xffffffff,
1162     0xffffffff,
1163     0xffffffff,
1164 # endif
1165     (GC_word)((GC_signed_word)-1),
1166     (GC_word)((GC_signed_word)-1),
1167     (GC_word)((GC_signed_word)-1),
1168     (GC_word)((GC_signed_word)-1),
1169     ((GC_word)((GC_signed_word)-1)) >> 8 /* highest byte is zero */
1170 };
1171 
1172 /* A very simple test of explicitly typed allocation    */
typed_test(void)1173 void typed_test(void)
1174 {
1175     GC_word * old, * newP;
1176     GC_word bm3[1] = {0};
1177     GC_word bm2[1] = {0};
1178     GC_word bm_large[1] = { 0xf7ff7fff };
1179     GC_descr d1;
1180     GC_descr d2;
1181     GC_descr d3 = GC_make_descriptor(bm_large, 32);
1182     GC_descr d4 = GC_make_descriptor(bm_huge, 320);
1183     GC_word * x = (GC_word *)GC_malloc_explicitly_typed(
1184                                 320 * sizeof(GC_word) + 123, d4);
1185     int i;
1186 
1187     AO_fetch_and_add1(&collectable_count);
1188     (void)GC_make_descriptor(bm_large, 32);
1189     if (GC_get_bit(bm_huge, 32) == 0 || GC_get_bit(bm_huge, 311) == 0
1190         || GC_get_bit(bm_huge, 319) != 0) {
1191       GC_printf("Bad GC_get_bit() or bm_huge initialization\n");
1192       FAIL;
1193     }
1194     GC_set_bit(bm3, 0);
1195     GC_set_bit(bm3, 1);
1196     d1 = GC_make_descriptor(bm3, 2);
1197     GC_set_bit(bm2, 1);
1198     d2 = GC_make_descriptor(bm2, 2);
1199     old = 0;
1200     for (i = 0; i < 4000; i++) {
1201         newP = (GC_word *)GC_malloc_explicitly_typed(4 * sizeof(GC_word), d1);
1202         CHECK_OUT_OF_MEMORY(newP);
1203         AO_fetch_and_add1(&collectable_count);
1204         if (newP[0] != 0 || newP[1] != 0) {
1205             GC_printf("Bad initialization by GC_malloc_explicitly_typed\n");
1206             FAIL;
1207         }
1208         newP[0] = 17;
1209         GC_PTR_STORE_AND_DIRTY(newP + 1, old);
1210         old = newP;
1211         AO_fetch_and_add1(&collectable_count);
1212         newP = (GC_word *)GC_malloc_explicitly_typed(4 * sizeof(GC_word), d2);
1213         CHECK_OUT_OF_MEMORY(newP);
1214         newP[0] = 17;
1215         GC_PTR_STORE_AND_DIRTY(newP + 1, old);
1216         old = newP;
1217         AO_fetch_and_add1(&collectable_count);
1218         newP = (GC_word*)GC_malloc_explicitly_typed(33 * sizeof(GC_word), d3);
1219         CHECK_OUT_OF_MEMORY(newP);
1220         newP[0] = 17;
1221         GC_PTR_STORE_AND_DIRTY(newP + 1, old);
1222         old = newP;
1223         AO_fetch_and_add1(&collectable_count);
1224         newP = (GC_word *)GC_calloc_explicitly_typed(4, 2 * sizeof(GC_word),
1225                                                      d1);
1226         CHECK_OUT_OF_MEMORY(newP);
1227         newP[0] = 17;
1228         GC_PTR_STORE_AND_DIRTY(newP + 1, old);
1229         old = newP;
1230         AO_fetch_and_add1(&collectable_count);
1231         if (i & 0xff) {
1232           newP = (GC_word *)GC_calloc_explicitly_typed(7, 3 * sizeof(GC_word),
1233                                                        d2);
1234         } else {
1235           newP = (GC_word *)GC_calloc_explicitly_typed(1001,
1236                                                        3 * sizeof(GC_word),
1237                                                        d2);
1238           if (newP != NULL && (newP[0] != 0 || newP[1] != 0)) {
1239             GC_printf("Bad initialization by GC_malloc_explicitly_typed\n");
1240             FAIL;
1241           }
1242         }
1243         CHECK_OUT_OF_MEMORY(newP);
1244         newP[0] = 17;
1245         GC_PTR_STORE_AND_DIRTY(newP + 1, old);
1246         old = newP;
1247     }
1248     for (i = 0; i < 20000; i++) {
1249         if (newP[0] != 17) {
1250             GC_printf("Typed alloc failed at %d\n", i);
1251             FAIL;
1252         }
1253         newP[0] = 0;
1254         old = newP;
1255         newP = (GC_word *)old[1];
1256     }
1257     GC_gcollect();
1258     GC_noop1((word)x);
1259 }
1260 #endif /* !NO_TYPED_TEST */
1261 
1262 #ifdef DBG_HDRS_ALL
1263 # define set_print_procs() (void)(A.dummy = 17)
1264 #else
1265   int fail_count = 0;
1266 
fail_proc1(void * x GC_ATTR_UNUSED)1267   void GC_CALLBACK fail_proc1(void *x GC_ATTR_UNUSED)
1268   {
1269     fail_count++;
1270   }
1271 
set_print_procs(void)1272   void set_print_procs(void)
1273   {
1274     /* Set these global variables just once to avoid TSan false positives. */
1275     A.dummy = 17;
1276     GC_is_valid_displacement_print_proc = fail_proc1;
1277     GC_is_visible_print_proc = fail_proc1;
1278   }
1279 
1280 # ifdef THREADS
1281 #   define TEST_FAIL_COUNT(n) 1
1282 # else
1283 #   define TEST_FAIL_COUNT(n) (fail_count >= (n))
1284 # endif
1285 #endif /* !DBG_HDRS_ALL */
1286 
uniq(void * p,...)1287 static void uniq(void *p, ...) {
1288   va_list a;
1289   void *q[100];
1290   int n = 0, i, j;
1291   q[n++] = p;
1292   va_start(a,p);
1293   for (;(q[n] = va_arg(a,void *)) != NULL;n++) ;
1294   va_end(a);
1295   for (i=0; i<n; i++)
1296     for (j=0; j<i; j++)
1297       if (q[i] == q[j]) {
1298         GC_printf(
1299               "Apparently failed to mark from some function arguments.\n"
1300               "Perhaps GC_push_regs was configured incorrectly?\n"
1301         );
1302         FAIL;
1303       }
1304 }
1305 
inc_int_counter(void * pcounter)1306 void * GC_CALLBACK inc_int_counter(void *pcounter)
1307 {
1308  ++(*(int *)pcounter);
1309  return NULL;
1310 }
1311 
1312 #ifndef MIN_WORDS
1313 # define MIN_WORDS 2
1314 #endif
1315 
run_one_test(void)1316 void run_one_test(void)
1317 {
1318 #   ifndef DBG_HDRS_ALL
1319         char *x;
1320         char **z;
1321         char *y = (char *)(GC_word)fail_proc1;
1322 #   endif
1323 #   ifndef NO_CLOCK
1324       CLOCK_TYPE start_time;
1325       CLOCK_TYPE reverse_time;
1326       unsigned long time_diff;
1327 #   endif
1328 #   ifndef NO_TEST_HANDLE_FORK
1329       pid_t pid;
1330       int wstatus;
1331 #   endif
1332 
1333     GC_FREE(0);
1334 #   ifdef THREADS
1335       if (!GC_thread_is_registered() && GC_is_init_called()) {
1336         GC_printf("Current thread is not registered with GC\n");
1337         FAIL;
1338       }
1339 #   endif
1340     test_tinyfl();
1341 #   ifndef DBG_HDRS_ALL
1342       AO_fetch_and_add1(&collectable_count); /* 1 */
1343       AO_fetch_and_add1(&collectable_count); /* 2 */
1344       AO_fetch_and_add1(&collectable_count); /* 3 */
1345       if ((GC_size(GC_malloc(7)) != 8 &&
1346            GC_size(GC_malloc(7)) != MIN_WORDS * sizeof(GC_word))
1347            || GC_size(GC_malloc(15)) != 16) {
1348         GC_printf("GC_size produced unexpected results\n");
1349         FAIL;
1350       }
1351       AO_fetch_and_add1(&collectable_count);
1352       if (GC_size(GC_malloc(0)) != MIN_WORDS * sizeof(GC_word)) {
1353         GC_printf("GC_malloc(0) failed: GC_size returns %lu\n",
1354                       (unsigned long)GC_size(GC_malloc(0)));
1355         FAIL;
1356       }
1357       AO_fetch_and_add1(&uncollectable_count);
1358       if (GC_size(GC_malloc_uncollectable(0)) != MIN_WORDS * sizeof(GC_word)) {
1359         GC_printf("GC_malloc_uncollectable(0) failed\n");
1360         FAIL;
1361       }
1362       AO_fetch_and_add1(&collectable_count);
1363       x = (char*)GC_malloc(16);
1364       if (GC_base(GC_PTR_ADD(x, 13)) != x) {
1365         GC_printf("GC_base(heap ptr) produced incorrect result\n");
1366         FAIL;
1367       }
1368       if (!GC_is_heap_ptr(x)) {
1369         GC_printf("GC_is_heap_ptr(heap_ptr) produced incorrect result\n");
1370         FAIL;
1371       }
1372       if (GC_is_heap_ptr(&x)) {
1373         GC_printf("GC_is_heap_ptr(&local_var) produced incorrect result\n");
1374         FAIL;
1375       }
1376       if (GC_is_heap_ptr(&fail_count) || GC_is_heap_ptr(NULL)) {
1377         GC_printf("GC_is_heap_ptr(&global_var) produced incorrect result\n");
1378         FAIL;
1379       }
1380       (void)GC_PRE_INCR(x, 0);
1381       (void)GC_POST_INCR(x);
1382       (void)GC_POST_DECR(x);
1383       if (GC_base(x) != x) {
1384         GC_printf("Bad INCR/DECR result\n");
1385         FAIL;
1386       }
1387 #     ifndef PCR
1388         if (GC_base(y) != 0) {
1389           GC_printf("GC_base(fn_ptr) produced incorrect result\n");
1390           FAIL;
1391         }
1392 #     endif
1393       if (GC_same_obj(x+5, x) != x + 5) {
1394         GC_printf("GC_same_obj produced incorrect result\n");
1395         FAIL;
1396       }
1397       if (GC_is_visible(y) != y || GC_is_visible(x) != x) {
1398         GC_printf("GC_is_visible produced incorrect result\n");
1399         FAIL;
1400       }
1401       z = (char**)GC_malloc(8);
1402       CHECK_OUT_OF_MEMORY(z);
1403       AO_fetch_and_add1(&collectable_count);
1404       GC_PTR_STORE(z, x);
1405       GC_end_stubborn_change(z);
1406       if (*z != x) {
1407         GC_printf("GC_PTR_STORE failed: %p != %p\n", (void *)(*z), (void *)x);
1408         FAIL;
1409       }
1410       if (!TEST_FAIL_COUNT(1)) {
1411 #       if!(defined(POWERPC) || defined(IA64)) || defined(M68K)
1412           /* On POWERPCs function pointers point to a descriptor in the */
1413           /* data segment, so there should have been no failures.       */
1414           /* The same applies to IA64.  Something similar seems to      */
1415           /* be going on with NetBSD/M68K.                              */
1416           GC_printf("GC_is_visible produced wrong failure indication\n");
1417           FAIL;
1418 #       endif
1419       }
1420       if (GC_is_valid_displacement(y) != y
1421         || GC_is_valid_displacement(x) != x
1422         || GC_is_valid_displacement(x + 3) != x + 3) {
1423         GC_printf("GC_is_valid_displacement produced incorrect result\n");
1424         FAIL;
1425       }
1426         {
1427           size_t i;
1428 
1429           (void)GC_malloc(17);
1430           AO_fetch_and_add1(&collectable_count);
1431           for (i = sizeof(GC_word); i < 512; i *= 2) {
1432             GC_word result = (GC_word) GC_memalign(i, 17);
1433             if (result % i != 0 || result == 0 || *(int *)result != 0) FAIL;
1434           }
1435         }
1436 #     ifndef ALL_INTERIOR_POINTERS
1437 #      if defined(RS6000) || defined(POWERPC)
1438         if (!TEST_FAIL_COUNT(1))
1439 #      else
1440         if (!TEST_FAIL_COUNT(GC_get_all_interior_pointers() ? 1 : 2))
1441 #      endif
1442         {
1443           GC_printf(
1444               "GC_is_valid_displacement produced wrong failure indication\n");
1445           FAIL;
1446         }
1447 #     endif
1448 #   endif /* DBG_HDRS_ALL */
1449     /* Test floating point alignment */
1450         {
1451           double *dp = GC_NEW(double);
1452           CHECK_OUT_OF_MEMORY(dp);
1453           AO_fetch_and_add1(&collectable_count);
1454           *dp = 1.0;
1455           dp = GC_NEW(double);
1456           CHECK_OUT_OF_MEMORY(dp);
1457           AO_fetch_and_add1(&collectable_count);
1458           *dp = 1.0;
1459         }
1460     /* Test size 0 allocation a bit more */
1461         {
1462            size_t i;
1463            for (i = 0; i < 10000; ++i) {
1464              (void)GC_MALLOC(0);
1465              AO_fetch_and_add1(&collectable_count);
1466              GC_FREE(GC_MALLOC(0));
1467              (void)GC_MALLOC_ATOMIC(0);
1468              AO_fetch_and_add1(&atomic_count);
1469              GC_FREE(GC_MALLOC_ATOMIC(0));
1470              test_generic_malloc_or_special(GC_malloc_atomic(1));
1471              AO_fetch_and_add1(&atomic_count);
1472              GC_FREE(GC_MALLOC_ATOMIC_IGNORE_OFF_PAGE(1));
1473              GC_FREE(GC_MALLOC_IGNORE_OFF_PAGE(2));
1474            }
1475          }
1476 #   ifdef GC_GCJ_SUPPORT
1477       GC_REGISTER_DISPLACEMENT(sizeof(struct fake_vtable *));
1478       GC_init_gcj_malloc(0, (void *)(GC_word)fake_gcj_mark_proc);
1479 #   endif
1480     /* Make sure that fn arguments are visible to the collector.        */
1481       uniq(
1482         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1483         (GC_gcollect(),GC_malloc(12)),
1484         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1485         (GC_gcollect(),GC_malloc(12)),
1486         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1487         (GC_gcollect(),GC_malloc(12)),
1488         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1489         (GC_gcollect(),GC_malloc(12)),
1490         GC_malloc(12), GC_malloc(12), GC_malloc(12),
1491         (GC_gcollect(),GC_malloc(12)),
1492         (void *)0);
1493     /* GC_malloc(0) must return NULL or something we can deallocate. */
1494         GC_free(GC_malloc(0));
1495         GC_free(GC_malloc_atomic(0));
1496         GC_free(GC_malloc(0));
1497         GC_free(GC_malloc_atomic(0));
1498 #   ifndef NO_TEST_HANDLE_FORK
1499         GC_atfork_prepare();
1500         pid = fork();
1501         if (pid != 0) {
1502           GC_atfork_parent();
1503           if (pid == -1) {
1504             GC_printf("Process fork failed\n");
1505             FAIL;
1506           }
1507           if (print_stats)
1508             GC_log_printf("Forked child process\n");
1509           if (waitpid(pid, &wstatus, 0) == -1) {
1510             GC_printf("Wait for child process failed\n");
1511             FAIL;
1512           }
1513           if (!WIFEXITED(wstatus) || WEXITSTATUS(wstatus) != 0) {
1514             GC_printf("Child process failed, status= 0x%x\n", wstatus);
1515             FAIL;
1516           }
1517         } else {
1518           GC_atfork_child();
1519           if (print_stats)
1520             GC_log_printf("Started a child process\n");
1521 #         ifdef THREADS
1522 #           ifdef PARALLEL_MARK
1523               GC_gcollect(); /* no parallel markers */
1524 #           endif
1525             GC_start_mark_threads();
1526 #         endif
1527           GC_gcollect();
1528 #         ifdef THREADS
1529             tiny_reverse_test(0);
1530             GC_gcollect();
1531 #         endif
1532           if (print_stats)
1533             GC_log_printf("Finished a child process\n");
1534           exit(0);
1535         }
1536 #   endif
1537     /* Repeated list reversal test. */
1538 #   ifndef NO_CLOCK
1539         GET_TIME(start_time);
1540 #   endif
1541         reverse_test();
1542 #   ifndef NO_CLOCK
1543         if (print_stats) {
1544           GET_TIME(reverse_time);
1545           time_diff = MS_TIME_DIFF(reverse_time, start_time);
1546           GC_log_printf("-------------Finished reverse_test at time %u (%p)\n",
1547                         (unsigned) time_diff, (void *)&start_time);
1548         }
1549 #   endif
1550 #   if !defined(DBG_HDRS_ALL) && !defined(NO_TYPED_TEST)
1551       typed_test();
1552 #     ifndef NO_CLOCK
1553         if (print_stats) {
1554           CLOCK_TYPE typed_time;
1555 
1556           GET_TIME(typed_time);
1557           time_diff = MS_TIME_DIFF(typed_time, start_time);
1558           GC_log_printf("-------------Finished typed_test at time %u (%p)\n",
1559                         (unsigned) time_diff, (void *)&start_time);
1560         }
1561 #     endif
1562 #   endif /* DBG_HDRS_ALL */
1563     tree_test();
1564 #   ifdef TEST_WITH_SYSTEM_MALLOC
1565       free(calloc(1,1));
1566       free(realloc(NULL, 64));
1567 #   endif
1568 #   ifndef NO_CLOCK
1569       if (print_stats) {
1570         CLOCK_TYPE tree_time;
1571 
1572         GET_TIME(tree_time);
1573         time_diff = MS_TIME_DIFF(tree_time, start_time);
1574         GC_log_printf("-------------Finished tree_test at time %u (%p)\n",
1575                       (unsigned) time_diff, (void *)&start_time);
1576       }
1577 #   endif
1578     /* Run reverse_test a second time, so we hopefully notice corruption. */
1579     reverse_test();
1580 #   ifndef NO_CLOCK
1581       if (print_stats) {
1582         GET_TIME(reverse_time);
1583         time_diff = MS_TIME_DIFF(reverse_time, start_time);
1584         GC_log_printf(
1585                 "-------------Finished second reverse_test at time %u (%p)\n",
1586                 (unsigned)time_diff, (void *)&start_time);
1587       }
1588 #   endif
1589     /* GC_allocate_ml and GC_need_to_lock are no longer exported, and   */
1590     /* AO_fetch_and_add1() may be unavailable to update a counter.      */
1591     (void)GC_call_with_alloc_lock(inc_int_counter, &n_tests);
1592 #   ifndef NO_CLOCK
1593       if (print_stats)
1594         GC_log_printf("Finished %p\n", (void *)&start_time);
1595 #   endif
1596 }
1597 
1598 /* Execute some tests after termination of other test threads (if any). */
run_single_threaded_test(void)1599 void run_single_threaded_test(void) {
1600     GC_disable();
1601     GC_FREE(GC_MALLOC(100));
1602     GC_enable();
1603 }
1604 
reachable_objs_counter(void * obj,size_t size,void * pcounter)1605 void GC_CALLBACK reachable_objs_counter(void *obj, size_t size,
1606                                         void *pcounter)
1607 {
1608   if (0 == size) {
1609     GC_printf("Reachable object has zero size\n");
1610     FAIL;
1611   }
1612   if (GC_base(obj) != obj) {
1613     GC_printf("Invalid reachable object base passed by enumerator: %p\n",
1614               obj);
1615     FAIL;
1616   }
1617   if (GC_size(obj) != size) {
1618     GC_printf("Invalid reachable object size passed by enumerator: %lu\n",
1619               (unsigned long)size);
1620     FAIL;
1621   }
1622   (*(unsigned *)pcounter)++;
1623 }
1624 
reachable_objs_count_enumerator(void * pcounter)1625 void * GC_CALLBACK reachable_objs_count_enumerator(void *pcounter)
1626 {
1627   GC_enumerate_reachable_objects_inner(reachable_objs_counter, pcounter);
1628   return NULL;
1629 }
1630 
1631 #define NUMBER_ROUND_UP(v, bound) ((((v) + (bound) - 1) / (bound)) * (bound))
1632 
check_heap_stats(void)1633 void check_heap_stats(void)
1634 {
1635     size_t max_heap_sz;
1636     int i;
1637 #   ifndef GC_NO_FINALIZATION
1638 #     ifdef FINALIZE_ON_DEMAND
1639         int late_finalize_count = 0;
1640 #     endif
1641 #   endif
1642     unsigned obj_count = 0;
1643 
1644     if (!GC_is_init_called()) {
1645       GC_printf("GC should be initialized!\n");
1646       FAIL;
1647     }
1648 #   ifdef VERY_SMALL_CONFIG
1649     /* The upper bounds are a guess, which has been empirically */
1650     /* adjusted.  On low end uniprocessors with incremental GC  */
1651     /* these may be particularly dubious, since empirically the */
1652     /* heap tends to grow largely as a result of the GC not     */
1653     /* getting enough cycles.                                   */
1654 #     if CPP_WORDSZ == 64
1655         max_heap_sz = 4500000;
1656 #     else
1657         max_heap_sz = 2800000;
1658 #     endif
1659 #   else
1660 #     if CPP_WORDSZ == 64
1661         max_heap_sz = 25000000;
1662 #     else
1663         max_heap_sz = 16000000;
1664 #     endif
1665 #   endif
1666 #   ifdef GC_DEBUG
1667         max_heap_sz *= 2;
1668 #       ifdef SAVE_CALL_CHAIN
1669             max_heap_sz *= 3;
1670 #           ifdef SAVE_CALL_COUNT
1671                 max_heap_sz += max_heap_sz * NFRAMES / 4;
1672 #           endif
1673 #       endif
1674 #   endif
1675 #   if defined(ADDRESS_SANITIZER) && !defined(__clang__)
1676         max_heap_sz = max_heap_sz * 2 - max_heap_sz / 3;
1677 #   endif
1678 #   ifdef MEMORY_SANITIZER
1679         max_heap_sz += max_heap_sz / 4;
1680 #   endif
1681     max_heap_sz *= n_tests;
1682 #   if defined(USE_MMAP) || defined(MSWIN32)
1683       max_heap_sz = NUMBER_ROUND_UP(max_heap_sz, 4 * 1024 * 1024);
1684 #   endif
1685     /* Garbage collect repeatedly so that all inaccessible objects      */
1686     /* can be finalized.                                                */
1687       while (GC_collect_a_little()) { }
1688       for (i = 0; i < 16; i++) {
1689         GC_gcollect();
1690 #       ifndef GC_NO_FINALIZATION
1691 #         ifdef FINALIZE_ON_DEMAND
1692             late_finalize_count +=
1693 #         endif
1694                 GC_invoke_finalizers();
1695 #       endif
1696       }
1697       if (print_stats) {
1698         struct GC_stack_base sb;
1699         int res = GC_get_stack_base(&sb);
1700 
1701         if (res == GC_SUCCESS) {
1702           GC_log_printf("Primordial thread stack bottom: %p\n", sb.mem_base);
1703         } else if (res == GC_UNIMPLEMENTED) {
1704           GC_log_printf("GC_get_stack_base() unimplemented\n");
1705         } else {
1706           GC_printf("GC_get_stack_base() failed: %d\n", res);
1707           FAIL;
1708         }
1709       }
1710     (void)GC_call_with_alloc_lock(reachable_objs_count_enumerator,
1711                                   &obj_count);
1712     GC_printf("Completed %u tests\n", n_tests);
1713     GC_printf("Allocated %d collectable objects\n", (int)collectable_count);
1714     GC_printf("Allocated %d uncollectable objects\n",
1715                   (int)uncollectable_count);
1716     GC_printf("Allocated %d atomic objects\n", (int)atomic_count);
1717     GC_printf("Reallocated %d objects\n", (int)realloc_count);
1718     GC_printf("Finalized %d/%d objects - ",
1719                   finalized_count, finalizable_count);
1720 # ifndef GC_NO_FINALIZATION
1721     if (!GC_get_find_leak()) {
1722       int still_live = 0;
1723 #     ifndef GC_LONG_REFS_NOT_NEEDED
1724         int still_long_live = 0;
1725 #     endif
1726 
1727 #     ifdef FINALIZE_ON_DEMAND
1728         if (finalized_count != late_finalize_count) {
1729             GC_printf("Demand finalization error\n");
1730             FAIL;
1731         }
1732 #     endif
1733       if (finalized_count > finalizable_count
1734           || finalized_count < finalizable_count/2) {
1735         GC_printf("finalization is probably broken\n");
1736         FAIL;
1737       } else {
1738         GC_printf("finalization is probably ok\n");
1739       }
1740       for (i = 0; i < MAX_FINALIZED; i++) {
1741         if (live_indicators[i] != 0) {
1742             still_live++;
1743         }
1744 #       ifndef GC_LONG_REFS_NOT_NEEDED
1745           if (live_long_refs[i] != NULL) {
1746               still_long_live++;
1747           }
1748 #       endif
1749       }
1750       i = finalizable_count - finalized_count - still_live;
1751       if (0 != i) {
1752         GC_printf("%d disappearing links remain and %d more objects "
1753                       "were not finalized\n", still_live, i);
1754         if (i > 10) {
1755             GC_printf("\tVery suspicious!\n");
1756         } else {
1757             GC_printf("\tSlightly suspicious, but probably OK\n");
1758         }
1759       }
1760 #     ifndef GC_LONG_REFS_NOT_NEEDED
1761         if (0 != still_long_live) {
1762           GC_printf("%d 'long' links remain\n", still_long_live);
1763         }
1764 #     endif
1765     }
1766 # endif
1767     GC_printf("Total number of bytes allocated is %lu\n",
1768                   (unsigned long)GC_get_total_bytes());
1769     GC_printf("Total memory use by allocated blocks is %lu bytes\n",
1770               (unsigned long)GC_get_memory_use());
1771     GC_printf("Final heap size is %lu bytes\n",
1772                   (unsigned long)GC_get_heap_size());
1773     if (GC_get_total_bytes() < (size_t)n_tests *
1774 #   ifdef VERY_SMALL_CONFIG
1775         2700000
1776 #   else
1777         33500000
1778 #   endif
1779         ) {
1780       GC_printf("Incorrect execution - missed some allocations\n");
1781       FAIL;
1782     }
1783     if (GC_get_heap_size() + GC_get_unmapped_bytes() > max_heap_sz
1784             && !GC_get_find_leak()) {
1785         GC_printf("Unexpected heap growth - collector may be broken"
1786                   " (heapsize: %lu, expected: %lu)\n",
1787             (unsigned long)(GC_get_heap_size() + GC_get_unmapped_bytes()),
1788             (unsigned long)max_heap_sz);
1789         FAIL;
1790     }
1791     GC_printf("Final number of reachable objects is %u\n", obj_count);
1792 
1793 #   ifndef GC_GET_HEAP_USAGE_NOT_NEEDED
1794       /* Get global counters (just to check the functions work).  */
1795       GC_get_heap_usage_safe(NULL, NULL, NULL, NULL, NULL);
1796       {
1797         struct GC_prof_stats_s stats;
1798         (void)GC_get_prof_stats(&stats, sizeof(stats));
1799 #       ifdef THREADS
1800           (void)GC_get_prof_stats_unsafe(&stats, sizeof(stats));
1801 #       endif
1802       }
1803       (void)GC_get_size_map_at(-1);
1804       (void)GC_get_size_map_at(1);
1805 #   endif
1806 
1807 #   ifdef THREADS
1808       GC_unregister_my_thread(); /* just to check it works (for main) */
1809 #   endif
1810     GC_printf("Completed %u collections", (unsigned)GC_get_gc_no());
1811 #   ifndef NO_CLOCK
1812       GC_printf(" in %lu msecs", GC_get_full_gc_total_time());
1813 #   endif
1814 #   ifdef PARALLEL_MARK
1815       GC_printf(" (using %d marker threads)", GC_get_parallel() + 1);
1816 #   endif
1817     GC_printf("\n" "Collector appears to work\n");
1818 }
1819 
1820 #if defined(MACOS)
SetMinimumStack(long minSize)1821 void SetMinimumStack(long minSize)
1822 {
1823         if (minSize > LMGetDefltStack())
1824         {
1825                 long newApplLimit = (long) GetApplLimit()
1826                                         - (minSize - LMGetDefltStack());
1827                 SetApplLimit((Ptr) newApplLimit);
1828                 MaxApplZone();
1829         }
1830 }
1831 
1832 #define cMinStackSpace (512L * 1024L)
1833 
1834 #endif
1835 
warn_proc(char * msg,GC_word p)1836 void GC_CALLBACK warn_proc(char *msg, GC_word p)
1837 {
1838     GC_printf(msg, (unsigned long)p);
1839     /*FAIL;*/
1840 }
1841 
1842 #if defined(CPPCHECK)
1843 # include "javaxfc.h" /* for GC_finalize_all */
1844 # define UNTESTED(sym) GC_noop1((word)&sym)
1845 #endif
1846 
1847 #if defined(MSWINCE) && defined(UNDER_CE)
1848 # define WINMAIN_LPTSTR LPWSTR
1849 #else
1850 # define WINMAIN_LPTSTR LPSTR
1851 #endif
1852 
1853 #if !defined(PCR) && !defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
1854 
1855 #if ((defined(MSWIN32) && !defined(__MINGW32__)) || defined(MSWINCE)) \
1856     && !defined(NO_WINMAIN_ENTRY)
WinMain(HINSTANCE instance GC_ATTR_UNUSED,HINSTANCE prev GC_ATTR_UNUSED,WINMAIN_LPTSTR cmd GC_ATTR_UNUSED,int n GC_ATTR_UNUSED)1857   int APIENTRY WinMain(HINSTANCE instance GC_ATTR_UNUSED,
1858                        HINSTANCE prev GC_ATTR_UNUSED,
1859                        WINMAIN_LPTSTR cmd GC_ATTR_UNUSED,
1860                        int n GC_ATTR_UNUSED)
1861 #elif defined(RTEMS)
1862 # include <bsp.h>
1863 # define CONFIGURE_APPLICATION_NEEDS_CLOCK_DRIVER
1864 # define CONFIGURE_APPLICATION_NEEDS_CONSOLE_DRIVER
1865 # define CONFIGURE_RTEMS_INIT_TASKS_TABLE
1866 # define CONFIGURE_MAXIMUM_TASKS 1
1867 # define CONFIGURE_INIT
1868 # define CONFIGURE_INIT_TASK_STACK_SIZE (64*1024)
1869 # include <rtems/confdefs.h>
1870   rtems_task Init(rtems_task_argument ignord)
1871 #else
1872   int main(void)
1873 #endif
1874 {
1875 #   if defined(CPPCHECK) && !defined(NO_WINMAIN_ENTRY) \
1876        && ((defined(MSWIN32) && !defined(__MINGW32__)) || defined(MSWINCE))
1877       GC_noop1((GC_word)&WinMain);
1878 #   elif defined(CPPCHECK) && defined(RTEMS)
1879       GC_noop1((GC_word)&Init);
1880 #   endif
1881     n_tests = 0;
1882 #   if defined(MACOS)
1883         /* Make sure we have lots and lots of stack space.      */
1884         SetMinimumStack(cMinStackSpace);
1885         /* Cheat and let stdio initialize toolbox for us.       */
1886         printf("Testing GC Macintosh port\n");
1887 #   endif
1888     GC_COND_INIT();
1889     GC_set_warn_proc(warn_proc);
1890 #   if !defined(GC_DISABLE_INCREMENTAL) \
1891        && (defined(TEST_DEFAULT_VDB) || !defined(DEFAULT_VDB))
1892 #     if !defined(MAKE_BACK_GRAPH) && !defined(NO_INCREMENTAL) \
1893          && !(defined(MPROTECT_VDB) && defined(USE_MUNMAP))
1894         GC_enable_incremental();
1895 #     endif
1896       if (GC_is_incremental_mode()) {
1897 #       ifndef SMALL_CONFIG
1898           if (GC_get_manual_vdb_allowed()) {
1899             GC_printf("Switched to incremental mode (manual VDB)\n");
1900           } else
1901 #       endif
1902         /* else */ {
1903           GC_printf("Switched to incremental mode\n");
1904 #       ifdef PROC_VDB
1905           GC_printf("Reading dirty bits from /proc\n");
1906 #       elif defined(GWW_VDB)
1907           GC_printf("Using GetWriteWatch-based implementation\n");
1908 #         ifdef MPROTECT_VDB
1909             GC_printf("Or emulating dirty bits with mprotect/signals\n");
1910 #         endif
1911 #       elif defined(MPROTECT_VDB)
1912           GC_printf("Emulating dirty bits with mprotect/signals\n");
1913 #       endif /* MPROTECT_VDB && !GWW_VDB */
1914         }
1915       }
1916 #   endif
1917     set_print_procs();
1918     run_one_test();
1919     run_single_threaded_test();
1920     check_heap_stats();
1921 #   ifndef MSWINCE
1922       fflush(stdout);
1923 #   endif
1924 #   if defined(CPPCHECK)
1925        /* Entry points we should be testing, but aren't.        */
1926 #      ifndef GC_DEBUG
1927          UNTESTED(GC_debug_generic_or_special_malloc);
1928          UNTESTED(GC_debug_register_displacement);
1929          UNTESTED(GC_post_incr);
1930          UNTESTED(GC_pre_incr);
1931 #        ifdef GC_GCJ_SUPPORT
1932            UNTESTED(GC_debug_gcj_malloc);
1933 #        endif
1934 #      endif
1935 #      ifdef AMIGA
1936 #        ifdef GC_AMIGA_FASTALLOC
1937            UNTESTED(GC_amiga_get_mem);
1938 #        endif
1939 #        ifndef GC_AMIGA_ONLYFAST
1940            UNTESTED(GC_amiga_set_toany);
1941 #        endif
1942 #      endif
1943 #      if defined(MACOS) && defined(USE_TEMPORARY_MEMORY)
1944          UNTESTED(GC_MacTemporaryNewPtr);
1945 #      endif
1946 #      if !defined(_M_AMD64) && defined(_MSC_VER)
1947          UNTESTED(GetFileLineFromStack);
1948          UNTESTED(GetModuleNameFromStack);
1949          UNTESTED(GetSymbolNameFromStack);
1950 #      endif
1951        UNTESTED(GC_abort_on_oom);
1952        UNTESTED(GC_get_bytes_since_gc);
1953        UNTESTED(GC_get_dont_expand);
1954        UNTESTED(GC_get_dont_precollect);
1955        UNTESTED(GC_get_finalize_on_demand);
1956        UNTESTED(GC_get_finalizer_notifier);
1957        UNTESTED(GC_get_force_unmap_on_gcollect);
1958        UNTESTED(GC_get_free_bytes);
1959        UNTESTED(GC_get_free_space_divisor);
1960        UNTESTED(GC_get_full_freq);
1961        UNTESTED(GC_get_java_finalization);
1962        UNTESTED(GC_get_max_retries);
1963        UNTESTED(GC_get_no_dls);
1964        UNTESTED(GC_get_non_gc_bytes);
1965        UNTESTED(GC_get_on_collection_event);
1966        UNTESTED(GC_get_on_heap_resize);
1967        UNTESTED(GC_get_pages_executable);
1968        UNTESTED(GC_get_push_other_roots);
1969        UNTESTED(GC_get_start_callback);
1970        UNTESTED(GC_get_stop_func);
1971        UNTESTED(GC_get_time_limit);
1972        UNTESTED(GC_get_warn_proc);
1973        UNTESTED(GC_is_disabled);
1974        UNTESTED(GC_set_dont_precollect);
1975        UNTESTED(GC_set_finalize_on_demand);
1976        UNTESTED(GC_set_finalizer_notifier);
1977        UNTESTED(GC_set_free_space_divisor);
1978        UNTESTED(GC_set_full_freq);
1979        UNTESTED(GC_set_java_finalization);
1980        UNTESTED(GC_set_max_retries);
1981        UNTESTED(GC_set_no_dls);
1982        UNTESTED(GC_set_non_gc_bytes);
1983        UNTESTED(GC_set_on_collection_event);
1984        UNTESTED(GC_set_on_heap_resize);
1985        UNTESTED(GC_set_oom_fn);
1986        UNTESTED(GC_set_push_other_roots);
1987        UNTESTED(GC_set_start_callback);
1988        UNTESTED(GC_set_stop_func);
1989        UNTESTED(GC_set_time_limit);
1990        UNTESTED(GC_malloc_explicitly_typed_ignore_off_page);
1991        UNTESTED(GC_debug_change_stubborn);
1992        UNTESTED(GC_debug_strndup);
1993        UNTESTED(GC_deinit);
1994        UNTESTED(GC_strndup);
1995        UNTESTED(GC_posix_memalign);
1996        UNTESTED(GC_new_free_list);
1997        UNTESTED(GC_new_kind);
1998        UNTESTED(GC_new_proc);
1999        UNTESTED(GC_clear_roots);
2000        UNTESTED(GC_exclude_static_roots);
2001        UNTESTED(GC_expand_hp);
2002        UNTESTED(GC_register_describe_type_fn);
2003        UNTESTED(GC_register_has_static_roots_callback);
2004 #      if !defined(PCR) && !defined(SMALL_CONFIG)
2005          UNTESTED(GC_get_abort_func);
2006          UNTESTED(GC_set_abort_func);
2007 #      endif
2008 #      ifdef GC_GCJ_SUPPORT
2009          UNTESTED(GC_gcj_malloc_ignore_off_page);
2010 #      endif
2011 #      ifndef NO_DEBUGGING
2012          UNTESTED(GC_dump);
2013          UNTESTED(GC_dump_regions);
2014          UNTESTED(GC_is_tmp_root);
2015          UNTESTED(GC_print_free_list);
2016 #      endif
2017 #      ifdef TRACE_BUF
2018          UNTESTED(GC_print_trace);
2019 #      endif
2020 #      ifndef GC_NO_FINALIZATION
2021          UNTESTED(GC_debug_register_finalizer_unreachable);
2022          UNTESTED(GC_get_await_finalize_proc);
2023          UNTESTED(GC_register_disappearing_link);
2024          UNTESTED(GC_set_await_finalize_proc);
2025          UNTESTED(GC_should_invoke_finalizers);
2026 #        ifndef JAVA_FINALIZATION_NOT_NEEDED
2027            UNTESTED(GC_finalize_all);
2028 #        endif
2029 #        ifndef NO_DEBUGGING
2030            UNTESTED(GC_dump_finalization);
2031 #        endif
2032 #        ifndef GC_TOGGLE_REFS_NOT_NEEDED
2033            UNTESTED(GC_get_toggleref_func);
2034            UNTESTED(GC_set_toggleref_func);
2035            UNTESTED(GC_toggleref_add);
2036 #        endif
2037 #      endif
2038 #      if !defined(OS2) && !defined(MACOS) && !defined(GC_ANDROID_LOG) \
2039           && !defined(MSWIN32) && !defined(MSWINCE)
2040          UNTESTED(GC_set_log_fd);
2041 #      endif
2042 #      ifndef REDIRECT_MALLOC_IN_HEADER
2043 #        ifdef REDIRECT_MALLOC
2044 #          ifndef strndup
2045              UNTESTED(strndup);
2046 #          endif
2047 #          ifndef strdup
2048              UNTESTED(strdup);
2049 #          endif
2050 #        endif
2051 #        ifdef REDIRECT_REALLOC
2052            UNTESTED(realloc);
2053 #        endif
2054 #      endif /* !REDIRECT_MALLOC_IN_HEADER */
2055 #      ifdef GC_REQUIRE_WCSDUP
2056          UNTESTED(GC_wcsdup);
2057          UNTESTED(GC_debug_wcsdup);
2058 #      endif
2059 #   endif
2060 #   ifdef MSWIN32
2061       GC_win32_free_heap();
2062 #   endif
2063 #   ifdef RTEMS
2064       exit(0);
2065 #   else
2066       return(0);
2067 #   endif
2068 }
2069 # endif /* !GC_WIN32_THREADS && !GC_PTHREADS */
2070 
2071 #if defined(GC_WIN32_THREADS) && !defined(GC_PTHREADS)
2072 
thr_run_one_test(void * arg GC_ATTR_UNUSED)2073 DWORD __stdcall thr_run_one_test(void * arg GC_ATTR_UNUSED)
2074 {
2075   run_one_test();
2076   return 0;
2077 }
2078 
2079 #ifdef MSWINCE
2080 HANDLE win_created_h;
2081 HWND win_handle;
2082 
window_proc(HWND hwnd,UINT uMsg,WPARAM wParam,LPARAM lParam)2083 LRESULT CALLBACK window_proc(HWND hwnd, UINT uMsg, WPARAM wParam,
2084                              LPARAM lParam)
2085 {
2086   LRESULT ret = 0;
2087   switch (uMsg) {
2088     case WM_HIBERNATE:
2089       GC_printf("Received WM_HIBERNATE, calling GC_gcollect\n");
2090       /* Force "unmap as much memory as possible" mode. */
2091       GC_gcollect_and_unmap();
2092       break;
2093     case WM_CLOSE:
2094       GC_printf("Received WM_CLOSE, closing window\n");
2095       DestroyWindow(hwnd);
2096       break;
2097     case WM_DESTROY:
2098       PostQuitMessage(0);
2099       break;
2100     default:
2101       ret = DefWindowProc(hwnd, uMsg, wParam, lParam);
2102       break;
2103   }
2104   return ret;
2105 }
2106 
thr_window(void * arg GC_ATTR_UNUSED)2107 DWORD __stdcall thr_window(void * arg GC_ATTR_UNUSED)
2108 {
2109   WNDCLASS win_class = {
2110     CS_NOCLOSE,
2111     window_proc,
2112     0,
2113     0,
2114     GetModuleHandle(NULL),
2115     NULL,
2116     NULL,
2117     (HBRUSH)(COLOR_APPWORKSPACE+1),
2118     NULL,
2119     TEXT("GCtestWindow")
2120   };
2121   MSG msg;
2122 
2123   if (!RegisterClass(&win_class))
2124     FAIL;
2125 
2126   win_handle = CreateWindowEx(
2127     0,
2128     TEXT("GCtestWindow"),
2129     TEXT("GCtest"),
2130     0,
2131     CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
2132     NULL,
2133     NULL,
2134     GetModuleHandle(NULL),
2135     NULL);
2136 
2137   if (win_handle == NULL)
2138     FAIL;
2139 
2140   SetEvent(win_created_h);
2141 
2142   ShowWindow(win_handle, SW_SHOW);
2143   UpdateWindow(win_handle);
2144 
2145   while (GetMessage(&msg, NULL, 0, 0)) {
2146     TranslateMessage(&msg);
2147     DispatchMessage(&msg);
2148   }
2149 
2150   return 0;
2151 }
2152 #endif
2153 
2154 #if !defined(NO_WINMAIN_ENTRY)
WinMain(HINSTANCE instance GC_ATTR_UNUSED,HINSTANCE prev GC_ATTR_UNUSED,WINMAIN_LPTSTR cmd GC_ATTR_UNUSED,int n GC_ATTR_UNUSED)2155   int APIENTRY WinMain(HINSTANCE instance GC_ATTR_UNUSED,
2156                        HINSTANCE prev GC_ATTR_UNUSED,
2157                        WINMAIN_LPTSTR cmd GC_ATTR_UNUSED,
2158                        int n GC_ATTR_UNUSED)
2159 #else
2160   int main(void)
2161 #endif
2162 {
2163 # if NTHREADS > 0
2164    HANDLE h[NTHREADS];
2165    int i;
2166 # endif
2167 # ifdef MSWINCE
2168     HANDLE win_thr_h;
2169 # endif
2170   DWORD thread_id;
2171 
2172 # if defined(CPPCHECK) && !defined(NO_WINMAIN_ENTRY)
2173     GC_noop1((GC_word)&WinMain);
2174 # endif
2175 # if defined(GC_DLL) && !defined(GC_NO_THREADS_DISCOVERY) \
2176         && !defined(MSWINCE) && !defined(THREAD_LOCAL_ALLOC) \
2177         && !defined(PARALLEL_MARK)
2178     GC_use_threads_discovery();
2179                 /* Test with implicit thread registration if possible. */
2180     GC_printf("Using DllMain to track threads\n");
2181 # endif
2182   GC_COND_INIT();
2183 # if !defined(MAKE_BACK_GRAPH) && !defined(NO_INCREMENTAL)
2184     GC_enable_incremental();
2185 # endif
2186   InitializeCriticalSection(&incr_cs);
2187   GC_set_warn_proc(warn_proc);
2188 # ifdef MSWINCE
2189     win_created_h = CreateEvent(NULL, FALSE, FALSE, NULL);
2190     if (win_created_h == (HANDLE)NULL) {
2191       GC_printf("Event creation failed %d\n", (int)GetLastError());
2192       FAIL;
2193     }
2194     win_thr_h = GC_CreateThread(NULL, 0, thr_window, 0, 0, &thread_id);
2195     if (win_thr_h == (HANDLE)NULL) {
2196       GC_printf("Thread creation failed %d\n", (int)GetLastError());
2197       FAIL;
2198     }
2199     if (WaitForSingleObject(win_created_h, INFINITE) != WAIT_OBJECT_0)
2200       FAIL;
2201     CloseHandle(win_created_h);
2202 # endif
2203   set_print_procs();
2204 # if NTHREADS > 0
2205    for (i = 0; i < NTHREADS; i++) {
2206     h[i] = GC_CreateThread(NULL, 0, thr_run_one_test, 0, 0, &thread_id);
2207     if (h[i] == (HANDLE)NULL) {
2208       GC_printf("Thread creation failed %d\n", (int)GetLastError());
2209       FAIL;
2210     }
2211    }
2212 # endif /* NTHREADS > 0 */
2213   run_one_test();
2214 # if NTHREADS > 0
2215    for (i = 0; i < NTHREADS; i++) {
2216     if (WaitForSingleObject(h[i], INFINITE) != WAIT_OBJECT_0) {
2217       GC_printf("Thread wait failed %d\n", (int)GetLastError());
2218       FAIL;
2219     }
2220    }
2221 # endif /* NTHREADS > 0 */
2222 # ifdef MSWINCE
2223     PostMessage(win_handle, WM_CLOSE, 0, 0);
2224     if (WaitForSingleObject(win_thr_h, INFINITE) != WAIT_OBJECT_0)
2225       FAIL;
2226 # endif
2227   run_single_threaded_test();
2228   check_heap_stats();
2229 # if defined(CPPCHECK) && defined(GC_WIN32_THREADS)
2230     UNTESTED(GC_ExitThread);
2231 #   if !defined(MSWINCE) && !defined(CYGWIN32)
2232       UNTESTED(GC_beginthreadex);
2233       UNTESTED(GC_endthreadex);
2234 #   endif
2235 # endif
2236   return(0);
2237 }
2238 
2239 #endif /* GC_WIN32_THREADS */
2240 
2241 
2242 #ifdef PCR
test(void)2243 int test(void)
2244 {
2245     PCR_Th_T * th1;
2246     PCR_Th_T * th2;
2247     int code;
2248 
2249 #   if defined(CPPCHECK)
2250       GC_noop1((word)&PCR_GC_Run);
2251       GC_noop1((word)&PCR_GC_Setup);
2252       GC_noop1((word)&test);
2253 #   endif
2254     n_tests = 0;
2255     /* GC_enable_incremental(); */
2256     GC_set_warn_proc(warn_proc);
2257     set_print_procs();
2258     th1 = PCR_Th_Fork(run_one_test, 0);
2259     th2 = PCR_Th_Fork(run_one_test, 0);
2260     run_one_test();
2261     if (PCR_Th_T_Join(th1, &code, NIL, PCR_allSigsBlocked, PCR_waitForever)
2262         != PCR_ERes_okay || code != 0) {
2263         GC_printf("Thread 1 failed\n");
2264     }
2265     if (PCR_Th_T_Join(th2, &code, NIL, PCR_allSigsBlocked, PCR_waitForever)
2266         != PCR_ERes_okay || code != 0) {
2267         GC_printf("Thread 2 failed\n");
2268     }
2269     run_single_threaded_test();
2270     check_heap_stats();
2271     return(0);
2272 }
2273 #endif
2274 
2275 #if defined(GC_PTHREADS)
thr_run_one_test(void * arg GC_ATTR_UNUSED)2276 void * thr_run_one_test(void * arg GC_ATTR_UNUSED)
2277 {
2278     run_one_test();
2279     return(0);
2280 }
2281 
2282 #ifdef GC_DEBUG
2283 #  define GC_free GC_debug_free
2284 #endif
2285 
main(void)2286 int main(void)
2287 {
2288 #   if NTHREADS > 0
2289       pthread_t th[NTHREADS];
2290       int i;
2291 #   endif
2292     pthread_attr_t attr;
2293     int code;
2294 #   ifdef GC_IRIX_THREADS
2295         /* Force a larger stack to be preallocated      */
2296         /* Since the initial can't always grow later.   */
2297         *((volatile char *)&code - 1024*1024) = 0;      /* Require 1 MB */
2298 #   endif /* GC_IRIX_THREADS */
2299 #   if defined(GC_HPUX_THREADS)
2300         /* Default stack size is too small, especially with the 64 bit ABI */
2301         /* Increase it.                                                    */
2302         if (pthread_default_stacksize_np(1024*1024, 0) != 0) {
2303           GC_printf("pthread_default_stacksize_np failed\n");
2304         }
2305 #   endif       /* GC_HPUX_THREADS */
2306 #   ifdef PTW32_STATIC_LIB
2307         pthread_win32_process_attach_np ();
2308         pthread_win32_thread_attach_np ();
2309 #   endif
2310 #   if defined(GC_DARWIN_THREADS) && !defined(GC_NO_THREADS_DISCOVERY) \
2311         && !defined(DARWIN_DONT_PARSE_STACK) && !defined(THREAD_LOCAL_ALLOC)
2312       /* Test with the Darwin implicit thread registration. */
2313       GC_use_threads_discovery();
2314       GC_printf("Using Darwin task-threads-based world stop and push\n");
2315 #   endif
2316     GC_COND_INIT();
2317 
2318     if ((code = pthread_attr_init(&attr)) != 0) {
2319       GC_printf("pthread_attr_init failed, error=%d\n", code);
2320       FAIL;
2321     }
2322 #   if defined(GC_IRIX_THREADS) || defined(GC_FREEBSD_THREADS) \
2323         || defined(GC_DARWIN_THREADS) || defined(GC_AIX_THREADS) \
2324         || defined(GC_OPENBSD_THREADS)
2325         if ((code = pthread_attr_setstacksize(&attr, 1000 * 1024)) != 0) {
2326           GC_printf("pthread_attr_setstacksize failed, error=%d\n", code);
2327           FAIL;
2328         }
2329 #   endif
2330     n_tests = 0;
2331 #   if !defined(GC_DISABLE_INCREMENTAL) \
2332        && (defined(TEST_DEFAULT_VDB) || !defined(DEFAULT_VDB))
2333 #     if !defined(REDIRECT_MALLOC) && !defined(MAKE_BACK_GRAPH) \
2334          && !defined(USE_PROC_FOR_LIBRARIES) && !defined(NO_INCREMENTAL) \
2335          && !defined(USE_MUNMAP)
2336         GC_enable_incremental();
2337 #     endif
2338       if (GC_is_incremental_mode()) {
2339 #       ifndef SMALL_CONFIG
2340           if (GC_get_manual_vdb_allowed()) {
2341             GC_printf("Switched to incremental mode (manual VDB)\n");
2342           } else
2343 #       endif
2344         /* else */ {
2345           GC_printf("Switched to incremental mode\n");
2346 #         ifdef MPROTECT_VDB
2347             GC_printf("Emulating dirty bits with mprotect/signals\n");
2348 #         endif
2349         }
2350       }
2351 #   endif
2352     GC_set_min_bytes_allocd(1);
2353     if (GC_get_min_bytes_allocd() != 1)
2354         FAIL;
2355     GC_set_rate(10);
2356     GC_set_max_prior_attempts(1);
2357     if (GC_get_rate() != 10 || GC_get_max_prior_attempts() != 1)
2358         FAIL;
2359     GC_set_warn_proc(warn_proc);
2360     if ((code = pthread_key_create(&fl_key, 0)) != 0) {
2361         GC_printf("Key creation failed %d\n", code);
2362         FAIL;
2363     }
2364     set_print_procs();
2365 #   if NTHREADS > 0
2366       for (i = 0; i < NTHREADS; ++i) {
2367         if ((code = pthread_create(th+i, &attr, thr_run_one_test, 0)) != 0) {
2368           GC_printf("Thread %d creation failed %d\n", i, code);
2369           FAIL;
2370         }
2371       }
2372 #   endif
2373     run_one_test();
2374 #   if NTHREADS > 0
2375       for (i = 0; i < NTHREADS; ++i) {
2376         if ((code = pthread_join(th[i], 0)) != 0) {
2377           GC_printf("Thread %d failed %d\n", i, code);
2378           FAIL;
2379         }
2380       }
2381 #   endif
2382     run_single_threaded_test();
2383     check_heap_stats();
2384     (void)fflush(stdout);
2385     (void)pthread_attr_destroy(&attr);
2386 #   if defined(CPPCHECK)
2387       UNTESTED(GC_allow_register_threads);
2388       UNTESTED(GC_get_on_thread_event);
2389       UNTESTED(GC_register_altstack);
2390       UNTESTED(GC_set_on_thread_event);
2391       UNTESTED(GC_set_suspend_signal);
2392       UNTESTED(GC_set_thr_restart_signal);
2393       UNTESTED(GC_stop_world_external);
2394       UNTESTED(GC_start_world_external);
2395 #     ifndef GC_NO_DLOPEN
2396         UNTESTED(GC_dlopen);
2397 #     endif
2398 #     ifndef GC_NO_PTHREAD_CANCEL
2399         UNTESTED(GC_pthread_cancel);
2400 #     endif
2401 #     ifdef GC_HAVE_PTHREAD_EXIT
2402         UNTESTED(GC_pthread_exit);
2403 #     endif
2404 #     ifndef GC_NO_PTHREAD_SIGMASK
2405         UNTESTED(GC_pthread_sigmask);
2406 #     endif
2407 #     ifdef NO_TEST_HANDLE_FORK
2408         UNTESTED(GC_atfork_child);
2409         UNTESTED(GC_atfork_parent);
2410         UNTESTED(GC_atfork_prepare);
2411         UNTESTED(GC_set_handle_fork);
2412         UNTESTED(GC_start_mark_threads);
2413 #     endif
2414 #   endif /* CPPCHECK */
2415 #   ifdef PTW32_STATIC_LIB
2416         pthread_win32_thread_detach_np ();
2417         pthread_win32_process_detach_np ();
2418 #   endif
2419     return(0);
2420 }
2421 #endif /* GC_PTHREADS */
2422