Mawg
Mawg

Reputation: 40140

How can I allocate more stack in my program's death throes?

On a Posix system, I am coding a signal handler, using sigaction.

I would like to record some debug information, before calling exit(). This involves a few procedure calls.

If we have had a stack overflow, is there any way that I can make those function calls without messing things up further?

I know that after I do my debug stuff, I am going to call exit(), so we won't ever unwind the stack. Could I code a small assembler insert to set the stack pointer to the base of the stack?

Never mind that I am trashing it; it won't be needed later, and by trashing the start of the stack, I am not trashing beyond the end of it.

Has anyone done this, or an alternative, and shown it to work?

Upvotes: 3

Views: 127

Answers (2)

autistic
autistic

Reputation: 15642

There is no requirement that your program use the stack (for callframes, as opposed to the data structure). Being a turing-complete programming language, you can rewrite any functionally recursive loop (e.g. loops using function invocation) as a procedurally recursive loop (e.g. procedural loops such as for, while and do .. while) providing you introduce the appropriate language and data structures.

You might then find growing a stack (data structure, not the same as the callframe) to several gigabytes is trivial for most laptops using realloc... As an added bonus, you'll no longer need to delve into non-portable hacks such as implementation-defined assembler notations or signals.

Upvotes: 1

user3185968
user3185968

Reputation:

On POSIX, you can set up a separate stack for specific signal-handlers with sigaltstack(). The manpage on Linux for this function is very nice:

The most common usage of an alternate signal stack is to handle the SIGSEGV signal that is generated if the space available for the normal process stack is exhausted: in this case, a signal handler for SIGSEGV cannot be invoked on the process stack; if we wish to handle it, we must use an alternate signal stack.

One thing to keep in mind is that you need to use sigaction() rather than signal() to establish the relevant signal-handler, but that's a good idea anyway. Also, the sa_flags for sigaction()s struct sigaction need to contain SA_ONSTACK.

Upvotes: 4

Related Questions