14

I am executing a program say A from another by first fork-ing followed by execve(). Now the problem is I would want A to use my library that I would generaly do by using LD_PRELOAD. How do I do it within execve().

Thanks

Lipika Deka
  • 3,774
  • 6
  • 43
  • 56

3 Answers3

14

you can pass the LD_PRELOAD in envp execve's argument:

the program that gets execved, named "run":

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char **argv) 
{

    printf("%s\n",getenv("LD_PRELOAD"));
}

the program that does the execve, named "ex":

#include <stdio.h>
#include <unistd.h>


int main(int argc, char **argv)
{
    char *const args[] = {"./run",NULL};
    char *const envs[] = {"LD_PRELOAD=caca",NULL};
    execve("./run",args,envs);
}

running it:

root@pinkpony:~# ./ex
ERROR: ld.so: object 'caca' from LD_PRELOAD cannot be preloaded: ignored.
caca

EDIT: the error shown gets thrown because "caca" lib can't be preloaded for run, so it works. (I skipped the fork() part for clarity but the usage is the same)

EDIT: doing something like:

LD_PRELOAD=caca ./ex

will not automagically preload caca lib when execve()-ing run if you're not passing it via envp execve()'s argument

user237419
  • 8,829
  • 4
  • 31
  • 38
0

Update

After reading the added info from the question, I'm guessing that you might have to specify a complete path, or set LD_LIBRARY_PATH as well? Since the loader is acknowledging the fact that the preload is ordered.

Otherwise, I can imagine there being a security restriction (allthough it would have to be tied to being run invoked from a login shell, which seems quite brittle to detect). Nonetheless, you may wish to try running as root (use sudo -E to keep your environment)


It would appear from this earlier question that such behaviour is the default

LD_PRELOAD affects new child even after unsetenv("LD_PRELOAD")

Have you tested it?

Community
  • 1
  • 1
sehe
  • 374,641
  • 47
  • 450
  • 633
0

If you want to use LD_PRELOAD just for program A (and not for its parent) you could load it via the shell; pass to the shell the name of the program to execute and add LD_PRELOAD to the environment.

Torp
  • 7,924
  • 1
  • 20
  • 18