LD_PRELOAD Not Working with Custom getpid Function

I'm trying to use the LD_PRELOAD to inject my custom function in a program. I've compiled a shared library getpid.so having a modified getpid function that prints a message:
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

pid_t getpid(void)
{
printf("Initializing..\n");
return syscall(SYS_getpid);
}
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>

pid_t getpid(void)
{
printf("Initializing..\n");
return syscall(SYS_getpid);
}
I've also compiled a program testpid.c that calls the regular getpid function:
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
printf( "pid = %d!\n", getpid() );

return 0;
}
#include <sys/syscall.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
int main()
{
printf( "pid = %d!\n", getpid() );

return 0;
}
When I run the command:
LD_PRELOAD=./getpid.so ./testpid
LD_PRELOAD=./getpid.so ./testpid
I get the following error:
ERROR: ld.so: object 'getpid.so' from LD_PRELOAD cannot be preloaded: ignored
ERROR: ld.so: object 'getpid.so' from LD_PRELOAD cannot be preloaded: ignored
I've compiled both files with gcc -Wall -fPIC -shared -o getpid.so getpid.c and gcc testpid -o testpid.c Can anyone help me understand why LD_PRELOAD is not working and how to fix the issue?
Solution:
Hi! @Marvee Amasi One common issue with LD_PRELOAD is that the shared library must be compiled with position-independent code (PIC). Make sure you compiled getpid.so with the -fPIC flag. Also, check that getpid.so is in the current directory when you run the LD_PRELOAD command. Try running ldd getpid.so to check if there are any missing dependencies.
Jump to solution
3 Replies
Dtynin
Dtynin5mo ago
hi friend @Marvee Amasi the issue you're encountering with LD_PRELOAD is likely due to the naming and location of the shared library getpid.so. You can go through it again to ensure everything is correctly set up, if you need further guidance do well to reach out
Marvee Amasi
Marvee Amasi5mo ago
Yh thanks @Dtynin I had to specify the full path to getpid.so in the LD_PRELOAD environment variable
Solution
RED HAT
RED HAT4mo ago
Hi! @Marvee Amasi One common issue with LD_PRELOAD is that the shared library must be compiled with position-independent code (PIC). Make sure you compiled getpid.so with the -fPIC flag. Also, check that getpid.so is in the current directory when you run the LD_PRELOAD command. Try running ldd getpid.so to check if there are any missing dependencies.
Want results from more Discord servers?
Add your server