Commit 73ffefd0 by Tom Tromey

Initial revision

From-SVN: r26246
parent c46bb2fd
# Makefile for Borland C++ 4.5 on NT
# For Borland 5.0, replace bc45 by bc5.
# If you have the Borland assembler, remove "-DUSE_GENERIC"
#
bc= c:\bc45
bcbin= $(bc)\bin
bclib= $(bc)\lib
bcinclude= $(bc)\include
cc= $(bcbin)\bcc32
rc= $(bcbin)\brc32
lib= $(bcbin)\tlib
link= $(bcbin)\tlink32
cflags= -R -v -vi -H -H=gc.csm -I$(bcinclude);cord -L$(bclib) \
-w-pro -w-aus -w-par -w-ccc -w-rch -a4 -D__STDC__=0
#defines= -DSILENT
defines= -DSMALL_CONFIG -DSILENT -DALL_INTERIOR_POINTERS -DUSE_GENERIC
.c.obj:
$(cc) @&&|
$(cdebug) $(cflags) $(cvars) $(defines) -o$* -c $*.c
|
.cpp.obj:
$(cc) @&&|
$(cdebug) $(cflags) $(cvars) $(defines) -o$* -c $*.cpp
|
.rc.res:
$(rc) -i$(bcinclude) -r -fo$* $*.rc
XXXOBJS= XXXalloc.obj XXXreclaim.obj XXXallchblk.obj XXXmisc.obj \
XXXmach_dep.obj XXXos_dep.obj XXXmark_rts.obj XXXheaders.obj XXXmark.obj \
XXXobj_map.obj XXXblacklst.obj XXXfinalize.obj XXXnew_hblk.obj \
XXXdbg_mlc.obj XXXmalloc.obj XXXstubborn.obj XXXdyn_load.obj \
XXXtypd_mlc.obj XXXptr_chck.obj XXXgc_cpp.obj XXXmallocx.obj
OBJS= $(XXXOBJS:XXX=)
all: gctest.exe cord\de.exe test_cpp.exe
$(OBJS) test.obj: gc_priv.h gc_hdrs.h gc.h config.h MAKEFILE
gc.lib: $(OBJS)
-del gc.lib
tlib $* @&&|
$(XXXOBJS:XXX=+)
|
gctest.exe: test.obj gc.lib
$(cc) @&&|
$(cflags) -W -e$* test.obj gc.lib
|
cord\de.obj cord\de_win.obj: cord\cord.h cord\private\cord_pos.h cord\de_win.h \
cord\de_cmds.h
cord\de.exe: cord\cordbscs.obj cord\cordxtra.obj cord\de.obj cord\de_win.obj \
cord\de_win.res gc.lib
$(cc) @&&|
$(cflags) -W -e$* cord\cordbscs.obj cord\cordxtra.obj \
cord\de.obj cord\de_win.obj gc.lib
|
$(rc) cord\de_win.res cord\de.exe
gc_cpp.obj: gc_cpp.h gc.h
gc_cpp.cpp: gc_cpp.cc
copy gc_cpp.cc gc_cpp.cpp
test_cpp.cpp: test_cpp.cc
copy test_cpp.cc test_cpp.cpp
test_cpp.exe: test_cpp.obj gc_cpp.h gc.h gc.lib
$(cc) @&&|
$(cflags) -W -e$* test_cpp.obj gc.lib
|
scratch:
-del *.obj *.res *.exe *.csm cord\*.obj cord\*.res cord\*.exe cord\*.csm
#
# OS/2 specific Makefile for the EMX environment
#
# You need GNU Make 3.71, gcc 2.5.7, emx 0.8h and GNU fileutils 3.9
# or similar tools. C++ interface and de.exe weren't tested.
#
# Rename this file "Makefile".
#
# Primary targets:
# gc.a - builds basic library
# c++ - adds C++ interface to library and include directory
# cords - adds cords (heavyweight strings) to library and include directory
# test - prints porting information, then builds basic version of gc.a, and runs
# some tests of collector and cords. Does not add cords or c++ interface to gc.a
# cord/de.exe - builds dumb editor based on cords.
CC= gcc
CXX=g++
# Needed only for "make c++", which adds the c++ interface
CFLAGS= -O -DALL_INTERIOR_POINTERS -DSILENT
# Setjmp_test may yield overly optimistic results when compiled
# without optimization.
# -DSILENT disables statistics printing, and improves performance.
# -DCHECKSUMS reports on erroneously clear dirty bits, and unexpectedly
# altered stubborn objects, at substantial performance cost.
# -DFIND_LEAK causes the collector to assume that all inaccessible
# objects should have been explicitly deallocated, and reports exceptions
# -DSOLARIS_THREADS enables support for Solaris (thr_) threads.
# (Clients should also define SOLARIS_THREADS and then include
# gc.h before performing thr_ or GC_ operations.)
# -DALL_INTERIOR_POINTERS allows all pointers to the interior
# of objects to be recognized. (See gc_private.h for consequences.)
# -DSMALL_CONFIG tries to tune the collector for small heap sizes,
# usually causing it to use less space in such situations.
# Incremental collection no longer works in this case.
# -DDONT_ADD_BYTE_AT_END is meaningful only with
# -DALL_INTERIOR_POINTERS. Normally -DALL_INTERIOR_POINTERS
# causes all objects to be padded so that pointers just past the end of
# an object can be recognized. This can be expensive. (The padding
# is normally more than one byte due to alignment constraints.)
# -DDONT_ADD_BYTE_AT_END disables the padding.
AR= ar
RANLIB= ar s
# Redefining srcdir allows object code for the nonPCR version of the collector
# to be generated in different directories
srcdir = .
VPATH = $(srcdir)
OBJS= alloc.o reclaim.o allchblk.o misc.o mach_dep.o os_dep.o mark_rts.o headers.o mark.o obj_map.o blacklst.o finalize.o new_hblk.o dyn_load.o dbg_mlc.o malloc.o stubborn.o checksums.o typd_mlc.o ptr_chck.o mallocx.o
CORD_OBJS= cord/cordbscs.o cord/cordxtra.o cord/cordprnt.o
CORD_INCLUDE_FILES= $(srcdir)/gc.h $(srcdir)/cord/cord.h $(srcdir)/cord/ec.h \
$(srcdir)/cord/cord_pos.h
# Libraries needed for curses applications. Only needed for de.
CURSES= -lcurses -ltermlib
# The following is irrelevant on most systems. But a few
# versions of make otherwise fork the shell specified in
# the SHELL environment variable.
SHELL= bash
SPECIALCFLAGS =
# Alternative flags to the C compiler for mach_dep.c.
# Mach_dep.c often doesn't like optimization, and it's
# not time-critical anyway.
all: gc.a gctest.exe
$(OBJS) test.o: $(srcdir)/gc_priv.h $(srcdir)/gc_hdrs.h $(srcdir)/gc.h \
$(srcdir)/config.h $(srcdir)/gc_typed.h
# The dependency on Makefile is needed. Changing
# options such as -DSILENT affects the size of GC_arrays,
# invalidating all .o files that rely on gc_priv.h
mark.o typd_mlc.o finalize.o: $(srcdir)/gc_mark.h
gc.a: $(OBJS)
$(AR) ru gc.a $(OBJS)
$(RANLIB) gc.a
cords: $(CORD_OBJS) cord/cordtest.exe
$(AR) ru gc.a $(CORD_OBJS)
$(RANLIB) gc.a
cp $(srcdir)/cord/cord.h include/cord.h
cp $(srcdir)/cord/ec.h include/ec.h
cp $(srcdir)/cord/cord_pos.h include/cord_pos.h
gc_cpp.o: $(srcdir)/gc_cpp.cc $(srcdir)/gc_cpp.h
$(CXX) -c -O $(srcdir)/gc_cpp.cc
c++: gc_cpp.o $(srcdir)/gc_cpp.h
$(AR) ru gc.a gc_cpp.o
$(RANLIB) gc.a
cp $(srcdir)/gc_cpp.h include/gc_cpp.h
mach_dep.o: $(srcdir)/mach_dep.c
$(CC) -o mach_dep.o -c $(SPECIALCFLAGS) $(srcdir)/mach_dep.c
mark_rts.o: $(srcdir)/mark_rts.c
$(CC) -o mark_rts.o -c $(CFLAGS) $(srcdir)/mark_rts.c
cord/cordbscs.o: $(srcdir)/cord/cordbscs.c $(CORD_INCLUDE_FILES)
$(CC) $(CFLAGS) -c $(srcdir)/cord/cordbscs.c -o cord/cordbscs.o
cord/cordxtra.o: $(srcdir)/cord/cordxtra.c $(CORD_INCLUDE_FILES)
$(CC) $(CFLAGS) -c $(srcdir)/cord/cordxtra.c -o cord/cordxtra.o
cord/cordprnt.o: $(srcdir)/cord/cordprnt.c $(CORD_INCLUDE_FILES)
$(CC) $(CFLAGS) -c $(srcdir)/cord/cordprnt.c -o cord/cordprnt.o
cord/cordtest.exe: $(srcdir)/cord/cordtest.c $(CORD_OBJS) gc.a
$(CC) $(CFLAGS) -o cord/cordtest.exe $(srcdir)/cord/cordtest.c $(CORD_OBJS) gc.a
cord/de.exe: $(srcdir)/cord/de.c $(srcdir)/cord/cordbscs.o $(srcdir)/cord/cordxtra.o gc.a
$(CC) $(CFLAGS) -o cord/de.exe $(srcdir)/cord/de.c $(srcdir)/cord/cordbscs.o $(srcdir)/cord/cordxtra.o gc.a $(CURSES)
clean:
rm -f gc.a test.o gctest.exe output-local output-diff $(OBJS) \
setjmp_test mon.out gmon.out a.out core \
$(CORD_OBJS) cord/cordtest.exe cord/de.exe
-rm -f *~
gctest.exe: test.o gc.a
$(CC) $(CFLAGS) -o gctest.exe test.o gc.a
# If an optimized setjmp_test generates a segmentation fault,
# odds are your compiler is broken. Gctest may still work.
# Try compiling setjmp_t.c unoptimized.
setjmp_test.exe: $(srcdir)/setjmp_t.c $(srcdir)/gc.h
$(CC) $(CFLAGS) -o setjmp_test.exe $(srcdir)/setjmp_t.c
test: setjmp_test.exe gctest.exe
./setjmp_test
./gctest
make cord/cordtest.exe
cord/cordtest
/*
MacOS.c
Some routines for the Macintosh OS port of the Hans-J. Boehm, Alan J. Demers
garbage collector.
<Revision History>
11/22/94 pcb StripAddress the temporary memory handle for 24-bit mode.
11/30/94 pcb Tracking all memory usage so we can deallocate it all at once.
02/10/96 pcb Added routine to perform a final collection when
unloading shared library.
by Patrick C. Beard.
*/
/* Boehm, February 15, 1996 2:55 pm PST */
#include <Resources.h>
#include <Memory.h>
#include <LowMem.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "gc.h"
#include "gc_priv.h"
// use 'CODE' resource 0 to get exact location of the beginning of global space.
typedef struct {
unsigned long aboveA5;
unsigned long belowA5;
unsigned long JTSize;
unsigned long JTOffset;
} *CodeZeroPtr, **CodeZeroHandle;
void* GC_MacGetDataStart()
{
CodeZeroHandle code0 = (CodeZeroHandle)GetResource('CODE', 0);
if (code0) {
long belowA5Size = (**code0).belowA5;
ReleaseResource((Handle)code0);
return (LMGetCurrentA5() - belowA5Size);
}
fprintf(stderr, "Couldn't load the jump table.");
exit(-1);
return 0;
}
/* track the use of temporary memory so it can be freed all at once. */
typedef struct TemporaryMemoryBlock TemporaryMemoryBlock, **TemporaryMemoryHandle;
struct TemporaryMemoryBlock {
TemporaryMemoryHandle nextBlock;
char data[];
};
static TemporaryMemoryHandle theTemporaryMemory = NULL;
static Boolean firstTime = true;
void GC_MacFreeTemporaryMemory(void);
Ptr GC_MacTemporaryNewPtr(size_t size, Boolean clearMemory)
{
static Boolean firstTime = true;
OSErr result;
TemporaryMemoryHandle tempMemBlock;
Ptr tempPtr = nil;
tempMemBlock = (TemporaryMemoryHandle)TempNewHandle(size + sizeof(TemporaryMemoryBlock), &result);
if (tempMemBlock && result == noErr) {
HLockHi((Handle)tempMemBlock);
tempPtr = (**tempMemBlock).data;
if (clearMemory) memset(tempPtr, 0, size);
tempPtr = StripAddress(tempPtr);
// keep track of the allocated blocks.
(**tempMemBlock).nextBlock = theTemporaryMemory;
theTemporaryMemory = tempMemBlock;
}
# if !defined(SHARED_LIBRARY_BUILD)
// install an exit routine to clean up the memory used at the end.
if (firstTime) {
atexit(&GC_MacFreeTemporaryMemory);
firstTime = false;
}
# endif
return tempPtr;
}
extern word GC_fo_entries;
static void perform_final_collection()
{
unsigned i;
word last_fo_entries = 0;
/* adjust the stack bottom, because CFM calls us from another stack
location. */
GC_stackbottom = (ptr_t)&i;
/* try to collect and finalize everything in sight */
for (i = 0; i < 2 || GC_fo_entries < last_fo_entries; i++) {
last_fo_entries = GC_fo_entries;
GC_gcollect();
}
}
void GC_MacFreeTemporaryMemory()
{
# if defined(SHARED_LIBRARY_BUILD)
/* if possible, collect all memory, and invoke all finalizers. */
perform_final_collection();
# endif
if (theTemporaryMemory != NULL) {
long totalMemoryUsed = 0;
TemporaryMemoryHandle tempMemBlock = theTemporaryMemory;
while (tempMemBlock != NULL) {
TemporaryMemoryHandle nextBlock = (**tempMemBlock).nextBlock;
totalMemoryUsed += GetHandleSize((Handle)tempMemBlock);
DisposeHandle((Handle)tempMemBlock);
tempMemBlock = nextBlock;
}
theTemporaryMemory = NULL;
# if !defined(SILENT) && !defined(SHARED_LIBRARY_BUILD)
fprintf(stdout, "[total memory used: %ld bytes.]\n",
totalMemoryUsed);
fprintf(stdout, "[total collections: %ld.]\n", GC_gc_no);
# endif
}
}
/*
MacOS_Test_config.h
Configuration flags for Macintosh development systems.
Test version.
<Revision History>
11/16/95 pcb Updated compilation flags to reflect latest 4.6 Makefile.
by Patrick C. Beard.
*/
/* Boehm, November 17, 1995 12:05 pm PST */
#ifdef __MWERKS__
// for CodeWarrior Pro with Metrowerks Standard Library (MSL).
// #define MSL_USE_PRECOMPILED_HEADERS 0
#include <ansi_prefix.mac.h>
#ifndef __STDC__
#define __STDC__ 0
#endif
#endif
// these are defined again in gc_priv.h.
#undef TRUE
#undef FALSE
#define ALL_INTERIOR_POINTERS // follows interior pointers.
//#define SILENT // want collection messages.
//#define DONT_ADD_BYTE_AT_END // no padding.
//#define SMALL_CONFIG // whether to a smaller heap.
#define NO_SIGNALS // signals aren't real on the Macintosh.
#define USE_TEMPORARY_MEMORY // use Macintosh temporary memory.
// CFLAGS= -O -DNO_SIGNALS -DALL_INTERIOR_POINTERS -DSILENT
//
//LIBGC_CFLAGS= -O -DNO_SIGNALS -DSILENT \
// -DREDIRECT_MALLOC=GC_malloc_uncollectable \
// -DDONT_ADD_BYTE_AT_END -DALL_INTERIOR_POINTERS
// Flags for building libgc.a -- the last two are required.
//
// Setjmp_test may yield overly optimistic results when compiled
// without optimization.
// -DSILENT disables statistics printing, and improves performance.
// -DCHECKSUMS reports on erroneously clear dirty bits, and unexpectedly
// altered stubborn objects, at substantial performance cost.
// Use only for incremental collector debugging.
// -DFIND_LEAK causes the collector to assume that all inaccessible
// objects should have been explicitly deallocated, and reports exceptions.
// Finalization and the test program are not usable in this mode.
// -DSOLARIS_THREADS enables support for Solaris (thr_) threads.
// (Clients should also define SOLARIS_THREADS and then include
// gc.h before performing thr_ or GC_ operations.)
// This is broken on nonSPARC machines.
// -DALL_INTERIOR_POINTERS allows all pointers to the interior
// of objects to be recognized. (See gc_priv.h for consequences.)
// -DSMALL_CONFIG tries to tune the collector for small heap sizes,
// usually causing it to use less space in such situations.
// Incremental collection no longer works in this case.
// -DLARGE_CONFIG tunes the collector for unusually large heaps.
// Necessary for heaps larger than about 500 MB on most machines.
// Recommended for heaps larger than about 64 MB.
// -DDONT_ADD_BYTE_AT_END is meaningful only with
// -DALL_INTERIOR_POINTERS. Normally -DALL_INTERIOR_POINTERS
// causes all objects to be padded so that pointers just past the end of
// an object can be recognized. This can be expensive. (The padding
// is normally more than one byte due to alignment constraints.)
// -DDONT_ADD_BYTE_AT_END disables the padding.
// -DNO_SIGNALS does not disable signals during critical parts of
// the GC process. This is no less correct than many malloc
// implementations, and it sometimes has a significant performance
// impact. However, it is dangerous for many not-quite-ANSI C
// programs that call things like printf in asynchronous signal handlers.
// -DOPERATOR_NEW_ARRAY declares that the C++ compiler supports the
// new syntax "operator new[]" for allocating and deleting arrays.
// See gc_cpp.h for details. No effect on the C part of the collector.
// This is defined implicitly in a few environments.
// -DREDIRECT_MALLOC=X causes malloc, realloc, and free to be defined
// as aliases for X, GC_realloc, and GC_free, respectively.
// Calloc is redefined in terms of the new malloc. X should
// be either GC_malloc or GC_malloc_uncollectable.
// The former is occasionally useful for working around leaks in code
// you don't want to (or can't) look at. It may not work for
// existing code, but it often does. Neither works on all platforms,
// since some ports use malloc or calloc to obtain system memory.
// (Probably works for UNIX, and win32.)
// -DNO_DEBUG removes GC_dump and the debugging routines it calls.
// Reduces code size slightly at the expense of debuggability.
/*
MacOS_config.h
Configuration flags for Macintosh development systems.
<Revision History>
11/16/95 pcb Updated compilation flags to reflect latest 4.6 Makefile.
by Patrick C. Beard.
*/
/* Boehm, November 17, 1995 12:10 pm PST */
#ifdef __MWERKS__
// for CodeWarrior Pro with Metrowerks Standard Library (MSL).
// #define MSL_USE_PRECOMPILED_HEADERS 0
#include <ansi_prefix.mac.h>
#ifndef __STDC__
#define __STDC__ 0
#endif
#endif /* __MWERKS__ */
// these are defined again in gc_priv.h.
#undef TRUE
#undef FALSE
#define ALL_INTERIOR_POINTERS // follows interior pointers.
#define SILENT // no collection messages.
//#define DONT_ADD_BYTE_AT_END // no padding.
//#define SMALL_CONFIG // whether to use a smaller heap.
#define NO_SIGNALS // signals aren't real on the Macintosh.
#define USE_TEMPORARY_MEMORY // use Macintosh temporary memory.
// CFLAGS= -O -DNO_SIGNALS -DSILENT -DALL_INTERIOR_POINTERS
//
//LIBGC_CFLAGS= -O -DNO_SIGNALS -DSILENT \
// -DREDIRECT_MALLOC=GC_malloc_uncollectable \
// -DDONT_ADD_BYTE_AT_END -DALL_INTERIOR_POINTERS
// Flags for building libgc.a -- the last two are required.
//
// Setjmp_test may yield overly optimistic results when compiled
// without optimization.
// -DSILENT disables statistics printing, and improves performance.
// -DCHECKSUMS reports on erroneously clear dirty bits, and unexpectedly
// altered stubborn objects, at substantial performance cost.
// Use only for incremental collector debugging.
// -DFIND_LEAK causes the collector to assume that all inaccessible
// objects should have been explicitly deallocated, and reports exceptions.
// Finalization and the test program are not usable in this mode.
// -DSOLARIS_THREADS enables support for Solaris (thr_) threads.
// (Clients should also define SOLARIS_THREADS and then include
// gc.h before performing thr_ or GC_ operations.)
// This is broken on nonSPARC machines.
// -DALL_INTERIOR_POINTERS allows all pointers to the interior
// of objects to be recognized. (See gc_priv.h for consequences.)
// -DSMALL_CONFIG tries to tune the collector for small heap sizes,
// usually causing it to use less space in such situations.
// Incremental collection no longer works in this case.
// -DLARGE_CONFIG tunes the collector for unusually large heaps.
// Necessary for heaps larger than about 500 MB on most machines.
// Recommended for heaps larger than about 64 MB.
// -DDONT_ADD_BYTE_AT_END is meaningful only with
// -DALL_INTERIOR_POINTERS. Normally -DALL_INTERIOR_POINTERS
// causes all objects to be padded so that pointers just past the end of
// an object can be recognized. This can be expensive. (The padding
// is normally more than one byte due to alignment constraints.)
// -DDONT_ADD_BYTE_AT_END disables the padding.
// -DNO_SIGNALS does not disable signals during critical parts of
// the GC process. This is no less correct than many malloc
// implementations, and it sometimes has a significant performance
// impact. However, it is dangerous for many not-quite-ANSI C
// programs that call things like printf in asynchronous signal handlers.
// -DOPERATOR_NEW_ARRAY declares that the C++ compiler supports the
// new syntax "operator new[]" for allocating and deleting arrays.
// See gc_cpp.h for details. No effect on the C part of the collector.
// This is defined implicitly in a few environments.
// -DREDIRECT_MALLOC=X causes malloc, realloc, and free to be defined
// as aliases for X, GC_realloc, and GC_free, respectively.
// Calloc is redefined in terms of the new malloc. X should
// be either GC_malloc or GC_malloc_uncollectable.
// The former is occasionally useful for working around leaks in code
// you don't want to (or can't) look at. It may not work for
// existing code, but it often does. Neither works on all platforms,
// since some ports use malloc or calloc to obtain system memory.
// (Probably works for UNIX, and win32.)
// -DNO_DEBUG removes GC_dump and the debugging routines it calls.
// Reduces code size slightly at the expense of debuggability.
\ No newline at end of file
/*
dataend.c
A hack to get the extent of global data for the Macintosh.
by Patrick C. Beard.
*/
long __dataend;
/*
datastart.c
A hack to get the extent of global data for the Macintosh.
by Patrick C. Beard.
*/
long __datastart;
#-----------------------------------------------------------------------------#
# Makefile.DLLs, version 0.4.
# Contributed by Fergus Henderson.
# This Makefile contains rules for creating DLLs on Windows using gnu-win32.
#-----------------------------------------------------------------------------#
# This rule creates a `.def' file, which lists the symbols that are exported
# from the DLL. We use `nm' to get a list of all the exported text (`T')
# symbols and data symbols -- including uninitialized data (`B'),
# initialized data (`D'), read-only data (`R'), and common blocks (`C').
%.def: %.a
echo EXPORTS > $@
nm $< | grep '^........ [BCDRT] _' | sed 's/[^_]*_//' >> $@
# We need to use macros to access global data:
# the user of the DLL must refer to `foo' as `(*__imp_foo)'.
# This rule creates a `_globals.h' file, which contains macros
# for doing this.
SYM_PREFIX = $(firstword $(SYM_PREFIX-$*) $*)
DLL_MACRO = $(SYM_PREFIX)_USE_DLL
IMP_MACRO = $(SYM_PREFIX)_IMP
GLOBAL_MACRO = $(SYM_PREFIX)_GLOBAL
%_globals.h: %.a
echo "/* automatically generated by Makefile.DLLs */" > $@
echo "#if defined(__GNUC__) && defined(_WIN32) \\" >> $@
echo " && defined($(DLL_MACRO))" >> $@
echo "# define $(IMP_MACRO)(name) __imp_##name" >> $@
echo "# define $(GLOBAL_MACRO)(name) (*$(IMP_MACRO)(name))" >> $@
echo "#else" >> $@
echo "# define $(GLOBAL_MACRO)(name) name" >> $@
echo "#endif" >> $@
echo "" >> $@
for sym in `nm $< | grep '^........ [BCDR] _' | sed 's/[^_]*_//'`; do \
echo "#define $$sym $(GLOBAL_MACRO)($$sym)" >> $@; \
done
# This rule creates the export object file (`foo.exp') which contains the
# jump table array; this export object file becomes part of the DLL.
# This rule also creates the import library (`foo_dll.a') which contains small
# stubs for all the functions exported by the DLL which jump to them via the
# jump table. Executables that will use the DLL must be linked against this
# stub library.
%.exp %_dll.a : %.def
dlltool $(DLLTOOLFLAGS) $(DLLTOOLFLAGS-$*) \
--def $< \
--dllname $*.dll \
--output-exp $*.exp \
--output-lib $*_dll.a
# The `sed' commands below are to convert DOS-style `C:\foo\bar'
# pathnames into Unix-style `//c/foo/bar' pathnames.
CYGWIN32_LIBS = $(shell echo \
-L`dirname \`gcc -print-file-name=libgcc.a | \
sed -e 's@^\\\\([A-Za-z]\\\\):@//\\\\1@g' -e 's@\\\\\\\\@/@g' \` ` \
-L`dirname \`gcc -print-file-name=libcygwin.a | \
sed -e 's@^\\\\([A-Za-z]\\\\):@//\\\\1@g' -e 's@\\\\\\\\@/@g' \` ` \
-L`dirname \`gcc -print-file-name=libkernel32.a | \
sed -e 's@^\\\\([A-Za-z]\\\\):@//\\\\1@g' -e 's@\\\\\\\\@/@g' \` ` \
-lgcc -lcygwin -lkernel32 -lgcc)
RELOCATABLE=yes
ifeq "$(strip $(RELOCATABLE))" "yes"
# to create relocatable DLLs, we need to do two passes
%.dll: %.exp %.a dll_fixup.o dll_init.o
$(LD) $(LDFLAGS) $(LDFLAGS-$*) --dll -o $*.base \
-e _dll_entry@12 dll_init.o \
dll_fixup.o $*.exp $*.a \
$(LDLIBS) $(LDLIBS-$*) \
$(CYGWIN32_LIBS)
$(LD) $(LDFLAGS) $(LDFLAGS-$*) --dll --base-file $*.base -o $@ \
-e _dll_entry@12 dll_init.o \
dll_fixup.o $*.exp $*.a \
$(LDLIBS) $(LDLIBS-$*) \
$(CYGWIN32_LIBS)
rm -f $*.base
else
%.dll: %.exp %.a dll_fixup.o dll_init.o
$(LD) $(LDFLAGS) $(LDFLAGS-$*) --dll -o $@ \
-e _dll_entry@12 dll_init.o \
dll_fixup.o $*.exp $*.a \
$(LDLIBS) $(LDLIBS-$*) \
$(CYGWIN32_LIBS)
endif
# This black magic piece of assembler needs to be linked in in order to
# properly terminate the list of imported DLLs.
dll_fixup.s:
echo '.section .idata$$3' > dll_fixup.s
echo '.long 0,0,0,0, 0,0,0,0' >> dll_fixup.s
# This bit is necessary to provide an initialization function for the DLL.
dll_init.c:
echo '__attribute__((stdcall))' > dll_init.c
echo 'int dll_entry(int handle, int reason, void *ptr)' >> dll_init.c
echo '{return 1; }' >> dll_init.c
dont_throw_away: dll_fixup.o dll_init.o
# Makefile for Windows NT. Assumes Microsoft compiler, and a single thread.
# DLLs are included in the root set under NT, but not under win32S.
# Use "nmake nodebug=1 all" for optimized versions of library, gctest and editor.
CPU= i386
!include <ntwin32.mak>
OBJS= alloc.obj reclaim.obj allchblk.obj misc.obj mach_dep.obj os_dep.obj mark_rts.obj headers.obj mark.obj obj_map.obj blacklst.obj finalize.obj new_hblk.obj dbg_mlc.obj malloc.obj stubborn.obj dyn_load.obj typd_mlc.obj ptr_chck.obj gc_cpp.obj mallocx.obj
all: gctest.exe cord\de.exe test_cpp.exe
.c.obj:
$(cc) $(cdebug) $(cflags) $(cvars) -DSMALL_CONFIG -DSILENT -DALL_INTERIOR_POINTERS -D__STDC__ $*.c /Fo$*.obj
.cpp.obj:
$(cc) $(cdebug) $(cflags) $(cvars) -DSMALL_CONFIG -DSILENT -DALL_INTERIOR_POINTERS $*.CPP /Fo$*.obj
$(OBJS) test.obj: gc_priv.h gc_hdrs.h gc.h
gc.lib: $(OBJS)
lib /MACHINE:i386 /out:gc.lib $(OBJS)
# The original NT SDK used lib32 instead of lib
gctest.exe: test.obj gc.lib
# The following works for win32 debugging. For win32s debugging use debugtype:coff
# and add mapsympe line.
# This produces a "GUI" applications that opens no windows and writes to the log file
# "gc.log". This is done to make the result runnable under win32s.
$(link) -debug:full -debugtype:cv $(guiflags) -stack:131072 -out:$*.exe test.obj $(guilibs) gc.lib
# mapsympe -n -o gctest.sym gctest.exe
cord\de_win.rbj: cord\de_win.res
cvtres -$(CPU) cord\de_win.res -o cord\de_win.rbj
cord\de.obj cord\de_win.obj: cord\cord.h cord\private\cord_pos.h cord\de_win.h cord\de_cmds.h
cord\de_win.res: cord\de_win.rc cord\de_win.h cord\de_cmds.h
$(rc) $(rcvars) -r -fo cord\de_win.res $(cvars) cord\de_win.rc
# Cord/de is a real win32 gui application.
cord\de.exe: cord\cordbscs.obj cord\cordxtra.obj cord\de.obj cord\de_win.obj cord\de_win.rbj gc.lib
$(link) -debug:full -debugtype:cv $(guiflags) -stack:16384 -out:cord\de.exe cord\cordbscs.obj cord\cordxtra.obj cord\de.obj cord\de_win.obj cord\de_win.rbj gc.lib $(guilibs)
gc_cpp.obj: gc_cpp.h gc.h
gc_cpp.cpp: gc_cpp.cc
copy gc_cpp.cc gc_cpp.cpp
test_cpp.cpp: test_cpp.cc
copy test_cpp.cc test_cpp.cpp
# This generates the C++ test executable. The executable expects
# a single numeric argument, which is the number of iterations.
# The output appears in the file "gc.log".
test_cpp.exe: test_cpp.obj gc_cpp.h gc.h gc.lib
$(link) -debug:full -debugtype:cv $(guiflags) -stack:16384 -out:test_cpp.exe test_cpp.obj gc.lib $(guilibs)
# Makefile for OS/2. Assumes IBM's compiler, static linking, and a single thread.
# Adding dynamic linking support seems easy, but takes a little bit of work.
# Adding thread support may be nontrivial, since we haven't yet figured out how to
# look at another thread's registers.
# Significantly revised for GC version 4.4 by Mark Boulter (Jan 1994).
OBJS= alloc.obj reclaim.obj allchblk.obj misc.obj mach_dep.obj os_dep.obj mark_rts.obj headers.obj mark.obj obj_map.obj blacklst.obj finalize.obj new_hblk.obj dbg_mlc.obj malloc.obj stubborn.obj typd_mlc.obj ptr_chck.obj mallocx.obj
CORDOBJS= cord\cordbscs.obj cord\cordxtra.obj cord\cordprnt.obj
CC= icc
CFLAGS= /O /Q /DSILENT /DSMALL_CONFIG /DALL_INTERIOR_POINTERS
# Use /Ti instead of /O for debugging
# Setjmp_test may yield overly optimistic results when compiled
# without optimization.
all: $(OBJS) gctest.exe cord\cordtest.exe
$(OBJS) test.obj: gc_priv.h gc_hdrs.h gc.h
## ERASE THE LIB FIRST - if it is already there then this command will fail
## (make sure its there or erase will fail!)
gc.lib: $(OBJS)
echo . > gc.lib
erase gc.lib
LIB gc.lib $(OBJS), gc.lst
mach_dep.obj: mach_dep.c
$(CC) $(CFLAGS) /C mach_dep.c
gctest.exe: test.obj gc.lib
$(CC) $(CFLAGS) /B"/STACK:524288" /Fegctest test.obj gc.lib
cord\cordbscs.obj: cord\cordbscs.c cord\cord.h cord\private\cord_pos.h
$(CC) $(CFLAGS) /C /Focord\cordbscs cord\cordbscs.c
cord\cordxtra.obj: cord\cordxtra.c cord\cord.h cord\private\cord_pos.h cord\ec.h
$(CC) $(CFLAGS) /C /Focord\cordxtra cord\cordxtra.c
cord\cordprnt.obj: cord\cordprnt.c cord\cord.h cord\private\cord_pos.h cord\ec.h
$(CC) $(CFLAGS) /C /Focord\cordprnt cord\cordprnt.c
cord\cordtest.exe: cord\cordtest.c cord\cord.h cord\private\cord_pos.h cord\ec.h $(CORDOBJS) gc.lib
$(CC) $(CFLAGS) /B"/STACK:65536" /Fecord\cordtest cord\cordtest.c gc.lib $(CORDOBJS)
#
# Default target
#
default: gc.o
include ../config/common.mk
#
# compilation flags, etc.
#
CPPFLAGS = $(INCLUDE) $(CONFIG_CPPFLAGS) \
-DPCR_NO_RENAME -DPCR_NO_HOSTDEP_ERR
#CFLAGS = -DPCR -DSILENT $(CONFIG_CFLAGS)
CFLAGS = -DPCR $(CONFIG_CFLAGS)
SPECIALCFLAGS = # For code involving asm's
ASPPFLAGS = $(INCLUDE) $(CONFIG_ASPPFLAGS) \
-DPCR_NO_RENAME -DPCR_NO_HOSTDEP_ERR -DASM
ASFLAGS = $(CONFIG_ASFLAGS)
LDRFLAGS = $(CONFIG_LDRFLAGS)
LDFLAGS = $(CONFIG_LDFLAGS)
#
#
#
#
# BEGIN PACKAGE-SPECIFIC PART
#
#
#
#
# Fix to point to local pcr installation directory.
PCRDIR= ..
COBJ= alloc.o reclaim.o allchblk.o misc.o os_dep.o mark_rts.o headers.o mark.o obj_map.o pcr_interface.o blacklst.o finalize.o new_hblk.o real_malloc.o dyn_load.o dbg_mlc.o malloc.o stubborn.o checksums.o solaris_threads.o typd_mlc.o ptr_chck.o mallocx.o
CSRC= reclaim.c allchblk.c misc.c alloc.c mach_dep.c os_dep.c mark_rts.c headers.c mark.c obj_map.c pcr_interface.c blacklst.c finalize.c new_hblk.c real_malloc.c dyn_load.c dbg_mlc.c malloc.c stubborn.c checksums.c solaris_threads.c typd_mlc.c ptr_chck.c mallocx.c
SHELL= /bin/sh
default: gc.o
gc.o: $(COBJ) mach_dep.o
$(LDR) $(CONFIG_LDRFLAGS) -o gc.o $(COBJ) mach_dep.o
mach_dep.o: mach_dep.c mips_mach_dep.s rs6000_mach_dep.s if_mach if_not_there
rm -f mach_dep.o
./if_mach MIPS "" as -o mach_dep.o mips_mach_dep.s
./if_mach RS6000 "" as -o mach_dep.o rs6000_mach_dep.s
./if_mach ALPHA "" as -o mach_dep.o alpha_mach_dep.s
./if_mach SPARC SUNOS5 as -o mach_dep.o sparc_mach_dep.s
./if_not_there mach_dep.o $(CC) -c $(SPECIALCFLAGS) mach_dep.c
if_mach: if_mach.c config.h
$(CC) $(CFLAGS) -o if_mach if_mach.c
if_not_there: if_not_there.c
$(CC) $(CFLAGS) -o if_not_there if_not_there.c
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.
Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
Copyright (c) 1991-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.
For more details and the names of other contributors, see the
README file and gc.h. This file describes typical use of
the collector on a machine that is already supported.
INSTALLATION:
Under UN*X, type "make test". Under OS/2 or Windows NT, copy the
appropriate makefile to MAKEFILE, read it, and type "nmake test".
Read the machine specific README if one exists. The only way to
develop code with the collector for Windows 3.1 is to develop under
Windows NT, and then to use win32S.
If you wish to use the cord (structured string) library type
"make cords". (This requires an ANSI C compiler. You may need
to redefine CC in the Makefile.)
If you wish to use the collector from C++, type
"make c++". These add further files to gc.a and to the include
subdirectory. See cord/cord.h and gc_c++.h.
TYPICAL USE:
Include "gc.h" from this directory. Link against the appropriate library
("gc.a" under UN*X). Replace calls to malloc by calls to GC_MALLOC,
and calls to realloc by calls to GC_REALLOC. If the object is known
to never contain pointers, use GC_MALLOC_ATOMIC instead of
GC_MALLOC.
Define GC_DEBUG before including gc.h for additional checking.
Should work under OSF/1 and Linux. Currently no VMS or NT support, though
the latter shouldn't be hard.
Incremental gc not yet supported under Linux because signal handler
for SIGSEGV can't get a hold of fault address. Dynamic library support
is also missing from Linux/alpha, probably for no good reason.
From Philippe Queinnec:
System: DEC/Alpha OSF1 v3.2, vendor cc
Problem: can't link if libgc has been compiled with "cc -std1".
It works if the library has been compiled with either gcc or "cc"
alone. The problem is because the variable "end" is not defined if
compiling in std1 mode (see man ld).
Proposed fix: none. Don't use cc -std1 !
===========================================================================
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.
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) Write a tool that traces back references to the appropriate root. Send me the code. (I have code that does this for old PCR.)
****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.)
[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.
Dynamic loading support requires that executables be linked with -ldld.
The alternative is to build the collector without defining DYNAMIC_LOADING
in config.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.
See README.alpha for Linux on DEC AXP info. This file applies to
Linux/Intel.
Incremental GC is supported.
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 -DLINUX_THREADS and -D_REENTRANT
specified in the Makefile.
3) Every file that makes thread calls should define 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.
4) Currently dlopen() is probably not safe. The collector must traverse
the list of libraries maintained by the runtime loader. That can
probably be an inconsistent state when a thread calling the loader is
is stopped for GC. (It's possible that this is fixable in the
same way it is handled for SOLARIS_THREADS, with GC_dlopen.)
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.
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 -DIRIX_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.)
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 config.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 config.h.)
You may want to reverse this decisions if you use -DREDIRECT_MALLOC=...
SOLARIS THREADS:
The collector must be compiled with -DSOLARIS_THREADS 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
SOLARIS_THREADS 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.
If you are using the Pthreads interface, also define _SOLARIS_PTHREADS.
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.
Jeremy Fitzhardinge points out that there is a problem with the dlopen
replacement, in that startup code in the library is run while the allocation
lock is held. This appears to be difficult to fix, since the collector does
look at data structures maintained by dlopen, and hence some locking is needed
around the dlopen call. Defining USE_PROC_FOR_LIBRARIES will get address
space layout information from /proc avoiding the dlopen lock. But this has
other disadvanatages, e.g. mmapped files may be scanned.
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.)
Alistair Crooks supplied the port. He used Lexa C version 2.1.3 with
-Xa to compile.
The collector has only been compiled under Windows NT, with the
original Microsoft SDK, with Visual C++ 2.0 and later, with
the GNU win32 environment, with Borland 4.5, and recently with
Watcom C.
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 will appear as long as it's running.
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.)
For Microsoft development tools, rename NT_MAKEFILE as
MAKEFILE. (Make sure that the CPU environment variable is defined
to be i386.)
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 config.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, config.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.
Incremental collection support was recently added. This is
currently pretty simpleminded. 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,
which is the default for win32. If you need incremental collection,
undefine SMALL_CONFIG.
Incremental collection is not supported under win32s, and it may not
be possible to do so. However, win32 applications that attempt to use
incremental collection should continue to run, since the
collector detects if it's running under win32s and turns calls to
GC_enable_incremental() into noops.
James Clark has contributed the necessary code to support win32 threads.
This code is known to exhibit some problems with incremental collection
enabled. 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.
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.
It is known to not be completely solid. At a minimum it can deadlock
if a thread starts in the middle of an allocation. There may be
other problems. If you need solid support for win32 threads, you
check with Geodesic Systems. I haven't tried it, but they claim
to support it.
Hans
Ivan V. Demakov's README for the Watcom port:
[ He points out in a later message that there may be a problem compiling
under Windows-3.11 for Windows NT. ]
Watcom C/C++ 10.5, 10.6, 11.0 tested.
The collector runs on WIN32 and DOS4GW dos-extender with both
stack and register based calling conventions (options -5r and -5s).
Incremental collection not supported.
OS/2 not tested, but should work (only some #ifdef's added for OS/2 port).
cord not ported. Watcom C fails to compile it, from first attempt.
Since I don't use it, I don't try to fix it.
cpp_test succeeds, but not compiled automaticaly with WCC_MAKEFILE.
My changes:
* config.h Added definitions for Watcom C/C++.
Undefined MPROTECT_VDB for Watcom C/C++ MSWIN32,
I don't have idea why it not work.
* gc.h Explicitly declared GC_noop. This prevents
program crash, compiled with -5r option.
* gc_priv.h Changed declaration for GC_push_one to make
compiler happy.
Added GC_dos4gw_get_mem declaration and
GET_MEM uses it in DOS4GW environment.
* os_dep.c Added __WATCOMC__ and DOS4GW #ifdef's.
Added GC_dos4gw_get_mem.
* mach_dep.c For Watcom used setjmp method of marking registers.
* WCC_MAKEFILE New file. Makefile for Watcom C/C++.
* gc_watcom.asm New file. Some functions for DOS4GW.
This functions may (probably) be done in C,
but I can't figure out how do this for all
possible options of compiler.
* README.watcom This file.
Ivan Demakov (email: dem@tgrad.nsk.su)
CPU=68030
NOSTACKCHECK
OPTIMIZE
VERBOSE
MAPHUNK
NOVERSION
NOICONS
OPTIMIZERTIME
DEFINE SILENT
DEFINE AMIGA_SKIP_SEG
IGNORE=85
IGNORE=154
IGNORE=161
IGNORE=100
OPTIMIZERCOMPLEXITY=4
OPTIMIZERDEPTH=3
OBJS= alloc.o reclaim.o allchblk.o misc.o mach_dep.o os_dep.o mark_rts.o headers.o mark.o obj_map.o blacklst.o finalize.o new_hblk.o real_malloc.o dyn_load.o dbg_mlc.o malloc.o stubborn.o checksums.o typd_mlc.o ptr_chck.o
INC= gc_private.h gc_hdrs.h gc.h config.h
all: gctest setjmp_t
alloc.o : alloc.c $(INC)
reclaim.o : reclaim.c $(INC)
allchblk.o : allchblk.c $(INC)
misc.o : misc.c $(INC)
os_dep.o : os_dep.c $(INC)
mark_rts.o : mark_rts.c $(INC)
headers.o : headers.c $(INC)
mark.o : mark.c $(INC)
obj_map.o : obj_map.c $(INC)
blacklst.o : blacklst.c $(INC)
finalize.o : finalize.c $(INC)
sc noopt finalize.c # There seems to be a bug in the optimizer (V6.51).
# gctest won't work if you remove this...
new_hblk.o : new_hblk.c $(INC)
real_malloc.o : real_malloc.c $(INC)
dyn_load.o : dyn_load.c $(INC)
dbg_mlc.o : dbg_mlc.c $(INC)
malloc.o : malloc.c $(INC)
mallocx.o : malloc.c $(INC)
stubborn.o : stubborn.c $(INC)
checksums.o : checksums.c $(INC)
typd_mlc.o: typd_mlc.c $(INC)
mach_dep.o : mach_dep.c $(INC)
ptr_chck.o: ptr_chck.c $(INC)
test.o : test.c $(INC)
gc.lib: $(OBJS)
oml gc.lib r $(OBJS)
clean:
delete gc.lib gctest setjmp_t \#?.o
gctest: gc.lib test.o
slink LIB:c.o test.o to $@ lib gc.lib LIB:sc.lib LIB:scm.lib
setjmp_t: setjmp_t.c gc.h
sc setjmp_t.c
slink LIB:c.o $@.o to $@ lib LIB:sc.lib
test: setjmp_t gctest
setjmp_t
gctest
# Makefile for Watcom C/C++ 10.5, 10.6, 11.0 on NT, OS2 and DOS4GW .
# May work with Watcom 10.0 .
#
#
# Uncoment one of line for cross compiling
#SYSTEM=DOS4GW
#SYSTEM=MSWIN32
#SYSTEM=OS2
!ifndef SYSTEM
!ifdef __MSDOS__
SYSTEM=DOS4GW
!endif
!ifdef __NT__
SYSTEM=MSWIN32
!endif
!ifdef __OS2__
SYSTEM=OS2
!endif
D_SYSTEM=
!else
D_SYSTEM=-D$(SYSTEM)
!endif
!define $(SYSTEM)
CC=wcc386
CXX=wpp386
AS=wasm
# Watcom before 11.0 not support option -oh
# Remove it if you get error
OPTIM=-oneatxh -s
CALLING=-5s
DEFS=-DALL_INTERIOR_POINTERS -DSILENT #-DSMALL_CONFIG #-DGC_DEBUG
# ! -DUSE_GENERIC required !
CFLAGS=$(OPTIM) -zp4 $(CALLING) -zc -DUSE_GENERIC $(D_SYSTEM) $(DEFS)
CXXFLAGS= $(CFLAGS)
ASFLAGS=$(CALLING)
OBJS= alloc.obj reclaim.obj allchblk.obj misc.obj &
mach_dep.obj os_dep.obj mark_rts.obj headers.obj mark.obj &
obj_map.obj blacklst.obj finalize.obj new_hblk.obj &
dbg_mlc.obj malloc.obj stubborn.obj dyn_load.obj &
typd_mlc.obj ptr_chck.obj gc_cpp.obj mallocx.obj
all: gc.lib gctest.exe
# this file required for DOS4GW only
gc_watcom.obj: gc_watcom.asm WCC_MAKEFILE
$(AS) $(ASFLAGS) gc_watcom.asm
!ifdef DOS4GW
gc.lib: $(OBJS) gc_watcom.obj
@%create $*.lb1
@for %i in ($(OBJS)) do @%append $*.lb1 +'%i'
@@%append $*.lb1 +'gc_watcom.obj'
*wlib -b -c -n -p=512 $@ @$*.lb1
!else
gc.lib: $(OBJS)
@%create $*.lb1
@for %i in ($(OBJS)) do @%append $*.lb1 +'%i'
*wlib -b -c -n -p=512 $@ @$*.lb1
!endif
test.obj: test.c
$(CC) $(CFLAGS) $*.c
gctest.exe: test.obj gc.lib
%create $*.lnk
!ifdef DOS4GW
@%append $*.lnk sys dos4g
!endif
!ifdef MSWIN32
@%append $*.lnk sys nt
!endif
!ifdef OS2
@%append $*.lnk sys os2v2
!endif
@%append $*.lnk op case
@%append $*.lnk op stack=256K
@%append $*.lnk name $*
@%append $*.lnk file test.obj
@%append $*.lnk library gc.lib
*wlink @$*.lnk
.c.obj: .AUTODEPEND
$(CC) $(CFLAGS) $*.c
.cc.obj: .AUTODEPEND
$(CXX) $(CXXFLAGS) $*.cc
.cpp.obj: .AUTODEPEND
$(CXX) $(CXXFLAGS) $*.cpp
clean : .SYMBOLIC
@if exist *.obj del *.obj
@if exist *.map del *.map
@if exist *.lnk del *.lnk
@if exist *.lb1 del *.lb1
@if exist *.sym del *.sym
@if exist *.err del *.err
@if exist *.tmp del *.tmp
@if exist *.lst del *.lst
@if exist *.exe del *.exe
@if exist *.log del *.log
# include <stdio.h>
int main(argc, argv, envp)
int argc;
char ** argv;
char ** envp;
{
int i;
for (i = 1; i < argc; i++) {
printf("gc/%s ", argv[i]);
}
return(0);
}
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.
/*
* Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-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.
*/
/* Boehm, August 9, 1995 6:09 pm PDT */
# include "gc_priv.h"
/*
* We maintain several hash tables of hblks that have had false hits.
* Each contains one bit per hash bucket; If any page in the bucket
* has had a false hit, we assume that all of them have.
* See the definition of page_hash_table in gc_private.h.
* False hits from the stack(s) are much more dangerous than false hits
* from elsewhere, since the former can pin a large object that spans the
* block, eventhough it does not start on the dangerous block.
*/
/*
* Externally callable routines are:
* GC_add_to_black_list_normal
* GC_add_to_black_list_stack
* GC_promote_black_lists
* GC_is_black_listed
*
* All require that the allocator lock is held.
*/
/* Pointers to individual tables. We replace one table by another by */
/* switching these pointers. */
word * GC_old_normal_bl;
/* Nonstack false references seen at last full */
/* collection. */
word * GC_incomplete_normal_bl;
/* Nonstack false references seen since last */
/* full collection. */
word * GC_old_stack_bl;
word * GC_incomplete_stack_bl;
word GC_total_stack_black_listed;
word GC_black_list_spacing = MINHINCR*HBLKSIZE; /* Initial rough guess */
void GC_clear_bl();
void GC_default_print_heap_obj_proc(p)
ptr_t p;
{
ptr_t base = GC_base(p);
GC_err_printf2("start: 0x%lx, appr. length: %ld", base, GC_size(base));
}
void (*GC_print_heap_obj)(/* char * s, ptr_t p */) =
GC_default_print_heap_obj_proc;
void GC_print_source_ptr(ptr_t p)
{
ptr_t base = GC_base(p);
if (0 == base) {
GC_err_printf0("in root set");
} else {
GC_err_printf0("in object at ");
(*GC_print_heap_obj)(base);
}
}
void GC_bl_init()
{
# ifndef ALL_INTERIOR_POINTERS
GC_old_normal_bl = (word *)
GC_scratch_alloc((word)(sizeof (page_hash_table)));
GC_incomplete_normal_bl = (word *)GC_scratch_alloc
((word)(sizeof(page_hash_table)));
if (GC_old_normal_bl == 0 || GC_incomplete_normal_bl == 0) {
GC_err_printf0("Insufficient memory for black list\n");
EXIT();
}
GC_clear_bl(GC_old_normal_bl);
GC_clear_bl(GC_incomplete_normal_bl);
# endif
GC_old_stack_bl = (word *)GC_scratch_alloc((word)(sizeof(page_hash_table)));
GC_incomplete_stack_bl = (word *)GC_scratch_alloc
((word)(sizeof(page_hash_table)));
if (GC_old_stack_bl == 0 || GC_incomplete_stack_bl == 0) {
GC_err_printf0("Insufficient memory for black list\n");
EXIT();
}
GC_clear_bl(GC_old_stack_bl);
GC_clear_bl(GC_incomplete_stack_bl);
}
void GC_clear_bl(doomed)
word *doomed;
{
BZERO(doomed, sizeof(page_hash_table));
}
void GC_copy_bl(old, new)
word *new, *old;
{
BCOPY(old, new, sizeof(page_hash_table));
}
static word total_stack_black_listed();
/* Signal the completion of a collection. Turn the incomplete black */
/* lists into new black lists, etc. */
void GC_promote_black_lists()
{
word * very_old_normal_bl = GC_old_normal_bl;
word * very_old_stack_bl = GC_old_stack_bl;
GC_old_normal_bl = GC_incomplete_normal_bl;
GC_old_stack_bl = GC_incomplete_stack_bl;
# ifndef ALL_INTERIOR_POINTERS
GC_clear_bl(very_old_normal_bl);
# endif
GC_clear_bl(very_old_stack_bl);
GC_incomplete_normal_bl = very_old_normal_bl;
GC_incomplete_stack_bl = very_old_stack_bl;
GC_total_stack_black_listed = total_stack_black_listed();
# ifdef PRINTSTATS
GC_printf1("%ld bytes in heap blacklisted for interior pointers\n",
(unsigned long)GC_total_stack_black_listed);
# endif
if (GC_total_stack_black_listed != 0) {
GC_black_list_spacing =
HBLKSIZE*(GC_heapsize/GC_total_stack_black_listed);
}
if (GC_black_list_spacing < 3 * HBLKSIZE) {
GC_black_list_spacing = 3 * HBLKSIZE;
}
}
void GC_unpromote_black_lists()
{
# ifndef ALL_INTERIOR_POINTERS
GC_copy_bl(GC_old_normal_bl, GC_incomplete_normal_bl);
# endif
GC_copy_bl(GC_old_stack_bl, GC_incomplete_stack_bl);
}
# ifndef ALL_INTERIOR_POINTERS
/* P is not a valid pointer reference, but it falls inside */
/* the plausible heap bounds. */
/* Add it to the normal incomplete black list if appropriate. */
#ifdef PRINT_BLACK_LIST
void GC_add_to_black_list_normal(p, source)
ptr_t source;
#else
void GC_add_to_black_list_normal(p)
#endif
word p;
{
if (!(GC_modws_valid_offsets[p & (sizeof(word)-1)])) return;
{
register int index = PHT_HASH(p);
if (HDR(p) == 0 || get_pht_entry_from_index(GC_old_normal_bl, index)) {
# ifdef PRINT_BLACK_LIST
if (!get_pht_entry_from_index(GC_incomplete_normal_bl, index)) {
GC_err_printf2(
"Black listing (normal) 0x%lx referenced from 0x%lx ",
(unsigned long) p, (unsigned long) source);
GC_print_source_ptr(source);
GC_err_puts("\n");
}
# endif
set_pht_entry_from_index(GC_incomplete_normal_bl, index);
} /* else this is probably just an interior pointer to an allocated */
/* object, and isn't worth black listing. */
}
}
# endif
/* And the same for false pointers from the stack. */
#ifdef PRINT_BLACK_LIST
void GC_add_to_black_list_stack(p, source)
ptr_t source;
#else
void GC_add_to_black_list_stack(p)
#endif
word p;
{
register int index = PHT_HASH(p);
if (HDR(p) == 0 || get_pht_entry_from_index(GC_old_stack_bl, index)) {
# ifdef PRINT_BLACK_LIST
if (!get_pht_entry_from_index(GC_incomplete_stack_bl, index)) {
GC_err_printf2(
"Black listing (stack) 0x%lx referenced from 0x%lx ",
(unsigned long)p, (unsigned long)source);
GC_print_source_ptr(source);
GC_err_puts("\n");
}
# endif
set_pht_entry_from_index(GC_incomplete_stack_bl, index);
}
}
/*
* Is the block starting at h of size len bytes black listed? If so,
* return the address of the next plausible r such that (r, len) might not
* be black listed. (R may not actually be in the heap. We guarantee only
* that every smaller value of r after h is also black listed.)
* If (h,len) is not black listed, return 0.
* Knows about the structure of the black list hash tables.
*/
struct hblk * GC_is_black_listed(h, len)
struct hblk * h;
word len;
{
register int index = PHT_HASH((word)h);
register word i;
word nblocks = divHBLKSZ(len);
# ifndef ALL_INTERIOR_POINTERS
if (get_pht_entry_from_index(GC_old_normal_bl, index)
|| get_pht_entry_from_index(GC_incomplete_normal_bl, index)) {
return(h+1);
}
# endif
for (i = 0; ; ) {
if (GC_old_stack_bl[divWORDSZ(index)] == 0
&& GC_incomplete_stack_bl[divWORDSZ(index)] == 0) {
/* An easy case */
i += WORDSZ - modWORDSZ(index);
} else {
if (get_pht_entry_from_index(GC_old_stack_bl, index)
|| get_pht_entry_from_index(GC_incomplete_stack_bl, index)) {
return(h+i+1);
}
i++;
}
if (i >= nblocks) break;
index = PHT_HASH((word)(h+i));
}
return(0);
}
/* Return the number of blacklisted blocks in a given range. */
/* Used only for statistical purposes. */
/* Looks only at the GC_incomplete_stack_bl. */
word GC_number_stack_black_listed(start, endp1)
struct hblk *start, *endp1;
{
register struct hblk * h;
word result = 0;
for (h = start; h < endp1; h++) {
register int index = PHT_HASH((word)h);
if (get_pht_entry_from_index(GC_old_stack_bl, index)) result++;
}
return(result);
}
/* Return the total number of (stack) black-listed bytes. */
static word total_stack_black_listed()
{
register unsigned i;
word total = 0;
for (i = 0; i < GC_n_heap_sects; i++) {
struct hblk * start = (struct hblk *) GC_heap_sects[i].hs_start;
word len = (word) GC_heap_sects[i].hs_bytes;
struct hblk * endp1 = start + len/HBLKSIZE;
total += GC_number_stack_black_listed(start, endp1);
}
return(total * HBLKSIZE);
}
#!/bin/sh
GC_DEBUG=1
export GC_DEBUG
$* 2>&1 | awk '{print "0x3e=c\""$0"\""};/^\t##PC##=/ {if ($2 != 0) {print $2"?i"}}' | adb $1 | sed "s/^ >/>/"
/*
* Copyright (c) 1992-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.
*/
/* Boehm, March 29, 1995 12:51 pm PST */
# ifdef CHECKSUMS
# include "gc_priv.h"
/* This is debugging code intended to verify the results of dirty bit */
/* computations. Works only in a single threaded environment. */
/* We assume that stubborn objects are changed only when they are */
/* enabled for writing. (Certain kinds of writing are actually */
/* safe under other conditions.) */
# define NSUMS 2000
# define OFFSET 0x10000
typedef struct {
GC_bool new_valid;
word old_sum;
word new_sum;
struct hblk * block; /* Block to which this refers + OFFSET */
/* to hide it from colector. */
} page_entry;
page_entry GC_sums [NSUMS];
word GC_checksum(h)
struct hblk *h;
{
register word *p = (word *)h;
register word *lim = (word *)(h+1);
register word result = 0;
while (p < lim) {
result += *p++;
}
return(result | 0x80000000 /* doesn't look like pointer */);
}
# ifdef STUBBORN_ALLOC
/* Check whether a stubborn object from the given block appears on */
/* the appropriate free list. */
GC_bool GC_on_free_list(h)
struct hblk *h;
{
register hdr * hhdr = HDR(h);
register int sz = hhdr -> hb_sz;
ptr_t p;
if (sz > MAXOBJSZ) return(FALSE);
for (p = GC_sobjfreelist[sz]; p != 0; p = obj_link(p)) {
if (HBLKPTR(p) == h) return(TRUE);
}
return(FALSE);
}
# endif
int GC_n_dirty_errors;
int GC_n_changed_errors;
int GC_n_clean;
int GC_n_dirty;
void GC_update_check_page(h, index)
struct hblk *h;
int index;
{
page_entry *pe = GC_sums + index;
register hdr * hhdr = HDR(h);
if (pe -> block != 0 && pe -> block != h + OFFSET) ABORT("goofed");
pe -> old_sum = pe -> new_sum;
pe -> new_sum = GC_checksum(h);
# ifndef MSWIN32
if (pe -> new_sum != 0 && !GC_page_was_ever_dirty(h)) {
GC_printf1("GC_page_was_ever_dirty(0x%lx) is wrong\n",
(unsigned long)h);
}
# endif
if (GC_page_was_dirty(h)) {
GC_n_dirty++;
} else {
GC_n_clean++;
}
if (pe -> new_valid && pe -> old_sum != pe -> new_sum) {
if (!GC_page_was_dirty(h) || !GC_page_was_ever_dirty(h)) {
/* Set breakpoint here */GC_n_dirty_errors++;
}
# ifdef STUBBORN_ALLOC
if (!IS_FORWARDING_ADDR_OR_NIL(hhdr)
&& hhdr -> hb_map != GC_invalid_map
&& hhdr -> hb_obj_kind == STUBBORN
&& !GC_page_was_changed(h)
&& !GC_on_free_list(h)) {
/* if GC_on_free_list(h) then reclaim may have touched it */
/* without any allocations taking place. */
/* Set breakpoint here */GC_n_changed_errors++;
}
# endif
}
pe -> new_valid = TRUE;
pe -> block = h + OFFSET;
}
word GC_bytes_in_used_blocks;
void GC_add_block(h, dummy)
struct hblk *h;
word dummy;
{
register hdr * hhdr = HDR(h);
register bytes = WORDS_TO_BYTES(hhdr -> hb_sz);
bytes += HDR_BYTES + HBLKSIZE-1;
bytes &= ~(HBLKSIZE-1);
GC_bytes_in_used_blocks += bytes;
}
void GC_check_blocks()
{
word bytes_in_free_blocks = 0;
struct hblk * h = GC_hblkfreelist;
hdr * hhdr = HDR(h);
word sz;
GC_bytes_in_used_blocks = 0;
GC_apply_to_all_blocks(GC_add_block, (word)0);
while (h != 0) {
sz = hhdr -> hb_sz;
bytes_in_free_blocks += sz;
h = hhdr -> hb_next;
hhdr = HDR(h);
}
GC_printf2("GC_bytes_in_used_blocks = %ld, bytes_in_free_blocks = %ld ",
GC_bytes_in_used_blocks, bytes_in_free_blocks);
GC_printf1("GC_heapsize = %ld\n", GC_heapsize);
if (GC_bytes_in_used_blocks + bytes_in_free_blocks != GC_heapsize) {
GC_printf0("LOST SOME BLOCKS!!\n");
}
}
/* Should be called immediately after GC_read_dirty and GC_read_changed. */
void GC_check_dirty()
{
register int index;
register unsigned i;
register struct hblk *h;
register ptr_t start;
GC_check_blocks();
GC_n_dirty_errors = 0;
GC_n_changed_errors = 0;
GC_n_clean = 0;
GC_n_dirty = 0;
index = 0;
for (i = 0; i < GC_n_heap_sects; i++) {
start = GC_heap_sects[i].hs_start;
for (h = (struct hblk *)start;
h < (struct hblk *)(start + GC_heap_sects[i].hs_bytes);
h++) {
GC_update_check_page(h, index);
index++;
if (index >= NSUMS) goto out;
}
}
out:
GC_printf2("Checked %lu clean and %lu dirty pages\n",
(unsigned long) GC_n_clean, (unsigned long) GC_n_dirty);
if (GC_n_dirty_errors > 0) {
GC_printf1("Found %lu dirty bit errors\n",
(unsigned long)GC_n_dirty_errors);
}
if (GC_n_changed_errors > 0) {
GC_printf1("Found %lu changed bit errors\n",
(unsigned long)GC_n_changed_errors);
GC_printf0("These may be benign (provoked by nonpointer changes)\n");
# ifdef THREADS
GC_printf0(
"Also expect 1 per thread currently allocating a stubborn obj.\n");
# endif
}
}
# else
extern int GC_quiet;
/* ANSI C doesn't allow translation units to be empty. */
/* So we guarantee this one is nonempty. */
# endif /* CHECKSUMS */
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 (boehm@sgi.com).
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.
MATH=STANDARD
CPU=68030
NOSTACKCHECK
OPTIMIZE
VERBOSE
NOVERSION
NOICONS
OPTIMIZERTIME
INCLUDEDIR=/
DEFINE AMIGA
LIBRARY=cord.lib
LIBRARY=/gc.lib
IGNORE=100
IGNORE=161
# Makefile for cord.lib
# Michel Schinz 1994/07/20
OBJS = cordbscs.o cordprnt.o cordxtra.o
all: cord.lib cordtest
cordbscs.o: cordbscs.c
cordprnt.o: cordprnt.c
cordxtra.o: cordxtra.c
cordtest.o: cordtest.c
cord.lib: $(OBJS)
oml cord.lib r $(OBJS)
cordtest: cordtest.o cord.lib
sc cordtest.o link
clean:
delete cord.lib cordtest \#?.o \#?.lnk
/*
* 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.
*/
/* Boehm, August 24, 1994 11:58 am PDT */
# include "cord.h"
# include <string.h>
# include <stdio.h>
/* This is a very incomplete test of the cord package. It knows about */
/* a few internals of the package (e.g. when C strings are returned) */
/* that real clients shouldn't rely on. */
# define ABORT(string) \
{ int x = 0; fprintf(stderr, "FAILED: %s\n", string); x = 1 / x; abort(); }
int count;
int test_fn(char c, void * client_data)
{
if (client_data != (void *)13) ABORT("bad client data");
if (count < 64*1024+1) {
if ((count & 1) == 0) {
if (c != 'b') ABORT("bad char");
} else {
if (c != 'a') ABORT("bad char");
}
count++;
return(0);
} else {
if (c != 'c') ABORT("bad char");
count++;
return(1);
}
}
char id_cord_fn(size_t i, void * client_data)
{
return((char)i);
}
void test_basics()
{
CORD x = CORD_from_char_star("ab");
register int i;
char c;
CORD y;
CORD_pos p;
x = CORD_cat(x,x);
if (!CORD_IS_STRING(x)) ABORT("short cord should usually be a string");
if (strcmp(x, "abab") != 0) ABORT("bad CORD_cat result");
for (i = 1; i < 16; i++) {
x = CORD_cat(x,x);
}
x = CORD_cat(x,"c");
if (CORD_len(x) != 128*1024+1) ABORT("bad length");
count = 0;
if (CORD_iter5(x, 64*1024-1, test_fn, CORD_NO_FN, (void *)13) == 0) {
ABORT("CORD_iter5 failed");
}
if (count != 64*1024 + 2) ABORT("CORD_iter5 failed");
count = 0;
CORD_set_pos(p, x, 64*1024-1);
while(CORD_pos_valid(p)) {
(void) test_fn(CORD_pos_fetch(p), (void *)13);
CORD_next(p);
}
if (count != 64*1024 + 2) ABORT("Position based iteration failed");
y = CORD_substr(x, 1023, 5);
if (!CORD_IS_STRING(y)) ABORT("short cord should usually be a string");
if (strcmp(y, "babab") != 0) ABORT("bad CORD_substr result");
y = CORD_substr(x, 1024, 8);
if (!CORD_IS_STRING(y)) ABORT("short cord should usually be a string");
if (strcmp(y, "abababab") != 0) ABORT("bad CORD_substr result");
y = CORD_substr(x, 128*1024-1, 8);
if (!CORD_IS_STRING(y)) ABORT("short cord should usually be a string");
if (strcmp(y, "bc") != 0) ABORT("bad CORD_substr result");
x = CORD_balance(x);
if (CORD_len(x) != 128*1024+1) ABORT("bad length");
count = 0;
if (CORD_iter5(x, 64*1024-1, test_fn, CORD_NO_FN, (void *)13) == 0) {
ABORT("CORD_iter5 failed");
}
if (count != 64*1024 + 2) ABORT("CORD_iter5 failed");
y = CORD_substr(x, 1023, 5);
if (!CORD_IS_STRING(y)) ABORT("short cord should usually be a string");
if (strcmp(y, "babab") != 0) ABORT("bad CORD_substr result");
y = CORD_from_fn(id_cord_fn, 0, 13);
i = 0;
CORD_set_pos(p, y, i);
while(CORD_pos_valid(p)) {
c = CORD_pos_fetch(p);
if(c != i) ABORT("Traversal of function node failed");
CORD_next(p); i++;
}
if (i != 13) ABORT("Bad apparent length for function node");
}
void test_extras()
{
# if defined(__OS2__)
# define FNAME1 "tmp1"
# define FNAME2 "tmp2"
# elif defined(AMIGA)
# define FNAME1 "T:tmp1"
# define FNAME2 "T:tmp2"
# else
# define FNAME1 "/tmp/cord_test"
# define FNAME2 "/tmp/cord_test2"
# endif
register int i;
CORD y = "abcdefghijklmnopqrstuvwxyz0123456789";
CORD x = "{}";
CORD w, z;
FILE *f;
FILE *f1a, *f1b, *f2;
w = CORD_cat(CORD_cat(y,y),y);
z = CORD_catn(3,y,y,y);
if (CORD_cmp(w,z) != 0) ABORT("CORD_catn comparison wrong");
for (i = 1; i < 100; i++) {
x = CORD_cat(x, y);
}
z = CORD_balance(x);
if (CORD_cmp(x,z) != 0) ABORT("balanced string comparison wrong");
if (CORD_cmp(x,CORD_cat(z, CORD_nul(13))) >= 0) ABORT("comparison 2");
if (CORD_cmp(CORD_cat(x, CORD_nul(13)), z) <= 0) ABORT("comparison 3");
if (CORD_cmp(x,CORD_cat(z, "13")) >= 0) ABORT("comparison 4");
if ((f = fopen(FNAME1, "w")) == 0) ABORT("open failed");
if (CORD_put(z,f) == EOF) ABORT("CORD_put failed");
if (fclose(f) == EOF) ABORT("fclose failed");
w = CORD_from_file(f1a = fopen(FNAME1, "rb"));
if (CORD_len(w) != CORD_len(z)) ABORT("file length wrong");
if (CORD_cmp(w,z) != 0) ABORT("file comparison wrong");
if (CORD_cmp(CORD_substr(w, 50*36+2, 36), y) != 0)
ABORT("file substr wrong");
z = CORD_from_file_lazy(f1b = fopen(FNAME1, "rb"));
if (CORD_cmp(w,z) != 0) ABORT("File conversions differ");
if (CORD_chr(w, 0, '9') != 37) ABORT("CORD_chr failed 1");
if (CORD_chr(w, 3, 'a') != 38) ABORT("CORD_chr failed 2");
if (CORD_rchr(w, CORD_len(w) - 1, '}') != 1) ABORT("CORD_rchr failed");
x = y;
for (i = 1; i < 14; i++) {
x = CORD_cat(x,x);
}
if ((f = fopen(FNAME2, "w")) == 0) ABORT("2nd open failed");
if (CORD_put(x,f) == EOF) ABORT("CORD_put failed");
if (fclose(f) == EOF) ABORT("fclose failed");
w = CORD_from_file(f2 = fopen(FNAME2, "rb"));
if (CORD_len(w) != CORD_len(x)) ABORT("file length wrong");
if (CORD_cmp(w,x) != 0) ABORT("file comparison wrong");
if (CORD_cmp(CORD_substr(w, 1000*36, 36), y) != 0)
ABORT("file substr wrong");
if (strcmp(CORD_to_char_star(CORD_substr(w, 1000*36, 36)), y) != 0)
ABORT("char * file substr wrong");
if (strcmp(CORD_substr(w, 1000*36, 2), "ab") != 0)
ABORT("short file substr wrong");
if (CORD_str(x,1,"9a") != 35) ABORT("CORD_str failed 1");
if (CORD_str(x,0,"9abcdefghijk") != 35) ABORT("CORD_str failed 2");
if (CORD_str(x,0,"9abcdefghijx") != CORD_NOT_FOUND)
ABORT("CORD_str failed 3");
if (CORD_str(x,0,"9>") != CORD_NOT_FOUND) ABORT("CORD_str failed 4");
if (remove(FNAME1) != 0) {
/* On some systems, e.g. OS2, this may fail if f1 is still open. */
if ((fclose(f1a) == EOF) & (fclose(f1b) == EOF))
ABORT("fclose(f1) failed");
if (remove(FNAME1) != 0) ABORT("remove 1 failed");
}
if (remove(FNAME2) != 0) {
if (fclose(f2) == EOF) ABORT("fclose(f2) failed");
if (remove(FNAME2) != 0) ABORT("remove 2 failed");
}
}
void test_printf()
{
CORD result;
char result2[200];
long l;
short s;
CORD x;
if (CORD_sprintf(&result, "%7.2f%ln", 3.14159F, &l) != 7)
ABORT("CORD_sprintf failed 1");
if (CORD_cmp(result, " 3.14") != 0)ABORT("CORD_sprintf goofed 1");
if (l != 7) ABORT("CORD_sprintf goofed 2");
if (CORD_sprintf(&result, "%-7.2s%hn%c%s", "abcd", &s, 'x', "yz") != 10)
ABORT("CORD_sprintf failed 2");
if (CORD_cmp(result, "ab xyz") != 0)ABORT("CORD_sprintf goofed 3");
if (s != 7) ABORT("CORD_sprintf goofed 4");
x = "abcdefghij";
x = CORD_cat(x,x);
x = CORD_cat(x,x);
x = CORD_cat(x,x);
if (CORD_sprintf(&result, "->%-120.78r!\n", x) != 124)
ABORT("CORD_sprintf failed 3");
(void) sprintf(result2, "->%-120.78s!\n", CORD_to_char_star(x));
if (CORD_cmp(result, result2) != 0)ABORT("CORD_sprintf goofed 5");
}
main()
{
# ifdef THINK_C
printf("cordtest:\n");
# endif
test_basics();
test_extras();
test_printf();
CORD_fprintf(stderr, "SUCCEEDED\n");
return(0);
}
/*
* 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.
*/
/* Boehm, May 19, 1994 2:24 pm PDT */
#ifndef DE_CMDS_H
# define DE_CMDS_H
# define UP 16 /* ^P */
# define DOWN 14 /* ^N */
# define LEFT 2 /* ^B */
# define RIGHT 6 /* ^F */
# define DEL 127 /* ^? */
# define BS 8 /* ^H */
# define UNDO 21 /* ^U */
# define WRITE 23 /* ^W */
# define QUIT 4 /* ^D */
# define REPEAT 18 /* ^R */
# define LOCATE 12 /* ^L */
# define TOP 20 /* ^T */
#endif
/*
* Copyright (c) 1991-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 copy this garbage collector for any purpose,
* provided the above notices are retained on all copies.
*/
/* Boehm, May 13, 1994 9:50 am PDT */
#include "windows.h"
#include "de_cmds.h"
#include "de_win.h"
ABOUTBOX DIALOG 19, 21, 163, 47
STYLE DS_MODALFRAME | WS_POPUP | WS_CAPTION | WS_SYSMENU
CAPTION "About Demonstration Text Editor"
BEGIN
ICON "DE", -1, 8, 8, 13, 13, WS_CHILD | WS_VISIBLE
LTEXT "Demonstration Text Editor", -1, 44, 8, 118, 8, WS_CHILD | WS_VISIBLE | WS_GROUP
LTEXT "Version 4.1", -1, 44, 16, 60, 8, WS_CHILD | WS_VISIBLE | WS_GROUP
PUSHBUTTON "OK", IDOK, 118, 27, 24, 14, WS_CHILD | WS_VISIBLE | WS_TABSTOP
END
DE MENU
BEGIN
POPUP "&File"
BEGIN
MENUITEM "&Save\t^W", IDM_FILESAVE
MENUITEM "E&xit\t^D", IDM_FILEEXIT
END
POPUP "&Edit"
BEGIN
MENUITEM "Page &Down\t^R^N", IDM_EDITPDOWN
MENUITEM "Page &Up\t^R^P", IDM_EDITPUP
MENUITEM "U&ndo\t^U", IDM_EDITUNDO
MENUITEM "&Locate\t^L ... ^L", IDM_EDITLOCATE
MENUITEM "D&own\t^N", IDM_EDITDOWN
MENUITEM "U&p\t^P", IDM_EDITUP
MENUITEM "Le&ft\t^B", IDM_EDITLEFT
MENUITEM "&Right\t^F", IDM_EDITRIGHT
MENUITEM "Delete &Backward\tBS", IDM_EDITBS
MENUITEM "Delete F&orward\tDEL", IDM_EDITDEL
MENUITEM "&Top\t^T", IDM_EDITTOP
END
POPUP "&Help"
BEGIN
MENUITEM "&Contents", IDM_HELPCONTENTS
MENUITEM "&About...", IDM_HELPABOUT
END
MENUITEM "Page_&Down", IDM_EDITPDOWN
MENUITEM "Page_&Up", IDM_EDITPUP
END
DE ACCELERATORS
BEGIN
"^R", IDM_EDITREPEAT
"^N", IDM_EDITDOWN
"^P", IDM_EDITUP
"^L", IDM_EDITLOCATE
"^B", IDM_EDITLEFT
"^F", IDM_EDITRIGHT
"^T", IDM_EDITTOP
VK_DELETE, IDM_EDITDEL, VIRTKEY
VK_BACK, IDM_EDITBS, VIRTKEY
END
DE ICON cord\de_win.ICO
/*
* 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.
*/
/* Boehm, May 19, 1994 2:25 pm PDT */
/* cord.h, de_cmds.h, and windows.h should be included before this. */
# define OTHER_FLAG 0x100
# define EDIT_CMD_FLAG 0x200
# define REPEAT_FLAG 0x400
# define CHAR_CMD(i) ((i) & 0xff)
/* MENU: DE */
#define IDM_FILESAVE (EDIT_CMD_FLAG + WRITE)
#define IDM_FILEEXIT (OTHER_FLAG + 1)
#define IDM_HELPABOUT (OTHER_FLAG + 2)
#define IDM_HELPCONTENTS (OTHER_FLAG + 3)
#define IDM_EDITPDOWN (REPEAT_FLAG + EDIT_CMD_FLAG + DOWN)
#define IDM_EDITPUP (REPEAT_FLAG + EDIT_CMD_FLAG + UP)
#define IDM_EDITUNDO (EDIT_CMD_FLAG + UNDO)
#define IDM_EDITLOCATE (EDIT_CMD_FLAG + LOCATE)
#define IDM_EDITDOWN (EDIT_CMD_FLAG + DOWN)
#define IDM_EDITUP (EDIT_CMD_FLAG + UP)
#define IDM_EDITLEFT (EDIT_CMD_FLAG + LEFT)
#define IDM_EDITRIGHT (EDIT_CMD_FLAG + RIGHT)
#define IDM_EDITBS (EDIT_CMD_FLAG + BS)
#define IDM_EDITDEL (EDIT_CMD_FLAG + DEL)
#define IDM_EDITREPEAT (EDIT_CMD_FLAG + REPEAT)
#define IDM_EDITTOP (EDIT_CMD_FLAG + TOP)
/* Windows UI stuff */
LRESULT CALLBACK WndProc (HWND hwnd, UINT message,
UINT wParam, LONG lParam);
LRESULT CALLBACK AboutBox( HWND hDlg, UINT message,
UINT wParam, LONG lParam );
/* Screen dimensions. Maintained by de_win.c. */
extern int LINES;
extern int COLS;
/* File being edited. */
extern char * arg_file_name;
/* Current display position in file. Maintained by de.c */
extern int dis_line;
extern int dis_col;
/* Current cursor position in file. */
extern int line;
extern int col;
/*
* Calls from de_win.c to de.c
*/
CORD retrieve_screen_line(int i);
/* Get the contents of i'th screen line. */
/* Relies on COLS. */
void set_position(int x, int y);
/* Set column, row. Upper left of window = (0,0). */
void do_command(int);
/* Execute an editor command. */
/* Agument is a command character or one */
/* of the IDM_ commands. */
void generic_init(void);
/* OS independent initialization */
/*
* Calls from de.c to de_win.c
*/
void move_cursor(int column, int line);
/* Physically move the cursor on the display, */
/* so that it appears at */
/* (column, line). */
void invalidate_line(int line);
/* Invalidate line i on the screen. */
void de_error(char *s);
/* Display error message. */
\ No newline at end of file
# ifndef EC_H
# define EC_H
# ifndef CORD_H
# include "cord.h"
# endif
/* Extensible cords are strings that may be destructively appended to. */
/* They allow fast construction of cords from characters that are */
/* being read from a stream. */
/*
* A client might look like:
*
* {
* CORD_ec x;
* CORD result;
* char c;
* FILE *f;
*
* ...
* CORD_ec_init(x);
* while(...) {
* c = getc(f);
* ...
* CORD_ec_append(x, c);
* }
* result = CORD_balance(CORD_ec_to_cord(x));
*
* If a C string is desired as the final result, the call to CORD_balance
* may be replaced by a call to CORD_to_char_star.
*/
# ifndef CORD_BUFSZ
# define CORD_BUFSZ 128
# endif
typedef struct CORD_ec_struct {
CORD ec_cord;
char * ec_bufptr;
char ec_buf[CORD_BUFSZ+1];
} CORD_ec[1];
/* This structure represents the concatenation of ec_cord with */
/* ec_buf[0 ... (ec_bufptr-ec_buf-1)] */
/* Flush the buffer part of the extended chord into ec_cord. */
/* Note that this is almost the only real function, and it is */
/* implemented in 6 lines in cordxtra.c */
void CORD_ec_flush_buf(CORD_ec x);
/* Convert an extensible cord to a cord. */
# define CORD_ec_to_cord(x) (CORD_ec_flush_buf(x), (x)[0].ec_cord)
/* Initialize an extensible cord. */
# define CORD_ec_init(x) ((x)[0].ec_cord = 0, (x)[0].ec_bufptr = (x)[0].ec_buf)
/* Append a character to an extensible cord. */
# define CORD_ec_append(x, c) \
{ \
if ((x)[0].ec_bufptr == (x)[0].ec_buf + CORD_BUFSZ) { \
CORD_ec_flush_buf(x); \
} \
*((x)[0].ec_bufptr)++ = (c); \
}
/* Append a cord to an extensible cord. Structure remains shared with */
/* original. */
void CORD_ec_append_cord(CORD_ec x, CORD s);
# endif /* EC_H */
/*
* 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.
*/
/* Boehm, May 19, 1994 2:23 pm PDT */
# ifndef CORD_POSITION_H
/* The representation of CORD_position. This is private to the */
/* implementation, but the size is known to clients. Also */
/* the implementation of some exported macros relies on it. */
/* Don't use anything defined here and not in cord.h. */
# define MAX_DEPTH 48
/* The maximum depth of a balanced cord + 1. */
/* We don't let cords get deeper than MAX_DEPTH. */
struct CORD_pe {
CORD pe_cord;
size_t pe_start_pos;
};
/* A structure describing an entry on the path from the root */
/* to current position. */
typedef struct CORD_Pos {
size_t cur_pos;
int path_len;
# define CORD_POS_INVALID (0x55555555)
/* path_len == INVALID <==> position invalid */
const char *cur_leaf; /* Current leaf, if it is a string. */
/* If the current leaf is a function, */
/* then this may point to function_buf */
/* containing the next few characters. */
/* Always points to a valid string */
/* containing the current character */
/* unless cur_end is 0. */
size_t cur_start; /* Start position of cur_leaf */
size_t cur_end; /* Ending position of cur_leaf */
/* 0 if cur_leaf is invalid. */
struct CORD_pe path[MAX_DEPTH + 1];
/* path[path_len] is the leaf corresponding to cur_pos */
/* path[0].pe_cord is the cord we point to. */
# define FUNCTION_BUF_SZ 8
char function_buf[FUNCTION_BUF_SZ]; /* Space for next few chars */
/* from function node. */
} CORD_pos[1];
/* Extract the cord from a position: */
CORD CORD_pos_to_cord(CORD_pos p);
/* Extract the current index from a position: */
size_t CORD_pos_to_index(CORD_pos p);
/* Fetch the character located at the given position: */
char CORD_pos_fetch(CORD_pos p);
/* Initialize the position to refer to the give cord and index. */
/* Note that this is the most expensive function on positions: */
void CORD_set_pos(CORD_pos p, CORD x, size_t i);
/* Advance the position to the next character. */
/* P must be initialized and valid. */
/* Invalidates p if past end: */
void CORD_next(CORD_pos p);
/* Move the position to the preceding character. */
/* P must be initialized and valid. */
/* Invalidates p if past beginning: */
void CORD_prev(CORD_pos p);
/* Is the position valid, i.e. inside the cord? */
int CORD_pos_valid(CORD_pos p);
char CORD__pos_fetch(CORD_pos);
void CORD__next(CORD_pos);
void CORD__prev(CORD_pos);
#define CORD_pos_fetch(p) \
(((p)[0].cur_end != 0)? \
(p)[0].cur_leaf[(p)[0].cur_pos - (p)[0].cur_start] \
: CORD__pos_fetch(p))
#define CORD_next(p) \
(((p)[0].cur_pos + 1 < (p)[0].cur_end)? \
(p)[0].cur_pos++ \
: (CORD__next(p), 0))
#define CORD_prev(p) \
(((p)[0].cur_end != 0 && (p)[0].cur_pos > (p)[0].cur_start)? \
(p)[0].cur_pos-- \
: (CORD__prev(p), 0))
#define CORD_pos_to_index(p) ((p)[0].cur_pos)
#define CORD_pos_to_cord(p) ((p)[0].path[0].pe_cord)
#define CORD_pos_valid(p) ((p)[0].path_len != CORD_POS_INVALID)
/* Some grubby stuff for performance-critical friends: */
#define CORD_pos_chars_left(p) ((long)((p)[0].cur_end) - (long)((p)[0].cur_pos))
/* Number of characters in cache. <= 0 ==> none */
#define CORD_pos_advance(p,n) ((p)[0].cur_pos += (n) - 1, CORD_next(p))
/* Advance position by n characters */
/* 0 < n < CORD_pos_chars_left(p) */
#define CORD_pos_cur_char_addr(p) \
(p)[0].cur_leaf + ((p)[0].cur_pos - (p)[0].cur_start)
/* address of current character in cache. */
#endif
This diff is collapsed. Click to expand it.
.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.
/*************************************************************************
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.
Last modified on Sat Nov 19 19:31:14 PST 1994 by ellis
on Sat Jun 8 15:10:00 PST 1994 by boehm
Permission is hereby granted to copy this code for any purpose,
provided the above notices are retained on all copies.
This implementation module for gc_c++.h provides an implementation of
the global operators "new" and "delete" that calls the Boehm
allocator. All objects allocated by this implementation will be
non-collectable but part of the root set of the collector.
You should ensure (using implementation-dependent techniques) that the
linker finds this module before the library that defines the default
built-in "new" and "delete".
Authors: John R. Ellis and Jesse Hull
**************************************************************************/
/* Boehm, December 20, 1994 7:26 pm PST */
#include "gc_cpp.h"
void* operator new( size_t size ) {
return GC_MALLOC_UNCOLLECTABLE( size );}
void operator delete( void* obj ) {
GC_FREE( obj );}
#ifdef OPERATOR_NEW_ARRAY
void* operator new[]( size_t size ) {
return GC_MALLOC_UNCOLLECTABLE( size );}
void operator delete[]( void* obj ) {
GC_FREE( obj );}
#endif /* OPERATOR_NEW_ARRAY */
#ifndef GC_CPP_H
#define GC_CPP_H
/****************************************************************************
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.
****************************************************************************
C++ Interface to the Boehm Collector
John R. Ellis and Jesse Hull
Last modified on Mon Jul 24 15:43:42 PDT 1995 by ellis
This interface provides access to the Boehm collector. It provides
basic facilities similar to those described in "Safe, Efficient
Garbage Collection for C++", by John R. Elis and David L. Detlefs
(ftp.parc.xerox.com:/pub/ellis/gc).
All heap-allocated objects are either "collectable" or
"uncollectable". Programs must explicitly delete uncollectable
objects, whereas the garbage collector will automatically delete
collectable objects when it discovers them to be inaccessible.
Collectable objects may freely point at uncollectable objects and vice
versa.
Objects allocated with the built-in "::operator new" are uncollectable.
Objects derived from class "gc" are collectable. For example:
class A: public gc {...};
A* a = new A; // a is collectable.
Collectable instances of non-class types can be allocated using the GC
placement:
typedef int A[ 10 ];
A* a = new (GC) A;
Uncollectable instances of classes derived from "gc" can be allocated
using the NoGC placement:
class A: public gc {...};
A* a = new (NoGC) A; // a is uncollectable.
Both uncollectable and collectable objects can be explicitly deleted
with "delete", which invokes an object's destructors and frees its
storage immediately.
A collectable object may have a clean-up function, which will be
invoked when the collector discovers the object to be inaccessible.
An object derived from "gc_cleanup" or containing a member derived
from "gc_cleanup" has a default clean-up function that invokes the
object's destructors. Explicit clean-up functions may be specified as
an additional placement argument:
A* a = ::new (GC, MyCleanup) A;
An object is considered "accessible" by the collector if it can be
reached by a path of pointers from static variables, automatic
variables of active functions, or from some object with clean-up
enabled; pointers from an object to itself are ignored.
Thus, if objects A and B both have clean-up functions, and A points at
B, B is considered accessible. After A's clean-up is invoked and its
storage released, B will then become inaccessible and will have its
clean-up invoked. If A points at B and B points to A, forming a
cycle, then that's considered a storage leak, and neither will be
collectable. See the interface gc.h for low-level facilities for
handling such cycles of objects with clean-up.
The collector cannot guarrantee that it will find all inaccessible
objects. In practice, it finds almost all of them.
Cautions:
1. Be sure the collector has been augmented with "make c++".
2. If your compiler supports the new "operator new[]" syntax, then
add -DOPERATOR_NEW_ARRAY to the Makefile.
If your compiler doesn't support "operator new[]", beware that an
array of type T, where T is derived from "gc", may or may not be
allocated as a collectable object (it depends on the compiler). Use
the explicit GC placement to make the array collectable. For example:
class A: public gc {...};
A* a1 = new A[ 10 ]; // collectable or uncollectable?
A* a2 = new (GC) A[ 10 ]; // collectable
3. The destructors of collectable arrays of objects derived from
"gc_cleanup" will not be invoked properly. For example:
class A: public gc_cleanup {...};
A* a = new (GC) A[ 10 ]; // destructors not invoked correctly
Typically, only the destructor for the first element of the array will
be invoked when the array is garbage-collected. To get all the
destructors of any array executed, you must supply an explicit
clean-up function:
A* a = new (GC, MyCleanUp) A[ 10 ];
(Implementing clean-up of arrays correctly, portably, and in a way
that preserves the correct exception semantics requires a language
extension, e.g. the "gc" keyword.)
4. Compiler bugs:
* Solaris 2's CC (SC3.0) doesn't implement t->~T() correctly, so the
destructors of classes derived from gc_cleanup won't be invoked.
You'll have to explicitly register a clean-up function with
new-placement syntax.
* Evidently cfront 3.0 does not allow destructors to be explicitly
invoked using the ANSI-conforming syntax t->~T(). If you're using
cfront 3.0, you'll have to comment out the class gc_cleanup, which
uses explicit invocation.
****************************************************************************/
#include "gc.h"
#ifndef THINK_CPLUS
#define _cdecl
#endif
#if ! defined( OPERATOR_NEW_ARRAY ) \
&& (__BORLANDC__ >= 0x450 || (__GNUC__ >= 2 && __GNUC_MINOR__ >= 6))
# define OPERATOR_NEW_ARRAY
#endif
enum GCPlacement {GC, NoGC, PointerFreeGC};
class gc {public:
inline void* operator new( size_t size );
inline void* operator new( size_t size, GCPlacement gcp );
inline void operator delete( void* obj );
#ifdef OPERATOR_NEW_ARRAY
inline void* operator new[]( size_t size );
inline void* operator new[]( size_t size, GCPlacement gcp );
inline void operator delete[]( void* obj );
#endif /* OPERATOR_NEW_ARRAY */
};
/*
Instances of classes derived from "gc" will be allocated in the
collected heap by default, unless an explicit NoGC placement is
specified. */
class gc_cleanup: virtual public gc {public:
inline gc_cleanup();
inline virtual ~gc_cleanup();
private:
inline static void _cdecl cleanup( void* obj, void* clientData );};
/*
Instances of classes derived from "gc_cleanup" will be allocated
in the collected heap by default. When the collector discovers an
inaccessible object derived from "gc_cleanup" or containing a
member derived from "gc_cleanup", its destructors will be
invoked. */
extern "C" {typedef void (*GCCleanUpFunc)( void* obj, void* clientData );}
inline void* operator new(
size_t size,
GCPlacement gcp,
GCCleanUpFunc cleanup = 0,
void* clientData = 0 );
/*
Allocates a collectable or uncollected object, according to the
value of "gcp".
For collectable objects, if "cleanup" is non-null, then when the
allocated object "obj" becomes inaccessible, the collector will
invoke the function "cleanup( obj, clientData )" but will not
invoke the object's destructors. It is an error to explicitly
delete an object allocated with a non-null "cleanup".
It is an error to specify a non-null "cleanup" with NoGC or for
classes derived from "gc_cleanup" or containing members derived
from "gc_cleanup". */
#ifdef OPERATOR_NEW_ARRAY
inline void* operator new[](
size_t size,
GCPlacement gcp,
GCCleanUpFunc cleanup = 0,
void* clientData = 0 );
/*
The operator new for arrays, identical to the above. */
#endif /* OPERATOR_NEW_ARRAY */
/****************************************************************************
Inline implementation
****************************************************************************/
inline void* gc::operator new( size_t size ) {
return GC_MALLOC( size );}
inline void* gc::operator new( size_t size, GCPlacement gcp ) {
if (gcp == GC)
return GC_MALLOC( size );
else
return GC_MALLOC_UNCOLLECTABLE( size );}
inline void gc::operator delete( void* obj ) {
GC_FREE( obj );}
#ifdef OPERATOR_NEW_ARRAY
inline void* gc::operator new[]( size_t size ) {
return gc::operator new( size );}
inline void* gc::operator new[]( size_t size, GCPlacement gcp ) {
return gc::operator new( size, gcp );}
inline void gc::operator delete[]( void* obj ) {
gc::operator delete( obj );}
#endif /* OPERATOR_NEW_ARRAY */
inline gc_cleanup::~gc_cleanup() {
GC_REGISTER_FINALIZER_IGNORE_SELF( this, 0, 0, 0, 0 );}
inline void gc_cleanup::cleanup( void* obj, void* displ ) {
((gc_cleanup*) ((char*) obj + (ptrdiff_t) displ))->~gc_cleanup();}
inline gc_cleanup::gc_cleanup() {
GC_finalization_proc oldProc;
void* oldData;
void* base = GC_base( (void *) this );
if (0 == base) return;
GC_REGISTER_FINALIZER_IGNORE_SELF(
base, cleanup, (void*) ((char*) this - (char*) base),
&oldProc, &oldData );
if (0 != oldProc) {
GC_REGISTER_FINALIZER_IGNORE_SELF( base, oldProc, oldData, 0, 0 );}}
inline void* operator new(
size_t size,
GCPlacement gcp,
GCCleanUpFunc cleanup,
void* clientData )
{
void* obj;
if (gcp == GC) {
obj = GC_MALLOC( size );
if (cleanup != 0)
GC_REGISTER_FINALIZER_IGNORE_SELF(
obj, cleanup, clientData, 0, 0 );}
else if (gcp == PointerFreeGC) {
obj = GC_MALLOC_ATOMIC( size );}
else {
obj = GC_MALLOC_UNCOLLECTABLE( size );};
return obj;}
#ifdef OPERATOR_NEW_ARRAY
inline void* operator new[](
size_t size,
GCPlacement gcp,
GCCleanUpFunc cleanup,
void* clientData )
{
return ::operator new( size, gcp, cleanup, clientData );}
#endif /* OPERATOR_NEW_ARRAY */
#endif /* GC_CPP_H */
/*
* Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-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.
*/
/* Boehm, July 11, 1995 11:54 am PDT */
# ifndef GC_HEADERS_H
# define GC_HEADERS_H
typedef struct hblkhdr hdr;
# if CPP_WORDSZ != 32 && CPP_WORDSZ < 36
--> Get a real machine.
# endif
/*
* The 2 level tree data structure that is used to find block headers.
* If there are more than 32 bits in a pointer, the top level is a hash
* table.
*/
# if CPP_WORDSZ > 32
# define HASH_TL
# endif
/* Define appropriate out-degrees for each of the two tree levels */
# ifdef SMALL_CONFIG
# define LOG_BOTTOM_SZ 11
/* Keep top index size reasonable with smaller blocks. */
# else
# define LOG_BOTTOM_SZ 10
# endif
# ifndef HASH_TL
# define LOG_TOP_SZ (WORDSZ - LOG_BOTTOM_SZ - LOG_HBLKSIZE)
# else
# define LOG_TOP_SZ 11
# endif
# define TOP_SZ (1 << LOG_TOP_SZ)
# define BOTTOM_SZ (1 << LOG_BOTTOM_SZ)
typedef struct bi {
hdr * index[BOTTOM_SZ];
/*
* The bottom level index contains one of three kinds of values:
* 0 means we're not responsible for this block.
* 1 < (long)X <= MAX_JUMP means the block starts at least
* X * HBLKSIZE bytes before the current address.
* A valid pointer points to a hdr structure. (The above can't be
* valid pointers due to the GET_MEM return convention.)
*/
struct bi * asc_link; /* All indices are linked in */
/* ascending order. */
word key; /* high order address bits. */
# ifdef HASH_TL
struct bi * hash_link; /* Hash chain link. */
# endif
} bottom_index;
/* extern bottom_index GC_all_nils; - really part of GC_arrays */
/* extern bottom_index * GC_top_index []; - really part of GC_arrays */
/* Each entry points to a bottom_index. */
/* On a 32 bit machine, it points to */
/* the index for a set of high order */
/* bits equal to the index. For longer */
/* addresses, we hash the high order */
/* bits to compute the index in */
/* GC_top_index, and each entry points */
/* to a hash chain. */
/* The last entry in each chain is */
/* GC_all_nils. */
# define MAX_JUMP (HBLKSIZE - 1)
# define HDR_FROM_BI(bi, p) \
((bi)->index[((word)(p) >> LOG_HBLKSIZE) & (BOTTOM_SZ - 1)])
# ifndef HASH_TL
# define BI(p) (GC_top_index \
[(word)(p) >> (LOG_BOTTOM_SZ + LOG_HBLKSIZE)])
# define HDR_INNER(p) HDR_FROM_BI(BI(p),p)
# ifdef SMALL_CONFIG
# define HDR(p) GC_find_header((ptr_t)(p))
# else
# define HDR(p) HDR_INNER(p)
# endif
# define GET_BI(p, bottom_indx) (bottom_indx) = BI(p)
# define GET_HDR(p, hhdr) (hhdr) = HDR(p)
# define SET_HDR(p, hhdr) HDR_INNER(p) = (hhdr)
# define GET_HDR_ADDR(p, ha) (ha) = &(HDR_INNER(p))
# else /* hash */
/* Hash function for tree top level */
# define TL_HASH(hi) ((hi) & (TOP_SZ - 1))
/* Set bottom_indx to point to the bottom index for address p */
# define GET_BI(p, bottom_indx) \
{ \
register word hi = \
(word)(p) >> (LOG_BOTTOM_SZ + LOG_HBLKSIZE); \
register bottom_index * _bi = GC_top_index[TL_HASH(hi)]; \
\
while (_bi -> key != hi && _bi != GC_all_nils) \
_bi = _bi -> hash_link; \
(bottom_indx) = _bi; \
}
# define GET_HDR_ADDR(p, ha) \
{ \
register bottom_index * bi; \
\
GET_BI(p, bi); \
(ha) = &(HDR_FROM_BI(bi, p)); \
}
# define GET_HDR(p, hhdr) { register hdr ** _ha; GET_HDR_ADDR(p, _ha); \
(hhdr) = *_ha; }
# define SET_HDR(p, hhdr) { register hdr ** _ha; GET_HDR_ADDR(p, _ha); \
*_ha = (hhdr); }
# define HDR(p) GC_find_header((ptr_t)(p))
# endif
/* Is the result a forwarding address to someplace closer to the */
/* beginning of the block or NIL? */
# define IS_FORWARDING_ADDR_OR_NIL(hhdr) ((unsigned long) (hhdr) <= MAX_JUMP)
/* Get an HBLKSIZE aligned address closer to the beginning of the block */
/* h. Assumes hhdr == HDR(h) and IS_FORWARDING_ADDR(hhdr). */
# define FORWARDED_ADDR(h, hhdr) ((struct hblk *)(h) - (unsigned long)(hhdr))
# endif /* GC_HEADERS_H */
/*
* Copyright (c) 1991-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.
*
*/
/* Boehm, November 7, 1994 4:56 pm PST */
/*
* Declarations of mark stack. Needed by marker and client supplied mark
* routines. To be included after gc_priv.h.
*/
#ifndef GC_MARK_H
# define GC_MARK_H
/* 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 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. */
# define PROC_BYTES 100
typedef struct ms_entry * (*mark_proc)(/* word * addr, mark_stack_ptr,
mark_stack_limit, env */);
# define LOG_MAX_MARK_PROCS 6
# define MAX_MARK_PROCS (1 << LOG_MAX_MARK_PROCS)
extern mark_proc GC_mark_procs[MAX_MARK_PROCS];
extern word GC_n_mark_procs;
/* 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 DS_TAG_BITS 2
#define DS_TAGS ((1 << DS_TAG_BITS) - 1)
#define DS_LENGTH 0 /* The entire word is a length in bytes that */
/* must be a multiple of 4. */
#define DS_BITMAP 1 /* 30 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 BITMAP_BITS (WORDSZ - DS_TAG_BITS)
#define 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 PROC(descr) \
(GC_mark_procs[((descr) >> DS_TAG_BITS) & (MAX_MARK_PROCS-1)])
# define ENV(descr) \
((descr) >> (DS_TAG_BITS + LOG_MAX_MARK_PROCS))
# define MAX_ENV \
(((word)1 << (WORDSZ - DS_TAG_BITS - LOG_MAX_MARK_PROCS)) - 1)
# define MAKE_PROC(proc_index, env) \
(((((env) << LOG_MAX_MARK_PROCS) | (proc_index)) << DS_TAG_BITS) \
| DS_PROC)
#define DS_PER_OBJECT 3 /* The real descriptor is at the */
/* byte displacement from the beginning of the */
/* object given by descr & ~DS_TAGS */
typedef struct ms_entry {
word * mse_start; /* First word of object */
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_top;
extern mse * GC_mark_stack;
word 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) \
{ \
register int displ; /* Displacement in block; first bytes, then words */ \
register hdr * hhdr; \
register map_entry_type map_entry; \
\
GET_HDR(current,hhdr); \
if (IS_FORWARDING_ADDR_OR_NIL(hhdr)) { \
current = GC_FIND_START(current, hhdr, (word)source); \
if (current == 0) goto exit_label; \
hhdr = HDR(current); \
} \
displ = HBLKDISPL(current); \
map_entry = MAP_ENTRY((hhdr -> hb_map), displ); \
if (map_entry == OBJ_INVALID) { \
GC_ADD_TO_BLACK_LIST_NORMAL(current, source); goto exit_label; \
} \
displ = BYTES_TO_WORDS(displ); \
displ -= map_entry; \
\
{ \
register word * mark_word_addr = hhdr -> hb_marks + divWORDSZ(displ); \
register word mark_word = *mark_word_addr; \
register word mark_bit = (word)1 << modWORDSZ(displ); \
\
if (mark_word & mark_bit) { \
/* Mark bit is already set */ \
goto exit_label; \
} \
*mark_word_addr = mark_word | mark_bit; \
} \
PUSH_OBJ(((word *)(HBLKPTR(current)) + displ), hhdr, \
mark_stack_top, mark_stack_limit) \
exit_label: ; \
}
/*
* Push a single value onto mark stack. Mark from the object pointed to by p.
* GC_push_one is normally called by GC_push_regs, and thus must be defined.
* 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) \
if ((ptr_t)(p) >= GC_least_plausible_heap_addr \
&& (ptr_t)(p) < GC_greatest_plausible_heap_addr) { \
GC_push_one_checked(p,TRUE); \
}
/*
* As above, but interior pointer recognition as for
* normal for heap pointers.
*/
# ifdef ALL_INTERIOR_POINTERS
# define AIP TRUE
# else
# define AIP FALSE
# endif
# define GC_PUSH_ONE_HEAP(p) \
if ((ptr_t)(p) >= GC_least_plausible_heap_addr \
&& (ptr_t)(p) < GC_greatest_plausible_heap_addr) { \
GC_push_one_checked(p,AIP); \
}
/*
* 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()) GC_mark_from_mark_stack(); \
if (GC_mark_state != MS_NONE) { \
GC_set_mark_bit(real_ptr); \
while (!GC_mark_some()); \
} \
}
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 */
/* 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_MARK_H */
# include "gc_priv.h"
/*
* Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
* Copyright 1996 Silicon Graphics. 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.
*/
/*
* Some simple primitives for allocation with explicit type information.
* Facilities for dynamic type inference may be added later.
* Should be used only for extremely performance critical applications,
* or if conservative collector leakage is otherwise a problem (unlikely).
* Note that this is implemented completely separately from the rest
* of the collector, and is not linked in unless referenced.
* This does not currently support GC_DEBUG in any interesting way.
*/
/* Boehm, May 19, 1994 2:13 pm PDT */
#ifndef _GC_TYPED_H
# define _GC_TYPED_H
# ifndef _GC_H
# include "gc.h"
# endif
typedef GC_word * GC_bitmap;
/* The least significant bit of the first word is one if */
/* the first word in the object may be a pointer. */
# define GC_get_bit(bm, index) \
(((bm)[divWORDSZ(index)] >> modWORDSZ(index)) & 1)
# define GC_set_bit(bm, index) \
(bm)[divWORDSZ(index)] |= (word)1 << modWORDSZ(index)
typedef GC_word GC_descr;
GC_API GC_descr GC_make_descriptor GC_PROTO((GC_bitmap bm, size_t len));
/* Return a type descriptor for the object whose layout */
/* is described by the argument. */
/* The least significant bit of the first word is one */
/* if the first word in the object may be a pointer. */
/* The second argument specifies the number of */
/* meaningful bits in the bitmap. The actual object */
/* may be larger (but not smaller). Any additional */
/* words in the object are assumed not to contain */
/* pointers. */
/* Returns a conservative approximation in the */
/* (unlikely) case of insufficient memory to build */
/* the descriptor. Calls to GC_make_descriptor */
/* may consume some amount of a finite resource. This */
/* is intended to be called once per type, not once */
/* per allocation. */
GC_API GC_PTR GC_malloc_explicitly_typed
GC_PROTO((size_t size_in_bytes, GC_descr d));
/* Allocate an object whose layout is described by d. */
/* The resulting object MAY NOT BE PASSED TO REALLOC. */
GC_API GC_PTR GC_malloc_explicitly_typed_ignore_off_page
GC_PROTO((size_t size_in_bytes, GC_descr d));
GC_API GC_PTR GC_calloc_explicitly_typed
GC_PROTO((size_t nelements,
size_t element_size_in_bytes,
GC_descr d));
/* Allocate an array of nelements elements, each of the */
/* given size, and with the given descriptor. */
/* The elemnt size must be a multiple of the byte */
/* alignment required for pointers. E.g. on a 32-bit */
/* machine with 16-bit aligned pointers, size_in_bytes */
/* must be a multiple of 2. */
#ifdef GC_DEBUG
# define GC_MALLOC_EXPLICTLY_TYPED(bytes, d) GC_MALLOC(bytes)
# define GC_CALLOC_EXPLICTLY_TYPED(n, bytes, d) GC_MALLOC(n*bytes)
#else
# define GC_MALLOC_EXPLICTLY_TYPED(bytes, d) \
GC_malloc_explicitly_typed(bytes, d)
# define GC_CALLOC_EXPLICTLY_TYPED(n, bytes, d) \
GC_calloc_explicitly_typed(n, bytes, d)
#endif /* !GC_DEBUG */
#endif /* _GC_TYPED_H */
name gc_watcom
.386p
extrn _edata : byte ; end of DATA (start of BSS)
extrn _end : byte ; end of BSS (start of STACK)
extrn __nullarea : word
extrn "C",_STACKLOW : dword
extrn "C",_STACKTOP : dword
DGROUP group _DATA
_DATA segment dword public 'DATA'
_DATA ends
_TEXT segment para public use32 'CODE'
assume cs:_TEXT, ds:DGROUP, ss:DGROUP
public Get_DATASTART
align 4
Get_DATASTART proc near
mov eax,offset DGROUP:__nullarea
ret
Get_DATASTART endp
public Get_DATAEND
align 4
Get_DATAEND proc near
mov eax,offset DGROUP:_end
ret
Get_DATAEND endp
public Get_STACKBOTTOM
align 4
Get_STACKBOTTOM proc near
mov eax,_STACKTOP
ret
Get_STACKBOTTOM endp
_TEXT ends
end
/*
* Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
* Copyright (c) 1996 by Silicon Graphics. 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 implements:
* 1. allocation of heap block headers
* 2. A map from addresses to heap block addresses to heap block headers
*
* Access speed is crucial. We implement an index structure based on a 2
* level tree.
*/
# include "gc_priv.h"
bottom_index * GC_all_bottom_indices = 0;
/* Non-macro version of header location routine */
hdr * GC_find_header(h)
ptr_t h;
{
# ifdef HASH_TL
register hdr * result;
GET_HDR(h, result);
return(result);
# else
return(HDR_INNER(h));
# endif
}
/* Routines to dynamically allocate collector data structures that will */
/* never be freed. */
static ptr_t scratch_free_ptr = 0;
ptr_t GC_scratch_end_ptr = 0;
ptr_t GC_scratch_last_end_ptr = 0;
/* End point of last obtained scratch area */
ptr_t GC_scratch_alloc(bytes)
register word bytes;
{
register ptr_t result = scratch_free_ptr;
register word bytes_needed = bytes;
# ifdef ALIGN_DOUBLE
# define GRANULARITY (2 * sizeof(word))
# else
# define GRANULARITY sizeof(word)
# endif
bytes += GRANULARITY-1;
bytes &= ~(GRANULARITY-1);
scratch_free_ptr += bytes;
if (scratch_free_ptr <= GC_scratch_end_ptr) {
return(result);
}
{
word bytes_to_get = MINHINCR * HBLKSIZE;
if (bytes_to_get <= bytes) {
/* Undo the damage, and get memory directly */
bytes_to_get = bytes;
# ifdef USE_MMAP
bytes_to_get += GC_page_size - 1;
bytes_to_get &= ~(GC_page_size - 1);
# endif
result = (ptr_t)GET_MEM(bytes_to_get);
scratch_free_ptr -= bytes;
GC_scratch_last_end_ptr = result + bytes;
return(result);
}
result = (ptr_t)GET_MEM(bytes_to_get);
if (result == 0) {
# ifdef PRINTSTATS
GC_printf0("Out of memory - trying to allocate less\n");
# endif
scratch_free_ptr -= bytes;
bytes_to_get = bytes;
# ifdef USE_MMAP
bytes_to_get += GC_page_size - 1;
bytes_to_get &= (GC_page_size - 1);
# endif
return((ptr_t)GET_MEM(bytes_to_get));
}
scratch_free_ptr = result;
GC_scratch_end_ptr = scratch_free_ptr + bytes_to_get;
GC_scratch_last_end_ptr = GC_scratch_end_ptr;
return(GC_scratch_alloc(bytes));
}
}
static hdr * hdr_free_list = 0;
/* Return an uninitialized header */
static hdr * alloc_hdr()
{
register hdr * result;
if (hdr_free_list == 0) {
result = (hdr *) GC_scratch_alloc((word)(sizeof(hdr)));
} else {
result = hdr_free_list;
hdr_free_list = (hdr *) (result -> hb_next);
}
return(result);
}
static void free_hdr(hhdr)
hdr * hhdr;
{
hhdr -> hb_next = (struct hblk *) hdr_free_list;
hdr_free_list = hhdr;
}
void GC_init_headers()
{
register int i;
GC_all_nils = (bottom_index *)GC_scratch_alloc((word)sizeof(bottom_index));
BZERO(GC_all_nils, sizeof(bottom_index));
for (i = 0; i < TOP_SZ; i++) {
GC_top_index[i] = GC_all_nils;
}
}
/* Make sure that there is a bottom level index block for address addr */
/* Return FALSE on failure. */
static GC_bool get_index(addr)
register word addr;
{
register word hi =
(word)(addr) >> (LOG_BOTTOM_SZ + LOG_HBLKSIZE);
register bottom_index * r;
register bottom_index * p;
register bottom_index ** prev;
# ifdef HASH_TL
register unsigned i = TL_HASH(hi);
register bottom_index * old;
old = p = GC_top_index[i];
while(p != GC_all_nils) {
if (p -> key == hi) return(TRUE);
p = p -> hash_link;
}
r = (bottom_index*)GC_scratch_alloc((word)(sizeof (bottom_index)));
if (r == 0) return(FALSE);
BZERO(r, sizeof (bottom_index));
r -> hash_link = old;
GC_top_index[i] = r;
# else
if (GC_top_index[hi] != GC_all_nils) return(TRUE);
r = (bottom_index*)GC_scratch_alloc((word)(sizeof (bottom_index)));
if (r == 0) return(FALSE);
GC_top_index[hi] = r;
BZERO(r, sizeof (bottom_index));
# endif
r -> key = hi;
/* Add it to the list of bottom indices */
prev = &GC_all_bottom_indices;
while ((p = *prev) != 0 && p -> key < hi) prev = &(p -> asc_link);
r -> asc_link = p;
*prev = r;
return(TRUE);
}
/* Install a header for block h. */
/* The header is uninitialized. */
/* Returns FALSE on failure. */
GC_bool GC_install_header(h)
register struct hblk * h;
{
hdr * result;
if (!get_index((word) h)) return(FALSE);
result = alloc_hdr();
SET_HDR(h, result);
return(result != 0);
}
/* Set up forwarding counts for block h of size sz */
GC_bool GC_install_counts(h, sz)
register struct hblk * h;
register word sz; /* bytes */
{
register struct hblk * hbp;
register int i;
for (hbp = h; (char *)hbp < (char *)h + sz; hbp += BOTTOM_SZ) {
if (!get_index((word) hbp)) return(FALSE);
}
if (!get_index((word)h + sz - 1)) return(FALSE);
for (hbp = h + 1; (char *)hbp < (char *)h + sz; hbp += 1) {
i = HBLK_PTR_DIFF(hbp, h);
SET_HDR(hbp, (hdr *)(i > MAX_JUMP? MAX_JUMP : i));
}
return(TRUE);
}
/* Remove the header for block h */
void GC_remove_header(h)
register struct hblk * h;
{
hdr ** ha;
GET_HDR_ADDR(h, ha);
free_hdr(*ha);
*ha = 0;
}
/* Remove forwarding counts for h */
void GC_remove_counts(h, sz)
register struct hblk * h;
register word sz; /* bytes */
{
register struct hblk * hbp;
for (hbp = h+1; (char *)hbp < (char *)h + sz; hbp += 1) {
SET_HDR(hbp, 0);
}
}
/* Apply fn to all allocated blocks */
/*VARARGS1*/
void GC_apply_to_all_blocks(fn, client_data)
void (*fn)(/* struct hblk *h, word client_data */);
word client_data;
{
register int j;
register bottom_index * index_p;
for (index_p = GC_all_bottom_indices; index_p != 0;
index_p = index_p -> asc_link) {
for (j = BOTTOM_SZ-1; j >= 0;) {
if (!IS_FORWARDING_ADDR_OR_NIL(index_p->index[j])) {
if (index_p->index[j]->hb_map != GC_invalid_map) {
(*fn)(((struct hblk *)
(((index_p->key << LOG_BOTTOM_SZ) + (word)j)
<< LOG_HBLKSIZE)),
client_data);
}
j--;
} else if (index_p->index[j] == 0) {
j--;
} else {
j -= (word)(index_p->index[j]);
}
}
}
}
/* Get the next valid block whose address is at least h */
/* Return 0 if there is none. */
struct hblk * GC_next_block(h)
struct hblk * h;
{
register bottom_index * bi;
register word j = ((word)h >> LOG_HBLKSIZE) & (BOTTOM_SZ-1);
GET_BI(h, bi);
if (bi == GC_all_nils) {
register word hi = (word)h >> (LOG_BOTTOM_SZ + LOG_HBLKSIZE);
bi = GC_all_bottom_indices;
while (bi != 0 && bi -> key < hi) bi = bi -> asc_link;
j = 0;
}
while(bi != 0) {
while (j < BOTTOM_SZ) {
if (IS_FORWARDING_ADDR_OR_NIL(bi -> index[j])) {
j++;
} else {
if (bi->index[j]->hb_map != GC_invalid_map) {
return((struct hblk *)
(((bi -> key << LOG_BOTTOM_SZ) + j)
<< LOG_HBLKSIZE));
} else {
j += divHBLKSZ(bi->index[j] -> hb_sz);
}
}
}
j = 0;
bi = bi -> asc_link;
}
return(0);
}
/* Conditionally execute a command based on machine and OS from config.h */
/* Boehm, November 21, 1994 1:40 pm PST */
# include "config.h"
# include <stdio.h>
int main(argc, argv, envp)
int argc;
char ** argv;
char ** envp;
{
if (argc < 4) goto Usage;
if (strcmp(MACH_TYPE, argv[1]) != 0) return(0);
if (strcmp(OS_TYPE, "") != 0 && strcmp(argv[2], "") != 0
&& strcmp(OS_TYPE, argv[2]) != 0) return(0);
printf("^^^^Starting command^^^^\n");
execvp(argv[3], argv+3);
perror("Couldn't execute");
Usage:
fprintf(stderr, "Usage: %s mach_type os_type command\n", argv[0]);
fprintf(stderr, "Currently mach_type = %s, os_type = %s\n",
MACH_TYPE, OS_TYPE);
return(1);
}
/* Conditionally execute a command based if the file argv[1] doesn't exist */
/* Except for execvp, we stick to ANSI C. */
# include "config.h"
# include <stdio.h>
int main(argc, argv, envp)
int argc;
char ** argv;
char ** envp;
{
FILE * f;
if (argc < 3) goto Usage;
if ((f = fopen(argv[1], "rb")) != 0
|| (f = fopen(argv[1], "r")) != 0) {
fclose(f);
return(0);
}
printf("^^^^Starting command^^^^\n");
execvp(argv[2], argv+2);
exit(1);
Usage:
fprintf(stderr, "Usage: %s file_name command\n", argv[0]);
return(1);
}
# ifndef EC_H
# define EC_H
# ifndef CORD_H
# include "cord.h"
# endif
/* Extensible cords are strings that may be destructively appended to. */
/* They allow fast construction of cords from characters that are */
/* being read from a stream. */
/*
* A client might look like:
*
* {
* CORD_ec x;
* CORD result;
* char c;
* FILE *f;
*
* ...
* CORD_ec_init(x);
* while(...) {
* c = getc(f);
* ...
* CORD_ec_append(x, c);
* }
* result = CORD_balance(CORD_ec_to_cord(x));
*
* If a C string is desired as the final result, the call to CORD_balance
* may be replaced by a call to CORD_to_char_star.
*/
# ifndef CORD_BUFSZ
# define CORD_BUFSZ 128
# endif
typedef struct CORD_ec_struct {
CORD ec_cord;
char * ec_bufptr;
char ec_buf[CORD_BUFSZ+1];
} CORD_ec[1];
/* This structure represents the concatenation of ec_cord with */
/* ec_buf[0 ... (ec_bufptr-ec_buf-1)] */
/* Flush the buffer part of the extended chord into ec_cord. */
/* Note that this is almost the only real function, and it is */
/* implemented in 6 lines in cordxtra.c */
void CORD_ec_flush_buf(CORD_ec x);
/* Convert an extensible cord to a cord. */
# define CORD_ec_to_cord(x) (CORD_ec_flush_buf(x), (x)[0].ec_cord)
/* Initialize an extensible cord. */
# define CORD_ec_init(x) ((x)[0].ec_cord = 0, (x)[0].ec_bufptr = (x)[0].ec_buf)
/* Append a character to an extensible cord. */
# define CORD_ec_append(x, c) \
{ \
if ((x)[0].ec_bufptr == (x)[0].ec_buf + CORD_BUFSZ) { \
CORD_ec_flush_buf(x); \
} \
*((x)[0].ec_bufptr)++ = (c); \
}
/* Append a cord to an extensible cord. Structure remains shared with */
/* original. */
void CORD_ec_append_cord(CORD_ec x, CORD s);
# endif /* EC_H */
#ifndef GC_CPP_H
#define GC_CPP_H
/****************************************************************************
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.
****************************************************************************
C++ Interface to the Boehm Collector
John R. Ellis and Jesse Hull
Last modified on Mon Jul 24 15:43:42 PDT 1995 by ellis
This interface provides access to the Boehm collector. It provides
basic facilities similar to those described in "Safe, Efficient
Garbage Collection for C++", by John R. Elis and David L. Detlefs
(ftp.parc.xerox.com:/pub/ellis/gc).
All heap-allocated objects are either "collectable" or
"uncollectable". Programs must explicitly delete uncollectable
objects, whereas the garbage collector will automatically delete
collectable objects when it discovers them to be inaccessible.
Collectable objects may freely point at uncollectable objects and vice
versa.
Objects allocated with the built-in "::operator new" are uncollectable.
Objects derived from class "gc" are collectable. For example:
class A: public gc {...};
A* a = new A; // a is collectable.
Collectable instances of non-class types can be allocated using the GC
placement:
typedef int A[ 10 ];
A* a = new (GC) A;
Uncollectable instances of classes derived from "gc" can be allocated
using the NoGC placement:
class A: public gc {...};
A* a = new (NoGC) A; // a is uncollectable.
Both uncollectable and collectable objects can be explicitly deleted
with "delete", which invokes an object's destructors and frees its
storage immediately.
A collectable object may have a clean-up function, which will be
invoked when the collector discovers the object to be inaccessible.
An object derived from "gc_cleanup" or containing a member derived
from "gc_cleanup" has a default clean-up function that invokes the
object's destructors. Explicit clean-up functions may be specified as
an additional placement argument:
A* a = ::new (GC, MyCleanup) A;
An object is considered "accessible" by the collector if it can be
reached by a path of pointers from static variables, automatic
variables of active functions, or from some object with clean-up
enabled; pointers from an object to itself are ignored.
Thus, if objects A and B both have clean-up functions, and A points at
B, B is considered accessible. After A's clean-up is invoked and its
storage released, B will then become inaccessible and will have its
clean-up invoked. If A points at B and B points to A, forming a
cycle, then that's considered a storage leak, and neither will be
collectable. See the interface gc.h for low-level facilities for
handling such cycles of objects with clean-up.
The collector cannot guarrantee that it will find all inaccessible
objects. In practice, it finds almost all of them.
Cautions:
1. Be sure the collector has been augmented with "make c++".
2. If your compiler supports the new "operator new[]" syntax, then
add -DOPERATOR_NEW_ARRAY to the Makefile.
If your compiler doesn't support "operator new[]", beware that an
array of type T, where T is derived from "gc", may or may not be
allocated as a collectable object (it depends on the compiler). Use
the explicit GC placement to make the array collectable. For example:
class A: public gc {...};
A* a1 = new A[ 10 ]; // collectable or uncollectable?
A* a2 = new (GC) A[ 10 ]; // collectable
3. The destructors of collectable arrays of objects derived from
"gc_cleanup" will not be invoked properly. For example:
class A: public gc_cleanup {...};
A* a = new (GC) A[ 10 ]; // destructors not invoked correctly
Typically, only the destructor for the first element of the array will
be invoked when the array is garbage-collected. To get all the
destructors of any array executed, you must supply an explicit
clean-up function:
A* a = new (GC, MyCleanUp) A[ 10 ];
(Implementing clean-up of arrays correctly, portably, and in a way
that preserves the correct exception semantics requires a language
extension, e.g. the "gc" keyword.)
4. Compiler bugs:
* Solaris 2's CC (SC3.0) doesn't implement t->~T() correctly, so the
destructors of classes derived from gc_cleanup won't be invoked.
You'll have to explicitly register a clean-up function with
new-placement syntax.
* Evidently cfront 3.0 does not allow destructors to be explicitly
invoked using the ANSI-conforming syntax t->~T(). If you're using
cfront 3.0, you'll have to comment out the class gc_cleanup, which
uses explicit invocation.
****************************************************************************/
#include "gc.h"
#ifndef THINK_CPLUS
#define _cdecl
#endif
#if ! defined( OPERATOR_NEW_ARRAY ) \
&& (__BORLANDC__ >= 0x450 || (__GNUC__ >= 2 && __GNUC_MINOR__ >= 6))
# define OPERATOR_NEW_ARRAY
#endif
enum GCPlacement {GC, NoGC, PointerFreeGC};
class gc {public:
inline void* operator new( size_t size );
inline void* operator new( size_t size, GCPlacement gcp );
inline void operator delete( void* obj );
#ifdef OPERATOR_NEW_ARRAY
inline void* operator new[]( size_t size );
inline void* operator new[]( size_t size, GCPlacement gcp );
inline void operator delete[]( void* obj );
#endif /* OPERATOR_NEW_ARRAY */
};
/*
Instances of classes derived from "gc" will be allocated in the
collected heap by default, unless an explicit NoGC placement is
specified. */
class gc_cleanup: virtual public gc {public:
inline gc_cleanup();
inline virtual ~gc_cleanup();
private:
inline static void _cdecl cleanup( void* obj, void* clientData );};
/*
Instances of classes derived from "gc_cleanup" will be allocated
in the collected heap by default. When the collector discovers an
inaccessible object derived from "gc_cleanup" or containing a
member derived from "gc_cleanup", its destructors will be
invoked. */
extern "C" {typedef void (*GCCleanUpFunc)( void* obj, void* clientData );}
inline void* operator new(
size_t size,
GCPlacement gcp,
GCCleanUpFunc cleanup = 0,
void* clientData = 0 );
/*
Allocates a collectable or uncollected object, according to the
value of "gcp".
For collectable objects, if "cleanup" is non-null, then when the
allocated object "obj" becomes inaccessible, the collector will
invoke the function "cleanup( obj, clientData )" but will not
invoke the object's destructors. It is an error to explicitly
delete an object allocated with a non-null "cleanup".
It is an error to specify a non-null "cleanup" with NoGC or for
classes derived from "gc_cleanup" or containing members derived
from "gc_cleanup". */
#ifdef OPERATOR_NEW_ARRAY
inline void* operator new[](
size_t size,
GCPlacement gcp,
GCCleanUpFunc cleanup = 0,
void* clientData = 0 );
/*
The operator new for arrays, identical to the above. */
#endif /* OPERATOR_NEW_ARRAY */
/****************************************************************************
Inline implementation
****************************************************************************/
inline void* gc::operator new( size_t size ) {
return GC_MALLOC( size );}
inline void* gc::operator new( size_t size, GCPlacement gcp ) {
if (gcp == GC)
return GC_MALLOC( size );
else
return GC_MALLOC_UNCOLLECTABLE( size );}
inline void gc::operator delete( void* obj ) {
GC_FREE( obj );}
#ifdef OPERATOR_NEW_ARRAY
inline void* gc::operator new[]( size_t size ) {
return gc::operator new( size );}
inline void* gc::operator new[]( size_t size, GCPlacement gcp ) {
return gc::operator new( size, gcp );}
inline void gc::operator delete[]( void* obj ) {
gc::operator delete( obj );}
#endif /* OPERATOR_NEW_ARRAY */
inline gc_cleanup::~gc_cleanup() {
GC_REGISTER_FINALIZER_IGNORE_SELF( this, 0, 0, 0, 0 );}
inline void gc_cleanup::cleanup( void* obj, void* displ ) {
((gc_cleanup*) ((char*) obj + (ptrdiff_t) displ))->~gc_cleanup();}
inline gc_cleanup::gc_cleanup() {
GC_finalization_proc oldProc;
void* oldData;
void* base = GC_base( (void *) this );
if (0 == base) return;
GC_REGISTER_FINALIZER_IGNORE_SELF(
base, cleanup, (void*) ((char*) this - (char*) base),
&oldProc, &oldData );
if (0 != oldProc) {
GC_REGISTER_FINALIZER_IGNORE_SELF( base, oldProc, oldData, 0, 0 );}}
inline void* operator new(
size_t size,
GCPlacement gcp,
GCCleanUpFunc cleanup,
void* clientData )
{
void* obj;
if (gcp == GC) {
obj = GC_MALLOC( size );
if (cleanup != 0)
GC_REGISTER_FINALIZER_IGNORE_SELF(
obj, cleanup, clientData, 0, 0 );}
else if (gcp == PointerFreeGC) {
obj = GC_MALLOC_ATOMIC( size );}
else {
obj = GC_MALLOC_UNCOLLECTABLE( size );};
return obj;}
#ifdef OPERATOR_NEW_ARRAY
inline void* operator new[](
size_t size,
GCPlacement gcp,
GCCleanUpFunc cleanup,
void* clientData )
{
return ::operator new( size, gcp, cleanup, clientData );}
#endif /* OPERATOR_NEW_ARRAY */
#endif /* GC_CPP_H */
/*
* Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-1995 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.
*/
/* Boehm, October 3, 1995 2:07 pm PDT */
# ifndef GC_PRIVATE_H
# include "private/gc_priv.h"
# endif
/* USE OF THIS FILE IS NOT RECOMMENDED unless the collector has been */
/* compiled without -DALL_INTERIOR_POINTERS or with */
/* -DDONT_ADD_BYTE_AT_END, or the specified size includes a pointerfree */
/* word at the end. In the standard collector configuration, */
/* the final word of each object may not be scanned. */
/* This is most useful for compilers that generate C. */
/* Manual use is hereby discouraged. */
/* Allocate n words (NOT BYTES). X is made to point to the result. */
/* It is assumed that n < MAXOBJSZ, and */
/* that n > 0. On machines requiring double word alignment of some */
/* data, we also assume that n is 1 or even. This bypasses the */
/* MERGE_SIZES mechanism. In order to minimize the number of distinct */
/* free lists that are maintained, the caller should ensure that a */
/* small number of distinct values of n are used. (The MERGE_SIZES */
/* mechanism normally does this by ensuring that only the leading three */
/* bits of n may be nonzero. See misc.c for details.) We really */
/* recommend this only in cases in which n is a constant, and no */
/* locking is required. */
/* In that case it may allow the compiler to perform substantial */
/* additional optimizations. */
# define GC_MALLOC_WORDS(result,n) \
{ \
register ptr_t op; \
register ptr_t *opp; \
DCL_LOCK_STATE; \
\
opp = &(GC_objfreelist[n]); \
FASTLOCK(); \
if( !FASTLOCK_SUCCEEDED() || (op = *opp) == 0 ) { \
FASTUNLOCK(); \
(result) = GC_generic_malloc_words_small((n), NORMAL); \
} else { \
*opp = obj_link(op); \
obj_link(op) = 0; \
GC_words_allocd += (n); \
FASTUNLOCK(); \
(result) = (GC_PTR) op; \
} \
}
/* The same for atomic objects: */
# define GC_MALLOC_ATOMIC_WORDS(result,n) \
{ \
register ptr_t op; \
register ptr_t *opp; \
DCL_LOCK_STATE; \
\
opp = &(GC_aobjfreelist[n]); \
FASTLOCK(); \
if( !FASTLOCK_SUCCEEDED() || (op = *opp) == 0 ) { \
FASTUNLOCK(); \
(result) = GC_generic_malloc_words_small((n), PTRFREE); \
} else { \
*opp = obj_link(op); \
obj_link(op) = 0; \
GC_words_allocd += (n); \
FASTUNLOCK(); \
(result) = (GC_PTR) op; \
} \
}
/* And once more for two word initialized objects: */
# define GC_CONS(result, first, second) \
{ \
register ptr_t op; \
register ptr_t *opp; \
DCL_LOCK_STATE; \
\
opp = &(GC_objfreelist[2]); \
FASTLOCK(); \
if( !FASTLOCK_SUCCEEDED() || (op = *opp) == 0 ) { \
FASTUNLOCK(); \
op = GC_generic_malloc_words_small(2, NORMAL); \
} else { \
*opp = obj_link(op); \
GC_words_allocd += 2; \
FASTUNLOCK(); \
} \
((word *)op)[0] = (word)(first); \
((word *)op)[1] = (word)(second); \
(result) = (GC_PTR) op; \
}
# include "gc_inl.h"
/*
* Copyright 1988, 1989 Hans-J. Boehm, Alan J. Demers
* Copyright (c) 1991-1994 by Xerox Corporation. All rights reserved.
* Copyright 1996 Silicon Graphics. 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.
*/
/*
* Some simple primitives for allocation with explicit type information.
* Facilities for dynamic type inference may be added later.
* Should be used only for extremely performance critical applications,
* or if conservative collector leakage is otherwise a problem (unlikely).
* Note that this is implemented completely separately from the rest
* of the collector, and is not linked in unless referenced.
* This does not currently support GC_DEBUG in any interesting way.
*/
/* Boehm, May 19, 1994 2:13 pm PDT */
#ifndef _GC_TYPED_H
# define _GC_TYPED_H
# ifndef _GC_H
# include "gc.h"
# endif
typedef GC_word * GC_bitmap;
/* The least significant bit of the first word is one if */
/* the first word in the object may be a pointer. */
# define GC_get_bit(bm, index) \
(((bm)[divWORDSZ(index)] >> modWORDSZ(index)) & 1)
# define GC_set_bit(bm, index) \
(bm)[divWORDSZ(index)] |= (word)1 << modWORDSZ(index)
typedef GC_word GC_descr;
GC_API GC_descr GC_make_descriptor GC_PROTO((GC_bitmap bm, size_t len));
/* Return a type descriptor for the object whose layout */
/* is described by the argument. */
/* The least significant bit of the first word is one */
/* if the first word in the object may be a pointer. */
/* The second argument specifies the number of */
/* meaningful bits in the bitmap. The actual object */
/* may be larger (but not smaller). Any additional */
/* words in the object are assumed not to contain */
/* pointers. */
/* Returns a conservative approximation in the */
/* (unlikely) case of insufficient memory to build */
/* the descriptor. Calls to GC_make_descriptor */
/* may consume some amount of a finite resource. This */
/* is intended to be called once per type, not once */
/* per allocation. */
GC_API GC_PTR GC_malloc_explicitly_typed
GC_PROTO((size_t size_in_bytes, GC_descr d));
/* Allocate an object whose layout is described by d. */
/* The resulting object MAY NOT BE PASSED TO REALLOC. */
GC_API GC_PTR GC_malloc_explicitly_typed_ignore_off_page
GC_PROTO((size_t size_in_bytes, GC_descr d));
GC_API GC_PTR GC_calloc_explicitly_typed
GC_PROTO((size_t nelements,
size_t element_size_in_bytes,
GC_descr d));
/* Allocate an array of nelements elements, each of the */
/* given size, and with the given descriptor. */
/* The elemnt size must be a multiple of the byte */
/* alignment required for pointers. E.g. on a 32-bit */
/* machine with 16-bit aligned pointers, size_in_bytes */
/* must be a multiple of 2. */
#ifdef GC_DEBUG
# define GC_MALLOC_EXPLICTLY_TYPED(bytes, d) GC_MALLOC(bytes)
# define GC_CALLOC_EXPLICTLY_TYPED(n, bytes, d) GC_MALLOC(n*bytes)
#else
# define GC_MALLOC_EXPLICTLY_TYPED(bytes, d) \
GC_malloc_explicitly_typed(bytes, d)
# define GC_CALLOC_EXPLICTLY_TYPED(n, bytes, d) \
GC_calloc_explicitly_typed(n, bytes, d)
#endif /* !GC_DEBUG */
#endif /* _GC_TYPED_H */
/*
* 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.
*/
/* Boehm, May 19, 1994 2:23 pm PDT */
# ifndef CORD_POSITION_H
/* The representation of CORD_position. This is private to the */
/* implementation, but the size is known to clients. Also */
/* the implementation of some exported macros relies on it. */
/* Don't use anything defined here and not in cord.h. */
# define MAX_DEPTH 48
/* The maximum depth of a balanced cord + 1. */
/* We don't let cords get deeper than MAX_DEPTH. */
struct CORD_pe {
CORD pe_cord;
size_t pe_start_pos;
};
/* A structure describing an entry on the path from the root */
/* to current position. */
typedef struct CORD_Pos {
size_t cur_pos;
int path_len;
# define CORD_POS_INVALID (0x55555555)
/* path_len == INVALID <==> position invalid */
const char *cur_leaf; /* Current leaf, if it is a string. */
/* If the current leaf is a function, */
/* then this may point to function_buf */
/* containing the next few characters. */
/* Always points to a valid string */
/* containing the current character */
/* unless cur_end is 0. */
size_t cur_start; /* Start position of cur_leaf */
size_t cur_end; /* Ending position of cur_leaf */
/* 0 if cur_leaf is invalid. */
struct CORD_pe path[MAX_DEPTH + 1];
/* path[path_len] is the leaf corresponding to cur_pos */
/* path[0].pe_cord is the cord we point to. */
# define FUNCTION_BUF_SZ 8
char function_buf[FUNCTION_BUF_SZ]; /* Space for next few chars */
/* from function node. */
} CORD_pos[1];
/* Extract the cord from a position: */
CORD CORD_pos_to_cord(CORD_pos p);
/* Extract the current index from a position: */
size_t CORD_pos_to_index(CORD_pos p);
/* Fetch the character located at the given position: */
char CORD_pos_fetch(CORD_pos p);
/* Initialize the position to refer to the give cord and index. */
/* Note that this is the most expensive function on positions: */
void CORD_set_pos(CORD_pos p, CORD x, size_t i);
/* Advance the position to the next character. */
/* P must be initialized and valid. */
/* Invalidates p if past end: */
void CORD_next(CORD_pos p);
/* Move the position to the preceding character. */
/* P must be initialized and valid. */
/* Invalidates p if past beginning: */
void CORD_prev(CORD_pos p);
/* Is the position valid, i.e. inside the cord? */
int CORD_pos_valid(CORD_pos p);
char CORD__pos_fetch(CORD_pos);
void CORD__next(CORD_pos);
void CORD__prev(CORD_pos);
#define CORD_pos_fetch(p) \
(((p)[0].cur_end != 0)? \
(p)[0].cur_leaf[(p)[0].cur_pos - (p)[0].cur_start] \
: CORD__pos_fetch(p))
#define CORD_next(p) \
(((p)[0].cur_pos + 1 < (p)[0].cur_end)? \
(p)[0].cur_pos++ \
: (CORD__next(p), 0))
#define CORD_prev(p) \
(((p)[0].cur_end != 0 && (p)[0].cur_pos > (p)[0].cur_start)? \
(p)[0].cur_pos-- \
: (CORD__prev(p), 0))
#define CORD_pos_to_index(p) ((p)[0].cur_pos)
#define CORD_pos_to_cord(p) ((p)[0].path[0].pe_cord)
#define CORD_pos_valid(p) ((p)[0].path_len != CORD_POS_INVALID)
/* Some grubby stuff for performance-critical friends: */
#define CORD_pos_chars_left(p) ((long)((p)[0].cur_end) - (long)((p)[0].cur_pos))
/* Number of characters in cache. <= 0 ==> none */
#define CORD_pos_advance(p,n) ((p)[0].cur_pos += (n) - 1, CORD_next(p))
/* Advance position by n characters */
/* 0 < n < CORD_pos_chars_left(p) */
#define CORD_pos_cur_char_addr(p) \
(p)[0].cur_leaf + ((p)[0].cur_pos - (p)[0].cur_start)
/* address of current character in cache. */
#endif
This diff is collapsed. Click to expand it.
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment