From 4e84a470a723dbd46e8839c1c010cec25ad55f97 Mon Sep 17 00:00:00 2001 From: ivmai Date: Sat, 26 Sep 2009 06:48:44 +0000 Subject: [PATCH] 2009-09-26 Ivan Maidanski * alloc.c: Expand all tabs to spaces; remove trailing spaces at EOLn; remove multiple trailing blank lines. * misc.c: Ditto. * os_dep.c: Ditto. * pthread_support.c: Ditto. * include/private/gc_priv.h: Ditto. * include/private/gcconfig.h: Ditto. --- ChangeLog | 11 +- alloc.c | 852 +++++++------- include/private/gc_priv.h | 4 +- include/private/gcconfig.h | 20 +- misc.c | 778 ++++++------- os_dep.c | 2714 ++++++++++++++++++++++---------------------- pthread_support.c | 915 ++++++++------- 7 files changed, 2650 insertions(+), 2644 deletions(-) diff --git a/ChangeLog b/ChangeLog index cfb5e05..c9f8bbf 100644 --- a/ChangeLog +++ b/ChangeLog @@ -1,3 +1,13 @@ +2009-09-26 Ivan Maidanski + + * alloc.c: Expand all tabs to spaces; remove trailing spaces at + EOLn; remove multiple trailing blank lines. + * misc.c: Ditto. + * os_dep.c: Ditto. + * pthread_support.c: Ditto. + * include/private/gc_priv.h: Ditto. + * include/private/gcconfig.h: Ditto. + 2009-09-25 Hans Boehm * include/private/gcconfig.h (CANCEL_SAFE, IF_CANCEL): new macros. @@ -23,7 +33,6 @@ (GC_unregister_my_thread): Disable cancellation. * Makefile.direct: Document NO_CANCEL_SAFE. - 2009-09-25 Ivan Maidanski * Makefile: Remove outdated file (Makefile.direct should be used diff --git a/alloc.c b/alloc.c index 12fe428..d40d8f0 100644 --- a/alloc.c +++ b/alloc.c @@ -49,7 +49,7 @@ * These chunks all start on addresses which are multiples of * HBLKSZ. Each allocated chunk has an associated header, * which can be located quickly based on the address of the chunk. - * (See headers.c for details.) + * (See headers.c for details.) * This makes it possible to check quickly whether an * arbitrary address corresponds to an object administered by the * allocator. @@ -60,21 +60,21 @@ word GC_non_gc_bytes = 0; /* Number of bytes not intended to be collected */ word GC_gc_no = 0; #ifndef SMALL_CONFIG - int GC_incremental = 0; /* By default, stop the world. */ + int GC_incremental = 0; /* By default, stop the world. */ #endif -int GC_parallel = FALSE; /* By default, parallel GC is off. */ +int GC_parallel = FALSE; /* By default, parallel GC is off. */ #ifndef GC_FULL_FREQ -# define GC_FULL_FREQ 19 /* Every 20th collection is a full */ - /* collection, whether we need it */ - /* or not. */ +# define GC_FULL_FREQ 19 /* Every 20th collection is a full */ + /* collection, whether we need it */ + /* or not. */ #endif int GC_full_freq = GC_FULL_FREQ; STATIC GC_bool GC_need_full_gc = FALSE; - /* Need full GC do to heap growth. */ + /* Need full GC do to heap growth. */ #ifdef THREADS GC_bool GC_world_stopped = FALSE; @@ -94,8 +94,8 @@ char * GC_copyright[] = " EXPRESSED OR IMPLIED. ANY USE IS AT YOUR OWN RISK.", "See source code for details." }; -/* Version macros are now defined in gc_version.h, which is included by */ -/* gc.h, which is included by gc_priv.h". */ +/* Version macros are now defined in gc_version.h, which is included by */ +/* gc.h, which is included by gc_priv.h". */ #ifndef GC_NO_VERSION_VAR @@ -105,8 +105,8 @@ unsigned GC_version = ((GC_VERSION_MAJOR << 16) | (GC_VERSION_MINOR << 8) | GC_T /* some more variables */ -extern signed_word GC_bytes_found; /* Number of reclaimed bytes */ - /* after garbage collection */ +extern signed_word GC_bytes_found; /* Number of reclaimed bytes */ + /* after garbage collection */ #ifdef GC_DONT_EXPAND GC_bool GC_dont_expand = TRUE; @@ -121,24 +121,24 @@ extern signed_word GC_bytes_found; /* Number of reclaimed bytes */ word GC_free_space_divisor = GC_FREE_SPACE_DIVISOR; extern GC_bool GC_collection_in_progress(void); - /* Collection is in progress, or was abandoned. */ + /* Collection is in progress, or was abandoned. */ int GC_CALLBACK GC_never_stop_func (void) { return(0); } #ifndef GC_TIME_LIMIT -# define GC_TIME_LIMIT 50 /* We try to keep pause times from exceeding */ - /* this by much. In milliseconds. */ +# define GC_TIME_LIMIT 50 /* We try to keep pause times from exceeding */ + /* this by much. In milliseconds. */ #endif unsigned long GC_time_limit = GC_TIME_LIMIT; #ifndef NO_CLOCK -STATIC CLOCK_TYPE GC_start_time;/* Time at which we stopped world. */ - /* used only in GC_timeout_stop_func. */ +STATIC CLOCK_TYPE GC_start_time;/* Time at which we stopped world. */ + /* used only in GC_timeout_stop_func. */ #endif -STATIC int GC_n_attempts = 0; /* Number of attempts at finishing */ - /* collection within GC_time_limit. */ +STATIC int GC_n_attempts = 0; /* Number of attempts at finishing */ + /* collection within GC_time_limit. */ STATIC GC_stop_func GC_default_stop_func = GC_never_stop_func; @@ -167,7 +167,7 @@ GC_API GC_stop_func GC_CALL GC_get_stop_func(void) CLOCK_TYPE current_time; static unsigned count = 0; unsigned long time_diff; - + if ((*GC_default_stop_func)()) return(1); @@ -175,38 +175,38 @@ GC_API GC_stop_func GC_CALL GC_get_stop_func(void) GET_TIME(current_time); time_diff = MS_TIME_DIFF(current_time,GC_start_time); if (time_diff >= GC_time_limit) { - if (GC_print_stats) { - GC_log_printf( - "Abandoning stopped marking after %lu msecs (attempt %d)\n", - time_diff, GC_n_attempts); - } - return(1); + if (GC_print_stats) { + GC_log_printf( + "Abandoning stopped marking after %lu msecs (attempt %d)\n", + time_diff, GC_n_attempts); + } + return(1); } return(0); } #endif /* !SMALL_CONFIG */ -/* Return the minimum number of words that must be allocated between */ -/* collections to amortize the collection cost. */ +/* Return the minimum number of words that must be allocated between */ +/* collections to amortize the collection cost. */ static word min_bytes_allocd(void) { # ifdef THREADS - /* We punt, for now. */ - signed_word stack_size = 10000; + /* We punt, for now. */ + signed_word stack_size = 10000; # else int dummy; signed_word stack_size = (ptr_t)(&dummy) - GC_stackbottom; # endif - word total_root_size; /* includes double stack size, */ - /* since the stack is expensive */ - /* to scan. */ - word scan_size; /* Estimate of memory to be scanned */ - /* during normal GC. */ - + word total_root_size; /* includes double stack size, */ + /* since the stack is expensive */ + /* to scan. */ + word scan_size; /* Estimate of memory to be scanned */ + /* during normal GC. */ + if (stack_size < 0) stack_size = -stack_size; total_root_size = 2 * stack_size + GC_root_size; scan_size = 2 * GC_composite_in_use + GC_atomic_in_use/4 - + total_root_size; + + total_root_size; if (TRUE_INCREMENTAL) { return scan_size / (2 * GC_free_space_divisor); } else { @@ -214,39 +214,39 @@ static word min_bytes_allocd(void) } } -/* Return the number of bytes allocated, adjusted for explicit storage */ -/* management, etc.. This number is used in deciding when to trigger */ -/* collections. */ +/* Return the number of bytes allocated, adjusted for explicit storage */ +/* management, etc.. This number is used in deciding when to trigger */ +/* collections. */ STATIC word GC_adj_bytes_allocd(void) { signed_word result; signed_word expl_managed = - (signed_word)GC_non_gc_bytes - - (signed_word)GC_non_gc_bytes_at_gc; - - /* Don't count what was explicitly freed, or newly allocated for */ - /* explicit management. Note that deallocating an explicitly */ - /* managed object should not alter result, assuming the client */ - /* is playing by the rules. */ + (signed_word)GC_non_gc_bytes + - (signed_word)GC_non_gc_bytes_at_gc; + + /* Don't count what was explicitly freed, or newly allocated for */ + /* explicit management. Note that deallocating an explicitly */ + /* managed object should not alter result, assuming the client */ + /* is playing by the rules. */ result = (signed_word)GC_bytes_allocd - + (signed_word)GC_bytes_dropped - - (signed_word)GC_bytes_freed - + (signed_word)GC_finalizer_bytes_freed - - expl_managed; + + (signed_word)GC_bytes_dropped + - (signed_word)GC_bytes_freed + + (signed_word)GC_finalizer_bytes_freed + - expl_managed; if (result > (signed_word)GC_bytes_allocd) { result = GC_bytes_allocd; - /* probably client bug or unfortunate scheduling */ + /* probably client bug or unfortunate scheduling */ } result += GC_bytes_finalized; - /* We count objects enqueued for finalization as though they */ - /* had been reallocated this round. Finalization is user */ - /* visible progress. And if we don't count this, we have */ - /* stability problems for programs that finalize all objects. */ + /* We count objects enqueued for finalization as though they */ + /* had been reallocated this round. Finalization is user */ + /* visible progress. And if we don't count this, we have */ + /* stability problems for programs that finalize all objects. */ if (result < (signed_word)(GC_bytes_allocd >> 3)) { - /* Always count at least 1/8 of the allocations. We don't want */ - /* to collect too infrequently, since that would inhibit */ - /* coalescing of free storage blocks. */ - /* This also makes us partially robust against client bugs. */ + /* Always count at least 1/8 of the allocations. We don't want */ + /* to collect too infrequently, since that would inhibit */ + /* coalescing of free storage blocks. */ + /* This also makes us partially robust against client bugs. */ return(GC_bytes_allocd >> 3); } else { return(result); @@ -254,11 +254,11 @@ STATIC word GC_adj_bytes_allocd(void) } -/* Clear up a few frames worth of garbage left at the top of the stack. */ -/* This is used to prevent us from accidentally treating garbage left */ -/* on the stack by other parts of the collector as roots. This */ -/* differs from the code in misc.c, which actually tries to keep the */ -/* stack clear of long-lived, client-generated garbage. */ +/* Clear up a few frames worth of garbage left at the top of the stack. */ +/* This is used to prevent us from accidentally treating garbage left */ +/* on the stack by other parts of the collector as roots. This */ +/* differs from the code in misc.c, which actually tries to keep the */ +/* stack clear of long-lived, client-generated garbage. */ STATIC void GC_clear_a_few_frames(void) { # ifndef CLEAR_NWORDS @@ -266,12 +266,12 @@ STATIC void GC_clear_a_few_frames(void) # endif volatile word frames[CLEAR_NWORDS]; int i; - + for (i = 0; i < CLEAR_NWORDS; i++) frames[i] = 0; } -/* Heap size at which we need a collection to avoid expanding past */ -/* limits used by blacklisting. */ +/* Heap size at which we need a collection to avoid expanding past */ +/* limits used by blacklisting. */ static word GC_collect_at_heapsize = (word)(-1); /* Have we allocated enough to amortize a collection? */ @@ -284,14 +284,14 @@ GC_bool GC_should_collect(void) last_min_bytes_allocd = min_bytes_allocd(); } return(GC_adj_bytes_allocd() >= last_min_bytes_allocd - || GC_heapsize >= GC_collect_at_heapsize); + || GC_heapsize >= GC_collect_at_heapsize); } STATIC void GC_notify_full_gc(void) { if (GC_start_call_back != (void (*) (void))0) { - (*GC_start_call_back)(); + (*GC_start_call_back)(); } } @@ -300,7 +300,7 @@ STATIC GC_bool GC_is_full_gc = FALSE; STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func); STATIC void GC_finish_collection(void); -/* +/* * Initiate a garbage collection if appropriate. * Choose judiciously * between partial, full, and stop-world collections. @@ -313,52 +313,52 @@ STATIC void GC_maybe_gc(void) ASSERT_CANCEL_DISABLED(); if (GC_should_collect()) { if (!GC_incremental) { - /* FIXME: If possible, GC_default_stop_func should be used here */ + /* FIXME: If possible, GC_default_stop_func should be used here */ GC_try_to_collect_inner(GC_never_stop_func); n_partial_gcs = 0; return; } else { -# ifdef PARALLEL_MARK - if (GC_parallel) - GC_wait_for_reclaim(); -# endif - if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) { - if (GC_print_stats) { - GC_log_printf( - "***>Full mark for collection %lu after %ld allocd bytes\n", - (unsigned long)GC_gc_no+1, - (long)GC_bytes_allocd); - } - GC_promote_black_lists(); - (void)GC_reclaim_all((GC_stop_func)0, TRUE); - GC_clear_marks(); +# ifdef PARALLEL_MARK + if (GC_parallel) + GC_wait_for_reclaim(); +# endif + if (GC_need_full_gc || n_partial_gcs >= GC_full_freq) { + if (GC_print_stats) { + GC_log_printf( + "***>Full mark for collection %lu after %ld allocd bytes\n", + (unsigned long)GC_gc_no+1, + (long)GC_bytes_allocd); + } + GC_promote_black_lists(); + (void)GC_reclaim_all((GC_stop_func)0, TRUE); + GC_clear_marks(); n_partial_gcs = 0; - GC_notify_full_gc(); - GC_is_full_gc = TRUE; + GC_notify_full_gc(); + GC_is_full_gc = TRUE; } else { n_partial_gcs++; } - } - /* We try to mark with the world stopped. */ - /* If we run out of time, this turns into */ - /* incremental marking. */ -# ifndef NO_CLOCK + } + /* We try to mark with the world stopped. */ + /* If we run out of time, this turns into */ + /* incremental marking. */ +# ifndef NO_CLOCK if (GC_time_limit != GC_TIME_UNLIMITED) { GET_TIME(GC_start_time); } -# endif - /* FIXME: If possible, GC_default_stop_func should be */ - /* used instead of GC_never_stop_func here. */ - if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED? - GC_never_stop_func : GC_timeout_stop_func)) { +# endif + /* FIXME: If possible, GC_default_stop_func should be */ + /* used instead of GC_never_stop_func here. */ + if (GC_stopped_mark(GC_time_limit == GC_TIME_UNLIMITED? + GC_never_stop_func : GC_timeout_stop_func)) { # ifdef SAVE_CALL_CHAIN GC_save_callers(GC_last_stack); # endif GC_finish_collection(); } else { - if (!GC_is_full_gc) { - /* Count this as the first attempt */ - GC_n_attempts++; - } - } + if (!GC_is_full_gc) { + /* Count this as the first attempt */ + GC_n_attempts++; + } + } } } @@ -378,38 +378,38 @@ GC_bool GC_try_to_collect_inner(GC_stop_func stop_func) if (GC_dont_gc) return FALSE; if (GC_incremental && GC_collection_in_progress()) { if (GC_print_stats) { - GC_log_printf( - "GC_try_to_collect_inner: finishing collection in progress\n"); + GC_log_printf( + "GC_try_to_collect_inner: finishing collection in progress\n"); } - /* Just finish collection already in progress. */ - while(GC_collection_in_progress()) { - if (stop_func()) return(FALSE); - GC_collect_a_little_inner(1); - } + /* Just finish collection already in progress. */ + while(GC_collection_in_progress()) { + if (stop_func()) return(FALSE); + GC_collect_a_little_inner(1); + } } if (stop_func == GC_never_stop_func) GC_notify_full_gc(); # ifndef SMALL_CONFIG if (GC_print_stats) { - GET_TIME(start_time); - GC_log_printf("Initiating full world-stop collection!\n"); + GET_TIME(start_time); + GC_log_printf("Initiating full world-stop collection!\n"); } # endif GC_promote_black_lists(); - /* Make sure all blocks have been reclaimed, so sweep routines */ - /* don't see cleared mark bits. */ - /* If we're guaranteed to finish, then this is unnecessary. */ - /* In the find_leak case, we have to finish to guarantee that */ - /* previously unmarked objects are not reported as leaks. */ + /* Make sure all blocks have been reclaimed, so sweep routines */ + /* don't see cleared mark bits. */ + /* If we're guaranteed to finish, then this is unnecessary. */ + /* In the find_leak case, we have to finish to guarantee that */ + /* previously unmarked objects are not reported as leaks. */ # ifdef PARALLEL_MARK - if (GC_parallel) - GC_wait_for_reclaim(); + if (GC_parallel) + GC_wait_for_reclaim(); # endif - if ((GC_find_leak || stop_func != GC_never_stop_func) - && !GC_reclaim_all(stop_func, FALSE)) { - /* Aborted. So far everything is still consistent. */ - return(FALSE); - } - GC_invalidate_mark_state(); /* Flush mark stack. */ + if ((GC_find_leak || stop_func != GC_never_stop_func) + && !GC_reclaim_all(stop_func, FALSE)) { + /* Aborted. So far everything is still consistent. */ + return(FALSE); + } + GC_invalidate_mark_state(); /* Flush mark stack. */ GC_clear_marks(); # ifdef SAVE_CALL_CHAIN GC_save_callers(GC_last_stack); @@ -417,13 +417,13 @@ GC_bool GC_try_to_collect_inner(GC_stop_func stop_func) GC_is_full_gc = TRUE; if (!GC_stopped_mark(stop_func)) { if (!GC_incremental) { - /* We're partially done and have no way to complete or use */ - /* current work. Reestablish invariants as cheaply as */ - /* possible. */ - GC_invalidate_mark_state(); - GC_unpromote_black_lists(); - } /* else we claim the world is already still consistent. We'll */ - /* finish incrementally. */ + /* We're partially done and have no way to complete or use */ + /* current work. Reestablish invariants as cheaply as */ + /* possible. */ + GC_invalidate_mark_state(); + GC_unpromote_black_lists(); + } /* else we claim the world is already still consistent. We'll */ + /* finish incrementally. */ return(FALSE); } GC_finish_collection(); @@ -447,18 +447,18 @@ GC_bool GC_try_to_collect_inner(GC_stop_func stop_func) * cleanup gets expensive. */ #ifndef GC_RATE -# define GC_RATE 10 +# define GC_RATE 10 #endif #ifndef MAX_PRIOR_ATTEMPTS # define MAX_PRIOR_ATTEMPTS 1 #endif - /* Maximum number of prior attempts at world stop marking */ - /* A value of 1 means that we finish the second time, no matter */ - /* how long it takes. Doesn't count the initial root scan */ - /* for a full GC. */ + /* Maximum number of prior attempts at world stop marking */ + /* A value of 1 means that we finish the second time, no matter */ + /* how long it takes. Doesn't count the initial root scan */ + /* for a full GC. */ -STATIC int GC_deficit = 0;/* The number of extra calls to GC_mark_some */ - /* that we have made. */ +STATIC int GC_deficit = 0;/* The number of extra calls to GC_mark_some */ + /* that we have made. */ void GC_collect_a_little_inner(int n) { @@ -468,36 +468,36 @@ void GC_collect_a_little_inner(int n) if (GC_dont_gc) return; DISABLE_CANCEL(cancel_state); if (GC_incremental && GC_collection_in_progress()) { - for (i = GC_deficit; i < GC_RATE*n; i++) { - if (GC_mark_some((ptr_t)0)) { - /* Need to finish a collection */ -# ifdef SAVE_CALL_CHAIN - GC_save_callers(GC_last_stack); -# endif -# ifdef PARALLEL_MARK - if (GC_parallel) - GC_wait_for_reclaim(); -# endif - if (GC_n_attempts < MAX_PRIOR_ATTEMPTS - && GC_time_limit != GC_TIME_UNLIMITED) { -# ifndef NO_CLOCK - GET_TIME(GC_start_time); -# endif - if (!GC_stopped_mark(GC_timeout_stop_func)) { - GC_n_attempts++; - break; - } - } else { - /* FIXME: If possible, GC_default_stop_func should be */ - /* used here. */ - (void)GC_stopped_mark(GC_never_stop_func); - } - GC_finish_collection(); - break; - } - } - if (GC_deficit > 0) GC_deficit -= GC_RATE*n; - if (GC_deficit < 0) GC_deficit = 0; + for (i = GC_deficit; i < GC_RATE*n; i++) { + if (GC_mark_some((ptr_t)0)) { + /* Need to finish a collection */ +# ifdef SAVE_CALL_CHAIN + GC_save_callers(GC_last_stack); +# endif +# ifdef PARALLEL_MARK + if (GC_parallel) + GC_wait_for_reclaim(); +# endif + if (GC_n_attempts < MAX_PRIOR_ATTEMPTS + && GC_time_limit != GC_TIME_UNLIMITED) { +# ifndef NO_CLOCK + GET_TIME(GC_start_time); +# endif + if (!GC_stopped_mark(GC_timeout_stop_func)) { + GC_n_attempts++; + break; + } + } else { + /* FIXME: If possible, GC_default_stop_func should be */ + /* used here. */ + (void)GC_stopped_mark(GC_never_stop_func); + } + GC_finish_collection(); + break; + } + } + if (GC_deficit > 0) GC_deficit -= GC_RATE*n; + if (GC_deficit < 0) GC_deficit = 0; } else { GC_maybe_gc(); } @@ -525,15 +525,15 @@ GC_API int GC_CALL GC_collect_a_little(void) #endif #ifndef SMALL_CONFIG - /* Variables for world-stop average delay time statistic computation. */ - /* "divisor" is incremented every world-stop and halved when reached */ - /* its maximum (or upon "total_time" oveflow). */ + /* Variables for world-stop average delay time statistic computation. */ + /* "divisor" is incremented every world-stop and halved when reached */ + /* its maximum (or upon "total_time" oveflow). */ static unsigned world_stopped_total_time = 0; static unsigned world_stopped_total_divisor = 0; # ifndef MAX_TOTAL_TIME_DIVISOR - /* We shall not use big values here (so "outdated" delay time */ - /* values would have less impact on "average" delay time value than */ - /* newer ones). */ + /* We shall not use big values here (so "outdated" delay time */ + /* values would have less impact on "average" delay time value than */ + /* newer ones). */ # define MAX_TOTAL_TIME_DIVISOR 1000 # endif #endif @@ -551,7 +551,7 @@ STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func) CLOCK_TYPE start_time = 0; /* initialized to prevent warning. */ CLOCK_TYPE current_time; # endif - + # if !defined(REDIRECT_MALLOC) && (defined(MSWIN32) || defined(MSWINCE)) GC_add_current_malloc_heap(); # endif @@ -561,16 +561,16 @@ STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func) # ifndef SMALL_CONFIG if (GC_print_stats) - GET_TIME(start_time); + GET_TIME(start_time); # endif STOP_WORLD(); IF_THREADS(GC_world_stopped = TRUE); if (GC_print_stats) { - /* Output blank line for convenience here */ - GC_log_printf( - "\n--> Marking for collection %lu after %lu allocated bytes\n", - (unsigned long)GC_gc_no + 1, (unsigned long) GC_bytes_allocd); + /* Output blank line for convenience here */ + GC_log_printf( + "\n--> Marking for collection %lu after %lu allocated bytes\n", + (unsigned long)GC_gc_no + 1, (unsigned long) GC_bytes_allocd); } # ifdef MAKE_BACK_GRAPH if (GC_print_back_height) { @@ -582,67 +582,67 @@ STATIC GC_bool GC_stopped_mark(GC_stop_func stop_func) /* Minimize junk left in my registers and on the stack */ GC_clear_a_few_frames(); GC_noop(0,0,0,0,0,0); - GC_initiate_gc(); - for(i = 0;;i++) { - if ((*stop_func)()) { - if (GC_print_stats) { - GC_log_printf("Abandoned stopped marking after " - "%u iterations\n", i); - } - GC_deficit = i; /* Give the mutator a chance. */ + GC_initiate_gc(); + for(i = 0;;i++) { + if ((*stop_func)()) { + if (GC_print_stats) { + GC_log_printf("Abandoned stopped marking after " + "%u iterations\n", i); + } + GC_deficit = i; /* Give the mutator a chance. */ IF_THREADS(GC_world_stopped = FALSE); - START_WORLD(); - return(FALSE); - } - if (GC_mark_some((ptr_t)(&dummy))) break; - } - + START_WORLD(); + return(FALSE); + } + if (GC_mark_some((ptr_t)(&dummy))) break; + } + GC_gc_no++; if (GC_print_stats) { GC_log_printf( - "Collection %lu reclaimed %ld bytes ---> heapsize = %lu bytes\n", - (unsigned long)(GC_gc_no - 1), (long)GC_bytes_found, - (unsigned long)GC_heapsize); + "Collection %lu reclaimed %ld bytes ---> heapsize = %lu bytes\n", + (unsigned long)(GC_gc_no - 1), (long)GC_bytes_found, + (unsigned long)GC_heapsize); } /* Check all debugged objects for consistency */ if (GC_debugging_started) { (*GC_check_heap)(); } - + IF_THREADS(GC_world_stopped = FALSE); START_WORLD(); # ifndef SMALL_CONFIG if (GC_print_stats) { - unsigned long time_diff; - unsigned total_time, divisor; - GET_TIME(current_time); - time_diff = MS_TIME_DIFF(current_time,start_time); - - /* Compute new world-stop delay total time */ - total_time = world_stopped_total_time; - divisor = world_stopped_total_divisor; - if ((int)total_time < 0 || divisor >= MAX_TOTAL_TIME_DIVISOR) { - /* Halve values if overflow occurs */ - total_time >>= 1; - divisor >>= 1; - } - total_time += time_diff < (((unsigned)-1) >> 1) ? - (unsigned)time_diff : ((unsigned)-1) >> 1; - /* Update old world_stopped_total_time and its divisor */ - world_stopped_total_time = total_time; - world_stopped_total_divisor = ++divisor; - - GC_ASSERT(divisor != 0); - GC_log_printf( - "World-stopped marking took %lu msecs (%u in average)\n", - time_diff, total_time / divisor); + unsigned long time_diff; + unsigned total_time, divisor; + GET_TIME(current_time); + time_diff = MS_TIME_DIFF(current_time,start_time); + + /* Compute new world-stop delay total time */ + total_time = world_stopped_total_time; + divisor = world_stopped_total_divisor; + if ((int)total_time < 0 || divisor >= MAX_TOTAL_TIME_DIVISOR) { + /* Halve values if overflow occurs */ + total_time >>= 1; + divisor >>= 1; + } + total_time += time_diff < (((unsigned)-1) >> 1) ? + (unsigned)time_diff : ((unsigned)-1) >> 1; + /* Update old world_stopped_total_time and its divisor */ + world_stopped_total_time = total_time; + world_stopped_total_divisor = ++divisor; + + GC_ASSERT(divisor != 0); + GC_log_printf( + "World-stopped marking took %lu msecs (%u in average)\n", + time_diff, total_time / divisor); } # endif return(TRUE); } -/* Set all mark bits for the free list whose first entry is q */ +/* Set all mark bits for the free list whose first entry is q */ void GC_set_fl_marks(ptr_t q) { struct hblk *h, *last_h; @@ -657,9 +657,9 @@ void GC_set_fl_marks(ptr_t q) IF_PER_OBJ(sz = hhdr->hb_sz;) for (;;) { - bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz); - if (!mark_bit_from_hdr(hhdr, bit_no)) { - set_mark_bit_from_hdr(hhdr, bit_no); + bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz); + if (!mark_bit_from_hdr(hhdr, bit_no)) { + set_mark_bit_from_hdr(hhdr, bit_no); ++hhdr -> hb_n_marks; } @@ -667,34 +667,34 @@ void GC_set_fl_marks(ptr_t q) if (q == NULL) break; - h = HBLKPTR(q); - if (h != last_h) { - last_h = h; - hhdr = HDR(h); - IF_PER_OBJ(sz = hhdr->hb_sz;) - } + h = HBLKPTR(q); + if (h != last_h) { + last_h = h; + hhdr = HDR(h); + IF_PER_OBJ(sz = hhdr->hb_sz;) + } } } } #ifdef GC_ASSERTIONS -/* Check that all mark bits for the free list whose first entry is q */ -/* are set. */ +/* Check that all mark bits for the free list whose first entry is q */ +/* are set. */ void GC_check_fl_marks(ptr_t q) { ptr_t p; for (p = q; p != 0; p = obj_link(p)){ - if (!GC_is_marked(p)) { - GC_err_printf("Unmarked object %p on list %p\n", p, q); - ABORT("Unmarked local free list entry."); - } + if (!GC_is_marked(p)) { + GC_err_printf("Unmarked object %p on list %p\n", p, q); + ABORT("Unmarked local free list entry."); + } } } #endif -/* Clear all mark bits for the free list whose first entry is q */ -/* Decrement GC_bytes_found by number of bytes on free list. */ +/* Clear all mark bits for the free list whose first entry is q */ +/* Decrement GC_bytes_found by number of bytes on free list. */ STATIC void GC_clear_fl_marks(ptr_t q) { struct hblk *h, *last_h; @@ -709,31 +709,31 @@ STATIC void GC_clear_fl_marks(ptr_t q) sz = hhdr->hb_sz; /* Normally set only once. */ for (;;) { - bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz); - if (mark_bit_from_hdr(hhdr, bit_no)) { - size_t n_marks = hhdr -> hb_n_marks - 1; - clear_mark_bit_from_hdr(hhdr, bit_no); -# ifdef PARALLEL_MARK - /* Appr. count, don't decrement to zero! */ - if (0 != n_marks || !GC_parallel) { + bit_no = MARK_BIT_NO((ptr_t)q - (ptr_t)h, sz); + if (mark_bit_from_hdr(hhdr, bit_no)) { + size_t n_marks = hhdr -> hb_n_marks - 1; + clear_mark_bit_from_hdr(hhdr, bit_no); +# ifdef PARALLEL_MARK + /* Appr. count, don't decrement to zero! */ + if (0 != n_marks || !GC_parallel) { hhdr -> hb_n_marks = n_marks; - } -# else + } +# else hhdr -> hb_n_marks = n_marks; -# endif +# endif } - GC_bytes_found -= sz; + GC_bytes_found -= sz; q = obj_link(q); if (q == NULL) break; - h = HBLKPTR(q); - if (h != last_h) { - last_h = h; - hhdr = HDR(h); - sz = hhdr->hb_sz; - } + h = HBLKPTR(q); + if (h != last_h) { + last_h = h; + hhdr = HDR(h); + sz = hhdr->hb_sz; + } } } } @@ -746,8 +746,8 @@ extern void GC_check_tls(void); void GC_traverse_back_graph(void); #endif -/* Finish up a collection. Assumes mark bits are consistent, lock is */ -/* held, but the world is otherwise running. */ +/* Finish up a collection. Assumes mark bits are consistent, lock is */ +/* held, but the world is otherwise running. */ STATIC void GC_finish_collection(void) { # ifndef SMALL_CONFIG @@ -755,43 +755,43 @@ STATIC void GC_finish_collection(void) CLOCK_TYPE finalize_time = 0; CLOCK_TYPE done_time; # endif - + # if defined(GC_ASSERTIONS) && defined(THREADS) \ && defined(THREAD_LOCAL_ALLOC) && !defined(DBG_HDRS_ALL) - /* Check that we marked some of our own data. */ - /* FIXME: Add more checks. */ + /* Check that we marked some of our own data. */ + /* FIXME: Add more checks. */ GC_check_tls(); # endif # ifndef SMALL_CONFIG if (GC_print_stats) - GET_TIME(start_time); + GET_TIME(start_time); # endif GC_bytes_found = 0; # if defined(LINUX) && defined(__ELF__) && !defined(SMALL_CONFIG) - if (getenv("GC_PRINT_ADDRESS_MAP") != 0) { - GC_print_address_map(); - } + if (getenv("GC_PRINT_ADDRESS_MAP") != 0) { + GC_print_address_map(); + } # endif COND_DUMP; if (GC_find_leak) { /* Mark all objects on the free list. All objects should be */ - /* marked when we're done. */ - { - word size; /* current object size */ - unsigned kind; - ptr_t q; - - for (kind = 0; kind < GC_n_kinds; kind++) { - for (size = 1; size <= MAXOBJGRANULES; size++) { - q = GC_obj_kinds[kind].ok_freelist[size]; - if (q != 0) GC_set_fl_marks(q); - } - } - } - GC_start_reclaim(TRUE); - /* The above just checks; it doesn't really reclaim anything. */ + /* marked when we're done. */ + { + word size; /* current object size */ + unsigned kind; + ptr_t q; + + for (kind = 0; kind < GC_n_kinds; kind++) { + for (size = 1; size <= MAXOBJGRANULES; size++) { + q = GC_obj_kinds[kind].ok_freelist[size]; + if (q != 0) GC_set_fl_marks(q); + } + } + } + GC_start_reclaim(TRUE); + /* The above just checks; it doesn't really reclaim anything. */ } GC_finalize(); @@ -801,72 +801,72 @@ STATIC void GC_finish_collection(void) # ifndef SMALL_CONFIG if (GC_print_stats) - GET_TIME(finalize_time); + GET_TIME(finalize_time); # endif if (GC_print_back_height) { # ifdef MAKE_BACK_GRAPH - GC_traverse_back_graph(); + GC_traverse_back_graph(); # else -# ifndef SMALL_CONFIG - GC_err_printf("Back height not available: " - "Rebuild collector with -DMAKE_BACK_GRAPH\n"); -# endif +# ifndef SMALL_CONFIG + GC_err_printf("Back height not available: " + "Rebuild collector with -DMAKE_BACK_GRAPH\n"); +# endif # endif } /* Clear free list mark bits, in case they got accidentally marked */ - /* (or GC_find_leak is set and they were intentionally marked). */ + /* (or GC_find_leak is set and they were intentionally marked). */ /* Also subtract memory remaining from GC_bytes_found count. */ /* Note that composite objects on free list are cleared. */ /* Thus accidentally marking a free list is not a problem; only */ /* objects on the list itself will be marked, and that's fixed here. */ { - word size; /* current object size */ - ptr_t q; /* pointer to current object */ - unsigned kind; - - for (kind = 0; kind < GC_n_kinds; kind++) { - for (size = 1; size <= MAXOBJGRANULES; size++) { - q = GC_obj_kinds[kind].ok_freelist[size]; - if (q != 0) GC_clear_fl_marks(q); - } - } + word size; /* current object size */ + ptr_t q; /* pointer to current object */ + unsigned kind; + + for (kind = 0; kind < GC_n_kinds; kind++) { + for (size = 1; size <= MAXOBJGRANULES; size++) { + q = GC_obj_kinds[kind].ok_freelist[size]; + if (q != 0) GC_clear_fl_marks(q); + } + } } if (GC_print_stats == VERBOSE) - GC_log_printf("Bytes recovered before sweep - f.l. count = %ld\n", - (long)GC_bytes_found); - + GC_log_printf("Bytes recovered before sweep - f.l. count = %ld\n", + (long)GC_bytes_found); + /* Reconstruct free lists to contain everything not marked */ GC_start_reclaim(FALSE); - if (GC_print_stats) { - GC_log_printf("Heap contains %lu pointer-containing " - "+ %lu pointer-free reachable bytes\n", - (unsigned long)GC_composite_in_use, - (unsigned long)GC_atomic_in_use); - } + if (GC_print_stats) { + GC_log_printf("Heap contains %lu pointer-containing " + "+ %lu pointer-free reachable bytes\n", + (unsigned long)GC_composite_in_use, + (unsigned long)GC_atomic_in_use); + } if (GC_is_full_gc) { - GC_used_heap_size_after_full = USED_HEAP_SIZE; - GC_need_full_gc = FALSE; - } else { - GC_need_full_gc = - USED_HEAP_SIZE - GC_used_heap_size_after_full - > min_bytes_allocd(); - } + GC_used_heap_size_after_full = USED_HEAP_SIZE; + GC_need_full_gc = FALSE; + } else { + GC_need_full_gc = + USED_HEAP_SIZE - GC_used_heap_size_after_full + > min_bytes_allocd(); + } if (GC_print_stats == VERBOSE) { -# ifdef USE_MUNMAP - GC_log_printf("Immediately reclaimed %ld bytes in heap" - " of size %lu bytes (%lu unmapped)\n", - (long)GC_bytes_found, (unsigned long)GC_heapsize, - (unsigned long)GC_unmapped_bytes); -# else - GC_log_printf("Immediately reclaimed %ld bytes in heap" - " of size %lu bytes\n", - (long)GC_bytes_found, (unsigned long)GC_heapsize); -# endif +# ifdef USE_MUNMAP + GC_log_printf("Immediately reclaimed %ld bytes in heap" + " of size %lu bytes (%lu unmapped)\n", + (long)GC_bytes_found, (unsigned long)GC_heapsize, + (unsigned long)GC_unmapped_bytes); +# else + GC_log_printf("Immediately reclaimed %ld bytes in heap" + " of size %lu bytes\n", + (long)GC_bytes_found, (unsigned long)GC_heapsize); +# endif } /* Reset or increment counters for next cycle */ @@ -878,21 +878,21 @@ STATIC void GC_finish_collection(void) GC_bytes_dropped = 0; GC_bytes_freed = 0; GC_finalizer_bytes_freed = 0; - + # ifdef USE_MUNMAP GC_unmap_old(); # endif # ifndef SMALL_CONFIG if (GC_print_stats) { - GET_TIME(done_time); + GET_TIME(done_time); - /* A convenient place to output finalization statistics. */ - GC_print_finalization_stats(); + /* A convenient place to output finalization statistics. */ + GC_print_finalization_stats(); - GC_log_printf("Finalize + initiate sweep took %lu + %lu msecs\n", - MS_TIME_DIFF(finalize_time,start_time), - MS_TIME_DIFF(done_time,finalize_time)); + GC_log_printf("Finalize + initiate sweep took %lu + %lu msecs\n", + MS_TIME_DIFF(finalize_time,start_time), + MS_TIME_DIFF(done_time,finalize_time)); } # endif } @@ -911,7 +911,7 @@ GC_API int GC_CALL GC_try_to_collect(GC_stop_func stop_func) # endif IF_CANCEL(int cancel_state;) DCL_LOCK_STATE; - + if (!GC_is_initialized) GC_init(); GC_ASSERT(stop_func != 0); if (GC_debugging_started) GC_print_all_smashed(); @@ -946,21 +946,21 @@ GC_API void GC_CALL GC_gcollect(void) if (GC_have_errors) GC_print_all_errors(); } -word GC_n_heap_sects = 0; /* Number of sections currently in heap. */ +word GC_n_heap_sects = 0; /* Number of sections currently in heap. */ #ifdef USE_PROC_FOR_LIBRARIES - word GC_n_memory = 0; /* Number of GET_MEM allocated memory */ - /* sections. */ + word GC_n_memory = 0; /* Number of GET_MEM allocated memory */ + /* sections. */ #endif #ifdef USE_PROC_FOR_LIBRARIES /* Add HBLKSIZE aligned, GET_MEM-generated block to GC_our_memory. */ - /* Defined to do nothing if USE_PROC_FOR_LIBRARIES not set. */ + /* Defined to do nothing if USE_PROC_FOR_LIBRARIES not set. */ void GC_add_to_our_memory(ptr_t p, size_t bytes) { if (0 == p) return; if (GC_n_memory >= MAX_HEAP_SECTS) - ABORT("Too many GC-allocated memory sections: Increase MAX_HEAP_SECTS"); + ABORT("Too many GC-allocated memory sections: Increase MAX_HEAP_SECTS"); GC_our_memory[GC_n_memory].hs_start = p; GC_our_memory[GC_n_memory].hs_bytes = bytes; GC_n_memory++; @@ -974,29 +974,29 @@ void GC_add_to_heap(struct hblk *p, size_t bytes) { hdr * phdr; word endp; - + if (GC_n_heap_sects >= MAX_HEAP_SECTS) { - ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS"); + ABORT("Too many heap sections: Increase MAXHINCR or MAX_HEAP_SECTS"); } while ((word)p <= HBLKSIZE) { /* Can't handle memory near address zero. */ ++p; - bytes -= HBLKSIZE; + bytes -= HBLKSIZE; if (0 == bytes) return; } endp = (word)p + bytes; if (endp <= (word)p) { - /* Address wrapped. */ - bytes -= HBLKSIZE; + /* Address wrapped. */ + bytes -= HBLKSIZE; if (0 == bytes) return; - endp -= HBLKSIZE; + endp -= HBLKSIZE; } phdr = GC_install_header(p); if (0 == phdr) { - /* This is extremely unlikely. Can't add it. This will */ - /* almost certainly result in a 0 return from the allocator, */ - /* which is entirely appropriate. */ - return; + /* This is extremely unlikely. Can't add it. This will */ + /* almost certainly result in a 0 return from the allocator, */ + /* which is entirely appropriate. */ + return; } GC_ASSERT(endp > (word)p && endp == (word)p + bytes); GC_heap_sects[GC_n_heap_sects].hs_start = (ptr_t)p; @@ -1009,10 +1009,10 @@ void GC_add_to_heap(struct hblk *p, size_t bytes) if ((ptr_t)p <= (ptr_t)GC_least_plausible_heap_addr || GC_least_plausible_heap_addr == 0) { GC_least_plausible_heap_addr = (void *)((ptr_t)p - sizeof(word)); - /* Making it a little smaller than necessary prevents */ - /* us from getting a false hit from the variable */ - /* itself. There's some unintentional reflection */ - /* here. */ + /* Making it a little smaller than necessary prevents */ + /* us from getting a false hit from the variable */ + /* itself. There's some unintentional reflection */ + /* here. */ } if ((ptr_t)p + bytes >= (ptr_t)GC_greatest_plausible_heap_addr) { GC_greatest_plausible_heap_addr = (void *)endp; @@ -1023,20 +1023,20 @@ void GC_add_to_heap(struct hblk *p, size_t bytes) void GC_print_heap_sects(void) { unsigned i; - + GC_printf("Total heap size: %lu\n", (unsigned long) GC_heapsize); for (i = 0; i < GC_n_heap_sects; i++) { ptr_t start = GC_heap_sects[i].hs_start; size_t len = GC_heap_sects[i].hs_bytes; struct hblk *h; unsigned nbl = 0; - - for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) { - if (GC_is_black_listed(h, HBLKSIZE)) nbl++; - } - GC_printf("Section %d from %p to %p %lu/%lu blacklisted\n", - i, start, start + len, - (unsigned long)nbl, (unsigned long)(len/HBLKSIZE)); + + for (h = (struct hblk *)start; h < (struct hblk *)(start + len); h++) { + if (GC_is_black_listed(h, HBLKSIZE)) nbl++; + } + GC_printf("Section %d from %p to %p %lu/%lu blacklisted\n", + i, start, start + len, + (unsigned long)nbl, (unsigned long)(len/HBLKSIZE)); } } # endif @@ -1072,18 +1072,18 @@ GC_bool GC_expand_hp_inner(word n) { word bytes; struct hblk * space; - word expansion_slop; /* Number of bytes by which we expect the */ - /* heap to expand soon. */ + word expansion_slop; /* Number of bytes by which we expect the */ + /* heap to expand soon. */ if (n < MINHINCR) n = MINHINCR; bytes = n * HBLKSIZE; /* Make sure bytes is a multiple of GC_page_size */ { - word mask = GC_page_size - 1; - bytes += mask; - bytes &= ~mask; + word mask = GC_page_size - 1; + bytes += mask; + bytes &= ~mask; } - + if (GC_max_heapsize != 0 && GC_heapsize + bytes > GC_max_heapsize) { /* Exceeded self-imposed limit */ return(FALSE); @@ -1091,38 +1091,38 @@ GC_bool GC_expand_hp_inner(word n) space = GET_MEM(bytes); GC_add_to_our_memory((ptr_t)space, bytes); if( space == 0 ) { - if (GC_print_stats) { - GC_log_printf("Failed to expand heap by %ld bytes\n", - (unsigned long)bytes); - } - return(FALSE); + if (GC_print_stats) { + GC_log_printf("Failed to expand heap by %ld bytes\n", + (unsigned long)bytes); + } + return(FALSE); } if (GC_print_stats) { - GC_log_printf("Increasing heap size by %lu after %lu allocated bytes\n", - (unsigned long)bytes, - (unsigned long)GC_bytes_allocd); + GC_log_printf("Increasing heap size by %lu after %lu allocated bytes\n", + (unsigned long)bytes, + (unsigned long)GC_bytes_allocd); } - /* Adjust heap limits generously for blacklisting to work better. */ - /* GC_add_to_heap performs minimal adjustment needed for */ - /* correctness. */ + /* Adjust heap limits generously for blacklisting to work better. */ + /* GC_add_to_heap performs minimal adjustment needed for */ + /* correctness. */ expansion_slop = min_bytes_allocd() + 4*MAXHINCR*HBLKSIZE; if ((GC_last_heap_addr == 0 && !((word)space & SIGNB)) || (GC_last_heap_addr != 0 && GC_last_heap_addr < (ptr_t)space)) { /* Assume the heap is growing up */ - word new_limit = (word)space + bytes + expansion_slop; - if (new_limit > (word)space) { + word new_limit = (word)space + bytes + expansion_slop; + if (new_limit > (word)space) { GC_greatest_plausible_heap_addr = (void *)GC_max((word)GC_greatest_plausible_heap_addr, (word)new_limit); - } + } } else { /* Heap is growing down */ - word new_limit = (word)space - expansion_slop; - if (new_limit < (word)space) { + word new_limit = (word)space - expansion_slop; + if (new_limit < (word)space) { GC_least_plausible_heap_addr = (void *)GC_min((word)GC_least_plausible_heap_addr, (word)space - expansion_slop); - } + } } GC_prev_heap_addr = GC_last_heap_addr; GC_last_heap_addr = (ptr_t)space; @@ -1138,12 +1138,12 @@ GC_bool GC_expand_hp_inner(word n) } /* Really returns a bool, but it's externally visible, so that's clumsy. */ -/* Arguments is in bytes. Includes GC_init() call. */ +/* Arguments is in bytes. Includes GC_init() call. */ GC_API int GC_CALL GC_expand_hp(size_t bytes) { int result; DCL_LOCK_STATE; - + LOCK(); if (!GC_is_initialized) GC_init(); result = (int)GC_expand_hp_inner(divHBLKSZ((word)bytes)); @@ -1152,9 +1152,9 @@ GC_API int GC_CALL GC_expand_hp(size_t bytes) return(result); } -unsigned GC_fail_count = 0; - /* How many consecutive GC/expansion failures? */ - /* Reset by GC_allochblk. */ +unsigned GC_fail_count = 0; + /* How many consecutive GC/expansion failures? */ + /* Reset by GC_allochblk. */ GC_bool GC_collect_or_expand(word needed_blocks, GC_bool ignore_off_page) { @@ -1163,26 +1163,26 @@ GC_bool GC_collect_or_expand(word needed_blocks, GC_bool ignore_off_page) DISABLE_CANCEL(cancel_state); if (GC_incremental || GC_dont_gc || - ((!GC_dont_expand || GC_bytes_allocd == 0) && !GC_should_collect()) || - (gc_not_stopped = GC_try_to_collect_inner(GC_bytes_allocd > 0 ? - GC_default_stop_func : - GC_never_stop_func)) == FALSE) { + ((!GC_dont_expand || GC_bytes_allocd == 0) && !GC_should_collect()) || + (gc_not_stopped = GC_try_to_collect_inner(GC_bytes_allocd > 0 ? + GC_default_stop_func : + GC_never_stop_func)) == FALSE) { word blocks_to_get = GC_heapsize/(HBLKSIZE*GC_free_space_divisor) - + needed_blocks; - + + needed_blocks; + if (blocks_to_get > MAXHINCR) { word slop; - - /* Get the minimum required to make it likely that we */ - /* can satisfy the current request in the presence of black- */ - /* listing. This will probably be more than MAXHINCR. */ + + /* Get the minimum required to make it likely that we */ + /* can satisfy the current request in the presence of black- */ + /* listing. This will probably be more than MAXHINCR. */ if (ignore_off_page) { slop = 4; } else { - slop = 2*divHBLKSZ(BL_LIMIT); - if (slop > needed_blocks) slop = needed_blocks; - } + slop = 2*divHBLKSZ(BL_LIMIT); + if (slop > needed_blocks) slop = needed_blocks; + } if (needed_blocks + slop > MAXHINCR) { blocks_to_get = needed_blocks + slop; } else { @@ -1192,25 +1192,25 @@ GC_bool GC_collect_or_expand(word needed_blocks, GC_bool ignore_off_page) if (!GC_expand_hp_inner(blocks_to_get) && !GC_expand_hp_inner(needed_blocks)) { if (gc_not_stopped == FALSE) { - /* Don't increment GC_fail_count here (and no warning). */ - GC_gcollect_inner(); - GC_ASSERT(GC_bytes_allocd == 0); - } else if (GC_fail_count++ < GC_max_retries) { - WARN("Out of Memory! Trying to continue ...\n", 0); - GC_gcollect_inner(); - } else { -# if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC) + /* Don't increment GC_fail_count here (and no warning). */ + GC_gcollect_inner(); + GC_ASSERT(GC_bytes_allocd == 0); + } else if (GC_fail_count++ < GC_max_retries) { + WARN("Out of Memory! Trying to continue ...\n", 0); + GC_gcollect_inner(); + } else { +# if !defined(AMIGA) || !defined(GC_AMIGA_FASTALLOC) WARN("Out of Memory! Heap size: %" GC_PRIdPTR " MiB." " Returning NIL!\n", (GC_heapsize - GC_unmapped_bytes) >> 20); -# endif - RESTORE_CANCEL(cancel_state); - return(FALSE); - } +# endif + RESTORE_CANCEL(cancel_state); + return(FALSE); + } } else { if (GC_fail_count && GC_print_stats) { - GC_printf("Memory available again ...\n"); - } + GC_printf("Memory available again ...\n"); + } } } RESTORE_CANCEL(cancel_state); @@ -1227,7 +1227,7 @@ ptr_t GC_allocobj(size_t gran, int kind) { void ** flh = &(GC_obj_kinds[kind].ok_freelist[gran]); GC_bool tried_minor = FALSE; - + if (gran == 0) return(0); while (*flh == 0) { @@ -1242,21 +1242,21 @@ ptr_t GC_allocobj(size_t gran, int kind) } if (*flh == 0) { ENTER_GC(); - if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED - && ! tried_minor ) { - GC_collect_a_little_inner(1); - tried_minor = TRUE; - } else { + if (GC_incremental && GC_time_limit == GC_TIME_UNLIMITED + && ! tried_minor ) { + GC_collect_a_little_inner(1); + tried_minor = TRUE; + } else { if (!GC_collect_or_expand((word)1,FALSE)) { - EXIT_GC(); - return(0); - } - } - EXIT_GC(); + EXIT_GC(); + return(0); + } + } + EXIT_GC(); } } - /* Successful allocation; reset failure count. */ + /* Successful allocation; reset failure count. */ GC_fail_count = 0; - + return(*flh); } diff --git a/include/private/gc_priv.h b/include/private/gc_priv.h index 1f4dbb2..78fcbe5 100644 --- a/include/private/gc_priv.h +++ b/include/private/gc_priv.h @@ -2153,7 +2153,7 @@ extern void GC_reset_fault_handler(void); # if defined(CANCEL_SAFE) # if defined(GC_ASSERTIONS) && (defined(USE_COMPILER_TLS) \ || (defined(LINUX) && !defined(ARM32) \ - && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) \ + && (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 3)) \ || defined(HPUX) /* and probably others ... */)) extern __thread unsigned char GC_cancel_disable_count; # define NEED_CANCEL_DISABLE_COUNT @@ -2173,7 +2173,7 @@ extern void GC_reset_fault_handler(void); pthread_setcancelstate(state, NULL); \ DECR_CANCEL_DISABLE(); } # else /* !CANCEL_SAFE */ -# define DISABLE_CANCEL(state) +# define DISABLE_CANCEL(state) # define RESTORE_CANCEL(state) # define ASSERT_CANCEL_DISABLED() # endif /* !CANCEL_SAFE */ diff --git a/include/private/gcconfig.h b/include/private/gcconfig.h index 69bec44..f9db883 100644 --- a/include/private/gcconfig.h +++ b/include/private/gcconfig.h @@ -2231,18 +2231,18 @@ # endif # if defined(UNIX_LIKE) && defined(THREADS) && !defined(NO_CANCEL_SAFE) - /* Make the code cancellation-safe. This basically means that we */ - /* ensure that cancellation requests are ignored while we are in */ + /* Make the code cancellation-safe. This basically means that we */ + /* ensure that cancellation requests are ignored while we are in */ /* the collector. This applies only to Posix deferred cancellation;*/ - /* we don't handle Posix asynchronous cancellation. */ - /* Note that this only works if pthread_setcancelstate is */ - /* async-signal-safe, at least in the absence of asynchronous */ - /* cancellation. This appears to be true for the glibc version, */ - /* though it is not documented. Without that assumption, there */ - /* seems to be no way to safely wait in a signal handler, which */ - /* we need to do for thread suspension. */ + /* we don't handle Posix asynchronous cancellation. */ + /* Note that this only works if pthread_setcancelstate is */ + /* async-signal-safe, at least in the absence of asynchronous */ + /* cancellation. This appears to be true for the glibc version, */ + /* though it is not documented. Without that assumption, there */ + /* seems to be no way to safely wait in a signal handler, which */ + /* we need to do for thread suspension. */ /* Also note that little other code appears to be cancellation-safe.*/ - /* Hence it may make sense to turn this off for performance. */ + /* Hence it may make sense to turn this off for performance. */ # define CANCEL_SAFE # define IF_CANCEL(x) x # else diff --git a/misc.c b/misc.c index 6db7dbd..c31503b 100644 --- a/misc.c +++ b/misc.c @@ -1,4 +1,4 @@ -/* +/* * Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers * Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved. * Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved. @@ -19,7 +19,7 @@ #include #include -#define I_HIDE_POINTERS /* To make GC_call_with_alloc_lock visible */ +#define I_HIDE_POINTERS /* To make GC_call_with_alloc_lock visible */ #include "private/gc_pmark.h" #ifndef MSWINCE @@ -40,7 +40,7 @@ # include # include - int GC_log; /* Forward decl, so we can set it. */ + int GC_log; /* Forward decl, so we can set it. */ #endif #ifdef NONSTOP @@ -51,11 +51,11 @@ # include "il/PCR_IL.h" PCR_Th_ML GC_allocate_ml; #endif -/* For other platforms with threads, the lock and possibly */ -/* GC_lock_holder variables are defined in the thread support code. */ +/* For other platforms with threads, the lock and possibly */ +/* GC_lock_holder variables are defined in the thread support code. */ -/* Dont unnecessarily call GC_register_main_static_data() in case */ -/* dyn_load.c isn't linked in. */ +/* Dont unnecessarily call GC_register_main_static_data() in case */ +/* dyn_load.c isn't linked in. */ #ifdef DYNAMIC_LOADING # define GC_REGISTER_MAIN_STATIC_DATA() GC_register_main_static_data() #else @@ -70,7 +70,7 @@ GC_FAR struct _GC_arrays GC_arrays /* = { 0 } */; GC_bool GC_debugging_started = FALSE; - /* defined here so we don't have to load debug_malloc.o */ + /* defined here so we don't have to load debug_malloc.o */ void (*GC_check_heap) (void) = (void (*) (void))0; void (*GC_print_all_smashed) (void) = (void (*) (void))0; @@ -100,8 +100,8 @@ GC_bool GC_print_back_height = 0; #endif #ifdef KEEP_BACK_PTRS - long GC_backtraces = 0; /* Number of random backtraces to */ - /* generate for each GC. */ + long GC_backtraces = 0; /* Number of random backtraces to */ + /* generate for each GC. */ #endif #ifdef FIND_LEAK @@ -125,10 +125,10 @@ GC_bool GC_print_back_height = 0; #endif long GC_large_alloc_warn_interval = 5; - /* Interval between unsuppressed warnings. */ + /* Interval between unsuppressed warnings. */ long GC_large_alloc_warn_suppressed = 0; - /* Number of warnings suppressed so far. */ + /* Number of warnings suppressed so far. */ /*ARGSUSED*/ STATIC void * GC_CALLBACK GC_default_oom_fn(size_t bytes_requested) @@ -136,49 +136,49 @@ STATIC void * GC_CALLBACK GC_default_oom_fn(size_t bytes_requested) return(0); } -/* All accesses to it should be synchronized to avoid data races. */ +/* All accesses to it should be synchronized to avoid data races. */ GC_oom_func GC_oom_fn = GC_default_oom_fn; -/* Set things up so that GC_size_map[i] >= granules(i), */ -/* but not too much bigger */ -/* and so that size_map contains relatively few distinct entries */ -/* This was originally stolen from Russ Atkinson's Cedar */ -/* quantization algorithm (but we precompute it). */ +/* Set things up so that GC_size_map[i] >= granules(i), */ +/* but not too much bigger */ +/* and so that size_map contains relatively few distinct entries */ +/* This was originally stolen from Russ Atkinson's Cedar */ +/* quantization algorithm (but we precompute it). */ STATIC void GC_init_size_map(void) { int i; - /* Map size 0 to something bigger. */ - /* This avoids problems at lower levels. */ + /* Map size 0 to something bigger. */ + /* This avoids problems at lower levels. */ GC_size_map[0] = 1; for (i = 1; i <= GRANULES_TO_BYTES(TINY_FREELISTS-1) - EXTRA_BYTES; i++) { GC_size_map[i] = ROUNDED_UP_GRANULES(i); # ifndef _MSC_VER GC_ASSERT(GC_size_map[i] < TINY_FREELISTS); - /* Seems to tickle bug in VC++ 2008 for AMD64 */ -# endif + /* Seems to tickle bug in VC++ 2008 for AMD64 */ +# endif } /* We leave the rest of the array to be filled in on demand. */ } /* Fill in additional entries in GC_size_map, including the ith one */ -/* We assume the ith entry is currently 0. */ +/* We assume the ith entry is currently 0. */ /* Note that a filled in section of the array ending at n always */ -/* has length at least n/4. */ +/* has length at least n/4. */ void GC_extend_size_map(size_t i) { size_t orig_granule_sz = ROUNDED_UP_GRANULES(i); size_t granule_sz = orig_granule_sz; size_t byte_sz = GRANULES_TO_BYTES(granule_sz); - /* The size we try to preserve. */ - /* Close to i, unless this would */ - /* introduce too many distinct sizes. */ + /* The size we try to preserve. */ + /* Close to i, unless this would */ + /* introduce too many distinct sizes. */ size_t smaller_than_i = byte_sz - (byte_sz >> 3); size_t much_smaller_than_i = byte_sz - (byte_sz >> 2); - size_t low_limit; /* The lowest indexed entry we */ - /* initialize. */ + size_t low_limit; /* The lowest indexed entry we */ + /* initialize. */ size_t j; - + if (GC_size_map[smaller_than_i] == 0) { low_limit = much_smaller_than_i; while (GC_size_map[low_limit] != 0) low_limit++; @@ -189,27 +189,27 @@ void GC_extend_size_map(size_t i) granule_sz += granule_sz >> 3; if (granule_sz < orig_granule_sz) granule_sz = orig_granule_sz; } - /* For these larger sizes, we use an even number of granules. */ - /* This makes it easier to, for example, construct a 16byte-aligned */ - /* allocator even if GRANULE_BYTES is 8. */ + /* For these larger sizes, we use an even number of granules. */ + /* This makes it easier to, for example, construct a 16byte-aligned */ + /* allocator even if GRANULE_BYTES is 8. */ granule_sz += 1; granule_sz &= ~1; if (granule_sz > MAXOBJGRANULES) { granule_sz = MAXOBJGRANULES; } - /* If we can fit the same number of larger objects in a block, */ - /* do so. */ + /* If we can fit the same number of larger objects in a block, */ + /* do so. */ { size_t number_of_objs = HBLK_GRANULES/granule_sz; granule_sz = HBLK_GRANULES/number_of_objs; - granule_sz &= ~1; + granule_sz &= ~1; } byte_sz = GRANULES_TO_BYTES(granule_sz); - /* We may need one extra byte; */ - /* don't always fill in GC_size_map[byte_sz] */ + /* We may need one extra byte; */ + /* don't always fill in GC_size_map[byte_sz] */ byte_sz -= EXTRA_BYTES; - for (j = low_limit; j <= byte_sz; j++) GC_size_map[j] = granule_sz; + for (j = low_limit; j <= byte_sz; j++) GC_size_map[j] = granule_sz; } @@ -222,15 +222,15 @@ void GC_extend_size_map(size_t i) * sections of the stack whenever we get control. */ # ifdef THREADS -# define BIG_CLEAR_SIZE 2048 /* Clear this much now and then. */ -# define SMALL_CLEAR_SIZE 256 /* Clear this much every time. */ +# define BIG_CLEAR_SIZE 2048 /* Clear this much now and then. */ +# define SMALL_CLEAR_SIZE 256 /* Clear this much every time. */ # else STATIC word GC_stack_last_cleared = 0; /* GC_no when we last did this */ - STATIC ptr_t GC_min_sp; /* Coolest stack pointer value from which */ - /* we've already cleared the stack. */ + STATIC ptr_t GC_min_sp; /* Coolest stack pointer value from which */ + /* we've already cleared the stack. */ STATIC ptr_t GC_high_water; - /* "hottest" stack pointer value we have seen */ - /* recently. Degrades over time. */ + /* "hottest" stack pointer value we have seen */ + /* recently. Degrades over time. */ STATIC word GC_bytes_allocd_at_reset; # define DEGRADE_RATE 50 # endif @@ -239,65 +239,65 @@ void GC_extend_size_map(size_t i) #if defined(ASM_CLEAR_CODE) extern void *GC_clear_stack_inner(void *, ptr_t); -#else +#else /* Clear the stack up to about limit. Return arg. */ /*ARGSUSED*/ void * GC_clear_stack_inner(void *arg, ptr_t limit) { word dummy[CLEAR_SIZE]; - + BZERO(dummy, CLEAR_SIZE*sizeof(word)); if ((ptr_t)(dummy) COOLER_THAN limit) { (void) GC_clear_stack_inner(arg, limit); } - /* Make sure the recursive call is not a tail call, and the bzero */ - /* call is not recognized as dead code. */ + /* Make sure the recursive call is not a tail call, and the bzero */ + /* call is not recognized as dead code. */ GC_noop1((word)dummy); return(arg); } #endif -/* Clear some of the inaccessible part of the stack. Returns its */ +/* Clear some of the inaccessible part of the stack. Returns its */ /* argument, so it can be used in a tail call position, hence clearing */ -/* another frame. */ +/* another frame. */ void * GC_clear_stack(void *arg) { ptr_t sp = GC_approx_sp(); /* Hotter than actual sp */ # ifdef THREADS word dummy[SMALL_CLEAR_SIZE]; - static unsigned random_no = 0; - /* Should be more random than it is ... */ - /* Used to occasionally clear a bigger */ - /* chunk. */ + static unsigned random_no = 0; + /* Should be more random than it is ... */ + /* Used to occasionally clear a bigger */ + /* chunk. */ # endif ptr_t limit; - + # define SLOP 400 - /* Extra bytes we clear every time. This clears our own */ - /* activation record, and should cause more frequent */ - /* clearing near the cold end of the stack, a good thing. */ + /* Extra bytes we clear every time. This clears our own */ + /* activation record, and should cause more frequent */ + /* clearing near the cold end of the stack, a good thing. */ # define GC_SLOP 4000 - /* We make GC_high_water this much hotter than we really saw */ - /* saw it, to cover for GC noise etc. above our current frame. */ + /* We make GC_high_water this much hotter than we really saw */ + /* saw it, to cover for GC noise etc. above our current frame. */ # define CLEAR_THRESHOLD 100000 - /* We restart the clearing process after this many bytes of */ - /* allocation. Otherwise very heavily recursive programs */ - /* with sparse stacks may result in heaps that grow almost */ - /* without bounds. As the heap gets larger, collection */ - /* frequency decreases, thus clearing frequency would decrease, */ - /* thus more junk remains accessible, thus the heap gets */ - /* larger ... */ + /* We restart the clearing process after this many bytes of */ + /* allocation. Otherwise very heavily recursive programs */ + /* with sparse stacks may result in heaps that grow almost */ + /* without bounds. As the heap gets larger, collection */ + /* frequency decreases, thus clearing frequency would decrease, */ + /* thus more junk remains accessible, thus the heap gets */ + /* larger ... */ # ifdef THREADS if (++random_no % 13 == 0) { - limit = sp; - MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word)); - limit = (ptr_t)((word)limit & ~0xf); - /* Make it sufficiently aligned for assembly */ - /* implementations of GC_clear_stack_inner. */ - return GC_clear_stack_inner(arg, limit); + limit = sp; + MAKE_HOTTER(limit, BIG_CLEAR_SIZE*sizeof(word)); + limit = (ptr_t)((word)limit & ~0xf); + /* Make it sufficiently aligned for assembly */ + /* implementations of GC_clear_stack_inner. */ + return GC_clear_stack_inner(arg, limit); } else { - BZERO(dummy, SMALL_CLEAR_SIZE*sizeof(word)); - return arg; + BZERO(dummy, SMALL_CLEAR_SIZE*sizeof(word)); + return arg; } # else if (GC_gc_no > GC_stack_last_cleared) { @@ -317,24 +317,24 @@ void * GC_clear_stack(void *arg) MAKE_HOTTER(limit, SLOP); if (sp COOLER_THAN limit) { limit = (ptr_t)((word)limit & ~0xf); - /* Make it sufficiently aligned for assembly */ - /* implementations of GC_clear_stack_inner. */ + /* Make it sufficiently aligned for assembly */ + /* implementations of GC_clear_stack_inner. */ GC_min_sp = sp; return(GC_clear_stack_inner(arg, limit)); } else if (GC_bytes_allocd - GC_bytes_allocd_at_reset > CLEAR_THRESHOLD) { - /* Restart clearing process, but limit how much clearing we do. */ - GC_min_sp = sp; - MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4); - if (GC_min_sp HOTTER_THAN GC_high_water) GC_min_sp = GC_high_water; - GC_bytes_allocd_at_reset = GC_bytes_allocd; - } + /* Restart clearing process, but limit how much clearing we do. */ + GC_min_sp = sp; + MAKE_HOTTER(GC_min_sp, CLEAR_THRESHOLD/4); + if (GC_min_sp HOTTER_THAN GC_high_water) GC_min_sp = GC_high_water; + GC_bytes_allocd_at_reset = GC_bytes_allocd; + } return(arg); # endif } -/* Return a pointer to the base address of p, given a pointer to a */ -/* an address within an object. Return 0 o.w. */ +/* Return a pointer to the base address of p, given a pointer to a */ +/* an address within an object. Return 0 o.w. */ GC_API void * GC_CALL GC_base(void * p) { ptr_t r; @@ -342,46 +342,46 @@ GC_API void * GC_CALL GC_base(void * p) bottom_index *bi; hdr *candidate_hdr; ptr_t limit; - + r = p; if (!GC_is_initialized) return 0; h = HBLKPTR(r); GET_BI(r, bi); candidate_hdr = HDR_FROM_BI(bi, r); if (candidate_hdr == 0) return(0); - /* If it's a pointer to the middle of a large object, move it */ - /* to the beginning. */ - while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) { - h = FORWARDED_ADDR(h,candidate_hdr); - r = (ptr_t)h; - candidate_hdr = HDR(h); - } + /* If it's a pointer to the middle of a large object, move it */ + /* to the beginning. */ + while (IS_FORWARDING_ADDR_OR_NIL(candidate_hdr)) { + h = FORWARDED_ADDR(h,candidate_hdr); + r = (ptr_t)h; + candidate_hdr = HDR(h); + } if (HBLK_IS_FREE(candidate_hdr)) return(0); /* Make sure r points to the beginning of the object */ - r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1)); + r = (ptr_t)((word)r & ~(WORDS_TO_BYTES(1) - 1)); { - size_t offset = HBLKDISPL(r); - signed_word sz = candidate_hdr -> hb_sz; - size_t obj_displ = offset % sz; + size_t offset = HBLKDISPL(r); + signed_word sz = candidate_hdr -> hb_sz; + size_t obj_displ = offset % sz; - r -= obj_displ; + r -= obj_displ; limit = r + sz; - if (limit > (ptr_t)(h + 1) && sz <= HBLKSIZE) { - return(0); - } - if ((ptr_t)p >= limit) return(0); - } + if (limit > (ptr_t)(h + 1) && sz <= HBLKSIZE) { + return(0); + } + if ((ptr_t)p >= limit) return(0); + } return((void *)r); } -/* Return the size of an object, given a pointer to its base. */ -/* (For small objects this also happens to work from interior pointers, */ -/* but that shouldn't be relied upon.) */ +/* Return the size of an object, given a pointer to its base. */ +/* (For small objects this also happens to work from interior pointers, */ +/* but that shouldn't be relied upon.) */ GC_API size_t GC_CALL GC_size(const void * p) { hdr * hhdr = HDR(p); - + return hhdr -> hb_sz; } @@ -390,8 +390,8 @@ GC_API size_t GC_CALL GC_get_heap_size(void) size_t value; DCL_LOCK_STATE; LOCK(); - /* ignore the memory space returned to OS (i.e. count only the */ - /* space owned by the garbage collector) */ + /* ignore the memory space returned to OS (i.e. count only the */ + /* space owned by the garbage collector) */ value = (size_t)(GC_heapsize - GC_unmapped_bytes); UNLOCK(); return value; @@ -408,8 +408,8 @@ GC_API size_t GC_CALL GC_get_free_bytes(void) return value; } -/* The _inner versions assume the caller holds the allocation lock. */ -/* Declared in gc_mark.h (where other public "inner" functions reside). */ +/* The _inner versions assume the caller holds the allocation lock. */ +/* Declared in gc_mark.h (where other public "inner" functions reside). */ GC_API size_t GC_CALL GC_get_heap_size_inner(void) { return (size_t)(GC_heapsize - GC_unmapped_bytes); @@ -493,8 +493,8 @@ static GC_bool installed_looping_handler = FALSE; static void maybe_install_looping_handler(void) { - /* Install looping handler before the write fault handler, so we */ - /* handle write faults correctly. */ + /* Install looping handler before the write fault handler, so we */ + /* handle write faults correctly. */ if (!installed_looping_handler && 0 != GETENV("GC_LOOP_ON_ABORT")) { GC_set_and_save_fault_handler(looping_handler); installed_looping_handler = TRUE; @@ -523,21 +523,21 @@ GC_API void GC_CALL GC_init(void) # endif # ifdef GC_INITIAL_HEAP_SIZE - word initial_heap_sz = divHBLKSZ(GC_INITIAL_HEAP_SIZE); + word initial_heap_sz = divHBLKSZ(GC_INITIAL_HEAP_SIZE); # else - word initial_heap_sz = (word)MINHINCR; + word initial_heap_sz = (word)MINHINCR; # endif IF_CANCEL(int cancel_state;) - + if (GC_is_initialized) return; DISABLE_CANCEL(cancel_state); /* Note that although we are nominally called with the */ - /* allocation lock held, the allocation lock is now */ + /* allocation lock held, the allocation lock is now */ /* only really acquired once a second thread is forked.*/ /* And the initialization code needs to run before */ /* then. Thus we really don't hold any locks, and can */ - /* in fact safely initialize them here. */ + /* in fact safely initialize them here. */ # ifdef THREADS GC_ASSERT(!GC_need_to_lock); # endif @@ -547,14 +547,14 @@ GC_API void GC_CALL GC_init(void) BOOL (WINAPI *pfn) (LPCRITICAL_SECTION, DWORD) = NULL; HMODULE hK32 = GetModuleHandle(TEXT("kernel32.dll")); if (hK32) - pfn = (BOOL (WINAPI *) (LPCRITICAL_SECTION, DWORD)) - GetProcAddress (hK32, - "InitializeCriticalSectionAndSpinCount"); + pfn = (BOOL (WINAPI *) (LPCRITICAL_SECTION, DWORD)) + GetProcAddress (hK32, + "InitializeCriticalSectionAndSpinCount"); if (pfn) pfn(&GC_allocate_ml, 4000); else # endif /* !MSWINCE */ - /* else */ InitializeCriticalSection (&GC_allocate_ml); + /* else */ InitializeCriticalSection (&GC_allocate_ml); } # endif /* GC_WIN32_THREADS */ # if (defined(MSWIN32) || defined(MSWINCE)) && defined(THREADS) @@ -562,28 +562,28 @@ GC_API void GC_CALL GC_init(void) # endif # if (!defined(SMALL_CONFIG)) # ifdef GC_PRINT_VERBOSE_STATS - /* This is useful for debugging and profiling on platforms with */ - /* missing getenv() (like WinCE). */ - GC_print_stats = VERBOSE; + /* This is useful for debugging and profiling on platforms with */ + /* missing getenv() (like WinCE). */ + GC_print_stats = VERBOSE; # else - if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) { - GC_print_stats = VERBOSE; - } else if (0 != GETENV("GC_PRINT_STATS")) { - GC_print_stats = 1; - } + if (0 != GETENV("GC_PRINT_VERBOSE_STATS")) { + GC_print_stats = VERBOSE; + } else if (0 != GETENV("GC_PRINT_STATS")) { + GC_print_stats = 1; + } # endif # if defined(UNIX_LIKE) || defined(CYGWIN32) { - char * file_name = GETENV("GC_LOG_FILE"); + char * file_name = GETENV("GC_LOG_FILE"); if (0 != file_name) { - int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666); - if (log_d < 0) { - GC_log_printf("Failed to open %s as log file\n", file_name); - } else { - GC_log = log_d; - } - } - } + int log_d = open(file_name, O_CREAT|O_WRONLY|O_APPEND, 0666); + if (log_d < 0) { + GC_log_printf("Failed to open %s as log file\n", file_name); + } else { + GC_log = log_d; + } + } + } # endif # endif # ifndef NO_DEBUGGING @@ -596,7 +596,7 @@ GC_API void GC_CALL GC_init(void) char * backtraces_string = GETENV("GC_BACKTRACES"); if (0 != backtraces_string) { GC_backtraces = atol(backtraces_string); - if (backtraces_string[0] == '\0') GC_backtraces = 1; + if (backtraces_string[0] == '\0') GC_backtraces = 1; } } # endif @@ -620,35 +620,35 @@ GC_API void GC_CALL GC_init(void) char * addr_string = GETENV("GC_TRACE"); if (0 != addr_string) { # ifndef ENABLE_TRACE - WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0); + WARN("Tracing not enabled: Ignoring GC_TRACE value\n", 0); # else - word addr = (word)STRTOULL(addr_string, NULL, 16); - if (addr < 0x1000) - WARN("Unlikely trace address: %p\n", addr); - GC_trace_addr = (ptr_t)addr; -# endif + word addr = (word)STRTOULL(addr_string, NULL, 16); + if (addr < 0x1000) + WARN("Unlikely trace address: %p\n", addr); + GC_trace_addr = (ptr_t)addr; +# endif } } # ifndef SMALL_CONFIG { - char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET"); - if (0 != time_limit_string) { - long time_limit = atol(time_limit_string); - if (time_limit < 5) { - WARN("GC_PAUSE_TIME_TARGET environment variable value too small " - "or bad syntax: Ignoring\n", 0); - } else { - GC_time_limit = time_limit; - } - } + char * time_limit_string = GETENV("GC_PAUSE_TIME_TARGET"); + if (0 != time_limit_string) { + long time_limit = atol(time_limit_string); + if (time_limit < 5) { + WARN("GC_PAUSE_TIME_TARGET environment variable value too small " + "or bad syntax: Ignoring\n", 0); + } else { + GC_time_limit = time_limit; + } + } } { - char * full_freq_string = GETENV("GC_FULL_FREQUENCY"); - if (full_freq_string != NULL) { - int full_freq = atoi(full_freq_string); - if (full_freq > 0) - GC_full_freq = full_freq; - } + char * full_freq_string = GETENV("GC_FULL_FREQUENCY"); + if (full_freq_string != NULL) { + int full_freq = atoi(full_freq_string); + if (full_freq > 0) + GC_full_freq = full_freq; + } } # endif { @@ -656,49 +656,49 @@ GC_API void GC_CALL GC_init(void) if (0 != interval_string) { long interval = atol(interval_string); if (interval <= 0) { - WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has " - "bad value: Ignoring\n", 0); + WARN("GC_LARGE_ALLOC_WARN_INTERVAL environment variable has " + "bad value: Ignoring\n", 0); } else { - GC_large_alloc_warn_interval = interval; + GC_large_alloc_warn_interval = interval; } } } { - char * space_divisor_string = GETENV("GC_FREE_SPACE_DIVISOR"); - if (space_divisor_string != NULL) { - int space_divisor = atoi(space_divisor_string); - if (space_divisor > 0) - GC_free_space_divisor = (GC_word)space_divisor; - } + char * space_divisor_string = GETENV("GC_FREE_SPACE_DIVISOR"); + if (space_divisor_string != NULL) { + int space_divisor = atoi(space_divisor_string); + if (space_divisor > 0) + GC_free_space_divisor = (GC_word)space_divisor; + } } # ifdef USE_MUNMAP { - char * string = GETENV("GC_UNMAP_THRESHOLD"); - if (string != NULL) { - if (*string == '0' && *(string + 1) == '\0') { - /* "0" is used to disable unmapping. */ - GC_unmap_threshold = 0; - } else { - int unmap_threshold = atoi(string); - if (unmap_threshold > 0) - GC_unmap_threshold = unmap_threshold; - } - } + char * string = GETENV("GC_UNMAP_THRESHOLD"); + if (string != NULL) { + if (*string == '0' && *(string + 1) == '\0') { + /* "0" is used to disable unmapping. */ + GC_unmap_threshold = 0; + } else { + int unmap_threshold = atoi(string); + if (unmap_threshold > 0) + GC_unmap_threshold = unmap_threshold; + } + } } { - char * string = GETENV("GC_FORCE_UNMAP_ON_GCOLLECT"); - if (string != NULL) { - if (*string == '0' && *(string + 1) == '\0') { - /* "0" is used to turn off the mode. */ + char * string = GETENV("GC_FORCE_UNMAP_ON_GCOLLECT"); + if (string != NULL) { + if (*string == '0' && *(string + 1) == '\0') { + /* "0" is used to turn off the mode. */ GC_force_unmap_on_gcollect = FALSE; - } else { + } else { GC_force_unmap_on_gcollect = TRUE; - } - } + } + } } # endif maybe_install_looping_handler(); - /* Adjust normal object descriptor for extra allocation. */ + /* Adjust normal object descriptor for extra allocation. */ if (ALIGNMENT > GC_DS_TAGS && EXTRA_BYTES != 0) { GC_obj_kinds[NORMAL].ok_descriptor = ((word)(-ALIGNMENT) | GC_DS_LENGTH); } @@ -710,37 +710,37 @@ GC_API void GC_CALL GC_init(void) GC_exclude_static_roots_inner(beginGC_aobjfreelist, endGC_aobjfreelist); # endif # ifdef MSWIN32 - GC_init_win32(); + GC_init_win32(); # endif # if defined(USE_PROC_FOR_LIBRARIES) && defined(GC_LINUX_THREADS) - WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0); - /* If thread stacks are cached, they tend to be scanned in */ - /* entirety as part of the root set. This wil grow them to */ - /* maximum size, and is generally not desirable. */ + WARN("USE_PROC_FOR_LIBRARIES + GC_LINUX_THREADS performs poorly.\n", 0); + /* If thread stacks are cached, they tend to be scanned in */ + /* entirety as part of the root set. This wil grow them to */ + /* maximum size, and is generally not desirable. */ # endif # if defined(SEARCH_FOR_DATA_START) - GC_init_linux_data_start(); + GC_init_linux_data_start(); # endif # if (defined(NETBSD) || defined(OPENBSD)) && defined(__ELF__) - GC_init_netbsd_elf(); + GC_init_netbsd_elf(); # endif # if !defined(THREADS) || defined(GC_PTHREADS) || defined(GC_WIN32_THREADS) \ - || defined(GC_SOLARIS_THREADS) + || defined(GC_SOLARIS_THREADS) if (GC_stackbottom == 0) { - GC_stackbottom = GC_get_main_stack_base(); + GC_stackbottom = GC_get_main_stack_base(); # if (defined(LINUX) || defined(HPUX)) && defined(IA64) - GC_register_stackbottom = GC_get_register_stack_base(); + GC_register_stackbottom = GC_get_register_stack_base(); # endif } else { # if (defined(LINUX) || defined(HPUX)) && defined(IA64) - if (GC_register_stackbottom == 0) { - WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0); - /* The following may fail, since we may rely on */ - /* alignment properties that may not hold with a user set */ - /* GC_stackbottom. */ - GC_register_stackbottom = GC_get_register_stack_base(); - } -# endif + if (GC_register_stackbottom == 0) { + WARN("GC_register_stackbottom should be set with GC_stackbottom\n", 0); + /* The following may fail, since we may rely on */ + /* alignment properties that may not hold with a user set */ + /* GC_stackbottom. */ + GC_register_stackbottom = GC_get_register_stack_base(); + } +# endif } # endif GC_STATIC_ASSERT(sizeof (ptr_t) == sizeof(word)); @@ -758,48 +758,48 @@ GC_API void GC_CALL GC_init(void) /* word should be unsigned */ # endif # if !defined(__BORLANDC__) /* Workaround for Borland C */ - GC_STATIC_ASSERT((ptr_t)(word)(-1) > (ptr_t)0); - /* Ptr_t comparisons should behave as unsigned comparisons. */ + GC_STATIC_ASSERT((ptr_t)(word)(-1) > (ptr_t)0); + /* Ptr_t comparisons should behave as unsigned comparisons. */ # endif GC_STATIC_ASSERT((signed_word)(-1) < (signed_word)0); # if !defined(SMALL_CONFIG) if (GC_incremental || 0 != GETENV("GC_ENABLE_INCREMENTAL")) { - /* For GWW_MPROTECT on Win32, this needs to happen before any */ - /* heap memory is allocated. */ + /* For GWW_MPROTECT on Win32, this needs to happen before any */ + /* heap memory is allocated. */ GC_dirty_init(); GC_ASSERT(GC_bytes_allocd == 0) - GC_incremental = TRUE; + GC_incremental = TRUE; } # endif /* !SMALL_CONFIG */ - - /* Add initial guess of root sets. Do this first, since sbrk(0) */ - /* might be used. */ + + /* Add initial guess of root sets. Do this first, since sbrk(0) */ + /* might be used. */ if (GC_REGISTER_MAIN_STATIC_DATA()) GC_register_data_segments(); GC_init_headers(); GC_bl_init(); GC_mark_init(); { - char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE"); - if (sz_str != NULL) { - initial_heap_sz = (word)STRTOULL(sz_str, NULL, 10); - if (initial_heap_sz <= MINHINCR * HBLKSIZE) { - WARN("Bad initial heap size %s - ignoring it.\n", - sz_str); - } - initial_heap_sz = divHBLKSZ(initial_heap_sz); - } + char * sz_str = GETENV("GC_INITIAL_HEAP_SIZE"); + if (sz_str != NULL) { + initial_heap_sz = (word)STRTOULL(sz_str, NULL, 10); + if (initial_heap_sz <= MINHINCR * HBLKSIZE) { + WARN("Bad initial heap size %s - ignoring it.\n", + sz_str); + } + initial_heap_sz = divHBLKSZ(initial_heap_sz); + } } { - char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE"); - if (sz_str != NULL) { - word max_heap_sz = (word)STRTOULL(sz_str, NULL, 10); - if (max_heap_sz < initial_heap_sz * HBLKSIZE) { - WARN("Bad maximum heap size %s - ignoring it.\n", - sz_str); - } - if (0 == GC_max_retries) GC_max_retries = 2; - GC_set_max_heap_size(max_heap_sz); - } + char * sz_str = GETENV("GC_MAXIMUM_HEAP_SIZE"); + if (sz_str != NULL) { + word max_heap_sz = (word)STRTOULL(sz_str, NULL, 10); + if (max_heap_sz < initial_heap_sz * HBLKSIZE) { + WARN("Bad maximum heap size %s - ignoring it.\n", + sz_str); + } + if (0 == GC_max_retries) GC_max_retries = 2; + GC_set_max_heap_size(max_heap_sz); + } } if (!GC_expand_hp_inner(initial_heap_sz)) { GC_err_printf("Can't start up: not enough memory\n"); @@ -809,7 +809,7 @@ GC_API void GC_CALL GC_init(void) GC_register_displacement_inner(0L); # if defined(GC_LINUX_THREADS) && defined(REDIRECT_MALLOC) if (!GC_all_interior_pointers) { - /* TLS ABI uses pointer-sized offsets for dtv. */ + /* TLS ABI uses pointer-sized offsets for dtv. */ GC_register_displacement_inner(sizeof(void *)); } # endif @@ -832,7 +832,7 @@ GC_API void GC_CALL GC_init(void) /* Get black list set up and/or incremental GC started */ if (!GC_dont_precollect || GC_incremental) GC_gcollect_inner(); # ifdef STUBBORN_ALLOC - GC_stubborn_init(); + GC_stubborn_init(); # endif /* Convince lint that some things are used */ # ifdef LINT @@ -840,26 +840,26 @@ GC_API void GC_CALL GC_init(void) extern char * GC_copyright[]; extern int GC_read(); extern void GC_register_finalizer_no_order(); - + GC_noop(GC_copyright, GC_find_header, GC_push_one, GC_call_with_alloc_lock, GC_read, GC_dont_expand, -# ifndef NO_DEBUGGING - GC_dump, -# endif +# ifndef NO_DEBUGGING + GC_dump, +# endif GC_register_finalizer_no_order); } # endif - /* The rest of this again assumes we don't really hold */ - /* the allocation lock. */ + /* The rest of this again assumes we don't really hold */ + /* the allocation lock. */ # if defined(PARALLEL_MARK) || defined(THREAD_LOCAL_ALLOC) - /* Make sure marker threads are started and thread local */ - /* allocation is initialized, in case we didn't get */ - /* called from GC_init_parallel(); */ + /* Make sure marker threads are started and thread local */ + /* allocation is initialized, in case we didn't get */ + /* called from GC_init_parallel(); */ { - GC_init_parallel(); - } + GC_init_parallel(); + } # endif /* PARALLEL_MARK || THREAD_LOCAL_ALLOC */ # if defined(DYNAMIC_LOADING) && defined(DARWIN) @@ -876,12 +876,12 @@ GC_API void GC_CALL GC_init(void) GC_API void GC_CALL GC_enable_incremental(void) { # if !defined(SMALL_CONFIG) && !defined(KEEP_BACK_PTRS) - /* If we are keeping back pointers, the GC itself dirties all */ - /* pages on which objects have been marked, making */ - /* incremental GC pointless. */ + /* If we are keeping back pointers, the GC itself dirties all */ + /* pages on which objects have been marked, making */ + /* incremental GC pointless. */ if (!GC_find_leak && 0 == GETENV("GC_DISABLE_INCREMENTAL")) { DCL_LOCK_STATE; - + LOCK(); if (GC_incremental) goto out; GC_setpagesize(); @@ -891,20 +891,20 @@ GC_API void GC_CALL GC_enable_incremental(void) if (!GC_is_initialized) { GC_init(); } else { - GC_dirty_init(); + GC_dirty_init(); } if (!GC_dirty_maintained) goto out; if (GC_dont_gc) { /* Can't easily do it. */ UNLOCK(); - return; + return; } if (GC_bytes_allocd > 0) { - /* There may be unmarked reachable objects */ - GC_gcollect_inner(); - } /* else we're OK in assuming everything's */ - /* clean since nothing can point to an */ - /* unmarked object. */ + /* There may be unmarked reachable objects */ + GC_gcollect_inner(); + } /* else we're OK in assuming everything's */ + /* clean since nothing can point to an */ + /* unmarked object. */ GC_read_dirty(); out: UNLOCK(); @@ -929,7 +929,7 @@ out: { # ifdef THREADS if (GC_is_initialized) { - DeleteCriticalSection(&GC_write_cs); + DeleteCriticalSection(&GC_write_cs); } # endif } @@ -956,25 +956,25 @@ out: /* Use GetEnvironmentVariable instead of GETENV() for unicode support. */ # ifndef NO_GETENV if (GetEnvironmentVariable(TEXT("GC_LOG_FILE"), logPath, - _MAX_PATH + 1) - 1U >= (DWORD)_MAX_PATH) + _MAX_PATH + 1) - 1U >= (DWORD)_MAX_PATH) # endif { - /* Env var not found or its value too long. */ + /* Env var not found or its value too long. */ # ifdef OLD_WIN32_LOG_FILE - return CreateFile(TEXT("gc.log"), GENERIC_WRITE, FILE_SHARE_READ, - NULL /* lpSecurityAttributes */, CREATE_ALWAYS, - FILE_FLAG_WRITE_THROUGH, NULL /* hTemplateFile */); + return CreateFile(TEXT("gc.log"), GENERIC_WRITE, FILE_SHARE_READ, + NULL /* lpSecurityAttributes */, CREATE_ALWAYS, + FILE_FLAG_WRITE_THROUGH, NULL /* hTemplateFile */); # else - /* strcat/wcscat() are deprecated on WinCE, so use memcpy() */ - memcpy(&logPath[GetModuleFileName(NULL /* hModule */, logPath, - _MAX_PATH + 1)], - TEXT(".log"), sizeof(TEXT(".log"))); + /* strcat/wcscat() are deprecated on WinCE, so use memcpy() */ + memcpy(&logPath[GetModuleFileName(NULL /* hModule */, logPath, + _MAX_PATH + 1)], + TEXT(".log"), sizeof(TEXT(".log"))); # endif } # if !defined(NO_GETENV) || !defined(OLD_WIN32_LOG_FILE) return CreateFile(logPath, GENERIC_WRITE, FILE_SHARE_READ, - NULL /* lpSecurityAttributes */, CREATE_ALWAYS, - FILE_FLAG_WRITE_THROUGH, NULL /* hTemplateFile */); + NULL /* lpSecurityAttributes */, CREATE_ALWAYS, + FILE_FLAG_WRITE_THROUGH, NULL /* hTemplateFile */); # endif } @@ -983,33 +983,33 @@ out: BOOL tmp; DWORD written; if (len == 0) - return 0; + return 0; IF_NEED_TO_LOCK(EnterCriticalSection(&GC_write_cs)); if (GC_stdout == INVALID_HANDLE_VALUE) { - IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs)); - return -1; + IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs)); + return -1; } else if (GC_stdout == 0) { - GC_stdout = GC_CreateLogFile(); - if (GC_stdout == INVALID_HANDLE_VALUE) - ABORT("Open of log file failed"); + GC_stdout = GC_CreateLogFile(); + if (GC_stdout == INVALID_HANDLE_VALUE) + ABORT("Open of log file failed"); } tmp = WriteFile(GC_stdout, buf, (DWORD)len, &written, NULL); if (!tmp) - DebugBreak(); + DebugBreak(); # if defined(_MSC_VER) && defined(_DEBUG) -# ifdef MSWINCE - /* There is no CrtDbgReport() in WinCE */ - { - WCHAR wbuf[1024]; - /* Always use Unicode variant of OutputDebugString() */ - wbuf[MultiByteToWideChar(CP_ACP, 0 /* dwFlags */, - buf, len, wbuf, - sizeof(wbuf) / sizeof(wbuf[0]) - 1)] = 0; - OutputDebugStringW(wbuf); - } -# else - _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf); -# endif +# ifdef MSWINCE + /* There is no CrtDbgReport() in WinCE */ + { + WCHAR wbuf[1024]; + /* Always use Unicode variant of OutputDebugString() */ + wbuf[MultiByteToWideChar(CP_ACP, 0 /* dwFlags */, + buf, len, wbuf, + sizeof(wbuf) / sizeof(wbuf[0]) - 1)] = 0; + OutputDebugStringW(wbuf); + } +# else + _CrtDbgReport(_CRT_WARN, NULL, 0, NULL, "%.*s", len, buf); +# endif # endif IF_NEED_TO_LOCK(LeaveCriticalSection(&GC_write_cs)); return tmp ? (int)written : -1; @@ -1026,13 +1026,13 @@ STATIC int GC_tmp; /* Should really be local ... */ STATIC void GC_set_files(void) { if (GC_stdout == NULL) { - GC_stdout = stdout; + GC_stdout = stdout; } if (GC_stderr == NULL) { - GC_stderr = stderr; + GC_stderr = stderr; } if (GC_log == NULL) { - GC_log = stderr; + GC_log = stderr; } } #endif @@ -1053,20 +1053,20 @@ STATIC int GC_write(int fd, const char *buf, size_t len) int bytes_written = 0; int result; IF_CANCEL(int cancel_state;) - + DISABLE_CANCEL(cancel_state); while (bytes_written < len) { -# ifdef GC_SOLARIS_THREADS - result = syscall(SYS_write, fd, buf + bytes_written, - len - bytes_written); -# else - result = write(fd, buf + bytes_written, len - bytes_written); -# endif - if (-1 == result) { +# ifdef GC_SOLARIS_THREADS + result = syscall(SYS_write, fd, buf + bytes_written, + len - bytes_written); +# else + result = write(fd, buf + bytes_written, len - bytes_written); +# endif + if (-1 == result) { RESTORE_CANCEL(cancel_state); - return(result); - } - bytes_written += result; + return(result); + } + bytes_written += result; } RESTORE_CANCEL(cancel_state); return(bytes_written); @@ -1096,8 +1096,8 @@ STATIC int GC_write(int fd, const char *buf, size_t len) #else # if defined(OS2) || defined(MACOS) # define WRITE(f, buf, len) (GC_set_files(), \ - GC_tmp = fwrite((buf), 1, (len), (f)), \ - fflush(f), GC_tmp) + GC_tmp = fwrite((buf), 1, (len), (f)), \ + fflush(f), GC_tmp) # else # define WRITE(f, buf, len) GC_write((f), (buf), (len)) # endif @@ -1114,14 +1114,14 @@ STATIC int GC_write(int fd, const char *buf, size_t len) #endif /* A version of printf that is unlikely to call malloc, and is thus safer */ /* to call from the collector in case malloc has been bound to GC_malloc. */ -/* Floating point arguments and formats should be avoided, since fp */ -/* conversion is more likely to allocate. */ -/* Assumes that no more than BUFSZ-1 characters are written at once. */ +/* Floating point arguments and formats should be avoided, since fp */ +/* conversion is more likely to allocate. */ +/* Assumes that no more than BUFSZ-1 characters are written at once. */ void GC_printf(const char *format, ...) { va_list args; char buf[BUFSZ+1]; - + va_start(args, format); if (GC_quiet) return; buf[BUFSZ] = 0x15; @@ -1135,7 +1135,7 @@ void GC_err_printf(const char *format, ...) { va_list args; char buf[BUFSZ+1]; - + va_start(args, format); buf[BUFSZ] = 0x15; (void) vsnprintf(buf, BUFSZ, format, args); @@ -1148,7 +1148,7 @@ void GC_log_printf(const char *format, ...) { va_list args; char buf[BUFSZ+1]; - + va_start(args, format); buf[BUFSZ] = 0x15; (void) vsnprintf(buf, BUFSZ, format, args); @@ -1190,10 +1190,10 @@ GC_API void GC_CALL GC_set_warn_proc(GC_warn_proc p) GC_ASSERT(p != 0); # ifdef GC_WIN32_THREADS # ifdef CYGWIN32 - /* Need explicit GC_INIT call */ + /* Need explicit GC_INIT call */ GC_ASSERT(GC_is_initialized); # else - if (!GC_is_initialized) GC_init(); + if (!GC_is_initialized) GC_init(); # endif # endif LOCK(); @@ -1215,40 +1215,40 @@ void GC_abort(const char *msg) { # if defined(MSWIN32) # ifndef DONT_USE_USER32_DLL - /* Use static binding to "user32.dll". */ - (void)MessageBoxA(NULL, msg, "Fatal error in GC", MB_ICONERROR|MB_OK); + /* Use static binding to "user32.dll". */ + (void)MessageBoxA(NULL, msg, "Fatal error in GC", MB_ICONERROR|MB_OK); # else - /* This simplifies linking - resolve "MessageBoxA" at run-time. */ - HINSTANCE hU32 = LoadLibrary(TEXT("user32.dll")); - if (hU32) { - FARPROC pfn = GetProcAddress(hU32, "MessageBoxA"); - if (pfn) - (void)(*(int (WINAPI *)(HWND, LPCSTR, LPCSTR, UINT))pfn)( - NULL /* hWnd */, msg, "Fatal error in GC", - MB_ICONERROR | MB_OK); - (void)FreeLibrary(hU32); - } + /* This simplifies linking - resolve "MessageBoxA" at run-time. */ + HINSTANCE hU32 = LoadLibrary(TEXT("user32.dll")); + if (hU32) { + FARPROC pfn = GetProcAddress(hU32, "MessageBoxA"); + if (pfn) + (void)(*(int (WINAPI *)(HWND, LPCSTR, LPCSTR, UINT))pfn)( + NULL /* hWnd */, msg, "Fatal error in GC", + MB_ICONERROR | MB_OK); + (void)FreeLibrary(hU32); + } # endif - /* Also duplicate msg to GC log file. */ + /* Also duplicate msg to GC log file. */ # endif - /* Avoid calling GC_err_printf() here, as GC_abort() could be */ - /* called from it. Note 1: this is not an atomic output. */ - /* Note 2: possible write errors are ignored. */ + /* Avoid calling GC_err_printf() here, as GC_abort() could be */ + /* called from it. Note 1: this is not an atomic output. */ + /* Note 2: possible write errors are ignored. */ if (WRITE(GC_stderr, (void *)msg, strlen(msg)) >= 0) - (void)WRITE(GC_stderr, (void *)("\n"), 1); + (void)WRITE(GC_stderr, (void *)("\n"), 1); if (GETENV("GC_LOOP_ON_ABORT") != NULL) { - /* In many cases it's easier to debug a running process. */ - /* It's arguably nicer to sleep, but that makes it harder */ - /* to look at the thread if the debugger doesn't know much */ - /* about threads. */ - for(;;) {} + /* In many cases it's easier to debug a running process. */ + /* It's arguably nicer to sleep, but that makes it harder */ + /* to look at the thread if the debugger doesn't know much */ + /* about threads. */ + for(;;) {} } # if defined(MSWIN32) && defined(NO_DEBUGGING) - /* A more user-friendly abort after showing fatal message. */ - _exit(-1); /* exit on error without running "at-exit" callbacks */ + /* A more user-friendly abort after showing fatal message. */ + _exit(-1); /* exit on error without running "at-exit" callbacks */ # elif defined(MSWIN32) || defined(MSWINCE) - DebugBreak(); + DebugBreak(); # else (void) abort(); # endif @@ -1269,11 +1269,11 @@ GC_API void GC_CALL GC_disable(void) UNLOCK(); } -/* Helper procedures for new kind creation. */ +/* Helper procedures for new kind creation. */ GC_API void ** GC_CALL GC_new_free_list_inner(void) { void *result = GC_INTERNAL_MALLOC((MAXOBJGRANULES+1)*sizeof(ptr_t), - PTRFREE); + PTRFREE); if (result == 0) ABORT("Failed to allocate freelist for new kind"); BZERO(result, (MAXOBJGRANULES+1)*sizeof(ptr_t)); return result; @@ -1289,7 +1289,7 @@ GC_API void ** GC_CALL GC_new_free_list(void) } GC_API unsigned GC_CALL GC_new_kind_inner(void **fl, GC_word descr, - int adjust, int clear) + int adjust, int clear) { unsigned result = GC_n_kinds++; @@ -1303,7 +1303,7 @@ GC_API unsigned GC_CALL GC_new_kind_inner(void **fl, GC_word descr, } GC_API unsigned GC_CALL GC_new_kind(void **fl, GC_word descr, int adjust, - int clear) + int clear) { unsigned result; LOCK(); @@ -1338,62 +1338,62 @@ GC_API void * GC_CALL GC_call_with_stack_base(GC_stack_base_func fn, void *arg) base.mem_base = (void *)&dummy; # ifdef IA64 base.reg_base = (void *)GC_save_regs_in_stack(); - /* Unnecessarily flushes register stack, */ - /* but that probably doesn't hurt. */ + /* Unnecessarily flushes register stack, */ + /* but that probably doesn't hurt. */ # endif return fn(&base, arg); } #ifdef THREADS -/* Defined in pthread_support.c or win32_threads.c. */ +/* Defined in pthread_support.c or win32_threads.c. */ void GC_do_blocking_inner(ptr_t data, void * context); #else ptr_t GC_blocked_sp = NULL; - /* NULL value means we are not inside GC_do_blocking() call. */ + /* NULL value means we are not inside GC_do_blocking() call. */ # ifdef IA64 STATIC ptr_t GC_blocked_register_sp = NULL; # endif struct GC_activation_frame_s *GC_activation_frame = NULL; -/* This is nearly the same as in win32_threads.c */ +/* This is nearly the same as in win32_threads.c */ GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn, - void * client_data) { + void * client_data) { struct GC_activation_frame_s frame; GC_ASSERT(GC_is_initialized); - /* Adjust our stack base value (this could happen if */ - /* GC_get_main_stack_base() is unimplemented or broken for */ - /* the platform). */ + /* Adjust our stack base value (this could happen if */ + /* GC_get_main_stack_base() is unimplemented or broken for */ + /* the platform). */ if (GC_stackbottom HOTTER_THAN (ptr_t)(&frame)) GC_stackbottom = (ptr_t)(&frame); if (GC_blocked_sp == NULL) { - /* We are not inside GC_do_blocking() - do nothing more. */ + /* We are not inside GC_do_blocking() - do nothing more. */ return fn(client_data); } - /* Setup new "frame". */ + /* Setup new "frame". */ frame.saved_stack_ptr = GC_blocked_sp; # ifdef IA64 - /* This is the same as in GC_call_with_stack_base(). */ + /* This is the same as in GC_call_with_stack_base(). */ frame.backing_store_end = GC_save_regs_in_stack(); - /* Unnecessarily flushes register stack, */ - /* but that probably doesn't hurt. */ + /* Unnecessarily flushes register stack, */ + /* but that probably doesn't hurt. */ frame.saved_backing_store_ptr = GC_blocked_register_sp; # endif frame.prev = GC_activation_frame; GC_blocked_sp = NULL; GC_activation_frame = &frame; - + client_data = fn(client_data); GC_ASSERT(GC_blocked_sp == NULL); GC_ASSERT(GC_activation_frame == &frame); - /* Restore original "frame". */ + /* Restore original "frame". */ GC_activation_frame = frame.prev; # ifdef IA64 GC_blocked_register_sp = frame.saved_backing_store_ptr; @@ -1403,41 +1403,41 @@ GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn, return client_data; /* result */ } -/* This is nearly the same as in win32_threads.c */ +/* This is nearly the same as in win32_threads.c */ /*ARGSUSED*/ STATIC void GC_do_blocking_inner(ptr_t data, void * context) { struct blocking_data * d = (struct blocking_data *) data; GC_ASSERT(GC_is_initialized); GC_ASSERT(GC_blocked_sp == NULL); # ifdef SPARC - GC_blocked_sp = GC_save_regs_in_stack(); + GC_blocked_sp = GC_save_regs_in_stack(); # else - GC_blocked_sp = (ptr_t) &d; /* save approx. sp */ + GC_blocked_sp = (ptr_t) &d; /* save approx. sp */ # endif # ifdef IA64 - GC_blocked_register_sp = GC_save_regs_in_stack(); + GC_blocked_register_sp = GC_save_regs_in_stack(); # endif d -> client_data = (d -> fn)(d -> client_data); # ifdef SPARC - GC_ASSERT(GC_blocked_sp != NULL); + GC_ASSERT(GC_blocked_sp != NULL); # else - GC_ASSERT(GC_blocked_sp == (ptr_t) &d); + GC_ASSERT(GC_blocked_sp == (ptr_t) &d); # endif GC_blocked_sp = NULL; } #endif /* !THREADS */ -/* Wrapper for functions that are likely to block (or, at least, do not */ -/* allocate garbage collected memory and/or manipulate pointers to the */ -/* garbage collected heap) for an appreciable length of time. */ -/* In the single threaded case, GC_do_blocking() (together */ -/* with GC_call_with_gc_active()) might be used to make stack scanning */ -/* more precise (i.e. scan only stack frames of functions that allocate */ -/* garbage collected memory and/or manipulate pointers to the garbage */ -/* collected heap). */ +/* Wrapper for functions that are likely to block (or, at least, do not */ +/* allocate garbage collected memory and/or manipulate pointers to the */ +/* garbage collected heap) for an appreciable length of time. */ +/* In the single threaded case, GC_do_blocking() (together */ +/* with GC_call_with_gc_active()) might be used to make stack scanning */ +/* more precise (i.e. scan only stack frames of functions that allocate */ +/* garbage collected memory and/or manipulate pointers to the garbage */ +/* collected heap). */ GC_API void * GC_CALL GC_do_blocking(GC_fn_type fn, void * client_data) { struct blocking_data my_data; @@ -1463,11 +1463,11 @@ GC_API void GC_CALL GC_dump(void) #endif /* NO_DEBUGGING */ -/* Getter functions for the public Read-only variables. */ +/* Getter functions for the public Read-only variables. */ -/* GC_get_gc_no() is unsynchronized and should be typically called */ -/* inside the context of GC_call_with_alloc_lock() to prevent data */ -/* races (on multiprocessors). */ +/* GC_get_gc_no() is unsynchronized and should be typically called */ +/* inside the context of GC_call_with_alloc_lock() to prevent data */ +/* races (on multiprocessors). */ GC_API GC_word GC_CALL GC_get_gc_no(void) { return GC_gc_no; @@ -1475,13 +1475,13 @@ GC_API GC_word GC_CALL GC_get_gc_no(void) GC_API int GC_CALL GC_get_parallel(void) { - /* GC_parallel is initialized at start-up. */ + /* GC_parallel is initialized at start-up. */ return GC_parallel; } -/* Setter and getter functions for the public R/W function variables. */ -/* These functions are synchronized (like GC_set_warn_proc() and */ -/* GC_get_warn_proc()). */ +/* Setter and getter functions for the public R/W function variables. */ +/* These functions are synchronized (like GC_set_warn_proc() and */ +/* GC_get_warn_proc()). */ GC_API void GC_CALL GC_set_oom_fn(GC_oom_func fn) { @@ -1517,12 +1517,12 @@ GC_API GC_finalizer_notifier_proc GC_CALL GC_get_finalizer_notifier(void) return fn; } -/* Setter and getter functions for the public numeric R/W variables. */ -/* It is safe to call these functions even before GC_INIT(). */ -/* These functions are unsynchronized and should be typically called */ -/* inside the context of GC_call_with_alloc_lock() (if called after */ -/* GC_INIT()) to prevent data races (unless it is guaranteed the */ -/* collector is not multi-threaded at that execution point). */ +/* Setter and getter functions for the public numeric R/W variables. */ +/* It is safe to call these functions even before GC_INIT(). */ +/* These functions are unsynchronized and should be typically called */ +/* inside the context of GC_call_with_alloc_lock() (if called after */ +/* GC_INIT()) to prevent data races (unless it is guaranteed the */ +/* collector is not multi-threaded at that execution point). */ GC_API void GC_CALL GC_set_find_leak(int value) { diff --git a/os_dep.c b/os_dep.c index daa0703..2b61f69 100644 --- a/os_dep.c +++ b/os_dep.c @@ -38,8 +38,8 @@ # include # if 2 <= __GLIBC__ # if 2 == __GLIBC__ && 0 == __GLIBC_MINOR__ - /* glibc 2.1 no longer has sigcontext.h. But signal.h */ - /* has the right declaration for glibc 2.1. */ + /* glibc 2.1 no longer has sigcontext.h. But signal.h */ + /* has the right declaration for glibc 2.1. */ # include # endif /* 0 == __GLIBC_MINOR__ */ # else /* not 2 <= __GLIBC__ */ @@ -53,7 +53,7 @@ && !defined(MSWINCE) # include # if !defined(MSWIN32) -# include +# include # endif # endif @@ -72,8 +72,8 @@ # include #endif -/* Blatantly OS dependent routines, except for those that are related */ -/* to dynamic loading. */ +/* Blatantly OS dependent routines, except for those that are related */ +/* to dynamic loading. */ #ifdef AMIGA # define GC_AMIGA_DEF @@ -85,8 +85,8 @@ # define WIN32_LEAN_AND_MEAN # define NOSERVICE # include - /* It's not clear this is completely kosher under Cygwin. But it */ - /* allows us to get a working GC_get_stack_base. */ + /* It's not clear this is completely kosher under Cygwin. But it */ + /* allows us to get a working GC_get_stack_base. */ #endif #ifdef MACOS @@ -99,8 +99,8 @@ #endif #if defined(LINUX) || defined(FREEBSD) || defined(SOLARIS) || defined(IRIX5) \ - || ((defined(USE_MMAP) || defined(USE_MUNMAP)) \ - && !defined(MSWIN32) && !defined(MSWINCE)) + || ((defined(USE_MMAP) || defined(USE_MUNMAP)) \ + && !defined(MSWIN32) && !defined(MSWINCE)) # define MMAP_SUPPORTED #endif @@ -120,8 +120,8 @@ #endif #ifdef DJGPP - /* Apparently necessary for djgpp 2.01. May cause problems with */ - /* other versions. */ + /* Apparently necessary for djgpp 2.01. May cause problems with */ + /* other versions. */ typedef long unsigned int caddr_t; #endif @@ -143,33 +143,33 @@ #endif #ifdef NEED_PROC_MAPS -/* We need to parse /proc/self/maps, either to find dynamic libraries, */ -/* and/or to find the register backing store base (IA64). Do it once */ -/* here. */ +/* We need to parse /proc/self/maps, either to find dynamic libraries, */ +/* and/or to find the register backing store base (IA64). Do it once */ +/* here. */ #define READ read -/* Repeatedly perform a read call until the buffer is filled or */ -/* we encounter EOF. */ +/* Repeatedly perform a read call until the buffer is filled or */ +/* we encounter EOF. */ ssize_t GC_repeat_read(int fd, char *buf, size_t count) { ssize_t num_read = 0; ssize_t result; - + ASSERT_CANCEL_DISABLED(); while (num_read < count) { - result = READ(fd, buf + num_read, count - num_read); - if (result < 0) return result; - if (result == 0) break; - num_read += result; + result = READ(fd, buf + num_read, count - num_read); + if (result < 0) return result; + if (result == 0) break; + num_read += result; } return num_read; } #ifdef THREADS -/* Determine the length of a file by incrementally reading it into a */ -/* This would be silly to use on a file supporting lseek, but Linux */ -/* /proc files usually do not. */ +/* Determine the length of a file by incrementally reading it into a */ +/* This would be silly to use on a file supporting lseek, but Linux */ +/* /proc files usually do not. */ STATIC size_t GC_get_file_len(int f) { size_t total = 0; @@ -178,9 +178,9 @@ STATIC size_t GC_get_file_len(int f) char buf[GET_FILE_LEN_BUF_SZ]; do { - result = read(f, buf, GET_FILE_LEN_BUF_SZ); - if (result == -1) return 0; - total += result; + result = read(f, buf, GET_FILE_LEN_BUF_SZ); + if (result == -1) return 0; + total += result; } while (result > 0); return total; } @@ -212,74 +212,74 @@ char * GC_get_maps(void) /* The buffer is essentially static, so there must be a single client. */ GC_ASSERT(I_HOLD_LOCK()); - /* Note that in the presence of threads, the maps file can */ - /* essentially shrink asynchronously and unexpectedly as */ - /* threads that we already think of as dead release their */ - /* stacks. And there is no easy way to read the entire */ - /* file atomically. This is arguably a misfeature of the */ - /* /proc/.../maps interface. */ - - /* Since we dont believe the file can grow */ - /* asynchronously, it should suffice to first determine */ - /* the size (using lseek or read), and then to reread the */ - /* file. If the size is inconsistent we have to retry. */ - /* This only matters with threads enabled, and if we use */ - /* this to locate roots (not the default). */ - - /* Determine the initial size of /proc/self/maps. */ - /* Note that lseek doesn't work, at least as of 2.6.15. */ + /* Note that in the presence of threads, the maps file can */ + /* essentially shrink asynchronously and unexpectedly as */ + /* threads that we already think of as dead release their */ + /* stacks. And there is no easy way to read the entire */ + /* file atomically. This is arguably a misfeature of the */ + /* /proc/.../maps interface. */ + + /* Since we dont believe the file can grow */ + /* asynchronously, it should suffice to first determine */ + /* the size (using lseek or read), and then to reread the */ + /* file. If the size is inconsistent we have to retry. */ + /* This only matters with threads enabled, and if we use */ + /* this to locate roots (not the default). */ + + /* Determine the initial size of /proc/self/maps. */ + /* Note that lseek doesn't work, at least as of 2.6.15. */ # ifdef THREADS - maps_size = GC_get_maps_len(); - if (0 == maps_size) return 0; + maps_size = GC_get_maps_len(); + if (0 == maps_size) return 0; # else - maps_size = 4000; /* Guess */ + maps_size = 4000; /* Guess */ # endif - /* Read /proc/self/maps, growing maps_buf as necessary. */ - /* Note that we may not allocate conventionally, and */ - /* thus can't use stdio. */ - do { - while (maps_size >= maps_buf_sz) { - /* Grow only by powers of 2, since we leak "too small" buffers. */ - while (maps_size >= maps_buf_sz) maps_buf_sz *= 2; - maps_buf = GC_scratch_alloc(maps_buf_sz); -# ifdef THREADS - /* Recompute initial length, since we allocated. */ - /* This can only happen a few times per program */ - /* execution. */ - maps_size = GC_get_maps_len(); - if (0 == maps_size) return 0; -# endif - if (maps_buf == 0) return 0; - } - GC_ASSERT(maps_buf_sz >= maps_size + 1); - f = open("/proc/self/maps", O_RDONLY); - if (-1 == f) return 0; -# ifdef THREADS - old_maps_size = maps_size; -# endif - maps_size = 0; - do { - result = GC_repeat_read(f, maps_buf, maps_buf_sz-1); - if (result <= 0) return 0; - maps_size += result; - } while (result == maps_buf_sz-1); - close(f); -# ifdef THREADS - if (maps_size > old_maps_size) { - GC_err_printf("Old maps size = %lu, new maps size = %lu\n", - (unsigned long)old_maps_size, - (unsigned long)maps_size); - ABORT("Unexpected asynchronous /proc/self/maps growth: " - "Unregistered thread?"); - } -# endif - } while (maps_size >= maps_buf_sz || maps_size < old_maps_size); - /* In the single-threaded case, the second clause is false. */ + /* Read /proc/self/maps, growing maps_buf as necessary. */ + /* Note that we may not allocate conventionally, and */ + /* thus can't use stdio. */ + do { + while (maps_size >= maps_buf_sz) { + /* Grow only by powers of 2, since we leak "too small" buffers. */ + while (maps_size >= maps_buf_sz) maps_buf_sz *= 2; + maps_buf = GC_scratch_alloc(maps_buf_sz); +# ifdef THREADS + /* Recompute initial length, since we allocated. */ + /* This can only happen a few times per program */ + /* execution. */ + maps_size = GC_get_maps_len(); + if (0 == maps_size) return 0; +# endif + if (maps_buf == 0) return 0; + } + GC_ASSERT(maps_buf_sz >= maps_size + 1); + f = open("/proc/self/maps", O_RDONLY); + if (-1 == f) return 0; +# ifdef THREADS + old_maps_size = maps_size; +# endif + maps_size = 0; + do { + result = GC_repeat_read(f, maps_buf, maps_buf_sz-1); + if (result <= 0) return 0; + maps_size += result; + } while (result == maps_buf_sz-1); + close(f); +# ifdef THREADS + if (maps_size > old_maps_size) { + GC_err_printf("Old maps size = %lu, new maps size = %lu\n", + (unsigned long)old_maps_size, + (unsigned long)maps_size); + ABORT("Unexpected asynchronous /proc/self/maps growth: " + "Unregistered thread?"); + } +# endif + } while (maps_size >= maps_buf_sz || maps_size < old_maps_size); + /* In the single-threaded case, the second clause is false. */ maps_buf[maps_size] = '\0'; - + /* Apply fn to result. */ - return maps_buf; + return maps_buf; } /* @@ -304,7 +304,7 @@ char * GC_get_maps(void) */ char *GC_parse_map_entry(char *buf_ptr, ptr_t *start, ptr_t *end, char **prot, unsigned int *maj_dev, - char **mapping_name) + char **mapping_name) { char *start_start, *end_start, *maj_dev_start; char *p; @@ -350,10 +350,10 @@ char *GC_parse_map_entry(char *buf_ptr, ptr_t *start, ptr_t *end, return p; } -/* Try to read the backing store base from /proc/self/maps. */ -/* Return the bounds of the writable mapping with a 0 major device, */ -/* which includes the address passed as data. */ -/* Return FALSE if there is no such mapping. */ +/* Try to read the backing store base from /proc/self/maps. */ +/* Return the bounds of the writable mapping with a 0 major device, */ +/* which includes the address passed as data. */ +/* Return FALSE if there is no such mapping. */ GC_bool GC_enclosing_mapping(ptr_t addr, ptr_t *startp, ptr_t *endp) { char *prot; @@ -361,27 +361,27 @@ GC_bool GC_enclosing_mapping(ptr_t addr, ptr_t *startp, ptr_t *endp) unsigned int maj_dev; char *maps = GC_get_maps(); char *buf_ptr = maps; - + if (0 == maps) return(FALSE); for (;;) { buf_ptr = GC_parse_map_entry(buf_ptr, &my_start, &my_end, - &prot, &maj_dev, 0); + &prot, &maj_dev, 0); if (buf_ptr == NULL) return FALSE; if (prot[1] == 'w' && maj_dev == 0) { if (my_end > addr && my_start <= addr) { - *startp = my_start; - *endp = my_end; - return TRUE; - } + *startp = my_start; + *endp = my_end; + return TRUE; + } } } return FALSE; } #if defined(REDIRECT_MALLOC) -/* Find the text(code) mapping for the library whose name, after */ -/* stripping the directory part, starts with nm. */ +/* Find the text(code) mapping for the library whose name, after */ +/* stripping the directory part, starts with nm. */ GC_bool GC_text_mapping(char *nm, ptr_t *startp, ptr_t *endp) { size_t nm_len = strlen(nm); @@ -391,24 +391,24 @@ GC_bool GC_text_mapping(char *nm, ptr_t *startp, ptr_t *endp) unsigned int maj_dev; char *maps = GC_get_maps(); char *buf_ptr = maps; - + if (0 == maps) return(FALSE); for (;;) { buf_ptr = GC_parse_map_entry(buf_ptr, &my_start, &my_end, - &prot, &maj_dev, &map_path); + &prot, &maj_dev, &map_path); if (buf_ptr == NULL) return FALSE; if (prot[0] == 'r' && prot[1] == '-' && prot[2] == 'x') { - char *p = map_path; - /* Set p to point just past last slash, if any. */ - while (*p != '\0' && *p != '\n' && *p != ' ' && *p != '\t') ++p; - while (*p != '/' && p >= map_path) --p; - ++p; - if (strncmp(nm, p, nm_len) == 0) { - *startp = my_start; - *endp = my_end; - return TRUE; - } + char *p = map_path; + /* Set p to point just past last slash, if any. */ + while (*p != '\0' && *p != '\n' && *p != ' ' && *p != '\t') ++p; + while (*p != '/' && p >= map_path) --p; + ++p; + if (strncmp(nm, p, nm_len) == 0) { + *startp = my_start; + *endp = my_end; + return TRUE; + } } } return FALSE; @@ -420,29 +420,29 @@ static ptr_t backing_store_base_from_proc(void) { ptr_t my_start, my_end; if (!GC_enclosing_mapping(GC_save_regs_in_stack(), &my_start, &my_end)) { - if (GC_print_stats) { - GC_log_printf("Failed to find backing store base from /proc\n"); - } - return 0; + if (GC_print_stats) { + GC_log_printf("Failed to find backing store base from /proc\n"); + } + return 0; } return my_start; } #endif -#endif /* NEED_PROC_MAPS */ +#endif /* NEED_PROC_MAPS */ #if defined(SEARCH_FOR_DATA_START) - /* The I386 case can be handled without a search. The Alpha case */ - /* used to be handled differently as well, but the rules changed */ - /* for recent Linux versions. This seems to be the easiest way to */ - /* cover all versions. */ + /* The I386 case can be handled without a search. The Alpha case */ + /* used to be handled differently as well, but the rules changed */ + /* for recent Linux versions. This seems to be the easiest way to */ + /* cover all versions. */ # if defined(LINUX) || defined(HURD) - /* Some Linux distributions arrange to define __data_start. Some */ - /* define data_start as a weak symbol. The latter is technically */ - /* broken, since the user program may define data_start, in which */ + /* Some Linux distributions arrange to define __data_start. Some */ + /* define data_start as a weak symbol. The latter is technically */ + /* broken, since the user program may define data_start, in which */ /* case we lose. Nonetheless, we try both, preferring __data_start.*/ - /* We assume gcc-compatible pragmas. */ + /* We assume gcc-compatible pragmas. */ # pragma weak __data_start extern int __data_start[]; # pragma weak data_start @@ -458,14 +458,14 @@ static ptr_t backing_store_base_from_proc(void) { # if defined(LINUX) || defined(HURD) - /* Try the easy approaches first: */ + /* Try the easy approaches first: */ if ((ptr_t)__data_start != 0) { - GC_data_start = (ptr_t)(__data_start); - return; + GC_data_start = (ptr_t)(__data_start); + return; } if ((ptr_t)data_start != 0) { - GC_data_start = (ptr_t)(data_start); - return; + GC_data_start = (ptr_t)(data_start); + return; } # endif /* LINUX */ GC_data_start = GC_find_limit((ptr_t)(_end), FALSE); @@ -478,10 +478,10 @@ static ptr_t backing_store_base_from_proc(void) # define ECOS_GC_MEMORY_SIZE (448 * 1024) # endif /* ECOS_GC_MEMORY_SIZE */ -/* FIXME: This is a simple way of allocating memory which is */ -/* compatible with ECOS early releases. Later releases use a more */ -/* sophisticated means of allocating memory than this simple static */ -/* allocator, but this method is at least bound to work. */ +/* FIXME: This is a simple way of allocating memory which is */ +/* compatible with ECOS early releases. Later releases use a more */ +/* sophisticated means of allocating memory than this simple static */ +/* allocator, but this method is at least bound to work. */ static char memory[ECOS_GC_MEMORY_SIZE]; static char *brk = memory; @@ -509,8 +509,8 @@ static void *tiny_sbrk(ptrdiff_t increment) void GC_init_netbsd_elf(void) { - /* This may need to be environ, without the underscore, for */ - /* some versions. */ + /* This may need to be environ, without the underscore, for */ + /* some versions. */ GC_data_start = GC_find_limit((ptr_t)&environ, FALSE); } #endif @@ -528,19 +528,19 @@ struct exe_hdr { }; #define E_MAGIC(x) (x).magic_number -#define EMAGIC 0x5A4D +#define EMAGIC 0x5A4D #define E_LFANEW(x) (x).new_exe_offset struct e32_exe { - unsigned char magic_number[2]; - unsigned char byte_order; - unsigned char word_order; + unsigned char magic_number[2]; + unsigned char byte_order; + unsigned char word_order; unsigned long exe_format_level; - unsigned short cpu; + unsigned short cpu; unsigned short os; unsigned long padding1[13]; unsigned long object_table_offset; - unsigned long object_count; + unsigned long object_count; unsigned long padding2[31]; }; @@ -558,11 +558,11 @@ struct e32_exe { #define E32_OBJCNT(x) (x).object_count struct o32_obj { - unsigned long size; + unsigned long size; unsigned long base; - unsigned long flags; + unsigned long flags; unsigned long pagemap; - unsigned long mapsize; + unsigned long mapsize; unsigned long reserved; }; @@ -610,16 +610,16 @@ word GC_page_size; # else # if defined(MPROTECT_VDB) || defined(PROC_VDB) || defined(USE_MMAP) - void GC_setpagesize(void) - { - GC_page_size = GETPAGESIZE(); - } + void GC_setpagesize(void) + { + GC_page_size = GETPAGESIZE(); + } # else - /* It's acceptable to fake it. */ - void GC_setpagesize(void) - { - GC_page_size = HBLKSIZE; - } + /* It's acceptable to fake it. */ + void GC_setpagesize(void) + { + GC_page_size = HBLKSIZE; + } # endif # endif @@ -628,19 +628,19 @@ word GC_page_size; #ifndef CYGWIN32 # define is_writable(prot) ((prot) == PAGE_READWRITE \ - || (prot) == PAGE_WRITECOPY \ - || (prot) == PAGE_EXECUTE_READWRITE \ - || (prot) == PAGE_EXECUTE_WRITECOPY) -/* Return the number of bytes that are writable starting at p. */ -/* The pointer p is assumed to be page aligned. */ -/* If base is not 0, *base becomes the beginning of the */ -/* allocation region containing p. */ + || (prot) == PAGE_WRITECOPY \ + || (prot) == PAGE_EXECUTE_READWRITE \ + || (prot) == PAGE_EXECUTE_WRITECOPY) +/* Return the number of bytes that are writable starting at p. */ +/* The pointer p is assumed to be page aligned. */ +/* If base is not 0, *base becomes the beginning of the */ +/* allocation region containing p. */ STATIC word GC_get_writable_length(ptr_t p, ptr_t *base) { MEMORY_BASIC_INFORMATION buf; word result; word protect; - + result = VirtualQuery(p, &buf, sizeof(buf)); if (result != sizeof(buf)) ABORT("Weird VirtualQuery result"); if (base != 0) *base = (ptr_t)(buf.AllocationBase); @@ -666,22 +666,22 @@ GC_API int GC_CALL GC_get_stack_base(struct GC_stack_base *sb) } #else /* CYGWIN32 */ - -/* An alternate version for Cygwin (adapted from Dave Korn's */ -/* gcc version of boehm-gc). */ + +/* An alternate version for Cygwin (adapted from Dave Korn's */ +/* gcc version of boehm-gc). */ GC_API int GC_CALL GC_get_stack_base(struct GC_stack_base *sb) { extern void * _tlsbase __asm__ ("%fs:4"); sb -> mem_base = _tlsbase; return GC_SUCCESS; } - + #endif /* CYGWIN32 */ #define HAVE_GET_STACK_BASE -/* This is always called from the main thread. */ +/* This is always called from the main thread. */ ptr_t GC_get_main_stack_base(void) { struct GC_stack_base sb; @@ -696,9 +696,9 @@ ptr_t GC_get_main_stack_base(void) # ifdef BEOS # include ptr_t GC_get_main_stack_base(void){ - thread_info th; - get_thread_info(find_thread(NULL),&th); - return th.stack_end; + thread_info th; + get_thread_info(find_thread(NULL),&th); + return th.stack_end; } # endif /* BEOS */ @@ -709,10 +709,10 @@ ptr_t GC_get_main_stack_base(void) { PTIB ptib; PPIB ppib; - + if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) { - GC_err_printf("DosGetInfoBlocks failed\n"); - ABORT("DosGetInfoBlocks failed\n"); + GC_err_printf("DosGetInfoBlocks failed\n"); + ABORT("DosGetInfoBlocks failed\n"); } return((ptr_t)(ptib -> tib_pstacklimit)); } @@ -731,60 +731,60 @@ ptr_t GC_get_main_stack_base(void) # if defined(SUNOS5SIGS) || defined(IRIX5) || defined(OSF1) \ || defined(HURD) || defined(NETBSD) - static struct sigaction old_segv_act; -# if defined(_sigargs) /* !Irix6.x */ || defined(HPUX) \ - || defined(HURD) || defined(NETBSD) || defined(FREEBSD) - static struct sigaction old_bus_act; -# endif + static struct sigaction old_segv_act; +# if defined(_sigargs) /* !Irix6.x */ || defined(HPUX) \ + || defined(HURD) || defined(NETBSD) || defined(FREEBSD) + static struct sigaction old_bus_act; +# endif # else static handler old_segv_handler, old_bus_handler; # endif - + void GC_set_and_save_fault_handler(handler h) { -# if defined(SUNOS5SIGS) || defined(IRIX5) \ +# if defined(SUNOS5SIGS) || defined(IRIX5) \ || defined(OSF1) || defined(HURD) || defined(NETBSD) - struct sigaction act; + struct sigaction act; - act.sa_handler = h; -# if 0 /* Was necessary for Solaris 2.3 and very temporary */ - /* NetBSD bugs. */ + act.sa_handler = h; +# if 0 /* Was necessary for Solaris 2.3 and very temporary */ + /* NetBSD bugs. */ act.sa_flags = SA_RESTART | SA_NODEFER; # else act.sa_flags = SA_RESTART; -# endif - - (void) sigemptyset(&act.sa_mask); -# ifdef GC_IRIX_THREADS - /* Older versions have a bug related to retrieving and */ - /* and setting a handler at the same time. */ - (void) sigaction(SIGSEGV, 0, &old_segv_act); - (void) sigaction(SIGSEGV, &act, 0); -# else - (void) sigaction(SIGSEGV, &act, &old_segv_act); -# if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \ - || defined(HPUX) || defined(HURD) || defined(NETBSD) \ - || defined(FREEBSD) - /* Under Irix 5.x or HP/UX, we may get SIGBUS. */ - /* Pthreads doesn't exist under Irix 5.x, so we */ - /* don't have to worry in the threads case. */ - (void) sigaction(SIGBUS, &act, &old_bus_act); -# endif -# endif /* GC_IRIX_THREADS */ -# else - old_segv_handler = signal(SIGSEGV, h); -# ifdef SIGBUS - old_bus_handler = signal(SIGBUS, h); -# endif -# endif +# endif + + (void) sigemptyset(&act.sa_mask); +# ifdef GC_IRIX_THREADS + /* Older versions have a bug related to retrieving and */ + /* and setting a handler at the same time. */ + (void) sigaction(SIGSEGV, 0, &old_segv_act); + (void) sigaction(SIGSEGV, &act, 0); +# else + (void) sigaction(SIGSEGV, &act, &old_segv_act); +# if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \ + || defined(HPUX) || defined(HURD) || defined(NETBSD) \ + || defined(FREEBSD) + /* Under Irix 5.x or HP/UX, we may get SIGBUS. */ + /* Pthreads doesn't exist under Irix 5.x, so we */ + /* don't have to worry in the threads case. */ + (void) sigaction(SIGBUS, &act, &old_bus_act); +# endif +# endif /* GC_IRIX_THREADS */ +# else + old_segv_handler = signal(SIGSEGV, h); +# ifdef SIGBUS + old_bus_handler = signal(SIGBUS, h); +# endif +# endif } # endif /* NEED_FIND_LIMIT || UNIX_LIKE */ # if defined(NEED_FIND_LIMIT) || \ defined(USE_PROC_FOR_LIBRARIES) && defined(THREADS) - /* Some tools to implement HEURISTIC2 */ -# define MIN_PAGE_SIZE 256 /* Smallest conceivable page size, bytes */ - + /* Some tools to implement HEURISTIC2 */ +# define MIN_PAGE_SIZE 256 /* Smallest conceivable page size, bytes */ + /*ARGSUSED*/ STATIC void GC_fault_handler(int sig) { @@ -793,68 +793,68 @@ ptr_t GC_get_main_stack_base(void) void GC_setup_temporary_fault_handler(void) { - /* Handler is process-wide, so this should only happen in */ - /* one thread at a time. */ - GC_ASSERT(I_HOLD_LOCK()); - GC_set_and_save_fault_handler(GC_fault_handler); + /* Handler is process-wide, so this should only happen in */ + /* one thread at a time. */ + GC_ASSERT(I_HOLD_LOCK()); + GC_set_and_save_fault_handler(GC_fault_handler); } - + void GC_reset_fault_handler(void) { # if defined(SUNOS5SIGS) || defined(IRIX5) \ - || defined(OSF1) || defined(HURD) || defined(NETBSD) - (void) sigaction(SIGSEGV, &old_segv_act, 0); -# if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \ - || defined(HPUX) || defined(HURD) || defined(NETBSD) \ - || defined(FREEBSD) - (void) sigaction(SIGBUS, &old_bus_act, 0); -# endif + || defined(OSF1) || defined(HURD) || defined(NETBSD) + (void) sigaction(SIGSEGV, &old_segv_act, 0); +# if defined(IRIX5) && defined(_sigargs) /* Irix 5.x, not 6.x */ \ + || defined(HPUX) || defined(HURD) || defined(NETBSD) \ + || defined(FREEBSD) + (void) sigaction(SIGBUS, &old_bus_act, 0); +# endif # else - (void) signal(SIGSEGV, old_segv_handler); -# ifdef SIGBUS - (void) signal(SIGBUS, old_bus_handler); -# endif + (void) signal(SIGSEGV, old_segv_handler); +# ifdef SIGBUS + (void) signal(SIGBUS, old_bus_handler); +# endif # endif } - /* Return the first non-addressable location > p (up) or */ - /* the smallest location q s.t. [q,p) is addressable (!up). */ - /* We assume that p (up) or p-1 (!up) is addressable. */ - /* Requires allocation lock. */ + /* Return the first non-addressable location > p (up) or */ + /* the smallest location q s.t. [q,p) is addressable (!up). */ + /* We assume that p (up) or p-1 (!up) is addressable. */ + /* Requires allocation lock. */ STATIC ptr_t GC_find_limit_with_bound(ptr_t p, GC_bool up, ptr_t bound) { static volatile ptr_t result; - /* Safer if static, since otherwise it may not be */ - /* preserved across the longjmp. Can safely be */ - /* static since it's only called with the */ - /* allocation lock held. */ - - GC_ASSERT(I_HOLD_LOCK()); - GC_setup_temporary_fault_handler(); - if (SETJMP(GC_jmp_buf) == 0) { - result = (ptr_t)(((word)(p)) - & ~(MIN_PAGE_SIZE-1)); - for (;;) { - if (up) { - result += MIN_PAGE_SIZE; - if (result >= bound) return bound; - } else { - result -= MIN_PAGE_SIZE; - if (result <= bound) return bound; - } - GC_noop1((word)(*result)); - } - } - GC_reset_fault_handler(); - if (!up) { - result += MIN_PAGE_SIZE; - } - return(result); + /* Safer if static, since otherwise it may not be */ + /* preserved across the longjmp. Can safely be */ + /* static since it's only called with the */ + /* allocation lock held. */ + + GC_ASSERT(I_HOLD_LOCK()); + GC_setup_temporary_fault_handler(); + if (SETJMP(GC_jmp_buf) == 0) { + result = (ptr_t)(((word)(p)) + & ~(MIN_PAGE_SIZE-1)); + for (;;) { + if (up) { + result += MIN_PAGE_SIZE; + if (result >= bound) return bound; + } else { + result -= MIN_PAGE_SIZE; + if (result <= bound) return bound; + } + GC_noop1((word)(*result)); + } + } + GC_reset_fault_handler(); + if (!up) { + result += MIN_PAGE_SIZE; + } + return(result); } ptr_t GC_find_limit(ptr_t p, GC_bool up) { - return GC_find_limit_with_bound(p, up, up ? (ptr_t)(word)(-1) : 0); + return GC_find_limit_with_bound(p, up, up ? (ptr_t)(word)(-1) : 0); } # endif @@ -893,8 +893,8 @@ ptr_t GC_get_main_stack_base(void) #include #include -# define STAT_SKIP 27 /* Number of fields preceding startstack */ - /* field in /proc/self/stat */ +# define STAT_SKIP 27 /* Number of fields preceding startstack */ + /* field in /proc/self/stat */ #ifdef USE_LIBC_PRIVATES # pragma weak __libc_stack_end @@ -913,20 +913,20 @@ ptr_t GC_get_main_stack_base(void) # ifdef USE_LIBC_PRIVATES if (0 != &__libc_ia64_register_backing_store_base - && 0 != __libc_ia64_register_backing_store_base) { - /* Glibc 2.2.4 has a bug such that for dynamically linked */ - /* executables __libc_ia64_register_backing_store_base is */ - /* defined but uninitialized during constructor calls. */ - /* Hence we check for both nonzero address and value. */ - return __libc_ia64_register_backing_store_base; + && 0 != __libc_ia64_register_backing_store_base) { + /* Glibc 2.2.4 has a bug such that for dynamically linked */ + /* executables __libc_ia64_register_backing_store_base is */ + /* defined but uninitialized during constructor calls. */ + /* Hence we check for both nonzero address and value. */ + return __libc_ia64_register_backing_store_base; } # endif result = backing_store_base_from_proc(); if (0 == result) { - result = GC_find_limit(GC_save_regs_in_stack(), FALSE); - /* Now seems to work better than constant displacement */ - /* heuristic used in 6.X versions. The latter seems to */ - /* fail for 2.6 kernels. */ + result = GC_find_limit(GC_save_regs_in_stack(), FALSE); + /* Now seems to work better than constant displacement */ + /* heuristic used in 6.X versions. The latter seems to */ + /* fail for 2.6 kernels. */ } return result; } @@ -934,54 +934,54 @@ ptr_t GC_get_main_stack_base(void) STATIC ptr_t GC_linux_stack_base(void) { - /* We read the stack base value from /proc/self/stat. We do this */ + /* We read the stack base value from /proc/self/stat. We do this */ /* using direct I/O system calls in order to avoid calling malloc */ - /* in case REDIRECT_MALLOC is defined. */ + /* in case REDIRECT_MALLOC is defined. */ # define STAT_BUF_SIZE 4096 # define STAT_READ read - /* Should probably call the real read, if read is wrapped. */ + /* Should probably call the real read, if read is wrapped. */ char stat_buf[STAT_BUF_SIZE]; int f; char c; word result = 0; size_t i, buf_offset = 0; - /* First try the easy way. This should work for glibc 2.2 */ + /* First try the easy way. This should work for glibc 2.2 */ /* This fails in a prelinked ("prelink" command) executable */ - /* since the correct value of __libc_stack_end never */ - /* becomes visible to us. The second test works around */ - /* this. */ + /* since the correct value of __libc_stack_end never */ + /* becomes visible to us. The second test works around */ + /* this. */ # ifdef USE_LIBC_PRIVATES if (0 != &__libc_stack_end && 0 != __libc_stack_end ) { # if defined(IA64) - /* Some versions of glibc set the address 16 bytes too */ - /* low while the initialization code is running. */ - if (((word)__libc_stack_end & 0xfff) + 0x10 < 0x1000) { - return __libc_stack_end + 0x10; - } /* Otherwise it's not safe to add 16 bytes and we fall */ - /* back to using /proc. */ -# elif defined(SPARC) - /* Older versions of glibc for 64-bit Sparc do not set - * this variable correctly, it gets set to either zero - * or one. - */ - if (__libc_stack_end != (ptr_t) (unsigned long)0x1) - return __libc_stack_end; -# else - return __libc_stack_end; -# endif + /* Some versions of glibc set the address 16 bytes too */ + /* low while the initialization code is running. */ + if (((word)__libc_stack_end & 0xfff) + 0x10 < 0x1000) { + return __libc_stack_end + 0x10; + } /* Otherwise it's not safe to add 16 bytes and we fall */ + /* back to using /proc. */ +# elif defined(SPARC) + /* Older versions of glibc for 64-bit Sparc do not set + * this variable correctly, it gets set to either zero + * or one. + */ + if (__libc_stack_end != (ptr_t) (unsigned long)0x1) + return __libc_stack_end; +# else + return __libc_stack_end; +# endif } # endif f = open("/proc/self/stat", O_RDONLY); if (f < 0 || STAT_READ(f, stat_buf, STAT_BUF_SIZE) < 2 * STAT_SKIP) { - ABORT("Couldn't read /proc/self/stat"); + ABORT("Couldn't read /proc/self/stat"); } c = stat_buf[buf_offset++]; - /* Skip the required number of fields. This number is hopefully */ - /* constant across all Linux implementations. */ + /* Skip the required number of fields. This number is hopefully */ + /* constant across all Linux implementations. */ for (i = 0; i < STAT_SKIP; ++i) { - while (isspace(c)) c = stat_buf[buf_offset++]; - while (!isspace(c)) c = stat_buf[buf_offset++]; + while (isspace(c)) c = stat_buf[buf_offset++]; + while (!isspace(c)) c = stat_buf[buf_offset++]; } while (isspace(c)) c = stat_buf[buf_offset++]; while (isdigit(c)) { @@ -998,8 +998,8 @@ ptr_t GC_get_main_stack_base(void) #ifdef FREEBSD_STACKBOTTOM -/* This uses an undocumented sysctl call, but at least one expert */ -/* believes it will stay. */ +/* This uses an undocumented sysctl call, but at least one expert */ +/* believes it will stay. */ #include #include @@ -1011,7 +1011,7 @@ ptr_t GC_get_main_stack_base(void) ptr_t base; size_t len = sizeof(ptr_t); int r = sysctl(nm, 2, &base, &len, NULL, 0); - + if (r) ABORT("Error getting stack base"); return base; @@ -1026,53 +1026,53 @@ ptr_t GC_get_main_stack_base(void) ptr_t GC_get_main_stack_base(void) { # ifdef STACKBOTTOM - return(STACKBOTTOM); + return(STACKBOTTOM); # else -# if defined(HEURISTIC1) || defined(HEURISTIC2) - word dummy; -# endif - ptr_t result; -# define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1) -# ifdef HEURISTIC1 -# ifdef STACK_GROWS_DOWN - result = (ptr_t)((((word)(&dummy)) - + STACKBOTTOM_ALIGNMENT_M1) - & ~STACKBOTTOM_ALIGNMENT_M1); -# else - result = (ptr_t)(((word)(&dummy)) - & ~STACKBOTTOM_ALIGNMENT_M1); -# endif -# endif /* HEURISTIC1 */ -# ifdef LINUX_STACKBOTTOM - result = GC_linux_stack_base(); -# endif -# ifdef FREEBSD_STACKBOTTOM - result = GC_freebsd_stack_base(); -# endif -# ifdef HEURISTIC2 -# ifdef STACK_GROWS_DOWN - result = GC_find_limit((ptr_t)(&dummy), TRUE); -# ifdef HEURISTIC2_LIMIT - if (result > HEURISTIC2_LIMIT - && (ptr_t)(&dummy) < HEURISTIC2_LIMIT) { - result = HEURISTIC2_LIMIT; - } -# endif -# else - result = GC_find_limit((ptr_t)(&dummy), FALSE); -# ifdef HEURISTIC2_LIMIT - if (result < HEURISTIC2_LIMIT - && (ptr_t)(&dummy) > HEURISTIC2_LIMIT) { - result = HEURISTIC2_LIMIT; - } -# endif -# endif - -# endif /* HEURISTIC2 */ -# ifdef STACK_GROWS_DOWN - if (result == 0) result = (ptr_t)(signed_word)(-sizeof(ptr_t)); -# endif - return(result); +# if defined(HEURISTIC1) || defined(HEURISTIC2) + word dummy; +# endif + ptr_t result; +# define STACKBOTTOM_ALIGNMENT_M1 ((word)STACK_GRAN - 1) +# ifdef HEURISTIC1 +# ifdef STACK_GROWS_DOWN + result = (ptr_t)((((word)(&dummy)) + + STACKBOTTOM_ALIGNMENT_M1) + & ~STACKBOTTOM_ALIGNMENT_M1); +# else + result = (ptr_t)(((word)(&dummy)) + & ~STACKBOTTOM_ALIGNMENT_M1); +# endif +# endif /* HEURISTIC1 */ +# ifdef LINUX_STACKBOTTOM + result = GC_linux_stack_base(); +# endif +# ifdef FREEBSD_STACKBOTTOM + result = GC_freebsd_stack_base(); +# endif +# ifdef HEURISTIC2 +# ifdef STACK_GROWS_DOWN + result = GC_find_limit((ptr_t)(&dummy), TRUE); +# ifdef HEURISTIC2_LIMIT + if (result > HEURISTIC2_LIMIT + && (ptr_t)(&dummy) < HEURISTIC2_LIMIT) { + result = HEURISTIC2_LIMIT; + } +# endif +# else + result = GC_find_limit((ptr_t)(&dummy), FALSE); +# ifdef HEURISTIC2_LIMIT + if (result < HEURISTIC2_LIMIT + && (ptr_t)(&dummy) > HEURISTIC2_LIMIT) { + result = HEURISTIC2_LIMIT; + } +# endif +# endif + +# endif /* HEURISTIC2 */ +# ifdef STACK_GROWS_DOWN + if (result == 0) result = (ptr_t)(signed_word)(-sizeof(ptr_t)); +# endif + return(result); # endif /* STACKBOTTOM */ } @@ -1085,7 +1085,7 @@ ptr_t GC_get_main_stack_base(void) #ifdef IA64 ptr_t GC_greatest_stack_base_below(ptr_t bound); - /* From pthread_support.c */ + /* From pthread_support.c */ #endif GC_API int GC_CALL GC_get_stack_base(struct GC_stack_base *b) @@ -1094,38 +1094,38 @@ GC_API int GC_CALL GC_get_stack_base(struct GC_stack_base *b) size_t size; if (pthread_getattr_np(pthread_self(), &attr) != 0) { - WARN("pthread_getattr_np failed\n", 0); - return GC_UNIMPLEMENTED; + WARN("pthread_getattr_np failed\n", 0); + return GC_UNIMPLEMENTED; } if (pthread_attr_getstack(&attr, &(b -> mem_base), &size) != 0) { - ABORT("pthread_attr_getstack failed"); + ABORT("pthread_attr_getstack failed"); } pthread_attr_destroy(&attr); # ifdef STACK_GROWS_DOWN b -> mem_base = (char *)(b -> mem_base) + size; # endif # ifdef IA64 - /* We could try backing_store_base_from_proc, but that's safe */ - /* only if no mappings are being asynchronously created. */ - /* Subtracting the size from the stack base doesn't work for at */ - /* least the main thread. */ + /* We could try backing_store_base_from_proc, but that's safe */ + /* only if no mappings are being asynchronously created. */ + /* Subtracting the size from the stack base doesn't work for at */ + /* least the main thread. */ LOCK(); { IF_CANCEL(int cancel_state;) - ptr_t bsp; - ptr_t next_stack; + ptr_t bsp; + ptr_t next_stack; - DISABLE_CANCEL(cancel_state); - bsp = GC_save_regs_in_stack(); - next_stack = GC_greatest_stack_base_below(bsp); - if (0 == next_stack) { + DISABLE_CANCEL(cancel_state); + bsp = GC_save_regs_in_stack(); + next_stack = GC_greatest_stack_base_below(bsp); + if (0 == next_stack) { b -> reg_base = GC_find_limit(bsp, FALSE); - } else { - /* Avoid walking backwards into preceding memory stack and */ - /* growing it. */ + } else { + /* Avoid walking backwards into preceding memory stack and */ + /* growing it. */ b -> reg_base = GC_find_limit_with_bound(bsp, FALSE, next_stack); - } - RESTORE_CANCEL(cancel_state); + } + RESTORE_CANCEL(cancel_state); } UNLOCK(); # endif @@ -1137,13 +1137,13 @@ GC_API int GC_CALL GC_get_stack_base(struct GC_stack_base *b) #endif /* GC_LINUX_THREADS */ #ifndef HAVE_GET_STACK_BASE -/* Retrieve stack base. */ -/* Using the GC_find_limit version is risky. */ -/* On IA64, for example, there is no guard page between the */ -/* stack of one thread and the register backing store of the */ -/* next. Thus this is likely to identify way too large a */ -/* "stack" and thus at least result in disastrous performance. */ -/* FIXME - Implement better strategies here. */ +/* Retrieve stack base. */ +/* Using the GC_find_limit version is risky. */ +/* On IA64, for example, there is no guard page between the */ +/* stack of one thread and the register backing store of the */ +/* next. Thus this is likely to identify way too large a */ +/* "stack" and thus at least result in disastrous performance. */ +/* FIXME - Implement better strategies here. */ GC_API int GC_CALL GC_get_stack_base(struct GC_stack_base *b) { # ifdef NEED_FIND_LIMIT @@ -1151,12 +1151,12 @@ GC_API int GC_CALL GC_get_stack_base(struct GC_stack_base *b) IF_CANCEL(int cancel_state;) DISABLE_CANCEL(cancel_state); /* May be unnecessary? */ # ifdef STACK_GROWS_DOWN - b -> mem_base = GC_find_limit((ptr_t)(&dummy), TRUE); + b -> mem_base = GC_find_limit((ptr_t)(&dummy), TRUE); # ifdef IA64 - b -> reg_base = GC_find_limit(GC_save_regs_in_stack(), FALSE); + b -> reg_base = GC_find_limit(GC_save_regs_in_stack(), FALSE); # endif # else - b -> mem_base = GC_find_limit(&dummy, FALSE); + b -> mem_base = GC_find_limit(&dummy, FALSE); # endif RESTORE_CANCEL(cancel_state); return GC_SUCCESS; @@ -1184,20 +1184,20 @@ void GC_register_data_segments(void) # define PBUFSIZ 512 UCHAR path[PBUFSIZ]; FILE * myexefile; - struct exe_hdr hdrdos; /* MSDOS header. */ - struct e32_exe hdr386; /* Real header for my executable */ - struct o32_obj seg; /* Currrent segment */ + struct exe_hdr hdrdos; /* MSDOS header. */ + struct e32_exe hdr386; /* Real header for my executable */ + struct o32_obj seg; /* Currrent segment */ int nsegs; - - + + if (DosGetInfoBlocks(&ptib, &ppib) != NO_ERROR) { - GC_err_printf("DosGetInfoBlocks failed\n"); - ABORT("DosGetInfoBlocks failed\n"); + GC_err_printf("DosGetInfoBlocks failed\n"); + ABORT("DosGetInfoBlocks failed\n"); } module_handle = ppib -> pib_hmte; if (DosQueryModuleName(module_handle, PBUFSIZ, path) != NO_ERROR) { - GC_err_printf("DosQueryModuleName failed\n"); - ABORT("DosGetInfoBlocks failed\n"); + GC_err_printf("DosQueryModuleName failed\n"); + ABORT("DosGetInfoBlocks failed\n"); } myexefile = fopen(path, "rb"); if (myexefile == 0) { @@ -1241,7 +1241,7 @@ void GC_register_data_segments(void) EXIT(); } if (fseek(myexefile, E_LFANEW(hdrdos) + E32_OBJTAB(hdr386), - SEEK_SET) != 0) { + SEEK_SET) != 0) { GC_err_puts("Seek to object table failed: "); GC_err_puts(path); GC_err_puts("\n"); ABORT("Seek to object table failed"); @@ -1259,9 +1259,9 @@ void GC_register_data_segments(void) if (flags & OBJINVALID) { GC_err_printf("Object with invalid pages?\n"); continue; - } + } GC_add_roots_inner((ptr_t)O32_BASE(seg), - (ptr_t)(O32_BASE(seg)+O32_SIZE(seg)), FALSE); + (ptr_t)(O32_BASE(seg)+O32_SIZE(seg)), FALSE); } } @@ -1302,29 +1302,29 @@ void GC_register_data_segments(void) return; # if defined(MPROTECT_VDB) - { - char * str = GETENV("GC_USE_GETWRITEWATCH"); -# if defined(GC_PREFER_MPROTECT_VDB) - if (str == NULL || (*str == '0' && *(str + 1) == '\0')) { - /* GC_USE_GETWRITEWATCH is unset or set to "0". */ - done = TRUE; /* falling back to MPROTECT_VDB strategy. */ - /* This should work as if GWW_VDB is undefined. */ - return; - } -# else - if (str != NULL && *str == '0' && *(str + 1) == '\0') { - /* GC_USE_GETWRITEWATCH is set "0". */ - done = TRUE; /* falling back to MPROTECT_VDB strategy. */ - return; - } -# endif - } + { + char * str = GETENV("GC_USE_GETWRITEWATCH"); +# if defined(GC_PREFER_MPROTECT_VDB) + if (str == NULL || (*str == '0' && *(str + 1) == '\0')) { + /* GC_USE_GETWRITEWATCH is unset or set to "0". */ + done = TRUE; /* falling back to MPROTECT_VDB strategy. */ + /* This should work as if GWW_VDB is undefined. */ + return; + } +# else + if (str != NULL && *str == '0' && *(str + 1) == '\0') { + /* GC_USE_GETWRITEWATCH is set "0". */ + done = TRUE; /* falling back to MPROTECT_VDB strategy. */ + return; + } +# endif + } # endif hK32 = GetModuleHandle(TEXT("kernel32.dll")); if (hK32 != (HMODULE)0 && (GetWriteWatch_func = (GetWriteWatch_type)GetProcAddress(hK32, - "GetWriteWatch")) != NULL) { + "GetWriteWatch")) != NULL) { /* Also check whether VirtualAlloc accepts MEM_WRITE_WATCH, */ /* as some versions of kernel32.dll have one but not the */ /* other, making the feature completely broken. */ @@ -1335,9 +1335,9 @@ void GC_register_data_segments(void) PVOID pages[16]; ULONG_PTR count = 16; DWORD page_size; - /* Check that it actually works. In spite of some */ - /* documentation it actually seems to exist on W2K. */ - /* This test may be unnecessary, but ... */ + /* Check that it actually works. In spite of some */ + /* documentation it actually seems to exist on W2K. */ + /* This test may be unnecessary, but ... */ if (GetWriteWatch_func(WRITE_WATCH_FLAG_RESET, page, GC_page_size, pages, @@ -1371,30 +1371,30 @@ void GC_register_data_segments(void) # if defined(MSWIN32) || defined(MSWINCE) # ifdef MSWIN32 - /* Unfortunately, we have to handle win32s very differently from NT, */ - /* Since VirtualQuery has very different semantics. In particular, */ - /* under win32s a VirtualQuery call on an unmapped page returns an */ - /* invalid result. Under NT, GC_register_data_segments is a no-op */ - /* and all real work is done by GC_register_dynamic_libraries. Under */ - /* win32s, we cannot find the data segments associated with dll's. */ - /* We register the main data segment here. */ + /* Unfortunately, we have to handle win32s very differently from NT, */ + /* Since VirtualQuery has very different semantics. In particular, */ + /* under win32s a VirtualQuery call on an unmapped page returns an */ + /* invalid result. Under NT, GC_register_data_segments is a no-op */ + /* and all real work is done by GC_register_dynamic_libraries. Under */ + /* win32s, we cannot find the data segments associated with dll's. */ + /* We register the main data segment here. */ GC_bool GC_no_win32_dlls = FALSE; - /* This used to be set for gcc, to avoid dealing with */ - /* the structured exception handling issues. But we now have */ - /* assembly code to do that right. */ + /* This used to be set for gcc, to avoid dealing with */ + /* the structured exception handling issues. But we now have */ + /* assembly code to do that right. */ GC_bool GC_wnt = FALSE; /* This is a Windows NT derivative, i.e. NT, W2K, XP or later. */ - + # ifdef USE_MUNMAP extern int GC_unmap_threshold; /* defined in allchblk.c */ # endif void GC_init_win32(void) { - /* Set GC_wnt. */ + /* Set GC_wnt. */ /* If we're running under win32s, assume that no DLLs will be loaded */ - /* I doubt anyone still runs win32s, but ... */ + /* I doubt anyone still runs win32s, but ... */ DWORD v = GetVersion(); GC_wnt = !(v & 0x80000000); GC_no_win32_dlls |= ((!GC_wnt) && (v & 0xff) <= 3); @@ -1407,48 +1407,48 @@ void GC_register_data_segments(void) # endif } - /* Return the smallest address a such that VirtualQuery */ - /* returns correct results for all addresses between a and start. */ - /* Assumes VirtualQuery returns correct information for start. */ + /* Return the smallest address a such that VirtualQuery */ + /* returns correct results for all addresses between a and start. */ + /* Assumes VirtualQuery returns correct information for start. */ STATIC ptr_t GC_least_described_address(ptr_t start) - { + { MEMORY_BASIC_INFORMATION buf; size_t result; LPVOID limit; ptr_t p; LPVOID q; - + limit = GC_sysinfo.lpMinimumApplicationAddress; p = (ptr_t)((word)start & ~(GC_page_size - 1)); for (;;) { - q = (LPVOID)(p - GC_page_size); - if ((ptr_t)q > (ptr_t)p /* underflow */ || q < limit) break; - result = VirtualQuery(q, &buf, sizeof(buf)); - if (result != sizeof(buf) || buf.AllocationBase == 0) break; - p = (ptr_t)(buf.AllocationBase); + q = (LPVOID)(p - GC_page_size); + if ((ptr_t)q > (ptr_t)p /* underflow */ || q < limit) break; + result = VirtualQuery(q, &buf, sizeof(buf)); + if (result != sizeof(buf) || buf.AllocationBase == 0) break; + p = (ptr_t)(buf.AllocationBase); } return p; } # endif # ifndef REDIRECT_MALLOC - /* We maintain a linked list of AllocationBase values that we know */ + /* We maintain a linked list of AllocationBase values that we know */ /* correspond to malloc heap sections. Currently this is only called */ - /* during a GC. But there is some hope that for long running */ - /* programs we will eventually see most heap sections. */ + /* during a GC. But there is some hope that for long running */ + /* programs we will eventually see most heap sections. */ - /* In the long run, it would be more reliable to occasionally walk */ - /* the malloc heap with HeapWalk on the default heap. But that */ - /* apparently works only for NT-based Windows. */ + /* In the long run, it would be more reliable to occasionally walk */ + /* the malloc heap with HeapWalk on the default heap. But that */ + /* apparently works only for NT-based Windows. */ - /* In the long run, a better data structure would also be nice ... */ + /* In the long run, a better data structure would also be nice ... */ STATIC struct GC_malloc_heap_list { void * allocation_base; struct GC_malloc_heap_list *next; } *GC_malloc_heap_l = 0; - /* Is p the base of one of the malloc heap sections we already know */ - /* about? */ + /* Is p the base of one of the malloc heap sections we already know */ + /* about? */ STATIC GC_bool GC_is_malloc_heap_base(ptr_t p) { struct GC_malloc_heap_list *q = GC_malloc_heap_l; @@ -1470,7 +1470,7 @@ void GC_register_data_segments(void) return buf.AllocationBase; } - STATIC size_t GC_max_root_size = 100000; /* Appr. largest root size. */ + STATIC size_t GC_max_root_size = 100000; /* Appr. largest root size. */ void GC_add_current_malloc_heap(void) { @@ -1480,38 +1480,38 @@ void GC_register_data_segments(void) if (new_l == 0) return; if (GC_is_malloc_heap_base(candidate)) { - /* Try a little harder to find malloc heap. */ - size_t req_size = 10000; - do { - void *p = malloc(req_size); - if (0 == p) { free(new_l); return; } - candidate = GC_get_allocation_base(p); - free(p); - req_size *= 2; - } while (GC_is_malloc_heap_base(candidate) - && req_size < GC_max_root_size/10 && req_size < 500000); - if (GC_is_malloc_heap_base(candidate)) { - free(new_l); return; - } + /* Try a little harder to find malloc heap. */ + size_t req_size = 10000; + do { + void *p = malloc(req_size); + if (0 == p) { free(new_l); return; } + candidate = GC_get_allocation_base(p); + free(p); + req_size *= 2; + } while (GC_is_malloc_heap_base(candidate) + && req_size < GC_max_root_size/10 && req_size < 500000); + if (GC_is_malloc_heap_base(candidate)) { + free(new_l); return; + } } if (GC_print_stats) - GC_log_printf("Found new system malloc AllocationBase at %p\n", + GC_log_printf("Found new system malloc AllocationBase at %p\n", candidate); new_l -> allocation_base = candidate; new_l -> next = GC_malloc_heap_l; GC_malloc_heap_l = new_l; } # endif /* REDIRECT_MALLOC */ - - STATIC word GC_n_heap_bases = 0; /* See GC_heap_bases. */ + + STATIC word GC_n_heap_bases = 0; /* See GC_heap_bases. */ /* Is p the start of either the malloc heap, or of one of our */ - /* heap sections? */ + /* heap sections? */ GC_bool GC_is_heap_base (ptr_t p) { - + unsigned i; - + # ifndef REDIRECT_MALLOC if (GC_root_size > GC_max_root_size) GC_max_root_size = GC_root_size; if (GC_is_malloc_heap_base(p)) return TRUE; @@ -1531,7 +1531,7 @@ void GC_register_data_segments(void) LPVOID p; char * base; char * limit, * new_limit; - + if (!GC_no_win32_dlls) return; p = base = limit = GC_least_described_address(static_root); while (p < GC_sysinfo.lpMaximumApplicationAddress) { @@ -1556,7 +1556,7 @@ void GC_register_data_segments(void) if (base != limit) GC_add_roots_inner(base, limit, FALSE); } #endif - + void GC_register_data_segments(void) { # ifdef MSWIN32 @@ -1572,58 +1572,58 @@ void GC_register_data_segments(void) ptr_t GC_SysVGetDataStart(size_t max_page_size, ptr_t etext_addr) { word text_end = ((word)(etext_addr) + sizeof(word) - 1) - & ~(sizeof(word) - 1); - /* etext rounded to word boundary */ + & ~(sizeof(word) - 1); + /* etext rounded to word boundary */ word next_page = ((text_end + (word)max_page_size - 1) - & ~((word)max_page_size - 1)); + & ~((word)max_page_size - 1)); word page_offset = (text_end & ((word)max_page_size - 1)); volatile char * result = (char *)(next_page + page_offset); - /* Note that this isnt equivalent to just adding */ - /* max_page_size to &etext if &etext is at a page boundary */ - + /* Note that this isnt equivalent to just adding */ + /* max_page_size to &etext if &etext is at a page boundary */ + GC_setup_temporary_fault_handler(); if (SETJMP(GC_jmp_buf) == 0) { - /* Try writing to the address. */ - *result = *result; + /* Try writing to the address. */ + *result = *result; GC_reset_fault_handler(); } else { GC_reset_fault_handler(); - /* We got here via a longjmp. The address is not readable. */ - /* This is known to happen under Solaris 2.4 + gcc, which place */ - /* string constants in the text segment, but after etext. */ - /* Use plan B. Note that we now know there is a gap between */ - /* text and data segments, so plan A bought us something. */ - result = (char *)GC_find_limit((ptr_t)(DATAEND), FALSE); + /* We got here via a longjmp. The address is not readable. */ + /* This is known to happen under Solaris 2.4 + gcc, which place */ + /* string constants in the text segment, but after etext. */ + /* Use plan B. Note that we now know there is a gap between */ + /* text and data segments, so plan A bought us something. */ + result = (char *)GC_find_limit((ptr_t)(DATAEND), FALSE); } return((ptr_t)result); } # endif # if defined(FREEBSD) && (defined(I386) || defined(X86_64) || defined(powerpc) || defined(__powerpc__)) && !defined(PCR) -/* Its unclear whether this should be identical to the above, or */ -/* whether it should apply to non-X86 architectures. */ -/* For now we don't assume that there is always an empty page after */ +/* Its unclear whether this should be identical to the above, or */ +/* whether it should apply to non-X86 architectures. */ +/* For now we don't assume that there is always an empty page after */ /* etext. But in some cases there actually seems to be slightly more. */ -/* This also deals with holes between read-only data and writable data. */ +/* This also deals with holes between read-only data and writable data. */ ptr_t GC_FreeBSDGetDataStart(size_t max_page_size, ptr_t etext_addr) { word text_end = ((word)(etext_addr) + sizeof(word) - 1) - & ~(sizeof(word) - 1); - /* etext rounded to word boundary */ + & ~(sizeof(word) - 1); + /* etext rounded to word boundary */ volatile word next_page = (text_end + (word)max_page_size - 1) - & ~((word)max_page_size - 1); + & ~((word)max_page_size - 1); volatile ptr_t result = (ptr_t)text_end; GC_setup_temporary_fault_handler(); if (SETJMP(GC_jmp_buf) == 0) { - /* Try reading at the address. */ - /* This should happen before there is another thread. */ - for (; next_page < (word)(DATAEND); next_page += (word)max_page_size) - *(volatile char *)next_page; - GC_reset_fault_handler(); + /* Try reading at the address. */ + /* This should happen before there is another thread. */ + for (; next_page < (word)(DATAEND); next_page += (word)max_page_size) + *(volatile char *)next_page; + GC_reset_fault_handler(); } else { - GC_reset_fault_handler(); - /* As above, we go to plan B */ - result = GC_find_limit((ptr_t)(DATAEND), FALSE); + GC_reset_fault_handler(); + /* As above, we go to plan B */ + result = GC_find_limit((ptr_t)(DATAEND), FALSE); } return(result); } @@ -1643,16 +1643,16 @@ void GC_register_data_segments(void) { # if !defined(PCR) && !defined(MACOS) # if defined(REDIRECT_MALLOC) && defined(GC_SOLARIS_THREADS) - /* As of Solaris 2.3, the Solaris threads implementation */ - /* allocates the data structure for the initial thread with */ - /* sbrk at process startup. It needs to be scanned, so that */ - /* we don't lose some malloc allocated data structures */ - /* hanging from it. We're on thin ice here ... */ + /* As of Solaris 2.3, the Solaris threads implementation */ + /* allocates the data structure for the initial thread with */ + /* sbrk at process startup. It needs to be scanned, so that */ + /* we don't lose some malloc allocated data structures */ + /* hanging from it. We're on thin ice here ... */ extern caddr_t sbrk(int); - GC_add_roots_inner(DATASTART, (ptr_t)sbrk(0), FALSE); + GC_add_roots_inner(DATASTART, (ptr_t)sbrk(0), FALSE); # else - GC_add_roots_inner(DATASTART, (ptr_t)(DATAEND), FALSE); + GC_add_roots_inner(DATASTART, (ptr_t)(DATAEND), FALSE); # if defined(DATASTART2) GC_add_roots_inner(DATASTART2, (ptr_t)(DATAEND2), FALSE); # endif @@ -1661,31 +1661,31 @@ void GC_register_data_segments(void) # if defined(MACOS) { # if defined(THINK_C) - extern void* GC_MacGetDataStart(void); - /* globals begin above stack and end at a5. */ - GC_add_roots_inner((ptr_t)GC_MacGetDataStart(), - (ptr_t)LMGetCurrentA5(), FALSE); + extern void* GC_MacGetDataStart(void); + /* globals begin above stack and end at a5. */ + GC_add_roots_inner((ptr_t)GC_MacGetDataStart(), + (ptr_t)LMGetCurrentA5(), FALSE); # else # if defined(__MWERKS__) # if !__POWERPC__ - extern void* GC_MacGetDataStart(void); - /* MATTHEW: Function to handle Far Globals (CW Pro 3) */ + extern void* GC_MacGetDataStart(void); + /* MATTHEW: Function to handle Far Globals (CW Pro 3) */ # if __option(far_data) - extern void* GC_MacGetDataEnd(void); + extern void* GC_MacGetDataEnd(void); # endif - /* globals begin above stack and end at a5. */ - GC_add_roots_inner((ptr_t)GC_MacGetDataStart(), - (ptr_t)LMGetCurrentA5(), FALSE); - /* MATTHEW: Handle Far Globals */ + /* globals begin above stack and end at a5. */ + GC_add_roots_inner((ptr_t)GC_MacGetDataStart(), + (ptr_t)LMGetCurrentA5(), FALSE); + /* MATTHEW: Handle Far Globals */ # if __option(far_data) /* Far globals follow he QD globals: */ - GC_add_roots_inner((ptr_t)LMGetCurrentA5(), - (ptr_t)GC_MacGetDataEnd(), FALSE); + GC_add_roots_inner((ptr_t)LMGetCurrentA5(), + (ptr_t)GC_MacGetDataEnd(), FALSE); # endif # else - extern char __data_start__[], __data_end__[]; - GC_add_roots_inner((ptr_t)&__data_start__, - (ptr_t)&__data_end__, FALSE); + extern char __data_start__[], __data_end__[]; + GC_add_roots_inner((ptr_t)&__data_start__, + (ptr_t)&__data_end__, FALSE); # endif /* __POWERPC__ */ # endif /* __MWERKS__ */ # endif /* !THINK_C */ @@ -1693,7 +1693,7 @@ void GC_register_data_segments(void) # endif /* MACOS */ /* Dynamic libraries are added at every collection, since they may */ - /* change. */ + /* change. */ } # endif /* ! AMIGA */ @@ -1705,8 +1705,8 @@ void GC_register_data_segments(void) */ # if !defined(OS2) && !defined(PCR) && !defined(AMIGA) \ - && !defined(MSWIN32) && !defined(MSWINCE) \ - && !defined(MACOS) && !defined(DOS4GW) && !defined(NONSTOP) + && !defined(MSWIN32) && !defined(MSWINCE) \ + && !defined(MACOS) && !defined(DOS4GW) && !defined(NONSTOP) # define SBRK_ARG_T ptrdiff_t @@ -1714,8 +1714,8 @@ void GC_register_data_segments(void) #ifdef USE_MMAP_FIXED # define GC_MMAP_FLAGS MAP_FIXED | MAP_PRIVATE - /* Seems to yield better performance on Solaris 2, but can */ - /* be unreliable if something is already mapped at the address. */ + /* Seems to yield better performance on Solaris 2, but can */ + /* be unreliable if something is already mapped at the address. */ #else # define GC_MMAP_FLAGS MAP_PRIVATE #endif @@ -1730,7 +1730,7 @@ void GC_register_data_segments(void) #else static int zero_fd; # define OPT_MAP_ANON 0 -#endif +#endif #ifndef HEAP_START # define HEAP_START ((ptr_t)0) @@ -1745,26 +1745,26 @@ STATIC ptr_t GC_unix_mmap_get_mem(word bytes) static GC_bool initialized = FALSE; if (!initialized) { - zero_fd = open("/dev/zero", O_RDONLY); - fcntl(zero_fd, F_SETFD, FD_CLOEXEC); - initialized = TRUE; + zero_fd = open("/dev/zero", O_RDONLY); + fcntl(zero_fd, F_SETFD, FD_CLOEXEC); + initialized = TRUE; } # endif if (bytes & (GC_page_size -1)) ABORT("Bad GET_MEM arg"); result = mmap(last_addr, bytes, PROT_READ | PROT_WRITE | OPT_PROT_EXEC, - GC_MMAP_FLAGS | OPT_MAP_ANON, zero_fd, 0/* offset */); + GC_MMAP_FLAGS | OPT_MAP_ANON, zero_fd, 0/* offset */); if (result == MAP_FAILED) return(0); last_addr = (ptr_t)result + bytes + GC_page_size - 1; last_addr = (ptr_t)((word)last_addr & ~(GC_page_size - 1)); # if !defined(LINUX) if (last_addr == 0) { - /* Oops. We got the end of the address space. This isn't */ - /* usable by arbitrary C code, since one-past-end pointers */ - /* don't work, so we discard it and try again. */ - munmap(result, (size_t)(-GC_page_size) - (size_t)result); - /* Leave last page mapped, so we can't repeat. */ - return GC_unix_mmap_get_mem(bytes); + /* Oops. We got the end of the address space. This isn't */ + /* usable by arbitrary C code, since one-past-end pointers */ + /* don't work, so we discard it and try again. */ + munmap(result, (size_t)(-GC_page_size) - (size_t)result); + /* Leave last page mapped, so we can't repeat. */ + return GC_unix_mmap_get_mem(bytes); } # else GC_ASSERT(last_addr != 0); @@ -1787,31 +1787,31 @@ STATIC ptr_t GC_unix_sbrk_get_mem(word bytes) { ptr_t result; # ifdef IRIX5 - /* Bare sbrk isn't thread safe. Play by malloc rules. */ - /* The equivalent may be needed on other systems as well. */ + /* Bare sbrk isn't thread safe. Play by malloc rules. */ + /* The equivalent may be needed on other systems as well. */ __LOCK_MALLOC(); # endif { ptr_t cur_brk = (ptr_t)sbrk(0); SBRK_ARG_T lsbs = (word)cur_brk & (GC_page_size-1); - + if ((SBRK_ARG_T)bytes < 0) { - result = 0; /* too big */ - goto out; + result = 0; /* too big */ + goto out; } if (lsbs != 0) { if((ptr_t)sbrk(GC_page_size - lsbs) == (ptr_t)(-1)) { - result = 0; - goto out; - } + result = 0; + goto out; + } } # ifdef ADD_HEAP_GUARD_PAGES /* This is useful for catching severe memory overwrite problems that */ - /* span heap sections. It shouldn't otherwise be turned on. */ + /* span heap sections. It shouldn't otherwise be turned on. */ { - ptr_t guard = (ptr_t)sbrk((SBRK_ARG_T)GC_page_size); - if (mprotect(guard, GC_page_size, PROT_NONE) != 0) - ABORT("ADD_HEAP_GUARD_PAGES: mprotect failed"); + ptr_t guard = (ptr_t)sbrk((SBRK_ARG_T)GC_page_size); + if (mprotect(guard, GC_page_size, PROT_NONE) != 0) + ABORT("ADD_HEAP_GUARD_PAGES: mprotect failed"); } # endif /* ADD_HEAP_GUARD_PAGES */ result = (ptr_t)sbrk((SBRK_ARG_T)bytes); @@ -1834,12 +1834,12 @@ ptr_t GC_unix_get_mem(word bytes) if (!sbrk_failed) result = GC_unix_sbrk_get_mem(bytes); if (0 == result) { - sbrk_failed = TRUE; - result = GC_unix_mmap_get_mem(bytes); + sbrk_failed = TRUE; + result = GC_unix_mmap_get_mem(bytes); } if (0 == result) { - /* Try sbrk again, in case sbrk memory became available. */ - result = GC_unix_sbrk_get_mem(bytes); + /* Try sbrk again, in case sbrk memory became available. */ + result = GC_unix_sbrk_get_mem(bytes); } return result; } @@ -1864,9 +1864,9 @@ void * os2_alloc(size_t bytes) void * result; if (DosAllocMem(&result, bytes, PAG_EXECUTE | PAG_READ | - PAG_WRITE | PAG_COMMIT) - != NO_ERROR) { - return(0); + PAG_WRITE | PAG_COMMIT) + != NO_ERROR) { + return(0); } if (result == 0) return(os2_alloc(bytes)); return(result); @@ -1889,9 +1889,9 @@ SYSTEM_INFO GC_sysinfo; #ifdef GC_USE_MEM_TOP_DOWN STATIC DWORD GC_mem_top_down = MEM_TOP_DOWN; - /* Use GC_USE_MEM_TOP_DOWN for better 64-bit */ - /* testing. Otherwise all addresses tend to */ - /* end up in first 4GB, hiding bugs. */ + /* Use GC_USE_MEM_TOP_DOWN for better 64-bit */ + /* testing. Otherwise all addresses tend to */ + /* end up in first 4GB, hiding bugs. */ #else STATIC DWORD GC_mem_top_down = 0; #endif @@ -1901,20 +1901,20 @@ ptr_t GC_win32_get_mem(word bytes) ptr_t result; if (GLOBAL_ALLOC_TEST) { - /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE. */ - /* There are also unconfirmed rumors of other */ - /* problems, so we dodge the issue. */ + /* VirtualAlloc doesn't like PAGE_EXECUTE_READWRITE. */ + /* There are also unconfirmed rumors of other */ + /* problems, so we dodge the issue. */ result = (ptr_t) GlobalAlloc(0, bytes + HBLKSIZE); result = (ptr_t)(((word)result + HBLKSIZE - 1) & ~(HBLKSIZE-1)); } else { - /* VirtualProtect only works on regions returned by a */ - /* single VirtualAlloc call. Thus we allocate one */ - /* extra page, which will prevent merging of blocks */ - /* in separate regions, and eliminate any temptation */ - /* to call VirtualProtect on a range spanning regions. */ - /* This wastes a small amount of memory, and risks */ - /* increased fragmentation. But better alternatives */ - /* would require effort. */ + /* VirtualProtect only works on regions returned by a */ + /* single VirtualAlloc call. Thus we allocate one */ + /* extra page, which will prevent merging of blocks */ + /* in separate regions, and eliminate any temptation */ + /* to call VirtualProtect on a range spanning regions. */ + /* This wastes a small amount of memory, and risks */ + /* increased fragmentation. But better alternatives */ + /* would require effort. */ # ifdef MPROTECT_VDB /* We can't check for GC_incremental here (because */ /* GC_enable_incremental() might be called some time */ @@ -1934,25 +1934,25 @@ ptr_t GC_win32_get_mem(word bytes) /* SP2). */ result = (ptr_t) VirtualAlloc(NULL, bytes + VIRTUAL_ALLOC_PAD, GetWriteWatch_alloc_flag | - MEM_COMMIT | MEM_RESERVE - | GC_mem_top_down, - PAGE_EXECUTE_READWRITE); + MEM_COMMIT | MEM_RESERVE + | GC_mem_top_down, + PAGE_EXECUTE_READWRITE); } if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result"); - /* If I read the documentation correctly, this can */ - /* only happen if HBLKSIZE > 64k or not a power of 2. */ + /* If I read the documentation correctly, this can */ + /* only happen if HBLKSIZE > 64k or not a power of 2. */ if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections"); if (0 != result) GC_heap_bases[GC_n_heap_bases++] = result; - return(result); + return(result); } GC_API void GC_CALL GC_win32_free_heap(void) { if (GC_no_win32_dlls) { - while (GC_n_heap_bases > 0) { - GlobalFree (GC_heap_bases[--GC_n_heap_bases]); - GC_heap_bases[GC_n_heap_bases] = 0; - } + while (GC_n_heap_bases > 0) { + GlobalFree (GC_heap_bases[--GC_n_heap_bases]); + GC_heap_bases[GC_n_heap_bases] = 0; + } } } # endif @@ -1975,53 +1975,53 @@ ptr_t GC_wince_get_mem(word bytes) /* Try to find reserved, uncommitted pages */ for (i = 0; i < GC_n_heap_bases; i++) { - if (((word)(-(signed_word)GC_heap_lengths[i]) - & (GC_sysinfo.dwAllocationGranularity-1)) - >= bytes) { - result = GC_heap_bases[i] + GC_heap_lengths[i]; - break; - } + if (((word)(-(signed_word)GC_heap_lengths[i]) + & (GC_sysinfo.dwAllocationGranularity-1)) + >= bytes) { + result = GC_heap_bases[i] + GC_heap_lengths[i]; + break; + } } if (i == GC_n_heap_bases) { - /* Reserve more pages */ - word res_bytes = (bytes + GC_sysinfo.dwAllocationGranularity-1) - & ~(GC_sysinfo.dwAllocationGranularity-1); - /* If we ever support MPROTECT_VDB here, we will probably need to */ - /* ensure that res_bytes is strictly > bytes, so that VirtualProtect */ - /* never spans regions. It seems to be OK for a VirtualFree */ - /* argument to span regions, so we should be OK for now. */ - result = (ptr_t) VirtualAlloc(NULL, res_bytes, - MEM_RESERVE | MEM_TOP_DOWN, - PAGE_EXECUTE_READWRITE); - if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result"); - /* If I read the documentation correctly, this can */ - /* only happen if HBLKSIZE > 64k or not a power of 2. */ - if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections"); - if (result == NULL) return NULL; - GC_heap_bases[GC_n_heap_bases] = result; - GC_heap_lengths[GC_n_heap_bases] = 0; - GC_n_heap_bases++; + /* Reserve more pages */ + word res_bytes = (bytes + GC_sysinfo.dwAllocationGranularity-1) + & ~(GC_sysinfo.dwAllocationGranularity-1); + /* If we ever support MPROTECT_VDB here, we will probably need to */ + /* ensure that res_bytes is strictly > bytes, so that VirtualProtect */ + /* never spans regions. It seems to be OK for a VirtualFree */ + /* argument to span regions, so we should be OK for now. */ + result = (ptr_t) VirtualAlloc(NULL, res_bytes, + MEM_RESERVE | MEM_TOP_DOWN, + PAGE_EXECUTE_READWRITE); + if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result"); + /* If I read the documentation correctly, this can */ + /* only happen if HBLKSIZE > 64k or not a power of 2. */ + if (GC_n_heap_bases >= MAX_HEAP_SECTS) ABORT("Too many heap sections"); + if (result == NULL) return NULL; + GC_heap_bases[GC_n_heap_bases] = result; + GC_heap_lengths[GC_n_heap_bases] = 0; + GC_n_heap_bases++; } /* Commit pages */ result = (ptr_t) VirtualAlloc(result, bytes, - MEM_COMMIT, - PAGE_EXECUTE_READWRITE); + MEM_COMMIT, + PAGE_EXECUTE_READWRITE); if (result != NULL) { - if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result"); - GC_heap_lengths[i] += bytes; + if (HBLKDISPL(result) != 0) ABORT("Bad VirtualAlloc result"); + GC_heap_lengths[i] += bytes; } - return(result); + return(result); } # endif #ifdef USE_MUNMAP -/* For now, this only works on Win32/WinCE and some Unix-like */ -/* systems. If you have something else, don't define */ -/* USE_MUNMAP. */ +/* For now, this only works on Win32/WinCE and some Unix-like */ +/* systems. If you have something else, don't define */ +/* USE_MUNMAP. */ #if !defined(MSWIN32) && !defined(MSWINCE) @@ -2032,9 +2032,9 @@ ptr_t GC_wince_get_mem(word bytes) #endif -/* Compute a page aligned starting address for the unmap */ -/* operation on a block of size bytes starting at start. */ -/* Return 0 if the block is too small to make this feasible. */ +/* Compute a page aligned starting address for the unmap */ +/* operation on a block of size bytes starting at start. */ +/* Return 0 if the block is too small to make this feasible. */ STATIC ptr_t GC_unmap_start(ptr_t start, size_t bytes) { ptr_t result; @@ -2044,24 +2044,24 @@ STATIC ptr_t GC_unmap_start(ptr_t start, size_t bytes) return result; } -/* Compute end address for an unmap operation on the indicated */ -/* block. */ +/* Compute end address for an unmap operation on the indicated */ +/* block. */ STATIC ptr_t GC_unmap_end(ptr_t start, size_t bytes) { return (ptr_t)((word)(start + bytes) & ~(GC_page_size - 1)); } -/* Under Win32/WinCE we commit (map) and decommit (unmap) */ -/* memory using VirtualAlloc and VirtualFree. These functions */ -/* work on individual allocations of virtual memory, made */ -/* previously using VirtualAlloc with the MEM_RESERVE flag. */ -/* The ranges we need to (de)commit may span several of these */ -/* allocations; therefore we use VirtualQuery to check */ -/* allocation lengths, and split up the range as necessary. */ - -/* We assume that GC_remap is called on exactly the same range */ -/* as a previous call to GC_unmap. It is safe to consistently */ -/* round the endpoints in both places. */ +/* Under Win32/WinCE we commit (map) and decommit (unmap) */ +/* memory using VirtualAlloc and VirtualFree. These functions */ +/* work on individual allocations of virtual memory, made */ +/* previously using VirtualAlloc with the MEM_RESERVE flag. */ +/* The ranges we need to (de)commit may span several of these */ +/* allocations; therefore we use VirtualQuery to check */ +/* allocation lengths, and split up the range as necessary. */ + +/* We assume that GC_remap is called on exactly the same range */ +/* as a previous call to GC_unmap. It is safe to consistently */ +/* round the endpoints in both places. */ void GC_unmap(ptr_t start, size_t bytes) { ptr_t start_addr = GC_unmap_start(start, bytes); @@ -2071,25 +2071,25 @@ void GC_unmap(ptr_t start, size_t bytes) # if defined(MSWIN32) || defined(MSWINCE) while (len != 0) { MEMORY_BASIC_INFORMATION mem_info; - GC_word free_len; - if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info)) - != sizeof(mem_info)) - ABORT("Weird VirtualQuery result"); - free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize; - if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT)) - ABORT("VirtualFree failed"); - GC_unmapped_bytes += free_len; - start_addr += free_len; - len -= free_len; + GC_word free_len; + if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info)) + != sizeof(mem_info)) + ABORT("Weird VirtualQuery result"); + free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize; + if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT)) + ABORT("VirtualFree failed"); + GC_unmapped_bytes += free_len; + start_addr += free_len; + len -= free_len; } # else - /* We immediately remap it to prevent an intervening mmap from */ - /* accidentally grabbing the same address space. */ + /* We immediately remap it to prevent an intervening mmap from */ + /* accidentally grabbing the same address space. */ { - void * result; + void * result; result = mmap(start_addr, len, PROT_NONE, - MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON, - zero_fd, 0/* offset */); + MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON, + zero_fd, 0/* offset */); if (result != (void *)start_addr) ABORT("mmap(...PROT_NONE...) failed"); } GC_unmapped_bytes += len; @@ -2103,54 +2103,54 @@ void GC_remap(ptr_t start, size_t bytes) ptr_t end_addr = GC_unmap_end(start, bytes); word len = end_addr - start_addr; - /* FIXME: Handle out-of-memory correctly (at least for Win32) */ + /* FIXME: Handle out-of-memory correctly (at least for Win32) */ # if defined(MSWIN32) || defined(MSWINCE) ptr_t result; if (0 == start_addr) return; while (len != 0) { MEMORY_BASIC_INFORMATION mem_info; - GC_word alloc_len; - if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info)) - != sizeof(mem_info)) - ABORT("Weird VirtualQuery result"); - alloc_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize; - result = VirtualAlloc(start_addr, alloc_len, - MEM_COMMIT, - PAGE_EXECUTE_READWRITE); - if (result != start_addr) { - if (GetLastError() == ERROR_NOT_ENOUGH_MEMORY || - GetLastError() == ERROR_OUTOFMEMORY) { - ABORT("Not enough memory to process remapping"); - } else { - ABORT("VirtualAlloc remapping failed"); - } - } - GC_unmapped_bytes -= alloc_len; - start_addr += alloc_len; - len -= alloc_len; + GC_word alloc_len; + if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info)) + != sizeof(mem_info)) + ABORT("Weird VirtualQuery result"); + alloc_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize; + result = VirtualAlloc(start_addr, alloc_len, + MEM_COMMIT, + PAGE_EXECUTE_READWRITE); + if (result != start_addr) { + if (GetLastError() == ERROR_NOT_ENOUGH_MEMORY || + GetLastError() == ERROR_OUTOFMEMORY) { + ABORT("Not enough memory to process remapping"); + } else { + ABORT("VirtualAlloc remapping failed"); + } + } + GC_unmapped_bytes -= alloc_len; + start_addr += alloc_len; + len -= alloc_len; } # else /* It was already remapped with PROT_NONE. */ - int result; + int result; if (0 == start_addr) return; result = mprotect(start_addr, len, - PROT_READ | PROT_WRITE | OPT_PROT_EXEC); + PROT_READ | PROT_WRITE | OPT_PROT_EXEC); if (result != 0) { - GC_err_printf( - "Mprotect failed at %p (length %ld) with errno %d\n", - start_addr, (unsigned long)len, errno); - ABORT("Mprotect remapping failed"); + GC_err_printf( + "Mprotect failed at %p (length %ld) with errno %d\n", + start_addr, (unsigned long)len, errno); + ABORT("Mprotect remapping failed"); } GC_unmapped_bytes -= len; # endif } -/* Two adjacent blocks have already been unmapped and are about to */ -/* be merged. Unmap the whole block. This typically requires */ -/* that we unmap a small section in the middle that was not previously */ -/* unmapped due to alignment constraints. */ +/* Two adjacent blocks have already been unmapped and are about to */ +/* be merged. Unmap the whole block. This typically requires */ +/* that we unmap a small section in the middle that was not previously */ +/* unmapped due to alignment constraints. */ void GC_unmap_gap(ptr_t start1, size_t bytes1, ptr_t start2, size_t bytes2) { ptr_t start1_addr = GC_unmap_start(start1, bytes1); @@ -2167,24 +2167,24 @@ void GC_unmap_gap(ptr_t start1, size_t bytes1, ptr_t start2, size_t bytes2) # if defined(MSWIN32) || defined(MSWINCE) while (len != 0) { MEMORY_BASIC_INFORMATION mem_info; - GC_word free_len; - if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info)) - != sizeof(mem_info)) - ABORT("Weird VirtualQuery result"); - free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize; - if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT)) - ABORT("VirtualFree failed"); - GC_unmapped_bytes += free_len; - start_addr += free_len; - len -= free_len; + GC_word free_len; + if (VirtualQuery(start_addr, &mem_info, sizeof(mem_info)) + != sizeof(mem_info)) + ABORT("Weird VirtualQuery result"); + free_len = (len < mem_info.RegionSize) ? len : mem_info.RegionSize; + if (!VirtualFree(start_addr, free_len, MEM_DECOMMIT)) + ABORT("VirtualFree failed"); + GC_unmapped_bytes += free_len; + start_addr += free_len; + len -= free_len; } # else if (len != 0) { /* Immediately remap as above. */ - void * result; + void * result; result = mmap(start_addr, len, PROT_NONE, - MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON, - zero_fd, 0/* offset */); + MAP_PRIVATE | MAP_FIXED | OPT_MAP_ANON, + zero_fd, 0/* offset */); if (result != (void *)start_addr) ABORT("mmap(...PROT_NONE...) failed"); } GC_unmapped_bytes += len; @@ -2193,9 +2193,9 @@ void GC_unmap_gap(ptr_t start1, size_t bytes1, ptr_t start2, size_t bytes2) #endif /* USE_MUNMAP */ -/* Routine for pushing any additional roots. In THREADS */ -/* environment, this is also responsible for marking from */ -/* thread stacks. */ +/* Routine for pushing any additional roots. In THREADS */ +/* environment, this is also responsible for marking from */ +/* thread stacks. */ #ifndef THREADS void (*GC_push_other_roots)(void) = 0; #else /* THREADS */ @@ -2205,16 +2205,16 @@ PCR_ERes GC_push_thread_stack(PCR_Th_T *t, PCR_Any dummy) { struct PCR_ThCtl_TInfoRep info; PCR_ERes result; - + info.ti_stkLow = info.ti_stkHi = 0; result = PCR_ThCtl_GetInfo(t, &info); GC_push_all_stack((ptr_t)(info.ti_stkLow), (ptr_t)(info.ti_stkHi)); return(result); } -/* Push the contents of an old object. We treat this as stack */ -/* data only because that makes it robust against mark stack */ -/* overflow. */ +/* Push the contents of an old object. We treat this as stack */ +/* data only because that makes it robust against mark stack */ +/* overflow. */ PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data) { GC_push_all_stack((ptr_t)p, (ptr_t)p + size); @@ -2224,22 +2224,22 @@ PCR_ERes GC_push_old_obj(void *p, size_t size, PCR_Any data) void GC_default_push_other_roots(void) { - /* Traverse data allocated by previous memory managers. */ - { - extern struct PCR_MM_ProcsRep * GC_old_allocator; - - if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false, - GC_push_old_obj, 0) - != PCR_ERes_okay) { - ABORT("Old object enumeration failed"); - } - } + /* Traverse data allocated by previous memory managers. */ + { + extern struct PCR_MM_ProcsRep * GC_old_allocator; + + if ((*(GC_old_allocator->mmp_enumerate))(PCR_Bool_false, + GC_push_old_obj, 0) + != PCR_ERes_okay) { + ABORT("Old object enumeration failed"); + } + } /* Traverse all thread stacks. */ - if (PCR_ERes_IsErr( + if (PCR_ERes_IsErr( PCR_ThCtl_ApplyToAllOtherThreads(GC_push_thread_stack,0)) || PCR_ERes_IsErr(GC_push_thread_stack(PCR_Th_CurrThread(), 0))) { ABORT("Thread stack marking failed\n"); - } + } } # endif /* PCR */ @@ -2263,37 +2263,37 @@ void (*GC_push_other_roots)(void) = GC_default_push_other_roots; /* * Routines for accessing dirty bits on virtual pages. * There are six ways to maintain this information: - * DEFAULT_VDB: A simple dummy implementation that treats every page - * as possibly dirty. This makes incremental collection - * useless, but the implementation is still correct. + * DEFAULT_VDB: A simple dummy implementation that treats every page + * as possibly dirty. This makes incremental collection + * useless, but the implementation is still correct. * MANUAL_VDB: Stacks and static data are always considered dirty. - * Heap pages are considered dirty if GC_dirty(p) has been - * called on some pointer p pointing to somewhere inside - * an object on that page. A GC_dirty() call on a large - * object directly dirties only a single page, but for - * MANUAL_VDB we are careful to treat an object with a dirty - * page as completely dirty. - * In order to avoid races, an object must be marked dirty - * after it is written, and a reference to the object - * must be kept on a stack or in a register in the interim. - * With threads enabled, an object directly reachable from the - * stack at the time of a collection is treated as dirty. - * In single-threaded mode, it suffices to ensure that no - * collection can take place between the pointer assignment - * and the GC_dirty() call. - * PCR_VDB: Use PPCRs virtual dirty bit facility. - * PROC_VDB: Use the /proc facility for reading dirty bits. Only - * works under some SVR4 variants. Even then, it may be - * too slow to be entirely satisfactory. Requires reading - * dirty bits for entire address space. Implementations tend - * to assume that the client is a (slow) debugger. + * Heap pages are considered dirty if GC_dirty(p) has been + * called on some pointer p pointing to somewhere inside + * an object on that page. A GC_dirty() call on a large + * object directly dirties only a single page, but for + * MANUAL_VDB we are careful to treat an object with a dirty + * page as completely dirty. + * In order to avoid races, an object must be marked dirty + * after it is written, and a reference to the object + * must be kept on a stack or in a register in the interim. + * With threads enabled, an object directly reachable from the + * stack at the time of a collection is treated as dirty. + * In single-threaded mode, it suffices to ensure that no + * collection can take place between the pointer assignment + * and the GC_dirty() call. + * PCR_VDB: Use PPCRs virtual dirty bit facility. + * PROC_VDB: Use the /proc facility for reading dirty bits. Only + * works under some SVR4 variants. Even then, it may be + * too slow to be entirely satisfactory. Requires reading + * dirty bits for entire address space. Implementations tend + * to assume that the client is a (slow) debugger. * MPROTECT_VDB:Protect pages and then catch the faults to keep track of - * dirtied pages. The implementation (and implementability) - * is highly system dependent. This usually fails when system - * calls write to a protected page. We prevent the read system - * call from doing so. It is the clients responsibility to - * make sure that other system calls are similarly protected - * or write only to the stack. + * dirtied pages. The implementation (and implementability) + * is highly system dependent. This usually fails when system + * calls write to a protected page. We prevent the read system + * call from doing so. It is the clients responsibility to + * make sure that other system calls are similarly protected + * or write only to the stack. * GWW_VDB: Use the Win32 GetWriteWatch functions, if available, to * read dirty bits. In case it is not available (because we * are running on Windows 95, Windows 2000 or earlier), @@ -2307,7 +2307,7 @@ GC_bool GC_dirty_maintained = FALSE; STATIC void GC_or_pages(page_hash_table pht1, page_hash_table pht2) { register int i; - + for (i = 0; i < PHT_SIZE; i++) pht1[i] |= pht2[i]; } @@ -2317,7 +2317,7 @@ STATIC void GC_or_pages(page_hash_table pht1, page_hash_table pht2) # define GC_GWW_BUF_LEN (MAXHINCR * HBLKSIZE / 4096 /* X86 page size */) /* Still susceptible to overflow, if there are very large allocations, */ - /* and everything is dirty. */ + /* and everything is dirty. */ static PVOID gww_buf[GC_GWW_BUF_LEN]; # ifdef MPROTECT_VDB @@ -2357,18 +2357,18 @@ STATIC void GC_or_pages(page_hash_table pht1, page_hash_table pht2) * GetWriteWatch is documented as returning non-zero when it fails, * but the documentation doesn't explicitly say why it would fail or * what its behaviour will be if it fails. - * It does appear to fail, at least on recent W2K instances, if - * the underlying memory was not allocated with the appropriate - * flag. This is common if GC_enable_incremental is called - * shortly after GC initialization. To avoid modifying the - * interface, we silently work around such a failure, it it only - * affects the initial (small) heap allocation. - * If there are more dirty + * It does appear to fail, at least on recent W2K instances, if + * the underlying memory was not allocated with the appropriate + * flag. This is common if GC_enable_incremental is called + * shortly after GC initialization. To avoid modifying the + * interface, we silently work around such a failure, it it only + * affects the initial (small) heap allocation. + * If there are more dirty * pages than will fit in the buffer, this is not treated as a * failure; we must check the page count in the loop condition. - * Since each partial call will reset the status of some - * pages, this should eventually terminate even in the overflow - * case. + * Since each partial call will reset the status of some + * pages, this should eventually terminate even in the overflow + * case. */ if (GetWriteWatch_func(WRITE_WATCH_FLAG_RESET, GC_heap_sects[i].hs_start, @@ -2405,8 +2405,8 @@ STATIC void GC_or_pages(page_hash_table pht1, page_hash_table pht2) } } while (count == GC_GWW_BUF_LEN); /* FIXME: It's unclear from Microsoft's documentation if this loop */ - /* is useful. We suspect the call just fails if the buffer fills */ - /* up. But that should still be handled correctly. */ + /* is useful. We suspect the call just fails if the buffer fills */ + /* up. But that should still be handled correctly. */ } GC_or_pages(GC_written_pages, GC_grungy_pages); @@ -2440,12 +2440,12 @@ STATIC void GC_or_pages(page_hash_table pht1, page_hash_table pht2) # ifdef DEFAULT_VDB -/* All of the following assume the allocation lock is held. */ +/* All of the following assume the allocation lock is held. */ -/* The client asserts that unallocated pages in the heap are never */ -/* written. */ +/* The client asserts that unallocated pages in the heap are never */ +/* written. */ -/* Initialize virtual dirty bit implementation. */ +/* Initialize virtual dirty bit implementation. */ void GC_dirty_init(void) { if (GC_print_stats == VERBOSE) @@ -2453,15 +2453,15 @@ void GC_dirty_init(void) GC_dirty_maintained = TRUE; } -/* Retrieve system dirty bits for heap to a local buffer. */ -/* Restore the systems notion of which pages are dirty. */ +/* Retrieve system dirty bits for heap to a local buffer. */ +/* Restore the systems notion of which pages are dirty. */ void GC_read_dirty(void) {} -/* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */ -/* If the actual page size is different, this returns TRUE if any */ -/* of the pages overlapping h are dirty. This routine may err on the */ -/* side of labeling pages as dirty (and this implementation does). */ +/* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */ +/* If the actual page size is different, this returns TRUE if any */ +/* of the pages overlapping h are dirty. This routine may err on the */ +/* side of labeling pages as dirty (and this implementation does). */ /*ARGSUSED*/ GC_bool GC_page_was_dirty(struct hblk *h) { @@ -2474,21 +2474,21 @@ GC_bool GC_page_was_dirty(struct hblk *h) * stacks, e.g. under Solaris 2.X. Otherwise the following default * versions are adequate. */ - -/* Could any valid GC heap pointer ever have been written to this page? */ + +/* Could any valid GC heap pointer ever have been written to this page? */ /*ARGSUSED*/ GC_bool GC_page_was_ever_dirty(struct hblk *h) { return(TRUE); } -/* A call that: */ -/* I) hints that [h, h+nblocks) is about to be written. */ -/* II) guarantees that protection is removed. */ -/* (I) may speed up some dirty bit implementations. */ -/* (II) may be essential if we need to ensure that */ -/* pointer-free system call buffers in the heap are */ -/* not protected. */ +/* A call that: */ +/* I) hints that [h, h+nblocks) is about to be written. */ +/* II) guarantees that protection is removed. */ +/* (I) may speed up some dirty bit implementations. */ +/* (II) may be essential if we need to ensure that */ +/* pointer-free system call buffers in the heap are */ +/* not protected. */ /*ARGSUSED*/ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) { @@ -2498,7 +2498,7 @@ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) # ifdef MANUAL_VDB -/* Initialize virtual dirty bit implementation. */ +/* Initialize virtual dirty bit implementation. */ void GC_dirty_init(void) { if (GC_print_stats == VERBOSE) @@ -2507,8 +2507,8 @@ void GC_dirty_init(void) GC_dirty_maintained = TRUE; } -/* Retrieve system dirty bits for heap to a local buffer. */ -/* Restore the systems notion of which pages are dirty. */ +/* Retrieve system dirty bits for heap to a local buffer. */ +/* Restore the systems notion of which pages are dirty. */ void GC_read_dirty(void) { BCOPY((word *)GC_dirty_pages, GC_grungy_pages, @@ -2516,28 +2516,28 @@ void GC_read_dirty(void) BZERO((word *)GC_dirty_pages, (sizeof GC_dirty_pages)); } -/* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */ -/* If the actual page size is different, this returns TRUE if any */ -/* of the pages overlapping h are dirty. This routine may err on the */ -/* side of labeling pages as dirty (and this implementation does). */ +/* Is the HBLKSIZE sized page at h marked dirty in the local buffer? */ +/* If the actual page size is different, this returns TRUE if any */ +/* of the pages overlapping h are dirty. This routine may err on the */ +/* side of labeling pages as dirty (and this implementation does). */ GC_bool GC_page_was_dirty(struct hblk *h) { register word index; - + index = PHT_HASH(h); return(HDR(h) == 0 || get_pht_entry_from_index(GC_grungy_pages, index)); } - -/* Could any valid GC heap pointer ever have been written to this page? */ + +/* Could any valid GC heap pointer ever have been written to this page? */ /*ARGSUSED*/ GC_bool GC_page_was_ever_dirty(struct hblk *h) { - /* FIXME - implement me. */ + /* FIXME - implement me. */ return(TRUE); } -/* Mark the page containing p as dirty. Logically, this dirties the */ -/* entire object. */ +/* Mark the page containing p as dirty. Logically, this dirties the */ +/* entire object. */ void GC_dirty(ptr_t p) { word index = PHT_HASH(p); @@ -2568,7 +2568,7 @@ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) * heap, and do even that only if we are on a platform on which those * are not protected. Another alternative is to wrap system calls * (see example for read below), but the current implementation holds - * applications. + * applications. * We assume the page size is a multiple of HBLKSIZE. * We prefer them to be the same. We avoid protecting POINTERFREE * objects only if they are the same. @@ -2581,16 +2581,16 @@ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) # include # define PROTECT(addr, len) \ - if (mprotect((caddr_t)(addr), (size_t)(len), \ - PROT_READ | OPT_PROT_EXEC) < 0) { \ - ABORT("mprotect failed"); \ - } + if (mprotect((caddr_t)(addr), (size_t)(len), \ + PROT_READ | OPT_PROT_EXEC) < 0) { \ + ABORT("mprotect failed"); \ + } # define UNPROTECT(addr, len) \ - if (mprotect((caddr_t)(addr), (size_t)(len), \ - PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \ - ABORT("un-mprotect failed"); \ - } - + if (mprotect((caddr_t)(addr), (size_t)(len), \ + PROT_WRITE | PROT_READ | OPT_PROT_EXEC ) < 0) { \ + ABORT("un-mprotect failed"); \ + } + # else # ifdef DARWIN @@ -2609,23 +2609,23 @@ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) ABORT("vm_portect failed"); \ } # else - + # ifndef MSWINCE # include # endif static DWORD protect_junk; # define PROTECT(addr, len) \ - if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \ - &protect_junk)) { \ - GC_printf("Last error code: %lx\n", (long)GetLastError()); \ - ABORT("VirtualProtect failed"); \ - } + if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READ, \ + &protect_junk)) { \ + GC_printf("Last error code: %lx\n", (long)GetLastError()); \ + ABORT("VirtualProtect failed"); \ + } # define UNPROTECT(addr, len) \ - if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \ - &protect_junk)) { \ - ABORT("un-VirtualProtect failed"); \ - } + if (!VirtualProtect((addr), (len), PAGE_EXECUTE_READWRITE, \ + &protect_junk)) { \ + ABORT("un-VirtualProtect failed"); \ + } # endif /* !DARWIN */ # endif /* MSWIN32 || MSWINCE || DARWIN */ @@ -2646,13 +2646,13 @@ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) #if defined(__GLIBC__) # if __GLIBC__ < 2 || __GLIBC__ == 2 && __GLIBC_MINOR__ < 2 -# error glibc too old? +# error glibc too old? # endif #endif #ifndef DARWIN STATIC SIG_HNDLR_PTR GC_old_segv_handler; - /* Also old MSWIN32 ACCESS_VIOLATION filter */ + /* Also old MSWIN32 ACCESS_VIOLATION filter */ #if !defined(MSWIN32) && !defined(MSWINCE) STATIC SIG_HNDLR_PTR GC_old_bus_handler; STATIC GC_bool GC_old_bus_handler_used_si; @@ -2661,58 +2661,58 @@ STATIC GC_bool GC_old_segv_handler_used_si; #endif /* !DARWIN */ #if defined(THREADS) -/* We need to lock around the bitmap update in the write fault handler */ -/* in order to avoid the risk of losing a bit. We do this with a */ -/* test-and-set spin lock if we know how to do that. Otherwise we */ -/* check whether we are already in the handler and use the dumb but */ -/* safe fallback algorithm of setting all bits in the word. */ -/* Contention should be very rare, so we do the minimum to handle it */ -/* correctly. */ +/* We need to lock around the bitmap update in the write fault handler */ +/* in order to avoid the risk of losing a bit. We do this with a */ +/* test-and-set spin lock if we know how to do that. Otherwise we */ +/* check whether we are already in the handler and use the dumb but */ +/* safe fallback algorithm of setting all bits in the word. */ +/* Contention should be very rare, so we do the minimum to handle it */ +/* correctly. */ #ifdef AO_HAVE_test_and_set_acquire volatile AO_TS_t GC_fault_handler_lock = 0; void async_set_pht_entry_from_index(volatile page_hash_table db, size_t index) { while (AO_test_and_set_acquire(&GC_fault_handler_lock) == AO_TS_SET) {} - /* Could also revert to set_pht_entry_from_index_safe if initial */ - /* GC_test_and_set fails. */ + /* Could also revert to set_pht_entry_from_index_safe if initial */ + /* GC_test_and_set fails. */ set_pht_entry_from_index(db, index); AO_CLEAR(&GC_fault_handler_lock); } #else /* !AO_HAVE_test_and_set_acquire */ # error No test_and_set operation: Introduces a race. - /* THIS WOULD BE INCORRECT! */ - /* The dirty bit vector may be temporarily wrong, */ + /* THIS WOULD BE INCORRECT! */ + /* The dirty bit vector may be temporarily wrong, */ /* just before we notice the conflict and correct it. We may end up */ - /* looking at it while it's wrong. But this requires contention */ - /* exactly when a GC is triggered, which seems far less likely to */ - /* fail than the old code, which had no reported failures. Thus we */ - /* leave it this way while we think of something better, or support */ - /* GC_test_and_set on the remaining platforms. */ + /* looking at it while it's wrong. But this requires contention */ + /* exactly when a GC is triggered, which seems far less likely to */ + /* fail than the old code, which had no reported failures. Thus we */ + /* leave it this way while we think of something better, or support */ + /* GC_test_and_set on the remaining platforms. */ static volatile word currently_updating = 0; void async_set_pht_entry_from_index(volatile page_hash_table db, size_t index) { unsigned int update_dummy; currently_updating = (word)(&update_dummy); set_pht_entry_from_index(db, index); - /* If we get contention in the 10 or so instruction window here, */ - /* and we get stopped by a GC between the two updates, we lose! */ + /* If we get contention in the 10 or so instruction window here, */ + /* and we get stopped by a GC between the two updates, we lose! */ if (currently_updating != (word)(&update_dummy)) { - set_pht_entry_from_index_safe(db, index); - /* We claim that if two threads concurrently try to update the */ - /* dirty bit vector, the first one to execute UPDATE_START */ - /* will see it changed when UPDATE_END is executed. (Note that */ - /* &update_dummy must differ in two distinct threads.) It */ - /* will then execute set_pht_entry_from_index_safe, thus */ - /* returning us to a safe state, though not soon enough. */ + set_pht_entry_from_index_safe(db, index); + /* We claim that if two threads concurrently try to update the */ + /* dirty bit vector, the first one to execute UPDATE_START */ + /* will see it changed when UPDATE_END is executed. (Note that */ + /* &update_dummy must differ in two distinct threads.) It */ + /* will then execute set_pht_entry_from_index_safe, thus */ + /* returning us to a safe state, though not soon enough. */ } } #endif /* !AO_HAVE_test_and_set_acquire */ #else /* !THREADS */ # define async_set_pht_entry_from_index(db, index) \ - set_pht_entry_from_index(db, index) + set_pht_entry_from_index(db, index) #endif /* !THREADS */ #ifdef CHECKSUMS void GC_record_fault(struct hblk * h); - /* From checksums.c */ + /* From checksums.c */ #endif #if !defined(DARWIN) @@ -2727,30 +2727,30 @@ STATIC GC_bool GC_old_segv_handler_used_si; # define SIG_OK (sig == SIGSEGV) # define CODE_OK (si -> si_code == EACCES) # elif defined(HURD) -# define SIG_OK (sig == SIGBUS || sig == SIGSEGV) +# define SIG_OK (sig == SIGBUS || sig == SIGSEGV) # define CODE_OK TRUE # elif defined(LINUX) # define SIG_OK (sig == SIGSEGV) # define CODE_OK TRUE - /* Empirically c.trapno == 14, on IA32, but is that useful? */ - /* Should probably consider alignment issues on other */ - /* architectures. */ + /* Empirically c.trapno == 14, on IA32, but is that useful? */ + /* Should probably consider alignment issues on other */ + /* architectures. */ # elif defined(HPUX) # define SIG_OK (sig == SIGSEGV || sig == SIGBUS) # define CODE_OK (si -> si_code == SEGV_ACCERR) \ - || (si -> si_code == BUS_ADRERR) \ - || (si -> si_code == BUS_UNKNOWN) \ - || (si -> si_code == SEGV_UNKNOWN) \ - || (si -> si_code == BUS_OBJERR) + || (si -> si_code == BUS_ADRERR) \ + || (si -> si_code == BUS_UNKNOWN) \ + || (si -> si_code == SEGV_UNKNOWN) \ + || (si -> si_code == BUS_OBJERR) # elif defined(SUNOS5SIGS) # define SIG_OK (sig == SIGSEGV) # define CODE_OK (si -> si_code == SEGV_ACCERR) # elif defined(MSWIN32) || defined(MSWINCE) # define SIG_OK (exc_info -> ExceptionRecord -> ExceptionCode \ - == STATUS_ACCESS_VIOLATION) + == STATUS_ACCESS_VIOLATION) # define CODE_OK (exc_info -> ExceptionRecord -> ExceptionInformation[0] \ - == 1) /* Write fault */ -# endif + == 1) /* Write fault */ +# endif # if defined(MSWIN32) || defined(MSWINCE) LONG WINAPI GC_write_fault_handler(struct _EXCEPTION_POINTERS *exc_info) @@ -2761,103 +2761,103 @@ STATIC GC_bool GC_old_segv_handler_used_si; # endif /* MSWIN32 || MSWINCE */ { # if !defined(MSWIN32) && !defined(MSWINCE) - char *addr = si -> si_addr; + char *addr = si -> si_addr; # else - char * addr = (char *) (exc_info -> ExceptionRecord - -> ExceptionInformation[1]); + char * addr = (char *) (exc_info -> ExceptionRecord + -> ExceptionInformation[1]); # endif unsigned i; - + if (SIG_OK && CODE_OK) { register struct hblk * h = - (struct hblk *)((word)addr & ~(GC_page_size-1)); + (struct hblk *)((word)addr & ~(GC_page_size-1)); GC_bool in_allocd_block; -# ifdef CHECKSUMS - GC_record_fault(h); -# endif /* CHECKSUMS */ - -# ifdef SUNOS5SIGS - /* Address is only within the correct physical page. */ - in_allocd_block = FALSE; +# ifdef CHECKSUMS + GC_record_fault(h); +# endif /* CHECKSUMS */ + +# ifdef SUNOS5SIGS + /* Address is only within the correct physical page. */ + in_allocd_block = FALSE; for (i = 0; i < divHBLKSZ(GC_page_size); i++) { if (HDR(h+i) != 0) { in_allocd_block = TRUE; } } -# else - in_allocd_block = (HDR(addr) != 0); -# endif +# else + in_allocd_block = (HDR(addr) != 0); +# endif if (!in_allocd_block) { - /* FIXME - We should make sure that we invoke the */ - /* old handler with the appropriate calling */ - /* sequence, which often depends on SA_SIGINFO. */ + /* FIXME - We should make sure that we invoke the */ + /* old handler with the appropriate calling */ + /* sequence, which often depends on SA_SIGINFO. */ - /* Heap blocks now begin and end on page boundaries */ + /* Heap blocks now begin and end on page boundaries */ SIG_HNDLR_PTR old_handler; -# if defined(MSWIN32) || defined(MSWINCE) - old_handler = GC_old_segv_handler; -# else - GC_bool used_si; - - if (sig == SIGSEGV) { - old_handler = GC_old_segv_handler; - used_si = GC_old_segv_handler_used_si; - } else { - old_handler = GC_old_bus_handler; - used_si = GC_old_bus_handler_used_si; - } -# endif - +# if defined(MSWIN32) || defined(MSWINCE) + old_handler = GC_old_segv_handler; +# else + GC_bool used_si; + + if (sig == SIGSEGV) { + old_handler = GC_old_segv_handler; + used_si = GC_old_segv_handler_used_si; + } else { + old_handler = GC_old_bus_handler; + used_si = GC_old_bus_handler_used_si; + } +# endif + if (old_handler == (SIG_HNDLR_PTR)SIG_DFL) { -# if !defined(MSWIN32) && !defined(MSWINCE) - GC_err_printf("Segfault at %p\n", addr); +# if !defined(MSWIN32) && !defined(MSWINCE) + GC_err_printf("Segfault at %p\n", addr); ABORT("Unexpected bus error or segmentation fault"); -# else - return(EXCEPTION_CONTINUE_SEARCH); -# endif +# else + return(EXCEPTION_CONTINUE_SEARCH); +# endif } else { /* - * FIXME: This code should probably check if the + * FIXME: This code should probably check if the * old signal handler used the traditional style and * if so call it using that style. */ -# if defined(MSWIN32) || defined(MSWINCE) - return((*old_handler)(exc_info)); -# else - if (used_si) - ((SIG_HNDLR_PTR)old_handler) (sig, si, raw_sc); - else - /* FIXME: should pass nonstandard args as well. */ - ((PLAIN_HNDLR_PTR)old_handler) (sig); - return; -# endif +# if defined(MSWIN32) || defined(MSWINCE) + return((*old_handler)(exc_info)); +# else + if (used_si) + ((SIG_HNDLR_PTR)old_handler) (sig, si, raw_sc); + else + /* FIXME: should pass nonstandard args as well. */ + ((PLAIN_HNDLR_PTR)old_handler) (sig); + return; +# endif } } UNPROTECT(h, GC_page_size); - /* We need to make sure that no collection occurs between */ - /* the UNPROTECT and the setting of the dirty bit. Otherwise */ - /* a write by a third thread might go unnoticed. Reversing */ - /* the order is just as bad, since we would end up unprotecting */ - /* a page in a GC cycle during which it's not marked. */ - /* Currently we do this by disabling the thread stopping */ - /* signals while this handler is running. An alternative might */ - /* be to record the fact that we're about to unprotect, or */ - /* have just unprotected a page in the GC's thread structure, */ - /* and then to have the thread stopping code set the dirty */ - /* flag, if necessary. */ + /* We need to make sure that no collection occurs between */ + /* the UNPROTECT and the setting of the dirty bit. Otherwise */ + /* a write by a third thread might go unnoticed. Reversing */ + /* the order is just as bad, since we would end up unprotecting */ + /* a page in a GC cycle during which it's not marked. */ + /* Currently we do this by disabling the thread stopping */ + /* signals while this handler is running. An alternative might */ + /* be to record the fact that we're about to unprotect, or */ + /* have just unprotected a page in the GC's thread structure, */ + /* and then to have the thread stopping code set the dirty */ + /* flag, if necessary. */ for (i = 0; i < divHBLKSZ(GC_page_size); i++) { size_t index = PHT_HASH(h+i); - + async_set_pht_entry_from_index(GC_dirty_pages, index); } - /* The write may not take place before dirty bits are read. */ - /* But then we'll fault again ... */ -# if defined(MSWIN32) || defined(MSWINCE) - return(EXCEPTION_CONTINUE_EXECUTION); -# else - return; -# endif + /* The write may not take place before dirty bits are read. */ + /* But then we'll fault again ... */ +# if defined(MSWIN32) || defined(MSWINCE) + return(EXCEPTION_CONTINUE_EXECUTION); +# else + return; +# endif } #if defined(MSWIN32) || defined(MSWINCE) return EXCEPTION_CONTINUE_SEARCH; @@ -2879,18 +2879,18 @@ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) struct hblk * h_trunc; /* Truncated to page boundary */ struct hblk * h_end; /* Page boundary following block end */ struct hblk * current; - + # if defined(GWW_VDB) if (GC_GWW_AVAILABLE()) return; # endif if (!GC_dirty_maintained) return; h_trunc = (struct hblk *)((word)h & ~(GC_page_size-1)); h_end = (struct hblk *)(((word)(h + nblocks) + GC_page_size-1) - & ~(GC_page_size-1)); + & ~(GC_page_size-1)); if (h_end == h_trunc + 1 && get_pht_entry_from_index(GC_dirty_pages, PHT_HASH(h_trunc))) { - /* already marked dirty, and hence unprotected. */ - return; + /* already marked dirty, and hence unprotected. */ + return; } for (current = h_trunc; current < h_end; ++current) { size_t index = PHT_HASH(current); @@ -2905,20 +2905,20 @@ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) void GC_dirty_init(void) { # if !defined(MSWIN32) && !defined(MSWINCE) - struct sigaction act, oldact; - act.sa_flags = SA_RESTART | SA_SIGINFO; + struct sigaction act, oldact; + act.sa_flags = SA_RESTART | SA_SIGINFO; act.sa_sigaction = GC_write_fault_handler; (void)sigemptyset(&act.sa_mask); # ifdef SIG_SUSPEND - /* Arrange to postpone SIG_SUSPEND while we're in a write fault */ - /* handler. This effectively makes the handler atomic w.r.t. */ - /* stopping the world for GC. */ + /* Arrange to postpone SIG_SUSPEND while we're in a write fault */ + /* handler. This effectively makes the handler atomic w.r.t. */ + /* stopping the world for GC. */ (void)sigaddset(&act.sa_mask, SIG_SUSPEND); # endif /* SIG_SUSPEND */ # endif if (GC_print_stats == VERBOSE) - GC_log_printf( - "Initializing mprotect virtual dirty bit implementation\n"); + GC_log_printf( + "Initializing mprotect virtual dirty bit implementation\n"); GC_dirty_maintained = TRUE; if (GC_page_size % HBLKSIZE != 0) { GC_err_printf("Page size not multiple of HBLKSIZE\n"); @@ -2926,46 +2926,46 @@ void GC_dirty_init(void) } # if !defined(MSWIN32) && !defined(MSWINCE) # if defined(GC_IRIX_THREADS) - sigaction(SIGSEGV, 0, &oldact); - sigaction(SIGSEGV, &act, 0); -# else - { - int res = sigaction(SIGSEGV, &act, &oldact); - if (res != 0) ABORT("Sigaction failed"); - } + sigaction(SIGSEGV, 0, &oldact); + sigaction(SIGSEGV, &act, 0); +# else + { + int res = sigaction(SIGSEGV, &act, &oldact); + if (res != 0) ABORT("Sigaction failed"); + } # endif if (oldact.sa_flags & SA_SIGINFO) { GC_old_segv_handler = oldact.sa_sigaction; - GC_old_segv_handler_used_si = TRUE; + GC_old_segv_handler_used_si = TRUE; } else { GC_old_segv_handler = (SIG_HNDLR_PTR)oldact.sa_handler; - GC_old_segv_handler_used_si = FALSE; + GC_old_segv_handler_used_si = FALSE; } if (GC_old_segv_handler == (SIG_HNDLR_PTR)SIG_IGN) { - GC_err_printf("Previously ignored segmentation violation!?\n"); - GC_old_segv_handler = (SIG_HNDLR_PTR)SIG_DFL; + GC_err_printf("Previously ignored segmentation violation!?\n"); + GC_old_segv_handler = (SIG_HNDLR_PTR)SIG_DFL; } if (GC_old_segv_handler != (SIG_HNDLR_PTR)SIG_DFL) { - if (GC_print_stats == VERBOSE) - GC_log_printf("Replaced other SIGSEGV handler\n"); + if (GC_print_stats == VERBOSE) + GC_log_printf("Replaced other SIGSEGV handler\n"); } # if defined(HPUX) || defined(LINUX) || defined(HURD) \ || (defined(FREEBSD) && defined(SUNOS5SIGS)) sigaction(SIGBUS, &act, &oldact); if (oldact.sa_flags & SA_SIGINFO) { GC_old_bus_handler = oldact.sa_sigaction; - GC_old_bus_handler_used_si = TRUE; + GC_old_bus_handler_used_si = TRUE; } else { GC_old_bus_handler = (SIG_HNDLR_PTR)oldact.sa_handler; - GC_old_bus_handler_used_si = FALSE; + GC_old_bus_handler_used_si = FALSE; } if (GC_old_bus_handler == (SIG_HNDLR_PTR)SIG_IGN) { - GC_err_printf("Previously ignored bus error!?\n"); - GC_old_bus_handler = (SIG_HNDLR_PTR)SIG_DFL; + GC_err_printf("Previously ignored bus error!?\n"); + GC_old_bus_handler = (SIG_HNDLR_PTR)SIG_DFL; } if (GC_old_bus_handler != (SIG_HNDLR_PTR)SIG_DFL) { - if (GC_print_stats == VERBOSE) - GC_log_printf("Replaced other SIGBUS handler\n"); + if (GC_print_stats == VERBOSE) + GC_log_printf("Replaced other SIGBUS handler\n"); } # endif /* HPUX || LINUX || HURD || (FREEBSD && SUNOS5SIGS) */ # endif /* ! MS windows */ @@ -2976,13 +2976,13 @@ void GC_dirty_init(void) # if defined(MSWIN32) GC_old_segv_handler = SetUnhandledExceptionFilter(GC_write_fault_handler); if (GC_old_segv_handler != NULL) { - if (GC_print_stats) + if (GC_print_stats) GC_log_printf("Replaced other UnhandledExceptionFilter\n"); } else { GC_old_segv_handler = SIG_DFL; } # elif defined(MSWINCE) - /* MPROTECT_VDB is unsupported for WinCE at present. */ + /* MPROTECT_VDB is unsupported for WinCE at present. */ /* FIXME: implement it (if possible). */ # endif } @@ -2991,9 +2991,9 @@ void GC_dirty_init(void) GC_API int GC_CALL GC_incremental_protection_needs(void) { if (GC_page_size == HBLKSIZE) { - return GC_PROTECTS_POINTER_HEAP; + return GC_PROTECTS_POINTER_HEAP; } else { - return GC_PROTECTS_POINTER_HEAP | GC_PROTECTS_PTRFREE_HEAP; + return GC_PROTECTS_POINTER_HEAP | GC_PROTECTS_PTRFREE_HEAP; } } @@ -3010,60 +3010,60 @@ STATIC void GC_protect_heap(void) struct hblk * current_start; /* Start of block to be protected. */ struct hblk * limit; unsigned i; - GC_bool protect_all = - (0 != (GC_incremental_protection_needs() & GC_PROTECTS_PTRFREE_HEAP)); + GC_bool protect_all = + (0 != (GC_incremental_protection_needs() & GC_PROTECTS_PTRFREE_HEAP)); for (i = 0; i < GC_n_heap_sects; i++) { start = GC_heap_sects[i].hs_start; len = GC_heap_sects[i].hs_bytes; - if (protect_all) { + if (protect_all) { PROTECT(start, len); - } else { - GC_ASSERT(PAGE_ALIGNED(len)) - GC_ASSERT(PAGE_ALIGNED(start)) - current_start = current = (struct hblk *)start; - limit = (struct hblk *)(start + len); - while (current < limit) { + } else { + GC_ASSERT(PAGE_ALIGNED(len)) + GC_ASSERT(PAGE_ALIGNED(start)) + current_start = current = (struct hblk *)start; + limit = (struct hblk *)(start + len); + while (current < limit) { hdr * hhdr; - word nhblks; - GC_bool is_ptrfree; - - GC_ASSERT(PAGE_ALIGNED(current)); - GET_HDR(current, hhdr); - if (IS_FORWARDING_ADDR_OR_NIL(hhdr)) { - /* This can happen only if we're at the beginning of a */ - /* heap segment, and a block spans heap segments. */ - /* We will handle that block as part of the preceding */ - /* segment. */ - GC_ASSERT(current_start == current); - current_start = ++current; - continue; - } - if (HBLK_IS_FREE(hhdr)) { - GC_ASSERT(PAGE_ALIGNED(hhdr -> hb_sz)); - nhblks = divHBLKSZ(hhdr -> hb_sz); - is_ptrfree = TRUE; /* dirty on alloc */ - } else { - nhblks = OBJ_SZ_TO_BLOCKS(hhdr -> hb_sz); - is_ptrfree = IS_PTRFREE(hhdr); - } - if (is_ptrfree) { - if (current_start < current) { - PROTECT(current_start, (ptr_t)current - (ptr_t)current_start); - } - current_start = (current += nhblks); - } else { - current += nhblks; - } - } - if (current_start < current) { - PROTECT(current_start, (ptr_t)current - (ptr_t)current_start); - } - } + word nhblks; + GC_bool is_ptrfree; + + GC_ASSERT(PAGE_ALIGNED(current)); + GET_HDR(current, hhdr); + if (IS_FORWARDING_ADDR_OR_NIL(hhdr)) { + /* This can happen only if we're at the beginning of a */ + /* heap segment, and a block spans heap segments. */ + /* We will handle that block as part of the preceding */ + /* segment. */ + GC_ASSERT(current_start == current); + current_start = ++current; + continue; + } + if (HBLK_IS_FREE(hhdr)) { + GC_ASSERT(PAGE_ALIGNED(hhdr -> hb_sz)); + nhblks = divHBLKSZ(hhdr -> hb_sz); + is_ptrfree = TRUE; /* dirty on alloc */ + } else { + nhblks = OBJ_SZ_TO_BLOCKS(hhdr -> hb_sz); + is_ptrfree = IS_PTRFREE(hhdr); + } + if (is_ptrfree) { + if (current_start < current) { + PROTECT(current_start, (ptr_t)current - (ptr_t)current_start); + } + current_start = (current += nhblks); + } else { + current += nhblks; + } + } + if (current_start < current) { + PROTECT(current_start, (ptr_t)current - (ptr_t)current_start); + } + } } } -/* We assume that either the world is stopped or its OK to lose dirty */ -/* bits while this is happenning (as in GC_enable_incremental). */ +/* We assume that either the world is stopped or its OK to lose dirty */ +/* bits while this is happenning (as in GC_enable_incremental). */ void GC_read_dirty(void) { # if defined(GWW_VDB) @@ -3081,7 +3081,7 @@ void GC_read_dirty(void) GC_bool GC_page_was_dirty(struct hblk *h) { register word index; - + # if defined(GWW_VDB) if (GC_GWW_AVAILABLE()) return GC_gww_page_was_dirty(h); @@ -3100,23 +3100,23 @@ GC_bool GC_page_was_dirty(struct hblk *h) */ #if 0 -static GC_bool syscall_acquired_lock = FALSE; /* Protected by GC lock. */ - +static GC_bool syscall_acquired_lock = FALSE; /* Protected by GC lock. */ + void GC_begin_syscall(void) { - /* FIXME: Resurrecting this code would require fixing the */ - /* test, which can spuriously return TRUE. */ + /* FIXME: Resurrecting this code would require fixing the */ + /* test, which can spuriously return TRUE. */ if (!I_HOLD_LOCK()) { - LOCK(); - syscall_acquired_lock = TRUE; + LOCK(); + syscall_acquired_lock = TRUE; } } void GC_end_syscall(void) { if (syscall_acquired_lock) { - syscall_acquired_lock = FALSE; - UNLOCK(); + syscall_acquired_lock = FALSE; + UNLOCK(); } } @@ -3126,7 +3126,7 @@ void GC_unprotect_range(ptr_t addr, word len) struct hblk * end_block; register struct hblk *h; ptr_t obj_start; - + if (!GC_dirty_maintained) return; obj_start = GC_base(addr); if (obj_start == 0) return; @@ -3138,58 +3138,58 @@ void GC_unprotect_range(ptr_t addr, word len) end_block += GC_page_size/HBLKSIZE - 1; for (h = start_block; h <= end_block; h++) { register word index = PHT_HASH(h); - + async_set_pht_entry_from_index(GC_dirty_pages, index); } UNPROTECT(start_block, - ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE); + ((ptr_t)end_block - (ptr_t)start_block) + HBLKSIZE); } -/* We no longer wrap read by default, since that was causing too many */ -/* problems. It is preferred that the client instead avoids writing */ -/* to the write-protected heap with a system call. */ +/* We no longer wrap read by default, since that was causing too many */ +/* problems. It is preferred that the client instead avoids writing */ +/* to the write-protected heap with a system call. */ /* This still serves as sample code if you do want to wrap system calls.*/ #if !defined(MSWIN32) && !defined(MSWINCE) && !defined(GC_USE_LD_WRAP) -/* Replacement for UNIX system call. */ -/* Other calls that write to the heap should be handled similarly. */ -/* Note that this doesn't work well for blocking reads: It will hold */ +/* Replacement for UNIX system call. */ +/* Other calls that write to the heap should be handled similarly. */ +/* Note that this doesn't work well for blocking reads: It will hold */ /* the allocation lock for the entire duration of the call. Multithreaded */ -/* clients should really ensure that it won't block, either by setting */ -/* the descriptor nonblocking, or by calling select or poll first, to */ -/* make sure that input is available. */ -/* Another, preferred alternative is to ensure that system calls never */ -/* write to the protected heap (see above). */ +/* clients should really ensure that it won't block, either by setting */ +/* the descriptor nonblocking, or by calling select or poll first, to */ +/* make sure that input is available. */ +/* Another, preferred alternative is to ensure that system calls never */ +/* write to the protected heap (see above). */ # include # include ssize_t read(int fd, void *buf, size_t nbyte) { int result; - + GC_begin_syscall(); GC_unprotect_range(buf, (word)nbyte); # if defined(IRIX5) || defined(GC_LINUX_THREADS) - /* Indirect system call may not always be easily available. */ - /* We could call _read, but that would interfere with the */ - /* libpthread interception of read. */ - /* On Linux, we have to be careful with the linuxthreads */ - /* read interception. */ - { - struct iovec iov; - - iov.iov_base = buf; - iov.iov_len = nbyte; - result = readv(fd, &iov, 1); - } + /* Indirect system call may not always be easily available. */ + /* We could call _read, but that would interfere with the */ + /* libpthread interception of read. */ + /* On Linux, we have to be careful with the linuxthreads */ + /* read interception. */ + { + struct iovec iov; + + iov.iov_base = buf; + iov.iov_len = nbyte; + result = readv(fd, &iov, 1); + } # else -# if defined(HURD) - result = __read(fd, buf, nbyte); +# if defined(HURD) + result = __read(fd, buf, nbyte); # else - /* The two zero args at the end of this list are because one - IA-64 syscall() implementation actually requires six args - to be passed, even though they aren't always used. */ - result = syscall(SYS_read, fd, buf, nbyte, 0, 0); + /* The two zero args at the end of this list are because one + IA-64 syscall() implementation actually requires six args + to be passed, even though they aren't always used. */ + result = syscall(SYS_read, fd, buf, nbyte, 0, 0); # endif /* !HURD */ # endif GC_end_syscall(); @@ -3198,25 +3198,25 @@ ssize_t read(int fd, void *buf, size_t nbyte) #endif /* !MSWIN32 && !MSWINCE && !GC_LINUX_THREADS */ #if defined(GC_USE_LD_WRAP) && !defined(THREADS) - /* We use the GNU ld call wrapping facility. */ - /* This requires that the linker be invoked with "--wrap read". */ - /* This can be done by passing -Wl,"--wrap read" to gcc. */ - /* I'm not sure that this actually wraps whatever version of read */ - /* is called by stdio. That code also mentions __read. */ + /* We use the GNU ld call wrapping facility. */ + /* This requires that the linker be invoked with "--wrap read". */ + /* This can be done by passing -Wl,"--wrap read" to gcc. */ + /* I'm not sure that this actually wraps whatever version of read */ + /* is called by stdio. That code also mentions __read. */ # include ssize_t __wrap_read(int fd, void *buf, size_t nbyte) { - int result; + int result; - GC_begin_syscall(); - GC_unprotect_range(buf, (word)nbyte); - result = __real_read(fd, buf, nbyte); - GC_end_syscall(); - return(result); + GC_begin_syscall(); + GC_unprotect_range(buf, (word)nbyte); + result = __real_read(fd, buf, nbyte); + GC_end_syscall(); + return(result); } - /* We should probably also do this for __read, or whatever stdio */ - /* actually calls. */ + /* We should probably also do this for __read, or whatever stdio */ + /* actually calls. */ #endif #endif /* 0 */ @@ -3238,7 +3238,7 @@ GC_bool GC_page_was_ever_dirty(struct hblk *h) /* * See DEFAULT_VDB for interface descriptions. */ - + /* * This implementation assumes a Solaris 2.X like /proc pseudo-file-system * from which we can read page modified bits. This facility is far from @@ -3267,30 +3267,30 @@ void GC_dirty_init(void) GC_dirty_maintained = TRUE; if (GC_bytes_allocd != 0 || GC_bytes_allocd_before_gc != 0) { - register int i; - + register int i; + for (i = 0; i < PHT_SIZE; i++) GC_written_pages[i] = (word)(-1); - if (GC_print_stats == VERBOSE) - GC_log_printf( - "Allocated bytes:%lu:all pages may have been written\n", - (unsigned long) - (GC_bytes_allocd + GC_bytes_allocd_before_gc)); + if (GC_print_stats == VERBOSE) + GC_log_printf( + "Allocated bytes:%lu:all pages may have been written\n", + (unsigned long) + (GC_bytes_allocd + GC_bytes_allocd_before_gc)); } sprintf(buf, "/proc/%ld", (long)getpid()); fd = open(buf, O_RDONLY); if (fd < 0) { - ABORT("/proc open failed"); + ABORT("/proc open failed"); } GC_proc_fd = syscall(SYS_ioctl, fd, PIOCOPENPD, 0); close(fd); syscall(SYS_fcntl, GC_proc_fd, F_SETFD, FD_CLOEXEC); if (GC_proc_fd < 0) { - ABORT("/proc ioctl failed"); + ABORT("/proc ioctl failed"); } GC_proc_buf = GC_scratch_alloc(GC_proc_buf_size); } -/* Ignore write hints. They don't help us here. */ +/* Ignore write hints. They don't help us here. */ /*ARGSUSED*/ void GC_remove_protection(struct hblk *h, word nblocks, GC_bool is_ptrfree) { @@ -3309,59 +3309,59 @@ void GC_read_dirty(void) int i; BZERO(GC_grungy_pages, (sizeof GC_grungy_pages)); - + bufp = GC_proc_buf; if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) { - if (GC_print_stats) + if (GC_print_stats) GC_log_printf("/proc read failed: GC_proc_buf_size = %lu\n", - (unsigned long)GC_proc_buf_size); + (unsigned long)GC_proc_buf_size); { /* Retry with larger buffer. */ word new_size = 2 * GC_proc_buf_size; char * new_buf = GC_scratch_alloc(new_size); - + if (new_buf != 0) { GC_proc_buf = bufp = new_buf; GC_proc_buf_size = new_size; } if (READ(GC_proc_fd, bufp, GC_proc_buf_size) <= 0) { WARN("Insufficient space for /proc read\n", 0); - /* Punt: */ - memset(GC_grungy_pages, 0xff, sizeof (page_hash_table)); - memset(GC_written_pages, 0xff, sizeof(page_hash_table)); - return; + /* Punt: */ + memset(GC_grungy_pages, 0xff, sizeof (page_hash_table)); + memset(GC_written_pages, 0xff, sizeof(page_hash_table)); + return; } } } /* Copy dirty bits into GC_grungy_pages */ - nmaps = ((struct prpageheader *)bufp) -> pr_nmap; - /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n", - nmaps, PG_REFERENCED, PG_MODIFIED); */ - bufp = bufp + sizeof(struct prpageheader); - for (i = 0; i < nmaps; i++) { - map = (struct prasmap *)bufp; - vaddr = (ptr_t)(map -> pr_vaddr); - ps = map -> pr_pagesize; - np = map -> pr_npage; - /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */ - limit = vaddr + ps * np; - bufp += sizeof (struct prasmap); - for (current_addr = vaddr; - current_addr < limit; current_addr += ps){ - if ((*bufp++) & PG_MODIFIED) { - register struct hblk * h = (struct hblk *) current_addr; - - while ((ptr_t)h < current_addr + ps) { - register word index = PHT_HASH(h); - - set_pht_entry_from_index(GC_grungy_pages, index); - h++; - } - } - } - bufp += sizeof(long) - 1; - bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1)); - } + nmaps = ((struct prpageheader *)bufp) -> pr_nmap; + /* printf( "nmaps = %d, PG_REFERENCED = %d, PG_MODIFIED = %d\n", + nmaps, PG_REFERENCED, PG_MODIFIED); */ + bufp = bufp + sizeof(struct prpageheader); + for (i = 0; i < nmaps; i++) { + map = (struct prasmap *)bufp; + vaddr = (ptr_t)(map -> pr_vaddr); + ps = map -> pr_pagesize; + np = map -> pr_npage; + /* printf("vaddr = 0x%X, ps = 0x%X, np = 0x%X\n", vaddr, ps, np); */ + limit = vaddr + ps * np; + bufp += sizeof (struct prasmap); + for (current_addr = vaddr; + current_addr < limit; current_addr += ps){ + if ((*bufp++) & PG_MODIFIED) { + register struct hblk * h = (struct hblk *) current_addr; + + while ((ptr_t)h < current_addr + ps) { + register word index = PHT_HASH(h); + + set_pht_entry_from_index(GC_grungy_pages, index); + h++; + } + } + } + bufp += sizeof(long) - 1; + bufp = (char *)((unsigned long)bufp & ~(sizeof(long)-1)); + } /* Update GC_written_pages. */ GC_or_pages(GC_written_pages, GC_grungy_pages); } @@ -3371,14 +3371,14 @@ void GC_read_dirty(void) GC_bool GC_page_was_dirty(struct hblk *h) { register word index = PHT_HASH(h); - + return get_pht_entry_from_index(GC_grungy_pages, index); } GC_bool GC_page_was_ever_dirty(struct hblk *h) { register word index = PHT_HASH(h); - + return get_pht_entry_from_index(GC_written_pages, index); } @@ -3389,12 +3389,12 @@ GC_bool GC_page_was_ever_dirty(struct hblk *h) # include "vd/PCR_VD.h" -# define NPAGES (32*1024) /* 128 MB */ +# define NPAGES (32*1024) /* 128 MB */ PCR_VD_DB GC_grungy_bits[NPAGES]; -ptr_t GC_vd_base; /* Address corresponding to GC_grungy_bits[0] */ - /* HBLKSIZE aligned. */ +ptr_t GC_vd_base; /* Address corresponding to GC_grungy_bits[0] */ + /* HBLKSIZE aligned. */ void GC_dirty_init(void) { @@ -3402,11 +3402,11 @@ void GC_dirty_init(void) /* For the time being, we assume the heap generally grows up */ GC_vd_base = GC_heap_sects[0].hs_start; if (GC_vd_base == 0) { - ABORT("Bad initial heap segment"); + ABORT("Bad initial heap segment"); } if (PCR_VD_Start(HBLKSIZE, GC_vd_base, NPAGES*HBLKSIZE) - != PCR_ERes_okay) { - ABORT("dirty bit initialization failed"); + != PCR_ERes_okay) { + ABORT("dirty bit initialization failed"); } } @@ -3426,14 +3426,14 @@ void GC_read_dirty(void) if (PCR_VD_Clear(GC_vd_base, NPAGES*HBLKSIZE, GC_grungy_bits) != PCR_ERes_okay) { - ABORT("dirty bit read failed"); + ABORT("dirty bit read failed"); } } GC_bool GC_page_was_dirty(struct hblk *h) { if((ptr_t)h < GC_vd_base || (ptr_t)h >= GC_vd_base + NPAGES*HBLKSIZE) { - return(TRUE); + return(TRUE); } return(GC_grungy_bits[h - (struct hblk *)GC_vd_base] & PCR_VD_DB_dirtyBit); } @@ -3477,21 +3477,21 @@ exc_server(mach_msg_header_t *, mach_msg_header_t *); extern kern_return_t exception_raise(mach_port_t, mach_port_t, mach_port_t, exception_type_t, - exception_data_t, mach_msg_type_number_t); + exception_data_t, mach_msg_type_number_t); extern kern_return_t exception_raise_state(mach_port_t, mach_port_t, mach_port_t, exception_type_t, - exception_data_t, mach_msg_type_number_t, - thread_state_flavor_t*, thread_state_t, - mach_msg_type_number_t, thread_state_t, - mach_msg_type_number_t*); + exception_data_t, mach_msg_type_number_t, + thread_state_flavor_t*, thread_state_t, + mach_msg_type_number_t, thread_state_t, + mach_msg_type_number_t*); extern kern_return_t exception_raise_state_identity(mach_port_t, mach_port_t, mach_port_t, - exception_type_t, exception_data_t, - mach_msg_type_number_t, thread_state_flavor_t*, - thread_state_t, mach_msg_type_number_t, - thread_state_t, mach_msg_type_number_t*); + exception_type_t, exception_data_t, + mach_msg_type_number_t, thread_state_flavor_t*, + thread_state_t, mach_msg_type_number_t, + thread_state_t, mach_msg_type_number_t*); #define MAX_EXCEPTION_PORTS 16 @@ -3550,8 +3550,8 @@ static void GC_mprotect_thread_notify(mach_msg_id_t id) buf.msg.head.msgh_id = id; r = mach_msg(&buf.msg.head, MACH_SEND_MSG | MACH_RCV_MSG | MACH_RCV_LARGE, - sizeof(buf.msg), sizeof(buf), GC_ports.reply, - MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); + sizeof(buf.msg), sizeof(buf), GC_ports.reply, + MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if(r != MACH_MSG_SUCCESS) ABORT("mach_msg failed in GC_mprotect_thread_notify"); if(buf.msg.head.msgh_id != ID_ACK) @@ -3572,7 +3572,7 @@ static void GC_mprotect_thread_reply(void) msg.head.msgh_id = ID_ACK; r = mach_msg(&msg.head, MACH_SEND_MSG, sizeof(msg), 0, MACH_PORT_NULL, - MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); + MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); if(r != MACH_MSG_SUCCESS) ABORT("mach_msg failed in GC_mprotect_thread_reply"); } @@ -3613,63 +3613,63 @@ static void *GC_mprotect_thread(void *arg) for(;;) { r = mach_msg(&msg.head, MACH_RCV_MSG | MACH_RCV_LARGE | - (GC_mprotect_state == GC_MP_DISCARDING ? MACH_RCV_TIMEOUT : 0), - 0, sizeof(msg), GC_ports.exception, - GC_mprotect_state == GC_MP_DISCARDING ? 0 - : MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); + (GC_mprotect_state == GC_MP_DISCARDING ? MACH_RCV_TIMEOUT : 0), + 0, sizeof(msg), GC_ports.exception, + GC_mprotect_state == GC_MP_DISCARDING ? 0 + : MACH_MSG_TIMEOUT_NONE, MACH_PORT_NULL); id = r == MACH_MSG_SUCCESS ? msg.head.msgh_id : -1; # if defined(THREADS) if(GC_mprotect_state == GC_MP_DISCARDING) { - if(r == MACH_RCV_TIMED_OUT) { - GC_mprotect_state = GC_MP_STOPPED; - GC_mprotect_thread_reply(); - continue; - } - if(r == MACH_MSG_SUCCESS && (id == ID_STOP || id == ID_RESUME)) - ABORT("out of order mprotect thread request"); + if(r == MACH_RCV_TIMED_OUT) { + GC_mprotect_state = GC_MP_STOPPED; + GC_mprotect_thread_reply(); + continue; + } + if(r == MACH_MSG_SUCCESS && (id == ID_STOP || id == ID_RESUME)) + ABORT("out of order mprotect thread request"); } # endif /* THREADS */ if(r != MACH_MSG_SUCCESS) { GC_err_printf("mach_msg failed with %d %s\n", (int)r, - mach_error_string(r)); + mach_error_string(r)); ABORT("mach_msg failed"); } switch(id) { # if defined(THREADS) case ID_STOP: - if(GC_mprotect_state != GC_MP_NORMAL) - ABORT("Called mprotect_stop when state wasn't normal"); - GC_mprotect_state = GC_MP_DISCARDING; - break; + if(GC_mprotect_state != GC_MP_NORMAL) + ABORT("Called mprotect_stop when state wasn't normal"); + GC_mprotect_state = GC_MP_DISCARDING; + break; case ID_RESUME: - if(GC_mprotect_state != GC_MP_STOPPED) - ABORT("Called mprotect_resume when state wasn't stopped"); - GC_mprotect_state = GC_MP_NORMAL; - GC_mprotect_thread_reply(); - break; + if(GC_mprotect_state != GC_MP_STOPPED) + ABORT("Called mprotect_resume when state wasn't stopped"); + GC_mprotect_state = GC_MP_NORMAL; + GC_mprotect_thread_reply(); + break; # endif /* THREADS */ default: - /* Handle the message (calls catch_exception_raise) */ - if(!exc_server(&msg.head, &reply.head)) - ABORT("exc_server failed"); - /* Send the reply */ - r = mach_msg(&reply.head, MACH_SEND_MSG, reply.head.msgh_size, 0, - MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, - MACH_PORT_NULL); - if(r != MACH_MSG_SUCCESS) { - /* This will fail if the thread dies, but the thread */ - /* shouldn't die... */ + /* Handle the message (calls catch_exception_raise) */ + if(!exc_server(&msg.head, &reply.head)) + ABORT("exc_server failed"); + /* Send the reply */ + r = mach_msg(&reply.head, MACH_SEND_MSG, reply.head.msgh_size, 0, + MACH_PORT_NULL, MACH_MSG_TIMEOUT_NONE, + MACH_PORT_NULL); + if(r != MACH_MSG_SUCCESS) { + /* This will fail if the thread dies, but the thread */ + /* shouldn't die... */ # ifdef BROKEN_EXCEPTION_HANDLING - GC_err_printf("mach_msg failed with %d %s while sending " - "exc reply\n", (int)r,mach_error_string(r)); + GC_err_printf("mach_msg failed with %d %s while sending " + "exc reply\n", (int)r,mach_error_string(r)); # else - ABORT("mach_msg failed while sending exception reply"); + ABORT("mach_msg failed while sending exception reply"); # endif - } + } } /* switch */ } /* for(;;) */ /* NOT REACHED */ @@ -3713,10 +3713,10 @@ void GC_dirty_init(void) if (GC_print_stats == VERBOSE) GC_log_printf("Initializing mach/darwin mprotect virtual dirty bit " - "implementation\n"); + "implementation\n"); # ifdef BROKEN_EXCEPTION_HANDLING WARN("Enabling workarounds for various darwin " - "exception handling bugs.\n", 0); + "exception handling bugs.\n", 0); # endif GC_dirty_maintained = TRUE; if (GC_page_size % HBLKSIZE != 0) { @@ -3731,7 +3731,7 @@ void GC_dirty_init(void) ABORT("mach_port_allocate failed (exception port)"); r = mach_port_insert_right(me, GC_ports.exception, GC_ports.exception, - MACH_MSG_TYPE_MAKE_SEND); + MACH_MSG_TYPE_MAKE_SEND); if(r != KERN_SUCCESS) ABORT("mach_port_insert_right failed (exception port)"); @@ -3745,14 +3745,14 @@ void GC_dirty_init(void) mask = EXC_MASK_BAD_ACCESS; r = task_get_exception_ports(me, mask, GC_old_exc_ports.masks, - &GC_old_exc_ports.count, GC_old_exc_ports.ports, - GC_old_exc_ports.behaviors, - GC_old_exc_ports.flavors); + &GC_old_exc_ports.count, GC_old_exc_ports.ports, + GC_old_exc_ports.behaviors, + GC_old_exc_ports.flavors); if(r != KERN_SUCCESS) ABORT("task_get_exception_ports failed"); r = task_set_exception_ports(me, mask, GC_ports.exception, EXCEPTION_DEFAULT, - GC_MACH_THREAD_STATE); + GC_MACH_THREAD_STATE); if(r != KERN_SUCCESS) ABORT("task_set_exception_ports failed"); if(pthread_attr_init(&attr) != 0) @@ -3774,10 +3774,10 @@ void GC_dirty_init(void) sigemptyset(&sa.sa_mask); sa.sa_flags = SA_RESTART|SA_SIGINFO; if(sigaction(SIGBUS, &sa, &oldsa) < 0) - ABORT("sigaction"); + ABORT("sigaction"); if ((SIG_HNDLR_PTR)oldsa.sa_handler != SIG_DFL) { - if (GC_print_stats == VERBOSE) - GC_err_printf("Replaced other SIGBUS handler\n"); + if (GC_print_stats == VERBOSE) + GC_err_printf("Replaced other SIGBUS handler\n"); } } # endif /* BROKEN_EXCEPTION_HANDLING */ @@ -3787,9 +3787,9 @@ void GC_dirty_init(void) forwarding code. This code is similar to be GDB code only because there is only one way to do it. */ static kern_return_t GC_forward_exception(mach_port_t thread, mach_port_t task, - exception_type_t exception, - exception_data_t data, - mach_msg_type_number_t data_count) + exception_type_t exception, + exception_data_t data, + mach_msg_type_number_t data_count) { unsigned int i; kern_return_t r; @@ -3819,14 +3819,14 @@ static kern_return_t GC_forward_exception(mach_port_t thread, mach_port_t task, switch(behavior) { case EXCEPTION_STATE: r = exception_raise_state(port, thread, task, exception, data, data_count, - &flavor, thread_state, thread_state_count, - thread_state, &thread_state_count); + &flavor, thread_state, thread_state_count, + thread_state, &thread_state_count); break; case EXCEPTION_STATE_IDENTITY: r = exception_raise_state_identity(port, thread, task, exception, data, - data_count, &flavor, thread_state, - thread_state_count, thread_state, - &thread_state_count); + data_count, &flavor, thread_state, + thread_state_count, thread_state, + &thread_state_count); break; /* case EXCEPTION_DEFAULT: */ /* default signal handlers */ default: /* user-supplied signal handlers */ @@ -3848,8 +3848,8 @@ static kern_return_t GC_forward_exception(mach_port_t thread, mach_port_t task, about it. The exception handling stuff is hard coded to call this */ kern_return_t catch_exception_raise(mach_port_t exception_port, mach_port_t thread, - mach_port_t task, exception_type_t exception, - exception_data_t code, mach_msg_type_number_t code_count) + mach_port_t task, exception_type_t exception, + exception_data_t code, mach_msg_type_number_t code_count) { kern_return_t r; char *addr; @@ -3884,13 +3884,13 @@ catch_exception_raise(mach_port_t exception_port, mach_port_t thread, # ifdef DEBUG_EXCEPTION_HANDLING /* We aren't interested, pass it on to the old handler */ GC_printf("Exception: 0x%x Code: 0x%x 0x%x in catch....\n", exception, - code_count > 0 ? code[0] : -1, code_count > 1 ? code[1] : -1); + code_count > 0 ? code[0] : -1, code_count > 1 ? code[1] : -1); # endif return FWD(); } r = thread_get_state(thread, flavor, (natural_t*)&exc_state, - &exc_state_count); + &exc_state_count); if(r != KERN_SUCCESS) { /* The thread is supposed to be suspended while the exception handler is called. This shouldn't fail. */ @@ -3913,34 +3913,34 @@ catch_exception_raise(mach_port_t exception_port, mach_port_t thread, if((HDR(addr)) == 0) { /* Ugh... just like the SIGBUS problem above, it seems we get a bogus - KERN_PROTECTION_FAILURE every once and a while. We wait till we get - a bunch in a row before doing anything about it. If a "real" fault - ever occurs it'll just keep faulting over and over and we'll hit - the limit pretty quickly. */ + KERN_PROTECTION_FAILURE every once and a while. We wait till we get + a bunch in a row before doing anything about it. If a "real" fault + ever occurs it'll just keep faulting over and over and we'll hit + the limit pretty quickly. */ # ifdef BROKEN_EXCEPTION_HANDLING static char *last_fault; - static int last_fault_count; - - if(addr != last_fault) { - last_fault = addr; - last_fault_count = 0; - } - if(++last_fault_count < 32) { - if(last_fault_count == 1) - WARN("Ignoring KERN_PROTECTION_FAILURE at %p\n", addr); - return KERN_SUCCESS; - } - - GC_err_printf("Unexpected KERN_PROTECTION_FAILURE at %p\n",addr); - /* Can't pass it along to the signal handler because that is - ignoring SIGBUS signals. We also shouldn't call ABORT here as - signals don't always work too well from the exception handler. */ - GC_err_printf("Aborting\n"); - exit(EXIT_FAILURE); + static int last_fault_count; + + if(addr != last_fault) { + last_fault = addr; + last_fault_count = 0; + } + if(++last_fault_count < 32) { + if(last_fault_count == 1) + WARN("Ignoring KERN_PROTECTION_FAILURE at %p\n", addr); + return KERN_SUCCESS; + } + + GC_err_printf("Unexpected KERN_PROTECTION_FAILURE at %p\n",addr); + /* Can't pass it along to the signal handler because that is + ignoring SIGBUS signals. We also shouldn't call ABORT here as + signals don't always work too well from the exception handler. */ + GC_err_printf("Aborting\n"); + exit(EXIT_FAILURE); # else /* BROKEN_EXCEPTION_HANDLING */ - /* Pass it along to the next exception handler - (which should call SIGBUS/SIGSEGV) */ - return FWD(); + /* Pass it along to the next exception handler + (which should call SIGBUS/SIGSEGV) */ + return FWD(); # endif /* !BROKEN_EXCEPTION_HANDLING */ } @@ -3953,13 +3953,13 @@ catch_exception_raise(mach_port_t exception_port, mach_port_t thread, h = (struct hblk*)((word)addr & ~(GC_page_size-1)); UNPROTECT(h, GC_page_size); for (i = 0; i < divHBLKSZ(GC_page_size); i++) { - register int index = PHT_HASH(h+i); - async_set_pht_entry_from_index(GC_dirty_pages, index); + register int index = PHT_HASH(h+i); + async_set_pht_entry_from_index(GC_dirty_pages, index); } } else if(GC_mprotect_state == GC_MP_DISCARDING) { /* Lie to the thread for now. No sense UNPROTECT()ing the memory - when we're just going to PROTECT() it again later. The thread - will just fault again once it resumes */ + when we're just going to PROTECT() it again later. The thread + will just fault again once it resumes */ } else { /* Shouldn't happen, i don't think */ GC_printf("KERN_PROTECTION_FAILURE while world is stopped\n"); @@ -3972,10 +3972,10 @@ catch_exception_raise(mach_port_t exception_port, mach_port_t thread, /* These should never be called, but just in case... */ kern_return_t catch_exception_raise_state(mach_port_name_t exception_port, int exception, - exception_data_t code, - mach_msg_type_number_t codeCnt, int flavor, - thread_state_t old_state, int old_stateCnt, - thread_state_t new_state, int new_stateCnt) + exception_data_t code, + mach_msg_type_number_t codeCnt, int flavor, + thread_state_t old_state, int old_stateCnt, + thread_state_t new_state, int new_stateCnt) { ABORT("catch_exception_raise_state"); return(KERN_INVALID_ARGUMENT); @@ -3983,11 +3983,11 @@ catch_exception_raise_state(mach_port_name_t exception_port, int exception, kern_return_t catch_exception_raise_state_identity(mach_port_name_t exception_port, - mach_port_t thread, mach_port_t task, - int exception, exception_data_t code, - mach_msg_type_number_t codeCnt, int flavor, - thread_state_t old_state, int old_stateCnt, - thread_state_t new_state, int new_stateCnt) + mach_port_t thread, mach_port_t task, + int exception, exception_data_t code, + mach_msg_type_number_t codeCnt, int flavor, + thread_state_t old_state, int old_stateCnt, + thread_state_t new_state, int new_stateCnt) { ABORT("catch_exception_raise_state_identity"); return(KERN_INVALID_ARGUMENT); @@ -4008,16 +4008,16 @@ catch_exception_raise_state_identity(mach_port_name_t exception_port, * Should probably be in mach_dep.c, but that requires reorganization. */ -/* I suspect the following works for most X86 *nix variants, so */ -/* long as the frame pointer is explicitly stored. In the case of gcc, */ -/* compiler flags (e.g. -fomit-frame-pointer) determine whether it is. */ +/* I suspect the following works for most X86 *nix variants, so */ +/* long as the frame pointer is explicitly stored. In the case of gcc, */ +/* compiler flags (e.g. -fomit-frame-pointer) determine whether it is. */ #if defined(I386) && defined(LINUX) && defined(SAVE_CALL_CHAIN) # include struct frame { - struct frame *fr_savfp; - long fr_savpc; - long fr_arg[NARGS]; /* All the arguments go here. */ + struct frame *fr_savfp; + long fr_savpc; + long fr_arg[NARGS]; /* All the arguments go here. */ }; #endif @@ -4026,15 +4026,15 @@ catch_exception_raise_state_identity(mach_port_name_t exception_port, # include struct frame { - long fr_local[8]; - long fr_arg[6]; - struct frame *fr_savfp; - long fr_savpc; + long fr_local[8]; + long fr_arg[6]; + struct frame *fr_savfp; + long fr_savpc; # ifndef __arch64__ - char *fr_stret; + char *fr_stret; # endif - long fr_argd[6]; - long fr_argx[0]; + long fr_argd[6]; + long fr_argx[0]; }; # elif defined (DRSNX) # include @@ -4051,8 +4051,8 @@ catch_exception_raise_state_identity(mach_port_name_t exception_port, #endif /* SPARC */ #ifdef NEED_CALLINFO -/* Fill in the pc and argument information for up to NFRAMES of my */ -/* callers. Ignore my frame and my callers frame. */ +/* Fill in the pc and argument information for up to NFRAMES of my */ +/* callers. Ignore my frame and my callers frame. */ #ifdef LINUX # include @@ -4074,23 +4074,23 @@ catch_exception_raise_state_identity(mach_port_name_t exception_port, && defined(GC_HAVE_BUILTIN_BACKTRACE) #ifdef REDIRECT_MALLOC - /* Deal with possible malloc calls in backtrace by omitting */ - /* the infinitely recursing backtrace. */ + /* Deal with possible malloc calls in backtrace by omitting */ + /* the infinitely recursing backtrace. */ # ifdef THREADS - __thread /* If your compiler doesn't understand this */ - /* you could use something like pthread_getspecific. */ + __thread /* If your compiler doesn't understand this */ + /* you could use something like pthread_getspecific. */ # endif GC_in_save_callers = FALSE; #endif -void GC_save_callers (struct callinfo info[NFRAMES]) +void GC_save_callers (struct callinfo info[NFRAMES]) { void * tmp_info[NFRAMES + 1]; int npcs, i; # define IGNORE_FRAMES 1 - - /* We retrieve NFRAMES+1 pc values, but discard the first, since it */ - /* points to our own frame. */ + + /* We retrieve NFRAMES+1 pc values, but discard the first, since it */ + /* points to our own frame. */ # ifdef REDIRECT_MALLOC if (GC_in_save_callers) { info[0].ci_pc = (word)(&GC_save_callers); @@ -4124,7 +4124,7 @@ void GC_save_callers (struct callinfo info[NFRAMES]) # define BIAS 0 #endif -void GC_save_callers (struct callinfo info[NFRAMES]) +void GC_save_callers (struct callinfo info[NFRAMES]) { struct frame *frame; struct frame *fp; @@ -4137,16 +4137,16 @@ void GC_save_callers (struct callinfo info[NFRAMES]) frame = (struct frame *) GC_save_regs_in_stack (); fp = (struct frame *)((long) frame -> FR_SAVFP + BIAS); #endif - + for (; (!(fp HOTTER_THAN frame) && !(GC_stackbottom HOTTER_THAN (ptr_t)fp) - && (nframes < NFRAMES)); + && (nframes < NFRAMES)); fp = (struct frame *)((long) fp -> FR_SAVFP + BIAS), nframes++) { register int i; - + info[nframes].ci_pc = fp->FR_SAVPC; # if NARGS > 0 for (i = 0; i < NARGS; i++) { - info[nframes].ci_arg[i] = ~(fp->fr_arg[i]); + info[nframes].ci_arg[i] = ~(fp->fr_arg[i]); } # endif /* NARGS > 0 */ } @@ -4166,141 +4166,141 @@ void GC_print_callers (struct callinfo info[NFRAMES]) static int reentry_count = 0; GC_bool stop = FALSE; - /* FIXME: This should probably use a different lock, so that we */ - /* become callable with or without the allocation lock. */ + /* FIXME: This should probably use a different lock, so that we */ + /* become callable with or without the allocation lock. */ LOCK(); ++reentry_count; UNLOCK(); - + # if NFRAMES == 1 GC_err_printf("\tCaller at allocation:\n"); # else GC_err_printf("\tCall chain at allocation:\n"); # endif for (i = 0; i < NFRAMES && !stop ; i++) { - if (info[i].ci_pc == 0) break; -# if NARGS > 0 - { - int j; - - GC_err_printf("\t\targs: "); - for (j = 0; j < NARGS; j++) { - if (j != 0) GC_err_printf(", "); - GC_err_printf("%d (0x%X)", ~(info[i].ci_arg[j]), - ~(info[i].ci_arg[j])); - } - GC_err_printf("\n"); - } -# endif + if (info[i].ci_pc == 0) break; +# if NARGS > 0 + { + int j; + + GC_err_printf("\t\targs: "); + for (j = 0; j < NARGS; j++) { + if (j != 0) GC_err_printf(", "); + GC_err_printf("%d (0x%X)", ~(info[i].ci_arg[j]), + ~(info[i].ci_arg[j])); + } + GC_err_printf("\n"); + } +# endif if (reentry_count > 1) { - /* We were called during an allocation during */ - /* a previous GC_print_callers call; punt. */ - GC_err_printf("\t\t##PC##= 0x%lx\n", info[i].ci_pc); - continue; - } - { -# ifdef LINUX - FILE *pipe; -# endif -# if defined(GC_HAVE_BUILTIN_BACKTRACE) \ - && !defined(GC_BACKTRACE_SYMBOLS_BROKEN) - char **sym_name = - backtrace_symbols((void **)(&(info[i].ci_pc)), 1); - char *name = sym_name[0]; -# else - char buf[40]; - char *name = buf; - sprintf(buf, "##PC##= 0x%lx", info[i].ci_pc); -# endif -# if defined(LINUX) && !defined(SMALL_CONFIG) - /* Try for a line number. */ - { -# define EXE_SZ 100 - static char exe_name[EXE_SZ]; -# define CMD_SZ 200 - char cmd_buf[CMD_SZ]; -# define RESULT_SZ 200 - static char result_buf[RESULT_SZ]; - size_t result_len; - char *old_preload; -# define PRELOAD_SZ 200 - char preload_buf[PRELOAD_SZ]; - static GC_bool found_exe_name = FALSE; - static GC_bool will_fail = FALSE; - int ret_code; - /* Try to get it via a hairy and expensive scheme. */ - /* First we get the name of the executable: */ - if (will_fail) goto out; - if (!found_exe_name) { - ret_code = readlink("/proc/self/exe", exe_name, EXE_SZ); - if (ret_code < 0 || ret_code >= EXE_SZ - || exe_name[0] != '/') { - will_fail = TRUE; /* Dont try again. */ - goto out; - } - exe_name[ret_code] = '\0'; - found_exe_name = TRUE; - } - /* Then we use popen to start addr2line -e */ - /* There are faster ways to do this, but hopefully this */ - /* isn't time critical. */ - sprintf(cmd_buf, "/usr/bin/addr2line -f -e %s 0x%lx", exe_name, - (unsigned long)info[i].ci_pc); - old_preload = getenv ("LD_PRELOAD"); - if (0 != old_preload) { - if (strlen (old_preload) >= PRELOAD_SZ) { - will_fail = TRUE; - goto out; - } - strcpy (preload_buf, old_preload); - unsetenv ("LD_PRELOAD"); - } - pipe = popen(cmd_buf, "r"); - if (0 != old_preload - && 0 != setenv ("LD_PRELOAD", preload_buf, 0)) { - WARN("Failed to reset LD_PRELOAD\n", 0); - } - if (pipe == NULL - || (result_len = fread(result_buf, 1, RESULT_SZ - 1, pipe)) - == 0) { - if (pipe != NULL) pclose(pipe); - will_fail = TRUE; - goto out; - } - if (result_buf[result_len - 1] == '\n') --result_len; - result_buf[result_len] = 0; - if (result_buf[0] == '?' - || (result_buf[result_len-2] == ':' - && result_buf[result_len-1] == '0')) { - pclose(pipe); - goto out; - } - /* Get rid of embedded newline, if any. Test for "main" */ - { - char * nl = strchr(result_buf, '\n'); - if (nl != NULL && nl < result_buf + result_len) { - *nl = ':'; - } - if (strncmp(result_buf, "main", nl - result_buf) == 0) { - stop = TRUE; - } - } - if (result_len < RESULT_SZ - 25) { - /* Add in hex address */ - sprintf(result_buf + result_len, " [0x%lx]", - (unsigned long)info[i].ci_pc); - } - name = result_buf; - pclose(pipe); - out:; - } -# endif /* LINUX */ - GC_err_printf("\t\t%s\n", name); -# if defined(GC_HAVE_BUILTIN_BACKTRACE) \ - && !defined(GC_BACKTRACE_SYMBOLS_BROKEN) - free(sym_name); /* May call GC_free; that's OK */ + /* We were called during an allocation during */ + /* a previous GC_print_callers call; punt. */ + GC_err_printf("\t\t##PC##= 0x%lx\n", info[i].ci_pc); + continue; + } + { +# ifdef LINUX + FILE *pipe; +# endif +# if defined(GC_HAVE_BUILTIN_BACKTRACE) \ + && !defined(GC_BACKTRACE_SYMBOLS_BROKEN) + char **sym_name = + backtrace_symbols((void **)(&(info[i].ci_pc)), 1); + char *name = sym_name[0]; +# else + char buf[40]; + char *name = buf; + sprintf(buf, "##PC##= 0x%lx", info[i].ci_pc); # endif - } +# if defined(LINUX) && !defined(SMALL_CONFIG) + /* Try for a line number. */ + { +# define EXE_SZ 100 + static char exe_name[EXE_SZ]; +# define CMD_SZ 200 + char cmd_buf[CMD_SZ]; +# define RESULT_SZ 200 + static char result_buf[RESULT_SZ]; + size_t result_len; + char *old_preload; +# define PRELOAD_SZ 200 + char preload_buf[PRELOAD_SZ]; + static GC_bool found_exe_name = FALSE; + static GC_bool will_fail = FALSE; + int ret_code; + /* Try to get it via a hairy and expensive scheme. */ + /* First we get the name of the executable: */ + if (will_fail) goto out; + if (!found_exe_name) { + ret_code = readlink("/proc/self/exe", exe_name, EXE_SZ); + if (ret_code < 0 || ret_code >= EXE_SZ + || exe_name[0] != '/') { + will_fail = TRUE; /* Dont try again. */ + goto out; + } + exe_name[ret_code] = '\0'; + found_exe_name = TRUE; + } + /* Then we use popen to start addr2line -e */ + /* There are faster ways to do this, but hopefully this */ + /* isn't time critical. */ + sprintf(cmd_buf, "/usr/bin/addr2line -f -e %s 0x%lx", exe_name, + (unsigned long)info[i].ci_pc); + old_preload = getenv ("LD_PRELOAD"); + if (0 != old_preload) { + if (strlen (old_preload) >= PRELOAD_SZ) { + will_fail = TRUE; + goto out; + } + strcpy (preload_buf, old_preload); + unsetenv ("LD_PRELOAD"); + } + pipe = popen(cmd_buf, "r"); + if (0 != old_preload + && 0 != setenv ("LD_PRELOAD", preload_buf, 0)) { + WARN("Failed to reset LD_PRELOAD\n", 0); + } + if (pipe == NULL + || (result_len = fread(result_buf, 1, RESULT_SZ - 1, pipe)) + == 0) { + if (pipe != NULL) pclose(pipe); + will_fail = TRUE; + goto out; + } + if (result_buf[result_len - 1] == '\n') --result_len; + result_buf[result_len] = 0; + if (result_buf[0] == '?' + || (result_buf[result_len-2] == ':' + && result_buf[result_len-1] == '0')) { + pclose(pipe); + goto out; + } + /* Get rid of embedded newline, if any. Test for "main" */ + { + char * nl = strchr(result_buf, '\n'); + if (nl != NULL && nl < result_buf + result_len) { + *nl = ':'; + } + if (strncmp(result_buf, "main", nl - result_buf) == 0) { + stop = TRUE; + } + } + if (result_len < RESULT_SZ - 25) { + /* Add in hex address */ + sprintf(result_buf + result_len, " [0x%lx]", + (unsigned long)info[i].ci_pc); + } + name = result_buf; + pclose(pipe); + out:; + } +# endif /* LINUX */ + GC_err_printf("\t\t%s\n", name); +# if defined(GC_HAVE_BUILTIN_BACKTRACE) \ + && !defined(GC_BACKTRACE_SYMBOLS_BROKEN) + free(sym_name); /* May call GC_free; that's OK */ +# endif + } } LOCK(); --reentry_count; @@ -4330,5 +4330,3 @@ void GC_print_address_map(void) } #endif - - diff --git a/pthread_support.c b/pthread_support.c index d216f77..f5cdbf1 100644 --- a/pthread_support.c +++ b/pthread_support.c @@ -1,4 +1,4 @@ -/* +/* * Copyright (c) 1994 by Xerox Corporation. All rights reserved. * Copyright (c) 1996 by Silicon Graphics. All rights reserved. * Copyright (c) 1998 by Fergus Henderson. All rights reserved. @@ -85,13 +85,13 @@ # include #endif /* GC_NETBSD_THREADS */ -/* Allocator lock definitions. */ +/* Allocator lock definitions. */ #if !defined(USE_SPIN_LOCK) pthread_mutex_t GC_allocate_ml = PTHREAD_MUTEX_INITIALIZER; #endif unsigned long GC_lock_holder = NO_THREAD; - /* Used only for assertions, and to prevent */ - /* recursive reentry in the system call wrapper. */ + /* Used only for assertions, and to prevent */ + /* recursive reentry in the system call wrapper. */ #if defined(GC_DGUX386_THREADS) # include @@ -127,12 +127,12 @@ unsigned long GC_lock_holder = NO_THREAD; # include # define WRAP_FUNC(f) f # define REAL_FUNC(f) GC_real_##f - /* We define both GC_f and plain f to be the wrapped function. */ - /* In that way plain calls work, as do calls from files that */ - /* included gc.h, wich redefined f to GC_f. */ + /* We define both GC_f and plain f to be the wrapped function. */ + /* In that way plain calls work, as do calls from files that */ + /* included gc.h, wich redefined f to GC_f. */ /* FIXME: Needs work for DARWIN and True64 (OSF1) */ typedef int (* GC_pthread_create_t)(pthread_t *, const pthread_attr_t *, - void * (*)(void *), void *); + void * (*)(void *), void *); static GC_pthread_create_t GC_real_pthread_create; typedef int (* GC_pthread_sigmask_t)(int, const sigset_t *, sigset_t *); static GC_pthread_sigmask_t GC_real_pthread_sigmask; @@ -151,22 +151,22 @@ unsigned long GC_lock_holder = NO_THREAD; #endif #if defined(GC_USE_DL_WRAP) || defined(GC_USE_DLOPEN_WRAP) -/* Define GC_ functions as aliases for the plain ones, which will */ -/* be intercepted. This allows files which include gc.h, and hence */ -/* generate references to the GC_ symbols, to see the right symbols. */ +/* Define GC_ functions as aliases for the plain ones, which will */ +/* be intercepted. This allows files which include gc.h, and hence */ +/* generate references to the GC_ symbols, to see the right symbols. */ GC_API int GC_pthread_create(pthread_t * t, const pthread_attr_t * a, - void * (* fn)(void *), void * arg) { - return pthread_create(t, a, fn, arg); + void * (* fn)(void *), void * arg) { + return pthread_create(t, a, fn, arg); } GC_API int GC_pthread_sigmask(int how, const sigset_t *mask, - sigset_t *old) { - return pthread_sigmask(how, mask, old); + sigset_t *old) { + return pthread_sigmask(how, mask, old); } GC_API int GC_pthread_join(pthread_t t, void **res) { - return pthread_join(t, res); + return pthread_join(t, res); } GC_API int GC_pthread_detach(pthread_t t) { - return pthread_detach(t); + return pthread_detach(t); } #endif /* Linker-based interception. */ @@ -197,13 +197,13 @@ unsigned long GC_lock_holder = NO_THREAD; if (NULL == dl_handle) ABORT("Couldn't open libpthread\n"); # endif GC_real_pthread_create = (GC_pthread_create_t) - dlsym(dl_handle, "pthread_create"); + dlsym(dl_handle, "pthread_create"); GC_real_pthread_sigmask = (GC_pthread_sigmask_t) - dlsym(dl_handle, "pthread_sigmask"); + dlsym(dl_handle, "pthread_sigmask"); GC_real_pthread_join = (GC_pthread_join_t) - dlsym(dl_handle, "pthread_join"); + dlsym(dl_handle, "pthread_join"); GC_real_pthread_detach = (GC_pthread_detach_t) - dlsym(dl_handle, "pthread_detach"); + dlsym(dl_handle, "pthread_detach"); GC_syms_initialized = TRUE; } @@ -221,23 +221,23 @@ GC_bool GC_need_to_lock = FALSE; void GC_init_parallel(void); STATIC long GC_nprocs = 1; - /* Number of processors. We may not have */ - /* access to all of them, but this is as good */ - /* a guess as any ... */ + /* Number of processors. We may not have */ + /* access to all of them, but this is as good */ + /* a guess as any ... */ #ifdef THREAD_LOCAL_ALLOC -/* We must explicitly mark ptrfree and gcj free lists, since the free */ -/* list links wouldn't otherwise be found. We also set them in the */ -/* normal free lists, since that involves touching less memory than if */ -/* we scanned them normally. */ +/* We must explicitly mark ptrfree and gcj free lists, since the free */ +/* list links wouldn't otherwise be found. We also set them in the */ +/* normal free lists, since that involves touching less memory than if */ +/* we scanned them normally. */ void GC_mark_thread_local_free_lists(void) { int i; GC_thread p; - + for (i = 0; i < THREAD_TABLE_SZ; ++i) { for (p = GC_threads[i]; 0 != p; p = p -> next) { - GC_mark_thread_local_fls_for(&(p->tlfs)); + GC_mark_thread_local_fls_for(&(p->tlfs)); } } } @@ -246,22 +246,22 @@ void GC_mark_thread_local_free_lists(void) void GC_check_tls_for(GC_tlfs p); # if defined(USE_CUSTOM_SPECIFIC) void GC_check_tsd_marks(tsd *key); -# endif - /* Check that all thread-local free-lists are completely marked. */ - /* also check that thread-specific-data structures are marked. */ +# endif + /* Check that all thread-local free-lists are completely marked. */ + /* also check that thread-specific-data structures are marked. */ void GC_check_tls(void) { - int i; - GC_thread p; - - for (i = 0; i < THREAD_TABLE_SZ; ++i) { - for (p = GC_threads[i]; 0 != p; p = p -> next) { - GC_check_tls_for(&(p->tlfs)); - } - } + int i; + GC_thread p; + + for (i = 0; i < THREAD_TABLE_SZ; ++i) { + for (p = GC_threads[i]; 0 != p; p = p -> next) { + GC_check_tls_for(&(p->tlfs)); + } + } # if defined(USE_CUSTOM_SPECIFIC) - if (GC_thread_key != 0) - GC_check_tsd_marks(GC_thread_key); -# endif + if (GC_thread_key != 0) + GC_check_tsd_marks(GC_thread_key); +# endif } #endif /* GC_ASSERTIONS */ @@ -284,8 +284,8 @@ STATIC void * GC_mark_thread(void * id) IF_CANCEL(int cancel_state;) DISABLE_CANCEL(cancel_state); - /* Mark threads are not cancellable; they */ - /* should be invisible to client. */ + /* Mark threads are not cancellable; they */ + /* should be invisible to client. */ marker_sp[(word)id] = GC_approx_sp(); # ifdef IA64 marker_bsp[(word)id] = GC_save_regs_in_stack(); @@ -294,28 +294,28 @@ STATIC void * GC_mark_thread(void * id) if ((word)id == (word)-1) return 0; /* to make compiler happy */ for (;; ++my_mark_no) { - /* GC_mark_no is passed only to allow GC_help_marker to terminate */ - /* promptly. This is important if it were called from the signal */ - /* handler or from the GC lock acquisition code. Under Linux, it's */ - /* not safe to call it from a signal handler, since it uses mutexes */ - /* and condition variables. Since it is called only here, the */ - /* argument is unnecessary. */ + /* GC_mark_no is passed only to allow GC_help_marker to terminate */ + /* promptly. This is important if it were called from the signal */ + /* handler or from the GC lock acquisition code. Under Linux, it's */ + /* not safe to call it from a signal handler, since it uses mutexes */ + /* and condition variables. Since it is called only here, the */ + /* argument is unnecessary. */ if (my_mark_no < GC_mark_no || my_mark_no > GC_mark_no + 2) { - /* resynchronize if we get far off, e.g. because GC_mark_no */ - /* wrapped. */ - my_mark_no = GC_mark_no; + /* resynchronize if we get far off, e.g. because GC_mark_no */ + /* wrapped. */ + my_mark_no = GC_mark_no; } # ifdef DEBUG_THREADS - GC_printf("Starting mark helper for mark number %lu\n", - (unsigned long)my_mark_no); + GC_printf("Starting mark helper for mark number %lu\n", + (unsigned long)my_mark_no); # endif GC_help_marker(my_mark_no); } } -extern long GC_markers; /* Number of mark threads we would */ - /* like to have. Includes the */ - /* initiating thread. */ +extern long GC_markers; /* Number of mark threads we would */ + /* like to have. Includes the */ + /* initiating thread. */ pthread_t GC_mark_threads[MAX_MARKERS]; @@ -327,40 +327,40 @@ static void start_mark_threads(void) pthread_attr_t attr; if (0 != pthread_attr_init(&attr)) ABORT("pthread_attr_init failed"); - + if (0 != pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED)) - ABORT("pthread_attr_setdetachstate failed"); + ABORT("pthread_attr_setdetachstate failed"); # if defined(HPUX) || defined(GC_DGUX386_THREADS) /* Default stack size is usually too small: fix it. */ - /* Otherwise marker threads or GC may run out of */ - /* space. */ + /* Otherwise marker threads or GC may run out of */ + /* space. */ # define MIN_STACK_SIZE (8*HBLKSIZE*sizeof(word)) { - size_t old_size; - int code; + size_t old_size; + int code; if (pthread_attr_getstacksize(&attr, &old_size) != 0) - ABORT("pthread_attr_getstacksize failed\n"); - if (old_size < MIN_STACK_SIZE) { - if (pthread_attr_setstacksize(&attr, MIN_STACK_SIZE) != 0) - ABORT("pthread_attr_setstacksize failed\n"); - } + ABORT("pthread_attr_getstacksize failed\n"); + if (old_size < MIN_STACK_SIZE) { + if (pthread_attr_setstacksize(&attr, MIN_STACK_SIZE) != 0) + ABORT("pthread_attr_setstacksize failed\n"); + } } # endif /* HPUX || GC_DGUX386_THREADS */ for (i = 0; i < GC_markers - 1; ++i) { if (0 != PTHREAD_CREATE(GC_mark_threads + i, &attr, - GC_mark_thread, (void *)(word)i)) { - WARN("Marker thread creation failed, errno = %" GC_PRIdPTR "\n", + GC_mark_thread, (void *)(word)i)) { + WARN("Marker thread creation failed, errno = %" GC_PRIdPTR "\n", errno); - /* Don't try to create other marker threads. */ - GC_markers = i + 1; - if (i == 0) GC_parallel = FALSE; - break; + /* Don't try to create other marker threads. */ + GC_markers = i + 1; + if (i == 0) GC_parallel = FALSE; + break; } } if (GC_print_stats) { - GC_log_printf("Started %ld mark helper threads\n", GC_markers - 1); + GC_log_printf("Started %ld mark helper threads\n", GC_markers - 1); } pthread_attr_destroy(&attr); } @@ -377,29 +377,29 @@ void GC_push_thread_structures(void) GC_push_all((ptr_t)(GC_threads), (ptr_t)(GC_threads)+sizeof(GC_threads)); # if defined(THREAD_LOCAL_ALLOC) GC_push_all((ptr_t)(&GC_thread_key), - (ptr_t)(&GC_thread_key)+sizeof(&GC_thread_key)); + (ptr_t)(&GC_thread_key)+sizeof(&GC_thread_key)); # endif } -/* It may not be safe to allocate when we register the first thread. */ +/* It may not be safe to allocate when we register the first thread. */ static struct GC_Thread_Rep first_thread; -/* Add a thread to GC_threads. We assume it wasn't already there. */ -/* Caller holds allocation lock. */ +/* Add a thread to GC_threads. We assume it wasn't already there. */ +/* Caller holds allocation lock. */ STATIC GC_thread GC_new_thread(pthread_t id) { int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ; GC_thread result; static GC_bool first_thread_used = FALSE; - + GC_ASSERT(I_HOLD_LOCK()); if (!first_thread_used) { - result = &first_thread; - first_thread_used = TRUE; + result = &first_thread; + first_thread_used = TRUE; } else { result = (struct GC_Thread_Rep *) - GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL); - if (result == 0) return(0); + GC_INTERNAL_MALLOC(sizeof(struct GC_Thread_Rep), NORMAL); + if (result == 0) return(0); } result -> id = id; result -> next = GC_threads[hv]; @@ -408,14 +408,14 @@ STATIC GC_thread GC_new_thread(pthread_t id) return(result); } -/* Delete a thread from GC_threads. We assume it is there. */ -/* (The code intentionally traps if it wasn't.) */ +/* Delete a thread from GC_threads. We assume it is there. */ +/* (The code intentionally traps if it wasn't.) */ STATIC void GC_delete_thread(pthread_t id) { int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ; register GC_thread p = GC_threads[hv]; register GC_thread prev = 0; - + GC_ASSERT(I_HOLD_LOCK()); while (!THREAD_EQUAL(p -> id, id)) { prev = p; @@ -427,15 +427,15 @@ STATIC void GC_delete_thread(pthread_t id) prev -> next = p -> next; } # ifdef GC_DARWIN_THREADS - mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread); + mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread); # endif GC_INTERNAL_FREE(p); } -/* If a thread has been joined, but we have not yet */ -/* been notified, then there may be more than one thread */ -/* in the table with the same pthread id. */ -/* This is OK, but we need a way to delete a specific one. */ +/* If a thread has been joined, but we have not yet */ +/* been notified, then there may be more than one thread */ +/* in the table with the same pthread id. */ +/* This is OK, but we need a way to delete a specific one. */ STATIC void GC_delete_gc_thread(GC_thread gc_id) { pthread_t id = gc_id -> id; @@ -454,46 +454,46 @@ STATIC void GC_delete_gc_thread(GC_thread gc_id) prev -> next = p -> next; } # ifdef GC_DARWIN_THREADS - mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread); + mach_port_deallocate(mach_task_self(), p->stop_info.mach_thread); # endif GC_INTERNAL_FREE(p); } -/* Return a GC_thread corresponding to a given pthread_t. */ -/* Returns 0 if it's not there. */ -/* Caller holds allocation lock or otherwise inhibits */ -/* updates. */ -/* If there is more than one thread with the given id we */ -/* return the most recent one. */ +/* Return a GC_thread corresponding to a given pthread_t. */ +/* Returns 0 if it's not there. */ +/* Caller holds allocation lock or otherwise inhibits */ +/* updates. */ +/* If there is more than one thread with the given id we */ +/* return the most recent one. */ GC_thread GC_lookup_thread(pthread_t id) { int hv = NUMERIC_THREAD_ID(id) % THREAD_TABLE_SZ; register GC_thread p = GC_threads[hv]; - + while (p != 0 && !THREAD_EQUAL(p -> id, id)) p = p -> next; return(p); } -/* Called by GC_finalize() (in case of an allocation failure observed). */ +/* Called by GC_finalize() (in case of an allocation failure observed). */ void GC_reset_finalizer_nested(void) { GC_thread me = GC_lookup_thread(pthread_self()); me->finalizer_nested = 0; } -/* Checks and updates the thread-local level of finalizers recursion. */ -/* Returns NULL if GC_invoke_finalizers() should not be called by the */ -/* collector (to minimize the risk of a deep finalizers recursion), */ -/* otherwise returns a pointer to the thread-local finalizer_nested. */ -/* Called by GC_notify_or_invoke_finalizers() only (the lock is held). */ +/* Checks and updates the thread-local level of finalizers recursion. */ +/* Returns NULL if GC_invoke_finalizers() should not be called by the */ +/* collector (to minimize the risk of a deep finalizers recursion), */ +/* otherwise returns a pointer to the thread-local finalizer_nested. */ +/* Called by GC_notify_or_invoke_finalizers() only (the lock is held). */ unsigned *GC_check_finalizer_nested(void) { GC_thread me = GC_lookup_thread(pthread_self()); unsigned nesting_level = me->finalizer_nested; if (nesting_level) { - /* We are inside another GC_invoke_finalizers(). */ - /* Skip some implicitly-called GC_invoke_finalizers() */ - /* depending on the nesting (recursion) level. */ + /* We are inside another GC_invoke_finalizers(). */ + /* Skip some implicitly-called GC_invoke_finalizers() */ + /* depending on the nesting (recursion) level. */ if (++me->finalizer_skipped < (1U << nesting_level)) return NULL; me->finalizer_skipped = 0; } @@ -502,10 +502,10 @@ unsigned *GC_check_finalizer_nested(void) } #ifdef HANDLE_FORK -/* Remove all entries from the GC_threads table, except the */ -/* one for the current thread. We need to do this in the child */ -/* process after a fork(), since only the current thread */ -/* survives in the child. */ +/* Remove all entries from the GC_threads table, except the */ +/* one for the current thread. We need to do this in the child */ +/* process after a fork(), since only the current thread */ +/* survives in the child. */ STATIC void GC_remove_all_threads_but_me(void) { pthread_t self = pthread_self(); @@ -515,18 +515,18 @@ STATIC void GC_remove_all_threads_but_me(void) for (hv = 0; hv < THREAD_TABLE_SZ; ++hv) { me = 0; for (p = GC_threads[hv]; 0 != p; p = next) { - next = p -> next; - if (THREAD_EQUAL(p -> id, self)) { - me = p; - p -> next = 0; - } else { -# ifdef THREAD_LOCAL_ALLOC - if (!(p -> flags & FINISHED)) { - GC_destroy_thread_local(&(p->tlfs)); - } -# endif /* THREAD_LOCAL_ALLOC */ - if (p != &first_thread) GC_INTERNAL_FREE(p); - } + next = p -> next; + if (THREAD_EQUAL(p -> id, self)) { + me = p; + p -> next = 0; + } else { +# ifdef THREAD_LOCAL_ALLOC + if (!(p -> flags & FINISHED)) { + GC_destroy_thread_local(&(p->tlfs)); + } +# endif /* THREAD_LOCAL_ALLOC */ + if (p != &first_thread) GC_INTERNAL_FREE(p); + } } GC_threads[hv] = me; } @@ -538,25 +538,25 @@ GC_bool GC_segment_is_thread_stack(ptr_t lo, ptr_t hi) { int i; GC_thread p; - + GC_ASSERT(I_HOLD_LOCK()); # ifdef PARALLEL_MARK for (i = 0; i < GC_markers - 1; ++i) { - if (marker_sp[i] > lo & marker_sp[i] < hi) return TRUE; + if (marker_sp[i] > lo & marker_sp[i] < hi) return TRUE; # ifdef IA64 - if (marker_bsp[i] > lo & marker_bsp[i] < hi) return TRUE; -# endif + if (marker_bsp[i] > lo & marker_bsp[i] < hi) return TRUE; +# endif } # endif for (i = 0; i < THREAD_TABLE_SZ; i++) { for (p = GC_threads[i]; p != 0; p = p -> next) { - if (0 != p -> stack_end) { -# ifdef STACK_GROWS_UP + if (0 != p -> stack_end) { +# ifdef STACK_GROWS_UP if (p -> stack_end >= lo && p -> stack_end < hi) return TRUE; -# else /* STACK_GROWS_DOWN */ +# else /* STACK_GROWS_DOWN */ if (p -> stack_end > lo && p -> stack_end <= hi) return TRUE; -# endif - } +# endif + } } } return FALSE; @@ -564,27 +564,27 @@ GC_bool GC_segment_is_thread_stack(ptr_t lo, ptr_t hi) #endif /* USE_PROC_FOR_LIBRARIES */ #ifdef IA64 -/* Find the largest stack_base smaller than bound. May be used */ -/* to find the boundary between a register stack and adjacent */ -/* immediately preceding memory stack. */ +/* Find the largest stack_base smaller than bound. May be used */ +/* to find the boundary between a register stack and adjacent */ +/* immediately preceding memory stack. */ ptr_t GC_greatest_stack_base_below(ptr_t bound) { int i; GC_thread p; ptr_t result = 0; - + GC_ASSERT(I_HOLD_LOCK()); # ifdef PARALLEL_MARK for (i = 0; i < GC_markers - 1; ++i) { - if (marker_sp[i] > result && marker_sp[i] < bound) - result = marker_sp[i]; + if (marker_sp[i] > result && marker_sp[i] < bound) + result = marker_sp[i]; } # endif for (i = 0; i < THREAD_TABLE_SZ; i++) { for (p = GC_threads[i]; p != 0; p = p -> next) { - if (p -> stack_end > result && p -> stack_end < bound) { - result = p -> stack_end; - } + if (p -> stack_end > result && p -> stack_end < bound) { + result = p -> stack_end; + } } } return result; @@ -592,107 +592,107 @@ ptr_t GC_greatest_stack_base_below(ptr_t bound) #endif /* IA64 */ #ifdef GC_LINUX_THREADS -/* Return the number of processors, or i<= 0 if it can't be determined. */ +/* Return the number of processors, or i<= 0 if it can't be determined. */ STATIC int GC_get_nprocs(void) { - /* Should be "return sysconf(_SC_NPROCESSORS_ONLN);" but that */ - /* appears to be buggy in many cases. */ - /* We look for lines "cpu" in /proc/stat. */ + /* Should be "return sysconf(_SC_NPROCESSORS_ONLN);" but that */ + /* appears to be buggy in many cases. */ + /* We look for lines "cpu" in /proc/stat. */ # define STAT_BUF_SIZE 4096 # define STAT_READ read - /* If read is wrapped, this may need to be redefined to call */ - /* the real one. */ + /* If read is wrapped, this may need to be redefined to call */ + /* the real one. */ char stat_buf[STAT_BUF_SIZE]; int f; word result = 1; - /* Some old kernels only have a single "cpu nnnn ..." */ - /* entry in /proc/stat. We identify those as */ - /* uniprocessors. */ + /* Some old kernels only have a single "cpu nnnn ..." */ + /* entry in /proc/stat. We identify those as */ + /* uniprocessors. */ size_t i, len = 0; f = open("/proc/stat", O_RDONLY); if (f < 0 || (len = STAT_READ(f, stat_buf, STAT_BUF_SIZE)) < 100) { - WARN("Couldn't read /proc/stat\n", 0); - return -1; + WARN("Couldn't read /proc/stat\n", 0); + return -1; } for (i = 0; i < len - 100; ++i) { if (stat_buf[i] == '\n' && stat_buf[i+1] == 'c' - && stat_buf[i+2] == 'p' && stat_buf[i+3] == 'u') { - int cpu_no = atoi(stat_buf + i + 4); - if (cpu_no >= result) result = cpu_no + 1; - } + && stat_buf[i+2] == 'p' && stat_buf[i+3] == 'u') { + int cpu_no = atoi(stat_buf + i + 4); + if (cpu_no >= result) result = cpu_no + 1; + } } close(f); return result; } #endif /* GC_LINUX_THREADS */ -/* We hold the GC lock. Wait until an in-progress GC has finished. */ -/* Repeatedly RELEASES GC LOCK in order to wait. */ -/* If wait_for_all is true, then we exit with the GC lock held and no */ -/* collection in progress; otherwise we just wait for the current GC */ -/* to finish. */ +/* We hold the GC lock. Wait until an in-progress GC has finished. */ +/* Repeatedly RELEASES GC LOCK in order to wait. */ +/* If wait_for_all is true, then we exit with the GC lock held and no */ +/* collection in progress; otherwise we just wait for the current GC */ +/* to finish. */ extern GC_bool GC_collection_in_progress(void); STATIC void GC_wait_for_gc_completion(GC_bool wait_for_all) { GC_ASSERT(I_HOLD_LOCK()); ASSERT_CANCEL_DISABLED(); if (GC_incremental && GC_collection_in_progress()) { - int old_gc_no = GC_gc_no; - - /* Make sure that no part of our stack is still on the mark stack, */ - /* since it's about to be unmapped. */ - while (GC_incremental && GC_collection_in_progress() - && (wait_for_all || old_gc_no == GC_gc_no)) { - ENTER_GC(); - GC_in_thread_creation = TRUE; + int old_gc_no = GC_gc_no; + + /* Make sure that no part of our stack is still on the mark stack, */ + /* since it's about to be unmapped. */ + while (GC_incremental && GC_collection_in_progress() + && (wait_for_all || old_gc_no == GC_gc_no)) { + ENTER_GC(); + GC_in_thread_creation = TRUE; GC_collect_a_little_inner(1); - GC_in_thread_creation = FALSE; - EXIT_GC(); - UNLOCK(); - sched_yield(); - LOCK(); - } + GC_in_thread_creation = FALSE; + EXIT_GC(); + UNLOCK(); + sched_yield(); + LOCK(); + } } } #ifdef HANDLE_FORK /* Procedures called before and after a fork. The goal here is to make */ -/* it safe to call GC_malloc() in a forked child. It's unclear that is */ -/* attainable, since the single UNIX spec seems to imply that one */ -/* should only call async-signal-safe functions, and we probably can't */ -/* quite guarantee that. But we give it our best shot. (That same */ -/* spec also implies that it's not safe to call the system malloc */ -/* between fork() and exec(). Thus we're doing no worse than it.) */ +/* it safe to call GC_malloc() in a forked child. It's unclear that is */ +/* attainable, since the single UNIX spec seems to imply that one */ +/* should only call async-signal-safe functions, and we probably can't */ +/* quite guarantee that. But we give it our best shot. (That same */ +/* spec also implies that it's not safe to call the system malloc */ +/* between fork() and exec(). Thus we're doing no worse than it.) */ IF_CANCEL(static int fork_cancel_state;) - /* protected by allocation lock. */ + /* protected by allocation lock. */ -/* Called before a fork() */ +/* Called before a fork() */ STATIC void GC_fork_prepare_proc(void) { - /* Acquire all relevant locks, so that after releasing the locks */ - /* the child will see a consistent state in which monitor */ - /* invariants hold. Unfortunately, we can't acquire libc locks */ - /* we might need, and there seems to be no guarantee that libc */ - /* must install a suitable fork handler. */ - /* Wait for an ongoing GC to finish, since we can't finish it in */ - /* the (one remaining thread in) the child. */ + /* Acquire all relevant locks, so that after releasing the locks */ + /* the child will see a consistent state in which monitor */ + /* invariants hold. Unfortunately, we can't acquire libc locks */ + /* we might need, and there seems to be no guarantee that libc */ + /* must install a suitable fork handler. */ + /* Wait for an ongoing GC to finish, since we can't finish it in */ + /* the (one remaining thread in) the child. */ LOCK(); DISABLE_CANCEL(fork_cancel_state); - /* Following waits may include cancellation points. */ + /* Following waits may include cancellation points. */ # if defined(PARALLEL_MARK) - if (GC_parallel) + if (GC_parallel) GC_wait_for_reclaim(); # endif GC_wait_for_gc_completion(TRUE); # if defined(PARALLEL_MARK) - if (GC_parallel) + if (GC_parallel) GC_acquire_mark_lock(); # endif } -/* Called in parent after a fork() */ +/* Called in parent after a fork() */ STATIC void GC_fork_parent_proc(void) { # if defined(PARALLEL_MARK) @@ -703,7 +703,7 @@ STATIC void GC_fork_parent_proc(void) UNLOCK(); } -/* Called in child after a fork() */ +/* Called in child after a fork() */ STATIC void GC_fork_child_proc(void) { /* Clean up the thread table, so that just our thread is left. */ @@ -713,8 +713,8 @@ STATIC void GC_fork_child_proc(void) # endif GC_remove_all_threads_but_me(); # ifdef PARALLEL_MARK - /* Turn off parallel marking in the child, since we are probably */ - /* just going to exec, and we would have to restart mark threads. */ + /* Turn off parallel marking in the child, since we are probably */ + /* just going to exec, and we would have to restart mark threads. */ GC_markers = 1; GC_parallel = FALSE; # endif /* PARALLEL_MARK */ @@ -733,7 +733,7 @@ STATIC int GC_get_nprocs(void) int status =0; status = dg_sys_info((long int *) &pm_sysinfo, - DG_SYS_INFO_PM_INFO_TYPE, DG_SYS_INFO_PM_CURRENT_VERSION); + DG_SYS_INFO_PM_INFO_TYPE, DG_SYS_INFO_PM_CURRENT_VERSION); if (status < 0) /* set -1 for error */ numCpus = -1; @@ -758,13 +758,13 @@ static int get_ncpu(void) sysctl(mib, sizeof(mib)/sizeof(int), &res, &len, NULL, 0); return res; } -#endif /* GC_NETBSD_THREADS */ +#endif /* GC_NETBSD_THREADS */ # if defined(GC_LINUX_THREADS) && defined(INCLUDE_LINUX_THREAD_DESCR) __thread int dummy_thread_local; # endif -/* We hold the allocation lock. */ +/* We hold the allocation lock. */ void GC_thr_init(void) { # ifndef GC_DARWIN_THREADS @@ -774,28 +774,28 @@ void GC_thr_init(void) if (GC_thr_initialized) return; GC_thr_initialized = TRUE; - + # ifdef HANDLE_FORK - /* Prepare for a possible fork. */ + /* Prepare for a possible fork. */ pthread_atfork(GC_fork_prepare_proc, GC_fork_parent_proc, - GC_fork_child_proc); + GC_fork_child_proc); # endif /* HANDLE_FORK */ # if defined(INCLUDE_LINUX_THREAD_DESCR) - /* Explicitly register the region including the address */ - /* of a thread local variable. This should include thread */ - /* locals for the main thread, except for those allocated */ - /* in response to dlopen calls. */ - { - ptr_t thread_local_addr = (ptr_t)(&dummy_thread_local); - ptr_t main_thread_start, main_thread_end; + /* Explicitly register the region including the address */ + /* of a thread local variable. This should include thread */ + /* locals for the main thread, except for those allocated */ + /* in response to dlopen calls. */ + { + ptr_t thread_local_addr = (ptr_t)(&dummy_thread_local); + ptr_t main_thread_start, main_thread_end; if (!GC_enclosing_mapping(thread_local_addr, &main_thread_start, - &main_thread_end)) { - ABORT("Failed to find mapping for main thread thread locals"); - } - GC_add_roots_inner(main_thread_start, main_thread_end, FALSE); - } + &main_thread_end)) { + ABORT("Failed to find mapping for main thread thread locals"); + } + GC_add_roots_inner(main_thread_start, main_thread_end, FALSE); + } # endif - /* Add the initial thread, so we can stop it. */ + /* Add the initial thread, so we can stop it. */ t = GC_new_thread(pthread_self()); # ifdef GC_DARWIN_THREADS t -> stop_info.mach_thread = mach_thread_self(); @@ -808,75 +808,75 @@ void GC_thr_init(void) /* Set GC_nprocs. */ { - char * nprocs_string = GETENV("GC_NPROCS"); - GC_nprocs = -1; - if (nprocs_string != NULL) GC_nprocs = atoi(nprocs_string); + char * nprocs_string = GETENV("GC_NPROCS"); + GC_nprocs = -1; + if (nprocs_string != NULL) GC_nprocs = atoi(nprocs_string); } if (GC_nprocs <= 0) { # if defined(GC_HPUX_THREADS) - GC_nprocs = pthread_num_processors_np(); + GC_nprocs = pthread_num_processors_np(); +# endif +# if defined(GC_OSF1_THREADS) || defined(GC_AIX_THREADS) \ + || defined(GC_SOLARIS_THREADS) || defined(GC_GNU_THREADS) + GC_nprocs = sysconf(_SC_NPROCESSORS_ONLN); + if (GC_nprocs <= 0) GC_nprocs = 1; # endif -# if defined(GC_OSF1_THREADS) || defined(GC_AIX_THREADS) \ - || defined(GC_SOLARIS_THREADS) || defined(GC_GNU_THREADS) - GC_nprocs = sysconf(_SC_NPROCESSORS_ONLN); - if (GC_nprocs <= 0) GC_nprocs = 1; -# endif # if defined(GC_IRIX_THREADS) - GC_nprocs = sysconf(_SC_NPROC_ONLN); - if (GC_nprocs <= 0) GC_nprocs = 1; + GC_nprocs = sysconf(_SC_NPROC_ONLN); + if (GC_nprocs <= 0) GC_nprocs = 1; # endif # if defined(GC_NETBSD_THREADS) - GC_nprocs = get_ncpu(); + GC_nprocs = get_ncpu(); # endif # if defined(GC_DARWIN_THREADS) || defined(GC_FREEBSD_THREADS) - int ncpus = 1; - size_t len = sizeof(ncpus); - sysctl((int[2]) {CTL_HW, HW_NCPU}, 2, &ncpus, &len, NULL, 0); - GC_nprocs = ncpus; + int ncpus = 1; + size_t len = sizeof(ncpus); + sysctl((int[2]) {CTL_HW, HW_NCPU}, 2, &ncpus, &len, NULL, 0); + GC_nprocs = ncpus; # endif -# if defined(GC_LINUX_THREADS) || defined(GC_DGUX386_THREADS) +# if defined(GC_LINUX_THREADS) || defined(GC_DGUX386_THREADS) GC_nprocs = GC_get_nprocs(); -# endif +# endif } if (GC_nprocs <= 0) { - WARN("GC_get_nprocs() returned %" GC_PRIdPTR "\n", GC_nprocs); - GC_nprocs = 2; -# ifdef PARALLEL_MARK - GC_markers = 1; -# endif + WARN("GC_get_nprocs() returned %" GC_PRIdPTR "\n", GC_nprocs); + GC_nprocs = 2; +# ifdef PARALLEL_MARK + GC_markers = 1; +# endif } else { -# ifdef PARALLEL_MARK +# ifdef PARALLEL_MARK { - char * markers_string = GETENV("GC_MARKERS"); - if (markers_string != NULL) { - GC_markers = atoi(markers_string); - if (GC_markers > MAX_MARKERS) { - WARN("Limiting number of mark threads\n", 0); - GC_markers = MAX_MARKERS; - } - } else { - GC_markers = GC_nprocs; - if (GC_markers >= MAX_MARKERS) - GC_markers = MAX_MARKERS; /* silently limit GC_markers value */ - } + char * markers_string = GETENV("GC_MARKERS"); + if (markers_string != NULL) { + GC_markers = atoi(markers_string); + if (GC_markers > MAX_MARKERS) { + WARN("Limiting number of mark threads\n", 0); + GC_markers = MAX_MARKERS; + } + } else { + GC_markers = GC_nprocs; + if (GC_markers >= MAX_MARKERS) + GC_markers = MAX_MARKERS; /* silently limit GC_markers value */ + } } -# endif +# endif } # ifdef PARALLEL_MARK if (GC_print_stats) { GC_log_printf("Number of processors = %ld, " - "number of marker threads = %ld\n", GC_nprocs, GC_markers); + "number of marker threads = %ld\n", GC_nprocs, GC_markers); } if (GC_markers <= 1) { - GC_parallel = FALSE; - if (GC_print_stats) { - GC_log_printf( - "Single marker thread, turning off parallel marking\n"); - } + GC_parallel = FALSE; + if (GC_print_stats) { + GC_log_printf( + "Single marker thread, turning off parallel marking\n"); + } } else { - GC_parallel = TRUE; - /* Disable true incremental collection, but generational is OK. */ - GC_time_limit = GC_TIME_UNLIMITED; + GC_parallel = TRUE; + /* Disable true incremental collection, but generational is OK. */ + GC_time_limit = GC_TIME_UNLIMITED; } /* If we are using a parallel marker, actually start helper threads. */ if (GC_parallel) start_mark_threads(); @@ -884,19 +884,19 @@ void GC_thr_init(void) } -/* Perform all initializations, including those that */ -/* may require allocation. */ -/* Called without allocation lock. */ -/* Must be called before a second thread is created. */ -/* Did we say it's called without the allocation lock? */ +/* Perform all initializations, including those that */ +/* may require allocation. */ +/* Called without allocation lock. */ +/* Must be called before a second thread is created. */ +/* Did we say it's called without the allocation lock? */ void GC_init_parallel(void) { if (parallel_initialized) return; parallel_initialized = TRUE; - /* GC_init() calls us back, so set flag first. */ + /* GC_init() calls us back, so set flag first. */ if (!GC_is_initialized) GC_init(); - /* Initialize thread local free lists if used. */ + /* Initialize thread local free lists if used. */ # if defined(THREAD_LOCAL_ALLOC) LOCK(); GC_init_thread_local(&(GC_lookup_thread(pthread_self())->tlfs)); @@ -907,10 +907,10 @@ void GC_init_parallel(void) #if !defined(GC_DARWIN_THREADS) GC_API int WRAP_FUNC(pthread_sigmask)(int how, const sigset_t *set, - sigset_t *oset) + sigset_t *oset) { sigset_t fudged_set; - + INIT_REAL_SYMS(); if (set != NULL && (how == SIG_BLOCK || how == SIG_SETMASK)) { fudged_set = *set; @@ -921,8 +921,8 @@ GC_API int WRAP_FUNC(pthread_sigmask)(int how, const sigset_t *set, } #endif /* !GC_DARWIN_THREADS */ -/* Wrapper for functions that are likely to block for an appreciable */ -/* length of time. */ +/* Wrapper for functions that are likely to block for an appreciable */ +/* length of time. */ /*ARGSUSED*/ void GC_do_blocking_inner(ptr_t data, void * context) { @@ -932,74 +932,74 @@ void GC_do_blocking_inner(ptr_t data, void * context) { me = GC_lookup_thread(pthread_self()); GC_ASSERT(!(me -> thread_blocked)); # ifdef SPARC - me -> stop_info.stack_ptr = GC_save_regs_in_stack(); + me -> stop_info.stack_ptr = GC_save_regs_in_stack(); # elif !defined(GC_DARWIN_THREADS) - me -> stop_info.stack_ptr = GC_approx_sp(); + me -> stop_info.stack_ptr = GC_approx_sp(); # endif # ifdef IA64 - me -> backing_store_ptr = GC_save_regs_in_stack(); + me -> backing_store_ptr = GC_save_regs_in_stack(); # endif me -> thread_blocked = TRUE; /* Save context here if we want to support precise stack marking */ UNLOCK(); d -> client_data = (d -> fn)(d -> client_data); - LOCK(); /* This will block if the world is stopped. */ + LOCK(); /* This will block if the world is stopped. */ me -> thread_blocked = FALSE; UNLOCK(); } -/* GC_call_with_gc_active() has the opposite to GC_do_blocking() */ -/* functionality. It might be called from a user function invoked by */ -/* GC_do_blocking() to temporarily back allow calling any GC function */ -/* and/or manipulating pointers to the garbage collected heap. */ +/* GC_call_with_gc_active() has the opposite to GC_do_blocking() */ +/* functionality. It might be called from a user function invoked by */ +/* GC_do_blocking() to temporarily back allow calling any GC function */ +/* and/or manipulating pointers to the garbage collected heap. */ GC_API void * GC_CALL GC_call_with_gc_active(GC_fn_type fn, - void * client_data) { + void * client_data) { struct GC_activation_frame_s frame; GC_thread me; - LOCK(); /* This will block if the world is stopped. */ + LOCK(); /* This will block if the world is stopped. */ me = GC_lookup_thread(pthread_self()); - /* Adjust our stack base value (this could happen unless */ - /* GC_get_stack_base() was used which returned GC_SUCCESS). */ + /* Adjust our stack base value (this could happen unless */ + /* GC_get_stack_base() was used which returned GC_SUCCESS). */ if ((me -> flags & MAIN_THREAD) == 0) { GC_ASSERT(me -> stack_end != NULL); if (me -> stack_end HOTTER_THAN (ptr_t)(&frame)) - me -> stack_end = (ptr_t)(&frame); + me -> stack_end = (ptr_t)(&frame); } else { /* The original stack. */ if (GC_stackbottom HOTTER_THAN (ptr_t)(&frame)) - GC_stackbottom = (ptr_t)(&frame); + GC_stackbottom = (ptr_t)(&frame); } if (me -> thread_blocked == FALSE) { - /* We are not inside GC_do_blocking() - do nothing more. */ + /* We are not inside GC_do_blocking() - do nothing more. */ UNLOCK(); return fn(client_data); } - /* Setup new "frame". */ + /* Setup new "frame". */ # ifdef GC_DARWIN_THREADS /* FIXME: Implement it for Darwin ("frames" are ignored at present). */ # else frame.saved_stack_ptr = me -> stop_info.stack_ptr; # endif # ifdef IA64 - /* This is the same as in GC_call_with_stack_base(). */ + /* This is the same as in GC_call_with_stack_base(). */ frame.backing_store_end = GC_save_regs_in_stack(); - /* Unnecessarily flushes register stack, */ - /* but that probably doesn't hurt. */ + /* Unnecessarily flushes register stack, */ + /* but that probably doesn't hurt. */ frame.saved_backing_store_ptr = me -> backing_store_ptr; # endif frame.prev = me -> activation_frame; me -> thread_blocked = FALSE; me -> activation_frame = &frame; - + UNLOCK(); client_data = fn(client_data); GC_ASSERT(me -> thread_blocked == FALSE); GC_ASSERT(me -> activation_frame == &frame); - /* Restore original "frame". */ + /* Restore original "frame". */ LOCK(); me -> activation_frame = frame.prev; # ifdef IA64 @@ -1018,8 +1018,8 @@ struct start_info { void *(*start_routine)(void *); void *arg; word flags; - sem_t registered; /* 1 ==> in our thread table, but */ - /* parent hasn't yet noticed. */ + sem_t registered; /* 1 ==> in our thread table, but */ + /* parent hasn't yet noticed. */ }; GC_API int GC_CALL GC_unregister_my_thread(void) @@ -1029,17 +1029,17 @@ GC_API int GC_CALL GC_unregister_my_thread(void) LOCK(); DISABLE_CANCEL(cancel_state); - /* Wait for any GC that may be marking from our stack to */ - /* complete before we remove this thread. */ + /* Wait for any GC that may be marking from our stack to */ + /* complete before we remove this thread. */ GC_wait_for_gc_completion(FALSE); me = GC_lookup_thread(pthread_self()); # if defined(THREAD_LOCAL_ALLOC) GC_destroy_thread_local(&(me->tlfs)); # endif if (me -> flags & DETACHED) { - GC_delete_thread(pthread_self()); + GC_delete_thread(pthread_self()); } else { - me -> flags |= FINISHED; + me -> flags |= FINISHED; } # if defined(THREAD_LOCAL_ALLOC) GC_remove_specific(GC_thread_key); @@ -1049,11 +1049,11 @@ GC_API int GC_CALL GC_unregister_my_thread(void) return GC_SUCCESS; } -/* Called at thread exit. */ -/* Never called for main thread. That's OK, since it */ -/* results in at most a tiny one-time leak. And */ -/* linuxthreads doesn't reclaim the main threads */ -/* resources or id anyway. */ +/* Called at thread exit. */ +/* Never called for main thread. That's OK, since it */ +/* results in at most a tiny one-time leak. And */ +/* linuxthreads doesn't reclaim the main threads */ +/* resources or id anyway. */ STATIC void GC_thread_exit_proc(void *arg) { GC_unregister_my_thread(); @@ -1063,12 +1063,12 @@ GC_API int WRAP_FUNC(pthread_join)(pthread_t thread, void **retval) { int result; GC_thread thread_gc_id; - + INIT_REAL_SYMS(); LOCK(); thread_gc_id = GC_lookup_thread(thread); - /* This is guaranteed to be the intended one, since the thread id */ - /* cant have been recycled by pthreads. */ + /* This is guaranteed to be the intended one, since the thread id */ + /* cant have been recycled by pthreads. */ UNLOCK(); result = REAL_FUNC(pthread_join)(thread, retval); # if defined (GC_FREEBSD_THREADS) @@ -1095,7 +1095,7 @@ GC_API int WRAP_FUNC(pthread_detach)(pthread_t thread) { int result; GC_thread thread_gc_id; - + INIT_REAL_SYMS(); LOCK(); thread_gc_id = GC_lookup_thread(thread); @@ -1116,7 +1116,7 @@ GC_API int WRAP_FUNC(pthread_detach)(pthread_t thread) GC_bool GC_in_thread_creation = FALSE; /* Protected by allocation lock. */ STATIC GC_thread GC_register_my_thread_inner(const struct GC_stack_base *sb, - pthread_t my_pthread) + pthread_t my_pthread) { GC_thread me; @@ -1153,28 +1153,28 @@ GC_API int GC_CALL GC_register_my_thread(const struct GC_stack_base *sb) GC_thread me; if (GC_need_to_lock == FALSE) - ABORT("Threads explicit registering is not previously enabled"); + ABORT("Threads explicit registering is not previously enabled"); LOCK(); me = GC_lookup_thread(my_pthread); if (0 == me) { me = GC_register_my_thread_inner(sb, my_pthread); - me -> flags |= DETACHED; - /* Treat as detached, since we do not need to worry about */ - /* pointer results. */ + me -> flags |= DETACHED; + /* Treat as detached, since we do not need to worry about */ + /* pointer results. */ # if defined(THREAD_LOCAL_ALLOC) GC_init_thread_local(&(me->tlfs)); # endif - UNLOCK(); + UNLOCK(); return GC_SUCCESS; } else { - UNLOCK(); - return GC_DUPLICATE; + UNLOCK(); + return GC_DUPLICATE; } } STATIC void * GC_CALLBACK GC_inner_start_routine(struct GC_stack_base *sb, - void * arg) + void * arg) { struct start_info * si = arg; void * result; @@ -1198,11 +1198,11 @@ STATIC void * GC_CALLBACK GC_inner_start_routine(struct GC_stack_base *sb, UNLOCK(); start = si -> start_routine; # ifdef DEBUG_THREADS - GC_printf("start_routine = %p\n", (void *)(signed_word)start); + GC_printf("start_routine = %p\n", (void *)(signed_word)start); # endif start_arg = si -> arg; - sem_post(&(si -> registered)); /* Last action on si. */ - /* OK to deallocate. */ + sem_post(&(si -> registered)); /* Last action on si. */ + /* OK to deallocate. */ pthread_cleanup_push(GC_thread_exit_proc, 0); result = (*start)(start_arg); # if DEBUG_THREADS @@ -1210,9 +1210,9 @@ STATIC void * GC_CALLBACK GC_inner_start_routine(struct GC_stack_base *sb, # endif me -> status = result; pthread_cleanup_pop(1); - /* Cleanup acquires lock, ensuring that we can't exit */ + /* Cleanup acquires lock, ensuring that we can't exit */ /* while a collection that thinks we're alive is trying to stop */ - /* us. */ + /* us. */ return(result); } @@ -1222,14 +1222,14 @@ STATIC void * GC_start_routine(void * arg) struct GC_stack_base sb; # ifdef REDIRECT_MALLOC - /* GC_get_stack_base may call pthread_getattr_np, which can */ - /* unfortunately call realloc, which may allocate from an */ - /* unregistered thread. This is unpleasant, since it might */ - /* force heap growth. */ + /* GC_get_stack_base may call pthread_getattr_np, which can */ + /* unfortunately call realloc, which may allocate from an */ + /* unregistered thread. This is unpleasant, since it might */ + /* force heap growth. */ GC_disable(); # endif if (GC_get_stack_base(&sb) != GC_SUCCESS) - ABORT("Failed to get thread stack base."); + ABORT("Failed to get thread stack base."); # ifdef REDIRECT_MALLOC GC_enable(); # endif @@ -1240,29 +1240,29 @@ STATIC void * GC_start_routine(void * arg) } GC_API int WRAP_FUNC(pthread_create)(pthread_t *new_thread, - const pthread_attr_t *attr, + const pthread_attr_t *attr, void *(*start_routine)(void *), void *arg) { int result; int detachstate; word my_flags = 0; - struct start_info * si; - /* This is otherwise saved only in an area mmapped by the thread */ - /* library, which isn't visible to the collector. */ - - /* We resist the temptation to muck with the stack size here, */ - /* even if the default is unreasonably small. That's the client's */ - /* responsibility. */ + struct start_info * si; + /* This is otherwise saved only in an area mmapped by the thread */ + /* library, which isn't visible to the collector. */ + + /* We resist the temptation to muck with the stack size here, */ + /* even if the default is unreasonably small. That's the client's */ + /* responsibility. */ INIT_REAL_SYMS(); LOCK(); si = (struct start_info *)GC_INTERNAL_MALLOC(sizeof(struct start_info), - NORMAL); + NORMAL); UNLOCK(); if (!parallel_initialized) GC_init_parallel(); if (0 == si && (si = (struct start_info *) - (*GC_get_oom_fn())(sizeof(struct start_info))) == 0) + (*GC_get_oom_fn())(sizeof(struct start_info))) == 0) return(ENOMEM); sem_init(&(si -> registered), 0, 0); si -> start_routine = start_routine; @@ -1271,38 +1271,38 @@ GC_API int WRAP_FUNC(pthread_create)(pthread_t *new_thread, if (!GC_thr_initialized) GC_thr_init(); # ifdef GC_ASSERTIONS { - size_t stack_size = 0; - if (NULL != attr) { - pthread_attr_getstacksize(attr, &stack_size); - } - if (0 == stack_size) { - pthread_attr_t my_attr; - pthread_attr_init(&my_attr); - pthread_attr_getstacksize(&my_attr, &stack_size); - } - /* On Solaris 10, with default attr initialization, */ - /* stack_size remains 0. Fudge it. */ - if (0 == stack_size) { -# ifndef SOLARIS - WARN("Failed to get stack size for assertion checking\n", 0); -# endif - stack_size = 1000000; - } + size_t stack_size = 0; + if (NULL != attr) { + pthread_attr_getstacksize(attr, &stack_size); + } + if (0 == stack_size) { + pthread_attr_t my_attr; + pthread_attr_init(&my_attr); + pthread_attr_getstacksize(&my_attr, &stack_size); + } + /* On Solaris 10, with default attr initialization, */ + /* stack_size remains 0. Fudge it. */ + if (0 == stack_size) { +# ifndef SOLARIS + WARN("Failed to get stack size for assertion checking\n", 0); +# endif + stack_size = 1000000; + } # ifdef PARALLEL_MARK - GC_ASSERT(stack_size >= (8*HBLKSIZE*sizeof(word))); + GC_ASSERT(stack_size >= (8*HBLKSIZE*sizeof(word))); # else - /* FreeBSD-5.3/Alpha: default pthread stack is 64K, */ - /* HBLKSIZE=8192, sizeof(word)=8 */ - GC_ASSERT(stack_size >= 65536); + /* FreeBSD-5.3/Alpha: default pthread stack is 64K, */ + /* HBLKSIZE=8192, sizeof(word)=8 */ + GC_ASSERT(stack_size >= 65536); # endif - /* Our threads may need to do some work for the GC. */ - /* Ridiculously small threads won't work, and they */ - /* probably wouldn't work anyway. */ + /* Our threads may need to do some work for the GC. */ + /* Ridiculously small threads won't work, and they */ + /* probably wouldn't work anyway. */ } # endif if (NULL == attr) { - detachstate = PTHREAD_CREATE_JOINABLE; - } else { + detachstate = PTHREAD_CREATE_JOINABLE; + } else { pthread_attr_getdetachstate(attr, &detachstate); } if (PTHREAD_CREATE_DETACHED == detachstate) my_flags |= DETACHED; @@ -1310,7 +1310,7 @@ GC_API int WRAP_FUNC(pthread_create)(pthread_t *new_thread, UNLOCK(); # ifdef DEBUG_THREADS GC_printf("About to start new thread from thread 0x%x\n", - (unsigned)pthread_self()); + (unsigned)pthread_self()); # endif GC_need_to_lock = TRUE; @@ -1319,18 +1319,18 @@ GC_API int WRAP_FUNC(pthread_create)(pthread_t *new_thread, # ifdef DEBUG_THREADS GC_printf("Started thread 0x%x\n", (unsigned)(*new_thread)); # endif - /* Wait until child has been added to the thread table. */ - /* This also ensures that we hold onto si until the child is done */ - /* with it. Thus it doesn't matter whether it is otherwise */ - /* visible to the collector. */ + /* Wait until child has been added to the thread table. */ + /* This also ensures that we hold onto si until the child is done */ + /* with it. Thus it doesn't matter whether it is otherwise */ + /* visible to the collector. */ if (0 == result) { IF_CANCEL(int cancel_state;) - DISABLE_CANCEL(cancel_state); - /* pthread_create is not a cancellation point. */ - while (0 != sem_wait(&(si -> registered))) { + DISABLE_CANCEL(cancel_state); + /* pthread_create is not a cancellation point. */ + while (0 != sem_wait(&(si -> registered))) { if (EINTR != errno) ABORT("sem_wait failed"); - } - RESTORE_CANCEL(cancel_state); + } + RESTORE_CANCEL(cancel_state); } sem_destroy(&(si -> registered)); LOCK(); @@ -1341,8 +1341,8 @@ GC_API int WRAP_FUNC(pthread_create)(pthread_t *new_thread, } #if defined(USE_SPIN_LOCK) || !defined(NO_PTHREAD_TRYLOCK) -/* Spend a few cycles in a way that can't introduce contention with */ -/* other threads. */ +/* Spend a few cycles in a way that can't introduce contention with */ +/* other threads. */ STATIC void GC_pause(void) { int i; @@ -1350,42 +1350,42 @@ STATIC void GC_pause(void) volatile word dummy = 0; # endif - for (i = 0; i < 10; ++i) { + for (i = 0; i < 10; ++i) { # if defined(__GNUC__) && !defined(__INTEL_COMPILER) __asm__ __volatile__ (" " : : : "memory"); # else - /* Something that's unlikely to be optimized away. */ - GC_noop(++dummy); + /* Something that's unlikely to be optimized away. */ + GC_noop(++dummy); # endif } } #endif - -#define SPIN_MAX 128 /* Maximum number of calls to GC_pause before */ - /* give up. */ + +#define SPIN_MAX 128 /* Maximum number of calls to GC_pause before */ + /* give up. */ volatile GC_bool GC_collecting = 0; - /* A hint that we're in the collector and */ + /* A hint that we're in the collector and */ /* holding the allocation lock for an */ /* extended period. */ #if (!defined(USE_SPIN_LOCK) && !defined(NO_PTHREAD_TRYLOCK)) \ - || defined(PARALLEL_MARK) -/* If we don't want to use the below spinlock implementation, either */ -/* because we don't have a GC_test_and_set implementation, or because */ -/* we don't want to risk sleeping, we can still try spinning on */ -/* pthread_mutex_trylock for a while. This appears to be very */ -/* beneficial in many cases. */ -/* I suspect that under high contention this is nearly always better */ -/* than the spin lock. But it's a bit slower on a uniprocessor. */ -/* Hence we still default to the spin lock. */ -/* This is also used to acquire the mark lock for the parallel */ -/* marker. */ - -/* Here we use a strict exponential backoff scheme. I don't know */ -/* whether that's better or worse than the above. We eventually */ -/* yield by calling pthread_mutex_lock(); it never makes sense to */ -/* explicitly sleep. */ + || defined(PARALLEL_MARK) +/* If we don't want to use the below spinlock implementation, either */ +/* because we don't have a GC_test_and_set implementation, or because */ +/* we don't want to risk sleeping, we can still try spinning on */ +/* pthread_mutex_trylock for a while. This appears to be very */ +/* beneficial in many cases. */ +/* I suspect that under high contention this is nearly always better */ +/* than the spin lock. But it's a bit slower on a uniprocessor. */ +/* Hence we still default to the spin lock. */ +/* This is also used to acquire the mark lock for the parallel */ +/* marker. */ + +/* Here we use a strict exponential backoff scheme. I don't know */ +/* whether that's better or worse than the above. We eventually */ +/* yield by calling pthread_mutex_lock(); it never makes sense to */ +/* explicitly sleep. */ /* #define LOCK_STATS */ #ifdef LOCK_STATS @@ -1399,32 +1399,32 @@ STATIC void GC_generic_lock(pthread_mutex_t * lock) #ifndef NO_PTHREAD_TRYLOCK unsigned pause_length = 1; unsigned i; - + if (0 == pthread_mutex_trylock(lock)) { # ifdef LOCK_STATS - (void)AO_fetch_and_add1(&GC_unlocked_count); + (void)AO_fetch_and_add1(&GC_unlocked_count); # endif - return; + return; } for (; pause_length <= SPIN_MAX; pause_length <<= 1) { - for (i = 0; i < pause_length; ++i) { - GC_pause(); - } + for (i = 0; i < pause_length; ++i) { + GC_pause(); + } switch(pthread_mutex_trylock(lock)) { - case 0: -# ifdef LOCK_STATS - (void)AO_fetch_and_add1(&GC_spin_count); -# endif - return; - case EBUSY: - break; - default: - ABORT("Unexpected error from pthread_mutex_trylock"); + case 0: +# ifdef LOCK_STATS + (void)AO_fetch_and_add1(&GC_spin_count); +# endif + return; + case EBUSY: + break; + default: + ABORT("Unexpected error from pthread_mutex_trylock"); } } #endif /* !NO_PTHREAD_TRYLOCK */ # ifdef LOCK_STATS - (void)AO_fetch_and_add1(&GC_block_count); + (void)AO_fetch_and_add1(&GC_block_count); # endif pthread_mutex_lock(lock); } @@ -1462,12 +1462,12 @@ void GC_lock(void) continue; } if (AO_test_and_set_acquire(&GC_allocate_lock) == AO_TS_CLEAR) { - /* + /* * got it! * Spinning worked. Thus we're probably not being scheduled * against the other process with which we were contending. * Thus it makes sense to spin longer the next time. - */ + */ last_spins = i; spin_max = high_spin_max; return; @@ -1481,24 +1481,24 @@ yield: return; } # define SLEEP_THRESHOLD 12 - /* Under Linux very short sleeps tend to wait until */ - /* the current time quantum expires. On old Linux */ - /* kernels nanosleep(<= 2ms) just spins under Linux. */ - /* (Under 2.4, this happens only for real-time */ - /* processes.) We want to minimize both behaviors */ - /* here. */ + /* Under Linux very short sleeps tend to wait until */ + /* the current time quantum expires. On old Linux */ + /* kernels nanosleep(<= 2ms) just spins under Linux. */ + /* (Under 2.4, this happens only for real-time */ + /* processes.) We want to minimize both behaviors */ + /* here. */ if (i < SLEEP_THRESHOLD) { sched_yield(); - } else { - struct timespec ts; - - if (i > 24) i = 24; - /* Don't wait for more than about 15msecs, even */ - /* under extreme contention. */ - ts.tv_sec = 0; - ts.tv_nsec = 1 << i; - nanosleep(&ts, 0); - } + } else { + struct timespec ts; + + if (i > 24) i = 24; + /* Don't wait for more than about 15msecs, even */ + /* under extreme contention. */ + ts.tv_sec = 0; + ts.tv_nsec = 1 << i; + nanosleep(&ts, 0); + } } } @@ -1507,7 +1507,7 @@ void GC_lock(void) { #ifndef NO_PTHREAD_TRYLOCK if (1 == GC_nprocs || GC_collecting) { - pthread_mutex_lock(&GC_allocate_ml); + pthread_mutex_lock(&GC_allocate_ml); } else { GC_generic_lock(&GC_allocate_ml); } @@ -1544,12 +1544,12 @@ void GC_acquire_mark_lock(void) { /* if (pthread_mutex_lock(&mark_mutex) != 0) { - ABORT("pthread_mutex_lock failed"); + ABORT("pthread_mutex_lock failed"); } */ GC_generic_lock(&mark_mutex); # ifdef GC_ASSERTIONS - GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self()); + GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self()); # endif } @@ -1557,31 +1557,31 @@ void GC_release_mark_lock(void) { GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self())); # ifdef GC_ASSERTIONS - GC_mark_lock_holder = NO_THREAD; + GC_mark_lock_holder = NO_THREAD; # endif if (pthread_mutex_unlock(&mark_mutex) != 0) { - ABORT("pthread_mutex_unlock failed"); + ABORT("pthread_mutex_unlock failed"); } } -/* Collector must wait for a freelist builders for 2 reasons: */ -/* 1) Mark bits may still be getting examined without lock. */ -/* 2) Partial free lists referenced only by locals may not be scanned */ -/* correctly, e.g. if they contain "pointer-free" objects, since the */ -/* free-list link may be ignored. */ +/* Collector must wait for a freelist builders for 2 reasons: */ +/* 1) Mark bits may still be getting examined without lock. */ +/* 2) Partial free lists referenced only by locals may not be scanned */ +/* correctly, e.g. if they contain "pointer-free" objects, since the */ +/* free-list link may be ignored. */ STATIC void GC_wait_builder(void) { GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self())); ASSERT_CANCEL_DISABLED(); # ifdef GC_ASSERTIONS - GC_mark_lock_holder = NO_THREAD; + GC_mark_lock_holder = NO_THREAD; # endif if (pthread_cond_wait(&builder_cv, &mark_mutex) != 0) { - ABORT("pthread_cond_wait failed"); + ABORT("pthread_cond_wait failed"); } GC_ASSERT(GC_mark_lock_holder == NO_THREAD); # ifdef GC_ASSERTIONS - GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self()); + GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self()); # endif } @@ -1589,7 +1589,7 @@ void GC_wait_for_reclaim(void) { GC_acquire_mark_lock(); while (GC_fl_builder_count > 0) { - GC_wait_builder(); + GC_wait_builder(); } GC_release_mark_lock(); } @@ -1598,7 +1598,7 @@ void GC_notify_all_builder(void) { GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self())); if (pthread_cond_broadcast(&builder_cv) != 0) { - ABORT("pthread_cond_broadcast failed"); + ABORT("pthread_cond_broadcast failed"); } } @@ -1609,25 +1609,24 @@ void GC_wait_marker(void) GC_ASSERT(GC_mark_lock_holder == NUMERIC_THREAD_ID(pthread_self())); ASSERT_CANCEL_DISABLED(); # ifdef GC_ASSERTIONS - GC_mark_lock_holder = NO_THREAD; + GC_mark_lock_holder = NO_THREAD; # endif if (pthread_cond_wait(&mark_cv, &mark_mutex) != 0) { - ABORT("pthread_cond_wait failed"); + ABORT("pthread_cond_wait failed"); } GC_ASSERT(GC_mark_lock_holder == NO_THREAD); # ifdef GC_ASSERTIONS - GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self()); + GC_mark_lock_holder = NUMERIC_THREAD_ID(pthread_self()); # endif } void GC_notify_all_marker(void) { if (pthread_cond_broadcast(&mark_cv) != 0) { - ABORT("pthread_cond_broadcast failed"); + ABORT("pthread_cond_broadcast failed"); } } #endif /* PARALLEL_MARK */ # endif /* GC_LINUX_THREADS and friends */ - -- 2.7.4