Copying Shared Library Dependencies
I call it cpld a simple utility for copying shared library dependencies to a given folder
Shared library dependenices can be easily listed with the help of ldd– list dynamic dependencies of executable files or shared objects.
Clues in the ldd source:
ldd is a very simple utility, that prints the shared libraries required by each program or shared library specified on the command line.
In the ldd source code, there is a line with a comment /ld.so magic /
setenv("LD_TRACE_LOADED_OBJECTS", "yes", 1);
Lets see an example:
$ LD_TRACE_LOADED_OBJECTS=1 /bin/bash
linux-vdso.so.1 => (0x00007fff11bff000)
libncurses.so.5 => /lib/libncurses.so.5 (0x00007f8bfcab0000)
libdl.so.2 => /lib/libdl.so.2 (0x00007f8bfc8ac000)
libc.so.6 => /lib/libc.so.6 (0x00007f8bfc529000)
/lib64/ld-linux-x86-64.so.2 (0x00007f8bfccf3000)
$ ldd /bin/bash
linux-vdso.so.1 => (0x00007fffe1dff000)
libncurses.so.5 => /lib/libncurses.so.5 (0x00007fc92daf3000)
libdl.so.2 => /lib/libdl.so.2 (0x00007fc92d8ef000)
libc.so.6 => /lib/libc.so.6 (0x00007fc92d56b000)
/lib64/ld-linux-x86-64.so.2 (0x00007fc92dd5a000)
So, the outputs are the same, indeed ldd uses /lib/ld.so with LD_TRACE_LOADED_OBJECTS evn set.
When working will virtual environment for an evalbot there was repeated use of ldd and fixing binaries, so this made me to write a small utility to do the job easy, the code is as below:
#!/bin/bash
# Author : Hemanth.HM
# Email : hemanth[dot]hm[at]gmail[dot]com
# License : GNU GPLv3
#
function useage()
{
cat << EOU
Useage: bash $0 <path to the binary> <path to copy the dependencies>
EOU
exit 1
}
#Validate the inputs
[[ $# < 2 ]] && useage
#Check if the paths are vaild
[[ ! -e $1 ]] && echo "Not a vaild input $1" && exit 1
[[ -d $2 ]] || echo "No such directory $2 creating..."&& mkdir -p "$2"
#Get the library dependencies
echo "Collecting the shared library dependencies for $1..."
deps=$(ldd $1 | awk 'BEGIN{ORS=" "}$1\
~/^\//{print $1}$3~/^\//{print $3}'\
| sed 's/,$/\n/')
echo "Copying the dependencies to $2"
#Copy the deps
for dep in $deps
do
echo "Copying $dep to $2"
cp "$dep" "$2"
done
echo "Done!"
Case studies :
$ bash cpld.bash
Useage: bash cpld.bash <path to the binary> <path to copy the dependencies>
$ bash cpld.bash /bin/bash
Useage: bash cpld.bash <path to the binary> <path to copy the dependencies>
$ bash cpld.bash /tmp/tet /tmp/test
Not a vaild input /tmp/tet
$ bash cpld.bash /bin/bash /tmp/deps
No such directory /tmp/deps creating...
Collecting the shared library dependencies for /bin/bash...
Copying the dependencies to /tmp/deps
Copying /lib/libncurses.so.5 to /tmp/deps
Copying /lib/libdl.so.2 to /tmp/deps
Copying /lib/libc.so.6 to /tmp/deps
Copying /lib64/ld-linux-x86-64.so.2 to /tmp/deps
Done!
Get the code
About Hemanth HM
Hemanth HM is a Sr. Machine Learning Manager at PayPal, Google Developer Expert, TC39 delegate, FOSS advocate, and community leader with a passion for programming, AI, and open-source contributions.