This seems like a simple problem, but being that's it's my first time coding for Linux, it's not. I'm not a complete newbie to C/C++ coding. Just trying to learn to deal with Linux as I've been coding for ONLY Windows for awhile.
All I'm trying to do is get the base memory address of a dynamic library loaded in memory. Since LoadLibrary in Windows returns this, I figured dlopen would do the same since it too returns a void pointer. But as I soon found out with this code, I was wrong about that:
Code:
#ifdef __linux__
gameDllAddress = (unsigned long)dlopen(GAMEDLL_NAME, RTLD_NOW);
#else
gameDllAddress = (unsigned long)LoadLibrary(GAMEDLL_NAME);
#endif
With this I got a segmentation fault and an error about not having access to a memory location when I tried to read a particular byte in memory using that as a base address.
Someone else mentioned to me about the use of dladdr and using Dl_info struct to get the base address. I too have tried this. Maybe I'm going about this the wrong way, but I'm not sure:
Code:
#ifdef __linux__
Dl_info gameDllInfo;
dladdr(&MDLL_Spawn, &gameDllInfo);
gameDllAddress = (unsigned long)gameDllInfo.dli_fbase;
#else
gameDllAddress = (unsigned long)LoadLibrary(GAMEDLL_NAME);
#endif
GAMEDLL_NAME is defined elsewhere with the name of the dynamic library I'm loading and gameDllAddress is obviously an unsigned long that is declared elsewhere. MDLL_Spawn is a function I have access to (which is not in the code I'm writing) and since dladdr requires a function pointer as an address this what I have used. The problem here though is odd. I do not get a seg fault anymore when reading memory, but I noticed that if I read one memory location as a Dword (long) I would get one value. If I moved 4 bytes up, I'd get the same value. Then I moved another 4 bytes and I'd still get the same value returned. And I know that looking through a hex editor at the DLL I'm loading, it doesn't have 3 Dwords in a row with the same value.
So I'm guessing the way I got the base address is incorrect here. If not, then perhaps the value I'm trying to read has been relocated and is not in the same offset as it would be if I looked at the DLL I'm loading in a hex editor. If that is the case, then what's the best way to deal with this? I might add that my code works fine in Windows and it's not relocating anything. But I'm unsure of the exact details of how Linux manages memory and such, so I certainly might have missed something here.
Help with this would be much appreciated.