Re: Question about Trampolines

Florian Weimer (fw@s.netic.de)
28 Dec 1999 21:54:11 +0100


wendling@ganymede.isdn.uiuc.edu (Bill Wendling) writes:

> Sorry for the spam, but what does it mean for code to act as a
> "trampoline"? It's come up in the non-executable-stack discussion and
> I've seen it in the source code.

It's a mechanism to implement nested subprograms which have to reference
the stack frame of the enclosing subprogram. From an abstract point of
view, some kind of currying is required to get rid of the stack frame
pointer of the calling routine. This is implemented by creating a
trampoline on the stack which pushes the address of the stack frame and
calls the nested subprogram after that. When you request a pointer to
the nested subprogram, the compiler uses the address of the template
instead, effecitvely hiding the additional parameter containing the
stack frame pointer. (Of course, you can do other funny things with
templates, not just nested subprograms.)

For clarification, consider the following code:

void caller(void (*trampoline)())
{
trampoline();
}

void main()
{
int i;
void nested()
{
}

caller(nested);
}

It compiles to:

caller:
subl $12,%esp
movl 16(%esp),%eax
call *%eax
addl $12,%esp
ret

(This is an ordinary indirect function call.)

nested.78:
subl $28,%esp
movl %ecx,12(%esp)
addl $28,%esp
ret

(Note that this code loads the parent frame pointer.)

main:
subl $28,%esp
movl %esp,%eax
movl $nested.78-10,%edx
movb $185,(%eax)
leal 16(%esp),%ecx
movl %ecx,1(%eax)
movb $233,5(%eax)
subl %eax,%edx
movl %edx,6(%eax)

(This writes the trampoline code code on the stack.)

addl $-12,%esp
leal 12(%esp),%eax
pushl %eax
call caller
addl $16,%esp
addl $28,%esp
ret

(Finally, `caller' is called, and the address of the trampoline on the
stack is passed to it.)

There are other options for implementing nested subprograms (at least,
Ada was specifically designed to permit them), but I never understood
them, and they seem to be a PITA to implement.

-
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@vger.rutgers.edu
Please read the FAQ at http://www.tux.org/lkml/