1

My aim is to call some function via its address. How can I do it?

I have done the next work for such aim, but at first(1) - I've got access violation ( don't know why ) and with the second I have some problems with calling function is ASM with ESP value...

The first (the problem with access violation):

#include <iostream>
#include <Windows.h>

const DWORD_PTR offset = 0x00001a90;

typedef void (__stdcall *uef)(int);

int main(void)
{
    HMODULE hModule = LoadLibrary(L"C:\\Windows\\system32\\OpenAL32.dll");

    DWORD_PTR addr = (DWORD_PTR)hModule + offset;

    uef func = (uef)offset;
    func(0);

    return 0;
}

The second (problems at runtime with ESP value):

#include <iostream>
#include <Windows.h>

typedef void (__stdcall *uef)(int);

int main(void)
{
    HMODULE hModule = LoadLibrary(L"C:\\Windows\\system32\\OpenAL32.dll");
    uef obj = NULL;

    if(hModule != NULL)
    {
        obj = reinterpret_cast<uef>(GetProcAddress(hModule, "alEnable"));
    }

    if(obj != NULL)
    {
        (*obj)(0);
    }

    if(hModule != NULL)
    {
        FreeLibrary(hModule);
    }

    return 0;
}

How could I solve this problem?

PS

And the another main question is:

How can I dynamically calculate the function address in runtime for next calling?

Thanks,

Best Regards!

Matt
  • 22,721
  • 17
  • 71
  • 112
Secret
  • 2,627
  • 7
  • 32
  • 46
  • 1
    `GetProcAddress` is *the* way to go. However, you must check that your function type definition matches that defined in the library *exactly*. Also, make sure that symbol (function) is exposed by the library (you can load the dll up in *depends.exe* and see all exported functions). – dirkgently Jun 10 '12 at 21:35

1 Answers1

1

First, there is a major issue (hence the access violation) with the hardcoded address offset (const DWORD_PTR offset = 0x00001a90). Don't do that! How can you know that the offsett will not be changed because of ASLR?

mox
  • 6,084
  • 2
  • 23
  • 35
  • 2
    Since the function is exported, just use GetProcAddress, period. (http://msdn.microsoft.com/en-us/library/windows/desktop/ms683212(v=vs.85).aspx) – mox Jun 11 '12 at 12:42