Unix Stack Frame Questions

Paul Falstad pfalstad at lit.Princeton.EDU
Sat Mar 23 20:17:30 AEST 1991


(I took this out of comp.lang.c, as this is VERY machine specific.)

tan at epic.epic.com (Andy Tan) wrote:
>I am trying to save the content of stack frame, so I can restore it later.
>The same source code runs on SunOS 3.x well, however, it does not work on
>SunOS 4.x.  

I'm assuming that the SunOS 4.x is running on a SPARC.  The type of CPU
is more relevant than the OS version for this question.

>save(){
>  int stack_size, stack_bot;
   
>  if (setjmp(save_state) == 0) {
>     ....
>     stack_bot = (int) &stack_bot;
>
>1. Is it right to assume that the address of the last automatic
>   variable is the bottom of stack frame ?

It's wrong even to assume that all the automatic variables will be
stored in memory.  stack_bot will be, since you took its address, but
the others won't in general, especially if you have optimization turned
on.  They'll be stored in registers, and only written to memory if
absolutely necessary.

>2. How come save_state[2], which stores the Stack Pointer for
>   SunOS 4.x, is far away from the assumed stack bottom ?
>   Note:  save_state[14], which stores the SP for SunOS 3.x, is
>    very close to the assumed stack bottom.

With a SPARC, a procedure almost always creates a stack frame of 96
bytes, plus whatever space for local variables it needs.  This is done
because the window_overflow trap handler needs somewhere to dump your
register window if you run out of windows (96 bytes is the size of a
window).  The sun compiler, I gather, puts the local variables at the
top of the stack frame, and the 96-byte buffer underneath.  So the stack
pointer will be quite far away from the address of stack_bot, which is
%fp-some small number (fp is the stack pointer from the calling
procedure).  MC680x0 processors don't have register windows, so this
won't happen on them.  (I think this is all right; someone correct me if
I'm wrong.)

>3. Any major differences in the way of stack frame manipulation
>   are there between SunOS 3.x and SunOS 4.x ?

Only slightly.  Sun 4 compilers might not store any of the locals on the
stack, unless some of them need to be addressable.

>4. Any better solutions to save and restore stack frame for
>   SunOS 4.x ?

Please don't do this.  This sort of thing is extremely unportable.  I'd
be interested in knowing why you think you need to do this.  It's wise
to avoid the use of setjmp() in general IMHO.

--
Paul Falstad, pfalstad at phoenix.princeton.edu | 10 PRINT "PRINCETON CS"
[Your blood pressure just went up.]          | 20 GOTO 10
Princeton University would like to apologize to everyone for this article.



More information about the Comp.unix.programmer mailing list