who called a C routine - get it from the stack frame

Walt Pesch wbp at cuuxb.UUCP
Fri Dec 5 14:42:45 AEST 1986


In article <810 at hropus.UUCP> jgy at hropus.UUCP writes:
>Can anyone help me with the following problem:  I'm looking for a few 
>lines of C or assembly code which can be used at the top of a function 
>to get the address of the function which called it.  I can then map
>this address to the calling functions name using "nm".

Oh, well, you asked!  Time to get down into the mud...  For System V,
the following dirty trick should work:

When defining the actual function, which is normally passed "n" 
variables, define the function to have "n+1" variables.  By the nature 
of the stack frame, the "n+1"'th variable will contain the program
address for returning.  Back up x words for the length of the jump
instruction, and call "nm"...  good luck.

This is an interesting way to get at the entire stack frame, and
needless to say, all sorts of fun!  A generic System V stack frame look
like:

<n words of passing parameters>
program address (address after call)
saved ap (start of previous frame)
saved fp (start of previous frame's automatics and temporaries)
<n words for saving registers>
<automatic and temporary variables>
   |
   |   Stack Growth
   V

I don't know if the same trick will work with BSD or any of the other
<a-hem> variants.  And life is too short to RTFS the BSD internals, so
I'll leave it to someone else to comment on how to do "it" on other
forms of Unix.


   Walt Pesch
   {ihnp4,akgua,et al}!cuuxb!wbp
   cuuxb!wbp at lll-crg



More information about the Comp.lang.c mailing list