1

Though the title reads dll, the actual library loaded is an exe. Suppose I have an exe file testlib.exe. I need to call a function from it, let it be func(). What I am doing is:

#include <windows.h>
#include <stdio.h>

typedef char* (__stdcall *f_func)();

int main()
{
  HINSTANCE hGetProcIDDLL = LoadLibrary("testlib.exe");
  f_func func = (f_func)GetProcAddress(hGetProcIDDLL, "func");

  printf(func());

  return 0;
}

Now most of the times I run the program it gives the correct output, but in some cases (1 out of 8 for example) it gives either garbage text or values of some other variables in testlib.exe. I identify it's due to wrong memory reference but can neither explain nor solve it.

My os is windows and I'm using mingw gcc. I do not use MSVS as it does not fit well in code portability.

PS: The testlib.exe is well built and I cannot change it. It is unlikely to have any problem. I tried different versions and also it's running in other build systems well. Also it is a release build, so less hope in debugging.

UPDATE: I've seen this question, it says that it is possible by patching the IAT table. My point is completly different. I am using a function that is neither initialised by main nor by dllmain. Actually what I found that GetProcAddress gives right function pointer everytime. What gets messed is the return object. For example if the function in exe library is:

const char* func() {
    return "Sometext";
}

then sometimes the reference to "sometext is sometimes wrong. I do suspect randomised loading but I'm not sure. I renamed the exe as dll but no change observed.

ratcher86
  • 11
  • 2
  • Does this answer your question? [LoadLibrary() an EXE?](https://stackoverflow.com/questions/19110747/loadlibrary-an-exe) – Adrian Mole May 29 '20 at 02:44
  • My program has apparently nothing to do with dllmain(). It calls a exported function. And I also tried with the lib file but same result (additionally sometimes 0x0000005 error occured, due to same reason I think). – ratcher86 May 29 '20 at 02:57
  • But, as stated in the suggested duplicate (specifically, in the linked article in the top answer), loading an `exe` file *via* a `LoadLibrary` call will not necessarily result in correct initialization of that module's code base. – Adrian Mole May 29 '20 at 02:59
  • I assumed that it may not be an issue as my test function just reads a constant and returns it. I chose the simplest case possible. – ratcher86 May 29 '20 at 03:02
  • Also I mentioned that the same exe is being loaded without any issue in a couple of other systems, key difference is they use MSVC and the `/DELAYLOAD:testlib.exe` flag. – ratcher86 May 29 '20 at 03:04
  • If you use `LoadLibrary` with an executable, then besides not loading the static imports, it also doesn't do base relocation. – ssbssa Jun 01 '20 at 10:54

0 Answers0