I am looking for a way to scan a program's memory for specific pattern. The program is loading our code as a library (.so
).
Here is my attempt:
unsigned long FindPattern(char *pattern, char *mask)
{
void *address;
unsigned long size, i;
// NULL = We want the base address of the process we are loaded in
address = dlopen(NULL, 0); // Would be GetModuleHandle(NULL) on Windows
// The size of the program, would be GetModuleInformation.SizeOfImage on Windows
size = 0x128000; // Didn't find a way for Linux
for(i = 0; i < size; i++)
{
if(_compare((unsigned char *)(address + i), (unsigned char *)pattern, mask))
return (unsigned long)(address + i);
}
return 0;
}
int _compare(unsigned char *data, unsigned char *pattern, char *mask)
{
for(; *mask; ++mask, ++data, ++pattern)
{
if(*mask == 'x' && *data != *pattern) // Crashes here according to gdb
return 0;
}
return (*mask) == 0;
}
But all of this doesn't work. Starting at dlopen
, it does not return the correct base address of the program we are loaded in. I have also tried link_map as explained here.
I do know the addresses from IDA and gdb that's why I know dlopen
returns wrong values.
Using gcc-4.4.7 on CentOS 6.5 64bit. The program is a 32bit executable binary.