Thursday 14 July 2016

A quick note on shared libraries

A shared library is basically some lines of code which when loaded into memory can be linked to a program at run time.
Multiple programs can share the libraries code loaded in memory & hence the name.
Shared libraries are easy to identify with names prefixed by lib & suffixed by .so.

For programs to make efficient use of shared libraries it's important to know their location.

The file /etc/ld.so.conf consists of path names that will be searched by the loader for shared libraries to be loaded.

The contents of the file for a fedora workstation are given below:

[user@linclient ~]#cat /etc/ld.so.conf
include ld.so.conf.d/*.conf
/usr/lib/mysql
/usr/X11R6/lib
/usr/lib/qt-3.3/lib
/opt/hp/lib
/opt/dce-1.1/lib
[user@linclient ~]#

If we want to view the shared libraries required by a program or command to work we can use the ldd command.
For example, if we want to see the shared libraries required by touch command:

[user@linclient ~]#ldd /bin/touch
        libc.so.6 => /lib/tls/libc.so.6 (0x00bc2000)
        /lib/ld-linux.so.2 => /lib/ld-linux.so.2 (0x00ba9000)
[user@linclient ~]#

It would be inefficient if every time a program needs to use a shared library the loader would check the /etc/ld.so.conf file, go through the path names &
then traverse each individual directory tree to finally load the share library object.

This task is taken care of by the ldconfig. Ldconfig creates the necessary links and cache to the most recent shared libraries found in the directories specified on the command line, in the file /etc/ld.so.conf, directories /lib and /usr/lib. The cache file is named ld.so.cache & resides in /etc directory.
If we make changes to the ld.so.conf file or add another conf file or shared library object  in the path names we just need to run the ldconfig command to update the cache.

If we want to see the contents of the cache we can run 'ldconfig -v' & it will display the contents of the cache while it rebuilds it.
Here's a snippet:

[user@linclient ~]# ldconfig -v
ldconfig: Can't stat /opt/hp/lib: No such file or directory
/usr/lib/mysql:
        libmysqlclient_r.so.10 -> libmysqlclient_r.so.10.0.0
        libmysqlclient.so.10 -> libmysqlclient.so.10.0.0
/usr/X11R6/lib:
        libdps.so.1 -> libdps.so.1.0
        libXcursor.so.1 -> libXcursor.so.1.0.2
        libxcin.so.0 -> libxcin.so.0.0.0
        libGL.so.1 -> libGL.so.1.2
        libOSMesa.so.4 -> libOSMesa.so.4.0
        libfontenc.so.1 -> libfontenc.so.1.0

If we want to run a program which will use a non-standard shared library for a temporary purpose then we can add the path to the library in the environment variable LD_LIBRARY_PATH.

No comments:

Post a Comment

Using capture groups in grep in Linux

Introduction Let me start by saying that this article isn't about capture groups in grep per se. What we are going to do here with gr...