Why doesn't LD_PRELOAD take effect with scripts without shebang?

If, when I run the script, I use LD_PRELOAD to indicate the library to be preloaded, I found that the library is actually preloaded only if the script has a shebang line. For example, given this script:

 # Not a shebang echo Hello 

and this command:

 LD_PRELOAD=/path/to/preload_me.so ./script.sh 

The script works without loading the library at all, which I can control with the (non) effects of its initialization code.

On the other hand, if I add the shebang line:

 #!/bin/sh echo Hello 

... then the library is loaded when the script starts using the same command. It does not seem to matter which interpreter is specified; Of course, I can also use /bin/bash or any other sh family shell I tried.

Why is there a difference, and is there a way to guarantee that a given library is preloaded to a given command line without any command?

(adapted from another question , the author of which resisted the question formulated in these terms.)

+5
source share
1 answer

(Adapted from my answer to another question indicated.)

It is important to understand that the LD_PRELOAD variable does not have much value for the operating system or for the shell. It makes sense and effect - if it has them at all - only in combination with a dynamic linker. If the dynamic linker is not involved, then LD_PRELOAD is another variable in the environment. Similarly, if the dynamic linker does not recognize this variable (for example, on OS X).

It is also important to understand that when executing a command whose name corresponds to a file that is not in an executable format, but which contains a shebang string, the specified interpreter is executed even if it is the shell itself. If the interpreter is an ELF binary that uses the dynamic linker. On the other hand, if there is no shebang line, then bash executes the contents of the file in a subnet environment, which does not require a dynamic linker; instead, the shell is just plugs. Other shells may or may not do the same.

It is also important to recognize that there are executable formats other than ELF. You are unlikely to encounter such binary code in a modern ELF-based system, but you should not rule out the possibility.

Bottom line: There is no way to guarantee that this dynamic library will be preloaded in the process space of an arbitrary shell command executed via bash or another shell selected by the user. If you require such a library to be preloaded for any or any arbitrary command, you need to more strictly control the runtime, perhaps by providing a custom shell and, possibly, also a custom dynamic linker and preventing others from being used.

+7
source

Source: https://habr.com/ru/post/1258040/


All Articles