Home > Blog > Wrong usage of LD_LIBRARY_PATH

Wrong usage of LD_LIBRARY_PATH
1 star2 stars3 stars4 stars5 stars
(no votes yet)
Loading ... Loading ...

October 19th, 2009 Leave a comment Go to comments

Lots of programs that bring their own libraries use the following snippet in their wrapper scripts:

export LD_LIBRARY_PATH="/my/special/librarypath:$LD_LIBRARY_PATH"

This allows linker to find the needed libraries, even if they are not located in the standard directories (which are defined by /etc/ld.so.conf). At first, this seems OK, but it creates one problem, though. When the $LD_LIBRARY_PATH was empty before the assignment, the new value ends with a colon. When we run the program wrapper, linker splits the variable into substrings and ends up with one empty path. This indicates to search for libraries in the CURRENT working directory, which can cause problems or even a security threat.

So, what’s the correct way of defining the library path? Of course, we could check if the variable is empty before the assignment like this:

if [ -n "$LD_LIBRARY_PATH" ]; then
    export LD_LIBRARY_PATH="/my/special/librarypath:$LD_LIBRARY_PATH"
else
    export LD_LIBRARY_PATH="/my/special/librarypath"
fi

but there is one neat shell trick we can use (should work on all POSIX shells). The description says:

${parameter:+word}
Use Alternate Value. If parameter is null or unset, nothing is substituted, otherwise the expansion of word is substituted.

In the end we have:

export LD_LIBRARY_PATH="/my/special/librarypath${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"

which is not much longer than the line we started with, but does the assignment correctly. (The first colon belongs to shell syntax, the second one is a part of the value being appended).

  1. Rich
    October 19th, 2009 at 20:50 | #1 | Safari 4.0.3Mac OS X 10.5.8

    I found this back in 2000 and emailed Ulrich Drepper about it, and he berated me for being an idiot.

    Perhaps I am an idiot, but I still believe to this day that it’s a bug in how LD_LIBRARY_PATH is handled.

  2. October 21st, 2009 at 10:43 | #2 | Firefox 3.5.3SuSE
  3. October 21st, 2009 at 10:54 | #3 | Google Chrome 4.0.223.2GNU/Linux

    @Vincent Untz
    Yes, right. I changed the wording to avoid confusion.

  4. October 27th, 2009 at 19:14 | #4 | Firefox 3.5.3SuSE

    Yes, I would think of it as a bug, too:
    If the current dir is to be included into LD_LIBRARY_PATH then a “.” – Entry should explicitly have to be added. Anyone who fails to see it really is an ‘idiot’.

  1. No trackbacks yet.
or