4

I frequently see code formatted like this:

push arg
push arg
(...)
mov ecx, arg
call function

If I need to call that function in Assembly, it's fine. But since I know how to consistently get the base of the functions, for the sake of organization and simplicity, I'd like to use typedefs in a DLL to call the functions.

The problem's that I have no idea how to make a call use ecx to pass data. Unless I'm mistaken, func(arg,arg) will always assemble to two pushes and a call. If I don't use ecx the function crashes because it's a pointer to an object and it needs to be that. Is there any way to do this without inline assembly which I'd like to avoid?

1 Answer 1

10

You can either typedef it like this:

// typedef <return-type>(__thiscall* <type-name>)(<ecx>, <stack-1>, <stack-2>);
typedef int(__thiscall* tSomeFunc)(int thisPtr, int arg1, int arg2);
tSomeFunc func = (tSomeFunc) 0xBAADC0DE;

// this is how you call it
func(/* this */ 0x123, /* arg1 */ 1, /* arg2 */ arg2);

Or directly call it:

((int(__thiscall*)(int, int, int)) 0xDEADBABE)(/* this */ 0x123, 1, 2);

It relies on the fact that your calling convention seems to be __thiscall, which stores the this pointer into ecx and then pushes the rest of the args to the stack.

2
  • Thank you, this was perfect. I always wondered how C++ could magically tell whether functions used ret or retn %d and this explained that, too
    – Lupe
    Aug 31, 2015 at 0:50
  • 3
    @AcidShout, nice job including both the typedef-style and the direct-call style in your answer! Aug 31, 2015 at 13:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.