How could one write a function, in assembly, that just forwards it’s arguments to another function and adds a couple extra?
So far, I pushed on the two extra arguments, then just jmped to the other function. Is that valid? Assuming that I make it a naked function, no prolog/epilog. I’m in x86.
If you want to do this, you need to pop the return address, push your two arguments, push the return address back onto the stack, and then do the jump.
The discussion below assumes that you’re doing this in an environment that doesn’t reserve the registers I tinker with, and you’re using a pure stack-based calling convention. If there are reserved registers (for example, if you’re writing an ASM function to be called by a C program) or the calling convention is register-based, then things would have to be somewhat different.
Also, be sure to read the disclaimer at the end.
With that out of the way …
Imagine you have a function that’s called with two parameters on the stack. The stack frame, on entry to your function, would look like this:
Let’s not quibble about argument ordering (i.e.
cdeclvsstdcall).Now, you want to pass control to another function that expects those two arguments and two more. On entry to that function, the stack frame should look like this:
So your first function has to pop the return address, add the two new parameters, push the return address, and do the jump:
(Yes, I did that with 16-bit instructions. Just change
axtoeax, etc.)Also, and this is very important: this only works if the callee is expected to clean up the stack. If the caller is expected to clean up the stack (typically by
poping or by adding to the stack pointer), then this technique will fail because the caller will be expecting to remove 2 parameters from the stack when there are actually 4. The result will be a corrupted stack frame and when the caller tries to do aretinstruction, it’s going to wander off into the weeds.