clinuxrootsudo

Can't link dynamic library when running C language with root privileges?


I have a C language file named testFunc.c that uses the dynamic library libCfunc.so. This library is placed under the path /home/cuiyujie/workspace/library/lib.

I added this path to library path export LD_LIBRARY_PATH=/home/cuiyujie/workspace/library/lib:$LD_LIBRARY_PATH When I use the following command to compile, it can be compiled normally.

gcc testFunc.c  -lCfunc -lm -O0 -g -o testFunc

But when I run it, if I use ./testFunc, it can run normally.

But if I use sudo ./testFunc, he will get the following error.

./testFunc: error while loading shared libraries: libCfunc.so: cannot open shared object file: No such file or directory

I found on Google that when root is used, the value of the LD_LIBRARY_PATH variable is ignored. I used the following command to recompile. Specify the library path when compiling.

gcc testFunc.c  -L/home/cuiyujie/workspace/library/lib -lCfunc -lm -O0 -g -o testFunc

When I continue to run with the sudo ./testFunc command, the same error still appears.

The reason why I need to execute with root is because I need to read some inquiries that only root privileges can read. I want to get the physical address of certain variables, so I need to read the mapping file of the process, which requires root privileges.


Solution

  • The linker flag -L just tells the linker where to look for the library (or a library stub, if such is used) at link time. It does not influence the library search path at runtime.

    For a system wide installed library you'd place the library in a place that's been configured in the global linker search path, set through /etc/ld.so.conf and files in /etc/ld.so.conf.d.

    However it is perfectly possible to specify additional search paths specific to certain binaries by means of the so callled rpath. The rpath is set using the (you guessed it) rpath extra linker flag -Wl,-rpath.

    Linking the program with

    gcc -o … -Wl,-rpath='${ORIGIN}' …
    

    would make the ELF interpreter (the piece of code that loads ELF binaries and does dynamic linkage) to also look for additional libraries right next to the program binary. You can read up on the details of rpaths in the ld.so manpage.

    Be aware that rpaths invoke certain security considerations.