[m-rev.] diff: throw_if_near_stack_limits

Fergus Henderson fjh at cs.mu.OZ.AU
Tue Jun 22 21:25:59 AEST 2004

On 21-Jun-2004, Zoltan Somogyi <zs at cs.mu.OZ.AU> wrote:
> +	/*
> +	** In high level code grades, I don't know of any portable way
> +	** to check whether we are near the limits of the C stack.
> +	*/

There are some reasonably portable ways.
Not perfect, but probably good enough.

See for example GC_find_limit() in boehm_gc/os_dep.c.  The idea there is
to set a signal handler for SIGSEGV and SIGBUS, and then to do a *read*
from the current stack pointer plus/minus some offset.  If the OS traps
stack overflow by protecting pages, and you are near the limit, this
should raise a signal.  The signal handler can then longjmp back
and throw an exception.

Alternatively, there's also sigaltstack().  sigaltstack() is part of
POSIX/SUS nowadays, and is supported by Linux, which IMHO makes it
sufficiently portable to be worth supporting.

With sigaltstack, you can do something like this:

	Allocate some memory: SIGSTKSIZ bytes or so.

	Register this memory as an alternative stack using sigaltstack().

	Install a signal handler for SIGSEGV/SIGBUS using sigaction with the

	Call a non-inline function which declares a (volatile) local array
	of bytes, and assign to both the first and last byte of
	that array.  If you're out of stack space, this will trigger
	the signal handler, which can longjmp back and then throw an

But that said, the technique in GC_find_limit() is probably simpler
and more portable.

Fergus Henderson                    |  "I have always known that the pursuit
                                    |  of excellence is a lethal habit"
WWW: <http://www.cs.mu.oz.au/~fjh>  |     -- the last words of T. S. Garp.
mercury-reviews mailing list
post:  mercury-reviews at cs.mu.oz.au
administrative address: owner-mercury-reviews at cs.mu.oz.au
unsubscribe: Address: mercury-reviews-request at cs.mu.oz.au Message: unsubscribe
subscribe:   Address: mercury-reviews-request at cs.mu.oz.au Message: subscribe

More information about the reviews mailing list