Linker and Libraries Guide

Chapter 4 Shared Objects

Shared objects are one form of output created by the link-editor and are generated by specifying the -G option. In the following example, the shared object is generated from the input file foo.c.

$ cc -o -G -K pic foo.c

A shared object is an indivisible unit generated from one or more relocatable objects. Shared objects can be bound with dynamic executables to form a runable process. As their name implies, shared objects can be shared by more than one application. Because of this potentially far-reaching effect, this chapter describes this form of link-editor output in greater depth than has been covered in previous chapters.

For a shared object to be bound to a dynamic executable or another shared object, it must first be available to the link-edit of the required output file. During this link-edit, any input shared objects are interpreted as if they had been added to the logical address space of the output file being produced. All the functionality of the shared object is made available to the output file.

These shared objects become dependencies of this output file. A small amount of bookkeeping information is maintained within the output file to describe these dependencies. The runtime linker interprets this information and completes the processing of these shared objects as part of creating a runable process.

The following sections expand upon the use of shared objects within the compilation and runtime environments. These environments are introduced in Runtime Linking.

Naming Conventions

Neither the link-editor nor the runtime linker interprets any file by virtue of its file name. All files are inspected to determine their ELF type (see ELF Header). This information enables the link-editor to deduce the processing requirements of the file. However, shared objects usually follow one of two naming conventions, depending on whether they are being used as part of the compilation environment or the runtime environment.

When used as part of the compilation environment, shared objects are read and processed by the link-editor. Although these shared objects can be specified by explicit file names as part of the command passed to the link-editor, the -l option is usually used to take advantage of the link-editor's library search capabilities. See Shared Object Processing.

A shared object applicable to this link-editor processing should be designated with the prefix lib and the suffix .so. For example, /usr/lib/ is the shared object representation of the standard C library made available to the compilation environment. By convention, 64–bit shared objects are placed in a subdirectory of the lib directory called 64. For example, the 64–bit counterpart of /usr/lib/, is /usr/lib/64/

When used as part of the runtime environment, shared objects are read and processed by the runtime linker. To allow for change in the exported interface of the shared object over a series of software releases, provide the shared object as a versioned file name.

A versioned file name commonly takes the form of a .so suffix followed by a version number. For example, /usr/lib/ is the shared object representation of version one of the standard C library made available to the runtime environment.

If a shared object is never intended for use within a compilation environment, its name might drop the conventional lib prefix. Examples of shared objects that fall into this category are those used solely with dlopen(3DL). A suffix of .so is still recommended to indicate the actual file type, and a version number is strongly recommended to provide for the correct binding of the shared object across a series of software releases. Chapter 5, Application Binary Interfaces and Versioning describes versioning in more detail.

Note –

The shared object name used in a dlopen(3DL) is usually represented as a simple file name, those with no `/' in the name. The runtime linker can then use a set of rules to locate the actual file. See Loading Additional Objects for more details.

Recording a Shared Object Name

The recording of a dependency in a dynamic executable or shared object will, by default, be the file name of the associated shared object as it is referenced by the link-editor. For example, the following dynamic executables, built against the same shared object, result in different interpretations of the same dependency:

$ cc -o ../tmp/ -G foo.o
$ cc -o prog main.o -L../tmp -lfoo
$ dump -Lv prog | grep NEEDED
[1]     NEEDED

$ cc -o prog main.o ../tmp/
$ dump -Lv prog | grep NEEDED
[1]     NEEDED   ../tmp/

$ cc -o prog main.o /usr/tmp/
$ dump -Lv prog | grep NEEDED
[1]     NEEDED   /usr/tmp/

As these examples show, this mechanism of recording dependencies can result in inconsistencies due to different compilation techniques. Also, the location of a shared object as referenced during the link-edit might differ from the eventual location of the shared object on an installed system. To provide a more consistent means of specifying dependencies, shared objects can record within themselves the file name by which they should be referenced at runtime.

During the link-edit of a shared object, its runtime name can be recorded within the shared object itself by using the -h option. In the following example, the shared object's runtime name, is recorded within the file itself. This identification is known as an soname.

$ cc -o ../tmp/ -G -K pic -h foo.c

The following example shows how the soname recording can be displayed using dump(1) and referring to the entry that has the SONAME tag.

$ dump -Lvp ../tmp/

[INDEX] Tag      Value
[1]     SONAME

When the link-editor processes a shared object that contains an soname, this is the name that is recorded as a dependency within the output file being generated.

If this new version of is used during the creation of the dynamic executable prog from the previous example, all three methods of creating the executable result in the same dependency recording.

$ cc -o prog main.o -L../tmp -lfoo
$ dump -Lv prog | grep NEEDED
[1]     NEEDED

$ cc -o prog main.o ../tmp/
$ dump -Lv prog | grep NEEDED
[1]     NEEDED

$ cc -o prog main.o /usr/tmp/
$ dump -Lv prog | grep NEEDED
[1]     NEEDED

In the previous examples, the -h option is used to specify a simple file name, one that has no `/' in the name. This convention enables the runtime linker to use a set of rules to locate the actual file. See Locating Shared Object Dependencies for more details.

Inclusion of Shared Objects in Archives

The mechanism of recording an soname within a shared object is essential if the shared object is ever processed from an archive library.

An archive can be built from one or more shared objects and then used to generate a dynamic executable or shared object. Shared objects can be extracted from the archive to satisfy the requirements of the link-edit. Unlike the processing of relocatable objects, which are concatenated to the output file being created, any shared objects extracted from the archive will be recorded as dependencies. See Archive Processing for more details on the criteria for archive extraction.

The name of an archive member is constructed by the link-editor and is a concatenation of the archive name and the object within the archive. For example:

$ cc -o -G -K pic foo.c
$ ar -r libfoo.a
$ cc -o main main.o libfoo.a
$ dump -Lv main | grep NEEDED
[1]     NEEDED   libfoo.a(

Because a file with this concatenated name is unlikely to exist at runtime, providing an soname within the shared object is the only means of generating a meaningful runtime file name for the dependency.

Note –

The runtime linker does not extract objects from archives. Therefore, in the above example the required shared object dependencies must be extracted from the archive and made available to the runtime environment.

Recorded Name Conflicts

When shared objects are used to create a dynamic executable or another shared object, the link-editor performs several consistency checks to ensure that any dependency names that will be recorded in the output file are unique.

Conflicts in dependency names can occur if two shared objects used as input files to a link-edit both contain the same soname. For example:

$ cc -o -G -K pic -h foo.c
$ cc -o -G -K pic -h bar.c
$ cc -o prog main.o -L. -lfoo -lbar
ld: fatal: recording name conflict: file `./' and \
    file `./' provide identical dependency names:
ld: fatal: File processing errors. No output written to prog

A similar error condition will occur if the file name of a shared object that does not have a recorded soname matches the soname of another shared object used during the same link-edit.

If the runtime name of a shared object being generated matches one of its dependencies, the link-editor also reports a name conflict. For example:

$ cc -o -G -K pic -h bar.c -L. -lfoo
ld: fatal: recording name conflict: file `./' and \
    -h option provide identical dependency names:
ld: fatal: File processing errors. No output written to

Shared Objects With Dependencies

Shared objects can have their own dependencies. The search rules used by the runtime linker to locate shared object dependencies are covered in Directories Searched by the Runtime Linker. If a shared object does not reside in the default directory /usr/lib (for 32–bit objects), or /usr/lib/64 (for 64–bit objects), then the runtime linker must explicitly be told where to look. The preferred mechanism of indicating any requirement of this kind is to record a runpath in the object that has the dependencies by using the link-editor's -R option.

In the following example, the shared object has a dependency on, which is expected to reside in the directory /home/me/lib at runtime or, failing that, in the default location.

$ cc -o -G -K pic bar.c
$ cc -o -G -K pic foo.c -R/home/me/lib -L. -lbar
$ dump -Lv

[INDEX] Tag      Value
[1]     NEEDED
[2]     RUNPATH  /home/me/lib

The shared object is responsible for specifying any runpath required to locate its dependencies. Any runpath specified in the dynamic executable is only used to locate the dependencies of the dynamic executable. These runpaths are not used to locate any dependencies of the shared objects.

The environment variable LD_LIBRARY_PATH has a more global scope. Any path names specified using this variable are used by the runtime linker to search for any shared object dependencies. Although useful as a temporary mechanism that influences the runtime linker's search path, the use of this environment variable is strongly discouraged in production software. See Directories Searched by the Runtime Linker for a more extensive discussion.

Dependency Ordering

When dynamic executables and shared objects have dependencies on the same common shared objects, the order in which the objects are processed can become less predictable.

For example, assume a shared object developer generates with the following dependencies:

$ ldd =>     ./ =>     ./ =>     ./

If you create a dynamic executable, prog, using this shared object, and also define an explicit dependency on, then the resulting shared object order will be:

$ cc -o prog main.c -R. -L. -lC -lfoo
$ ldd prog =>     ./ =>   ./ =>     ./ =>     ./

Any requirement on the order of processing the shared object dependencies would be compromised by the construction of the dynamic executable prog.

Developers who place special emphasis on symbol interposition and .init section processing should be aware of this potential change in shared object processing order.

Shared Objects as Filters

A filter is a special form of shared object used to provide indirection to an alternative shared object. Two forms of shared object filter exist: a standard filter and an auxiliary filter.

A standard filter, in essence, consists solely of a symbol table, and provides a mechanism of abstracting the compilation environment from the runtime environment. A link-edit using the filter will reference the symbols provided by the filter itself; however, the implementation of the symbol reference is provided from an alternative source at runtime.

Standard filters are identified using the link-editor's -F flag. This flag takes an associated file name indicating the shared object that supplies symbol references at runtime. This shared object is referred to as the filtee. Multiple use of the -F flag enables multiple filtees to be recorded.

If the filtee cannot be processed at runtime, or any symbol defined by the filter cannot be located within the filtees, a fatal error condition results.

An auxiliary filter has a similar mechanism, except that the filter itself contains an implementation corresponding to its symbols. A link-edit using the filter references the symbols provided by the filter itself. The implementation of the symbol reference can be provided from an alternative source at runtime.

Auxiliary filters are identified using the link-editor's -f flag. This flag takes an associated file name indicating the shared object that can be used to supply symbols at runtime. This shared object is referred to as the filtee. Multiple use of the -f flag allows multiple filtees to be recorded.

If the filtee cannot be processed at runtime, or any symbol defined by the filter cannot be located within the filtee, the implementation of the symbol within the filter will be used.

Generating a Standard Filter

To generate a standard filter, you first define a filtee,, on which this filter technology is applied. This filtee might be built from several relocatable objects. In the following example, one of these objects originates from the file bar.c, and supplies the symbols foo and bar.

$ cat bar.c
char * bar = "bar";

char * foo()
        return("defined in bar.c");
$ cc -o -G -K pic .... bar.c ....

In the following example a standard filter,, is generated for the symbols foo and bar, and indicates the association to the filtee The environment variable LD_OPTIONS is used to circumvent the compiler driver from interpreting the -F option as one of its own.

$ cat foo.c
char * bar = 0;

char * foo(){}

cc -o -G -K pic -h -R. foo.c
$ ln -s
$ dump -Lv | egrep "SONAME|FILTER"
[1]     SONAME
[2]     FILTER

If the link-editor references the standard filter to create a dynamic executable or shared object, it will use the information from the filter's symbol table during symbol resolution. See Symbol Resolution for more details.

At runtime, any reference to the symbols of the filter result in the additional loading of the filtee The runtime linker uses this filtee to resolve any symbols defined by

For example, the following dynamic executable, prog, references the symbols foo and bar, which are resolved during link-edit from the filter

$ cat main.c
extern char * bar, * foo();

        (void) printf("foo() is %s: bar=%s\n", foo(), bar);
$ cc -o prog main.c -R. -L. -lfoo
$ prog
foo() is defined in bar.c: bar=bar

The execution of the dynamic executable prog results in the function foo(), and the data item bar, being obtained from the filtee, not from the filter

In this example, the filtee is uniquely associated to the filter and is not available to satisfy symbol lookup from any other objects that might be loaded as a consequence of executing prog.

Standard filters provide a mechanism for defining a subset interface of an existing shared object, or an interface group spanning a number of existing shared objects. Several filters are used in the Solaris operating environment.

The /usr/lib/ filter provides a subset of the standard C library /usr/lib/ This subset represents the ABI-conforming functions and data items that reside in the C library that must be imported by a conforming application.

The /usr/lib/ filter defines the user interface to the runtime linker itself. This interface provides an abstraction between the symbols referenced in a compilation environment from and the actual implementation binding produced within the runtime environment from

The /usr/lib/ filter uses multiple filtees. This library provides socket and XTI interfaces from /usr/lib/, /usr/lib/, and /usr/lib/

Because the code in a standard filter is never referenced at runtime, there is no point in adding content to any functions defined within the filter. Filter code might require relocation, which would result in an unnecessary overhead when processing the filter at runtime. Functions are best defined as empty routines, or directly from a mapfile. See Defining Additional Symbols.

When generating data symbols within a filter, you should always initialize the data items to ensure that they result in references from dynamic executables.

Some of the more complex symbol resolutions carried out by the link-editor require knowledge of a symbol's attributes, including the symbol's size. See Symbol Resolution for more details. Therefore, you should generate the symbols in the filter so that their attributes match those of the symbols in the filtee. This ensures that the link-editing process analyzes the filter in a manner compatible with the symbol definitions used at runtime.

Note –

The link-editor uses the ELF class of the first input relocatable file it sees to govern the class of object it creates. Use the link-editor's -64 option to create a 64–bit filter solely from a mapfile.

Generating an Auxiliary Filter

The creation of an auxiliary filter is essentially the same as creating a standard filter (see Generating a Standard Filter for more details). First define a filtee,, on which this filter technology is applied. This filtee might be built from several relocatable objects. One of these objects originates from the file bar.c, and supplies the symbol foo:

$ cat bar.c
char * foo()
        return("defined in bar.c");
$ cc -o -G -K pic .... bar.c ....

In the following example, an auxiliary filter,, is generated for the symbols foo and bar, and indicates the association to the filtee The environment variable LD_OPTIONS is used to circumvent the compiler driver from interpreting the -f option as one of its own.

$ cat foo.c
char * bar = "foo";

char * foo()
        return ("defined in foo.c");
$ LD_OPTIONS='-f' \
cc -o -G -K pic -h -R. foo.c
$ ln -s
$ dump -Lv | egrep "SONAME|AUXILIARY"
[1]     SONAME

If the link-editor references the auxiliary filter to create a dynamic executable or shared object, it will use the information from the filter's symbol table during symbol resolution. See Symbol Resolution for more details.

At runtime, any reference to the symbols of the filter result in a search for the filtee If this filtee is found, the runtime linker uses the filtee to resolve any symbols defined by If the filtee is not found, or a symbol from the filter is not found in the filtee, then the original value of the symbol within the filter is used.

For example, the following dynamic executable, prog, references the symbols foo and bar, which are resolved during link-edit from the filter

$ cat main.c
extern char * bar, * foo();

        (void) printf("foo() is %s: bar=%s\n", foo(), bar);
$ cc -o prog main.c -R. -L. -lfoo
$ prog
foo() is defined in bar.c: bar=foo

When the dynamic executable prog is executed, the function foo() is obtained from the filtee, not from the filter However, the data item bar is obtained from the filter, as this symbol has no alternative definition in the filtee

Auxiliary filters provide a mechanism for defining an alternative interface of an existing shared object. This mechanism is used in the Solaris operating environment to provide optimized functionality within platform specific shared objects. See Instruction Set Specific Shared Objects and System Specific Shared Objects for examples.

Note –

The environment variable LD_NOAUXFLTR can be set to disable the runtime linkers auxiliary filter processing. Because auxiliary filters are frequently employed to provide platform specific optimizations, this option can be useful in evaluating a filtee's use and performance impact.

Filtee Processing

The runtime linker's processing of a filter defers the loading of a filtee until a reference to a symbol within the filter has occurred. This implementation is analogous to the filter performing a dlopen(3DL) on each of its filtees as they are required. This implementation accounts for differences in dependency reporting that can be produced by tools such as ldd(1).

The link-editor's -z loadfltr option can be used when creating a filter to cause the immediate processing of its filtees at runtime. In addition, the immediate processing of any filtees within a process can be triggered by setting the LD_LOADFLTR environment variable to any value.

Performance Considerations

A shared object can be used by multiple applications within the same system. The performance of a shared object affects the applications that use it and the system as a whole.

Although the actual code within a shared object will directly affect the performance of a running process, the performance issues focused upon here target the runtime processing of the shared object itself. The following sections investigate this processing in more detail by looking at aspects such as text size and purity, together with relocation overhead.

Analyzing Files

Various tools are available to analyze the contents of an ELF file. To display the size of a file use the size(1) command. For example:

$ size -x
59c + 10c + 20 = 0x6c8

$ size -xf
..... + 1c(.init) + ac(.text) + c(.fini) + 4(.rodata) + \
..... + 18(.data) + 20(.bss) .....

The first example indicates the size of the shared objects text, data, and bss, a categorization used in previous releases of the SunOS operating system.

The ELF format provides a finer granularity for expressing data within a file by organizing the data into sections. The second example displays the size of each of the file's loadable sections.

Sections are allocated to units known as segments, some of which describe how portions of a file are mapped into memory (see the mmap(2) man page). These loadable segments can be displayed by using the dump(1) command and examining the LOAD entries. For example:

$ dump -ov
Type        Offset      Vaddr       Paddr
Filesz      Memsz       Flags       Align

LOAD        0x94        0x94        0x0
0x59c       0x59c       r-x         0x10000

LOAD        0x630       0x10630     0x0
0x10c       0x12c       rwx         0x10000

There are two loadable segments in the shared object, commonly referred to as the text and data segments. The text segment is mapped to allow reading and execution of its contents (r-x), whereas the data segment is mapped to also allow its contents to be modified (rwx). The memory size (Memsz) of the data segment differs from the file size (Filesz). This difference accounts for the .bss section, which is part of the data segment, and is dynamically created when the segment is loaded.

Programmers usually think of a file in terms of the symbols that define the functions and data elements within their code. These symbols can be displayed using nm(1). For example:

$ nm -x

[Index]   Value      Size      Type  Bind  Other Shndx   Name
[39]    |0x00000538|0x00000000|FUNC |GLOB |0x0  |7      |_init
[40]    |0x00000588|0x00000034|FUNC |GLOB |0x0  |8      |foo
[41]    |0x00000600|0x00000000|FUNC |GLOB |0x0  |9      |_fini
[42]    |0x00010688|0x00000010|OBJT |GLOB |0x0  |13     |data
[43]    |0x0001073c|0x00000020|OBJT |GLOB |0x0  |16     |bss

The section that contains a symbol can be determined by referencing the section index (Shndx) field from the symbol table and by using dump(1) to display the sections within the file. For example:

$ dump -hv
           **** SECTION HEADER TABLE ****
[No]    Type    Flags   Addr      Offset    Size      Name
[7]     PBIT    -AI     0x538     0x538     0x1c      .init

[8]     PBIT    -AI     0x554     0x554     0xac      .text

[9]     PBIT    -AI     0x600     0x600     0xc       .fini
[13]    PBIT    WA-     0x10688   0x688     0x18      .data

[16]    NOBI    WA-     0x1073c   0x73c     0x20      .bss

The output from both the previous nm(1) and dump(1) examples shows the association of the functions _init, foo, and _fini to the sections .init, .text and .fini. These sections, because of their read-only nature, are part of the text segment.

Similarly, the data arrays data, and bss are associated with the sections .data and .bss respectively. These sections, because of their writable nature, are part of the data segment.

Note –

The previous dump(1) display has been simplified for this example.

Underlying System

When an application is built using a shared object, the entire loadable contents of the object are mapped into the virtual address space of that process at runtime. Each process that uses a shared object starts by referencing a single copy of the shared object in memory.

Relocations within the shared object are processed to bind symbolic references to their appropriate definitions. This results in the calculation of true virtual addresses that could not be derived at the time the shared object was generated by the link-editor. These relocations usually result in updates to entries within the process's data segments.

The memory management scheme underlying the dynamic linking of shared objects shares memory among processes at the granularity of a page. Memory pages can be shared as long as they are not modified at runtime. If a process writes to a page of a shared object when writing a data item, or relocating a reference to a shared object, it generates a private copy of that page. This private copy will have no effect on other users of the shared object. However, this page has lost any benefit of sharing between other processes. Text pages that become modified in this manner are referred to as impure.

The segments of a shared object that are mapped into memory fall into two basic categories; the text segment, which is read-only, and the data segment, which is read-write. See Analyzing Files on how to obtain this information from an ELF file. An overriding goal when developing a shared object is to maximize the text segment and minimize the data segment. This optimizes the amount of code sharing while reducing the amount of processing needed to initialize and use a shared object. The following sections present mechanisms that can help achieve this goal.

Lazy Loading of Dynamic Dependencies

You can defer the loading of a shared object dependency until the dependency is first referenced by establishing the object as lazy loadable. See Lazy Loading of Dynamic Dependencies.

For small applications a typical thread of execution may reference all the applications dependencies. The application loads all of its dependencies whether they are defined lazy loadable or not. However, under lazy loading, dependency processing may be deferred from process startup and spread throughout the process's execution.

For applications with many dependencies, lazy loading often results in some dependencies not being loaded at all. These dependencies are those not referenced for the particular thread of execution.

Position-Independent Code

The compiler can generate position-independent code under the -K pic option. Whereas the code within a dynamic executable is usually tied to a fixed address in memory, position-independent code can be loaded anywhere in the address space of a process. Because the code is not tied to a specific address, it will execute correctly without page modification at a different address in each process that uses it. This code creates programs that require the smallest amount of page modification at runtime.

When you use position-independent code, relocatable references are generated as an indirection that use data in the shared object's data segment. The text segment code remains read-only, and all relocation updates are applied to corresponding entries within the data segment. See Global Offset Table (Processor-Specific) and Procedure Linkage Table (Processor-Specific) for more details on the use of these two sections.

If a shared object is built from code that is not position-independent, the text segment will usually require a large number of relocations to be performed at runtime. Although the runtime linker is equipped to handle this, the system overhead this creates can cause serious performance degradation.

You can identify a shared object that requires relocations against its text segment. Use dump(1) and inspect the output for any TEXTREL entry. For example:

$ cc -o -G -R. foo.c
$ dump -Lv | grep TEXTREL
[9]     TEXTREL  0

Note –

The value of the TEXTREL entry is irrelevant. Its presence in a shared object indicates that text relocations exist.

To prevent the creation of a shared object that contains text relocations use the link-editor's -z text flag. This flag causes the link-editor to generate diagnostics indicating the source of any non-position-independent code used as input. Such code results in a failure to generate the intended shared object. For example:

$ cc -o -z text -G -R. foo.c
Text relocation remains                       referenced
    against symbol                  offset      in file
foo                                 0x0         foo.o
bar                                 0x8         foo.o
ld: fatal: relocations remain against allocatable but \
non-writable sections

Two relocations are generated against the text segment because of the non-position-independent code generated from the file foo.o. Where possible, these diagnostics indicate any symbolic references that are required to carry out the relocations. In this case, the relocations are against the symbols foo and bar.

Another common cause of creating text relocations when generating a shared object is by including hand-written assembler code that has not been coded with the appropriate position-independent prototypes.

Note –

You may want to experiment with some simple source files to determine coding sequences that enable position-independence. Use the compilers ability to generate intermediate assembler output.

SPARC: -K pic and -K PIC Options

For SPARC binaries, a subtle difference between the -K pic option and an alternative -K PIC option affects references to global offset table entries. See Global Offset Table (Processor-Specific).

The global offset table is an array of pointers, the size of whose entries are constant for 32–bit (4–bytes) and 64–bit (8–bytes). The following code sequence makes reference to an entry under -K pic:

        ld    [%l7 + j], %o0    ! load &j into %o0

Where %l7 is the precomputed value of the symbol _GLOBAL_OFFSET_TABLE_ of the object making the reference.

This code sequence provides a 13–bit displacement constant for the global offset table entry. This displacement therefore provides for 2048 unique entries for 32–bit objects, and 1024 unique entries for 64–bit objects. If an object is built that requires more than the available number of entries, the link-editor produces a fatal error:

$ cc -K pic -G -o a.o b.o ... z.o
ld: fatal: too many symbols require `small' PIC references:
        have 2050, maximum 2048 -- recompile some modules -K PIC.

To overcome this error condition, compile some of the input relocatable objects with the -K PIC option. This option provides a 32–bit constant for the global offset table entry:

        sethi %hi(j), %g1
        or    %g1, %lo(j), %g1    ! get 32-bit constant GOT offset
        ld    [%l7 + %g1], %o0    ! load &j into %o0

You can investigate the global offset table requirements of an object using elfdump(1) with the -G option. You can also examine the processing of these entries during a link-edit using the link-editors debugging tokens -D got,detail.

Ideally, frequently accessed data items benefit from using the -K pic model. You can reference a single entry using both models. However, determining which relocatable objects should be compiled with either option can be time consuming, and the performance improvement realized small. A recompilation of all relocatable objects with the -K PIC option is typically easier.

Remove Unused Material

The inclusion of functions and data that are not used by the object being built, is wasteful. This material bloats the object, which can result in unnecessary relocation overhead and associated paging activity. References to unused dependencies are also wasteful. These references result in the unnecessary loading and processing of other shared objects.

Unused sections are displayed during a link-edit when using the link-editors debugging token -D unused. Sections identified as unused should be removed from the link-edit, or eliminated using the link-editors -z ignore option.

The link-editor identifies a section from a relocatable object as unused if:

You can improve the link-editors ability to eliminate sections by defining the shared objects external interfaces. By defining an interface, global symbols that are not defined as part of the interface are reduced to locals. These reduced symbols, if unreferenced from other objects, are now clearly identified as candidates for elimination.

Individual functions and data variables can be eliminated by the link-editor if these items are assigned to their own sections. This section refinement is achieved using compiler options such as -xF. Earlier compilers only provided for the assignment of functions to their own sections. Newer compilers have extended the -xF syntax to assign data variables to their own sections. Earlier compilers required C++ exception handling to be disabled when using -xF. This restriction has been dropped with later compilers.

If all allocatable sections from a relocatable object can be eliminated, the entire file is discarded from the link-edit.

In addition to input file elimination, the link-editor also identifies unused dependencies. A dependency is deemed unused if it is not bound to by the object being produced. An object built with the -z ignore option, will have no unused dependencies recorded in it.

The -z ignore option applies only to the files that follow the option on the link-edit command line. The -z ignore option is cancelled with -z record.

Maximizing Shareability

As mentioned in Underlying System, only a shared object's text segment is shared by all processes that use it. The object's data segment typically is not shared. Each process using a shared object, generates a private memory copy of its entire data segment as data items within the segment are written to. Reduce the data segment, either by moving data elements that are never written to the text segment, or by removing the data items completely.

The following sections describe several mechanisms that can be used to reduce the size of the data segment.

Move Read-Only Data to Text

Data elements that are read-only should be moved into the text segment using const declarations. For example, the following character string resides in the .data section, which is part of the writable data segment:

char * rdstr = "this is a read-only string";

In contrast, the following character string resides in the .rodata section, which is the read-only data section contained within the text segment:

const char * rdstr = "this is a read-only string";

Reducing the data segment by moving read-only elements into the text segment is admirable. However, moving data elements that require relocations can be counterproductive. For example, examine the following array of strings:

char * rdstrs[] = { "this is a read-only string",
                    "this is another read-only string" };

A better definition might seem to be:

const char * const rdstrs[] = { ..... };

This definition ensures that the strings and the array of pointers to these strings are placed in a .rodata section. Unfortunately, although the user perceives the array of addresses as read-only, these addresses must be relocated at runtime. This definition therefore results in the creation of text relocations. Representing it as:

const char * rdstrs[] = { ..... };

insures the array pointers are maintained in the writable data segment where they can be relocated. The array strings are maintained in the read-only text segment.

Note –

Some compilers, when generating position-independent code, can detect read-only assignments that result in runtime relocations. These compilers arrange for placing such items in writable segments. For example, .picdata.

Collapse Multiply-Defined Data

Data can be reduced by collapsing multiply-defined data. A program with multiple occurrences of the same error messages can be better off by defining one global datum, and have all other instances reference this. For example:

const char * Errmsg = "prog: error encountered: %d";

        (void) fprintf(stderr, Errmsg, error);

The main candidates for this sort of data reduction are strings. String usage in a shared object can be investigated using strings(1). The following example generates a sorted list of the data strings within the file Each entry in the list is prefixed with the number of occurrences of the string.

$ strings -10 | sort | uniq -c | sort -rn 

Use Automatic Variables

Permanent storage for data items can be removed entirely if the associated functionality can be designed to use automatic (stack) variables. Any removal of permanent storage usually results in a corresponding reduction in the number of runtime relocations required.

Allocate Buffers Dynamically

Large data buffers should usually be allocated dynamically rather than being defined using permanent storage. Often this results in an overall saving in memory, as only those buffers needed by the present invocation of an application are allocated. Dynamic allocation also provides greater flexibility by enabling the buffer's size to change without affecting compatibility.

Minimizing Paging Activity

Any process that accesses a new page causes a page fault, which is an expensive operation. Because shared objects can be used by many processes, any reduction in the number of page faults generated by accessing a shared object will benefit the process and the system as a whole.

Organizing frequently used routines and their data to an adjacent set of pages frequently improves performance because it improves the locality of reference. When a process calls one of these functions, the function might already be in memory because of its proximity to the other frequently used functions. Similarly, grouping interrelated functions improves locality of references. For example, if every call to the function foo() results in a call to the function bar(), place these functions on the same page. Tools like cflow(1), tcov(1), prof(1) and gprof(1) are useful in determining code coverage and profiling.

Isolate related functionality to its own shared object. The standard C library has historically been built containing many unrelated functions. Only rarely, for example, will any single executable use everything in this library. Because of widespread use, determining what set of functions are really the most frequently used is also somewhat difficult. In contrast, when designing a shared object from scratch, maintain only related functions within the shared object. This will improve locality of reference and has the side effect of reducing the object's overall size.


In Relocation Processing, the mechanisms by which the runtime linker relocates dynamic executables and shared objects to create a runable process was covered. Symbol Lookup and When Relocations Are Performed categorized this relocation processing into two areas to simplify and help illustrate the mechanisms involved. These same two categorizations are also ideally suited for considering the performance impact of relocations.

Symbol Lookup

When the runtime linker needs to look up a symbol, by default it does so by searching in each object. The runtime linker starts with the dynamic executable, and progresses through each shared object in the same order that the objects are loaded. In many instances, the shared object that requires a symbolic relocation turns out to be the provider of the symbol definition.

In this situation, if the symbol used for this relocation is not required as part of the shared object's interface, then this symbol is a strong candidate for conversion to a static or automatic variable. A symbol reduction can also be applied to removed symbols from a shared objects interface. See Reducing Symbol Scope for more details. By making these conversions, the link-editor incurs the expense of processing any symbolic relocation against these symbols during the shared object's creation.

The only global data items that should be visible from a shared object are those that contribute to its user interface. Historically this has been a hard goal to accomplish, because global data are often defined to allow reference from two or more functions located in different source files. By applying symbol reduction, unnecessary global symbols can be removed. See Reducing Symbol Scope. Any reduction in the number of global symbols exported from a shared object results in lower relocation costs and an overall performance improvement.

The use of direct bindings can also significantly reduce the symbol lookup overhead within a dynamic process that has many symbolic relocations and many dependencies. See Direct Binding.

When Relocations are Performed

All immediate reference relocations must be carried out during process initialization before the application gains control. However, any lazy reference relocations can be deferred until the first instance of a function being called. Immediate relocations typically result from data references. Therefore, reducing the number of data references also reduces the runtime initialization of a process.

Initialization relocation costs can also be deferred by converting data references into function references. For example, you can return data items by a functional interface. This conversion usually results in a perceived performance improvement because the initialization relocation costs are effectively spread throughout the process's execution. Some of the functional interfaces might never be called by a particular invocation of a process, thus removing their relocation overhead altogether.

The advantage of using a functional interface can be seen in the section, Copy Relocations. This section examines a special, and somewhat expensive, relocation mechanism employed between dynamic executables and shared objects. It also provides an example of how this relocation overhead can be avoided.

Combined Relocation Sections

Relocations by default are grouped by the sections against which they are to be applied. However, when an object is built with the -z combreloc option, all but the procedure linkage table relocations are placed into a single common section named .SUNW_reloc. See Procedure Linkage Table (Processor-Specific).

Combining relocation records in this manner enables all RELATIVE relocations to be grouped together. All symbolic relocations are sorted by symbol name. The grouping of RELATIVE relocations permits optimized runtime processing using the DT_RELACOUNT/DT_RELCOUNT .dynamic entries. Sorted symbolic entries help reduce runtime symbol lookup.

Copy Relocations

Shared objects are usually built with position-independent code. References to external data items from code of this type employs indirect addressing through a set of tables. See Position-Independent Code for more details. These tables are updated at runtime with the real address of the data items. These updated tables enable access to the data without the code itself being modified.

Dynamic executables, however, are generally not created from position-independent code. Any references to external data they make can seemingly only be achieved at runtime by modifying the code that makes the reference. Modifying a read-only text segment is to be avoided. The copy relocation technique can solve this reference.

Suppose the link-editor is used to create a dynamic executable, and a reference to a data item is found to reside in one of the dependent shared objects. Space is allocated in the dynamic executable's .bss, equivalent in size to the data item found in the shared object. This space is also assigned the same symbolic name as defined in the shared object. Along with this data allocation, the link-editor generates a special copy relocation record that will instruct the runtime linker to copy the data from the shared object to this allocated space within the dynamic executable.

Because the symbol assigned to this space is global, it is used to satisfy any references from any shared objects. The dynamic executable inherits the data item. Any other objects within the process that make reference to this item are bound to this copy. The original data from which the copy is made effectively becomes unused.

The following example of this mechanism uses an array of system error messages that is maintained within the standard C library. In previous SunOS operating system releases, the interface to this information was provided by two global variables, sys_errlist[], and sys_nerr. The first variable provided the array of error message strings, while the second conveyed the size of the array itself. These variables were commonly used within an application in the following manner:

$ cat foo.c
extern int      sys_nerr;
extern char *   sys_errlist[];

char *
error(int errnumb)
        if ((errnumb < 0) || (errnumb >= sys_nerr))
                return (0);
        return (sys_errlist[errnumb]);

The application uses the function error to provide a focal point to obtain the system error message associated with the number errnumb.

Examining a dynamic executable built using this code shows the implementation of the copy relocation in more detail:

$ cc -o prog main.c foo.c
$ nm -x prog | grep sys_
[36]  |0x00020910|0x00000260|OBJT |WEAK |0x0  |16 |sys_errlist
[37]  |0x0002090c|0x00000004|OBJT |WEAK |0x0  |16 |sys_nerr
$ dump -hv prog | grep bss
[16]    NOBI    WA-    0x20908   0x908    0x268   .bss
$ dump -rv prog


Offset      Symndx                Type              Addend

0x2090c     sys_nerr              R_SPARC_COPY      0
0x20910     sys_errlist           R_SPARC_COPY      0

The link-editor has allocated space in the dynamic executable's .bss to receive the data represented by sys_errlist and sys_nerr. These data are copied from the C library by the runtime linker at process initialization. Thus, each application that uses these data gets a private copy of the data in its own data segment.

There are two drawbacks to this technique. First, each application pays a performance penalty for the overhead of copying the data at runtime. Second, the size of the data array sys_errlist has now become part of the C library's interface. Suppose the size of this array were to change, prehaps as new error messages are added. Any dynamic executables that reference this array have to undergo a new link-edit to be able to access any of the new error messages. Without this new link-edit, the allocated space within the dynamic executable is insufficient to hold the new data.

These drawbacks can be eliminated if the data required by a dynamic executable are provided by a functional interface. The ANSI C function strerror(3C) returns a pointer to the appropriate error string, based on the error number supplied to it. One implementation of this function might be:

$ cat strerror.c
static const char * sys_errlist[] = {
        "Error 0",
        "Not owner",
        "No such file or directory",
static const int sys_nerr =
        sizeof (sys_errlist) / sizeof (char *);

char *
strerror(int errnum)
        if ((errnum < 0) || (errnum >= sys_nerr))
                return (0);
        return ((char *)sys_errlist[errnum]);

The error routine in foo.c can now be simplified to use this functional interface. This simplification in turn removes any need to perform the original copy relocations at process initialization.

Additionally, because the data are now local to the shared object, the data are no longer part of its interface. The shared object therefore has the flexibility of changing the data without adversely effecting any dynamic executables that use it. Eliminating data items from a shared object's interface generally improves performance while making the shared object's interface and code easier to maintain.

ldd(1), when used with either the -d or -r options, can verify any copy relocations that exist within a dynamic executable.

For example, suppose the dynamic executable prog had originally been built against the shared object and the following two copy relocations had been recorded:

$ nm -x prog | grep _size_
[36]   |0x000207d8|0x40|OBJT |GLOB |15  |_size_gets_smaller
[39]   |0x00020818|0x40|OBJT |GLOB |15  |_size_gets_larger
$ dump -rv size | grep _size_
0x207d8     _size_gets_smaller    R_SPARC_COPY      0
0x20818     _size_gets_larger     R_SPARC_COPY      0

A new version of this shared object is supplied that contains different data sizes for these symbols:

$ nm -x | grep _size_
[26]   |0x00010378|0x10|OBJT |GLOB |8   |_size_gets_smaller
[28]   |0x00010388|0x80|OBJT |GLOB |8   |_size_gets_larger

Running ldd(1) against the dynamic executable reveals:

$ ldd -d prog =>   ./
    copy relocation sizes differ: _size_gets_smaller
       (file prog size=40; file ./ size=10);
       ./ size used; possible insufficient data copied
    copy relocation sizes differ: _size_gets_larger
       (file prog size=40; file ./ size=80);
       ./prog size used; possible data truncation

ldd(1) shows that the dynamic executable will copy as much data as the shared object has to offer, but only accepts as much as its allocated space allows.

Copy relocations can be eliminated by building the application from position-independent code. See Position-Independent Code.

Using -B symbolic

The link-editor's -B symbolic option enables you to bind symbol references to their global definitions within a shared object. This option is historic, in that it was designed for use in creating the runtime linker itself.

Defining an object's interface and reducing non-public symbols to local is preferable to using the -B symbolic option. See Reducing Symbol Scope. Using -B symbolic can often result in some non-intuitive side effects.

If a symbolically bound symbol is interposed upon, then references to the symbol from outside of the symbolically bound object bind to the interposer. The object itself is already bound internally. Essentially, two symbols with the same name are now being referenced from within the process. A symbolically bound data symbol that results in a copy relocation creates the same interposition situation. See Copy Relocations.

Note –

Symbolically bound shared objects are identified by the .dynamic flag DF_SYMBOLIC. This flag is informational only. The runtime linker processes symbol lookups from these objects in the same manner as any other object. Any symbolic binding is assumed to have been created at the link-edit phase.

Profiling Shared Objects

The runtime linker can generate profiling information for any shared objects that are processed during the running of an application. The runtime linker is responsible for binding shared objects to an application and is therefore able to intercept any global function bindings. These bindings take place through .plt entries. See When Relocations Are Performed for details of this mechanism.

The LD_PROFILE environment variable specifies the name of a shared object to profile. You can analyze one shared object at a time using this environment variable. The setting of the environment variable can be used to analyze the use of the shared object by one or more applications. In the following example, the use of libc by the single invocation of the command ls(1) is analyzed:

$  ls -l

In the following example, the environment variable setting is recorded in a configuration file. This setting causes any application's use of libc to accumulate the analyzed information:

# crle  -e
$ ls -l
$ make
$ ...

When profiling is enabled, a profile data file is created, if it does not already exist. The file is mapped by the runtime linker. In the above examples, this data file is /var/tmp/ 64–bit libraries require an extended profile format and are written using the .profilex suffix. You can also specify an alternative directory to store the profile data using the LD_PROFILE_OUTPUT environment variable.

This profile data file is used to deposit profil(2) data and call count information related to the use of the specified shared object. This profiled data can be directly examined with gprof(1).

Note –

gprof(1) is most commonly used to analyze the gmon.out profile data created by an executable that has been compiled with the -xpg option of cc(1). The runtime linker's profile analysis does not require any code to be compiled with this option. Applications whose dependent shared objects are being profiled should not make calls to profil(2), because this system call does not provide for multiple invocations within the same process. For the same reason, these applications must not be compiled with the -xpg option of cc(1). This compiler-generated mechanism of profiling is also built on top of profil(2).

One of the most powerful features of this profiling mechanism is to enable the analysis of a shared object as used by multiple applications. Frequently, profiling analysis is carried out using one or two applications. However, a shared object, by its very nature, can be used by a multitude of applications. Analyzing how these applications use the shared object can offer insights into where energy might be spent to improvement the overall performance of the shared object.

The following example shows a performance analysis of libc over a creation of several applications within a source hierarchy.

$ ; export LD_PROFILE
$ make
$ gprof -b /usr/lib/ /var/tmp/

granularity: each sample hit covers 4 byte(s) ....

                                  called/total     parents
index  %time    self descendents  called+self    name      index
                                  called/total     children
                0.33        0.00      52/29381     _gettxt [96]
                1.12        0.00     174/29381     _tzload [54]
               10.50        0.00    1634/29381     <external>
               16.14        0.00    2512/29381     _opendir [15]
              160.65        0.00   25009/29381     _endopen [3]
[2]     35.0  188.74        0.00   29381         _open [2]
granularity: each sample hit covers 4 byte(s) ....

   %  cumulative    self              self    total         
 time   seconds   seconds    calls  ms/call  ms/call name   
 35.0     188.74   188.74    29381     6.42     6.42  _open [2]
 13.0     258.80    70.06    12094     5.79     5.79  _write [4]
  9.9     312.32    53.52    34303     1.56     1.56  _read [6]
  7.1     350.53    38.21     1177    32.46    32.46  _fork [9]

The special name <external> indicates a reference from outside of the address range of the shared object being profiled. Thus, in the above example, 1634 calls to the function open(2) within libc occurred from the dynamic executables, or from other shared objects, bound with libc while the profiling analysis was in progress.

Note –

The profiling of shared objects is multithread safe, except in the case where one thread calls fork(2) while another thread is updating the profile data information. The use of fork1(2) removes this restriction.