Initial revision

From-SVN: r42370
This commit is contained in:
Bryce McKinlay 2001-05-21 07:39:23 +01:00
parent 9d2f2c45d8
commit f54d42879f
41 changed files with 7939 additions and 0 deletions

623
boehm-gc/AmigaOS.c Normal file
View File

@ -0,0 +1,623 @@
/******************************************************************
AmigaOS-spesific routines for GC.
This file is normally included from os_dep.c
******************************************************************/
#if !defined(GC_AMIGA_DEF) && !defined(GC_AMIGA_SB) && !defined(GC_AMIGA_DS) && !defined(GC_AMIGA_AM)
# include "gc_priv.h"
# include <stdio.h>
# include <signal.h>
# define GC_AMIGA_DEF
# define GC_AMIGA_SB
# define GC_AMIGA_DS
# define GC_AMIGA_AM
#endif
#ifdef GC_AMIGA_DEF
# ifndef __GNUC__
# include <exec/exec.h>
# endif
# include <proto/exec.h>
# include <proto/dos.h>
# include <dos/dosextens.h>
# include <workbench/startup.h>
#endif
#ifdef GC_AMIGA_SB
/******************************************************************
Find the base of the stack.
******************************************************************/
ptr_t GC_get_stack_base()
{
struct Process *proc = (struct Process*)SysBase->ThisTask;
/* Reference: Amiga Guru Book Pages: 42,567,574 */
if (proc->pr_Task.tc_Node.ln_Type==NT_PROCESS
&& proc->pr_CLI != NULL) {
/* first ULONG is StackSize */
/*longPtr = proc->pr_ReturnAddr;
size = longPtr[0];*/
return (char *)proc->pr_ReturnAddr + sizeof(ULONG);
} else {
return (char *)proc->pr_Task.tc_SPUpper;
}
}
#if 0 /* old version */
ptr_t GC_get_stack_base()
{
extern struct WBStartup *_WBenchMsg;
extern long __base;
extern long __stack;
struct Task *task;
struct Process *proc;
struct CommandLineInterface *cli;
long size;
if ((task = FindTask(0)) == 0) {
GC_err_puts("Cannot find own task structure\n");
ABORT("task missing");
}
proc = (struct Process *)task;
cli = BADDR(proc->pr_CLI);
if (_WBenchMsg != 0 || cli == 0) {
size = (char *)task->tc_SPUpper - (char *)task->tc_SPLower;
} else {
size = cli->cli_DefaultStack * 4;
}
return (ptr_t)(__base + GC_max(size, __stack));
}
#endif
#endif
#ifdef GC_AMIGA_DS
/******************************************************************
Register data segments.
******************************************************************/
void GC_register_data_segments()
{
struct Process *proc;
struct CommandLineInterface *cli;
BPTR myseglist;
ULONG *data;
int num;
# ifdef __GNUC__
ULONG dataSegSize;
GC_bool found_segment = FALSE;
extern char __data_size[];
dataSegSize=__data_size+8;
/* Can`t find the Location of __data_size, because
it`s possible that is it, inside the segment. */
# endif
proc= (struct Process*)SysBase->ThisTask;
/* Reference: Amiga Guru Book Pages: 538ff,565,573
and XOper.asm */
if (proc->pr_Task.tc_Node.ln_Type==NT_PROCESS) {
if (proc->pr_CLI == NULL) {
myseglist = proc->pr_SegList;
} else {
/* ProcLoaded 'Loaded as a command: '*/
cli = BADDR(proc->pr_CLI);
myseglist = cli->cli_Module;
}
} else {
ABORT("Not a Process.");
}
if (myseglist == NULL) {
ABORT("Arrrgh.. can't find segments, aborting");
}
/* xoper hunks Shell Process */
num=0;
for (data = (ULONG *)BADDR(myseglist); data != NULL;
data = (ULONG *)BADDR(data[0])) {
if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
# ifdef __GNUC__
if (dataSegSize == data[-1]) {
found_segment = TRUE;
}
# endif
GC_add_roots_inner((char *)&data[1],
((char *)&data[1]) + data[-1], FALSE);
}
++num;
} /* for */
# ifdef __GNUC__
if (!found_segment) {
ABORT("Can`t find correct Segments.\nSolution: Use an newer version of ixemul.library");
}
# endif
}
#if 0 /* old version */
void GC_register_data_segments()
{
extern struct WBStartup *_WBenchMsg;
struct Process *proc;
struct CommandLineInterface *cli;
BPTR myseglist;
ULONG *data;
if ( _WBenchMsg != 0 ) {
if ((myseglist = _WBenchMsg->sm_Segment) == 0) {
GC_err_puts("No seglist from workbench\n");
return;
}
} else {
if ((proc = (struct Process *)FindTask(0)) == 0) {
GC_err_puts("Cannot find process structure\n");
return;
}
if ((cli = BADDR(proc->pr_CLI)) == 0) {
GC_err_puts("No CLI\n");
return;
}
if ((myseglist = cli->cli_Module) == 0) {
GC_err_puts("No seglist from CLI\n");
return;
}
}
for (data = (ULONG *)BADDR(myseglist); data != 0;
data = (ULONG *)BADDR(data[0])) {
# ifdef AMIGA_SKIP_SEG
if (((ULONG) GC_register_data_segments < (ULONG) &data[1]) ||
((ULONG) GC_register_data_segments > (ULONG) &data[1] + data[-1])) {
# else
{
# endif /* AMIGA_SKIP_SEG */
GC_add_roots_inner((char *)&data[1],
((char *)&data[1]) + data[-1], FALSE);
}
}
}
#endif /* old version */
#endif
#ifdef GC_AMIGA_AM
#ifndef GC_AMIGA_FASTALLOC
void *GC_amiga_allocwrapper(size_t size,void *(*AllocFunction)(size_t size2)){
return (*AllocFunction)(size);
}
void *(*GC_amiga_allocwrapper_do)(size_t size,void *(*AllocFunction)(size_t size2))
=GC_amiga_allocwrapper;
#else
void *GC_amiga_allocwrapper_firsttime(size_t size,void *(*AllocFunction)(size_t size2));
void *(*GC_amiga_allocwrapper_do)(size_t size,void *(*AllocFunction)(size_t size2))
=GC_amiga_allocwrapper_firsttime;
/******************************************************************
Amiga-spesific routines to obtain memory, and force GC to give
back fast-mem whenever possible.
These hacks makes gc-programs go many times faster when
the amiga is low on memory, and are therefore strictly necesarry.
-Kjetil S. Matheussen, 2000.
******************************************************************/
/* List-header for all allocated memory. */
struct GC_Amiga_AllocedMemoryHeader{
ULONG size;
struct GC_Amiga_AllocedMemoryHeader *next;
};
struct GC_Amiga_AllocedMemoryHeader *GC_AMIGAMEM=(struct GC_Amiga_AllocedMemoryHeader *)(int)~(NULL);
/* Type of memory. Once in the execution of a program, this might change to MEMF_ANY|MEMF_CLEAR */
ULONG GC_AMIGA_MEMF = MEMF_FAST | MEMF_CLEAR;
/* Prevents GC_amiga_get_mem from allocating memory if this one is TRUE. */
#ifndef GC_AMIGA_ONLYFAST
BOOL GC_amiga_dontalloc=FALSE;
#endif
#ifdef GC_AMIGA_PRINTSTATS
int succ=0,succ2=0;
int nsucc=0,nsucc2=0;
int nullretries=0;
int numcollects=0;
int chipa=0;
int allochip=0;
int allocfast=0;
int cur0=0;
int cur1=0;
int cur10=0;
int cur50=0;
int cur150=0;
int cur151=0;
int ncur0=0;
int ncur1=0;
int ncur10=0;
int ncur50=0;
int ncur150=0;
int ncur151=0;
#endif
/* Free everything at program-end. */
void GC_amiga_free_all_mem(void){
struct GC_Amiga_AllocedMemoryHeader *gc_am=(struct GC_Amiga_AllocedMemoryHeader *)(~(int)(GC_AMIGAMEM));
struct GC_Amiga_AllocedMemoryHeader *temp;
#ifdef GC_AMIGA_PRINTSTATS
printf("\n\n"
"%d bytes of chip-mem, and %d bytes of fast-mem where allocated from the OS.\n",
allochip,allocfast
);
printf(
"%d bytes of chip-mem were returned from the GC_AMIGA_FASTALLOC supported allocating functions.\n",
chipa
);
printf("\n");
printf("GC_gcollect was called %d times to avoid returning NULL or start allocating with the MEMF_ANY flag.\n",numcollects);
printf("%d of them was a success. (the others had to use allocation from the OS.)\n",nullretries);
printf("\n");
printf("Succeded forcing %d gc-allocations (%d bytes) of chip-mem to be fast-mem.\n",succ,succ2);
printf("Failed forcing %d gc-allocations (%d bytes) of chip-mem to be fast-mem.\n",nsucc,nsucc2);
printf("\n");
printf(
"Number of retries before succeding a chip->fast force:\n"
"0: %d, 1: %d, 2-9: %d, 10-49: %d, 50-149: %d, >150: %d\n",
cur0,cur1,cur10,cur50,cur150,cur151
);
printf(
"Number of retries before giving up a chip->fast force:\n"
"0: %d, 1: %d, 2-9: %d, 10-49: %d, 50-149: %d, >150: %d\n",
ncur0,ncur1,ncur10,ncur50,ncur150,ncur151
);
#endif
while(gc_am!=NULL){
temp=gc_am->next;
FreeMem(gc_am,gc_am->size);
gc_am=(struct GC_Amiga_AllocedMemoryHeader *)(~(int)(temp));
}
}
#ifndef GC_AMIGA_ONLYFAST
/* All memory with address lower than this one is chip-mem. */
char *chipmax;
/*
* Allways set to the last size of memory tried to be allocated.
* Needed to ensure allocation when the size is bigger than 100000.
*
*/
size_t latestsize;
#endif
/*
* The actual function that is called with the GET_MEM macro.
*
*/
void *GC_amiga_get_mem(size_t size){
struct GC_Amiga_AllocedMemoryHeader *gc_am;
#ifndef GC_AMIGA_ONLYFAST
if(GC_amiga_dontalloc==TRUE){
// printf("rejected, size: %d, latestsize: %d\n",size,latestsize);
return NULL;
}
// We really don't want to use chip-mem, but if we must, then as little as possible.
if(GC_AMIGA_MEMF==(MEMF_ANY|MEMF_CLEAR) && size>100000 && latestsize<50000) return NULL;
#endif
gc_am=AllocMem((ULONG)(size + sizeof(struct GC_Amiga_AllocedMemoryHeader)),GC_AMIGA_MEMF);
if(gc_am==NULL) return NULL;
gc_am->next=GC_AMIGAMEM;
gc_am->size=size + sizeof(struct GC_Amiga_AllocedMemoryHeader);
GC_AMIGAMEM=(struct GC_Amiga_AllocedMemoryHeader *)(~(int)(gc_am));
// printf("Allocated %d (%d) bytes at address: %x. Latest: %d\n",size,tot,gc_am,latestsize);
#ifdef GC_AMIGA_PRINTSTATS
if((char *)gc_am<chipmax){
allochip+=size;
}else{
allocfast+=size;
}
#endif
return gc_am+1;
}
#ifndef GC_AMIGA_ONLYFAST
/* Tries very hard to force GC to find fast-mem to return. Done recursively
* to hold the rejected memory-pointers reachable from the collector in an
* easy way.
*
*/
#ifdef GC_AMIGA_RETRY
void *GC_amiga_rec_alloc(size_t size,void *(*AllocFunction)(size_t size2),const int rec){
void *ret;
ret=(*AllocFunction)(size);
#ifdef GC_AMIGA_PRINTSTATS
if((char *)ret>chipmax || ret==NULL){
if(ret==NULL){
nsucc++;
nsucc2+=size;
if(rec==0) ncur0++;
if(rec==1) ncur1++;
if(rec>1 && rec<10) ncur10++;
if(rec>=10 && rec<50) ncur50++;
if(rec>=50 && rec<150) ncur150++;
if(rec>=150) ncur151++;
}else{
succ++;
succ2+=size;
if(rec==0) cur0++;
if(rec==1) cur1++;
if(rec>1 && rec<10) cur10++;
if(rec>=10 && rec<50) cur50++;
if(rec>=50 && rec<150) cur150++;
if(rec>=150) cur151++;
}
}
#endif
if (((char *)ret)<=chipmax && ret!=NULL && (rec<(size>500000?9:size/5000))){
ret=GC_amiga_rec_alloc(size,AllocFunction,rec+1);
// GC_free(ret2);
}
return ret;
}
#endif
/* The allocating-functions defined inside the amiga-blocks in gc.h is called
* via these functions.
*/
void *GC_amiga_allocwrapper_any(size_t size,void *(*AllocFunction)(size_t size2)){
void *ret,*ret2;
GC_amiga_dontalloc=TRUE; // Pretty tough thing to do, but its indeed necesarry.
latestsize=size;
ret=(*AllocFunction)(size);
if(((char *)ret) <= chipmax){
if(ret==NULL){
//Give GC access to allocate memory.
#ifdef GC_AMIGA_GC
if(!GC_dont_gc){
GC_gcollect();
#ifdef GC_AMIGA_PRINTSTATS
numcollects++;
#endif
ret=(*AllocFunction)(size);
}
#endif
if(ret==NULL){
GC_amiga_dontalloc=FALSE;
ret=(*AllocFunction)(size);
if(ret==NULL){
WARN("Out of Memory! Returning NIL!\n", 0);
}
}
#ifdef GC_AMIGA_PRINTSTATS
else{
nullretries++;
}
if(ret!=NULL && (char *)ret<=chipmax) chipa+=size;
#endif
}
#ifdef GC_AMIGA_RETRY
else{
/* We got chip-mem. Better try again and again and again etc., we might get fast-mem sooner or later... */
/* Using gctest to check the effectiviness of doing this, does seldom give a very good result. */
/* However, real programs doesn't normally rapidly allocate and deallocate. */
// printf("trying to force... %d bytes... ",size);
if(
AllocFunction!=GC_malloc_uncollectable
#ifdef ATOMIC_UNCOLLECTABLE
&& AllocFunction!=GC_malloc_atomic_uncollectable
#endif
){
ret2=GC_amiga_rec_alloc(size,AllocFunction,0);
}else{
ret2=(*AllocFunction)(size);
#ifdef GC_AMIGA_PRINTSTATS
if((char *)ret2<chipmax || ret2==NULL){
nsucc++;
nsucc2+=size;
ncur0++;
}else{
succ++;
succ2+=size;
cur0++;
}
#endif
}
if(((char *)ret2)>chipmax){
// printf("Succeeded.\n");
GC_free(ret);
ret=ret2;
}else{
GC_free(ret2);
// printf("But did not succeed.\n");
}
}
#endif
}
GC_amiga_dontalloc=FALSE;
return ret;
}
void (*GC_amiga_toany)(void)=NULL;
void GC_amiga_set_toany(void (*func)(void)){
GC_amiga_toany=func;
}
#endif // !GC_AMIGA_ONLYFAST
void *GC_amiga_allocwrapper_fast(size_t size,void *(*AllocFunction)(size_t size2)){
void *ret;
ret=(*AllocFunction)(size);
if(ret==NULL){
// Enable chip-mem allocation.
// printf("ret==NULL\n");
#ifdef GC_AMIGA_GC
if(!GC_dont_gc){
GC_gcollect();
#ifdef GC_AMIGA_PRINTSTATS
numcollects++;
#endif
ret=(*AllocFunction)(size);
}
#endif
if(ret==NULL){
#ifndef GC_AMIGA_ONLYFAST
GC_AMIGA_MEMF=MEMF_ANY | MEMF_CLEAR;
if(GC_amiga_toany!=NULL) (*GC_amiga_toany)();
GC_amiga_allocwrapper_do=GC_amiga_allocwrapper_any;
return GC_amiga_allocwrapper_any(size,AllocFunction);
#endif
}
#ifdef GC_AMIGA_PRINTSTATS
else{
nullretries++;
}
#endif
}
return ret;
}
void *GC_amiga_allocwrapper_firsttime(size_t size,void *(*AllocFunction)(size_t size2)){
atexit(&GC_amiga_free_all_mem);
chipmax=(char *)SysBase->MaxLocMem; // For people still having SysBase in chip-mem, this might speed up a bit.
GC_amiga_allocwrapper_do=GC_amiga_allocwrapper_fast;
return GC_amiga_allocwrapper_fast(size,AllocFunction);
}
#endif //GC_AMIGA_FASTALLOC
/*
* The wrapped realloc function.
*
*/
void *GC_amiga_realloc(void *old_object,size_t new_size_in_bytes){
#ifndef GC_AMIGA_FASTALLOC
return GC_realloc(old_object,new_size_in_bytes);
#else
void *ret;
latestsize=new_size_in_bytes;
ret=GC_realloc(old_object,new_size_in_bytes);
if(ret==NULL && GC_AMIGA_MEMF==(MEMF_FAST | MEMF_CLEAR)){
/* Out of fast-mem. */
#ifdef GC_AMIGA_GC
if(!GC_dont_gc){
GC_gcollect();
#ifdef GC_AMIGA_PRINTSTATS
numcollects++;
#endif
ret=GC_realloc(old_object,new_size_in_bytes);
}
#endif
if(ret==NULL){
#ifndef GC_AMIGA_ONLYFAST
GC_AMIGA_MEMF=MEMF_ANY | MEMF_CLEAR;
if(GC_amiga_toany!=NULL) (*GC_amiga_toany)();
GC_amiga_allocwrapper_do=GC_amiga_allocwrapper_any;
ret=GC_realloc(old_object,new_size_in_bytes);
#endif
}
#ifdef GC_AMIGA_PRINTSTATS
else{
nullretries++;
}
#endif
}
if(ret==NULL){
WARN("Out of Memory! Returning NIL!\n", 0);
}
#ifdef GC_AMIGA_PRINTSTATS
if(((char *)ret)<chipmax && ret!=NULL){
chipa+=new_size_in_bytes;
}
#endif
return ret;
#endif
}
#endif //GC_AMIGA_AM

608
boehm-gc/doc/README Normal file
View File

@ -0,0 +1,608 @@
Copyright (c) 1988, 1989 Hans-J. Boehm, Alan J. Demers
Copyright (c) 1991-1996 by Xerox Corporation. All rights reserved.
Copyright (c) 1996-1999 by Silicon Graphics. All rights reserved.
Copyright (c) 1999-2001 by Hewlett-Packard Company. All rights reserved.
The file linux_threads.c is also
Copyright (c) 1998 by Fergus Henderson. All rights reserved.
The files Makefile.am, and configure.in are
Copyright (c) 2001 by Red Hat Inc. All rights reserved.
THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
Permission is hereby granted to use or copy this program
for any purpose, provided the above notices are retained on all copies.
Permission to modify the code and to distribute modified code is granted,
provided the above notices are retained, and a notice that the code was
modified is included with the above copyright notice.
This is version 6.0alpha7 of a conservative garbage collector for C and C++.
You might find a more recent version of this at
http://www.hpl.hp.com/personal/Hans_Boehm/gc
OVERVIEW
This is intended to be a general purpose, garbage collecting storage
allocator. The algorithms used are described in:
Boehm, H., and M. Weiser, "Garbage Collection in an Uncooperative Environment",
Software Practice & Experience, September 1988, pp. 807-820.
Boehm, H., A. Demers, and S. Shenker, "Mostly Parallel Garbage Collection",
Proceedings of the ACM SIGPLAN '91 Conference on Programming Language Design
and Implementation, SIGPLAN Notices 26, 6 (June 1991), pp. 157-164.
Boehm, H., "Space Efficient Conservative Garbage Collection", Proceedings
of the ACM SIGPLAN '91 Conference on Programming Language Design and
Implementation, SIGPLAN Notices 28, 6 (June 1993), pp. 197-206.
Boehm H., "Reducing Garbage Collector Cache Misses", Proceedings of the
2000 International Symposium on Memory Management.
Possible interactions between the collector and optimizing compilers are
discussed in
Boehm, H., and D. Chase, "A Proposal for GC-safe C Compilation",
The Journal of C Language Translation 4, 2 (December 1992).
and
Boehm H., "Simple GC-safe Compilation", Proceedings
of the ACM SIGPLAN '96 Conference on Programming Language Design and
Implementation.
(Some of these are also available from
http://www.hpl.hp.com/personal/Hans_Boehm/papers/, among other places.)
Unlike the collector described in the second reference, this collector
operates either with the mutator stopped during the entire collection
(default) or incrementally during allocations. (The latter is supported
on only a few machines.) On the most common platforms, it can be built
with or without thread support. On a few platforms, it can take advantage
of a multiprocessor to speed up garbage collection.
Many of the ideas underlying the collector have previously been explored
by others. Notably, some of the run-time systems developed at Xerox PARC
in the early 1980s conservatively scanned thread stacks to locate possible
pointers (cf. Paul Rovner, "On Adding Garbage Collection and Runtime Types
to a Strongly-Typed Statically Checked, Concurrent Language" Xerox PARC
CSL 84-7). Doug McIlroy wrote a simpler fully conservative collector that
was part of version 8 UNIX (tm), but appears to not have received
widespread use.
Rudimentary tools for use of the collector as a leak detector are included
(see http://www.hpl.hp.com/personal/Hans_Boehm/gc/leak.html),
as is a fairly sophisticated string package "cord" that makes use of the
collector. (See doc/README.cords and H.-J. Boehm, R. Atkinson, and M. Plass,
"Ropes: An Alternative to Strings", Software Practice and Experience 25, 12
(December 1995), pp. 1315-1330. This is very similar to the "rope" package
in Xerox Cedar, or the "rope" package in the SGI STL or the g++ distribution.)
Further collector documantation can be found at
http://www.hpl.hp.com/personal/Hans_Boehm/gc
GENERAL DESCRIPTION
This is a garbage collecting storage allocator that is intended to be
used as a plug-in replacement for C's malloc.
Since the collector does not require pointers to be tagged, it does not
attempt to ensure that all inaccessible storage is reclaimed. However,
in our experience, it is typically more successful at reclaiming unused
memory than most C programs using explicit deallocation. Unlike manually
introduced leaks, the amount of unreclaimed memory typically stays
bounded.
In the following, an "object" is defined to be a region of memory allocated
by the routines described below.
Any objects not intended to be collected must be pointed to either
from other such accessible objects, or from the registers,
stack, data, or statically allocated bss segments. Pointers from
the stack or registers may point to anywhere inside an object.
The same is true for heap pointers if the collector is compiled with
ALL_INTERIOR_POINTERS defined, as is now the default.
Compiling without ALL_INTERIOR_POINTERS may reduce accidental retention
of garbage objects, by requiring pointers from the heap to to the beginning
of an object. But this no longer appears to be a significant
issue for most programs.
There are a number of routines which modify the pointer recognition
algorithm. GC_register_displacement allows certain interior pointers
to be recognized even if ALL_INTERIOR_POINTERS is nor defined.
GC_malloc_ignore_off_page allows some pointers into the middle of large objects
to be disregarded, greatly reducing the probablility of accidental
retention of large objects. For most purposes it seems best to compile
with ALL_INTERIOR_POINTERS and to use GC_malloc_ignore_off_page if
you get collector warnings from allocations of very large objects.
See README.debugging for details.
WARNING: pointers inside memory allocated by the standard "malloc" are not
seen by the garbage collector. Thus objects pointed to only from such a
region may be prematurely deallocated. It is thus suggested that the
standard "malloc" be used only for memory regions, such as I/O buffers, that
are guaranteed not to contain pointers to garbage collectable memory.
Pointers in C language automatic, static, or register variables,
are correctly recognized. (Note that GC_malloc_uncollectable has semantics
similar to standard malloc, but allocates objects that are traced by the
collector.)
WARNING: the collector does not always know how to find pointers in data
areas that are associated with dynamic libraries. This is easy to
remedy IF you know how to find those data areas on your operating
system (see GC_add_roots). Code for doing this under SunOS, IRIX 5.X and 6.X,
HP/UX, Alpha OSF/1, Linux, and win32 is included and used by default. (See
README.win32 for win32 details.) On other systems pointers from dynamic
library data areas may not be considered by the collector.
If you're writing a program that depends on the collector scanning
dynamic library data areas, it may be a good idea to include at least
one call to GC_is_visible() to ensure that those areas are visible
to the collector.
Note that the garbage collector does not need to be informed of shared
read-only data. However if the shared library mechanism can introduce
discontiguous data areas that may contain pointers, then the collector does
need to be informed.
Signal processing for most signals may be deferred during collection,
and during uninterruptible parts of the allocation process.
Like standard ANSI C mallocs, by default it is unsafe to invoke
malloc (and other GC routines) from a signal handler while another
malloc call may be in progress. Removing -DNO_SIGNALS from Makefile
attempts to remedy that. But that may not be reliable with a compiler that
substantially reorders memory operations inside GC_malloc.
The allocator/collector can also be configured for thread-safe operation.
(Full signal safety can also be achieved, but only at the cost of two system
calls per malloc, which is usually unacceptable.)
WARNING: the collector does not guarantee to scan thread-local storage
(e.g. of the kind accessed with pthread_getspecific()). The collector
does scan thread stacks, though, so generally the best solution is to
ensure that any pointers stored in thread-local storage are also
stored on the thread's stack for the duration of their lifetime.
(This is arguably a longstanding bug, but it hasn't been fixed yet.)
INSTALLATION AND PORTABILITY
As distributed, the macro SILENT is defined in Makefile.
In the event of problems, this can be removed to obtain a moderate
amount of descriptive output for each collection.
(The given statistics exhibit a few peculiarities.
Things don't appear to add up for a variety of reasons, most notably
fragmentation losses. These are probably much more significant for the
contrived program "test.c" than for your application.)
Note that typing "make test" will automatically build the collector
and then run setjmp_test and gctest. Setjmp_test will give you information
about configuring the collector, which is useful primarily if you have
a machine that's not already supported. Gctest is a somewhat superficial
test of collector functionality. Failure is indicated by a core dump or
a message to the effect that the collector is broken. Gctest takes about
35 seconds to run on a SPARCstation 2. It may use up to 8 MB of memory. (The
multi-threaded version will use more. 64-bit versions may use more.)
"Make test" will also, as its last step, attempt to build and test the
"cord" string library. This will fail without an ANSI C compiler, but
the garbage collector itself should still be usable.
The Makefile will generate a library gc.a which you should link against.
Typing "make cords" will add the cord library to gc.a.
Note that this requires an ANSI C compiler.
It is suggested that if you need to replace a piece of the collector
(e.g. GC_mark_rts.c) you simply list your version ahead of gc.a on the
ld command line, rather than replacing the one in gc.a. (This will
generate numerous warnings under some versions of AIX, but it still
works.)
All include files that need to be used by clients will be put in the
include subdirectory. (Normally this is just gc.h. "Make cords" adds
"cord.h" and "ec.h".)
The collector currently is designed to run essentially unmodified on
machines that use a flat 32-bit or 64-bit address space.
That includes the vast majority of Workstations and X86 (X >= 3) PCs.
(The list here was deleted because it was getting too long and constantly
out of date.)
It does NOT run under plain 16-bit DOS or Windows 3.X. There are however
various packages (e.g. win32s, djgpp) that allow flat 32-bit address
applications to run under those systemsif the have at least an 80386 processor,
and several of those are compatible with the collector.
In a few cases (Amiga, OS/2, Win32, MacOS) a separate makefile
or equivalent is supplied. Many of these have separate README.system
files.
Dynamic libraries are completely supported only under SunOS
(and even that support is not functional on the last Sun 3 release),
Linux, IRIX 5&6, HP-PA, Win32 (not Win32S) and OSF/1 on DEC AXP machines.
On other machines we recommend that you do one of the following:
1) Add dynamic library support (and send us the code).
2) Use static versions of the libraries.
3) Arrange for dynamic libraries to use the standard malloc.
This is still dangerous if the library stores a pointer to a
garbage collected object. But nearly all standard interfaces
prohibit this, because they deal correctly with pointers
to stack allocated objects. (Strtok is an exception. Don't
use it.)
In all cases we assume that pointer alignment is consistent with that
enforced by the standard C compilers. If you use a nonstandard compiler
you may have to adjust the alignment parameters defined in gc_priv.h.
A port to a machine that is not byte addressed, or does not use 32 bit
or 64 bit addresses will require a major effort. A port to plain MSDOS
or win16 is hard.
For machines not already mentioned, or for nonstandard compilers, the
following are likely to require change:
1. The parameters in gcconfig.h.
The parameters that will usually require adjustment are
STACKBOTTOM, ALIGNMENT and DATASTART. Setjmp_test
prints its guesses of the first two.
DATASTART should be an expression for computing the
address of the beginning of the data segment. This can often be
&etext. But some memory management units require that there be
some unmapped space between the text and the data segment. Thus
it may be more complicated. On UNIX systems, this is rarely
documented. But the adb "$m" command may be helpful. (Note
that DATASTART will usually be a function of &etext. Thus a
single experiment is usually insufficient.)
STACKBOTTOM is used to initialize GC_stackbottom, which
should be a sufficient approximation to the coldest stack address.
On some machines, it is difficult to obtain such a value that is
valid across a variety of MMUs, OS releases, etc. A number of
alternatives exist for using the collector in spite of this. See the
discussion in gcconfig.h immediately preceding the various
definitions of STACKBOTTOM.
2. mach_dep.c.
The most important routine here is one to mark from registers.
The distributed file includes a generic hack (based on setjmp) that
happens to work on many machines, and may work on yours. Try
compiling and running setjmp_t.c to see whether it has a chance of
working. (This is not correct C, so don't blame your compiler if it
doesn't work. Based on limited experience, register window machines
are likely to cause trouble. If your version of setjmp claims that
all accessible variables, including registers, have the value they
had at the time of the longjmp, it also will not work. Vanilla 4.2 BSD
on Vaxen makes such a claim. SunOS does not.)
If your compiler does not allow in-line assembly code, or if you prefer
not to use such a facility, mach_dep.c may be replaced by a .s file
(as we did for the MIPS machine and the PC/RT).
At this point enough architectures are supported by mach_dep.c
that you will rarely need to do more than adjust for assembler
syntax.
3. os_dep.c (and gc_priv.h).
Several kinds of operating system dependent routines reside here.
Many are optional. Several are invoked only through corresponding
macros in gc_priv.h, which may also be redefined as appropriate.
The routine GC_register_data_segments is crucial. It registers static
data areas that must be traversed by the collector. (User calls to
GC_add_roots may sometimes be used for similar effect.)
Routines to obtain memory from the OS also reside here.
Alternatively this can be done entirely by the macro GET_MEM
defined in gc_priv.h. Routines to disable and reenable signals
also reside here if they are need by the macros DISABLE_SIGNALS
and ENABLE_SIGNALS defined in gc_priv.h.
In a multithreaded environment, the macros LOCK and UNLOCK
in gc_priv.h will need to be suitably redefined.
The incremental collector requires page dirty information, which
is acquired through routines defined in os_dep.c. Unless directed
otherwise by gcconfig.h, these are implemented as stubs that simply
treat all pages as dirty. (This of course makes the incremental
collector much less useful.)
4. dyn_load.c
This provides a routine that allows the collector to scan data
segments associated with dynamic libraries. Often it is not
necessary to provide this routine unless user-written dynamic
libraries are used.
For a different version of UN*X or different machines using the
Motorola 68000, Vax, SPARC, 80386, NS 32000, PC/RT, or MIPS architecture,
it should frequently suffice to change definitions in gcconfig.h.
THE C INTERFACE TO THE ALLOCATOR
The following routines are intended to be directly called by the user.
Note that usually only GC_malloc is necessary. GC_clear_roots and GC_add_roots
calls may be required if the collector has to trace from nonstandard places
(e.g. from dynamic library data areas on a machine on which the
collector doesn't already understand them.) On some machines, it may
be desirable to set GC_stacktop to a good approximation of the stack base.
(This enhances code portability on HP PA machines, since there is no
good way for the collector to compute this value.) Client code may include
"gc.h", which defines all of the following, plus many others.
1) GC_malloc(nbytes)
- allocate an object of size nbytes. Unlike malloc, the object is
cleared before being returned to the user. Gc_malloc will
invoke the garbage collector when it determines this to be appropriate.
GC_malloc may return 0 if it is unable to acquire sufficient
space from the operating system. This is the most probable
consequence of running out of space. Other possible consequences
are that a function call will fail due to lack of stack space,
or that the collector will fail in other ways because it cannot
maintain its internal data structures, or that a crucial system
process will fail and take down the machine. Most of these
possibilities are independent of the malloc implementation.
2) GC_malloc_atomic(nbytes)
- allocate an object of size nbytes that is guaranteed not to contain any
pointers. The returned object is not guaranteed to be cleared.
(Can always be replaced by GC_malloc, but results in faster collection
times. The collector will probably run faster if large character
arrays, etc. are allocated with GC_malloc_atomic than if they are
statically allocated.)
3) GC_realloc(object, new_size)
- change the size of object to be new_size. Returns a pointer to the
new object, which may, or may not, be the same as the pointer to
the old object. The new object is taken to be atomic iff the old one
was. If the new object is composite and larger than the original object,
then the newly added bytes are cleared (we hope). This is very likely
to allocate a new object, unless MERGE_SIZES is defined in gc_priv.h.
Even then, it is likely to recycle the old object only if the object
is grown in small additive increments (which, we claim, is generally bad
coding practice.)
4) GC_free(object)
- explicitly deallocate an object returned by GC_malloc or
GC_malloc_atomic. Not necessary, but can be used to minimize
collections if performance is critical. Probably a performance
loss for very small objects (<= 8 bytes).
5) GC_expand_hp(bytes)
- Explicitly increase the heap size. (This is normally done automatically
if a garbage collection failed to GC_reclaim enough memory. Explicit
calls to GC_expand_hp may prevent unnecessarily frequent collections at
program startup.)
6) GC_malloc_ignore_off_page(bytes)
- identical to GC_malloc, but the client promises to keep a pointer to
the somewhere within the first 256 bytes of the object while it is
live. (This pointer should nortmally be declared volatile to prevent
interference from compiler optimizations.) This is the recommended
way to allocate anything that is likely to be larger than 100Kbytes
or so. (GC_malloc may result in failure to reclaim such objects.)
7) GC_set_warn_proc(proc)
- Can be used to redirect warnings from the collector. Such warnings
should be rare, and should not be ignored during code development.
8) GC_enable_incremental()
- Enables generational and incremental collection. Useful for large
heaps on machines that provide access to page dirty information.
Some dirty bit implementations may interfere with debugging
(by catching address faults) and place restrictions on heap arguments
to system calls (since write faults inside a system call may not be
handled well).
9) Several routines to allow for registration of finalization code.
User supplied finalization code may be invoked when an object becomes
unreachable. To call (*f)(obj, x) when obj becomes inaccessible, use
GC_register_finalizer(obj, f, x, 0, 0);
For more sophisticated uses, and for finalization ordering issues,
see gc.h.
The global variable GC_free_space_divisor may be adjusted up from its
default value of 4 to use less space and more collection time, or down for
the opposite effect. Setting it to 1 or 0 will effectively disable collections
and cause all allocations to simply grow the heap.
The variable GC_non_gc_bytes, which is normally 0, may be changed to reflect
the amount of memory allocated by the above routines that should not be
considered as a candidate for collection. Careless use may, of course, result
in excessive memory consumption.
Some additional tuning is possible through the parameters defined
near the top of gc_priv.h.
If only GC_malloc is intended to be used, it might be appropriate to define:
#define malloc(n) GC_malloc(n)
#define calloc(m,n) GC_malloc((m)*(n))
For small pieces of VERY allocation intensive code, gc_inl.h
includes some allocation macros that may be used in place of GC_malloc
and friends.
All externally visible names in the garbage collector start with "GC_".
To avoid name conflicts, client code should avoid this prefix, except when
accessing garbage collector routines or variables.
There are provisions for allocation with explicit type information.
This is rarely necessary. Details can be found in gc_typed.h.
THE C++ INTERFACE TO THE ALLOCATOR:
The Ellis-Hull C++ interface to the collector is included in
the collector distribution. If you intend to use this, type
"make c++" after the initial build of the collector is complete.
See gc_cpp.h for the definition of the interface. This interface
tries to approximate the Ellis-Detlefs C++ garbage collection
proposal without compiler changes.
Cautions:
1. Arrays allocated without new placement syntax are
allocated as uncollectable objects. They are traced by the
collector, but will not be reclaimed.
2. Failure to use "make c++" in combination with (1) will
result in arrays allocated using the default new operator.
This is likely to result in disaster without linker warnings.
3. If your compiler supports an overloaded new[] operator,
then gc_cpp.cc and gc_cpp.h should be suitably modified.
4. Many current C++ compilers have deficiencies that
break some of the functionality. See the comments in gc_cpp.h
for suggested workarounds.
USE AS LEAK DETECTOR:
The collector may be used to track down leaks in C programs that are
intended to run with malloc/free (e.g. code with extreme real-time or
portability constraints). To do so define FIND_LEAK in Makefile
This will cause the collector to invoke the report_leak
routine defined near the top of reclaim.c whenever an inaccessible
object is found that has not been explicitly freed. Such objects will
also be automatically reclaimed.
Productive use of this facility normally involves redefining report_leak
to do something more intelligent. This typically requires annotating
objects with additional information (e.g. creation time stack trace) that
identifies their origin. Such code is typically not very portable, and is
not included here, except on SPARC machines.
If all objects are allocated with GC_DEBUG_MALLOC (see next section),
then the default version of report_leak will report the source file
and line number at which the leaked object was allocated. This may
sometimes be sufficient. (On SPARC/SUNOS4 machines, it will also report
a cryptic stack trace. This can often be turned into a sympolic stack
trace by invoking program "foo" with "callprocs foo". Callprocs is
a short shell script that invokes adb to expand program counter values
to symbolic addresses. It was largely supplied by Scott Schwartz.)
Note that the debugging facilities described in the next section can
sometimes be slightly LESS effective in leak finding mode, since in
leak finding mode, GC_debug_free actually results in reuse of the object.
(Otherwise the object is simply marked invalid.) Also note that the test
program is not designed to run meaningfully in FIND_LEAK mode.
Use "make gc.a" to build the collector.
DEBUGGING FACILITIES:
The routines GC_debug_malloc, GC_debug_malloc_atomic, GC_debug_realloc,
and GC_debug_free provide an alternate interface to the collector, which
provides some help with memory overwrite errors, and the like.
Objects allocated in this way are annotated with additional
information. Some of this information is checked during garbage
collections, and detected inconsistencies are reported to stderr.
Simple cases of writing past the end of an allocated object should
be caught if the object is explicitly deallocated, or if the
collector is invoked while the object is live. The first deallocation
of an object will clear the debugging info associated with an
object, so accidentally repeated calls to GC_debug_free will report the
deallocation of an object without debugging information. Out of
memory errors will be reported to stderr, in addition to returning
NIL.
GC_debug_malloc checking during garbage collection is enabled
with the first call to GC_debug_malloc. This will result in some
slowdown during collections. If frequent heap checks are desired,
this can be achieved by explicitly invoking GC_gcollect, e.g. from
the debugger.
GC_debug_malloc allocated objects should not be passed to GC_realloc
or GC_free, and conversely. It is however acceptable to allocate only
some objects with GC_debug_malloc, and to use GC_malloc for other objects,
provided the two pools are kept distinct. In this case, there is a very
low probablility that GC_malloc allocated objects may be misidentified as
having been overwritten. This should happen with probability at most
one in 2**32. This probability is zero if GC_debug_malloc is never called.
GC_debug_malloc, GC_malloc_atomic, and GC_debug_realloc take two
additional trailing arguments, a string and an integer. These are not
interpreted by the allocator. They are stored in the object (the string is
not copied). If an error involving the object is detected, they are printed.
The macros GC_MALLOC, GC_MALLOC_ATOMIC, GC_REALLOC, GC_FREE, and
GC_REGISTER_FINALIZER are also provided. These require the same arguments
as the corresponding (nondebugging) routines. If gc.h is included
with GC_DEBUG defined, they call the debugging versions of these
functions, passing the current file name and line number as the two
extra arguments, where appropriate. If gc.h is included without GC_DEBUG
defined, then all these macros will instead be defined to their nondebugging
equivalents. (GC_REGISTER_FINALIZER is necessary, since pointers to
objects with debugging information are really pointers to a displacement
of 16 bytes form the object beginning, and some translation is necessary
when finalization routines are invoked. For details, about what's stored
in the header, see the definition of the type oh in debug_malloc.c)
INCREMENTAL/GENERATIONAL COLLECTION:
The collector normally interrupts client code for the duration of
a garbage collection mark phase. This may be unacceptable if interactive
response is needed for programs with large heaps. The collector
can also run in a "generational" mode, in which it usually attempts to
collect only objects allocated since the last garbage collection.
Furthermore, in this mode, garbage collections run mostly incrementally,
with a small amount of work performed in response to each of a large number of
GC_malloc requests.
This mode is enabled by a call to GC_enable_incremental().
Incremental and generational collection is effective in reducing
pause times only if the collector has some way to tell which objects
or pages have been recently modified. The collector uses two sources
of information:
1. Information provided by the VM system. This may be provided in
one of several forms. Under Solaris 2.X (and potentially under other
similar systems) information on dirty pages can be read from the
/proc file system. Under other systems (currently SunOS4.X) it is
possible to write-protect the heap, and catch the resulting faults.
On these systems we require that system calls writing to the heap
(other than read) be handled specially by client code.
See os_dep.c for details.
2. Information supplied by the programmer. We define "stubborn"
objects to be objects that are rarely changed. Such an object
can be allocated (and enabled for writing) with GC_malloc_stubborn.
Once it has been initialized, the collector should be informed with
a call to GC_end_stubborn_change. Subsequent writes that store
pointers into the object must be preceded by a call to
GC_change_stubborn.
This mechanism performs best for objects that are written only for
initialization, and such that only one stubborn object is writable
at once. It is typically not worth using for short-lived
objects. Stubborn objects are treated less efficiently than pointerfree
(atomic) objects.
A rough rule of thumb is that, in the absence of VM information, garbage
collection pauses are proportional to the amount of pointerful storage
plus the amount of modified "stubborn" storage that is reachable during
the collection.
Initial allocation of stubborn objects takes longer than allocation
of other objects, since other data structures need to be maintained.
We recommend against random use of stubborn objects in client
code, since bugs caused by inappropriate writes to stubborn objects
are likely to be very infrequently observed and hard to trace.
However, their use may be appropriate in a few carefully written
library routines that do not make the objects themselves available
for writing by client code.
BUGS:
Any memory that does not have a recognizable pointer to it will be
reclaimed. Exclusive-or'ing forward and backward links in a list
doesn't cut it.
Some C optimizers may lose the last undisguised pointer to a memory
object as a consequence of clever optimizations. This has almost
never been observed in practice. Send mail to boehm@acm.org
for suggestions on how to fix your compiler.
This is not a real-time collector. In the standard configuration,
percentage of time required for collection should be constant across
heap sizes. But collection pauses will increase for larger heaps.
(On SPARCstation 2s collection times will be on the order of 300 msecs
per MB of accessible memory that needs to be scanned. Your mileage
may vary.) The incremental/generational collection facility helps,
but is portable only if "stubborn" allocation is used.
Please address bug reports to boehm@acm.org. If you are
contemplating a major addition, you might also send mail to ask whether
it's already been done (or whether we tried and discarded it).

385
boehm-gc/doc/README.Mac Normal file
View File

@ -0,0 +1,385 @@
Patrick Beard's Notes for building GC v4.12 with CodeWarrior Pro 2:
----------------------------------------------------------------------------
The current build environment for the collector is CodeWarrior Pro 2.
Projects for CodeWarrior Pro 2 (and for quite a few older versions)
are distributed in the file Mac_projects.sit.hqx. The project file
:Mac_projects:gc.prj builds static library versions of the collector.
:Mac_projects:gctest.prj builds the GC test suite.
Configuring the collector is still done by editing the files
:Mac_files:MacOS_config.h and :Mac_files:MacOS_Test_config.h.
Lars Farm's suggestions on building the collector:
----------------------------------------------------------------------------
Garbage Collection on MacOS - a manual 'MakeFile'
-------------------------------------------------
Project files and IDE's are great on the Macintosh, but they do have
problems when used as distribution media. This note tries to provide
porting instructions in pure TEXT form to avoid those problems. A manual
'makefile' if you like.
GC version: 4.12a2
Codewarrior: CWPro1
date: 18 July 1997
The notes may or may not apply to earlier or later versions of the
GC/CWPro. Actually, they do apply to earlier versions of both except that
until recently a project could only build one target so each target was a
separate project. The notes will most likely apply to future versions too.
Possibly with minor tweaks.
This is just to record my experiences. These notes do not mean I now
provide a supported port of the GC to MacOS. It works for me. If it works
for you, great. If it doesn't, sorry, try again...;-) Still, if you find
errors, please let me know.
mailto: lars.farm@ite.mh.se
address: Lars Farm
Krönvägen 33b
856 44 Sundsvall
Sweden
Porting to MacOS is a bit more complex than it first seems. Which MacOS?
68K/PowerPC? Which compiler? Each supports both 68K and PowerPC and offer a
large number of (unique to each environment) compiler settings. Each
combination of compiler/68K/PPC/settings require a unique combination of
standard libraries. And the IDE's does not select them for you. They don't
even check that the library is built with compatible setting and this is
the major source of problems when porting the GC (and otherwise too).
You will have to make choices when you configure the GC. I've made some
choices here, but there are other combinations of settings and #defines
that work too.
As for target settings the major obstacles may be:
- 68K Processor: check "4-byte Ints".
- PPC Processor: uncheck "Store Static Data in TOC".
What you need to do:
===================
1) Build the GC as a library
2) Test that the library works with 'test.c'.
3) Test that the C++ interface 'gc_cpp.cc/h' works with 'test_cpp.cc'.
1) The Libraries:
=================
I made one project with four targets (68K/PPC tempmem or appheap). One target
will suffice if you're able to decide which one you want. I wasn't...
Codewarrior allows a large number of compiler/linker settings. I used these:
Settings shared by all targets:
------------------------------
o Access Paths:
- User Paths: the GC folder
- System Paths: {Compiler}:Metrowerks Standard Library:
{Compiler}:MacOS Support:Headers:
{Compiler}:MacOS Support:MacHeaders:
o C/C++ language:
- inlining: normal
- direct to SOM: off
- enable/check: exceptions, RTTI, bool (and if you like pool strings)
PowerPC target settings
-----------------------
o Target Settings:
- name of target
- MacOS PPC Linker
o PPC Target
- name of library
o C/C++ language
- prefix file as described below
o PPC Processor
- Struct Alignment: PowerPC
- uncheck "Store Static Data in TOC" -- important!
I don't think the others matter, I use full optimization and its ok
o PPC Linker
- Factory Settings (SYM file with full paths, faster linking, dead-strip
static init, Main: __start)
68K target settings
-------------------
o Target Settings:
- name of target
- MacOS 68K Linker
o 68K Target
- name of library
- A5 relative data
o C/C++ language
- prefix file as described below
o 68K Processor
- Code model: smart
- Struct alignment: 68K
- FP: SANE
- enable 4-Byte Ints -- important!
I don't think the others matter. I selected...
- enable: 68020
- enable: global register allocation
o IR Optimizer
- enable: Optimize Space, Optimize Speed
I suppose the others would work too, but haven't tried...
o 68K Linker
- Factory Settings (New Style MacsBug,SYM file with full paths,
A6 Frames, fast link, Merge compiler glue into segment 1,
dead-strip static init)
Prefix Files to configure the GC sources
----------------------------------------
The Codewarrior equivalent of commandline compilers -DNAME=X is to use
prefix-files. A TEXT file that is automatically #included before the first byte
of every source file. I used these:
---- ( cut here ) ---- gc_prefix_tempmem.h -- 68K and PPC -----
#include "gc_prefix_common.h"
#undef USE_TEMPORARY_MEMORY
#define USE_TEMPORARY_MEMORY
---- ( cut here ) ---- gc_prefix_appmem.h -- 68K and PPC -----
#include "gc_prefix_common.h"
#undef USE_TEMPORARY_MEMORY
// #define USE_TEMPORARY_MEMORY
---- ( cut here ) ---- gc_prefix_common.h --------------------
// gc_prefix_common.h
// ------------------
// Codewarrior prefix file to configure the GC libraries
//
// prefix files are the Codewarrior equivalent of the
// command line option -Dname=x frequently seen in makefiles
#if !__MWERKS__
#error only tried this with Codewarrior
#endif
#if macintosh
#define MSL_USE_PRECOMPILED_HEADERS 0
#include <ansi_prefix.mac.h>
#ifndef __STDC__
#define __STDC__ 0
#endif
// See list of #defines to configure the library in: 'MakeFile'
// see also README
#define SILENT // no collection messages. In case
// of trouble you might want this off
#define ALL_INTERIOR_POINTERS // follows interior pointers.
//#define DONT_ADD_BYTE_AT_END // disables the padding if defined.
//#define SMALL_CONFIG // whether to use a smaller heap.
#define NO_SIGNALS // signals aren't real on the Macintosh.
#define ATOMIC_UNCOLLECTABLE // GC_malloc_atomic_uncollectable()
// define either or none as per personal preference
// used in malloc.c
#define REDIRECT_MALLOC GC_malloc
//#define REDIRECT_MALLOC GC_malloc_uncollectable
// if REDIRECT_MALLOC is #defined make sure that the GC library
// is listed before the ANSI/ISO libs in the Codewarrior
// 'Link order' panel
//#define IGNORE_FREE
// mac specific configs
//#define USE_TEMPORARY_MEMORY // use Macintosh temporary memory.
//#define SHARED_LIBRARY_BUILD // build for use in a shared library.
#else
// could build Win32 here too, or in the future
// Rhapsody PPC-mach, Rhapsody PPC-MacOS,
// Rhapsody Intel-mach, Rhapsody Intel-Win32,...
// ... ugh this will get messy ...
#endif
// make sure ints are at least 32-bit
// ( could be set to 16-bit by compiler settings (68K) )
struct gc_private_assert_intsize_{ char x[ sizeof(int)>=4 ? 1 : 0 ]; };
#if __powerc
#if __option(toc_data)
#error turn off "store static data in TOC" when using GC
// ... or find a way to add TOC to the root set...(?)
#endif
#endif
---- ( cut here ) ---- end of gc_prefix_common.h -----------------
Files to build the GC libraries:
--------------------------------
allchblk.c
alloc.c
blacklst.c
checksums.c
dbg_mlc.c
finalize.c
headers.c
mach_dep.c
MacOS.c -- contains MacOS code
malloc.c
mallocx.c
mark.c
mark_rts.c
misc.c
new_hblk.c
obj_map.c
os_dep.c -- contains MacOS code
ptr_chck.c
reclaim.c
stubborn.c
typd_mlc.c
gc++.cc -- this is 'gc_cpp.cc' with less 'inline' and
-- throw std::bad_alloc when out of memory
-- gc_cpp.cc works just fine too
2) Test that the library works with 'test.c'.
=============================================
The test app is just an ordinary ANSI-C console app. Make sure settings
match the library you're testing.
Files
-----
test.c
the GC library to test -- link order before ANSI libs
suitable Mac+ANSI libraries
prefix:
------
---- ( cut here ) ---- gc_prefix_testlib.h -- all libs -----
#define MSL_USE_PRECOMPILED_HEADERS 0
#include <ansi_prefix.mac.h>
#undef NDEBUG
#define ALL_INTERIOR_POINTERS /* for GC_priv.h */
---- ( cut here ) ----
3) Test that the C++ interface 'gc_cpp.cc/h' works with 'test_cpp.cc'.
The test app is just an ordinary ANSI-C console app. Make sure settings match
the library you're testing.
Files
-----
test_cpp.cc
the GC library to test -- link order before ANSI libs
suitable Mac+ANSI libraries
prefix:
------
same as for test.c
For convenience I used one test-project with several targets so that all
test apps are build at once. Two for each library to test: test.c and
gc_app.cc. When I was satisfied that the libraries were ok. I put the
libraries + gc.h + the c++ interface-file in a folder that I then put into
the MSL hierarchy so that I don't have to alter access-paths in projects
that use the GC.
After that, just add the proper GC library to your project and the GC is in
action! malloc will call GC_malloc and free GC_free, new/delete too. You
don't have to call free or delete. You may have to be a bit cautious about
delete if you're freeing other resources than RAM. See gc_cpp.h. You can
also keep coding as always with delete/free. That works too. If you want,
"include <gc.h> and tweak it's use a bit.
Symantec SPM
============
It has been a while since I tried the GC in SPM, but I think that the above
instructions should be sufficient to guide you through in SPM too. SPM
needs to know where the global data is. Use the files 'datastart.c' and
'dataend.c'. Put 'datastart.c' at the top of your project and 'dataend.c'
at the bottom of your project so that all data is surrounded. This is not
needed in Codewarrior because it provides intrinsic variables
__datastart__, __data_end__ that wraps all globals.
Source Changes (GC 4.12a2)
==========================
Very few. Just one tiny in the GC, not strictly needed.
- MacOS.c line 131 in routine GC_MacFreeTemporaryMemory()
change # if !defined(SHARED_LIBRARY_BUILD)
to # if !defined(SILENT) && !defined(SHARED_LIBRARY_BUILD)
To turn off a message when the application quits (actually, I faked
this change by #defining SHARED_LIBRARY_BUILD in a statically linked
library for more than a year without ill effects but perhaps this is
better).
- test_cpp.cc
made the first lines of main() look like this:
------------
int main( int argc, char* argv[] ) {
#endif
#if macintosh // MacOS
char* argv_[] = {"test_cpp","10"}; // doesn't
argv=argv_; // have a
argc = sizeof(argv_)/sizeof(argv_[0]); // commandline
#endif //
int i, iters, n;
# ifndef __GNUC__
alloc dummy_to_fool_the_compiler_into_doing_things_it_currently_cant_handle;
------------
- config.h [now gcconfig.h]
__MWERKS__ does not have to mean MACOS. You can use Codewarrior to
build a Win32 or BeOS library and soon a Rhapsody library. You may
have to change that #if...
It worked for me, hope it works for you.
Lars Farm
18 July 1997
----------------------------------------------------------------------------
Patrick Beard's instructions (may be dated):
v4.3 of the collector now runs under Symantec C++/THINK C v7.0.4, and
Metrowerks C/C++ v4.5 both 68K and PowerPC. Project files are provided
to build and test the collector under both development systems.
Configuration
-------------
To configure the collector, under both development systems, a prefix file
is used to set preprocessor directives. This file is called "MacOS_config.h".
Also to test the collector, "MacOS_Test_config.h" is provided.
Testing
-------
To test the collector (always a good idea), build one of the gctest projects,
gctest.¹ (Symantec C++/THINK C), mw/gctest.68K.¹, or mw/gctest.PPC.¹. The
test will ask you how many times to run; 1 should be sufficient.
Building
--------
For your convenience project files for the major Macintosh development
systems are provided.
For Symantec C++/THINK C, you must build the two projects gclib-1.¹ and
gclib-2.¹. It has to be split up because the collector has more than 32k
of static data and no library can have more than this in the Symantec
environment. (Future versions will probably fix this.)
For Metrowerks C/C++ 4.5 you build gc.68K.¹/gc.PPC.¹ and the result will
be a library called gc.68K.lib/gc.PPC.lib.
Using
-----
Under Symantec C++/THINK C, you can just add the gclib-1.¹ and gclib-2.¹
projects to your own project. Under Metrowerks, you add gc.68K.lib or
gc.PPC.lib and two additional files. You add the files called datastart.c
and dataend.c to your project, bracketing all files that use the collector.
See mw/gctest.¹ for an example.
Include the projects/libraries you built above into your own project,
#include "gc.h", and call GC_malloc. You don't have to call GC_free.
Patrick C. Beard
January 4, 1995

View File

@ -0,0 +1,19 @@
While the GC should work on MacOS X Server, MacOS X and Darwin, I only tested
it on MacOS X Server.
I've added a PPC assembly version of GC_push_regs(), thus the setjmp() hack is
no longer necessary. Incremental collection is supported via mprotect/signal.
The current solution isn't really optimal because the signal handler must decode
the faulting PPC machine instruction in order to find the correct heap address.
Further, it must poke around in the register state which the kernel saved away
in some obscure register state structure before it calls the signal handler -
needless to say the layout of this structure is no where documented.
Threads and dynamic libraries are not yet supported (adding dynamic library
support via the low-level dyld API shouldn't be that hard).
The original MacOS X port was brought to you by Andrew Stone.
June, 1 2000
Dietmar Planitzer
dave.pl@ping.at

6
boehm-gc/doc/README.OS2 Normal file
View File

@ -0,0 +1,6 @@
The code assumes static linking, and a single thread. The editor de has
not been ported. The cord test program has. The supplied OS2_MAKEFILE
assumes the IBM C Set/2 environment, but the code shouldn't.
Since we haven't figured out hoe to do perform partial links or to build static
libraries, clients currently need to link against a long list of executables.

322
boehm-gc/doc/README.amiga Normal file
View File

@ -0,0 +1,322 @@
===========================================================================
Kjetil S. Matheussen's notes (28-11-2000)
===========================================================================
Compiles under SAS/C again. Should allso still compile under other
amiga compilers without big changes. I haven't checked if it still
works under gcc, because I don't have gcc for amiga. But I have
updated 'Makefile', and hope it compiles fine.
WHATS NEW:
1.
Made a pretty big effort in preventing GCs allocating-functions from returning
chip-mem.
The lower part of the new file AmigaOS.c does this in various ways, mainly by
wrapping GC_malloc, GC_malloc_atomic, GC_malloc_uncollectable,
GC_malloc_atomic_uncollectable, GC_malloc_stubborn, GC_malloc_ignore_off_page
and GC_malloc_atomic_ignore_off_page. GC_realloc is allso wrapped, but
doesn't do the same effort in preventing to return chip-mem.
Other allocating-functions (f.ex. GC_*_typed_) can probably be
used without any problems, but beware that the warn hook will not be called.
In case of problems, don't define GC_AMIGA_FASTALLOC.
Programs using more time actually using the memory allocated
(instead of just allocate and free rapidly) have
the most to earn on this, but even gctest now normally runs twice
as fast and uses less memory, on my poor 8MB machine.
The changes have only effect when there is no more
fast-mem left. But with the way GC works, it
could happen quite often. Beware that an atexit handler had to be added,
so using the abort() function will make a big memory-loss.
If you absolutely must call abort() instead of exit(), try calling
the GC_amiga_free_all_mem function before abort().
New amiga-spesific compilation flags:
GC_AMIGA_FASTALLOC - By NOT defining this option, GC will work like before,
it will not try to force fast-mem out of the OS, and
it will use normal calloc for allocation, and the rest
of the following flags will have no effect.
GC_AMIGA_ONLYFAST - Makes GC never to return chip-mem. GC_AMIGA_RETRY have
no effect if this flag is set.
GC_AMIGA_GC - If gc returns NULL, do a GC_gcollect, and try again. This
usually is a success with the standard GC configuration.
It is allso the most important flag to set to prevent
GC from returning chip-mem. Beware that it slows down a lot
when a program is rapidly allocating/deallocating when
theres either very little fast-memory left or verly little
chip-memory left. Its not a very common situation, but gctest
sometimes (very rare) use many minutes because of this.
GC_AMIGA_RETRY - If gc succeed allocating memory, but it is chip-mem,
try again and see if it is fast-mem. Most of the time,
it will actually return fast-mem for the second try.
I have set max number of retries to 9 or size/5000. You
can change this if you like. (see GC_amiga_rec_alloc())
GC_AMIGA_PRINTSTATS - Gather some statistics during the execution of a
program, and prints out the info when the atexit-handler
is called.
My reccomendation is to set all this flags, except GC_AMIGA_PRINTSTATS and
GC_AMIGA_ONLYFAST.
If your program demands high response-time, you should
not define GC_AMIGA_GC, and possible allso define GC_AMIGA_ONLYFAST.
GC_AMIGA_RETRY does not seem to slow down much.
Allso, when compiling up programs, and GC_AMIGA_FASTALLOC was not defined when
compilling gc, you can define GC_AMIGA_MAKINGLIB to avoid having these allocation-
functions wrapped. (see gc.h)
Note that GC_realloc must not be called before any of
the other above mentioned allocating-functions have been called. (shouldn't be
any programs doing so either, I hope).
Another note. The allocation-function is wrapped when defining
GC_AMIGA_FASTALLOC by letting the function go thru the new
GC_amiga_allocwrapper_do function-pointer (see gc.h). Means that
sending function-pointers, such as GC_malloc, GC_malloc_atomic, etc.,
for later to be called like f.ex this, (*GC_malloc_functionpointer)(size),
will not wrap the function. This is normally not a big problem, unless
all allocation function is called like this, which will cause the
atexit un-allocating function never to be called. Then you either
have to manually add the atexit handler, or call the allocation-
functions function-pointer functions like this;
(*GC_amiga_allocwrapper_do)(size,GC_malloc_functionpointer).
There are probably better ways this problem could be handled, unfortunately,
I didn't find any without rewriting or replacing a lot of the GC-code, which
I really didn't want to. (Making new GC_malloc_* functions, and just
define f.ex GC_malloc as GC_amiga_malloc should allso work).
New amiga-spesific function:
void GC_amiga_set_toany(void (*func)(void));
'func' is a function that will be called right before gc has to change
allocation-method from MEMF_FAST to MEMF_ANY. Ie. when it is likely
it will return chip-mem.
2. A few small compiler-spesific additions to make it compile with SAS/C again.
3. Updated and rewritten the smakefile, so that it works again and that
the "unnecesarry" 'SCOPTIONS' files could be removed. Allso included
the cord-smakefile stuff in the main smakefile, so that the cord smakefile
could be removed too. By writing smake -f Smakefile.smk, both gc.lib and
cord.lib will be made.
STILL MISSING:
Programs can not be started from workbench, at least not for SAS/C. (Martin
Tauchmanns note about that it now works with workbench is definitely wrong
when concerning SAS/C). I guess it works if you use the old "#if 0'ed"-code,
but I haven't tested it. I think the reason for MT to replace the
"#if 0'ed"-code was only because it was a bit to SAS/C-spesific. But I
don't know. An iconx-script solves this problem anyway.
BEWARE!
-To run gctest, set the stack to around 200000 bytes first.
-SAS/C-spesific: cord will crash if you compile gc.lib with
either parm=reg or parm=both. (missing legal prototypes for
function-pointers someplace is the reason I guess.).
tested with software: Radium, http://www.stud.ifi.uio.no/~ksvalast/radium/
tested with hardware: MC68060
-ksvalast@ifi.uio.no
===========================================================================
Martin Tauchmann's notes (1-Apr-99)
===========================================================================
Works now, also with the GNU-C compiler V2.7.2.1. <ftp://ftp.unina.it/pub/amiga/geekgadgets/amiga/m68k/snapshots/971125/amiga-bin/>
Modify the `Makefile`
CC=cc $(ABI_FLAG)
to
CC=gcc $(ABI_FLAG)
TECHNICAL NOTES
- `GC_get_stack_base()`, `GC_register_data_segments()` works now with every
C compiler; also Workbench.
- Removed AMIGA_SKIP_SEG, but the Code-Segment must not be scanned by GC.
PROBLEMS
- When the Linker, does`t merge all Code-Segments to an single one. LD of GCC
do it always.
- With ixemul.library V47.3, when an GC program launched from another program
(example: `Make` or `if_mach M68K AMIGA gctest`), `GC_register_data_segments()`
found the Segment-List of the caller program.
Can be fixed, if the run-time initialization code (for C programs, usually *crt0*)
support `__data` and `__bss`.
- PowerPC Amiga currently not supported.
- Dynamic libraries (dyn_load.c) not supported.
TESTED WITH SOFTWARE
`Optimized Oberon 2 C` (oo2c) <http://cognac.informatik.uni-kl.de/download/index.html>
TESTED WITH HARDWARE
MC68030
CONTACT
Please, contact me at <martintauchmann@bigfoot.com>, when you change the
Amiga port. <http://martintauchmann.home.pages.de>
===========================================================================
Michel Schinz's notes
===========================================================================
WHO DID WHAT
The original Amiga port was made by Jesper Peterson. I (Michel Schinz)
modified it slightly to reflect the changes made in the new official
distributions, and to take advantage of the new SAS/C 6.x features. I also
created a makefile to compile the "cord" package (see the cord
subdirectory).
TECHNICAL NOTES
In addition to Jesper's notes, I have the following to say:
- Starting with version 4.3, gctest checks to see if the code segment is
added to the root set or not, and complains if it is. Previous versions
of this Amiga port added the code segment to the root set, so I tried to
fix that. The only problem is that, as far as I know, it is impossible to
know which segments are code segments and which are data segments (there
are indeed solutions to this problem, like scanning the program on disk
or patch the LoadSeg functions, but they are rather complicated). The
solution I have chosen (see os_dep.c) is to test whether the program
counter is in the segment we are about to add to the root set, and if it
is, to skip the segment. The problems are that this solution is rather
awkward and that it works only for one code segment. This means that if
your program has more than one code segment, all of them but one will be
added to the root set. This isn't a big problem in fact, since the
collector will continue to work correctly, but it may be slower.
Anyway, the code which decides whether to skip a segment or not can be
removed simply by not defining AMIGA_SKIP_SEG. But notice that if you do
so, gctest will complain (it will say that "GC_is_visible produced wrong
failure indication"). However, it may be useful if you happen to have
pointers stored in a code segment (you really shouldn't).
If anyone has a good solution to the problem of finding, when a program
is loaded in memory, whether a segment is a code or a data segment,
please let me know.
PROBLEMS
If you have any problem with this version, please contact me at
schinz@alphanet.ch (but do *not* send long files, since we pay for
every mail!).
===========================================================================
Jesper Peterson's notes
===========================================================================
ADDITIONAL NOTES FOR AMIGA PORT
These notes assume some familiarity with Amiga internals.
WHY I PORTED TO THE AMIGA
The sole reason why I made this port was as a first step in getting
the Sather(*) language on the Amiga. A port of this language will
be done as soon as the Sather 1.0 sources are made available to me.
Given this motivation, the garbage collection (GC) port is rather
minimal.
(*) For information on Sather read the comp.lang.sather newsgroup.
LIMITATIONS
This port assumes that the startup code linked with target programs
is that supplied with SAS/C versions 6.0 or later. This allows
assumptions to be made about where to find the stack base pointer
and data segments when programs are run from WorkBench, as opposed
to running from the CLI. The compiler dependent code is all in the
GC_get_stack_base() and GC_register_data_segments() functions, but
may spread as I add Amiga specific features.
Given that SAS/C was assumed, the port is set up to be built with
"smake" using the "SMakefile". Compiler options in "SCoptions" can
be set with "scopts" program. Both "smake" and "scopts" are part of
the SAS/C commercial development system.
In keeping with the porting philosophy outlined above, this port
will not behave well with Amiga specific code. Especially not inter-
process comms via messages, and setting up public structures like
Intuition objects or anything else in the system lists. For the
time being the use of this library is limited to single threaded
ANSI/POSIX compliant or near-complient code. (ie. Stick to stdio
for now). Given this limitation there is currently no mechanism for
allocating "CHIP" or "PUBLIC" memory under the garbage collector.
I'll add this after giving it considerable thought. The major
problem is the entire physical address space may have to me scanned,
since there is no telling who we may have passed memory to.
If you allocate your own stack in client code, you will have to
assign the pointer plus stack size to GC_stackbottom.
The initial stack size of the target program can be compiled in by
setting the __stack symbol (see SAS documentaion). It can be over-
ridden from the CLI by running the AmigaDOS "stack" program, or from
the WorkBench by setting the stack size in the tool types window.
SAS/C COMPILER OPTIONS (SCoptions)
You may wish to check the "CPU" code option is appropriate for your
intended target system.
Under no circumstances set the "StackExtend" code option in either
compiling the library or *ANY* client code.
All benign compiler warnings have been suppressed. These mainly
involve lack of prototypes in the code, and dead assignments
detected by the optimizer.
THE GOOD NEWS
The library as it stands is compatible with the GigaMem commercial
virtual memory software, and probably similar PD software.
The performance of "gctest" on an Amiga 2630 (68030 @ 25Mhz)
compares favourably with an HP9000 with similar architecture (a 325
with a 68030 I think).
-----------------------------------------------------------------------
The Amiga port has been brought to you by:
Jesper Peterson.
jep@mtiame.mtia.oz.au (preferred, but 1 week turnaround)
jep@orca1.vic.design.telecom.au (that's orca<one>, 1 day turnaround)
At least one of these addresses should be around for a while, even
though I don't work for either of the companies involved.

1312
boehm-gc/doc/README.changes Normal file

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,57 @@
This is an attempt to acknowledge early contributions to the garbage
collector. Later contributions should instead be mentioned in
README.changes.
HISTORY -
Early versions of this collector were developed as a part of research
projects supported in part by the National Science Foundation
and the Defense Advance Research Projects Agency.
The garbage collector originated as part of the run-time system for
the Russell programming language implementation. The first version of the
garbage collector was written primarily by Al Demers. It was then refined
and mostly rewritten, primarily by Hans-J. Boehm, at Cornell U.,
the University of Washington, Rice University (where it was first used for
C and assembly code), Xerox PARC, SGI, and HP Labs. However, significant
contributions have also been made by many others.
Some other contributors:
More recent contributors are mentioned in the modification history in
README.changes. My apologies for any omissions.
The SPARC specific code was originally contributed by Mark Weiser.
The Encore Multimax modifications were supplied by
Kevin Kenny (kenny@m.cs.uiuc.edu). The adaptation to the IBM PC/RT is largely
due to Vernon Lee, on machines made available to Rice by IBM.
Much of the HP specific code and a number of good suggestions for improving the
generic code are due to Walter Underwood.
Robert Brazile (brazile@diamond.bbn.com) originally supplied the ULTRIX code.
Al Dosser (dosser@src.dec.com) and Regis Cridlig (Regis.Cridlig@cl.cam.ac.uk)
subsequently provided updates and information on variation between ULTRIX
systems. Parag Patel (parag@netcom.com) supplied the A/UX code.
Jesper Peterson(jep@mtiame.mtia.oz.au), Michel Schinz, and
Martin Tauchmann (martintauchmann@bigfoot.com) supplied the Amiga port.
Thomas Funke (thf@zelator.in-berlin.de(?)) and
Brian D.Carlstrom (bdc@clark.lcs.mit.edu) supplied the NeXT ports.
Douglas Steel (doug@wg.icl.co.uk) provided ICL DRS6000 code.
Bill Janssen (janssen@parc.xerox.com) supplied the SunOS dynamic loader
specific code. Manuel Serrano (serrano@cornas.inria.fr) supplied linux and
Sony News specific code. Al Dosser provided Alpha/OSF/1 code. He and
Dave Detlefs(detlefs@src.dec.com) also provided several generic bug fixes.
Alistair G. Crooks(agc@uts.amdahl.com) supplied the NetBSD and 386BSD ports.
Jeffrey Hsu (hsu@soda.berkeley.edu) provided the FreeBSD port.
Brent Benson (brent@jade.ssd.csd.harris.com) ported the collector to
a Motorola 88K processor running CX/UX (Harris NightHawk).
Ari Huttunen (Ari.Huttunen@hut.fi) generalized the OS/2 port to
nonIBM development environments (a nontrivial task).
Patrick Beard (beard@cs.ucdavis.edu) provided the initial MacOS port.
David Chase, then at Olivetti Research, suggested several improvements.
Scott Schwartz (schwartz@groucho.cse.psu.edu) supplied some of the
code to save and print call stacks for leak detection on a SPARC.
Jesse Hull and John Ellis supplied the C++ interface code.
Zhong Shao performed much of the experimentation that led to the
current typed allocation facility. (His dynamic type inference code hasn't
made it into the released version of the collector, yet.)

39
boehm-gc/doc/README.cords Normal file
View File

@ -0,0 +1,39 @@
Copyright (c) 1993-1994 by Xerox Corporation. All rights reserved.
THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
Permission is hereby granted to use or copy this program
for any purpose, provided the above notices are retained on all copies.
Permission to modify the code and to distribute modified code is granted,
provided the above notices are retained, and a notice that the code was
modified is included with the above copyright notice.
Please send bug reports to Hans-J. Boehm (Hans_Boehm@hp.com or
boehm@acm.org).
This is a string packages that uses a tree-based representation.
See cord.h for a description of the functions provided. Ec.h describes
"extensible cords", which are essentially output streams that write
to a cord. These allow for efficient construction of cords without
requiring a bound on the size of a cord.
de.c is a very dumb text editor that illustrates the use of cords.
It maintains a list of file versions. Each version is simply a
cord representing the file contents. Nonetheless, standard
editing operations are efficient, even on very large files.
(Its 3 line "user manual" can be obtained by invoking it without
arguments. Note that ^R^N and ^R^P move the cursor by
almost a screen. It does not understand tabs, which will show
up as highlighred "I"s. Use the UNIX "expand" program first.)
To build the editor, type "make cord/de" in the gc directory.
This package assumes an ANSI C compiler such as gcc. It will
not compile with an old-style K&R compiler.
Note that CORD_printf iand friends use C functions with variable numbers
of arguments in non-standard-conforming ways. This code is known to
break on some platforms, notably PowerPC. It should be possible to
build the remainder of the library (everything but cordprnt.c) on
any platform that supports the collector.

View File

@ -0,0 +1,68 @@
Debugging suggestions:
****If you get a segmentation fault or bus error while debugging with a debugger:
If the fault occurred in GC_find_limit, or with incremental collection enabled, this is probably normal. The collector installs handlers to take care of these. You will not see these unless you are using a debugger. Your debugger should allow you to continue. It's preferable to tell the debugger to ignore SIGBUS and SIGSEGV ("handle" in gdb, "ignore" in most versions of dbx) and set a breakpoint in abort. The collector will call abort if the signal had another cause, and there was not other handler previously installed. I recommend debugging without incremental collection if possible. (This applies directly to UNIX systems. Debugging with incremental collection under win32 is worse. See README.win32.)
****If you get warning messages informing you that the collector needed to allocate blacklisted blocks:
0) Ignore these warnings while you are using GC_DEBUG. Some of the routines mentioned below don't have debugging equivalents. (Alternatively, write the missing routines and send them to me.)
1) Replace allocator calls that request large blocks with calls to GC_malloc_ignore_off_page or GC_malloc_atomic_ignore_off_page. You may want to set a breakpoint in GC_default_warn_proc to help you identify such calls. Make sure that a pointer to somewhere near the beginning of the resulting block is maintained in a (preferably volatile) variable as long as the block is needed.
2) If the large blocks are allocated with realloc, I suggest instead allocating them with something like the following. Note that the realloc size increment should be fairly large (e.g. a factor of 3/2) for this to exhibit reasonable performance. But we all know we should do that anyway.
void * big_realloc(void *p, size_t new_size)
{
size_t old_size = GC_size(p);
void * result;
if (new_size <= 10000) return(GC_realloc(p, new_size));
if (new_size <= old_size) return(p);
result = GC_malloc_ignore_off_page(new_size);
if (result == 0) return(0);
memcpy(result,p,old_size);
GC_free(p);
return(result);
}
3) In the unlikely case that even relatively small object (<20KB) allocations are triggering these warnings, then your address space contains lots of "bogus pointers", i.e. values that appear to be pointers but aren't. Usually this can be solved by using GC_malloc_atomic or the routines in gc_typed.h to allocate large pointerfree regions of bitmaps, etc. Sometimes the problem can be solved with trivial changes of encoding in certain values. It is possible, though not pleasant, to identify the source of the bogus pointers by setting a breakpoint in GC_add_to_black_list_stack, and looking at the value of current_p in the GC_mark_from_mark_stack frame. Current_p contains the address of the bogus pointer.
4) If you get only a fixed number of these warnings, you are probably only introducing a bounded leak by ignoring them. If the data structures being allocated are intended to be permanent, then it is also safe to ignore them. The warnings can be turned off by calling GC_set_warn_proc with a procedure that ignores these warnings (e.g. by doing absolutely nothing).
****If the collector dies in GC_malloc while trying to remove a free list element:
1) With > 99% probability, you wrote past the end of an allocated object. Try setting GC_DEBUG and using the debugging facilities in gc.h.
****If the heap grows too much:
1) Consider using GC_malloc_atomic for objects containing nonpointers. This is especially important for large arrays containg compressed data, pseudo-random numbers, and the like. (This isn't all that likely to solve your problem, but it's a useful and easy optimization anyway, and this is a good time to try it.) If you allocate large objects containg only one or two pointers at the beginning, either try the typed allocation primitives is gc.h, or separate out the pointerfree component.
2) If you are using the collector in its default mode, with interior pointer recognition enabled, consider using GC_malloc_ignore_off_page to allocate large objects. (See gc.h and above for details. Large means > 100K in most environments.)
3) GC_print_block_list() will print a list of all currently allocated heap blocks and what size objects they contain. GC_print_hblkfreelist() will print a list of free heap blocks, and whether they are blacklisted. GC_dump calls both of these, and also prints information about heap sections, and root segments.
4) Build the collector with -DKEEP_BACK_PTRS, and use the backptr.h
interface to determine why objects are being retained.
****If the collector appears to be losing objects:
1) Replace all calls to GC_malloc_atomic and typed allocation by GC_malloc calls. If this fixes the problem, gradually reinsert your optimizations.
2) You may also want to try the safe(r) pointer manipulation primitives in gc.h. But those are hard to use until the preprocessor becomes available.
3) Try using the GC_DEBUG facilities. This is less likely to be successful here than if the collector crashes.
[The rest of these are primarily for wizards. You shouldn't need them unless you're doing something really strange, or debugging a collector port.]
4) Don't turn on incremental collection. If that fixes the problem, suspect a bug in the dirty bit implementation. Try compiling with -DCHECKSUMS to check for modified, but supposedly clean, pages.
5) On a SPARC, in a single-threaded environment, GC_print_callers(GC_arrays._last_stack) prints a cryptic stack trace as of the time of the last collection. (You will need a debugger to decipher the result.) The question to ask then is "why should this object have been accessible at the time of the last collection? Where was a pointer to it stored?". This facility should be easy to add for some other collector ports (namely if it's easy to traverse stack frames), but will be hard for others.
6) "print *GC_find_header(p)" in dbx or gdb will print the garbage collector block header information associated with the object p (e.g. object size, etc.)
7) GC_is_marked(p) determines whether p is the base address of a marked object. Note that objects allocated since the last collection should not be marked, and that unmarked objects are reclaimed incrementally. It's usually most interesting to set a breakpoint in GC_finish_collection and then to determine how much of the damaged data structure is marked at that point.
8) Look at the tracing facility in mark.c. (Ignore this suggestion unless you are very familiar with collector internals.)
9) [From Melissa O'Neill:]
If you're using multiple threads, double check that all thread
creation goes through the GC_ wrapper functions rather than
calling the thread-creation functions themselves (e.g.,
GC_pthread_create rather than pthread_create). The gc.h header
file includes suitable preprocessor definitions to accomplish
this mapping transparently -- the question is: are you including
it in all the modules that create threads?

12
boehm-gc/doc/README.dj Normal file
View File

@ -0,0 +1,12 @@
[Original version supplied by Xiaokun Zhu <xiaokun@aero.gla.ac.uk>]
[This version came mostly from Gary Leavens. ]
Look first at Makefile.dj, and possibly change the definitions of
RM and MV if you don't have rm and mv installed.
Then use Makefile.dj to compile the garbage collector.
For example, you can do:
make -f Makefile.dj test
All the tests should work fine.

View File

@ -0,0 +1,41 @@
The garbage collector looks at a number of environment variables which are
the used to affect its operation. These are examined only on Un*x-like
platforms.
GC_INITIAL_HEAP_SIZE=<bytes> - Initial heap size in bytes. May speed up
process start-up.
GC_LOOP_ON_ABORT - Causes the collector abort routine to enter a tight loop.
This may make it easier to debug, such a process, especially
for multithreaded platforms that don't produce usable core
files, or if a core file would be too large. On some
platforms, this also causes SIGSEGV to be caught and
result in an infinite loop in a handler, allowing
similar debugging techniques.
GC_PRINT_STATS - Turn on as much logging as is easily feasible without
adding signifcant runtime overhead. Doesn't work if
the collector is built with SMALL_CONFIG. Overridden
by setting GC_quiet. On by default if the collector
was built without -DSILENT.
GC_PRINT_ADDRESS_MAP - Linux only. Dump /proc/self/maps, i.e. various address
maps for the process, to stderr on every GC. Useful for
mapping root addresses to source for deciphering leak
reports.
GC_NPROCS=<n> - Linux w/threads only. Explicitly sets the number of processors
that the GC should expect to use. Note that setting this to 1
when multiple processors are available will preserve
correctness, but may lead to really horrible performance.
The following turn on runtime flags that are also program settable. Checked
only during initialization. We expect that they will usually be set through
other means, but this may help with debugging and testing:
GC_FIND_LEAK - Turns on GC_find_leak and thus leak detection.
GC_ALL_INTERIOR_POINTERS - Turns on GC_all_interior_pointers and thus interior
pointer recognition.
GC_DONT_GC - Turns off garbage collection. Use cautiously.

18
boehm-gc/doc/README.hp Normal file
View File

@ -0,0 +1,18 @@
Dynamic loading support requires that executables be linked with -ldld.
The alternative is to build the collector without defining DYNAMIC_LOADING
in gcconfig.h and ensuring that all garbage collectable objects are
accessible without considering statically allocated variables in dynamic
libraries.
The collector should compile with either plain cc or cc -Ae. Cc -Aa
fails to define _HPUX_SOURCE and thus will not configure the collector
correctly.
Incremental collection support was reccently added, and should now work.
In spite of past claims, pthread support under HP/UX 11 should now work.
Define GC_HPUX_THREADS for the build. Incremental collection still does not
work in combination with it.
The stack finding code can be confused by putenv calls before collector
initialization. Call GC_malloc or GC_init before any putenv calls.

135
boehm-gc/doc/README.linux Normal file
View File

@ -0,0 +1,135 @@
See README.alpha for Linux on DEC AXP info.
This file applies mostly to Linux/Intel IA32. Ports to Linux on an M68K
and PowerPC are also integrated. They should behave similarly, except that
the PowerPC port lacks incremental GC support, and it is unknown to what
extent the Linux threads code is functional. See below for M68K specific
notes.
Incremental GC is supported on Intel IA32 and M68K.
Dynamic libraries are supported on an ELF system. A static executable
should be linked with the gcc option "-Wl,-defsym,_DYNAMIC=0".
The collector appears to work with Linux threads. We have seen
intermittent hangs in sem_wait. So far we have been unable to reproduce
these unless the process was being debugged or traced. Thus it's
possible that the only real issue is that the debugger loses
signals on rare occasions.
The garbage collector uses SIGPWR and SIGXCPU if it is used with
Linux threads. These should not be touched by the client program.
To use threads, you need to abide by the following requirements:
1) You need to use LinuxThreads (which are included in libc6).
The collector relies on some implementation details of the LinuxThreads
package. It is unlikely that this code will work on other
pthread implementations (in particular it will *not* work with
MIT pthreads).
2) You must compile the collector with -DGC_LINUX_THREADS and -D_REENTRANT
specified in the Makefile.
3a) Every file that makes thread calls should define GC_LINUX_THREADS and
_REENTRANT and then include gc.h. Gc.h redefines some of the
pthread primitives as macros which also provide the collector with
information it requires.
3b) A new alternative to (3a) is to build the collector and compile GC clients
with -DGC_USE_LD_WRAP, and to link the final program with
(for ld) --wrap read --wrap dlopen --wrap pthread_create \
--wrap pthread_join --wrap pthread_detach \
--wrap pthread_sigmask --wrap sleep
(for gcc) -Wl,--wrap -Wl,read -Wl,--wrap -Wl,dlopen -Wl,--wrap \
-Wl,pthread_create -Wl,--wrap -Wl,pthread_join -Wl,--wrap \
-Wl,pthread_detach -Wl,--wrap -Wl,pthread_sigmask \
-Wl,--wrap -Wl,sleep
In any case, _REENTRANT should be defined during compilation.
4) Dlopen() disables collection during its execution. (It can't run
concurrently with the collector, since the collector looks at its
data structures. It can't acquire the allocator lock, since arbitrary
user startup code may run as part of dlopen().) Under unusual
conditions, this may cause unexpected heap growth.
5) The combination of GC_LINUX_THREADS, REDIRECT_MALLOC, and incremental
collection fails in seemingly random places. This hasn't been tracked
down yet, but is perhaps not completely astonishing. The thread package
uses malloc, and thus can presumably get SIGSEGVs while inside the
package. There is no real guarantee that signals are handled properly
at that point.
6) Thread local storage may not be viewed as part of the root set by the
collector. This probably depends on the linuxthreads version. For the
time being, any collectable memory referenced by thread local storage should
also be referenced from elsewhere, or be allocated as uncollectable.
(This is really a bug that should be fixed somehow.)
M68K LINUX:
(From Richard Zidlicky)
The bad news is that it can crash every linux-m68k kernel on a 68040,
so an additional test is needed somewhere on startup. I have meanwhile
patches to correct the problem in 68040 buserror handler but it is not
yet in any standard kernel.
Here is a simple test program to detect whether the kernel has the
problem. It could be run as a separate check in configure or tested
upon startup. If it fails (return !0) than mprotect can't be used
on that system.
/*
* test for bug that may crash 68040 based Linux
*/
#include <sys/mman.h>
#include <signal.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
char *membase;
int pagesize=4096;
int pageshift=12;
int x_taken=0;
int sighandler(int sig)
{
mprotect(membase,pagesize,PROT_READ|PROT_WRITE);
x_taken=1;
}
main()
{
long l;
signal(SIGSEGV,sighandler);
l=(long)mmap(NULL,pagesize,PROT_READ,MAP_PRIVATE | MAP_ANON,-1,0);
if (l==-1)
{
perror("mmap/malloc");
abort();
}
membase=(char*)l;
*(long*)(membase+sizeof(long))=123456789;
if (*(long*)(membase+sizeof(long)) != 123456789 )
{
fprintf(stderr,"writeback failed !\n");
exit(1);
}
if (!x_taken)
{
fprintf(stderr,"exception not taken !\n");
exit(1);
}
fprintf(stderr,"vmtest Ok\n");
exit(0);
}

View File

@ -0,0 +1,9 @@
We have so far failed to find a good way to determine the stack base.
It is highly recommended that GC_stackbottom be set explicitly on program
startup. The supplied value sometimes causes failure under AIX 4.1, though
it appears to work under 3.X. HEURISTIC2 seems to work under 4.1, but
involves a substantial performance penalty, and will fail if there is
no limit on stack size.
There is no thread support. (I assume recent versions of AIX provide
pthreads? I no longer have access to a machine ...)

41
boehm-gc/doc/README.sgi Normal file
View File

@ -0,0 +1,41 @@
Performance of the incremental collector can be greatly enhanced with
-DNO_EXECUTE_PERMISSION.
The collector should run with all of the -32, -n32 and -64 ABIs. Remember to
define the AS macro in the Makefile to be "as -64", or "as -n32".
If you use -DREDIRECT_MALLOC=GC_malloc with C++ code, your code should make
at least one explicit call to malloc instead of new to ensure that the proper
version of malloc is linked in.
Sproc threads are not supported in this version, though there may exist other
ports.
Pthreads support is provided. This requires that:
1) You compile the collector with -DGC_IRIX_THREADS specified in the Makefile.
2) You have the latest pthreads patches installed.
(Though the collector makes only documented pthread calls,
it relies on signal/threads interactions working just right in ways
that are not required by the standard. It is unlikely that this code
will run on other pthreads platforms. But please tell me if it does.)
3) Every file that makes thread calls should define IRIX_THREADS and then
include gc.h. Gc.h redefines some of the pthread primitives as macros which
also provide the collector with information it requires.
4) pthread_cond_wait and pthread_cond_timed_wait should be prepared for
premature wakeups. (I believe the pthreads and realted standards require this
anyway. Irix pthreads often terminate a wait if a signal arrives.
The garbage collector uses signals to stop threads.)
5) It is expensive to stop a thread waiting in IO at the time the request is
initiated. Applications with many such threads may not exhibit acceptable
performance with the collector. (Increasing the heap size may help.)
6) The collector should not be compiled with -DREDIRECT_MALLOC. This
confuses some library calls made by the pthreads implementation, which
expect the standard malloc.

View File

@ -0,0 +1,62 @@
The collector supports both incremental collection and threads under
Solaris 2. The incremental collector normally retrieves page dirty information
through the appropriate /proc calls. But it can also be configured
(by defining MPROTECT_VDB instead of PROC_VDB in gcconfig.h) to use mprotect
and signals. This may result in shorter pause times, but it is no longer
safe to issue arbitrary system calls that write to the heap.
Under other UNIX versions,
the collector normally obtains memory through sbrk. There is some reason
to expect that this is not safe if the client program also calls the system
malloc, or especially realloc. The sbrk man page strongly suggests this is
not safe: "Many library routines use malloc() internally, so use brk()
and sbrk() only when you know that malloc() definitely will not be used by
any library routine." This doesn't make a lot of sense to me, since there
seems to be no documentation as to which routines can transitively call malloc.
Nonetheless, under Solaris2, the collector now (since 4.12) allocates
memory using mmap by default. (It defines USE_MMAP in gcconfig.h.)
You may want to reverse this decisions if you use -DREDIRECT_MALLOC=...
SOLARIS THREADS:
The collector must be compiled with -DGC_SOLARIS_THREADS (thr_ functions)
or -DGC_SOLARIS_PTHREADS (pthread_ functions) to be thread safe.
It is also essential that gc.h be included in files that call thr_create,
thr_join, thr_suspend, thr_continue, or dlopen. Gc.h macro defines
these to also do GC bookkeeping, etc. Gc.h must be included with
one or both of these macros defined, otherwise
these replacements are not visible.
A collector built in this way way only be used by programs that are
linked with the threads library.
In this mode, the collector contains various workarounds for older Solaris
bugs. Mostly, these should not be noticeable unless you look at system
call traces. However, it cannot protect a guard page at the end of
a thread stack. If you know that you will only be running Solaris2.5
or later, it should be possible to fix this by compiling the collector
with -DSOLARIS23_MPROTECT_BUG_FIXED.
Since 5.0 alpha5, dlopen disables collection temporarily,
unless USE_PROC_FOR_LIBRARIES is defined. In some unlikely cases, this
can result in unpleasant heap growth. But it seems better than the
race/deadlock issues we had before.
If solaris_threads are used on an X86 processor with malloc redirected to
GC_malloc, it is necessary to call GC_thr_init explicitly before forking the
first thread. (This avoids a deadlock arising from calling GC_thr_init
with the allocation lock held.)
It appears that there is a problem in using gc_cpp.h in conjunction with
Solaris threads and Sun's C++ runtime. Apparently the overloaded new operator
is invoked by some iostream initialization code before threads are correctly
initialized. As a result, call to thr_self() in garbage collector
initialization segfaults. Currently the only known workaround is to not
invoke the garbage collector from a user defined global operator new, or to
have it invoke the garbage-collector's allocators only after main has started.
(Note that the latter requires a moderately expensive test in operator
delete.)
Hans-J. Boehm
(The above contains my personal opinions, which are probably not shared
by anyone else.)

2
boehm-gc/doc/README.uts Normal file
View File

@ -0,0 +1,2 @@
Alistair Crooks supplied the port. He used Lexa C version 2.1.3 with
-Xa to compile.

149
boehm-gc/doc/README.win32 Normal file
View File

@ -0,0 +1,149 @@
The collector has at various times been compiled under Windows 95 & NT,
with the original Microsoft SDK, with Visual C++ 2.0, 4.0, and 6, with
the GNU win32 environment, with Borland 4.5, and recently with
Watcom C. It is likely that some of these have been broken in the
meantime. Patches are appreciated.
It runs under both win32s and win32, but with different semantics.
Under win32, all writable pages outside of the heaps and stack are
scanned for roots. Thus the collector sees pointers in DLL data
segments. Under win32s, only the main data segment is scanned.
(The main data segment should always be scanned. Under some
versions of win32s, other regions may also be scanned.)
Thus all accessible objects should be accessible from local variables
or variables in the main data segment. Alternatively, other data
segments (e.g. in DLLs) may be registered with the collector by
calling GC_init() and then GC_register_root_section(a), where
a is the address of some variable inside the data segment. (Duplicate
registrations are ignored, but not terribly quickly.)
(There are two reasons for this. We didn't want to see many 16:16
pointers. And the VirtualQuery call has different semantics under
the two systems, and under different versions of win32s.)
The collector test program "gctest" is linked as a GUI application,
but does not open any windows. Its output appears in the file
"gc.log". It may be started from the file manager. The hour glass
cursor may appear as long as it's running. If it is started from the
command line, it will usually run in the background. Wait a few
minutes (a few seconds on a modern machine) before you check the output.
You should see either a failure indication or a "Collector appears to
work" message.
The cord test program has not been ported (but should port
easily). A toy editor (cord/de.exe) based on cords (heavyweight
strings represented as trees) has been ported and is included.
It runs fine under either win32 or win32S. It serves as an example
of a true Windows application, except that it was written by a
nonexpert Windows programmer. (There are some peculiarities
in the way files are displayed. The <cr> is displayed explicitly
for standard DOS text files. As in the UNIX version, control
characters are displayed explicitly, but in this case as red text.
This may be suboptimal for some tastes and/or sets of default
window colors.)
In general -DREDIRECT_MALLOC is unlikely to work unless the
application is completely statically linked.
For Microsoft development tools, rename NT_MAKEFILE as
MAKEFILE. (Make sure that the CPU environment variable is defined
to be i386.) In order to use the gc_cpp.h C++ interface, all
client code should include gc_cpp.h.
Clients may need to define GC_NOT_DLL before including gc.h, if the
collector was built as a static library (as it normally is in the
absence of thread support).
For GNU-win32, use the regular makefile, possibly after uncommenting
the line "include Makefile.DLLs". The latter should be necessary only
if you want to package the collector as a DLL. The GNU-win32 port is
believed to work only for b18, not b19, probably dues to linker changes
in b19. This is probably fixable with a different definition of
DATASTART and DATAEND in gcconfig.h.
For Borland tools, use BCC_MAKEFILE. Note that
Borland's compiler defaults to 1 byte alignment in structures (-a1),
whereas Visual C++ appears to default to 8 byte alignment (/Zp8).
The garbage collector in its default configuration EXPECTS AT
LEAST 4 BYTE ALIGNMENT. Thus the BORLAND DEFAULT MUST
BE OVERRIDDEN. (In my opinion, it should usually be anyway.
I expect that -a1 introduces major performance penalties on a
486 or Pentium.) Note that this changes structure layouts. (As a last
resort, gcconfig.h can be changed to allow 1 byte alignment. But
this has significant negative performance implications.)
The Makefile is set up to assume Borland 4.5. If you have another
version, change the line near the top. By default, it does not
require the assembler. If you do have the assembler, I recommend
removing the -DUSE_GENERIC.
There is some support for incremental collection. This is
currently pretty simple-minded. Pages are protected. Protection
faults are caught by a handler installed at the bottom of the handler
stack. This is both slow and interacts poorly with a debugger.
Whenever possible, I recommend adding a call to
GC_enable_incremental at the last possible moment, after most
debugging is complete. Unlike the UNIX versions, no system
calls are wrapped by the collector itself. It may be necessary
to wrap ReadFile calls that use a buffer in the heap, so that the
call does not encounter a protection fault while it's running.
(As usual, none of this is an issue unless GC_enable_incremental
is called.)
Note that incremental collection is disabled with -DSMALL_CONFIG.
James Clark has contributed the necessary code to support win32 threads.
Use NT_THREADS_MAKEFILE (a.k.a gc.mak) instead of NT_MAKEFILE
to build this version. Note that this requires some files whose names
are more than 8 + 3 characters long. Thus you should unpack the tar file
so that long file names are preserved. To build the garbage collector
test with VC++ from the command line, use
nmake /F ".\gc.mak" CFG="gctest - Win32 Release"
This requires that the subdirectory gctest\Release exist.
The test program and DLL will reside in the Release directory.
This version relies on the collector residing in a dll.
This version currently supports incremental collection only if it is
enabled before any additional threads are created.
Version 4.13 attempts to fix some of the earlier problems, but there
may be other issues. If you need solid support for win32 threads, you
might check with Geodesic Systems. Their collector must be licensed,
but they have invested far more time in win32-specific issues.
Hans
Ivan V. Demakov's README for the Watcom port:
The collector has been compiled with Watcom C 10.6 and 11.0.
It runs under win32, win32s, and even under msdos with dos4gw
dos-extender. It should also run under OS/2, though this isn't
tested. Under win32 the collector can be built either as dll
or as static library.
Note that all compilations were done under Windows 95 or NT.
For unknown reason compiling under Windows 3.11 for NT (one
attempt has been made) leads to broken executables.
Incremental collection is not supported.
cord is not ported.
Before compiling you may need to edit WCC_MAKEFILE to set target
platform, library type (dynamic or static), calling conventions, and
optimization options.
To compile the collector and testing programs use the command:
wmake -f WCC_MAKEFILE
All programs using gc should be compiled with 4-byte alignment.
For further explanations on this see comments about Borland.
If gc compiled as dll, the macro ``GC_DLL'' should be defined before
including "gc.h" (for example, with -DGC_DLL compiler option). It's
important, otherwise resulting programs will not run.
Ivan Demakov (email: ivan@tgrad.nsk.su)

View File

@ -0,0 +1,106 @@
This is an ASCII diagram of the data structure used to check pointer
validity. It was provided by Dave Barrett <barrett@asgard.cs.colorado.edu>,
and should be of use to others attempting to understand the code.
The data structure in GC4.X is essentially the same. -HB
Data Structure used by GC_base in gc3.7:
21-Apr-94
63 LOG_TOP_SZ[11] LOG_BOTTOM_SZ[10] LOG_HBLKSIZE[13]
+------------------+----------------+------------------+------------------+
p:| | TL_HASH(hi) | | HBLKDISPL(p) |
+------------------+----------------+------------------+------------------+
\-----------------------HBLKPTR(p)-------------------/
\------------hi-------------------/
\______ ________/ \________ _______/ \________ _______/
V V V
| | |
GC_top_index[] | | |
--- +--------------+ | | |
^ | | | | |
| | | | | |
TOP +--------------+<--+ | |
_SZ +-<| [] | * | |
(items)| +--------------+ if 0 < bi< HBLKSIZE | |
| | | | then large object | |
| | | | starts at the bi'th | |
v | | | HBLK before p. | i |
--- | +--------------+ | (word- |
v | aligned) |
bi= |GET_BI(p){->hash_link}->key==hi | |
v | |
| (bottom_index) \ scratch_alloc'd | |
| ( struct bi ) / by get_index() | |
--- +->+--------------+ | |
^ | | | |
^ | | | |
BOTTOM | | ha=GET_HDR_ADDR(p) | |
_SZ(items)+--------------+<----------------------+ +-------+
| +--<| index[] | |
| | +--------------+ GC_obj_map: v
| | | | from / +-+-+-----+-+-+-+-+ ---
v | | | GC_add < 0| | | | | | | | ^
--- | +--------------+ _map_entry \ +-+-+-----+-+-+-+-+ |
| | asc_link | +-+-+-----+-+-+-+-+ MAXOBJSZ
| +--------------+ +-->| | | j | | | | | +1
| | key | | +-+-+-----+-+-+-+-+ |
| +--------------+ | +-+-+-----+-+-+-+-+ |
| | hash_link | | | | | | | | | | v
| +--------------+ | +-+-+-----+-+-+-+-+ ---
| | |<--MAX_OFFSET--->|
| | (bytes)
HDR(p)| GC_find_header(p) | |<--MAP_ENTRIES-->|
| \ from | =HBLKSIZE/WORDSZ
| (hdr) (struct hblkhdr) / alloc_hdr() | (1024 on Alpha)
+-->+----------------------+ | (8/16 bits each)
GET_HDR(p)| word hb_sz (words) | |
+----------------------+ |
| struct hblk *hb_next | |
+----------------------+ |
|mark_proc hb_mark_proc| |
+----------------------+ |
| char * hb_map |>-------------+
+----------------------+
| ushort hb_obj_kind |
+----------------------+
| hb_last_reclaimed |
--- +----------------------+
^ | |
MARK_BITS| hb_marks[] | *if hdr is free, hb_sz + DISCARD_WORDS
_SZ(words)| | is the size of a heap chunk (struct hblk)
v | | of at least MININCR*HBLKSIZE bytes (below),
--- +----------------------+ otherwise, size of each object in chunk.
Dynamic data structures above are interleaved throughout the heap in blocks of
size MININCR * HBLKSIZE bytes as done by gc_scratch_alloc which cannot be
freed; free lists are used (e.g. alloc_hdr). HBLKs's below are collected.
(struct hblk)
--- +----------------------+ < HBLKSIZE --- --- DISCARD_
^ |garbage[DISCARD_WORDS]| aligned ^ ^ HDR_BYTES WORDS
| | | | v (bytes) (words)
| +-----hb_body----------+ < WORDSZ | --- ---
| | | aligned | ^ ^
| | Object 0 | | hb_sz |
| | | i |(word- (words)|
| | | (bytes)|aligned) v |
| + - - - - - - - - - - -+ --- | --- |
| | | ^ | ^ |
n * | | j (words) | hb_sz BODY_SZ
HBLKSIZE | Object 1 | v v | (words)
(bytes) | |--------------- v MAX_OFFSET
| + - - - - - - - - - - -+ --- (bytes)
| | | !All_INTERIOR_PTRS ^ |
| | | sets j only for hb_sz |
| | Object N | valid object offsets. | |
v | | All objects WORDSZ v v
--- +----------------------+ aligned. --- ---
DISCARD_WORDS is normally zero. Indeed the collector has not been tested
with another value in ages.

80
boehm-gc/doc/gc.man Normal file
View File

@ -0,0 +1,80 @@
.TH GC_MALLOC 1L "12 February 1996"
.SH NAME
GC_malloc, GC_malloc_atomic, GC_free, GC_realloc, GC_enable_incremental, GC_register_finalizer, GC_malloc_ignore_off_page, GC_malloc_atomic_ignore_off_page, GC_set_warn_proc \- Garbage collecting malloc replacement
.SH SYNOPSIS
#include "gc.h"
.br
# define malloc(n) GC_malloc(n)
.br
... malloc(...) ...
.br
.sp
cc ... gc.a
.LP
.SH DESCRIPTION
.I GC_malloc
and
.I GC_free
are plug-in replacements for standard malloc and free. However,
.I
GC_malloc
will attempt to reclaim inaccessible space automatically by invoking a conservative garbage collector at appropriate points. The collector traverses all data structures accessible by following pointers from the machines registers, stack(s), data, and bss segments. Inaccessible structures will be reclaimed. A machine word is considered to be a valid pointer if it is an address inside an object allocated by
.I
GC_malloc
or friends.
.LP
See the documentation in the include file gc_cpp.h for an alternate, C++ specific interface to the garbage collector.
.LP
Unlike the standard implementations of malloc,
.I
GC_malloc
clears the newly allocated storage.
.I
GC_malloc_atomic
does not. Furthermore, it informs the collector that the resulting object will never contain any pointers, and should therefore not be scanned by the collector.
.LP
.I
GC_free
can be used to deallocate objects, but its use is optional, and generally discouraged.
.I
GC_realloc
has the standard realloc semantics. It preserves pointer-free-ness.
.I
GC_register_finalizer
allows for registration of functions that are invoked when an object becomes inaccessible.
.LP
The garbage collector tries to avoid allocating memory at locations that already appear to be referenced before allocation. (Such apparent ``pointers'' are usually large integers and the like that just happen to look like an address.) This may make it hard to allocate very large objects. An attempt to do so may generate a warning.
.LP
.I
GC_malloc_ignore_off_page
and
.I
GC_malloc_atomic_ignore_off_page
inform the collector that the client code will always maintain a pointer to near the beginning of the object (within the first 512 bytes), and that pointers beyond that can be ignored by the collector. This makes it much easier for the collector to place large objects. These are recommended for large object allocation. (Objects expected to be larger than about 100KBytes should be allocated this way.)
.LP
It is also possible to use the collector to find storage leaks in programs destined to be run with standard malloc/free. The collector can be compiled for thread-safe operation. Unlike standard malloc, it is safe to call malloc after a previous malloc call was interrupted by a signal, provided the original malloc call is not resumed.
.LP
The collector may, on rare occasion produce warning messages. On UNIX machines these appear on stderr. Warning messages can be filtered, redirected, or ignored with
.I
GC_set_warn_proc.
This is recommended for production code. See gc.h for details.
.LP
Debugging versions of many of the above routines are provided as macros. Their names are identical to the above, but consist of all capital letters. If GC_DEBUG is defined before gc.h is included, these routines do additional checking, and allow the leak detecting version of the collector to produce slightly more useful output. Without GC_DEBUG defined, they behave exactly like the lower-case versions.
.LP
On some machines, collection will be performed incrementally after a call to
.I
GC_enable_incremental.
This may temporarily write protect pages in the heap. See the README file for more information on how this interacts with system calls that write to the heap.
.LP
Other facilities not discussed here include limited facilities to support incremental collection on machines without appropriate VM support, provisions for providing more explicit object layout information to the garbage collector, more direct support for ``weak'' pointers, support for ``abortable'' garbage collections during idle time, etc.
.LP
.SH "SEE ALSO"
The README and gc.h files in the distribution. More detailed definitions of the functions exported by the collector are given there. (The above list is not complete.)
.LP
Boehm, H., and M. Weiser, "Garbage Collection in an Uncooperative Environment",
\fISoftware Practice & Experience\fP, September 1988, pp. 807-820.
.LP
The malloc(3) man page.
.LP
.SH AUTHOR
Hans-J. Boehm (boehm@parc.xerox.com). Some of the code was written by others, most notably Alan Demers.

2
boehm-gc/gc_cpp.cpp Normal file
View File

@ -0,0 +1,2 @@
// Visual C++ seems to prefer a .cpp extension to .cc
#include "gc_cpp.cc"

96
boehm-gc/gc_dlopen.c Normal file
View File

@ -0,0 +1,96 @@
/*
* Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 1997 by Silicon Graphics. All rights reserved.
* Copyright (c) 2000 by Hewlett-Packard Company. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
* Original author: Bill Janssen
* Heavily modified by Hans Boehm and others
*/
/*
* This used to be in dyn_load.c. It was extracted into a separate file
* to avoid having to link against libdl.{a,so} if the client doesn't call
* dlopen. -HB
*/
#include "private/gc_priv.h"
# if defined(LINUX_THREADS) || defined(SOLARIS_THREADS) \
|| defined(HPUX_THREADS) || defined(IRIX_THREADS)
# if defined(dlopen) && !defined(GC_USE_LD_WRAP)
/* To support various threads pkgs, gc.h interposes on dlopen by */
/* defining "dlopen" to be "GC_dlopen", which is implemented below. */
/* However, both GC_FirstDLOpenedLinkMap() and GC_dlopen() use the */
/* real system dlopen() in their implementation. We first remove */
/* gc.h's dlopen definition and restore it later, after GC_dlopen(). */
# undef dlopen
# endif
/* Make sure we're not in the middle of a collection, and make */
/* sure we don't start any. Returns previous value of GC_dont_gc. */
/* This is invoked prior to a dlopen call to avoid synchronization */
/* issues. We can't just acquire the allocation lock, since startup */
/* code in dlopen may try to allocate. */
/* This solution risks heap growth in the presence of many dlopen */
/* calls in either a multithreaded environment, or if the library */
/* initialization code allocates substantial amounts of GC'ed memory. */
/* But I don't know of a better solution. */
/* This can still deadlock if the client explicitly starts a GC */
/* during the dlopen. He shouldn't do that. */
static GC_bool disable_gc_for_dlopen()
{
GC_bool result;
LOCK();
result = GC_dont_gc;
while (GC_incremental && GC_collection_in_progress()) {
GC_collect_a_little_inner(1000);
}
GC_dont_gc = TRUE;
UNLOCK();
return(result);
}
/* Redefine dlopen to guarantee mutual exclusion with */
/* GC_register_dynamic_libraries. */
/* Should probably happen for other operating systems, too. */
#include <dlfcn.h>
#ifdef GC_USE_LD_WRAP
void * __wrap_dlopen(const char *path, int mode)
#else
void * GC_dlopen(path, mode)
GC_CONST char * path;
int mode;
#endif
{
void * result;
GC_bool dont_gc_save;
# ifndef USE_PROC_FOR_LIBRARIES
dont_gc_save = disable_gc_for_dlopen();
# endif
# ifdef GC_USE_LD_WRAP
result = (void *)__real_dlopen(path, mode);
# else
result = dlopen(path, mode);
# endif
# ifndef USE_PROC_FOR_LIBRARIES
GC_dont_gc = dont_gc_save;
# endif
return(result);
}
# endif /* LINUX_THREADS || SOLARIS_THREADS || ... */

View File

@ -0,0 +1,30 @@
#ifndef GC_AMIGA_REDIRECTS_H
# define GC_AMIGA_REDIRECTS_H
# if ( defined(_AMIGA) && !defined(GC_AMIGA_MAKINGLIB) )
extern void *GC_amiga_realloc(void *old_object,size_t new_size_in_bytes);
# define GC_realloc(a,b) GC_amiga_realloc(a,b)
extern void GC_amiga_set_toany(void (*func)(void));
extern int GC_amiga_free_space_divisor_inc;
extern void *(*GC_amiga_allocwrapper_do) \
(size_t size,void *(*AllocFunction)(size_t size2));
# define GC_malloc(a) \
(*GC_amiga_allocwrapper_do)(a,GC_malloc)
# define GC_malloc_atomic(a) \
(*GC_amiga_allocwrapper_do)(a,GC_malloc_atomic)
# define GC_malloc_uncollectable(a) \
(*GC_amiga_allocwrapper_do)(a,GC_malloc_uncollectable)
# define GC_malloc_stubborn(a) \
(*GC_amiga_allocwrapper_do)(a,GC_malloc_stubborn)
# define GC_malloc_atomic_uncollectable(a) \
(*GC_amiga_allocwrapper_do)(a,GC_malloc_atomic_uncollectable)
# define GC_malloc_ignore_off_page(a) \
(*GC_amiga_allocwrapper_do)(a,GC_malloc_ignore_off_page)
# define GC_malloc_atomic_ignore_off_page(a) \
(*GC_amiga_allocwrapper_do)(a,GC_malloc_atomic_ignore_off_page)
# endif /* _AMIGA && !GC_AMIGA_MAKINGLIB */
#endif /* GC_AMIGA_REDIRECTS_H */

View File

@ -0,0 +1,65 @@
/*
* This is a simple API to implement pointer back tracing, i.e.
* to answer questions such as "who is pointing to this" or
* "why is this object being retained by the collector"
*
* This API assumes that we have an ANSI C compiler.
*
* Most of these calls yield useful information on only after
* a garbage collection. Usually the client will first force
* a full collection and then gather information, preferably
* before much intervening allocation.
*
* The implementation of the interface is only about 99.9999%
* correct. It is intended to be good enough for profiling,
* but is not intended to be used with production code.
*
* Results are likely to be much more useful if all allocation is
* accomplished through the debugging allocators.
*
* The implementation idea is due to A. Demers.
*/
#ifndef GC_BACKPTR_H
#define GC_BACKPTR_H
/* Store information about the object referencing dest in *base_p */
/* and *offset_p. */
/* If multiple objects or roots point to dest, the one reported */
/* will be the last on used by the garbage collector to trace the */
/* object. */
/* source is root ==> *base_p = address, *offset_p = 0 */
/* source is heap object ==> *base_p != 0, *offset_p = offset */
/* Returns 1 on success, 0 if source couldn't be determined. */
/* Dest can be any address within a heap object. */
typedef enum { GC_UNREFERENCED, /* No reference info available. */
GC_NO_SPACE, /* Dest not allocated with debug alloc */
GC_REFD_FROM_ROOT, /* Referenced directly by root *base_p */
GC_REFD_FROM_REG, /* Referenced from a register, i.e. */
/* a root without an address. */
GC_REFD_FROM_HEAP, /* Referenced from another heap obj. */
GC_FINALIZER_REFD /* Finalizable and hence accessible. */
} GC_ref_kind;
GC_ref_kind GC_get_back_ptr_info(void *dest, void **base_p, size_t *offset_p);
/* Generate a random heap address. */
/* The resulting address is in the heap, but */
/* not necessarily inside a valid object. */
void * GC_generate_random_heap_address(void);
/* Generate a random address inside a valid marked heap object. */
void * GC_generate_random_valid_address(void);
/* Force a garbage collection and generate a backtrace from a */
/* random heap address. */
/* This uses the GC logging mechanism (GC_printf) to produce */
/* output. It can often be called from a debugger. The */
/* source in dbg_mlc.c also serves as a sample client. */
void GC_generate_random_backtrace(void);
/* Print a backtrace from a specific address. Used by the */
/* above. The client should call GC_gcollect() immediately */
/* before invocation. */
void GC_print_backtrace(void *);
#endif /* GC_BACKPTR_H */

View File

@ -0,0 +1,85 @@
/*
* Copyright (c) 2000 by Hewlett-Packard Company. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*/
/*
* Interface for thread local allocation. Memory obtained
* this way can be used by all threads, as though it were obtained
* from an allocator like GC_malloc. The difference is that GC_local_malloc
* counts the number of allocations of a given size from the current thread,
* and uses GC_malloc_many to perform the allocations once a threashold
* is exceeded. Thus far less synchronization may be needed.
* Allocation of known large objects should not use this interface.
* This interface is designed primarily for fast allocation of small
* objects on multiprocessors, e.g. for a JVM running on an MP server.
*
* If this file is included with GC_GCJ_SUPPORT defined, GCJ-style
* bitmap allocation primitives will also be included.
*
* If this file is included with GC_REDIRECT_TO_LOCAL defined, then
* GC_MALLOC, GC_MALLOC_ATOMIC, and possibly GC_GCJ_MALLOC will
* be redefined to use the thread local allocatoor.
*
* The interface is available only if the collector is built with
* -DTHREAD_LOCAL_ALLOC, which is currently supported only on Linux.
*
* The debugging allocators use standard, not thread-local allocation.
*/
#ifndef GC_LOCAL_ALLOC_H
#define GC_LOCAL_ALLOC_H
#ifndef _GC_H
# include "gc.h"
#endif
#if defined(GC_GCJ_SUPPORT) && !defined(GC_GCJ_H)
# include "gc_gcj.h"
#endif
/* We assume ANSI C for this interface. */
GC_PTR GC_local_malloc(size_t bytes);
GC_PTR GC_local_malloc_atomic(size_t bytes);
#if defined(GC_GCJ_SUPPORT)
GC_PTR GC_local_gcj_malloc(size_t bytes,
void * ptr_to_struct_containing_descr);
#endif
# ifdef GC_DEBUG
# define GC_LOCAL_MALLOC(s) GC_debug_malloc(s,GC_EXTRAS)
# define GC_LOCAL_MALLOC_ATOMIC(s) GC_debug_malloc_atomic(s,GC_EXTRAS)
# ifdef GC_GCJ_SUPPORT
# define GC_LOCAL_GCJ_MALLOC(s,d) GC_debug_gcj_malloc(s,d,GC_EXTRAS)
# endif
# else
# define GC_LOCAL_MALLOC(s) GC_local_malloc(s)
# define GC_LOCAL_MALLOC_ATOMIC(s) GC_local_malloc_atomic(s)
# ifdef GC_GCJ_SUPPORT
# define GC_LOCAL_GCJ_MALLOC(s,d) GC_local_gcj_malloc(s,d)
# endif
# endif
# ifdef GC_REDIRECT_TO_LOCAL
# undef GC_MALLOC
# define GC_MALLOC(s) GC_LOCAL_MALLOC(s)
# undef GC_MALLOC_ATOMIC
# define GC_MALLOC_ATOMIC(s) GC_LOCAL_MALLOC_ATOMIC(s)
# ifdef GC_GCJ_SUPPORT
# undef GC_GCJ_MALLOC
# define GC_GCJ_MALLOC(s,d) GC_LOCAL_GCJ_MALLOC(s,d)
# endif
# endif
#endif /* GC_LOCAL_ALLOC_H */

145
boehm-gc/include/gc_mark.h Normal file
View File

@ -0,0 +1,145 @@
/*
* Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 2001 by Hewlett-Packard Company. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
/*
* This contains interfaces to the GC marker that are likely to be useful to
* clients that provide detailed heap layout information to the collector.
* This interface should not be used by normal C or C++ clients.
* It will be useful to runtimes for other languages.
*
* Note that this file is not "namespace-clean", i.e. it introduces names
* not prefixed with GC_, which may collide with the client's names. It
* should be included only in those few places that directly provide
* information to the collector.
*/
#ifndef GC_MARK_H
# define GC_MARK_H
# ifndef GC_H
# include "gc.h"
# endif
/* A client supplied mark procedure. Returns new mark stack pointer. */
/* Primary effect should be to push new entries on the mark stack. */
/* Mark stack pointer values are passed and returned explicitly. */
/* Global variables decribing mark stack are not necessarily valid. */
/* (This usually saves a few cycles by keeping things in registers.) */
/* Assumed to scan about GC_PROC_BYTES on average. If it needs to do */
/* much more work than that, it should do it in smaller pieces by */
/* pushing itself back on the mark stack. */
/* Note that it should always do some work (defined as marking some */
/* objects) before pushing more than one entry on the mark stack. */
/* This is required to ensure termination in the event of mark stack */
/* overflows. */
/* This procedure is always called with at least one empty entry on the */
/* mark stack. */
/* Currently we require that mark procedures look for pointers in a */
/* subset of the places the conservative marker would. It must be safe */
/* to invoke the normal mark procedure instead. */
/* WARNING: Such a mark procedure may be invoked on an unused object */
/* residing on a free list. Such objects are cleared, except for a */
/* free list link field in the first word. Thus mark procedures may */
/* not count on the presence of a type descriptor, and must handle this */
/* case correctly somehow. */
# define GC_PROC_BYTES 100
struct GC_ms_entry;
typedef struct GC_ms_entry * (*GC_mark_proc) GC_PROTO((
GC_word * addr, struct GC_ms_entry * mark_stack_ptr,
struct GC_ms_entry * mark_stack_limit, GC_word env));
# define GC_LOG_MAX_MARK_PROCS 6
# define GC_MAX_MARK_PROCS (1 << GC_LOG_MAX_MARK_PROCS)
/* In a few cases it's necessary to assign statically known indices to */
/* certain mark procs. Thus we reserve a few for well known clients. */
/* (This is necessary if mark descriptors are compiler generated.) */
#define GC_RESERVED_MARK_PROCS 8
# define GC_GCJ_RESERVED_MARK_PROC_INDEX 0
/* Object descriptors on mark stack or in objects. Low order two */
/* bits are tags distinguishing among the following 4 possibilities */
/* for the high order 30 bits. */
#define GC_DS_TAG_BITS 2
#define GC_DS_TAGS ((1 << GC_DS_TAG_BITS) - 1)
#define GC_DS_LENGTH 0 /* The entire word is a length in bytes that */
/* must be a multiple of 4. */
#define GC_DS_BITMAP 1 /* 30 (62) bits are a bitmap describing pointer */
/* fields. The msb is 1 iff the first word */
/* is a pointer. */
/* (This unconventional ordering sometimes */
/* makes the marker slightly faster.) */
/* Zeroes indicate definite nonpointers. Ones */
/* indicate possible pointers. */
/* Only usable if pointers are word aligned. */
#define GC_DS_PROC 2
/* The objects referenced by this object can be */
/* pushed on the mark stack by invoking */
/* PROC(descr). ENV(descr) is passed as the */
/* last argument. */
# define GC_MAKE_PROC(proc_index, env) \
(((((env) << GC_LOG_MAX_MARK_PROCS) \
| (proc_index)) << GC_DS_TAG_BITS) | GC_DS_PROC)
#define GC_DS_PER_OBJECT 3 /* The real descriptor is at the */
/* byte displacement from the beginning of the */
/* object given by descr & ~DS_TAGS */
/* If the descriptor is negative, the real */
/* descriptor is at (*<object_start>) - */
/* (descr & ~DS_TAGS) - GC_INDIR_PER_OBJ_BIAS */
/* The latter alternative can be used if each */
/* object contains a type descriptor in the */
/* first word. */
/* Note that in multithreaded environments */
/* per object descriptors maust be located in */
/* either the first two or last two words of */
/* the object, since only those are guaranteed */
/* to be cleared while the allocation lock is */
/* held. */
#define GC_INDIR_PER_OBJ_BIAS 0x10
extern GC_PTR GC_least_plausible_heap_addr;
extern GC_PTR GC_greatest_plausible_heap_addr;
/* Bounds on the heap. Guaranteed valid */
/* Likely to include future heap expansion. */
/* Handle nested references in a custom mark procedure. */
/* Check if obj is a valid object. If so, ensure that it is marked. */
/* If it was not previously marked, push its contents onto the mark */
/* stack for future scanning. The object will then be scanned using */
/* its mark descriptor. */
/* Returns the new mark stack pointer. */
/* Handles mark stack overflows correctly. */
/* Since this marks first, it makes progress even if there are mark */
/* stack overflows. */
/* Src is the address of the pointer to obj, which is used only */
/* for back pointer-based heap debugging. */
/* It is strongly recommended that most objects be handled without mark */
/* procedures, e.g. with bitmap descriptors, and that mark procedures */
/* be reserved for exceptional cases. That will ensure that */
/* performance of this call is not extremely performance critical. */
/* (Otherwise we would need to inline GC_mark_and_push completely, */
/* which would tie the client code to a fixed colllector version.) */
struct GC_ms_entry *GC_mark_and_push
GC_PROTO((GC_PTR obj,
struct GC_ms_entry * mark_stack_ptr,
struct GC_ms_entry * mark_stack_limit, GC_PTR *src));
#define GC_MARK_AND_PUSH(obj, msp, lim, src) \
(((GC_word)obj >= (GC_word)GC_least_plausible_heap_addr && \
(GC_word)obj <= (GC_word)GC_greatest_plausible_heap_addr)? \
GC_mark_and_push(obj, msp, lim, src) : \
msp)
#endif /* GC_MARK_H */

View File

@ -0,0 +1,69 @@
/* Our pthread support normally needs to intercept a number of thread */
/* calls. We arrange to do that here, if appropriate. */
#ifndef GC_PTHREAD_REDIRECTS_H
#define GC_PTHREAD_REDIRECTS_H
#if defined(GC_SOLARIS_THREADS)
/* We need to intercept calls to many of the threads primitives, so */
/* that we can locate thread stacks and stop the world. */
/* Note also that the collector cannot see thread specific data. */
/* Thread specific data should generally consist of pointers to */
/* uncollectable objects (allocated with GC_malloc_uncollectable, */
/* not the system malloc), which are deallocated using the destructor */
/* facility in thr_keycreate. Alternatively, keep a redundant pointer */
/* to thread specific data on the thread stack. */
# include <thread.h>
int GC_thr_create(void *stack_base, size_t stack_size,
void *(*start_routine)(void *), void *arg, long flags,
thread_t *new_thread);
int GC_thr_join(thread_t wait_for, thread_t *departed, void **status);
int GC_thr_suspend(thread_t target_thread);
int GC_thr_continue(thread_t target_thread);
void * GC_dlopen(const char *path, int mode);
# define thr_create GC_thr_create
# define thr_join GC_thr_join
# define thr_suspend GC_thr_suspend
# define thr_continue GC_thr_continue
#endif /* GC_SOLARIS_THREADS */
#if defined(GC_SOLARIS_PTHREADS)
# include <pthread.h>
# include <signal.h>
extern int GC_pthread_create(pthread_t *new_thread,
const pthread_attr_t *attr,
void * (*thread_execp)(void *), void *arg);
extern int GC_pthread_join(pthread_t wait_for, void **status);
# define pthread_join GC_pthread_join
# define pthread_create GC_pthread_create
#endif
#if defined(GC_SOLARIS_PTHREADS) || defined(GC_SOLARIS_THREADS)
# define dlopen GC_dlopen
#endif /* SOLARIS_THREADS || SOLARIS_PTHREADS */
#if !defined(GC_USE_LD_WRAP) && \
(defined(GC_IRIX_THREADS) || defined(GC_LINUX_THREADS) \
|| defined(GC_HPUX_THREADS) || defined(GC_OSF1_THREADS))
/* We treat these similarly. */
# include <pthread.h>
# include <signal.h>
int GC_pthread_create(pthread_t *new_thread,
const pthread_attr_t *attr,
void *(*start_routine)(void *), void *arg);
int GC_pthread_sigmask(int how, const sigset_t *set, sigset_t *oset);
int GC_pthread_join(pthread_t thread, void **retval);
int GC_pthread_detach(pthread_t thread);
# define pthread_create GC_pthread_create
# define pthread_sigmask GC_pthread_sigmask
# define pthread_join GC_pthread_join
# define pthread_detach GC_pthread_detach
# define dlopen GC_dlopen
#endif /* GC_xxxxx_THREADS */
#endif /* GC_PTHREAD_REDIRECTS_H */

View File

@ -0,0 +1,132 @@
/*
* Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-1995 by Xerox Corporation. All rights reserved.
* Copyright (c) 1997 by Silicon Graphics. All rights reserved.
* Copyright (c) 1999 by Hewlett-Packard Company. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*/
/*
* This is mostly an internal header file. Typical clients should
* not use it. Clients that define their own object kinds with
* debugging allocators will probably want to include this, however.
* No attempt is made to keep the namespace clean. This should not be
* included from header filrd that are frequently included by clients.
*/
#ifndef _DBG_MLC_H
#define _DBG_MLC_H
# define I_HIDE_POINTERS
# include "gc_priv.h"
# ifdef KEEP_BACK_PTRS
# include "gc_backptr.h"
# endif
# define START_FLAG ((word)0xfedcedcb)
# define END_FLAG ((word)0xbcdecdef)
/* Stored both one past the end of user object, and one before */
/* the end of the object as seen by the allocator. */
/* Object header */
typedef struct {
# ifdef KEEP_BACK_PTRS
GC_hidden_pointer oh_back_ptr;
/* We make sure that we only store even valued */
/* pointers here, so that the hidden version has */
/* the least significant bit set. We never */
/* overwrite a value with the least significant */
/* bit clear, thus ensuring that we never overwrite */
/* a free list link field. */
/* The following are special back pointer values. */
/* Note that the "hidden" (i.e. bitwise */
/* complemented version) of these is actually */
/* stored. */
# define NOT_MARKED (ptr_t)(0)
# define MARKED_FOR_FINALIZATION (ptr_t)(2)
/* Object was marked because it is finalizable. */
# define MARKED_FROM_REGISTER (ptr_t)(4)
/* Object was marked from a rgister. Hence the */
/* source of the reference doesn't have an address. */
# if ALIGNMENT == 1
/* Fudge back pointer to be even. */
# define HIDE_BACK_PTR(p) HIDE_POINTER(~1 & (GC_word)(p))
# else
# define HIDE_BACK_PTR(p) HIDE_POINTER(p)
# endif
# ifdef ALIGN_DOUBLE
word oh_dummy;
# endif
# endif
char * oh_string; /* object descriptor string */
word oh_int; /* object descriptor integers */
# ifdef NEED_CALLINFO
struct callinfo oh_ci[NFRAMES];
# endif
# ifndef SHORT_DBG_HDRS
word oh_sz; /* Original malloc arg. */
word oh_sf; /* start flag */
# endif /* SHORT_DBG_HDRS */
} oh;
/* The size of the above structure is assumed not to dealign things, */
/* and to be a multiple of the word length. */
#define DEBUG_BYTES (sizeof (oh) + sizeof (word))
#define USR_PTR_FROM_BASE(p) ((ptr_t)(p) + sizeof(oh))
/* There is no reason to ever add a byte at the end explicitly, since we */
/* already add a guard word. */
#undef ROUNDED_UP_WORDS
#define ROUNDED_UP_WORDS(n) BYTES_TO_WORDS((n) + WORDS_TO_BYTES(1) - 1)
#ifdef SAVE_CALL_CHAIN
# define ADD_CALL_CHAIN(base, ra) GC_save_callers(((oh *)(base)) -> oh_ci)
# define PRINT_CALL_CHAIN(base) GC_print_callers(((oh *)(base)) -> oh_ci)
#else
# ifdef GC_ADD_CALLER
# define ADD_CALL_CHAIN(base, ra) ((oh *)(base)) -> oh_ci[0].ci_pc = (ra)
# define PRINT_CALL_CHAIN(base) GC_print_callers(((oh *)(base)) -> oh_ci)
# else
# define ADD_CALL_CHAIN(base, ra)
# define PRINT_CALL_CHAIN(base)
# endif
#endif
# ifdef GC_ADD_CALLER
# define OPT_RA ra,
# else
# define OPT_RA
# endif
/* Check whether object with base pointer p has debugging info */
/* p is assumed to point to a legitimate object in our part */
/* of the heap. */
#ifdef SHORT_DBG_HDRS
# define GC_has_other_debug_info(p) TRUE
#else
GC_bool GC_has_other_debug_info(/* p */);
#endif
#ifdef KEEP_BACK_PTRS
# define GC_HAS_DEBUG_INFO(p) \
((((oh *)p)->oh_back_ptr & 1) && GC_has_other_debug_info(p))
#else
# define GC_HAS_DEBUG_INFO(p) GC_has_other_debug_info(p)
#endif
/* Store debugging info into p. Return displaced pointer. */
/* Assumes we don't hold allocation lock. */
ptr_t GC_store_debug_info(/* p, sz, string, integer */);
#endif /* _DBG_MLC_H */

View File

@ -0,0 +1,480 @@
/*
* Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 1996-1999 by Silicon Graphics. All rights reserved.
* Copyright (c) 1999 by Hewlett-Packard Company. All rights reserved.
*
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*/
#ifndef GC_LOCKS_H
#define GC_LOCKS_H
/*
* Mutual exclusion between allocator/collector routines.
* Needed if there is more than one allocator thread.
* FASTLOCK() is assumed to try to acquire the lock in a cheap and
* dirty way that is acceptable for a few instructions, e.g. by
* inhibiting preemption. This is assumed to have succeeded only
* if a subsequent call to FASTLOCK_SUCCEEDED() returns TRUE.
* FASTUNLOCK() is called whether or not FASTLOCK_SUCCEEDED().
* If signals cannot be tolerated with the FASTLOCK held, then
* FASTLOCK should disable signals. The code executed under
* FASTLOCK is otherwise immune to interruption, provided it is
* not restarted.
* DCL_LOCK_STATE declares any local variables needed by LOCK and UNLOCK
* and/or DISABLE_SIGNALS and ENABLE_SIGNALS and/or FASTLOCK.
* (There is currently no equivalent for FASTLOCK.)
*
* In the PARALLEL_MARK case, we also need to define a number of
* other inline finctions here:
* GC_bool GC_compare_and_exchange( volatile GC_word *addr,
* GC_word old, GC_word new )
* GC_word GC_atomic_add( volatile GC_word *addr, GC_word how_much )
* void GC_memory_barrier( )
*
*/
# ifdef THREADS
# ifdef PCR_OBSOLETE /* Faster, but broken with multiple lwp's */
# include "th/PCR_Th.h"
# include "th/PCR_ThCrSec.h"
extern struct PCR_Th_MLRep GC_allocate_ml;
# define DCL_LOCK_STATE PCR_sigset_t GC_old_sig_mask
# define LOCK() PCR_Th_ML_Acquire(&GC_allocate_ml)
# define UNLOCK() PCR_Th_ML_Release(&GC_allocate_ml)
# define UNLOCK() PCR_Th_ML_Release(&GC_allocate_ml)
# define FASTLOCK() PCR_ThCrSec_EnterSys()
/* Here we cheat (a lot): */
# define FASTLOCK_SUCCEEDED() (*(int *)(&GC_allocate_ml) == 0)
/* TRUE if nobody currently holds the lock */
# define FASTUNLOCK() PCR_ThCrSec_ExitSys()
# endif
# ifdef PCR
# include <base/PCR_Base.h>
# include <th/PCR_Th.h>
extern PCR_Th_ML GC_allocate_ml;
# define DCL_LOCK_STATE \
PCR_ERes GC_fastLockRes; PCR_sigset_t GC_old_sig_mask
# define LOCK() PCR_Th_ML_Acquire(&GC_allocate_ml)
# define UNLOCK() PCR_Th_ML_Release(&GC_allocate_ml)
# define FASTLOCK() (GC_fastLockRes = PCR_Th_ML_Try(&GC_allocate_ml))
# define FASTLOCK_SUCCEEDED() (GC_fastLockRes == PCR_ERes_okay)
# define FASTUNLOCK() {\
if( FASTLOCK_SUCCEEDED() ) PCR_Th_ML_Release(&GC_allocate_ml); }
# endif
# ifdef SRC_M3
extern GC_word RT0u__inCritical;
# define LOCK() RT0u__inCritical++
# define UNLOCK() RT0u__inCritical--
# endif
# ifdef SOLARIS_THREADS
# include <thread.h>
# include <signal.h>
extern mutex_t GC_allocate_ml;
# define LOCK() mutex_lock(&GC_allocate_ml);
# define UNLOCK() mutex_unlock(&GC_allocate_ml);
# endif
/* Try to define GC_TEST_AND_SET and a matching GC_CLEAR for spin lock */
/* acquisition and release. We need this for correct operation of the */
/* incremental GC. */
# ifdef __GNUC__
# if defined(I386)
inline static int GC_test_and_set(volatile unsigned int *addr) {
int oldval;
/* Note: the "xchg" instruction does not need a "lock" prefix */
__asm__ __volatile__("xchgl %0, %1"
: "=r"(oldval), "=m"(*(addr))
: "0"(1), "m"(*(addr)) : "memory");
return oldval;
}
# define GC_TEST_AND_SET_DEFINED
# endif
# if defined(IA64)
inline static int GC_test_and_set(volatile unsigned int *addr) {
long oldval, n = 1;
__asm__ __volatile__("xchg4 %0=%1,%2"
: "=r"(oldval), "=m"(*addr)
: "r"(n), "1"(*addr) : "memory");
return oldval;
}
# define GC_TEST_AND_SET_DEFINED
/* Should this handle post-increment addressing?? */
inline static void GC_clear(volatile unsigned int *addr) {
__asm__ __volatile__("st4.rel %0=r0" : "=m" (*addr) : : "memory");
}
# define GC_CLEAR_DEFINED
# endif
# ifdef SPARC
inline static int GC_test_and_set(volatile unsigned int *addr) {
int oldval;
__asm__ __volatile__("ldstub %1,%0"
: "=r"(oldval), "=m"(*addr)
: "m"(*addr) : "memory");
return oldval;
}
# define GC_TEST_AND_SET_DEFINED
# endif
# ifdef M68K
/* Contributed by Tony Mantler. I'm not sure how well it was */
/* tested. */
inline static int GC_test_and_set(volatile unsigned int *addr) {
char oldval; /* this must be no longer than 8 bits */
/* The return value is semi-phony. */
/* 'tas' sets bit 7 while the return */
/* value pretends bit 0 was set */
__asm__ __volatile__(
"tas %1@; sne %0; negb %0"
: "=d" (oldval)
: "a" (addr) : "memory");
return oldval;
}
# define GC_TEST_AND_SET_DEFINED
# endif
# if defined(POWERPC)
inline static int GC_test_and_set(volatile unsigned int *addr) {
int oldval;
int temp = 1; // locked value
__asm__ __volatile__(
"1:\tlwarx %0,0,%3\n" // load and reserve
"\tcmpwi %0, 0\n" // if load is
"\tbne 2f\n" // non-zero, return already set
"\tstwcx. %2,0,%1\n" // else store conditional
"\tbne- 1b\n" // retry if lost reservation
"2:\t\n" // oldval is zero if we set
: "=&r"(oldval), "=p"(addr)
: "r"(temp), "1"(addr)
: "memory");
return (int)oldval;
}
# define GC_TEST_AND_SET_DEFINED
inline static void GC_clear(volatile unsigned int *addr) {
__asm__ __volatile__("eieio" ::: "memory");
*(addr) = 0;
}
# define GC_CLEAR_DEFINED
# endif
# if defined(ALPHA)
inline static int GC_test_and_set(volatile unsigned int * addr)
{
unsigned long oldvalue;
unsigned long temp;
__asm__ __volatile__(
"1: ldl_l %0,%1\n"
" and %0,%3,%2\n"
" bne %2,2f\n"
" xor %0,%3,%0\n"
" stl_c %0,%1\n"
" beq %0,3f\n"
" mb\n"
"2:\n"
".section .text2,\"ax\"\n"
"3: br 1b\n"
".previous"
:"=&r" (temp), "=m" (*addr), "=&r" (oldvalue)
:"Ir" (1), "m" (*addr)
:"memory");
return oldvalue;
}
# define GC_TEST_AND_SET_DEFINED
/* Should probably also define GC_clear, since it needs */
/* a memory barrier ?? */
# endif /* ALPHA */
# ifdef ARM32
inline static int GC_test_and_set(volatile unsigned int *addr) {
int oldval;
/* SWP on ARM is very similar to XCHG on x86. Doesn't lock the
* bus because there are no SMP ARM machines. If/when there are,
* this code will likely need to be updated. */
/* See linuxthreads/sysdeps/arm/pt-machine.h in glibc-2.1 */
__asm__ __volatile__("swp %0, %1, [%2]"
: "=r"(oldval)
: "r"(1), "r"(addr)
: "memory");
return oldval;
}
# define GC_TEST_AND_SET_DEFINED
# endif /* ARM32 */
# endif /* __GNUC__ */
# if (defined(ALPHA) && !defined(__GNUC__))
# define GC_test_and_set(addr) __cxx_test_and_set_atomic(addr, 1)
# define GC_TEST_AND_SET_DEFINED
# endif
# if defined(MSWIN32)
# define GC_test_and_set(addr) InterlockedExchange((LPLONG)addr,1)
# define GC_TEST_AND_SET_DEFINED
# endif
# ifdef MIPS
# if __mips < 3 || !(defined (_ABIN32) || defined(_ABI64)) \
|| !defined(_COMPILER_VERSION) || _COMPILER_VERSION < 700
# define GC_test_and_set(addr, v) test_and_set(addr,v)
# else
# define GC_test_and_set(addr, v) __test_and_set(addr,v)
# define GC_clear(addr) __lock_release(addr);
# define GC_CLEAR_DEFINED
# endif
# define GC_TEST_AND_SET_DEFINED
# endif /* MIPS */
# if 0 /* defined(HP_PA) */
/* The official recommendation seems to be to not use ldcw from */
/* user mode. Since multithreaded incremental collection doesn't */
/* work anyway on HP_PA, this shouldn't be a major loss. */
/* "set" means 0 and "clear" means 1 here. */
# define GC_test_and_set(addr) !GC_test_and_clear(addr);
# define GC_TEST_AND_SET_DEFINED
# define GC_clear(addr) GC_noop1(addr); *(volatile unsigned int *)addr = 1;
/* The above needs a memory barrier! */
# define GC_CLEAR_DEFINED
# endif
# if defined(GC_TEST_AND_SET_DEFINED) && !defined(GC_CLEAR_DEFINED)
# ifdef __GNUC__
inline static void GC_clear(volatile unsigned int *addr) {
/* Try to discourage gcc from moving anything past this. */
__asm__ __volatile__(" " : : : "memory");
*(addr) = 0;
}
# else
/* The function call in the following should prevent the */
/* compiler from moving assignments to below the UNLOCK. */
# define GC_clear(addr) GC_noop1((word)(addr)); \
*((volatile unsigned int *)(addr)) = 0;
# endif
# define GC_CLEAR_DEFINED
# endif /* !GC_CLEAR_DEFINED */
# if !defined(GC_TEST_AND_SET_DEFINED)
# define USE_PTHREAD_LOCKS
# endif
# if defined(LINUX_THREADS) || defined(OSF1_THREADS) \
|| defined(HPUX_THREADS)
# define NO_THREAD (pthread_t)(-1)
# include <pthread.h>
# if defined(PARALLEL_MARK)
/* We need compare-and-swap to update mark bits, where it's */
/* performance critical. If USE_MARK_BYTES is defined, it is */
/* no longer needed for this purpose. However we use it in */
/* either case to implement atomic fetch-and-add, though that's */
/* less performance critical, and could perhaps be done with */
/* a lock. */
# if defined(GENERIC_COMPARE_AND_SWAP)
/* Probably not useful, except for debugging. */
/* We do use GENERIC_COMPARE_AND_SWAP on PA_RISC, but we */
/* minimize its use. */
extern pthread_mutex_t GC_compare_and_swap_lock;
/* Note that if GC_word updates are not atomic, a concurrent */
/* reader should acquire GC_compare_and_swap_lock. On */
/* currently supported platforms, such updates are atomic. */
extern GC_bool GC_compare_and_exchange(volatile GC_word *addr,
GC_word old, GC_word new_val);
# endif /* GENERIC_COMPARE_AND_SWAP */
# if defined(I386)
# if !defined(GENERIC_COMPARE_AND_SWAP)
/* Returns TRUE if the comparison succeeded. */
inline static GC_bool GC_compare_and_exchange(volatile GC_word *addr,
GC_word old,
GC_word new_val)
{
char result;
__asm__ __volatile__("lock; cmpxchgl %2, %0; setz %1"
: "=m"(*(addr)), "=r"(result)
: "r" (new_val), "0"(*(addr)), "a"(old) : "memory");
return (GC_bool) result;
}
# endif /* !GENERIC_COMPARE_AND_SWAP */
inline static void GC_memory_write_barrier()
{
/* We believe the processor ensures at least processor */
/* consistent ordering. Thus a compiler barrier */
/* should suffice. */
__asm__ __volatile__("" : : : "memory");
}
# endif /* I386 */
# if defined(IA64)
# if !defined(GENERIC_COMPARE_AND_SWAP)
inline static GC_bool GC_compare_and_exchange(volatile GC_word *addr,
GC_word old, GC_word new_val)
{
unsigned long oldval;
__asm__ __volatile__("mov ar.ccv=%4 ;; cmpxchg8.rel %0=%1,%2,ar.ccv"
: "=r"(oldval), "=m"(*addr)
: "r"(new_val), "1"(*addr), "r"(old) : "memory");
return (oldval == old);
}
# endif /* !GENERIC_COMPARE_AND_SWAP */
# if 0
/* Shouldn't be needed; we use volatile stores instead. */
inline static void GC_memory_write_barrier()
{
__asm__ __volatile__("mf" : : : "memory");
}
# endif /* 0 */
# endif /* IA64 */
# if !defined(GENERIC_COMPARE_AND_SWAP)
/* Returns the original value of *addr. */
inline static GC_word GC_atomic_add(volatile GC_word *addr,
GC_word how_much)
{
GC_word old;
do {
old = *addr;
} while (!GC_compare_and_exchange(addr, old, old+how_much));
return old;
}
# else /* GENERIC_COMPARE_AND_SWAP */
/* So long as a GC_word can be atomically updated, it should */
/* be OK to read *addr without a lock. */
extern GC_word GC_atomic_add(volatile GC_word *addr, GC_word how_much);
# endif /* GENERIC_COMPARE_AND_SWAP */
# endif /* PARALLEL_MARK */
# if !defined(THREAD_LOCAL_ALLOC) && !defined(USE_PTHREAD_LOCKS)
/* In the THREAD_LOCAL_ALLOC case, the allocation lock tends to */
/* be held for long periods, if it is held at all. Thus spinning */
/* and sleeping for fixed periods are likely to result in */
/* significant wasted time. We thus rely mostly on queued locks. */
# define USE_SPIN_LOCK
extern volatile unsigned int GC_allocate_lock;
extern void GC_lock(void);
/* Allocation lock holder. Only set if acquired by client through */
/* GC_call_with_alloc_lock. */
# ifdef GC_ASSERTIONS
# define LOCK() \
{ if (GC_test_and_set(&GC_allocate_lock)) GC_lock(); \
SET_LOCK_HOLDER(); }
# define UNLOCK() \
{ GC_ASSERT(I_HOLD_LOCK()); UNSET_LOCK_HOLDER(); \
GC_clear(&GC_allocate_lock); }
# else
# define LOCK() \
{ if (GC_test_and_set(&GC_allocate_lock)) GC_lock(); }
# define UNLOCK() \
GC_clear(&GC_allocate_lock)
# endif /* !GC_ASSERTIONS */
# if 0
/* Another alternative for OSF1 might be: */
# include <sys/mman.h>
extern msemaphore GC_allocate_semaphore;
# define LOCK() { if (msem_lock(&GC_allocate_semaphore, MSEM_IF_NOWAIT) \
!= 0) GC_lock(); else GC_allocate_lock = 1; }
/* The following is INCORRECT, since the memory model is too weak. */
/* Is this true? Presumably msem_unlock has the right semantics? */
/* - HB */
# define UNLOCK() { GC_allocate_lock = 0; \
msem_unlock(&GC_allocate_semaphore, 0); }
# endif /* 0 */
# else /* THREAD_LOCAL_ALLOC || USE_PTHREAD_LOCKS */
# ifndef USE_PTHREAD_LOCKS
# define USE_PTHREAD_LOCKS
# endif
# endif /* THREAD_LOCAL_ALLOC */
# ifdef USE_PTHREAD_LOCKS
# include <pthread.h>
extern pthread_mutex_t GC_allocate_ml;
# ifdef GC_ASSERTIONS
# define LOCK() \
{ GC_lock(); \
SET_LOCK_HOLDER(); }
# define UNLOCK() \
{ GC_ASSERT(I_HOLD_LOCK()); UNSET_LOCK_HOLDER(); \
pthread_mutex_unlock(&GC_allocate_ml); }
# else /* !GC_ASSERTIONS */
# define LOCK() \
{ if (0 != pthread_mutex_trylock(&GC_allocate_ml)) GC_lock(); }
# define UNLOCK() pthread_mutex_unlock(&GC_allocate_ml)
# endif /* !GC_ASSERTIONS */
# endif /* USE_PTHREAD_LOCKS */
# define SET_LOCK_HOLDER() GC_lock_holder = pthread_self()
# define UNSET_LOCK_HOLDER() GC_lock_holder = NO_THREAD
# define I_HOLD_LOCK() (pthread_equal(GC_lock_holder, pthread_self()))
extern VOLATILE GC_bool GC_collecting;
# define ENTER_GC() GC_collecting = 1;
# define EXIT_GC() GC_collecting = 0;
extern void GC_lock(void);
extern pthread_t GC_lock_holder;
# ifdef GC_ASSERTIONS
extern pthread_t GC_mark_lock_holder;
# endif
# endif /* LINUX_THREADS || OSF1_THREADS || HPUX_THREADS */
# if defined(IRIX_THREADS)
# include <pthread.h>
/* This probably should never be included, but I can't test */
/* on Irix anymore. */
# include <mutex.h>
extern unsigned long GC_allocate_lock;
/* This is not a mutex because mutexes that obey the (optional) */
/* POSIX scheduling rules are subject to convoys in high contention */
/* applications. This is basically a spin lock. */
extern pthread_t GC_lock_holder;
extern void GC_lock(void);
/* Allocation lock holder. Only set if acquired by client through */
/* GC_call_with_alloc_lock. */
# define SET_LOCK_HOLDER() GC_lock_holder = pthread_self()
# define NO_THREAD (pthread_t)(-1)
# define UNSET_LOCK_HOLDER() GC_lock_holder = NO_THREAD
# define I_HOLD_LOCK() (pthread_equal(GC_lock_holder, pthread_self()))
# define LOCK() { if (GC_test_and_set(&GC_allocate_lock, 1)) GC_lock(); }
# define UNLOCK() GC_clear(&GC_allocate_lock);
extern VOLATILE GC_bool GC_collecting;
# define ENTER_GC() \
{ \
GC_collecting = 1; \
}
# define EXIT_GC() GC_collecting = 0;
# endif /* IRIX_THREADS */
# ifdef WIN32_THREADS
# include <windows.h>
GC_API CRITICAL_SECTION GC_allocate_ml;
# define LOCK() EnterCriticalSection(&GC_allocate_ml);
# define UNLOCK() LeaveCriticalSection(&GC_allocate_ml);
# endif
# ifndef SET_LOCK_HOLDER
# define SET_LOCK_HOLDER()
# define UNSET_LOCK_HOLDER()
# define I_HOLD_LOCK() FALSE
/* Used on platforms were locks can be reacquired, */
/* so it doesn't matter if we lie. */
# endif
# else /* !THREADS */
# define LOCK()
# define UNLOCK()
# endif /* !THREADS */
# ifndef SET_LOCK_HOLDER
# define SET_LOCK_HOLDER()
# define UNSET_LOCK_HOLDER()
# define I_HOLD_LOCK() FALSE
/* Used on platforms were locks can be reacquired, */
/* so it doesn't matter if we lie. */
# endif
# ifndef ENTER_GC
# define ENTER_GC()
# define EXIT_GC()
# endif
# ifndef DCL_LOCK_STATE
# define DCL_LOCK_STATE
# endif
# ifndef FASTLOCK
# define FASTLOCK() LOCK()
# define FASTLOCK_SUCCEEDED() TRUE
# define FASTUNLOCK() UNLOCK()
# endif
#endif /* GC_LOCKS_H */

View File

@ -0,0 +1,396 @@
/*
* Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 2001 by Hewlett-Packard Company. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*
*/
/* Private declarations of GC marker data structures and macros */
/*
* Declarations of mark stack. Needed by marker and client supplied mark
* routines. Transitively include gc_priv.h.
* (Note that gc_priv.h should not be included before this, since this
* includes dbg_mlc.h, which wants to include gc_priv.h AFTER defining
* I_HIDE_POINTERS.)
*/
#ifndef GC_PMARK_H
# define GC_PMARK_H
# ifdef KEEP_BACK_PTRS
# include "dbg_mlc.h"
# endif
# ifndef GC_MARK_H
# include "../gc_mark.h"
# endif
# ifndef GC_PRIVATE_H
# include "gc_priv.h"
# endif
/* The real declarations of the following is in gc_priv.h, so that */
/* we can avoid scanning the following table. */
/*
extern mark_proc GC_mark_procs[MAX_MARK_PROCS];
*/
/*
* Mark descriptor stuff that should remain private for now, mostly
* because it's hard to export WORDSZ without including gcconfig.h.
*/
# define BITMAP_BITS (WORDSZ - GC_DS_TAG_BITS)
# define PROC(descr) \
(GC_mark_procs[((descr) >> GC_DS_TAG_BITS) & (GC_MAX_MARK_PROCS-1)])
# define ENV(descr) \
((descr) >> (GC_DS_TAG_BITS + GC_LOG_MAX_MARK_PROCS))
# define MAX_ENV \
(((word)1 << (WORDSZ - GC_DS_TAG_BITS - GC_LOG_MAX_MARK_PROCS)) - 1)
extern word GC_n_mark_procs;
/* Number of mark stack entries to discard on overflow. */
#define GC_MARK_STACK_DISCARDS (INITIAL_MARK_STACK_SIZE/8)
typedef struct GC_ms_entry {
GC_word * mse_start; /* First word of object */
GC_word mse_descr; /* Descriptor; low order two bits are tags, */
/* identifying the upper 30 bits as one of the */
/* following: */
} mse;
extern word GC_mark_stack_size;
extern mse * GC_mark_stack_limit;
#ifdef PARALLEL_MARK
extern mse * VOLATILE GC_mark_stack_top;
#else
extern mse * GC_mark_stack_top;
#endif
extern mse * GC_mark_stack;
#ifdef PARALLEL_MARK
/*
* Allow multiple threads to participate in the marking process.
* This works roughly as follows:
* The main mark stack never shrinks, but it can grow.
*
* The initiating threads holds the GC lock, and sets GC_help_wanted.
*
* Other threads:
* 1) update helper_count (while holding mark_lock.)
* 2) allocate a local mark stack
* repeatedly:
* 3) Steal a global mark stack entry by atomically replacing
* its descriptor with 0.
* 4) Copy it to the local stack.
* 5) Mark on the local stack until it is empty, or
* it may be profitable to copy it back.
* 6) If necessary, copy local stack to global one,
* holding mark lock.
* 7) Stop when the global mark stack is empty.
* 8) decrement helper_count (holding mark_lock).
*
* This is an experiment to see if we can do something along the lines
* of the University of Tokyo SGC in a less intrusive, though probably
* also less performant, way.
*/
void GC_do_parallel_mark();
/* inititate parallel marking. */
extern GC_bool GC_help_wanted; /* Protected by mark lock */
extern unsigned GC_helper_count; /* Number of running helpers. */
/* Protected by mark lock */
extern unsigned GC_active_count; /* Number of active helpers. */
/* Protected by mark lock */
/* May increase and decrease */
/* within each mark cycle. But */
/* once it returns to 0, it */
/* stays zero for the cycle. */
/* GC_mark_stack_top is also protected by mark lock. */
extern mse * VOLATILE GC_first_nonempty;
/* Lowest entry on mark stack */
/* that may be nonempty. */
/* Updated only by initiating */
/* thread. */
/*
* GC_notify_all_marker() is used when GC_help_wanted is first set,
* when the last helper becomes inactive,
* when something is added to the global mark stack, and just after
* GC_mark_no is incremented.
* This could be split into multiple CVs (and probably should be to
* scale to really large numbers of processors.)
*/
#endif /* PARALLEL_MARK */
ptr_t GC_find_start();
mse * GC_signal_mark_stack_overflow();
# ifdef GATHERSTATS
# define ADD_TO_ATOMIC(sz) GC_atomic_in_use += (sz)
# define ADD_TO_COMPOSITE(sz) GC_composite_in_use += (sz)
# else
# define ADD_TO_ATOMIC(sz)
# define ADD_TO_COMPOSITE(sz)
# endif
/* Push the object obj with corresponding heap block header hhdr onto */
/* the mark stack. */
# define PUSH_OBJ(obj, hhdr, mark_stack_top, mark_stack_limit) \
{ \
register word _descr = (hhdr) -> hb_descr; \
\
if (_descr == 0) { \
ADD_TO_ATOMIC((hhdr) -> hb_sz); \
} else { \
ADD_TO_COMPOSITE((hhdr) -> hb_sz); \
mark_stack_top++; \
if (mark_stack_top >= mark_stack_limit) { \
mark_stack_top = GC_signal_mark_stack_overflow(mark_stack_top); \
} \
mark_stack_top -> mse_start = (obj); \
mark_stack_top -> mse_descr = _descr; \
} \
}
#ifdef PRINT_BLACK_LIST
# define GC_FIND_START(current, hhdr, source) \
GC_find_start(current, hhdr, source)
#else
# define GC_FIND_START(current, hhdr, source) \
GC_find_start(current, hhdr)
#endif
/* Push the contents of current onto the mark stack if it is a valid */
/* ptr to a currently unmarked object. Mark it. */
/* If we assumed a standard-conforming compiler, we could probably */
/* generate the exit_label transparently. */
# define PUSH_CONTENTS(current, mark_stack_top, mark_stack_limit, \
source, exit_label) \
{ \
hdr * my_hhdr; \
ptr_t my_current = current; \
\
GET_HDR(my_current, my_hhdr); \
if (IS_FORWARDING_ADDR_OR_NIL(my_hhdr)) { \
my_current = GC_FIND_START(my_current, my_hhdr, (word)source); \
if (my_current == 0) goto exit_label; \
my_hhdr = GC_find_header(my_current); \
} \
PUSH_CONTENTS_HDR(my_current, mark_stack_top, mark_stack_limit, \
source, exit_label, my_hhdr); \
exit_label: ; \
}
/* As above, but use header cache for header lookup. */
# define HC_PUSH_CONTENTS(current, mark_stack_top, mark_stack_limit, \
source, exit_label) \
{ \
hdr * my_hhdr; \
ptr_t my_current = current; \
\
HC_GET_HDR(my_current, my_hhdr, source); \
PUSH_CONTENTS_HDR(my_current, mark_stack_top, mark_stack_limit, \
source, exit_label, my_hhdr); \
exit_label: ; \
}
/* As above, but deal with two pointers in interleaved fashion. */
# define HC_PUSH_CONTENTS2(current1, current2, mark_stack_top, \
mark_stack_limit, \
source1, source2, exit_label1, exit_label2) \
{ \
hdr * hhdr1; \
ptr_t my_current1 = current1; \
hdr * hhdr2; \
ptr_t my_current2 = current2; \
\
HC_GET_HDR2(my_current1, hhdr1, source1, my_current2, hhdr2, source2); \
PUSH_CONTENTS_HDR(my_current1, mark_stack_top, mark_stack_limit, \
source1, exit_label1, hhdr1); \
exit_label1: ; \
if (0 != hhdr2) { \
PUSH_CONTENTS_HDR(my_current2, mark_stack_top, mark_stack_limit, \
source2, exit_label2, hhdr2); \
} \
exit_label2: ; \
}
/* Set mark bit, exit if it was already set. */
# ifdef USE_MARK_BYTES
/* Unlike the mark bit case, there is a race here, and we may set */
/* the bit twice in the concurrent case. This can result in the */
/* object being pushed twice. But that's only a performance issue. */
# define SET_MARK_BIT_EXIT_IF_SET(hhdr,displ,exit_label) \
{ \
register VOLATILE char * mark_byte_addr = \
hhdr -> hb_marks + ((displ) >> 1); \
register char mark_byte = *mark_byte_addr; \
\
if (mark_byte) goto exit_label; \
*mark_byte_addr = 1; \
}
# else
# define SET_MARK_BIT_EXIT_IF_SET(hhdr,displ,exit_label) \
{ \
register word * mark_word_addr = hhdr -> hb_marks + divWORDSZ(displ); \
register word mark_word = *mark_word_addr; \
\
OR_WORD_EXIT_IF_SET(mark_word_addr, (word)1 << modWORDSZ(displ), \
exit_label); \
}
# endif /* USE_MARK_BYTES */
/* If the mark bit corresponding to current is not set, set it, and */
/* push the contents of the object on the mark stack. Since we */
/* already have the header, we only look at the low order bits of */
/* current. (The value of current doesn't matter if hhdr = */
/* GC_invalid_header.) */
# define PUSH_CONTENTS_HDR(current, mark_stack_top, mark_stack_limit, \
source, exit_label, hhdr) \
{ \
int displ; /* Displacement in block; first bytes, then words */ \
int map_entry; \
\
displ = HBLKDISPL(current); \
map_entry = MAP_ENTRY((hhdr -> hb_map), displ); \
displ = BYTES_TO_WORDS(displ); \
if (map_entry > CPP_MAX_OFFSET) { \
if (map_entry == OFFSET_TOO_BIG) { \
map_entry = displ % (hhdr -> hb_sz); \
displ -= map_entry; \
if (displ + (hhdr -> hb_sz) > BYTES_TO_WORDS(HBLKSIZE)) { \
GC_ADD_TO_BLACK_LIST_NORMAL((word)current, source); \
goto exit_label; \
} \
} else { \
GC_ADD_TO_BLACK_LIST_NORMAL((word)current, source); goto exit_label; \
} \
} else { \
displ -= map_entry; \
} \
GC_ASSERT(displ >= 0 && displ < MARK_BITS_PER_HBLK); \
SET_MARK_BIT_EXIT_IF_SET(hhdr, displ, exit_label); \
GC_STORE_BACK_PTR((ptr_t)source, (ptr_t)HBLKPTR(current) \
+ WORDS_TO_BYTES(displ)); \
PUSH_OBJ(((word *)(HBLKPTR(current)) + displ), hhdr, \
mark_stack_top, mark_stack_limit) \
}
#if defined(PRINT_BLACK_LIST) || defined(KEEP_BACK_PTRS)
# define PUSH_ONE_CHECKED_STACK(p, source) \
GC_mark_and_push_stack(p, (ptr_t)(source))
#else
# define PUSH_ONE_CHECKED_STACK(p, source) \
GC_mark_and_push_stack(p)
#endif
/*
* Push a single value onto mark stack. Mark from the object pointed to by p.
* P is considered valid even if it is an interior pointer.
* Previously marked objects are not pushed. Hence we make progress even
* if the mark stack overflows.
*/
# define GC_PUSH_ONE_STACK(p, source) \
if ((ptr_t)(p) >= (ptr_t)GC_least_plausible_heap_addr \
&& (ptr_t)(p) < (ptr_t)GC_greatest_plausible_heap_addr) { \
PUSH_ONE_CHECKED_STACK(p, source); \
}
/*
* As above, but interior pointer recognition as for
* normal for heap pointers.
*/
# define GC_PUSH_ONE_HEAP(p,source) \
if ((ptr_t)(p) >= (ptr_t)GC_least_plausible_heap_addr \
&& (ptr_t)(p) < (ptr_t)GC_greatest_plausible_heap_addr) { \
GC_mark_stack_top = GC_mark_and_push( \
(GC_PTR)(p), GC_mark_stack_top, \
GC_mark_stack_limit, (GC_PTR *)(source)); \
}
/* Mark starting at mark stack entry top (incl.) down to */
/* mark stack entry bottom (incl.). Stop after performing */
/* about one page worth of work. Return the new mark stack */
/* top entry. */
mse * GC_mark_from GC_PROTO((mse * top, mse * bottom, mse *limit));
#define MARK_FROM_MARK_STACK() \
GC_mark_stack_top = GC_mark_from(GC_mark_stack_top, \
GC_mark_stack, \
GC_mark_stack + GC_mark_stack_size);
/*
* Mark from one finalizable object using the specified
* mark proc. May not mark the object pointed to by
* real_ptr. That is the job of the caller, if appropriate
*/
# define GC_MARK_FO(real_ptr, mark_proc) \
{ \
(*(mark_proc))(real_ptr); \
while (!GC_mark_stack_empty()) MARK_FROM_MARK_STACK(); \
if (GC_mark_state != MS_NONE) { \
GC_set_mark_bit(real_ptr); \
while (!GC_mark_some((ptr_t)0)); \
} \
}
extern GC_bool GC_mark_stack_too_small;
/* We need a larger mark stack. May be */
/* set by client supplied mark routines.*/
typedef int mark_state_t; /* Current state of marking, as follows:*/
/* Used to remember where we are during */
/* concurrent marking. */
/* We say something is dirty if it was */
/* written since the last time we */
/* retrieved dirty bits. We say it's */
/* grungy if it was marked dirty in the */
/* last set of bits we retrieved. */
/* Invariant I: all roots and marked */
/* objects p are either dirty, or point */
/* to objects q that are either marked */
/* or a pointer to q appears in a range */
/* on the mark stack. */
# define MS_NONE 0 /* No marking in progress. I holds. */
/* Mark stack is empty. */
# define MS_PUSH_RESCUERS 1 /* Rescuing objects are currently */
/* being pushed. I holds, except */
/* that grungy roots may point to */
/* unmarked objects, as may marked */
/* grungy objects above scan_ptr. */
# define MS_PUSH_UNCOLLECTABLE 2
/* I holds, except that marked */
/* uncollectable objects above scan_ptr */
/* may point to unmarked objects. */
/* Roots may point to unmarked objects */
# define MS_ROOTS_PUSHED 3 /* I holds, mark stack may be nonempty */
# define MS_PARTIALLY_INVALID 4 /* I may not hold, e.g. because of M.S. */
/* overflow. However marked heap */
/* objects below scan_ptr point to */
/* marked or stacked objects. */
# define MS_INVALID 5 /* I may not hold. */
extern mark_state_t GC_mark_state;
#endif /* GC_PMARK_H */

View File

@ -0,0 +1,34 @@
#ifdef SOLARIS_THREADS
/* The set of all known threads. We intercept thread creation and */
/* joins. We never actually create detached threads. We allocate all */
/* new thread stacks ourselves. These allow us to maintain this */
/* data structure. */
/* Protected by GC_thr_lock. */
/* Some of this should be declared volatile, but that's incosnsistent */
/* with some library routine declarations. In particular, the */
/* definition of cond_t doesn't mention volatile! */
typedef struct GC_Thread_Rep {
struct GC_Thread_Rep * next;
thread_t id;
word flags;
# define FINISHED 1 /* Thread has exited. */
# define DETACHED 2 /* Thread is intended to be detached. */
# define CLIENT_OWNS_STACK 4
/* Stack was supplied by client. */
# define SUSPENDED 8 /* Currently suspended. */
ptr_t stack;
size_t stack_size;
cond_t join_cv;
void * status;
} * GC_thread;
extern GC_thread GC_new_thread(thread_t id);
extern GC_bool GC_thr_initialized;
extern volatile GC_thread GC_threads[];
extern size_t GC_min_stack_sz;
extern size_t GC_page_sz;
extern void GC_thr_init(void);
# endif /* SOLARIS_THREADS */

View File

@ -0,0 +1,83 @@
/*
* This is a reimplementation of a subset of the pthread_getspecific/setspecific
* interface. This appears to outperform the standard linuxthreads one
* by a significant margin.
* The major restriction is that each thread may only make a single
* pthread_setspecific call on a single key. (The current data structure
* doesn't really require that. The restriction should be easily removable.)
* We don't currently support the destruction functions, though that
* could be done.
* We also currently assume that only one pthread_setspecific call
* can be executed at a time, though that assumption would be easy to remove
* by adding a lock.
*/
#include <errno.h>
/* Called during key creation or setspecific. */
/* For the GC we already hold lock. */
/* Currently allocated objects leak on thread exit. */
/* That's hard to fix, but OK if we allocate garbage */
/* collected memory. */
#define MALLOC_CLEAR(n) GC_INTERNAL_MALLOC(n, NORMAL)
#define PREFIXED(name) GC_##name
#define TS_CACHE_SIZE 1024
#define CACHE_HASH(n) (((((long)n) >> 8) ^ (long)n) & (TS_CACHE_SIZE - 1))
#define TS_HASH_SIZE 1024
#define HASH(n) (((((long)n) >> 8) ^ (long)n) & (TS_HASH_SIZE - 1))
typedef struct thread_specific_entry {
unsigned long qtid; /* quick thread id, only for cache */
void * value;
pthread_t thread;
struct thread_specific_entry *next;
} tse;
/* We represent each thread-specific datum as two tables. The first is */
/* a cache, index by a "quick thread identifier". The "quick" thread */
/* identifier is an easy to compute value, which is guaranteed to */
/* determine the thread, though a thread may correspond to more than */
/* one value. We typically use the address of a page in the stack. */
/* The second is a hash table, indexed by pthread_self(). It is used */
/* only as a backup. */
/* Return the "quick thread id". Default version. Assumes page size, */
/* or at least thread stack separation, is at least 4K. */
static __inline__ long quick_thread_id() {
int dummy;
return (long)(&dummy) >> 12;
}
#define INVALID_QTID ((unsigned long)(-1))
typedef struct thread_specific_data {
tse * volatile cache[TS_CACHE_SIZE];
/* A faster index to the hash table */
tse * hash[TS_HASH_SIZE];
pthread_mutex_t lock;
} tsd;
typedef tsd * PREFIXED(key_t);
extern int PREFIXED(key_create) (tsd ** key_ptr, void (* destructor)(void *));
extern int PREFIXED(setspecific) (tsd * key, void * value);
extern void PREFIXED(remove_specific) (tsd * key);
/* An internal version of getspecific that assumes a cache miss. */
void * PREFIXED(slow_getspecific) (tsd * key, unsigned long qtid,
tse * volatile * cache_entry);
static __inline__ void * PREFIXED(getspecific) (tsd * key) {
long qtid = quick_thread_id();
unsigned hash_val = CACHE_HASH(qtid);
tse * volatile * entry_ptr = key -> cache + hash_val;
tse * entry = *entry_ptr; /* Must be loaded only once. */
if (entry -> qtid == qtid) return entry -> value;
return PREFIXED(slow_getspecific) (key, qtid, entry_ptr);
}

View File

@ -0,0 +1,66 @@
.text
.set linkageArea,24
.set params,4
.set alignment,4
.set spaceToSave,linkageArea+params+alignment
.set spaceToSave8,spaceToSave+8
; Mark from machine registers that are saved by C compiler
.globl _GC_push_regs
_GC_push_regs:
; PROLOG
mflr r0 ; get return address
stw r0,8(r1) ; save return address
stwu r1,-spaceToSave(r1) ; skip over caller save area
;
mr r3,r2 ; mark from r2. Well I'm not really sure
; that this is necessary or even the right
; thing to do - at least it doesn't harm...
; According to Apple's docs it points to
; the direct data area, whatever that is...
bl _GC_push_one
mr r3,r13 ; mark from r13-r31
bl _GC_push_one
mr r3,r14
bl _GC_push_one
mr r3,r15
bl _GC_push_one
mr r3,r16
bl _GC_push_one
mr r3,r17
bl _GC_push_one
mr r3,r18
bl _GC_push_one
mr r3,r19
bl _GC_push_one
mr r3,r20
bl _GC_push_one
mr r3,r21
bl _GC_push_one
mr r3,r22
bl _GC_push_one
mr r3,r23
bl _GC_push_one
mr r3,r24
bl _GC_push_one
mr r3,r25
bl _GC_push_one
mr r3,r26
bl _GC_push_one
mr r3,r27
bl _GC_push_one
mr r3,r28
bl _GC_push_one
mr r3,r29
bl _GC_push_one
mr r3,r30
bl _GC_push_one
mr r3,r31
bl _GC_push_one
; EPILOG
lwz r0,spaceToSave8(r1) ; get return address back
mtlr r0 ; reset link register
addic r1,r1,spaceToSave ; restore stack pointer
blr

View File

@ -0,0 +1,34 @@
! SPARCompiler 3.0 and later apparently no longer handles
! asm outside functions. So we need a separate .s file
! This is only set up for SunOS 4.
! Assumes this is called before the stack contents are
! examined.
#include "machine/asm.h"
.seg "text"
.globl _C_LABEL(GC_save_regs_in_stack)
.globl _C_LABEL(GC_push_regs)
_C_LABEL(GC_save_regs_in_stack):
_C_LABEL(GC_push_regs):
ta 0x3 ! ST_FLUSH_WINDOWS
mov %sp,%o0
retl
nop
.globl _C_LABEL(GC_clear_stack_inner)
_C_LABEL(GC_clear_stack_inner):
mov %sp,%o2 ! Save sp
add %sp,-8,%o3 ! p = sp-8
clr %g1 ! [g0,g1] = 0
add %o1,-0x60,%sp ! Move sp out of the way,
! so that traps still work.
! Includes some extra words
! so we can be sloppy below.
loop:
std %g0,[%o3] ! *(long long *)p = 0
cmp %o3,%o1
bgu loop ! if (p > limit) goto loop
add %o3,-8,%o3 ! p -= 8 (delay slot)
retl
mov %o2,%sp ! Restore sp., delay slot

108
boehm-gc/specific.c Normal file
View File

@ -0,0 +1,108 @@
/*
* Copyright (c) 2000 by Hewlett-Packard Company. All rights reserved.
*
* THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
* OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
*
* Permission is hereby granted to use or copy this program
* for any purpose, provided the above notices are retained on all copies.
* Permission to modify the code and to distribute modified code is granted,
* provided the above notices are retained, and a notice that the code was
* modified is included with the above copyright notice.
*/
#if defined(LINUX_THREADS) || defined(GC_LINUX_THREADS)
#include "private/gc_priv.h" /* For GC_compare_and_exchange, GC_memory_barrier */
#include "private/specific.h"
static tse invalid_tse; /* 0 qtid is guaranteed to be invalid */
int PREFIXED(key_create) (tsd ** key_ptr, void (* destructor)(void *)) {
int i;
tsd * result = (tsd *)MALLOC_CLEAR(sizeof (tsd));
if (0 == result) return ENOMEM;
pthread_mutex_init(&(result -> lock), NULL);
for (i = 0; i < TS_CACHE_SIZE; ++i) {
result -> cache[i] = &invalid_tse;
}
*key_ptr = result;
return 0;
}
int PREFIXED(setspecific) (tsd * key, void * value) {
pthread_t self = pthread_self();
int hash_val = HASH(self);
volatile tse * entry = (volatile tse *)MALLOC_CLEAR(sizeof (tse));
if (0 == entry) return ENOMEM;
pthread_mutex_lock(&(key -> lock));
/* Could easily check for an existing entry here. */
entry -> next = key -> hash[hash_val];
entry -> thread = self;
entry -> value = value;
/* There can only be one writer at a time, but this needs to be */
/* atomic with respect to concurrent readers. */
*(volatile tse **)(key -> hash + hash_val) = entry;
pthread_mutex_unlock(&(key -> lock));
return 0;
}
/* Remove thread-specific data for this thread. Should be called on */
/* thread exit. */
void PREFIXED(remove_specific) (tsd * key) {
pthread_t self = pthread_self();
unsigned hash_val = HASH(self);
tse *entry;
tse **link = key -> hash + hash_val;
pthread_mutex_lock(&(key -> lock));
entry = *link;
while (entry != NULL && entry -> thread != self) {
link = &(entry -> next);
entry = *link;
}
/* Invalidate qtid field, since qtids may be reused, and a later */
/* cache lookup could otherwise find this entry. */
entry -> qtid = INVALID_QTID;
if (entry != NULL) {
*link = entry -> next;
/* Atomic! concurrent accesses still work. */
/* They must, since readers don't lock. */
}
/* If we wanted to deallocate the entry, we'd first have to clear */
/* any cache entries pointing to it. That probably requires */
/* additional synchronization, since we can't prevent a concurrent */
/* cache lookup, which should still be examining deallocated memory.*/
/* This can only happen if the concurrent access is from another */
/* thread, and hence has missed the cache, but still... */
/* With GC, we're done, since the pointers from the cache will */
/* be overwritten, all local pointers to the entries will be */
/* dropped, and the entry will then be reclaimed. */
pthread_mutex_unlock(&(key -> lock));
}
/* Note that even the slow path doesn't lock. */
void * PREFIXED(slow_getspecific) (tsd * key, unsigned long qtid,
tse * volatile * cache_ptr) {
pthread_t self = pthread_self();
unsigned hash_val = HASH(self);
tse *entry = key -> hash[hash_val];
while (entry != NULL && entry -> thread != self) {
entry = entry -> next;
}
if (entry == NULL) return NULL;
/* Set cache_entry. */
entry -> qtid = qtid;
/* It's safe to do this asynchronously. Either value */
/* is safe, though may produce spurious misses. */
*cache_ptr = entry;
/* Again this is safe since pointer assignments are */
/* presumed atomic, and either pointer is valid. */
return entry -> value;
}
#endif /* LINUX_THREADS */

View File

@ -0,0 +1,21 @@
#include "leak_detector.h"
main() {
int *p[10];
int i;
GC_find_leak = 1; /* for new collect versions not compiled */
/* with -DFIND_LEAK. */
for (i = 0; i < 10; ++i) {
p[i] = malloc(sizeof(int)+i);
}
CHECK_LEAKS();
for (i = 1; i < 10; ++i) {
free(p[i]);
}
for (i = 0; i < 9; ++i) {
p[i] = malloc(sizeof(int)+i);
}
CHECK_LEAKS();
CHECK_LEAKS();
CHECK_LEAKS();
}

1654
boehm-gc/tests/test.c Normal file

File diff suppressed because it is too large Load Diff

277
boehm-gc/tests/test_cpp.cc Normal file
View File

@ -0,0 +1,277 @@
/****************************************************************************
Copyright (c) 1994 by Xerox Corporation. All rights reserved.
THIS MATERIAL IS PROVIDED AS IS, WITH ABSOLUTELY NO WARRANTY EXPRESSED
OR IMPLIED. ANY USE IS AT YOUR OWN RISK.
Permission is hereby granted to use or copy this program for any
purpose, provided the above notices are retained on all copies.
Permission to modify the code and to distribute modified code is
granted, provided the above notices are retained, and a notice that
the code was modified is included with the above copyright notice.
****************************************************************************
Last modified on Mon Jul 10 21:06:03 PDT 1995 by ellis
modified on December 20, 1994 7:27 pm PST by boehm
usage: test_cpp number-of-iterations
This program tries to test the specific C++ functionality provided by
gc_c++.h that isn't tested by the more general test routines of the
collector.
A recommended value for number-of-iterations is 10, which will take a
few minutes to complete.
***************************************************************************/
#include "gc_cpp.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifdef __GNUC__
# include "new_gc_alloc.h"
#else
# include "gc_alloc.h"
#endif
extern "C" {
#include "private/gc_priv.h"
}
#ifdef MSWIN32
# include <windows.h>
#endif
#ifdef GC_NAME_CONFLICT
# define USE_GC UseGC
struct foo * GC;
#else
# define USE_GC GC
#endif
#define my_assert( e ) \
if (! (e)) { \
GC_printf1( "Assertion failure in " __FILE__ ", line %d: " #e "\n", \
__LINE__ ); \
exit( 1 ); }
class A {public:
/* An uncollectable class. */
A( int iArg ): i( iArg ) {}
void Test( int iArg ) {
my_assert( i == iArg );}
int i;};
class B: public gc, public A {public:
/* A collectable class. */
B( int j ): A( j ) {}
~B() {
my_assert( deleting );}
static void Deleting( int on ) {
deleting = on;}
static int deleting;};
int B::deleting = 0;
class C: public gc_cleanup, public A {public:
/* A collectable class with cleanup and virtual multiple inheritance. */
C( int levelArg ): A( levelArg ), level( levelArg ) {
nAllocated++;
if (level > 0) {
left = new C( level - 1 );
right = new C( level - 1 );}
else {
left = right = 0;}}
~C() {
this->A::Test( level );
nFreed++;
my_assert( level == 0 ?
left == 0 && right == 0 :
level == left->level + 1 && level == right->level + 1 );
left = right = 0;
level = -123456;}
static void Test() {
my_assert( nFreed <= nAllocated && nFreed >= .8 * nAllocated );}
static int nFreed;
static int nAllocated;
int level;
C* left;
C* right;};
int C::nFreed = 0;
int C::nAllocated = 0;
class D: public gc {public:
/* A collectable class with a static member function to be used as
an explicit clean-up function supplied to ::new. */
D( int iArg ): i( iArg ) {
nAllocated++;}
static void CleanUp( void* obj, void* data ) {
D* self = (D*) obj;
nFreed++;
my_assert( self->i == (int) (long) data );}
static void Test() {
my_assert( nFreed >= .8 * nAllocated );}
int i;
static int nFreed;
static int nAllocated;};
int D::nFreed = 0;
int D::nAllocated = 0;
class E: public gc_cleanup {public:
/* A collectable class with clean-up for use by F. */
E() {
nAllocated++;}
~E() {
nFreed++;}
static int nFreed;
static int nAllocated;};
int E::nFreed = 0;
int E::nAllocated = 0;
class F: public E {public:
/* A collectable class with clean-up, a base with clean-up, and a
member with clean-up. */
F() {
nAllocated++;}
~F() {
nFreed++;}
static void Test() {
my_assert( nFreed >= .8 * nAllocated );
my_assert( 2 * nFreed == E::nFreed );}
E e;
static int nFreed;
static int nAllocated;};
int F::nFreed = 0;
int F::nAllocated = 0;
long Disguise( void* p ) {
return ~ (long) p;}
void* Undisguise( long i ) {
return (void*) ~ i;}
#ifdef MSWIN32
int APIENTRY WinMain(
HINSTANCE instance, HINSTANCE prev, LPSTR cmd, int cmdShow )
{
int argc;
char* argv[ 3 ];
for (argc = 1; argc < sizeof( argv ) / sizeof( argv[ 0 ] ); argc++) {
argv[ argc ] = strtok( argc == 1 ? cmd : 0, " \t" );
if (0 == argv[ argc ]) break;}
#else
# ifdef MACOS
int main() {
# else
int main( int argc, char* argv[] ) {
# endif
#endif
# if defined(MACOS) // MacOS
char* argv_[] = {"test_cpp", "10"}; // doesn't
argv = argv_; // have a
argc = sizeof(argv_)/sizeof(argv_[0]); // commandline
# endif
int i, iters, n;
# if !defined(MACOS)
# ifdef __GNUC__
int *x = (int *)gc_alloc::allocate(sizeof(int));
# else
int *x = (int *)alloc::allocate(sizeof(int));
# endif
*x = 29;
x -= 3;
# endif
if (argc != 2 || (0 >= (n = atoi( argv[ 1 ] )))) {
GC_printf0( "usage: test_cpp number-of-iterations\n" );
exit( 1 );}
for (iters = 1; iters <= n; iters++) {
GC_printf1( "Starting iteration %d\n", iters );
/* Allocate some uncollectable As and disguise their pointers.
Later we'll check to see if the objects are still there. We're
checking to make sure these objects really are uncollectable. */
long as[ 1000 ];
long bs[ 1000 ];
for (i = 0; i < 1000; i++) {
as[ i ] = Disguise( new (NoGC) A( i ) );
bs[ i ] = Disguise( new (NoGC) B( i ) );}
/* Allocate a fair number of finalizable Cs, Ds, and Fs.
Later we'll check to make sure they've gone away. */
for (i = 0; i < 1000; i++) {
C* c = new C( 2 );
C c1( 2 ); /* stack allocation should work too */
D* d = ::new (USE_GC, D::CleanUp, (void*)(long)i) D( i );
F* f = new F;
if (0 == i % 10) delete c;}
/* Allocate a very large number of collectable As and Bs and
drop the references to them immediately, forcing many
collections. */
for (i = 0; i < 1000000; i++) {
A* a = new (USE_GC) A( i );
B* b = new B( i );
b = new (USE_GC) B( i );
if (0 == i % 10) {
B::Deleting( 1 );
delete b;
B::Deleting( 0 );}
# ifdef FINALIZE_ON_DEMAND
GC_invoke_finalizers();
# endif
}
/* Make sure the uncollectable As and Bs are still there. */
for (i = 0; i < 1000; i++) {
A* a = (A*) Undisguise( as[ i ] );
B* b = (B*) Undisguise( bs[ i ] );
a->Test( i );
delete a;
b->Test( i );
B::Deleting( 1 );
delete b;
B::Deleting( 0 );
# ifdef FINALIZE_ON_DEMAND
GC_invoke_finalizers();
# endif
}
/* Make sure most of the finalizable Cs, Ds, and Fs have
gone away. */
C::Test();
D::Test();
F::Test();}
# if !defined(__GNUC__) && !defined(MACOS)
my_assert (29 == x[3]);
# endif
GC_printf0( "The test appears to have succeeded.\n" );
return( 0 );}

View File

@ -0,0 +1,40 @@
#define GC_LINUX_THREADS
#include "leak_detector.h"
#include <pthread.h>
#include <stdio.h>
void * test(void * arg) {
int *p[10];
int i;
GC_find_leak = 1; /* for new collect versions not compiled */
/* with -DFIND_LEAK. */
for (i = 0; i < 10; ++i) {
p[i] = malloc(sizeof(int)+i);
}
CHECK_LEAKS();
for (i = 1; i < 10; ++i) {
free(p[i]);
}
}
#define NTHREADS 5
main() {
int i;
pthread_t t[NTHREADS];
int code;
for (i = 0; i < NTHREADS; ++i) {
if ((code = pthread_create(t + i, 0, test, 0)) != 0) {
printf("Thread creation failed %d\n", code);
}
}
for (i = 0; i < NTHREADS; ++i) {
if ((code = pthread_join(t[i], 0)) != 0) {
printf("Thread join failed %lu\n", code);
}
}
CHECK_LEAKS();
CHECK_LEAKS();
CHECK_LEAKS();
}

View File

@ -0,0 +1,28 @@
#include <stdio.h>
#define GC_DEBUG
#include "gc.h"
struct treenode {
struct treenode *x;
struct treenode *y;
} * root[10];
struct treenode * mktree(int i) {
struct treenode * r = GC_MALLOC(sizeof(struct treenode));
if (0 == i) return 0;
r -> x = mktree(i-1);
r -> y = mktree(i-1);
return r;
}
main()
{
int i;
for (i = 0; i < 10; ++i) {
root[i] = mktree(12);
}
GC_generate_random_backtrace();
GC_generate_random_backtrace();
GC_generate_random_backtrace();
GC_generate_random_backtrace();
}