Kenwood Personal Computer HP 9000 User Manual

HP -UX Lin k er a n d Libr a r ies User 's Gu id e  
HP 9000 Com p u ter s  
B2355-90655  
Novem ber 1997  
© Copyright 1997 Hewlett-Packard Company. All rights reserved.  
Download from Www.Somanuals.com. All Manuals Search And Download.  
UNIX is a registered trademark in the United States and other  
countries, licensed exclusively through X/Open Company Limited.  
© Copyright 1979, 1980, 1983, 1985-1990 Regents of the University of  
California. This software is based in part on the Fourth Berkeley  
Software Distribution under license from the Regents of the University  
of California.  
Copyright © The Regents of the University of Colorado, a body corporate  
1979  
This document has been reproduced and modified with the permission of  
the Regents of the University of Colorado, a body corporate.  
PostScript is a trademark of Adobe Systems, Inc.  
Intel is a registered trademark and Intel 80386 is a trademark of Intel  
Corporation.  
Ethernet is a trademark of Xerox Corporation.  
© Copyright 1985-1986, 1988 Massachussetts Institute of Technology. X  
Window System is a trademark of the Massachussetts Institute of  
Technology.  
MS-DOS and Microsoft are U.S. registered trademarks of Microsoft  
Corporation.  
OSF/Motif is a trademark of the Open Software Foundation, Inc. in the  
U.S. and other countries. Certification for conformance with OSF/Motif  
user environment pending.  
3
Download from Www.Somanuals.com. All Manuals Search And Download.  
4
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
P r efa ce . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15  
Printing History. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15  
1. Wh a t's New in Recen t Relea ses  
PA-RISC Changes in Hardware Compatibility . . . . . . . . . . . . . . . . . . . .21  
PA-RISC 2.0 Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21  
PA-RISC Architectures and Their System Models . . . . . . . . . . . . . . . .22  
64-bit Mode Linker Toolset Compatibility with De Facto Industry  
Standards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23  
64-bit Mode ELF Object File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . .24  
New Features for 64-bit Mode Linking. . . . . . . . . . . . . . . . . . . . . . . . . . .25  
64-bit Mode Linker Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .25  
64-bit Mode Linker-defined Symbols. . . . . . . . . . . . . . . . . . . . . . . . . . .26  
64-bit Mode Link-time Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28  
64-bit Mode Run Time Differences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30  
Changes in Future Releases . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32  
Online Help for Linker and Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . .33  
Accessing Help with ld +help. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .33  
Accessing Help with the HP CDE Front Panel. . . . . . . . . . . . . . . . . . .33  
Accessing Help with the dthelpview Command . . . . . . . . . . . . . . . . . .33  
Accessing Help with the charhelp Command . . . . . . . . . . . . . . . . . . . .33  
2. Wh a t Ha p p en s Wh en You Com p ile a n d Lin k a P r ogr a m  
Compiling Programs on HP-UX:  
An Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .36  
Looking inside” a Compiler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .38  
What is an Object File? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40  
Local Definitions. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40  
5
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
Global Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40  
External References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40  
Compiler-Linker Interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41  
Linking Programs on HP-UX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42  
The crt0.o Startup File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43  
The a.out File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44  
File Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45  
Linking with Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46  
Library Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46  
Default Libraries. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 46  
The Default Library Search Path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47  
Link Order . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47  
Running the Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48  
Loading Programs: exec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48  
Binding Routines to a Program . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48  
Deferred Binding is the Default . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49  
Linker Thread-Safe Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50  
3. Lin k er Ta sk s  
Using the Compiler to Link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53  
Changing the Default Library Search Path with -Wl, -L . . . . . . . . . . 53  
Getting Verbose Output with -v . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54  
Passing Linker Options from the Compiler Command with -Wl . . . . 54  
Renaming the Output File with -o . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55  
Specifying Libraries with -l . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55  
Suppressing the Link-Edit Phase with -c . . . . . . . . . . . . . . . . . . . . . . 55  
Using Linker commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57  
Linking with the 32-bit crt0.o Startup File . . . . . . . . . . . . . . . . . . . . . 57  
Changing the Default Library Search Path with -L and LPATH . . . . 57  
6
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
Changing the Default Shared Library Binding with -B. . . . . . . . . . . .58  
Improving Shared Library Performance with -B symbolic . . . . . . . . .60  
Choosing Archive or Shared Libraries with -a . . . . . . . . . . . . . . . . . . .63  
Dynamic Linking with -A and -R. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .65  
Exporting Symbols with +e . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79  
Exporting Symbols with +ee . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81  
Exporting Symbols from main with -E . . . . . . . . . . . . . . . . . . . . . . . . .81  
Hiding Symbols with -h . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81  
Moving Libraries after Linking with +b . . . . . . . . . . . . . . . . . . . . . . . .84  
Moving Libraries After Linking with +s and SHLIB_PATH . . . . . . . .86  
Passing Linker Options in a file with -c . . . . . . . . . . . . . . . . . . . . . . . .86  
Passing Linker Options with LDOPTS . . . . . . . . . . . . . . . . . . . . . . . . .87  
Specifying Libraries with -l and l: . . . . . . . . . . . . . . . . . . . . . . . . . . . . .87  
Stripping Symbol Table Information from the Output File with -s and  
-x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .89  
Using 64-bit Mode Linker Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .90  
Using the 64-bit Mode Linker with +compat or +std . . . . . . . . . . . . . .90  
Linking Shared Libraries with -dynamic . . . . . . . . . . . . . . . . . . . . . . .93  
Linking Archived Libraries with -noshared . . . . . . . . . . . . . . . . . . . . .93  
Controlling Archive Library Loading with +[no]forceload . . . . . . . . . .93  
Flagging Unsatisfied Symbols with +[no]allowunsats . . . . . . . . . . . . .94  
Hiding Symbols from export with +hideallsymbols . . . . . . . . . . . . . . .95  
Changing Mapfiles with -k and +nodefaultmap . . . . . . . . . . . . . . . . . .95  
Ignoring Dynamic Path Environment Variables with +noenvvar . . . .96  
Linking in 64-bit Mode with +std . . . . . . . . . . . . . . . . . . . . . . . . . . . . .96  
Linking in 32-bit Mode Style with +compat . . . . . . . . . . . . . . . . . . . . .96  
Controlling Output from the Unwind Table with +stripwind . . . . . . .96  
Selecting Verbose Output with +vtype . . . . . . . . . . . . . . . . . . . . . . . . .97  
Linking with the 64-bit crt0.o Startup File . . . . . . . . . . . . . . . . . . . . .98  
Linker Compatibility Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .99  
Linking to Archive Libraries with Unsatisfied Symbols . . . . . . . . . .100  
7
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
4. Lin k er Tools  
Changing a Program's Attributes with chatr(1). . . . . . . . . . . . . . . . . . 104  
Using chatr for 32-bit Program Attributes . . . . . . . . . . . . . . . . . . . . 104  
Using chatr for 64-bit Program Attributes . . . . . . . . . . . . . . . . . . . . 105  
Viewing Symbols in an Object file with nm(1) . . . . . . . . . . . . . . . . . . . 107  
Viewing the Contents of an Object File with elfdump(1). . . . . . . . . . . 111  
Viewing library dependencies with ldd(1). . . . . . . . . . . . . . . . . . . . . . . 113  
Viewing the Size of Object File Elements with size(1). . . . . . . . . . . . . 115  
Reducing Storage Space with strip(1) . . . . . . . . . . . . . . . . . . . . . . . . . . 116  
Improving Program Start-up with fastbind(1) . . . . . . . . . . . . . . . . . . . 118  
Finding Object Library Ordering Relationships with lorder(1). . . . . . 120  
5. Cr ea tin g a n d Usin g Libr a r ies  
Overview of Shared and Archive Libraries. . . . . . . . . . . . . . . . . . . . . . 122  
What are Archive Libraries? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125  
Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 125  
What are Shared Libraries? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126  
The Dynamic Loader dld.sl. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126  
Default Behavior When Searching for Libraries at Run Time. . . . . 127  
Caution on Using Dynamic Library Searching . . . . . . . . . . . . . . . . . 127  
Example Program Comparing Shared and Archive Libraries. . . . . . . 128  
Shared Libraries with Debuggers, Profilers, and Static Analysis . . . . 130  
Creating Archive Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 131  
Overview of Creating an Archive Library . . . . . . . . . . . . . . . . . . . . . 131  
Contents of an Archive File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132  
Example of Creating an Archive Library. . . . . . . . . . . . . . . . . . . . . . 133  
Replacing, Adding, and Deleting an Object Module . . . . . . . . . . . . . 134  
8
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
Summary of Keys to the ar(1) Command . . . . . . . . . . . . . . . . . . . . . .135  
crt0.o . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136  
Archive Library Location . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .136  
Creating Shared Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .138  
Creating Position-Independent Code (PIC). . . . . . . . . . . . . . . . . . . . .138  
Creating the Shared Library with ld. . . . . . . . . . . . . . . . . . . . . . . . . .139  
Shared Library Dependencies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .140  
Updating a Shared Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .144  
Shared Library Location . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .144  
Improving Shared Library Performance . . . . . . . . . . . . . . . . . . . . . . .145  
Version Control with Shared Libraries . . . . . . . . . . . . . . . . . . . . . . . . .149  
When to Use Shared Library Versioning . . . . . . . . . . . . . . . . . . . . . .149  
Maintaining Old Versions of Library Modules . . . . . . . . . . . . . . . . . .150  
Library-Level Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .150  
Intra-Library Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .154  
Switching from Archive to Shared Libraries . . . . . . . . . . . . . . . . . . . . .158  
Library Path Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .158  
Relying on Undocumented Linker Behavior . . . . . . . . . . . . . . . . . . . .158  
Absolute Virtual Addresses . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .159  
Stack Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .160  
Version Control . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .160  
Debugger Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161  
Using the chroot Command with Shared Libraries . . . . . . . . . . . . . .161  
Profiling Limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .161  
Summary of HP-UX Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .162  
Caution When Mixing Shared and Archive Libraries . . . . . . . . . . . . . .164  
Example 1: Unsatisfied Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . .164  
Example 2: Using shl_load(3X) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .167  
Example 3: Hidden Definitions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .171  
Summary of Mixing Shared and Archive Libraries . . . . . . . . . . . . . .175  
9
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
Using Shared Libraries in 64-bit mode. . . . . . . . . . . . . . . . . . . . . . . . . 176  
Internal Name Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176  
Dynamic Path Searching for Shared Libraries . . . . . . . . . . . . . . . . . 177  
Shared Library Symbol Binding Semantics . . . . . . . . . . . . . . . . . . . 178  
Mixed Mode Shared Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 184  
64-bit Mode Library Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186  
6. Sh a r ed Libr a r y Ma n a gem en t Rou tin es  
Shared Library Management Routine Summaries . . . . . . . . . . . . . . . 196  
The shl_load Routine Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196  
The dlopen Routines Summary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 197  
Related Files and Commands. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198  
Shared Library Header Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 199  
Using Shared Libraries with cc and ld Options . . . . . . . . . . . . . . . . . . 200  
Initializers for Shared Libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201  
Styles of Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 201  
32-bit Mode Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203  
64-bit Mode Initializers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210  
The shl_load Shared Library Management Routines . . . . . . . . . . . . . 215  
The shl_load and cxxshl_load Routines . . . . . . . . . . . . . . . . . . . . . . . 215  
The shl_findsym Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222  
The shl_get and shl_get_r Routines . . . . . . . . . . . . . . . . . . . . . . . . . . 226  
The shl_gethandle and shl_gethandle_r Routines . . . . . . . . . . . . . . 230  
The shl_definesym Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 231  
The shl_getsymbols Routine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232  
The shl_unload and cxxshl_unload Routines . . . . . . . . . . . . . . . . . . 238  
The dlopen Shared Library Management Routines . . . . . . . . . . . . . . . 240  
The dlopen Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240  
The dlerror Routine. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244  
10  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
The dlsym Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .245  
The dlget Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .248  
The dlmodinfo Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .249  
The dlgetname Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .252  
The dlclose Routine . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .253  
Dynamic Loader Compatibility Warnings . . . . . . . . . . . . . . . . . . . . . . .256  
Unsupported Shared Library Management Routines . . . . . . . . . . . .256  
Unsupported Shared Library Management Flags . . . . . . . . . . . . . . .256  
7. Position -In d ep en d en t Cod e  
What Is Relocatable Object Code? . . . . . . . . . . . . . . . . . . . . . . . . . . . . .260  
What is Absolute Object Code? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .261  
What Is Position-Independent Code? . . . . . . . . . . . . . . . . . . . . . . . . . . .262  
Generating Position-Independent Code . . . . . . . . . . . . . . . . . . . . . . . . .263  
For More Information: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .264  
PIC Requirements for Compilers and Assembly Code . . . . . . . . . . . .264  
Long Calls . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .265  
Long Branches and Switch Tables. . . . . . . . . . . . . . . . . . . . . . . . . . . .265  
Assigned GOTO Statements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .266  
Literal References . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .266  
Global and Static Variable References . . . . . . . . . . . . . . . . . . . . . . . .267  
Procedure Labels . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .267  
8. Wa ys to Im p r ove Per for m a n ce  
Linker Optimizations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .270  
Invoking Linker Optimizations from the Compile Line . . . . . . . . . . .270  
Incompatibilities with other Options . . . . . . . . . . . . . . . . . . . . . . . . .271  
Unused Procedure Elimination with +Oprocelim. . . . . . . . . . . . . . . .271  
Options to Improve TLB Hit Rates. . . . . . . . . . . . . . . . . . . . . . . . . . . . .273  
11  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
Profile-Based Optimization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274  
General Information about PBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274  
Using PBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 274  
When to Use PBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275  
How to Use PBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275  
Instrumenting (+I/-I). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277  
Profiling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279  
Optimizing Based on Profile Data (+P/-P) . . . . . . . . . . . . . . . . . . . . . 283  
Selecting an Optimization Level with PBO. . . . . . . . . . . . . . . . . . . . 285  
Using PBO to Optimize Shared Libraries . . . . . . . . . . . . . . . . . . . . . 286  
Using PBO with ld -r . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 287  
Restrictions and Limitations of PBO . . . . . . . . . . . . . . . . . . . . . . . . . 288  
Compatibility with 9.0 PBO . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 291  
Improving Shared Library Start-Up Time with fastbind . . . . . . . . . . 293  
Using fastbind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293  
Invoking the fastbind Tool . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 293  
Invoking fastbind from the Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . 294  
How to Tell if fastbind Information is Current . . . . . . . . . . . . . . . . . 294  
Removing fastbind Information from a File . . . . . . . . . . . . . . . . . . . 294  
Turning off fastbind at Run Time . . . . . . . . . . . . . . . . . . . . . . . . . . . 294  
For More Information: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 294  
A. Usin g Ma p files  
Controlling Mapfiles with the -k Option . . . . . . . . . . . . . . . . . . . . . . . . 296  
Mapfile Example: Using -k filename (without +nodefaultmap Option)  
. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 296  
Changing Mapfiles with -k filename and +nodefaultmap . . . . . . . . . . 298  
Mapfile Example: Using -k mapfile and +nodefaultmap . . . 298  
Simple Mapfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 300  
Default HP-UX Release 11.0 Mapfile . . . . . . . . . . . . . . . . . . . . . . . . . . 301  
12  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
Defining Syntax for Mapfile Directives . . . . . . . . . . . . . . . . . . . . . . . . .303  
Defining Mapfile Segment Declarations. . . . . . . . . . . . . . . . . . . . . . . . .304  
Segment Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .304  
Mapfile Segment Declaration Examples . . . . . . . . . . . . . . . . . . . . . . .306  
Defining Mapfile Section Mapping Directives . . . . . . . . . . . . . . . . . . . .307  
Internal Map Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .309  
Placement of Segments in an Executable . . . . . . . . . . . . . . . . . . . . . .309  
Mapping Input Sections to Segments . . . . . . . . . . . . . . . . . . . . . . . . .309  
Interaction between User-defined and Default Mapfile Directives . .312  
Mapfile Option Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .313  
Fatal Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .313  
Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .313  
Glossa r y . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 315  
In d ex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 325  
13  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Con ten ts  
14  
Download from Www.Somanuals.com. All Manuals Search And Download.  
P r efa ce  
This Guide covers the following topics:  
Chapter 1, What's New in Recent Releases,” lists new features added  
in recent releases.  
Chapter 2, What Happens When You Compile and Link a Program,”  
provides details on compiling and linking programs.  
Chapter 3, Linker Tasks,” lists many ways you can specify how you  
want your program linked.  
Chapter 4, Linker Tools,” list the tools available in the linker toolset.  
Chapter 5, Creating and Using Libraries,” discusses all aspects of  
both archive and shared libraries.  
Chapter 6, Shared Library Management Routines,” explains how to  
explicitly load libraries at run time using shared library management  
routines.  
Chapter 7, Position-Independent Code,” describes how to write  
position-independent assembly code.  
Chapter 8, Ways to Improve Performance,” discusses several ways to  
optimize your program.  
Appendix A, Using Mapfiles,” describes mapfiles.  
Glossary contains definitions of important terms in this manual.  
P r in tin g Histor y  
New editions of this manual will incorporate all material updated since  
the previous edition. The manual printing date and part number indicate  
its current edition. The printing date changes when a new edition is  
printed. The manual part number changes when extensive technical  
changes are incorporated.  
November 1997, Edition 1, part number B2355-90655. This manual  
supersedes HP-UX Linker and Libraries Users Guide part number  
B2355-90655. The main reason for this new edition is to document  
new functionality for the HP-UX 11.00 release:  
15  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Add the +eelinker option to export symbols.  
Add 64-bit linker toolset support for linker options.  
Add 64-bit mode linker tools and describe the enhancements to the  
32-bit mode toolset.  
Describe 32-bit and 64-bit mode behavior differences.  
Add 64-bit mode dynamic path searching mechanisms.  
Add 64-bit mode symbol binding semantics.  
Add the dl*shared library management routines for 64-bit mode  
support and describe enhancement to the shl_loadroutines for  
shared libraries.  
Add init/fini style initializers for 64-bit mode support for shared  
libraries.  
Add the BIND_BREADTH_FIRSTflag to the shl_loadroutine to  
control search path behavior.  
Add description of support for ELF object file format.  
April 1997, Edition 1, part number B2355-90654. This manual  
supersedes Programming on HP-UX part number B2355-90652. The  
main reason for this new edition is to document new functionality for  
the HP-UX 10.30 release:  
Announce linker thread-safe features for ld, dld.sl, crt0.o,  
and libdld.sl.  
Add the +pdsize linker option to set the virtual memory page size  
for program data.  
Add the +pisize linker option to set the virtual memory page size  
for program instructions.  
Add the +klinker option (see ld(1)) to only create an executable if  
no errors are found at link time.  
Add the chatr +koption to enable or disable kernel-assisted  
branch prediction.  
Add the chatr +pdsize and +pisize virtual memory page setting  
options.  
16  
Download from Www.Somanuals.com. All Manuals Search And Download.  
July 1996, Edition 1, part number B2355-90653. This manual  
supersedes Programming on HP-UX part number B2355-90652. The  
main reason for this new edition is to document new functionality for  
the HP-UX 10.20 release and to describe what's ahead in a future  
release of the linker toolset:  
Add a -B symbolicoption to help improve shared library  
performance.  
Introduce the fastbindtool to improve the start up time of  
programs that use shared libraries.  
Introduce the Linker and Libraries Online User Guide.  
Announce changes in PA-RISC hardware compatibility—PA-RISC  
1.1 systems, by default, generate PA-RISC 1.1 code; PA-RISC 2.0  
systems generate 2.0 code.  
Describe compatibility warnings generated by the linker and  
dynamic loader for HP 9000 architecture issues and linker toolset  
features that may change in a future release.  
Describe what's changing in a future release of the linker toolset.  
Add the +Ostaticpredictionoption to use with profile-based  
optimization.  
January 1995, Edition 1, part number B2355-90652. This manual  
supersedes Programming on HP-UX part number B2355-90026. The  
main reason for this new edition is to document new functionality for  
the HP-UX 10.0 release:  
Update path names to reflect the new System V Release 4 file  
system. Some of the changes are:  
Most files in /libare now in /usr/lib.  
Most optional products are in /opt. For example, HP C is in  
/opt/ansic, HP C is in /opt/CC, HP FORTRAN/9000 is in  
/opt/fortran, and HP/DDE is in /opt/langtools/dde.  
Caution against mixing shared and archive libraries.  
Describe a new library-level versioning scheme for shared  
libraries.  
Update the chapter on profile-based optimization.  
Describe changes in optimization levels 3 and 4.  
17  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Describe thread-safe interfaces shl_get_rand  
shl_gethandle_r.  
Add a new BIND_TOGETHERflag to the shl_loadroutine.  
Add a new chapter "Porting Applications to HP-UX."  
18  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
1
Wh a t's New in Recen t Relea ses  
This section contains information about recent releases of the HP-UX  
linker toolset:  
For This Release  
The HP-UX 11.00 linker toolset contains new features:  
If you use the 32-bit mode linker toolset, see the following items:  
PA-RISC Changes in Hardware Compatibility” updated in this  
chapter.  
Exporting Symbols with +ee” on page 81.  
Changes in Future Releases” updated in this chapter.  
If you use the 64-bit mode linker toolset, see the following items:  
PA-RISC Changes in Hardware Compatibility” updated in this  
chapter.  
64-bit Mode Linker Toolset Compatibility with De Facto Industry  
Standards” described in this chapter.  
64-bit Mode ELF Object File Format” described in this chapter.  
Dynamic Path Searching for Shared Libraries” on page 177  
describes differences in the run time searching of shared libraries.  
Shared Library Symbol Binding Semantics” on page 178 describes  
differences in shared library binding semantics.  
New 64-bit mode linker options, symbols, and features, described  
inNew Features for 64-bit Mode Linking” in this chapter.  
Unsupported 32-bit mode features, behavior, and linker options,  
described in 64-bit Mode Link-time Differences” and64-bit Mode  
Run Time Differences” in this chapter.  
64-bit Mode Initializers” on page 210 describes the init/fini support  
for 64-bit mode shared libraries.  
Chapter 1  
19  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
The dlopen Shared Library Management Routines” on page 240  
describes the dl*family of shared library management routines for  
64-bit mode.  
BIND_BREADTH_FIRST Modifier” on page 222 describes the flag  
added to the shl_loadroutine to modify search behavior.  
Changes in Future Releases” updated in this chapter.  
For Previous Releases  
The following items were added in the HP-UX 10.30 release:  
Linker Thread-Safe Features” on page 50.  
Options to Improve TLB Hit Rates” on page 273.  
The +klinker option (see ld(1)) to remove an executable if the link  
fails.  
The +kchatroption (see chatr(1)) to improve branch prediction on  
PA-RISC 2.0.  
The following items were added in the HP-UX 10.20 release:  
Improving Shared Library Performance with -B symbolic” on page  
60.  
Improving Shared Library Start-Up Time with fastbind” on page  
293.  
Online Help for Linker and Libraries” described in this chapter.  
PA-RISC Changes in Hardware Compatibility” described in this  
chapter.  
Linker Compatibility Warnings” on page 99.  
Dynamic Loader Compatibility Warnings” on page 256.  
The +Ostaticpredictionlinker option described in the ld(1) man  
page to use with profile-based optimization  
20  
Chapter1  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
PA-RISC Changes in Hardware Compatibility  
PA-RISC Ch a n ges in Ha r d w a r e  
Com p a tibility  
The HP-UX 10.20 release introduced HP 9000 systems based on the  
PA-RISC 2.0 architecture. Also, beginning with that release, HP  
compilers by default generate executable code for the PA-RISC  
architecture of the machine on which you are compiling.  
In previous releases, the compilers generated PA-RISC 1.0 code on all  
HP 9000 Series 800 servers and PA-RISC 1.1 code on Series 700  
workstations. HP compilers now by default generate PA-RISC 1.1 code  
on 1.1 systems and 2.0 code on 2.0 systems.  
Using the +DAportablecompiler option provides compatibility of code  
between PA-RISC 1.1 and 2.0 systems. Note that the HP-UX 10.10  
release is the last supported release for PA-RISC 1.0 systems, so code  
generated by the HP-UX 10.20 release of HP compilers is not supported  
on PA-RISC 1.0 systems.  
NOTE  
The +DA1.0option will be obsolete in a future release. You can achieve  
better performance on PA-RISC 1.1 and 2.0 systems by not using this  
option.  
PA-RISC 2.0 Com p a tibility  
The instruction set on PA-RISC 2.0 is a superset of the instruction set on  
PA-RISC 1.1. As a result, code generated for PA-RISC 1.1 systems will  
run on PA-RISC 2.0 systems. However, code generated for PA-RISC 2.0  
systems will not run on PA-RISC 1.1 or 1.0. The linker issues a hardware  
compatibility warning whenever it links in any PA-RISC 2.0 object files:  
/usr/ccs/bin/ld: (Warning) At least one PA 2.0 object file  
(sum.o) was detected. The linked output may not run on PA 1.x  
system.  
If you try to run a PA-RISC 2.0 program on a 1.1 system, you'll see a  
message like:  
$ a.out  
ksh: ./a.out: Executable file incompatible with hardware  
Chapter 1  
21  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
PA-RISC Changes in Hardware Compatibility  
In this example, the +DAportablecompiler option can be used to create  
code compatible for PA-RISC 1.1 and 2.0 systems.  
PA-RISC Ar ch itectu r es a n d Th eir System  
Mod els  
The HP 9000 PA-RISC (Precision Architecture Reduced Instruction Set  
Computing) Series 700/800 family of workstations and servers has  
evolved from three versions of PA-RISC:  
PA-RISC 1.0  
PA-RISC 1.1  
The original version of PA-RISC first introduced on  
Series 800 servers. The following Series are included:  
840, 825, 835/SE, 845/SE, 850, 855, 860, 865, 870/x00,  
822, 832, 842, 852, 890, 808, 815, 635, 645.  
The second version of PA-RISC first introduced on  
Series 700 workstations. Newer Series 800 systems  
also use this version of the architecture. The following  
Series are included: 700, 705, 710, 715, 720, 725, 730,  
735, 750, 755, B132L, B160L, B132L+, B180L, C100,  
C110, J 200, J 210, J 210XC, 742i, 742rt, 743i, 743rt,  
745i, 747i, 748i, 8x7, D (except Dx70, Dx80), E, F, G, H,  
I, K (except Kx50, Kx60, Kx70), T500, T520.  
PA-RISC 2.0  
The newest version of PA-RISC. The following Series  
are included: C160, C180, C180XP, C200, C240, J 280,  
J 282, J 2240, Dx70, Dx80, Kx50, Kx60, Kx70, T600,  
V2200.  
For More Information  
See your compiler online help or documentation for details on the +DA  
option.  
See the file /opt/langtools/lib/sched.modelsfor a complete  
list of model numbers and their architectures. Use the command  
modelto determine the model number of your system.  
22  
Chapter1  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
64-bit Mode Linker Toolset Compatibility with De Facto Industry Standards  
64-bit Mod e Lin k er Toolset  
Com p a tibility w ith De Fa cto In d u str y  
Sta n d a r d s  
The 64-bit mode linker and dynamic loader provide linking and loading  
behaviors found widely across the Unix industry, considered, with the  
SVR4 standards, to define the de facto industry standards. The following  
64-bit linker behavior is compliant with de facto industry standard:  
ELF object file format and libelf(3x) routines  
Dynamic path searching  
Library-level versioning  
dl*family of dynamic loading routines  
Breadth-first symbol searching  
The HP-UX 11.00 release maintains certain behaviors to make  
transition from 32-bit to 64-bit mode easier:  
Creation of default run-time path environment variable (RPATH) if no  
ld +bis seen on the link line, to improve transition from the 32-bit  
mode linker.  
ld +compatoption for compatibility with 32-bit linking and loading  
behavior.  
Chapter 1  
23  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
64-bit Mode ELF Object File Format  
64-bit Mod e ELF Object File For m a t  
Starting with HP-UX release 11.00, the 64-bit linker toolset supports the  
ELF (executable and linking format) object file format. The 64-bit linker  
toolset provides new tools to display and manipulate ELF files. The  
libelf(3x) library routines provide access to ELF files. The command  
elfdump(1) displays contents of an ELF file.  
The following options instruct the compiler to generate 64-bit ELF object  
code.  
Op tion  
Com p iler  
+DA2.0W  
+DD64  
C and aC++  
C
See the HP-UX Software Transition Toolkit (STK) at  
http://www.software.hp.com/STK/for more information on the  
structure of ELF object files.  
24  
Chapter1  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
New Features for 64-bit Mode Linking  
New Fea tu r es for 64-bit Mod e Lin k in g  
This section introduces new features of the 64-bit linker for HP-UX  
release 11.00.  
64-bit Mod e Lin k er Op tion s  
The ld(1) command supports the following new options in 64-bit mode:  
Op tion  
-dynamic  
Action  
Forces the linker to create a shared  
executable. The linker looks for shared  
libraries first and then archived libraries.  
This option is on by default when you  
compile in 64-bit mode.  
-noshared  
Forces the linker to create a fully bound  
archive program.  
-k filename  
Allows you to control the mapping of input  
section in the object file to segments in the  
output file.  
+[no]allowunsats  
+compat  
Instructs the linker how to report errors for  
output files with unsatisfied symbols.  
Instruct the linker to use 32-bit mode  
linking and dynamic loading behaviors.  
+[no]forceload  
Enables/disables forced loading of all the  
object files from archive libraries.  
a
a
+hideallsymbols  
+nodefaultmap  
Hides all symbols from being exported.  
Instructs the linker not to load the default  
a
mapfile. See the -koption.  
Chapter 1  
25  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
New Features for 64-bit Mode Linking  
Op tion  
Action  
+noenvvar  
Instructs the dynamic loader not to look at  
the LD_LIBRARY_PATHand SHLIB_PATH  
a
environment variables at runtime.  
+std  
Instructs the linker to use SVR4 compatible  
linking and loading behaviors. Default for  
a
64-bit mode.  
+stripunwind  
Instructs the linker not to output the  
unwind table.  
+vtype type  
Produces verbose output about selected link  
a
operations.  
a. The linker accepts but ignores this option in 32-bit mode. It  
creates an executable (a.out).  
64-bit Mod e Lin k er -d efin ed Sym bols  
The 64-bit linker reserves the following symbol names:  
Sym bol  
Defin ition  
__SYSTEM_ID  
Largest architecture revision level used by  
any compilation unit  
_FPU_STATUS  
_end  
Initial value of FPU status register  
Address of first byte following the end of the  
main programs data segment; identifies the  
beginning of the heap segment  
__TLS_SIZE  
Size of the Thread Local Storage segment  
required by the program  
__text_start  
_etext  
Beginning of the text segment  
End of the text segment  
__data_start  
Beginning of the data segment  
26  
Chapter1  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
New Features for 64-bit Mode Linking  
Sym bol  
_edata  
Defin ition  
End of initialized data  
__gp  
Global pointer value  
__init_start  
__init_end  
__fini_start  
__fini_end  
__unwind_start  
__unwind_end  
Beginning of the .init section  
End of the .init section  
Beginning of the .fini section  
End of the .fini section  
Beginning of the unwind table  
End of the unwind table  
NOTE  
The linker generates an error if a user application also defines these  
symbols.  
Chapter 1  
27  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
64-bit Mode Link-time Differences  
64-bit Mod e Lin k -tim e Differ en ces  
The 64-bit mode linker toolset does not support the following 32-bit mode  
features.  
Op tion or  
Descr ip tion  
Beh a vior  
-Aname  
-C n  
-S  
Specifies incremental loading. 64-bit applications  
must use shared libraries instead.  
Does parameter type checking. This option is  
unsupported.  
Generates an initial program loader header file.  
This option is unsupported.  
-T  
Save data and relocation information in temporary  
files to reduce virtual memory requirements during  
linking. This option is unsupported.  
-q, -Q, -n  
Generates an executable with file type  
DEMAND_MAGIC, EXEC_MAGIC, and SHARE_MAGIC  
respectively. These options have no effect and are  
ignored in 64-bit mode.  
-N  
Causes the data segment to be placed immediately  
after the text segment. This option is accepted but  
ignored in 64-bit mode. If this option is used  
because your application data segment is large,  
then the option is no longer needed in 64-bit mode.  
If this option is used because your program is used  
in an embedded system or other specialized  
application, consider using mapfile support with  
the -koption.  
+cg pathname Specifies pathname for compiling I-SOMs to SOMs.  
This option is unsupported.  
28  
Chapter1  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
64-bit Mode Link-time Differences  
Op tion or  
Beh a vior  
Descr ip tion  
+dpv  
Displays verbose messages regarding procedures  
which have been removed due to dead procedure  
elimination. Use the -vlinker option instead.  
Intra-library  
versioning  
Specified by using the HP_SHLIB_VERSIONpragma  
(C and aC++) or SHLIB_VERSIONdirective  
(Fortran90).  
In 32-bit mode, the linker lets you version your  
library by object files. 64-bit applications must use  
SVR4 library-level versioning instead.  
Duplicate code  
and data  
symbols  
Code and data cannot share the same namespace in  
64-bit mode. You should rename the conflicting  
symbols.  
All internal  
and  
These options are unsupported.  
undocumented  
linker options  
For more information, see the HP-UX Linker and Libraries Online User  
Guide (ld +help).  
Chapter 1  
29  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
64-bit Mode Run Time Differences  
64-bit Mod e Ru n Tim e Differ en ces  
Applications compiled and linked in 64-bit mode use a run-time dynamic  
loading model similar to other SVR4 systems. There are two main areas  
where program startup changes in 64-bit mode:  
Dynamic path searching for shared libraries.  
Symbol searching in dependent libraries.  
It is recommended that you use the standard SVR4 linking option  
(+std), which is on by default when linking 64-bit applications. There  
may be circumstances while you transition, that you need 32-bit  
compatible linking behavior. The 64-bit linker provides the +compat  
option to force the linker to use 32-bit linking and dynamic loading  
behavior.  
The following table summarizes the dynamic loader differences between  
32-bit and 64-bit mode:  
Lin k er a n d Loa d er  
F u n ction s  
32-bit Mod e Beh a vior  
64-bit Mod e Beh a vior  
+sand +bpath_list  
Ordering is significant.  
Ordering is insignificant by default.  
ordering  
Use +compatto enforce ordering.  
30  
Chapter1  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
64-bit Mode Run Time Differences  
Lin k er a n d Loa d er  
F u n ction s  
32-bit Mod e Beh a vior  
64-bit Mod e Beh a vior  
Symbol searching in  
dependent libraries  
Depth-first search order. Breadth-first search order.  
Use +compatto enforce depth first  
ordering.  
Run time path  
No run time  
LD_LIBRARY_PATHand  
environment variables  
environment variables  
by default.  
SHLIB_PATHare available.  
Use +noenvor +compatto turn off  
run-time path environment  
variables.  
If +sis specified, then  
SHLIB_PATHis  
available.  
+bpath_list and -L  
directories interaction  
-Ldirectories recorded  
as absolute paths in  
executables.  
-Ldirectories are not recorded in  
executables.  
Add all directories specified in -Lto  
+bpath_list.  
For more information on transition issues, see HP-UX 64-bit Porting and  
Transition Guide.  
Chapter 1  
31  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
Changes in Future Releases  
Ch a n ges in F u tu r e Relea ses  
The following changes are planned in future releases.  
Support of ELF 32 object file format  
A future release will support the ELF 32 object file format.  
Future of ld +compatoption  
The +compatlinker option and support of compatibility mode may  
be discontinued in a future release.  
Support of shl_loadshared library management routines  
A future release may discontinue support of the shl_loadfamily of  
shared library management routines.  
32  
Chapter1  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
Online Help for Linker and Libraries  
On lin e Help for Lin k er a n d Libr a r ies  
The Linker and Libraries Online User Guide is available for HP 9000  
Series 700 and 800 systems. The online help comes with HP C, HP C++,  
HP aC++, HP Fortran, HP Pascal, and HP Micro Focus COBOL/UX.  
Online help can be accessed from any X Window display device, or from  
the charhelp(1) character-mode help browser.  
Accessin g Help w ith ld +h elp  
To access the Linker and Libraries Online User Guide from the ld  
command line:  
ld +help  
Accessin g Help w ith th e HP CDE Fr on t Pa n el  
To access the Linker and Libraries Online User Guide if your HP  
compiler is installed on your system:  
1. Click on the?icon on the HP CDE front panel.  
2. The "Welcome to Help Manager" menu appears. Click on the HP  
Linker icon.  
Accessin g Help w ith th e d th elp view  
Com m a n d  
If your HP compiler is installed on another system or you are not  
running HP CDE, enter the following command from the system where  
your compiler is installed:  
/usr/dt/bin/dthelpview -h linker  
NOTE  
To make it easier to access, add the path /usr/dt/binto your  
.profileor .loginfile.  
Accessin g Help w ith th e ch a r h elp Com m a n d  
To access the Linker and Libraries Online User Guide from a  
character-mode terminal or terminal emulator:  
Chapter 1  
33  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What's New in Recent Releases  
Online Help for Linker and Libraries  
/opt/langtools/bin/charhelp ld  
See charhelp(1) for details.  
34  
Chapter1  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
2
Wh a t Ha p p en s Wh en You  
Com p ile a n d Lin k a P r ogr a m  
This chapter describes the process of compiling and linking a program.  
Compiling Programs on HP-UX: An Example” provides an overview  
of compiling on HP-UX.  
Looking inside” a Compiler” describes the process of creating an  
executable file in more detail.  
Linking Programs on HP-UXdescribes how ldcreates an  
executable file from one or more object files.  
Linking with Libraries” describes conventions for using libraries  
with ld.  
Running the Program” describes the process of loading and binding  
programs at run time.  
Linker Thread-Safe Featuresdescribes the thread-safe features.  
Chapter 2  
35  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Compiling Programs on HP-UX: An Example  
Com p ilin g P r ogr a m s on HP -UX:  
An Exa m p le  
To create an executable program, you compile a source file containing a  
main program. For example, to compile an ANSI C program named  
sumnum.c, shown below, use this command (-Aasays to compile in ANSI  
mode):  
$ cc -Aa sumnum.c  
The compiler displays status, warning, and error messages to standard  
error output (stderr). If no errors occur, the compiler creates an  
executable file named a.outin the current working directory. If your  
PATHenvironment variable includes the current working directory, you  
can run a.outas follows:  
$ a.out  
Enter a number: 4  
Sum 1 to 4: 10  
The process is essentially the same for all HP-UX compilers. For  
instance, to compile and run a similar FORTRAN program named  
sumnum.f:  
$ f77 sumnum.f  
Compile and link sumnum.f.  
...  
$ a.out  
...  
The compiler displays any messages here.  
Run the program.  
Output from the program is displayed here.  
Program source can also be divided among separate files. For example,  
sumnum.ccould be divided into two files: main.c, containing the main  
program, and func.c, containing the function sum_n. The command for  
compiling the two together is:  
$ cc -Aa main.c func.c  
main.c:  
func.c:  
Notice that ccdisplays the name of each source file it compiles. This way,  
if errors occur, you know where they occur.  
#include <stdio.h>  
/* contains standard I/O defs */  
int  
{
sum_n( int n )  
/* sum numbers from n to 1  
*/  
int sum = 0;  
for (; n >= 1; n--)  
/* running total; initially 0 */  
/* sum from n to 1  
*/  
36  
Chapter2  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Compiling Programs on HP-UX: An Example  
sum += n;  
return sum;  
/* add n to sum  
/* return the value of sum  
*/  
*/  
}
main()  
{
/* begin main program  
*/  
int  
n;  
/* number to input from user */  
printf("Enter a number: ");  
scanf("%d", &n);  
/* prompt for number  
*/  
*/  
/* read the number into n  
printf("Sum 1 to %d: %d\\n", n, sum_n(n)); /* display the sum */  
}
Generally speaking, the compiler reads one or more source files, one of  
which contains a main program, and outputs an executable a.outfile,  
as shown in “High-Level View of the Compiler.  
Figu r e 2-1  
High -Level View of th e Com p iler  
Chapter 2  
37  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Looking inside” a Compiler  
Look in g “in sid e” a Com p iler  
On the surface, it appears as though an HP-UX compiler generates an  
a.outfile by itself. Actually, an HP-UX compiler is a d r iver that calls  
other commands to create the a.outfile. The driver performs different  
tasks (or p h a ses) for different languages, but two phases are common to  
all languages:  
1. For each source file, the driver calls the language compiler to create  
an object file. (See Also “What is an Object File?.)  
2. Then, the driver calls the HP-UX linker (ld) which builds an a.out  
file from the object files. This is known as the lin k -ed it p h a se of  
compilation. (See Also Compiler-Linker Interaction.)  
Looking inside” a Compiler” summarizes how a compiler driver works.  
Figu r e 2-2  
Look in g “in sid e” a Com p iler  
The C, C++, FORTRAN, and Pascal compilers provide the -v(verbose)  
option to display the phases a compiler is performing. Compiling main.c  
and func.cwith the -voption produced this output on a Series 700  
workstation (\at the end of a line indicates the line is continued to the  
next line):  
$ cc -Aa -v main.c func.c -lm  
cc: CCOPTS is not set.  
main.c:  
/opt/langtools/lbin/cpp.ansi main.c /var/tmp/ctmAAAa10102 \\  
-D__hp9000s700 -D__hp9000s800 -D__hppa -D__hpux \\  
-D__unix -D_PA_RISC1_1  
cc: Entering Preprocessor.  
/opt/ansic/lbin/ccom /var/tmp/ctmAAAa10102 main.o -O0 -Aa \\  
func.c:  
/opt/langtools/lbin/cpp.ansi func.c /var/tmp/ctmAAAa10102 \\  
-D__hp9000s700 -D__hp9000s800 -D__hppa -D__hpux \\  
38  
Chapter2  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Looking inside” a Compiler  
-D__unix -D_PA_RISC1_1  
cc: Entering Preprocessor.  
/opt/ansic/lbin/ccom /var/tmp/ctmAAAa10102 func.o -O0 -Aa  
cc: LPATH is /usr/lib/pa1.1:/usr/lib:/opt/langtools/lib:  
/usr/ccs/bin/ld /opt/langtools/lib/crt0.o -u main main.o func.o \\  
-lm -lc  
cc: Entering Link editor.  
This example shows that the ccdriver calls the C preprocessor  
(/opt/langtools/lbin/cpp.ansi) for each source file, then calls the  
actual C compiler (/opt/ansic/lbin/ccom) to create the object files.  
Finally, the driver calls the linker (/usr/ccs/bin/ld) on the object files  
created by the compiler (main.oand func.o).  
Chapter 2  
39  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
What is an Object File?  
Wh a t is a n Object File?  
An object file is basically a file containing machine language  
instructions and data in a form that the linker can use to create an  
executable program. Each routine or data item defined in an object file  
has a corresponding sym bol n a m e by which it is referenced. A symbol  
generated for a routine or data definition can be either a loca l  
d efin ition or globa l d efin ition . Any reference to a symbol outside the  
object file is known as an exter n a l r efer en ce.  
To keep track of where all the symbols and external references occur, an  
object file has a sym bol ta ble. The linker uses the symbol tables of all  
input object files to match up external references to global definitions.  
Loca l Defin ition s  
A local definition is a definition of a routine or data that is accessible only  
within the object file in which it is defined. Such a definition cannot be  
accessed from another object file. Local definitions are used primarily by  
debuggers, such as adb. More important for this discussion are global  
definitions and external references.  
Globa l Defin ition s  
A global definition is a definition of a procedure, function, or data item  
that can be accessed by code in another object file. For example, the C  
compiler generates global definitions for all variable and function  
definitions that are not static. The FORTRAN compiler generates  
global definitions for subroutines and common blocks. In Pascal, global  
definitions are generated for external procedures, external variables, and  
global data areas for each module.  
Exter n a l Refer en ces  
An external reference is an attempt by code in one object file to access a  
global definition in another object file. A compiler cannot resolve external  
references because it works on only one source file at a time. Therefore,  
the compiler simply places external references in an object file's symbol  
table; the matching of external references to global definitions is left to  
the linker or loader.  
40  
Chapter2  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Compiler-Linker Interaction  
Com p iler -Lin k er In ter a ction  
As described in Looking inside” a Compiler, the compilers  
automatically call ldto create an executable file. To see how the  
compilers call ld, run the compiler with the -v(verbose) option. For  
example, compiling a C program in 32-bit mode produces the output  
below:  
$ cc -Aa -v main.c func.c -lm  
cc: CCOPTS is not set.  
main.c:  
/opt/langtools/lbin/cpp.ansi main.c /var/tmp/ctmAAAa10102 \\  
-D__hp9000s700 -D__hp9000s800 -D__hppa -D__hpux \\  
-D__unix -D_PA_RISC1_1  
cc: Entering Preprocessor.  
/opt/ansic/lbin/ccom /var/tmp/ctmAAAa10102 main.o -O0 -Aa  
func.c:  
/opt/langtools/lbin/cpp.ansi func.c /var/tmp/ctmAAAa10102 \\  
-D__hp9000s700 -D__hp9000s800 -D__hppa -D__hpux \\  
-D__unix -D_PA_RISC1_1  
cc: Entering Preprocessor.  
/opt/ansic/lbin/ccom /var/tmp/ctmAAAa10102 func.o -O0 -Aa  
cc: LPATH is /usr/lib/pa1.1:/usr/lib:/opt/langtools/lib:  
/usr/ccs/bin/ld /opt/langtools/lib/crt0.o -u main main.o  
func.o -lm -lc  
cc: Entering Link editor.  
The next-to-last line in the above example is the command line the  
compiler used to invoke the 32-bit mode linker, /usr/ccs/bin/ld. In  
this command, ldcombines a sta r tu p file (crt0.o) and the two object  
files created by the compiler (main.oand func.o). Also, ldsearches the  
libmand libclibraries.  
In 64-bit mode, the startup functions are handled by the dynamic loader,  
dld.sl. In most cases, the ldcommand line does not include crt0.o.  
NOTE  
If you are linking any C++ object files to create an executable or a shared  
library, you must use the CCcommand to link. This ensures that  
c++patchexecutes and chains together your nonlocal static constructors  
and destructors. If you use ld, the library or executable may not work  
correctly and you may not get any error messages. For more information  
see the HP C++ Programmer's Guide.  
Chapter 2  
41  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Linking Programs on HP-UX  
Lin k in g P r ogr a m s on HP -UX  
The HP-UX linker, ld, produces a single executable file from one or more  
input object files and libraries. In doing so, it matches external  
references to global definitions contained in other object files or libraries.  
It revises code and data to reflect new addresses, a process known as  
r eloca tion . If the input files contain debugger information, ldupdates  
this information appropriately. The linker places the resulting  
executable code in a file named, by default, a.out.  
In the C program example (see Compiling Programs on HP-UX: An  
Example) main.ocontains an external reference to sum_n, which has a  
global definition in func.o. ldmatches the external reference to the  
global definition, allowing the main program code in a.outto access  
sum_n(see Figure 2-3).  
Figu r e 2-3  
Ma tch in g th e Exter n a l Refer en ce to su m _n  
If ldcannot match an external reference to a global definition, it  
displays a message to standard error output. If, for instance, you compile  
main.cwithout func.c, ldcannot match the external reference to  
sum_nand displays this output:  
$ cc -Aa main.c  
/usr/ccs/bin/ld: Unsatisfied symbols:  
sum_n (code)  
42  
Chapter2  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Linking Programs on HP-UX  
Th e cr t0.o Sta r tu p File  
Notice in the example in Compiler-Linker Interaction” that the first  
object file on the linker command line is  
/opt/langtools/lib/crt0.o, even though this file was not specified  
on the compiler command line. This file, known as a sta r tu p file,  
contains the program's en tr y p oin t that is, the location at which the  
program starts running after HP-UX loads it into memory to begin  
execution. The startup code does such things as retrieving command line  
arguments into the program at run time, and activating the dynamic  
loader (dld.sl(5)) to load any required shared libraries. In the C  
language, it also calls the routine _startin libcwhich, in turn, calls  
the main program as a function.  
The 64-bit linker uses the startup file,  
/opt/langtools/lib/pa_64/crt0.o, when:  
The linker is in compatibility mode (+compat).  
The linker is in default standard mode (+std) with the -noshared  
option.  
If the -pprofiling option is specified on the 32-bit mode compile line, the  
compilers link with mcrt0.o instead of crt0.o. If the -G profiling option is  
specified, the compilers link with gcrt0.o. In 64-bit mode with the -p  
option, the linker adds -lprofbefore the -lcoption. With the -G  
option, the linker adds -lgprof.  
If the linker option -Iis specified to create an executable file with  
profile-based optimization, in 32-bit mode icrt0.ois used, and in 64-bit  
mode the linker inserts /usr/ccs/lib/pa20_64/fdp_init.o. If the  
linker options -Iand -bare specified to create a shared library with  
profile-based optimization, in 32-bit mode scrt0.ois used, and in 64-bit  
mode, the linker inserts /usr/ccs/lib/pa20_64/fdp_init_sl.o. In  
64-bit mode, the linker uses the single 64-bit crt0.oto support these  
option.  
For details on startup files, see crt0(3).  
Th e P r ogr a m 's En tr y Poin t  
In 32-bit mode and in 64-bit statically-bound (-noshared) executables,  
the entry point is the location at which execution begins in the a.out  
file. The entry point is defined by the symbol $START$in crt0.o.  
Chapter 2  
43  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Linking Programs on HP-UX  
In 64-bit mode for dynamically bound executables, the entry point,  
defined by the symbol $START$in the dynamic loader (dld.sl).  
Th e a .ou t File  
The information contained in the resulting a.outfile depends on which  
architecture the file was created on and what options were used to link  
the program. In any case, an executable a.outfile contains information  
that HP-UX needs when loading and running the file, for example: Is it a  
shared executable? Does it reference shared libraries? Is it  
demand-loadable? Where do the code (text), data, and bss (uninitialized  
data) segments reside in the file? For details on the format of this file, see  
a.out(4).  
Ma gic Nu m ber s  
In 32-bit mode, the linker records a m a gic n u m ber with each  
executable program that determines how the program should be loaded.  
There are three possible values for an executable file's magic number:  
SHARE_MAGIC The program's text (code) can be shared by processes;  
its data cannot be shared. The first process to run the  
program loads the entire program into virtual memory.  
If the program is already loaded by another process,  
then a process shares the program text with the other  
process.  
DEMAND_MAGIC As with SHARE_MAGICthe program's text is shareable  
but its data is not. However, the program's text is  
loaded only as needed — that is, only as the pages are  
accessed. This can improve process startup time since  
the entire program does not need to be loaded; however,  
it can degrade performance throughout execution.  
EXEC_MAGIC  
Neither the program's text nor data is shareable. In  
other words, the program is an unshared executable.  
Usually, it is not desirable to create such unshared  
executables because they place greater demands on  
memory resources.  
By default, the linker creates executables whose magic number is  
SHARE_MAGIC. The following shows which linker option to use to  
specifically set the magic number.  
44  
Chapter2  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Linking Programs on HP-UX  
Ta ble 2-1  
32-bit Mod e Ma gic Nu m ber Lin k er Op tion s  
To set th e m a gic  
n u m ber to:  
Use th is  
op tion :  
SHARE_MAGIC  
DEMAND_MAGIC  
EXEC_MAGIC  
-n  
-q  
-N  
An executable file's magic number can also be changed using the chatr  
command (see Changing a Program's Attributes with chatr(1)” on page  
104). However, chatrcan only toggle between SHARE_MAGICand  
DEMAND_MAGIC; it cannot be used to change from or to EXEC_MAGIC.  
This is because the file format of SHARE_MAGICand DEMAND_MAGICis  
exactly the same, while EXEC_MAGICfiles have a different format. For  
details on magic numbers, refer to magic(4).  
In 64-bit mode, the linker sets the magic number to the predefined type  
for ELF object files (\177ELF). The value of the E_TYPEin the ELF  
object file specifies how the file should be loaded.  
File Per m ission s  
If no linker errors occur, the linker gives the a.outfile  
read/write/execute permissions to all users (owner, group, and other). If  
errors occurred, the linker gives read/write permissions to all users.  
Permissions are further modified if the u m a sk is set (see umask(1)). For  
example, on a system with umask set to 022, a successful link produces  
an a.outfile with read/write/execute permissions for the owner, and  
read/execute permissions for group and other:  
$ umask  
022  
$ ls -l a.out  
-rwxr-xr-x  
1 michael users  
74440 Apr 4 14:38 a.out  
Chapter 2  
45  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Linking with Libraries  
Lin k in g w ith Libr a r ies  
In addition to matching external references to global definitions in object  
files, ldmatches external references to global definitions in libraries. A  
libr a r y is a file containing object code for subroutines and data that can  
be used by other programs. For example, the standard C library, libc,  
contains object code for functions that can be used by C, C++, FORTRAN,  
and Pascal programs to do input, output, and other standard operations.  
Libr a r y Na m in g Con ven tion s  
By convention, library names have the form:  
libname.suffix  
name  
is a string of one or more characters that identifies the  
library.  
suffix  
is .aif the library is an archive library or .slif the  
library is a shared library. suffix is a number, for  
example .0, .1, and so forth, if library-level versioning  
is being used.  
Typically, library names are referred to without the suffix. For instance,  
the standard C library is referred to as libc.  
Defa u lt Libr a r ies  
A compiler driver automatically specifies certain default libraries when  
it invokes ld. For example, ccautomatically links in the standard  
library libc, as shown by the -lcoption to ldin this example:  
$ cc -Aa -v main.c func.c  
...  
/usr/ccs/bin/ld /opt/langtools/lib/crt0.o -u main main.o \  
func.o -lc  
cc: Entering Link editor.  
Similarly, the Series 700/800 FORTRAN compiler automatically links  
with the libcl(C interface), libisamstub(ISAM file I/O), and libc  
libraries:  
46  
Chapter2  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Linking with Libraries  
$ f77 -v sumnum.f  
...  
/usr/ccs/bin/ld -x /opt/langtools/lib/crt0.o \  
sumnum.o -lcl -lisamstub -lc  
Th e Defa u lt Libr a r y Sea r ch Pa th  
By default, ldsearches for libraries in the directory /usr/lib. (If the  
-por -Gcompiler profiling option is specified on the command line, the  
compiler directs the linker to also search /usr/lib/libp.) The default  
order can be overridden with the LPATHenvironment variable or the -L  
linker option. LPATHand -Lare described in Changing the Default  
Library Search Path with -L and LPATHon page 57.  
Lin k Or d er  
The linker searches libraries in the order in which they are specified on  
the command line — the lin k or d er . Link order is important in that a  
library containing an external reference to another library must precede  
the library containing the definition. This is why libcis typically the  
last library specified on the linker command line: because the other  
libraries preceding it in the link order often contain references to libc  
routines and so must precede it.  
NOTE  
If multiple definitions of a symbol occur in the specified libraries, lddoes  
not necessarily choose the first definition. It depends on whether the  
program is linked with archive libraries, shared libraries, or a  
combination of both. Depending on link order to resolve such library  
definition conflicts is risky because it relies on undocumented linker  
behavior that may change in future releases. (See Also Caution When  
Mixing Shared and Archive Libraries” on page 164.)  
Chapter 2  
47  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Running the Program  
Ru n n in g th e P r ogr a m  
An executable file is created after the program has been compiled and  
linked. The next step is to run or load the program.  
Loa d in g P r ogr a m s: exec  
When you run an executable file created by ld, the program is loaded  
into memory by the HP-UX program loader, exec. This routine is  
actually a system call and can be called by other programs to load a new  
program into the current process space. The execfunction performs  
many tasks; some of the more important ones are:  
Determine how to load the executable file by looking at its magic  
number. (See Also The a.out File.)  
Determine where to begin execution of the program — that is, the  
en tr y p oin t usually in crt0.o. (See Also The crt0.o Startup  
File.)  
When the program uses shared libraries, the crt0.ostartup code  
invokes the dynamic loader (dld.sl), which in turn attaches any  
required shared libraries. If immediate binding was specified at link  
time, then the libraries are bound immediately. If deferred binding  
was specified, then libraries are bound as they are referenced. (See  
Also What are Shared Libraries?” on page 126.)For details on exec,  
see the exec(2) page in the HP-UX Reference.  
Bin d in g Rou tin es to a P r ogr a m  
Since shared library routines and data are not actually contained in the  
a.outfile, the dynamic loader must a tta ch the routines and data to the  
program at run time. Attaching a shared library entails mapping the  
shared library code and data into the process's address space, relocating  
any pointers in the shared library data that depend on actual virtual  
addresses, allocating the bss segm en t, and bin d in g routines and data  
in the shared library to the program.  
The dynamic loader binds only those symbols that are reachable during  
the execution of the program. This is similar to how archive libraries are  
treated by the linker; namely, ldpulls in an object file from an archive  
library only if the object file is needed for program execution.  
48  
Chapter2  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Running the Program  
Defer r ed Bin d in g is th e Defa u lt  
To accelerate program startup time, routines in a shared library are not  
bound until referenced. (Data items are always bound at program  
startup.) This d efer r ed bin d in g of shared library routines distributes  
the overhead of binding across the execution time of the program and is  
especially expedient for programs that contain many references that are  
not likely to be executed. In essence, deferred binding is similar to  
d em a n d -loa d in g.  
Chapter 2  
49  
Download from Www.Somanuals.com. All Manuals Search And Download.  
What Happens When You Compile and Link a Program  
Linker Thread-Safe Features  
Lin k er Th r ea d -Sa fe Fea tu r es  
Beginning with the HP-UX 10.30 release, the dynamic loader (dld.sl)  
and its application interface library (libdld.sl) are thread-safe.  
Also, beginning with the HP-UX 10.30 release, the linker toolset provides  
thread local storage support in:  
ldthe link editor  
dld.slthe shared library dynamic loader  
crt0.othe program startup file  
Thread local storage (also called thread-specific data) is data specific to a  
thread. Each thread has its own copy of the data item.  
NOTE  
NOTE  
A program with thread local storage is only supported on systems  
running HP-UX 10.30 or later versions of the operating system.  
Use of the __threadkeyword in a shared library prevents that shared  
library from being dynamically loaded, that is, loaded by an explicit call  
to shl_load().  
For More Information:  
See your HP compiler documentation to learn how to create thread  
local storage data items with the _threadcompiler directive.  
See Programming with Threads on HP-UX for information on  
threads.  
50  
Chapter2  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
3
Lin k er Ta sk s  
You have a great deal of control over how the linker links your program  
or library by using ldcommand-line options.  
Using the Compiler Command  
Changing the Default Library Search Path with -Wl, -L”  
Getting Verbose Output with -v”  
Passing Linker Options from the Compiler Command with -Wl”  
Renaming the Output File with -o”  
Specifying Libraries with -l”  
Suppressing the Link-Edit Phase with -c”  
Using the Linker Command  
Linking with the 32-bit crt0.o Startup File”  
Changing the Default Library Search Path with -L and LPATH”  
Changing the Default Shared Library Binding with -B”  
Choosing Archive or Shared Libraries with -a”  
Dynamic Linking with -A and -R”  
Exporting Symbols with +e”  
Exporting Symbols from main with -E”  
Getting Verbose Output with -v”  
Hiding Symbols with -h”  
Improving Shared Library Performance with -B symbolic”  
Moving Libraries after Linking with +b”  
Moving Libraries After Linking with +s and SHLIB_PATH”  
Passing Linker Options from the Compiler Command with -Wl”  
Passing Linker Options in a file with -c”  
Passing Linker Options with LDOPTS”  
Chapter 3  
51  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Specifying Libraries with -l and l:”  
Stripping Symbol Table Information from the Output File with -s  
and -x”  
Using the 64-bit mode linker command  
Using the 64-bit Mode Linker with +compat or +std”  
Linking Shared Libraries with -dynamic”  
Linking Archived Libraries with -noshared”  
Controlling Archive Library Loading with +[no]forceload”  
Flagging Unsatisfied Symbols with +[no]allowunsats”  
Hiding Symbols from export with +hideallsymbols”  
Changing Mapfiles with -k and +nodefaultmap”  
Changing Mapfiles with -k and +nodefaultmap”  
Ignoring Dynamic Path Environment Variables with +noenvvar”  
Linking in 64-bit Mode with +std”  
Linking in 32-bit Mode Style with +compat”  
Controlling Output from the Unwind Table with +stripwind”  
Selecting Verbose Output with +vtype”  
Linking with the 64-bit crt0.o Startup File”  
Linker Compatibility Warnings  
52  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using the Compiler to Link  
Usin g th e Com p iler to Lin k  
In many cases, you use your compiler command to compile and link  
programs. Your compiler uses options that directly affect the linker.  
Ch a n gin g th e Defa u lt Libr a r y Sea r ch Pa th  
w ith -Wl, -L  
By default, the linker searches the directory /usr/liband  
/usr/ccs/libfor libraries specified with the -lcompiler option. (If the  
-por -Gcompiler option is specified, then the linker also searches the  
profiling library directory /usr/lib/libp.)  
The -Llibpath option to ldaugments the default search path; that is, it  
causes ldto search the specified libpath before the default places. The C  
compiler (cc), the C++ compiler (CC), the POSIX FORTRAN compiler  
(fort77), and the HP Fortran 90 compiler (f90) recognize the -Loption  
and pass it directly to ld. However, the HP FORTRAN compiler (f77)  
and Pascal compiler (pc) do not recognize -L; it must be passed to ld  
with the -Wloption.  
Exa m p le Usin g -Wl, -L  
For example, to make the f77compiler search /usr/local/libto find  
a locally developed library named liblocal, use this command line:  
$f77 prog.f -Wl,-L,/usr/local/lib -llocal  
(The f77compiler searches /opt/fortran/liband /usr/libas  
default directories.)  
To make the f90compiler search /usr/local/libto find a locally  
developed library named liblocal,, use this command line:  
$f90 prog.f90 -L/usr/local/lib -llocal  
(The f90compiler searches /opt/fortran90/liband /usr/libas  
default directories.)  
For the C compiler, use this command line:  
$ cc -Aa prog.c -L /usr/local/lib -llocal  
Chapter 3  
53  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using the Compiler to Link  
The LPATHenvironment variable provides another way to override the  
default search path. For details, see Changing the Default Library  
Search Path with -L and LPATH.  
Gettin g Ver bose Ou tp u t w ith -v  
The -voption makes a compiler display verbose information. This is  
useful for seeing how the compiler calls ld. For example, using the -v  
option with the Pascal compiler shows that it automatically links with  
libcl, libm, and libc.  
$ pc -v prog.p  
/opt/pascal/lbin/pascomp prog.p prog.o -O0  
LPATH = /usr/lib/pa1.1:/usr/lib:/opt/langtools/lib  
/usr/ccs/bin/ld /opt/langtools/lib/crt0.o -z prog.o -lcl -lm -lc  
unlink prog.o  
Pa ssin g Lin k er Op tion s fr om th e Com p iler  
Com m a n d w ith -Wl  
The -Wloption passes options and arguments to lddirectly, without the  
compiler interpreting the options. Its syntax is:  
-Wl,arg1 [,arg2]…  
where each argn is an option or argument passed to the linker. For  
example, to make lduse the archive version of a library instead of the  
shared, you must specify -a archiveon the ldcommand line before  
the library.  
Exa m p le Usin g -Wl  
The command for telling the linker to use an archive version of libm  
from the C command line is:  
$ cc -Aa mathprog.c -Wl,-a,archive,-lm,-a,default  
The command for telling the linker to use an archive version of libmis:  
$ ld /opt/langtools/lib/crt0.o mathprog.o -a archive -lm \  
-a default -lc  
54  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using the Compiler to Link  
Ren a m in g th e Ou tp u t File w ith -o  
The -oname option causes ldto name the output file name instead of  
a.out. For example, to compile a C program prog.cand name the  
resulting file sum_num:  
$ cc -Aa -o sum_num prog.c  
$ sum_num  
Enter a number to sum: 5  
The sum of 1 to 5: 15  
Compile using -o option.  
Run the program.  
Sp ecifyin g Libr a r ies w ith -l  
Sometimes programs call routines not contained in the default libraries.  
In such cases you must explicitly specify the necessary libraries on the  
compile line with the -loption. The compilers pass -loptions directly to  
the linker before the default libraries.  
For example, if a C program calls library routines in the curses library  
(libcurses), you must specify -lcurseson the cccommand line:  
$ cc -Aa -v cursesprog.c -lcurses  
...  
/usr/ccs/bin/ld /opt/langtools/lib/crt0.o -u main \  
cursesprog.o -lcurses -lc  
cc: Entering Link editor.  
Lin k in g w ith th e cr t0.o Sta r tu p File in 32-bit m od e  
Notice also, in the above example, that the compiler linked  
cursesprog.owith the file /opt/langtools/lib/crt0.o. This file  
contains object code that performs tasks which must be executed when a  
program starts running — for example, retrieving any arguments  
specified on the command line when the program is invoked. For details  
on this file, see crt0(3) and The crt0.o Startup File” on page 43.  
Su p p r essin g th e Lin k -Ed it P h a se w ith -c  
The -ccompiler option suppresses the link-edit phase. That is, the  
compiler generates only the .ofiles and not the a.outfile. This is useful  
when compiling source files that contain only subprograms and data.  
These may be linked later with other object files, or placed in an archive  
or shared library. The resulting object files can then be specified on the  
compiler command line, just like source files. For example:  
Chapter 3  
55  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using the Compiler to Link  
$ f77 -c func.f  
$ ls func.o  
func.o  
$ f77 main.f func.o  
$ a.out  
Produce .o for func.f.  
Verify that func.o was created.  
Compile main.f with func.o  
Run it to verify it worked.  
56  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Usin g Lin k er com m a n d s  
This section describes linker commands for the 32-bit and 64-bit linker.  
NOTE  
Unless otherwise noted, all examples show 32-bit behavior.  
Lin k in g w ith th e 32-bit cr t0.o Sta r tu p File  
In 32-bit mode, you must always include crt0.oon the link line.  
In 64-bit mode, you must include crt0.oon the link line for all fully  
archive links (ld -noshared) and in compatibility mode (+compat). You  
do not need to include the crt0.ostartup file on the ldcommand line  
for shared bound links. In 64-bit mode, the dynamic loader, dld.sl, does  
some of the startup duties previously done by crt0.o.  
See The crt0.o Startup File” on page 43, and the crt0(3) man page for  
more information.  
Ch a n gin g th e Defa u lt Libr a r y Sea r ch Pa th  
w ith -L a n d LPATH  
You can change or override the default linker search path by using the  
LPATHenvironment variable or the -Llinker option.  
Over r id in g th e Defa u lt Lin k er Sea r ch Pa th w ith  
LPATH  
The LPATHenvironment variable allows you to specify which directories  
ldshould search. If LPATHis not set, ldsearches the default directory  
/usr/lib. If LPATHis set, ldsearches only the directories specified in  
LPATH; the default directories are not searched unless they are specified  
in LPATH.  
If set, LPATHshould contain a list of colon-separated directory path  
names ldshould search. For example, to include /usr/local/libin  
the search path after the default directories, set LPATHas follows:  
$ LPATH=/usr/lib:/usr/local/lib  
$ export LPATH  
Korn and Bourne shell syntax.  
Chapter 3  
57  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Au gm en tin g th e Defa u lt Lin k er Sea r ch Pa th w ith -L  
The -Loption to ldalso allows you to add additional directories to the  
search path. If -Llibpath is specified, ldsearches the libpath directory  
before the default places.  
For example, suppose you have a locally developed version of libc,  
which resides in the directory /usr/local/lib. To make ldfind this  
version of libcbefore the default libc, use the -Loption as follows:  
$ ld /opt/langtools/lib/crt0.o prog.o -L /usr/local/lib -lc  
Multiple -Loptions can be specified. For example, to search  
/usr/contrib/liband /usr/local/libbefore the default places:  
$ ld /opt/langtools/lib/crt0.o prog.o -L /usr/contrib/lib \  
-L /usr/local/lib -lc  
If LPATHis set, then the -Loption specifies the directories to search  
before the directories specified in LPATH.  
Ch a n gin g th e Defa u lt Sh a r ed Libr a r y Bin d in g  
w ith -B  
You might want to force im m ed ia te bin d in g that is, force all  
routines and data to be bound at startup time. With immediate binding,  
the overhead of binding occurs only at program startup, rather than  
across the program's execution. One possibly useful characteristic of  
immediate binding is that it causes any possible unresolved symbols to  
be detected at startup time, rather than during program execution.  
Another use of immediate binding is to get better interactive  
performance, if you don't mind program startup taking a little longer.  
Exa m p le Usin g -B im m ed ia te  
To force immediate binding, link an application with the -B immediate  
linker option. For example, to force immediate binding of all symbols in  
the main program and in all shared libraries linked with it, you could  
use this ldcommand:  
$ ld -B immediate /opt/langtools/lib/crt0.o prog.o -lc -lm  
58  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Non fa ta l Sh a r ed Libr a r y Bin d in g w ith -B n on fa ta l  
The linker also supports n on fa ta l bin d in g, which is useful with the -B  
immediateoption. Like immediate binding, nonfatal immediate binding  
causes all required symbols to be bound at program startup. The main  
difference from immediate binding is that program execution continues  
even if the dynamic loader cannot resolve symbols. Compare this with  
immediate binding, where unresolved symbols cause the program to  
abort.  
To use nonfatal binding, specify the -B nonfataloption along with the  
-B immediateoption on the linker command line. The order of the  
options is not important, nor is the placement of the options on the line.  
For example, the following ldcommand uses nonfatal immediate  
binding:  
$ ld /opt/langtools/lib/crt0.o prog.o -B nonfatal \  
-B immediate -lm -lc  
Note that the -B nonfatalmodifier does not work with deferred  
binding because a symbol must have been bound by the time a program  
actually references or calls it. A program attempting to call or access a  
nonexistent symbol is a fatal error.  
Restr icted Sh a r ed Libr a r y Bin d in g w ith -B r estr icted  
The linker also supports r estr icted bin d in g, which is useful with the  
-B deferredand -B nonfataloptions. The -B restrictedoption  
causes the dynamic loader to restrict the search for symbols to those that  
were visible when the library was loaded. If the dynamic loader cannot  
find a symbol within the restricted set, a run-time symbol binding error  
occurs and the program aborts.  
The -B nonfatalmodifier alters this behavior slightly: If the dynamic  
loader cannot find a symbol in the restricted set, it looks in the global  
symbol set (the symbols defined in all libraries) to resolve the symbol. If  
it still cannot find the symbol, then a run-time symbol-binding error  
occurs and the program aborts.  
When is -B restrictedmost useful? Consider a program that creates  
duplicate symbol definitions by either of these methods:  
The program uses shl_loadwith the BIND_FIRSTflag to load a  
library that contains symbol definitions that are already defined in a  
library that was loaded at program startup.  
Chapter 3  
59  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
The program calls shl_definesymto define a symbol that is already  
defined in a library that was loaded at program startup.  
If such a program is linked with -B immediate, references to symbols  
will be bound at program startup, regardless of whether duplicate  
symbols are created later by shl_loador shl_definesym.  
But what happens when, to take advantage of the performance benefits  
of deferred binding, the same program is linked with -B deferred? If a  
duplicate, more visible symbol definition is created prior to referencing  
the symbol, it binds to the more visible definition, and the program  
might run incorrectly. In such cases, -B restrictedis useful, because  
symbols bind the same way as they do with -B immediate, but actual  
binding is still deferred.  
Im p r ovin g Sh a r ed Libr a r y Per for m a n ce w ith  
-B sym bolic  
The linker supports the -B symbolicoption which optimizes call paths  
between procedures when building shared libraries. It does this by  
building direct internal call paths inside a shared library. In linker  
terms, im p or t and exp or t stu bs are bypassed for calls within the  
library.  
A benefit of -B symbolicis that it can help improve application  
performance and the resulting shared library will be slightly smaller.  
The -B symbolicoption is useful for applications that make a lot of  
calls between procedures inside a shared library and when these same  
procedures are called by programs outside of the shared library.  
NOTE  
The -B symbolicoption applies only to function, but not variable,  
references in a shared library.  
Exa m p le Usin g -B sym bolic  
For example, to optimize the call path between procedures when building  
a shared library called lib1.sl, use -B symbolicas follows:  
$ ld -B symbolic -b func1.o func2.o -o lib1.sl  
60  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
NOTE  
The +eoption overrides the -B symbolicoption. For example, you use  
+esymbol, only symbol is exported and all other symbols are hidden.  
Similarly, if you use +eesymbol, only symbol is exported, but other  
symbols exported by default remain visible.  
Since all internal calls inside the shared library are resolved inside the  
shared library, user-supplied modules with the same name are not seen  
by routines inside the library. For example, you could not replace  
internal libc.sl malloc()calls with your own version of malloc()if  
libc.slwas linked with -B symbolic.  
Com p a r in g -B sym bolic w ith -h a n d +e  
Similar to the -h(hide symbol) and +e (export symbol) linker options, -B  
symbolic optimizes call paths in a shared library. However, unlike -hand  
+e, all functions in a shared library linked with -Bsymbolic are also  
visible outside of the shared library.  
Ca se 1: Bu ild in g a Sh a r ed Libr a r y w ith -B sym bolic.  
Suppose you have two functions to place in a shared library. The  
convert_rtn() calls gal_to_liter().  
1. Build the shared library with -b. Optimize the call path inside the  
shared library with -B symbolic.  
$ ld -B symbolic -b convert.o volume.o -o libunits.sl  
2. Two main programs link to the shared library. main1 calls  
convert_rtn() and main2 calls gal_to_liter().  
$ cc -Aa main1.c libunits.sl -o main1  
$ cc -Aa main1.c libunits.sl -o main2  
Figure 3-1 shows that a direct call path is established between  
convert_rtn() and gal_to_liter() inside the shared library. Both symbols  
are visible to outside callers.  
Chapter 3  
61  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Figu r e 3-1  
Sym bols in sid e a Sh a r ed Libr a r y Visible w ith -B sym bolic  
main1  
libunits.sl  
main () {  
convert_rtn();  
}
convert_rtn() {  
gal_to_liter();  
}
Direct call path  
main2  
Both convert_rtn and  
gal_to_liter symbols  
main () {  
gal_to_liter();  
gal_to_liter() { }  
are visible.  
}
Ca se 2: Bu ild in g a Sh a r ed Libr a r y w ith -h or +e. The -h(hide  
symbol) and +e(export symbol) options can also optimize the call path in  
a shared library for symbols that are explicitly hidden. However, only the  
exported symbols are visible outside of the shared library.  
For example, you could hide the gal_to_litersymbol as shown:  
$ ld -b convert.o -h gal_to_liter volume.o -o libunits.sl  
or export the convert_rtn symbol:  
$ ld -b +e convert_rtn convert.o volume.o -o libunits.sl  
62  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
In both cases, main2 will not be able to resolve its reference to  
gal_to_liter() because only the convert_rtn()symbol is exported as  
shown below:  
libunits.sl  
main1  
main () {  
convert_rtn ();  
convert_rtn() {  
gal_to_liter();  
}
}
Only convert_rtn  
symbol is  
main2  
visible.  
main () {  
gal_to_liter() { }  
gal_to_liter();  
}
Unsatisfied symbol: gal_to_liter (at link-time)  
Ch oosin g Ar ch ive or Sh a r ed Libr a r ies w ith -a  
If both an archive and shared version of a particular library reside in the  
same directory, ldlinks with the shared version. Occasionally, you might  
want to override this behavior.  
As an example, suppose you write an application that will run on a  
system on which shared libraries may not be present. Since the program  
could not run without the shared library, it would be best to link with the  
archive library, resulting in executable code that contains the required  
library routines. See also Caution When Mixing Shared and Archive  
Libraries” on page 164.  
Op tion Settin gs to -a  
The -aoption tells the linker what kind of library to link with. It applies  
to all libraries (-loptions) until the end of the command line or until the  
next -aoption. Its syntax is:  
-a {archive | shared | default | archive_shared | shared_archive}  
The different option settings are:  
Chapter 3  
63  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
-a archive  
-a shared  
Select archive libraries. If the archive  
library does not exist, ldgenerates  
an error message and does not  
generate the output file.  
Select shared libraries. If the shared  
library does not exist, ldgenerates  
an error message and does not  
generate the output file.  
-a default  
This is the same as -a  
shared_archive.  
-a archive_shared  
Select the archive library if it exists;  
otherwise, select the shared library. If  
the library cannot be found in either  
version, ldgenerates an error  
message and does not generate the  
output file.  
-a shared_archive  
Select the shared library if it exists;  
otherwise, select the archive library.  
If the library cannot be found in  
either version, ldgenerates an error  
message and does not generate the  
output file.  
The -a sharedand -a archiveoptions specify only one type of library  
to use. An error results if that type is not found. The other three options  
specify a preferred type of library and an alternate type of library if the  
preferred type is not found.  
CAUTION  
You should avoid mixing shared libraries and archive libraries in the  
same application. For more information see Caution When Mixing  
Shared and Archive Libraries” on page 164.  
Exa m p le Usin g -a  
The following command links with the archive versions of libcurses,  
libmand libc:  
$ ld /opt/langtools/lib/crt0.o prog.o -a archive -lcurses -lm -lc  
64  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Dyn a m ic Lin k in g w ith -A a n d -R  
This section describes how to do d yn a m ic lin k in g that is, how to add  
an object module to a running program. Conceptually, it is very similar to  
loading a shared library and accessing its symbols (routines and data).  
In fact, if you require such functionality, you should probably use shared  
library management routines (see Chapter 6, Shared Library  
Management Routines,” on page 195).  
However, be aware that dynamic linking is incompatible with shared  
libraries. That is, a running program cannot be linked to shared libraries  
and also use ld -Ato dynamically load object modules.  
NOTE  
Another reason to use shared library management routines instead of  
dynamic linking is that dynamic linking may not be supported in a  
future release. See Linker Compatibility Warnings” and Changes in  
Future Releases” on page 32for additional future changes.  
Topics in this section include:  
Overview of Dynamic Linking” describes steps to load an object file  
into a running program.  
An Example Program” provides an example dynamic linking  
scenario.  
Over view of Dyn a m ic Lin k in g  
The implementation details of dynamic linking vary across platforms. To  
load an object module into the address space of a running program, and  
to be able to access its procedures and data, follow these steps on all  
HP9000 computers:  
1. Determine how much space is required to load the module.  
2. Allocate the required memory and obtain its starting address.  
3. Link the module from the running application.  
4. Get information about the module's text, data, and bss segments from  
the module's header.  
5. Read the text and data into the allocated space.  
6. Clear (fill with zeros) the bss segment.  
7. Flush the text from the data cache before executing code from the  
loaded module.  
Chapter 3  
65  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
8. Get the addresses of routines and data that are referenced in the  
module.  
Step 1: Deter m in e h ow m u ch sp a ce is r equ ir ed to loa d th e  
m od u le. There must be enough contiguous memory to hold the  
module's text, data, and bss segments. You can make a liberal guess as to  
how much memory is needed, and hope that you've guessed correctly. Or  
you can be more precise by pre-linking the module and getting size  
information from its header.  
Step 2: Alloca te th e r equ ir ed m em or y a n d obta in its  
sta r tin g a d d r ess. Typically, you use malloc(3C) to allocate the  
required memory. You must modify the starting address returned by  
mallocto ensure that it starts on a memory page boundary (address  
MOD 4096 == 0).  
Step 3: Lin k th e m od u le fr om th e r u n n in g a p p lica tion . Use  
the following options when invoking the linker from the program:  
-omod_name  
Name of the output module that will be loaded by the  
running program.  
-Abase_prog  
Tells the linker to prepare the output file for  
incremental loading. Also causes the linker to include  
symbol table information from base_prog in the output  
file.  
-Rhex_addr  
-N  
Specifies the hexadecimal address at which the module  
will be loaded. This is the address calculated in Step 2.  
Causes the data segment to be placed immediately  
after the text segment.  
-eentry_pt  
If specified (it is optional), causes the symbol named  
entry_pt to be the entry point into the module. The  
location of the entry point is stored in the module's  
header.  
Step 4: Get in for m a tion a bou t th e m od u le's text, d a ta , a n d  
bss segm en ts fr om th e m od u le's h ea d er . There are two header  
structures stored at the start of the file: struct header(defined in  
<filehdr.h>) and struct som_exec_auxhdr(defined in  
<aouthdr.h>). The required information is stored in the second header,  
so to get it, a program must seek past the first header before reading the  
second one.  
66  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
The useful members of the som_exec_auxhdrstructure are:  
.exec_tsize Size of text (code) segment.  
.exec_tmem Address at which to load the text (already adjusted for  
offset specified by the -Rlinker option).  
.exec_tfile Offset into file (location) where text segment starts.  
.exec_dsize Size of data segment.  
.exec_dmem  
Address at which to load the data (already adjusted).  
.exec_dfile Offset into file (location) where data segment starts.  
.exec_bsize Size of bss segment. It is assumed to start immediately  
after the data segment.  
.exec_entry Address of entry point (if one was specified by the -e  
linker option).  
Step 5: Rea d th e text a n d d a ta in to th e a lloca ted sp a ce.  
Once you know the location of the required segments in the file, you can  
read them into the area allocated in Step 2.  
The location of the text and data segments in the file is defined by the  
.exec_tfileand .exec_dfilemembers of the som_exec_auxhdr  
structure. The address at which to place the segments in the allocated  
memory is defined by the .exec_tmemand .exec_dmemmembers. The  
size of the segments to read in is defined by the .exec_tsizeand  
.exec_dsizemembers.  
Step 6: Clea r (zer o ou t) th e bss segm en t. The bss segment  
starts immediately after the data segment. To zero out the bss, find the  
end of the data segment and use memset(see memory(3C)) to zero out  
the size of the bss.  
The end of the data segment can be determined by adding the  
.exec_dmemand .exec_dsizemembers of the som_exec_auxhdr  
structure. The bss's size is defined by the .exec_bsizemember.  
Step 7: F lu sh th e text fr om th e d a ta ca ch e befor e execu tin g  
cod e fr om th e loa d ed m od u le. Before executing code in the  
allocated space, a program should flush the instruction and data caches.  
Although this is really only necessary on systems that have instruction  
and data caches, it is easiest just to do it on all systems for ease of  
portability.  
Chapter 3  
67  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Use an assembly language routine named flush_cache(see The  
flush_cache Function” in this chapter). You must assemble this routine  
separately (with the ascommand) and link it with the main program.  
Step 8: Get th e a d d r esses of r ou tin es a n d d a ta th a t a r e  
r efer en ced in th e m od u le. If the -elinker option was used, the  
module's header will contain the address of the entry point. The entry  
point's address is stored in the .exec_entrymember of the  
som_exec_auxhdrstructure.  
If the module contains multiple routines and data that must be accessed  
from the main program, the main program can use the nlist(3C) function  
to get their addresses.  
Another approach that can be used is to have the entry point routine  
return the addresses of required routines and data.  
An Exa m p le P r ogr a m  
To illustrate dynamic linking concepts, this section presents an example  
program, dynprog. This program loads an object module named  
dynobj.o, which is created by dynamically linking two object files  
file1.oand file2.o(see le1.o and file2.o).  
The program allocates space for dynobj.oby calling a function named  
alloc_load_space(see The alloc_load_space Function” later in this  
chapter). The program then calls a function named dyn_loadto  
dynamically link and load dynobj.o(see The dyn_load Function” later  
in this chapter). Both functions are defined in a file called dynload.c  
(see dynload.c).  
As a return value, dyn_loadprovides the address of the entry point in  
dynobj.o— in this case, the function foo. To get the addresses of the  
function barand the variable counter, the program uses the nlist(3C)  
function.  
The Build Environment” shows the example makefile used to create  
the dynprogprogram.  
Source for dynprog” shows the C source code for the dynprog  
program.  
Output of dynprog” shows the run time output of the dynprog  
program.  
The flush_cache Function” provides example source code in assembly  
language to flush text from the data cache.  
68  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Th e Bu ild En vir on m en t. Before seeing the program's source code,  
it may help to see how the program and the various object files were  
built. The following shows the makefile used to generate the various  
files.  
Makele Used to Create Dynamic Link Files  
CFLAGS = -Aa -D_POSIX_SOURCE  
dynprog:  
dynprog.o dynload.o flush_cache.o  
# Compile line:  
cc -o dynprog dynprog.o dynload.o flush_cache.o -Wl,-a,archive  
file1.o:  
file2.o:  
file1.c dynprog.c  
file2.c  
# Create flush_cache.o:  
flush_cache.o:  
as flush_cache.s  
This makefile assumes that the following files are found in the current  
directory:  
dynload.c  
The file containing the alloc_load_spaceand  
dyn_loadfunctions.  
dynprog.c  
The main program that calls functions from  
dynload.cand dynamically links and loads file1.o  
and file2.o. Also contains the function glorp, which  
is called by fooand bar.  
file1.c  
file2.c  
Contains the functions fooand bar.  
Contains the variable counter, which is incremented  
by foo, bar, and main.  
flush_cache.s  
Assembly language source for function flush_cache,  
which is called by the dyn_loadfunction.  
To create the executable program dynprogfrom this makefile, you would  
simply run:  
$ make dynprog file1.o file2.o  
cc -Aa -D_POSIX_SOURCE -c dynprog.c  
cc -Aa -D_POSIX_SOURCE -c dynload.c  
cc -o dynprog dynprog.o dynload.o -Wl,-a,archive  
cc -Aa -D_POSIX_SOURCE -c file1.c  
cc -Aa -D_POSIX_SOURCE -c file2.c  
as -o flush_cache flush_cache.s  
Chapter 3  
69  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Note that the line CFLAGS =causes any C files to be compiled in ANSI  
mode (-Aa) and causes the compiler to search for routines that are  
defined in the Posix standard (-D_POSIX_SOURCE).  
For details on using makerefer to make(1).  
Sou r ce for d yn p r og. Here is the source file for the dynprog  
program.  
dynprog.c — Example Dynamic Link and Load Program  
#include <stdio.h>  
#include <nlist.h>  
extern void * alloc_load_space(const char * base_prog,  
const char * obj_files,  
const char * dest_file);  
extern void * dyn_load(const char * base_prog,  
unsigned int addr,  
const char * obj_files,  
const char * dest_file,  
const char * entry_pt);  
const char * base_prog = “dynprog”;  
*/  
/* this executable’s name  
const char * obj_files = “file1.o file2.o”; /* .o files to combine  
*/  
const char * dest_file = “dynobj.o”;  
/* .o file to load  
*/  
const char * entry_pt = “foo”;  
*/  
/* define entry pt name  
void glorp (const char *); /* prototype for local  
function  
*/  
void (* foo_ptr) ();  
/* pointer to entry point foo  
/* pointer to function bar  
*/  
void (* bar_ptr) ();  
*/  
int * counter_ptr;  
/* pointer to variable counter [file2.c]  
*/  
main()  
{
unsigned int addr;  
struct nlist nl[3];  
/* address at which to load dynobj.o */  
/* nlist struct to retrieve addresse */  
/*  
STEP 1: Allocate space for module:  
*/  
addr = (unsigned int) alloc_load_space(base_prog,  
obj_files, dest_file);  
/*  
STEP 2: Load the file at the address, and get address of entry  
point:  
*/  
70  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
foo_ptr = (void (*)()) dyn_load(base_prog, addr, obj_files,  
dest_file, entry_pt);  
/*  
STEP 3: Get the addresses of all desired routines using  
nlist(3C):  
*/  
nl[0].n_name = “bar”;  
nl[1].n_name = “counter”;  
nl[2].n_name = NULL;  
if (nlist(dest_file, nl)) {  
fprintf(stderr, “error obtaining namelist for %s\n”,  
dest_file);  
exit(1);  
}
/*  
* Assign the addresses to meaningful variable names:  
*/  
bar_ptr = (void (*)()) nl[0].n_value;  
counter_ptr = (int *) nl[1].n_value;  
/*  
* Now you can call the routines and modify the variables:  
*/  
glorp(“main”);  
(*foo_ptr) ();  
(*bar_ptr) ();  
(*counter_ptr) ++;  
printf(“counter = %d\n”, *counter_ptr);  
}
void  
{
glorp(const char * from)  
printf(“glorp called from %s\n”, from);  
}
file1.o a n d file2.o . Source for file1.c and file2.c” shows the source for  
file1.oand file2.o. Notice that fooand barcall glorpin  
dynprog.c. Also, both functions update the variable counterin  
file2.o; however, fooupdates counterthrough the pointer  
(counter_ptr) defined in dynprog.c.  
Source for file1.c and file2.c  
/****************************************************************  
* file1.c - Contains routines foo() and bar().  
****************************************************************/  
extern int * counter_ptr;  
extern int counter;  
/* defined in dynprog.c */  
/* defined in file2.c */  
extern void glorp(const char * from); /* defined in dynprog.c */  
void foo()  
{
Chapter 3  
71  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
glorp(“foo”);  
(*counter_ptr) ++; /* update counter indirectly with global  
pointer */  
}
void bar()  
{
glorp(“bar”);  
counter ++;  
/* update counter directly */  
}
/****************************************************************  
* file2.c - Global counter variable referenced by dynprog.c  
* and file1.c.  
****************************************************************/  
int counter = 0;  
Ou tp u t of d yn p r og . Now that you see how the main program and  
the module it loads are organized, here is the output produced when  
dynprogruns:  
glorp called from main  
glorp called from foo  
glorp called from bar  
counter = 3  
d yn loa d .c . The dynload.cfile contains the definitions of the  
functions alloc_load_spaceand dyn_load. “Include Directives for  
dynload.c” shows the #includedirectives must appear at the start of  
this file.  
Include Directives for dynload.c  
#include <stdio.h>  
#include <stdlib.h>  
#include <nlist.h>  
# include <filehdr.h>  
# include <aouthdr.h>  
# define PAGE_SIZE 4096  
/* memory page size */  
Th e a lloc_loa d _sp a ce F u n ction . The alloc_load_space  
function returns a pointer to space (allocated by malloc) into which  
dynprogwill load the object module dynobj.o. It syntax is:  
void * alloc_load_space(const char * base_prog,  
const char * obj_files,  
const char * dest_file)  
base_prog  
The name of the program that is calling the routine. In  
other words, the name of the program that will  
dynamically link and load dest_file.  
72  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
obj_files  
dest_file  
The name of the object file or files that will be linked  
together to create dest_file.  
The name of the resulting object module that will by  
dynamically linked and loaded by base_prog.  
As described in Step 1 in Overview of Dynamic Linking” at the start of  
this section, you can either guess at how much space will be required to  
load a module, or you can try to be more accurate. The advantage of the  
former approach is that it is much easier and probably adequate in most  
cases; the advantage of the latter is that it results in less memory  
fragmentation and could be a better approach if you have multiple  
modules to load throughout the course of program execution.  
The alloc_load_spacefunction allocates only the required amount of  
space. To determine how much memory is required, alloc_load_space  
performs these steps:  
1. Pre-link the specified obj_files to create base_prog.  
2. Get text, data, and bss segment location and size information to  
determine how much space to allocate.  
3. Return a pointer to the space. (The address of the space is adjusted to  
begin on a memory page boundary — that is, a 4096-byte boundary.)  
“C Source for alloc_load_space Function” shows the source for this  
function.  
C Source for alloc_load_space Function  
void * alloc_load_space(const char * base_prog,  
const char * obj_files,  
const char * dest_file)  
{
char cmd_buf[256];  
int ret_val;  
/* linker command line  
/* value returned by various lib calls */  
/* size of space to allocate for module */  
/* address of allocated space  
/* size of bss (uninitialized data)  
/* file pointer for dest_file  
*/  
size_t space;  
size_t addr;  
*/  
*/  
*/  
size_t bss_size;  
FILE * destfp;  
struct som_exec_auxhdr aux_hdr;  
/* file header  
*/  
unsigned int tdb_size; /* size of text, data, and bss combined */  
/* ---------------------------------------------------------------  
* STEP 1: Pre-link the destination module so we can get its size:  
*/  
sprintf(cmd_buf, “/bin/ld -a archive -R80000 -A %s -N %s -o %s -lc”,  
base_prog, obj_files, dest_file);  
if (ret_val = system(cmd_buf)) {  
Chapter 3  
73  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
fprintf(stderr, “link failed: %s\n”, cmd_buf);  
exit(ret_val);  
}
/* ---------------------------------------------------------------  
* STEP 2: Get the size of the module’s text, data, and bss segments  
* from the auxiliary header for dest_file; add them together to  
* determine size:  
*/  
if ((destfp = fopen(dest_file, “r”)) == NULL) {  
fprintf(stderr, “error opening %s\n”, dest_file);  
exit(1);  
}
/*  
* Must seek past SOM “header” to get to the desired  
* “som_exec_auxhdr”:  
*/  
if (fseek(destfp, sizeof(struct header), 0)) {  
fprintf(stderr, “error seeking past header in %s\n”, dest_file);  
exit(1);  
}
if (fread(&aux_hdr, sizeof(aux_hdr), 1, destfp) <= 0) {  
fprintf(stderr, “error reading som aux header from %s\n”, dest_file);  
exit(1);  
}
/* allow for page-alignment of data segment */  
space = aux_hdr.exec_tsize + aux_hdr.exec_dsize  
+ aux_hdr.exec_bsize + 2 * PAGE_SIZE;  
fclose(destfp);  
/* done reading from module file */  
/* ---------------------------------------------------------------  
* STEP 3: Call malloc(3C) to allocate the required memory and get  
* its address; then return a pointer to the space:  
*/  
addr = (size_t) malloc(space);  
/*  
* Make sure allocated area is on page-aligned address:  
*/  
if (addr % PAGE_SIZE != 0) addr += PAGE_SIZE - (addr % PAGE_SIZE);  
return((void *) addr);  
}
Th e d yn _loa d F u n ction . The dyn_loadfunction dynamically links  
and loads an object module into the space allocated by the  
alloc_load_spacefunction. In addition, it returns the address of the  
entry point in the loaded module. Its syntax is:  
void * dyn_load(const char * base_prog,  
unsigned int addr,  
const char * obj_files,  
const char * dest_file,  
const char * entry_pt)  
74  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
The base_prog, obj_files, and dest_file parameters are the same  
parameters supplied to alloc_load_space. The addr parameter is the  
address returned by alloc_load_space, and the entry_pt parameter  
specifies a symbol name that you want to act as the entry point in the  
module.  
To dynamically link and load dest_file into base_prog, the dyn_load  
function performs these steps:  
1. Dynamically link base_prog with obj_files, producing dest_file. The  
address at which dest_file will be loaded into memory is specified with  
the -Raddr option. The name of the entry point for the file is  
specified with -eentry_pt.  
2. Open dest_file and get its header information on the text, data, and  
bss segments. Read this information into a som_exec_auxhdr  
structure, which starts immediately after a headerstructure.  
3. Read the text and data segments into the area allocated by  
alloc_load_space. (The text and data segments are read  
separately.)  
4. Initialize (fill with zeros) the bss, which starts immediately after the  
data segment.  
5. Flush text from the data cache before execution, using the  
flush_cacheroutine. (See The flush_cache Function” later in this  
chapter.)  
6. Return a pointer to the entry point, specified by the -eoption in Step  
1.  
C Source for dyn_load Function  
void * dyn_load(const char * base_prog,  
unsigned int addr,  
const char * obj_files,  
const char * dest_file,  
const char * entry_pt)  
{
char cmd_buf[256];  
*/  
/* buffer holding linker command  
/* holds return value of library calls  
/* file pointer for destination file  
int ret_val;  
*/  
*/  
*/  
FILE * destfp;  
unsigned int bss_start; /* start address of bss in VM  
unsigned int bss_size;  
/* size of bss  
*/  
unsigned int entry_pt_addr; /* address of entry point  
Chapter 3  
75  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
*/  
struct som_exec_auxhdr aux_hdr; /* som file auxiliary header  
*/  
unsigned int tdb_size;  
combined*/  
/* size of text, data, and bss  
/*  
-----------------------------------------------------------------  
* STEP 1: Dynamically link the module to be loaded:  
*/  
sprintf(cmd_buf,  
“/bin/ld -a archive -A %s -R %x -N %s -o %s -lc -e %s”,  
base_prog, addr, obj_files, dest_file, entry_pt);  
if (ret_val = system(cmd_buf))  
{
fprintf(stderr, “link command failed: %s\n”, cmd_buf);  
exit(ret_val);  
}
/*  
-----------------------------------------------------------------  
* STEP 2: Open dest_file. Read its auxiliary header for text,  
data,  
*
and bss info:  
*/  
if ((destfp = fopen(dest_file, “r”)) == NULL)  
{
fprintf(stderr, “error opening %s for loading\n”, dest_file);  
exit(1);  
}
/*  
* Get auxiliary header information from “som_exec_auxhdr”  
struct,  
* which is after SOM header.  
*/  
if (fseek(destfp, sizeof(struct header), 0))  
{
fprintf(stderr, “error seeking past header in %s\n”,  
dest_file);  
exit(1);  
}
if (fread(&aux_hdr, sizeof(aux_hdr), 1, destfp) <= 0)  
{
fprintf(stderr, “error reading som aux header from %s\n”,  
dest_file);  
exit(1);  
}
/*  
-----------------------------------------------------------------  
* STEP 3: Read the text and data segments into the buffer area:  
*/  
/*  
* Read text and data separately. First load the text:  
*/  
76  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
if (fseek(destfp, aux_hdr.exec_tfile, 0))  
{
fprintf(stderr, “error seeking start of text in %s\n”,  
dest_file);  
exit(1);  
}
if ((fread(aux_hdr.exec_tmem, aux_hdr.exec_tsize, 1, destfp)) <=  
0)  
{
fprintf(stderr, “error reading text from %s\n”, dest_file);  
exit(1);  
}
/*  
* Now load the data, if any:  
*/  
if (aux_hdr.exec_dsize) {  
if (fseek(destfp, aux_hdr.exec_dfile, 0))  
{
fprintf(stderr, “error seeking start of data in %s\n”,  
dest_file);  
exit(1);  
}
if ((fread(aux_hdr.exec_dmem, aux_hdr.exec_dsize, 1,  
destfp))<= 0)  
{
fprintf(stderr, “error reading data from %s\n”, dest_file);  
exit(1);  
}
}
fclose(destfp);  
/*  
/* done reading from module file */  
-----------------------------------------------------------------  
* STEP 4: Zero out the bss (uninitialized data segment):  
*/  
bss_start = aux_hdr.exec_dmem + aux_hdr.exec_dsize;  
bss_size = aux_hdr.exec_bsize;  
memset(bss_start, 0, bss_size);  
/*  
-----------------------------------------------------------------  
* STEP 5: Flush the text from the data cache before execution:  
*/  
/*  
* The flush_cache routine must know the exact size of the  
* text, data, and bss, computed as follows:  
*
Size = (Data Addr - Text Addr) + Data Size + BSS Size  
* where (Data Addr - Text Addr) = Text Size + alignment between  
*
Text and Data.  
*/  
tdb_size = (aux_hdr.exec_dmem - aux_hdr.exec_tmem) +  
aux_hdr.exec_dsize + aux_hdr.exec_bsize;  
flush_cache(addr, tdb_size);  
Chapter 3  
77  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
/*  
-----------------------------------------------------------------  
* STEP 6: Return a pointer to the entry point specified by -e:  
*/  
entry_pt_addr = (unsigned int) aux_hdr.exec_entry;  
return ((void *) entry_pt_addr);  
}
Th e flu sh _ca ch e F u n ction . Since there is no existing routine to  
flush text from the data cache before execution, you must create one.  
Below is the assembly language source for such a function.  
Assembly Language Source for flush_cache Function  
; flush_cache.s  
;
; Routine to flush and synchronize data and instruction caches  
; for dynamic loading  
;
; Copyright Hewlett-Packard Co. 1985,1991, 1995  
;
; All HP VARs and HP customers have a non-exclusive royalty-free  
; license to copy and use this flush_cashe() routine in source  
; code and/or object code.  
.code  
; flush_cache(addr, len) - executes FDC and FIC instructions for  
; every cache line in the text region given by starting addr and  
; len. When done, it executes a SYNC instruction and then enough  
; NOPs to assure the cache has been flushed.  
;
; Assumption: Cache line size is at least 16 bytes. Seven NOPs  
; is enough to assure cache has been flushed. This routine is  
; called to flush the cache for just-loaded dynamically linked  
; code which will be executed from SR5 (data) space.  
; %arg0=GR26, %arg1=GR25, %arg2=GR24, %arg3=GR23, %sr0=SR0.  
; loop1 flushes data cache. arg0 holds address. arg1 holds  
offset.  
; SR=0 means that SID of data area is used for fdc.  
; loop2 flushes inst cache. arg2 holds address. arg3 holds  
offset.  
; SR=sr0 means that SID of data area is used for fic.  
; fdc x(0,y) -> 0 means use SID of data area.  
; fic x(%sr0,y) -> SR0 means use SR0 SID (which is set to data  
area).  
.proc  
.callinfo  
.export flush_cache,entry  
flush_cache  
.enter  
ldsid  
mtsp  
ldo  
(0,%arg0),%r1  
%r1,%sr0  
; Extract SID (SR5) from address  
; SID -> SR0  
-1(%arg1),%arg1  
%arg0,%arg2  
; offset = length -1  
copy  
; Copy address from GR26 to GR24  
78  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
copy  
fdc  
%arg1,%arg3  
; Copy offset from GR25 to GR23  
; Flush data cache  
%arg1(0,%arg0)  
@SID.address+offset  
loop1  
addib,>,n  
-16,%arg1,loop1 ; Decrement offset by cache line  
size  
fdc  
%arg1(0,%arg0) ; Flush data cache  
@SID.address+offset  
; flush first word at addr, to handle arbitrary cache line  
boundary  
fdc  
sync  
0(0,%arg0)  
fic  
%arg3(%sr0,%arg2)  
; Flush inst cache  
@SID.address+offset  
loop2  
addib,>,n  
-16,%arg3,loop2 ; Decrement offset by cache line  
size  
fic  
%arg3(%sr0,%arg2) ; Flush inst cache  
@SID.address+offset  
; flush first word at addr, to handle arbitrary cache line  
boundary  
fic  
0(%sr0,%arg2)  
sync  
nop  
nop  
nop  
nop  
nop  
nop  
nop  
.leave  
.procend  
.end  
Exp or tin g Sym bols w ith +e  
The +eoption allow you to hide and export symbols. Exp or tin g a  
symbol makes the symbol a global definition, which can be accessed by  
any other object modules or libraries. The +eoption exports symbol and  
hides from export all other global symbols not specified with +e. In  
essence, -hand +eprovide two different ways to do the same thing.  
The syntax of the +eoption is:  
+esymbol  
Exa m p le Usin g +e  
Suppose you want to build a shared library from an object file that  
contains the following symbol definitions as displayed by the nm  
command:  
Chapter 3  
79  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
$ nm -p sem.o  
0000000000 U $global$  
1073741824 d $THIS_DATA$  
1073741864 b $THIS_BSS$  
0000000004 cS sem_val  
0000000000 T check_sem_val  
0000000036 T foo  
0000000000 U printf  
0000000088 T bar  
0000000140 T sem  
In this example, check_sem_val, foo, bar, and semare all global  
definitions. To create a shared library where check_sem_valis a  
hidden, local definition, you could use either of the following commands:  
$ ld -b -h check_sem_val sem.o  
$ ld -b +e foo +e bar +e sem sem.o  
One -h option.  
Three +e options.  
In contrast, suppose you want to export only the check_sem_val  
symbol. Either of the following commands would work:  
$ ld -b -h foo -h bar -h sem sem.o  
$ ld -b +e check_sem_val sem.o  
Three -h options.  
One +e option.  
Wh en to u se -h ver su s +e  
How do you decide whether to use -hor +e? In general, use -hif you  
simply want to hide a few symbols. And use +eif you want to export a  
few symbols and hide a large number of symbols.  
You should not combine -hand +eoptions on the same command line.  
For instance, suppose you specify +e sem. This would export the symbol  
semand hide all other symbols. Any additional -hoptions would be  
unnecessary. If both -hand +eare used on the same symbol, the -h  
overrides the +eoption.  
The linker command line could get quite lengthy and difficult to read if  
several such options were specified. And in fact, you could exceed the  
maximum HP-UX command line length if you specify too many options.  
To get around this, use ldlinker option files, described under Passing  
Linker Options in a file with -c. You can specify any number of -hor +e  
options in this file.  
You can use -hor +eoptions when building a shared library (with -b)  
and when linking to create an a.outfile. When combining .ofiles with  
-r, you can still use only the -hoption.  
80  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Exp or tin g Sym bols w ith +ee  
Like the +eoption, the +eeoption allows you to export symbols. Unlike  
the +eoption, the option does not alter the visibility of any other symbols  
in the file. It exports the specified symbol, and does not hide any of the  
symbols exported by default.  
Exp or tin g Sym bols fr om m a in w ith -E  
By default, the linker exports from a program only those symbols that  
were imported by a shared library. For example, if a shared executable's  
libraries do not reference the program's mainroutine, the linker does not  
include the mainsymbol in the a.outfile's export list. Normally, this is  
a problem only when a program calls shared library management  
routines (described inChapter 6, Shared Library Management  
Routines,” on page 195). To make the linker export all symbols from a  
program, invoke ldwith the -Eoption.  
The +eoption allows you to be more selective about which symbols are  
exported, resulting in better performance. For details on +e, see  
Exporting Symbols with +e.  
Hid in g Sym bols w ith -h  
The -hoption allows you to hide symbols. Hid in g a symbol makes the  
symbol a local definition, accessible only from the object module or  
library in which it is defined. Use -hif you simply want to hide a few  
symbols.  
You can use -hoption when building a shared library (with -b) and  
when linking to create an a.outfile. When combining .ofiles with -r,  
you can use the -hoption.  
The syntax of the -hoption is:  
-hsymbol  
The -hoption hides symbol. Any other global symbols remain exported  
unless hidden with -h.  
Exa m p le Usin g -h  
Suppose you want to build a shared library from an object file that  
contains the following symbol definitions as displayed by the nm  
command:  
Chapter 3  
81  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
$ nm -p sem.o  
0000000000 U $global$  
1073741824 d $THIS_DATA$  
1073741864 b $THIS_BSS$  
0000000004 cS sem_val  
0000000000 T check_sem_val  
0000000036 T foo  
0000000000 U printf  
0000000088 T bar  
0000000140 T sem  
In this example, check_sem_val, foo, bar, and semare all global  
definitions. To create a shared library where check_sem_valis a  
hidden, local definition, you could do the following:  
$ ld -b -h check_sem_val sem.o  
Tip s on Usin g -h  
You should not combine -hand +eoptions on the same command line.  
For instance, suppose you specify +e sem. This would export the symbol  
semand hide all other symbols. Any additional -hoptions would be  
unnecessary. If both -hand +eare used on the same symbol, the -h  
overrides the +eoption.  
The linker command line could get quite lengthy and difficult to read if  
several such options were specified. And in fact, you could exceed the  
maximum HP-UX command line length if you specify too many options.  
To get around this, use ldlinker option files, described under Passing  
Linker Options in a file with -c. You can specify any number of -hor +e  
options in this file.  
Hid in g a n d Exp or tin g Sym bols Wh en Bu ild in g a  
Sh a r ed Libr a r y  
When building a shared library, you might want to hide a symbol in the  
library for several reasons:  
It can improve performance because the dynamic loader does not have  
to bind hidden symbols. Since most symbols need not be exported  
from a shared library, hiding selected symbols can have a significant  
impact on performance.  
It ensures that the definition can only be accessed by other routines  
in the same library. When linking with other object modules or  
libraries, the definition will be hidden from them.  
82  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
When linking with other libraries (to create an executable), it ensures  
that the library will use the local definition of a routine rather than a  
definition that occurs earlier in the link order.  
Exporting a symbol is necessary if the symbol must be accessible outside  
the shared library. But remember that, by default, most symbols are  
global definitions anyway, so it is seldom necessary to explicitly export  
symbols. In C, all functions and global variables that are not explicitly  
declared as statichave global definitions, while staticfunctions and  
variables have local definitions. In FORTRAN, global definitions are  
generated for all subroutines, functions, and initialized common blocks.  
When using +e, be sure to export any data symbols defined in the shared  
library that will be used by another shared library or the program, even  
if these other files have definitions of the data symbols. Otherwise, your  
shared library will use its own private copy of the global data, and  
another library or the program file will not see any change.  
One example of a data symbol that should almost always be exported  
from a shared library is errno. errnois defined in every shared library  
and program; if this definition is hidden, the value of errnowill not be  
shared outside of the library.  
Hid in g Sym bols Wh en Com bin in g .o Files w ith th e -r  
Op tion  
The -roption combines multiple .ofiles, creating a single .ofile. The  
reasons for hiding symbols in a .ofile are the same as the reasons listed  
above for shared libraries. However, a performance improvement will  
occur only if the resulting .ofile is later linked into a shared library.  
Hid in g a n d Exp or tin g Sym bols Wh en Cr ea tin g a n  
a .ou t File  
By default, the linker exports all of a program's global definitions that  
are imported by shared libraries specified on the linker command line.  
For example, given the following linker command, all global symbols in  
crt0.oand prog.othat are referenced by libmor libcare  
automatically exported:  
$ ld /usr/ccs/lib/crt0.o prog.o -lm -lc  
With libraries that are explicitly loaded with shl_load, this behavior  
may not always be sufficient because the linker does not search explicitly  
loaded libraries (they aren't even present on the command line). You can  
work around this using the -Eor +elinker option.  
Chapter 3  
83  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
As mentioned previously in the section Exporting Symbols from main  
with -E, the -Eoption forces the export of all symbols from the program,  
regardless of whether they are referenced by shared libraries on the  
linker command line. The +eoption allows you to be more selective in  
what symbols are exported. You can use +eto limit the exported symbols  
to only those symbols you want to be visible.  
For example, the following ldcommand exports the symbols mainand  
foo. The symbol mainis referenced by libc. The symbol foois  
referenced at run time by an explicitly loaded library not specified at link  
time:  
$ ld /usr/ccs/lib/crt0.o prog.o +e main +e foo -lm -lc -ldld  
When using +e, be sure to export any data symbols defined in the  
program that may also be defined in explicitly loaded libraries. If a data  
symbol that a shared library imports is not exported from the program  
file, the program uses its own copy while the shared library uses a  
different copy if a definition exists outside the program file. In such  
cases, a shared library might update a global variable needed by the  
program, but the program would never see the change because it would  
be referencing its own copy.  
One example of a data symbol that should almost always be exported  
from a program is errno. errnois defined in every shared library and  
program; if this definition is hidden, the value of errnowill not be  
shared outside of the program in which it is hidden.  
Movin g Libr a r ies a fter Lin k in g w ith +b  
A library can be moved even after an application has been linked with it.  
This is done by providing the executable with a list of directories to  
search at run time for any required libraries. One way you can store a  
directory path list in the program is by using the +bpath_list linker  
option.  
Note that dynamic path list search works only for libraries specified with  
-lon the linker command line (for example, -lfoo). It won't work for  
libraries whose full path name is specified (for example,  
/usr/contrib/lib/libfoo.sl). However, it can be enabled for such  
libraries with the -loption to the chatrcommand (see Changing a  
Program's Attributes with chatr(1)” on page 104).  
84  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Sp ecifyin g a Pa th List w ith +b  
The syntax of the +boption is  
+b path_list  
where path_list is the list of directories you want the dynamic loader to  
search at run time. For example, the following linker command causes  
the path .:/app/lib::to be stored in the executable. At run time, the  
dynamic loader would search for libfoo.sl, libm.sl, and libc.slin  
the current working directory (.), the directory /app/lib, and lastly in  
the location in which the libraries were found at link time (::):  
$ ld /opt/langtools/lib/crt0.o +b .:/app/lib:: prog.o -lfoo \  
-lm -lc  
If path_list is only a single colon, the linker constructs a path list  
consisting of all the directories specified by -L, followed by all the  
directories specified by the LPATHenvironment variable. For instance,  
the following linker command records the path list as /app/lib:/tmp:  
$ LPATH=/tmp ; export LPATH  
$ ld /opt/langtools/lib/crt0.o +b : -L/app/lib prog.o -lfoo \  
-lm -lc  
Th e Pa th List  
Whether specified as a parameter to +bor set as the value of the  
SHLIB_PATHenvironment variable, the path list is simply one or more  
path names separated by colons (:), just like the syntax of the PATH  
environment variable. An optional colon can appear at the start and end  
of the list.  
Absolute and relative path names are allowed. Relative paths are  
searched relative to the program's current working directory at run time.  
Remember that a shared library's full path name is stored in the  
executable. When searching for a library in an absolute or relative path  
at run time, the dynamic loader uses only the basename of the library  
path name stored in the executable. For instance, if a program is linked  
with /usr/local/lib/libfoo.sl, and the directory path list contains  
/apps/lib:xyz, the dynamic loader searches for  
/apps/lib/libfoo.sl, then ./xyz/libfoo.sl.  
The full library path name stored in the executable is referred to as the  
default library path. To cause the dynamic loader to search for the  
library in the default location, use a null directory path (). When the  
loader comes to a null directory path, it uses the default shared library  
path stored in the executable. For instance, if the directory path list in  
Chapter 3  
85  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
the previous example were /apps/lib::xyz, the dynamic loader would  
search for /apps/lib/libfoo.sl, /usr/local/lib/libfoo.sl,  
then ./xyz/libfoo.sl.  
If the dynamic loader cannot find a required library in any of the  
directories specified in the path list, it searches for the library in the  
default location () recorded by the linker.  
Movin g Libr a r ies After Lin k in g w ith +s a n d  
SHLIB_PATH  
A library can be moved even after an application has been linked with it.  
Linking the program with +s, enables the program to use the path list  
defined by the SHLIB_PATHenvironment variable at run time.  
Sp ecifyin g a Pa th List w ith +s a n d SHLIB_PATH  
When a program is linked with +s, the dynamic loader will get the  
library path list from the SHLIB_PATHenvironment variable at run time.  
This is especially useful for application developers who don't know where  
the libraries will reside at run time. In such cases, they can have the user  
or an install script set SHLIB_PATHto the correct value.  
For Mor e In for m a tion :  
The Path List” provides additional details about the path list to  
SHLIB_PATH.  
Moving Libraries after Linking with +b” provides another way to  
move libraries.  
Pa ssin g Lin k er Op tion s in a file w ith -c  
The -cfile option causes the linker to read command line options from  
the specified file. This is useful if you have many -hor +eoptions to  
include on the ldcommand line, or if you have to link with numerous  
object files. For example, suppose you have over a hundred +eoptions  
that you need when building a shared library. You could place them in a  
file named eoptsand force the linker to read options from the file as  
follows:  
$ ld -o libmods.sl -b -c eopts mod*.o  
$ cat eopts  
+e foo  
+e bar  
Display the file.  
86  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
+e reverse_tree  
+e preorder_traversal  
+e shift_reduce_parse  
.
.
.
Note that the linker ignores lines in that option file that begin with a  
pound sign (#). You can use such lines as comment lines or to temporarily  
disable certain linker options in the file. For instance, the following  
linker option file for an application contains a disabled -Ooption:  
# Exporting only the "compress" symbol resulted  
# in better run-time performance:  
+e compress  
# When the program is debugged, remove the pound sign  
# from the following optimization option:  
# -O  
Pa ssin g Lin k er Op tion s w ith LDOP TS  
If you use certain linker options all the time, you may find it useful to  
specify them in the LDOPTSenvironment variable. The linker inserts the  
value of this variable before all other arguments on the linker command  
line. For instance, if you always want the linker to display verbose  
information (-v) and a trace of each input file (-t), set LDOPTSas  
follows:  
$ LDOPTS="-v -t" Korn and Bourne shell syntax.  
$ export LDOPTS  
Thereafter, the following commands would be equivalent:  
$ ld /opt/langtools/lib/crt0.o -u main prog.o -lc  
$ ld -v -t /opt/langtools/lib/crt0.o -u main prog.o -lc  
Sp ecifyin g Libr a r ies w ith -l a n d l:  
To direct the linker to search a particular library, use the -lname option.  
For example, to specify libc, use -lc; to specify libm, use -lm; to  
specify libXm, use -lXm.  
Sp ecifyin g Libr a r ies (-l)  
When writing programs that call routines not found in the default  
libraries linked at compile time, you must specify the libraries on the  
compiler command line with the -lx option. For example, if you write a C  
program that calls POSIX math functions, you must link with libm.  
Chapter 3  
87  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
The x argument corresponds to the identifying portion of the library path  
name — the part following liband preceding the suffix .aor .sl. For  
example, for the libm.slor libm.alibrary, x is the letter m:  
$ cc -Aa mathprog.c -lm  
The linker searches libraries in the order in which they are specified on  
the command line (that is, the lin k or d er ). In addition, libraries  
specified with -lare searched before the libraries that the compiler links  
by default.  
Usin g th e -l: op tion  
The -l:option works just like the -loption with one major difference:  
-l:allows you to specify the full basename of the library to link with.  
For instance, -l:libm.acauses the linker to link with the archive  
library /usr/lib/libm.a, regardless of whether -a sharedwas  
specified previously on the linker command line.  
The advantage of using this option is that it allows you to specify an  
archive or shared library explicitly without having to change the state of  
the -aoption. (See also Caution When Mixing Shared and Archive  
Libraries” on page 164.)  
For instance, suppose you use the LDOPTSenvironment variable (see  
Passing Linker Options with LDOPTS) to set the -aoption that you  
want to use by default when linking. And depending on what  
environment you are building an application for, you might set LDOPTS  
to -a archiveor -a shared. You can use -l:to ensure that the linker  
will always link with a particular library regardless of the setting of the  
-aoption in the LDOPTSvariable.  
Exa m p le Usin g -l:  
For example, even if LDOPTSwere set to -a shared, the following  
command would link with the archive libfoo.ain the directory  
/usr/mylibs, the archive libm.aand libc.a:  
$ ld /opt/langtools/lib/crt0.o -u main prog.o -L/usr/mylibs \  
-l:libfoo.a -l:libc.a -l:libm.a  
88  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using Linker commands  
Str ip p in g Sym bol Ta ble In for m a tion fr om th e  
Ou tp u t File w ith -s a n d -x  
The a.outfile created by the linker contains symbol table, relocation,  
and (if debug options were specified) information used by the debugger.  
Such information can be used by other commands that work on a.out  
files, but is not actually necessary to make the file run. ldprovides two  
command line options for removing such information and, thus, reducing  
the size of executables:  
-s  
Strips all such information from the file. The  
executable becomes smaller, but difficult or impossible  
to use with a symbolic debugger. You can get much the  
same results by running the stripcommand on an  
executable (see strip(1)). In some cases, however, -s  
rearranges the file to save more space than strip.  
-x  
Strips only local symbols from the symbol table. It  
reduces executable file size with only a minimal affect  
on commands that work with executables. However,  
using this option may still make the file unusable by a  
symbolic debugger.  
These options can reduce the size of executables dramatically. Note, also,  
that these options can also be used when generating shared libraries  
without affecting shareability.  
Chapter 3  
89  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
Usin g 64-bit Mod e Lin k er Op tion s  
This section introduces 64-bit-only linker options.  
Usin g th e 64-bit Mod e Lin k er w ith +com p a t or  
+std  
In the HP-UX 11.0 release, the linker toolset supports extended features  
for linking in 64-bit mode. Since compatibility with the previous linker  
toolset is a high priority, the 64-bit linker uses much of the old behavior  
in the new toolset. The 64-bit mode linker includes two options to allow  
you to instruct the linker to link in one of two modes:  
Compatibility mode, with the +compatoption, to create a link and  
operation in 32-bit style. Because of some object file format  
restrictions, the mode is not completely compatible with the style of  
the 32-bit linker.  
Standard mode, with the +stdoption, set by default in 64-bit mode,  
to create a link and load operation in 64-bit style. This mode uses the  
new behaviors and features of the 64-bit linker.  
Usin g th e Lin k er w ith +com p a t for Com p a tibility  
Mod e  
The +compat option instructs the linker to do a 32-bit-style link.  
When you use the +compatoption, the linker:  
Uses 32-bit style shared library internal name processing.  
Lists all dependent shared libraries in a DT_HP_NEEDED entry the  
dynamic table using the 32 bit-style shared library naming  
conventions. These dependent libraries are recorded as compatibility  
mode libraries even if they are really created as standard mode  
dependent libraries.  
If an error occurs during the link, the linker creates an a.out  
without the executable permission bits set.  
Does not use embedded paths at link time to find dependent  
libraries.  
Considers the order of ld +band +s.  
90  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
+bfirst means dld looks at the RPATHfirst when searching for  
dependent shared libraries.  
To get the default RPATH, you must specify ld +b. This instructs  
the linker to construct a default RPATHconsisting of the -L  
directories and LPATH.  
+sfirst means the dynamic loader looks at the SHLIB_PATH  
environment variable first when searching for dependent shared  
libraries.  
You must specify ld +sto force the dynamic loader to use  
SHLIB_PATHto search for shared libraries at runtime.  
At runtime, the dynamic loader does a 32-bit style load for all  
compatibility mode dependent shared libraries. The dynamic loader:  
Does dynamic path searching for compatibility-mode dependent  
shared libraries that have the dynamic path selected (set in the  
DT_HP_NEEDEDentry if the shared library was specified with -l).  
Uses SHLIB_PATHonly if you specify ld +s(or chatr +s) for  
compatibility-mode shared libraries.  
Allows RPATHinheritance from ancestors to children when searching  
for dependent compatibility-mode shared libraries specified with ld  
-l. This is only allowed in an a.outthat was linked with +compat.  
If the a.outwas linked +std, no library (even a compatibility mode  
shared library) uses embedded RPATHinheritance.  
Allows dynamic path searching on shared libraries loaded by  
shl_loadroutines, if the DYNAMIC_FLAGis passed to shl_load().  
Does a depth-first search of all compatibility-mode dependent  
libraries.  
Looks at RPATHor SHLIB_PATHfirst, depending on the ld +b/+s  
ordering for all ld -ldependent shared libraries. The dynamic  
loader looks at whichever has second precedence next, and then  
looks for the shared library as specified in the dynamic load entry.  
Looks for the dynamic table entry as if the dynamic path bit is not  
set.  
Usin g th e 64-bit Lin k er w ith +std for Sta n d a r d Mod e  
The +stdoption instructs the linker to do a standard mode 64-bit style  
link. This is currently the default in 64-bit mode.  
Chapter 3  
91  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
This default may change in future releases.  
When you use +std, the linker:  
Assumes -dynamicwas passed to ld. The linker looks for shared  
libraries first. The output executable is a shared executable.  
All dependent shared libraries are output in the dynamic table in a  
DT_NEEDEDentry. These dependent shared libraries are recorded as  
standard mode shared libraries.  
ld +band +sordering is ignored. ld +sis on by default.  
If an error occurs during the link, the linker does not generate an  
a.outfile.  
Uses de facto standard internal name processing for dependent  
shared libraries.  
Uses embedded RPATHs at link time to find dependent shared  
libraries.  
If you do not specify ld +b, the linker uses a default RPATHconsisting  
of the -Ldirectories, LPATH, and the default directories  
/usr/lib/pa20_64:/usr/ccs/lib/pa20_64.  
At runtime, the dynamic loader does a 64-bit-style load for all standard  
mode dependent shared libraries. The dynamic loader:  
Does dynamic path searching only for standard-mode shared libraries  
in the DT_NEEDEDentry of the dynamic table which do not contain a  
path. For those standard-mode dynamic libraries that contain paths,  
dldlooks for the library as specified.  
Looks for the shared library as specified in the DT_NEEDEDdynamic  
table entry if it contains a path.  
Looks at LD_LIBRARY_PATHand SHLIB_PATHenvironment variables  
at runtime by default when doing dynamic path searching for  
standard-mode shared libraries.  
Does not allow RPATHinheritance from ancestors to children (only  
allowed from parent to child).  
Does a breadth-first search for all standard-mode dependent shared  
libraries.  
92  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
Looks at the environment variables first, followed by RPATH, and the  
default directories by default when doing dynamic path searching for  
standard-mode dependentshared libraries.  
Lin k in g Sh a r ed Libr a r ies w ith -d yn a m ic  
Use the -dynamicoption to instruct the linker to look for shared  
libraries first and then archive libraries. The linker outputs a  
dynamically linked executable.  
This option is on by default in standard mode.  
In the following example, the linker only looks for shared libraries:  
$ld main.o -dynamic -L. -lbar -lc  
If you specified an archive library, the linker links it in, but the resulting  
executable is still a dynamically linked executable. This is true even if  
the linker finds no shared libraries at link time.  
Lin k in g Ar ch ived Libr a r ies w ith -n osh a r ed  
Use the -nosharedoption if you need to link with all archive libraries.  
The linker outputs a statically bound executable.  
NOTE  
You cannot link in shared libraries if you specify this option.  
In the following example, the linker only looks for  
/usr/lib/pa20_64/libfoo.aand /usr/lib/pa20_64/libc.a:  
ld crt0.o main.o -noshared -L. -lfoo -lc  
If you specify a shared library with this option, the linker emits an error  
message.  
ld: The shared library “libbar.sl” cannot be processed in a static  
link.  
Fatal error.  
Con tr ollin g Ar ch ive Libr a r y Loa d in g w ith  
+[n o]for celoa d  
Use the +[no]forceloadoption to control how the linker loads object  
files from an archived library. +forceloadinstructs the linker to load  
all object files from an archive library. +noforceloadtells the linker to  
Chapter 3  
93  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
only load those modules from an archive library that is needed. The  
mode you select, either by default or explicitly, remains on until you  
change it.  
+noforceloadis the default on both 32-bit and 64-bit modes.  
In the following example, main()references foo(), which is a module  
in mylib.a. foo()doesnt reference any other module in mylib.aand  
libc.a. If mylib.acontains foo.oand bar.o, then only foo.ois  
linked in.  
ld crt0.o main.o +vtype libraries mylib.a -lc  
...  
Selecting liba.a[foo.o] to resolve foo  
ld crt0.o main.o +forceload mylib.a -lc +vtype libraries  
...  
Selecting liba.a[foo.o] to forcibly load  
Selecting liba.a[bar.o] to forcibly load  
F la ggin g Un sa tisfied Sym bols w ith  
+[n o]a llow u n sa ts  
Use the +allowunsatsoption to instruct the linker to not flag  
unsatisfied symbols at link time. This is the default for relocatable (-r)  
and shared library builds (-b), and is the default behavior in 32-bit  
mode.  
Use the +noallowunsatoption to instruct the linker to flag as an error  
any unsatisfied symbol in the resulting output file. The linker still  
creates a.out, but the file does not have any execute permission bits set.  
This is the default for program files (same behavior as in 32-bit mode).  
For example, where main()references functions foo()and bar().  
bar()resides in libbar.sl. foo()resides in libfoo.sl  
ld main.o +allowunsats -L. -lbar -lc  
ld: (warning) Unsatisfied symbol “foo”.  
1 warning.  
+allowunsatsstill causes the linker to emit a warning message and  
output a.out. If you do not specify the option and the linker finds an  
unsatisfied symbol, the linker emits an error message and an  
unexecutable a.outonly if linking with +compatset.  
ld main.o -L. -lbar -lc  
ld: Unsatisfied symbol “foo”.  
1 error.  
94  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
Hid in g Sym bols fr om exp or t w ith  
+h id ea llsym bols  
Use the +hideallsymbolsoption to hide all symbols to prevent the  
linker from exporting them in a shared link.  
In the following example, main()exports func()and test(). Using  
+hideallsymbols, the linker does not export these two routines in the  
a.out.  
ld main.o +hideallsymbols -L. -lfoo -lc  
elfdump -t a.out  
a.out:  
...  
.symtab  
index Type Bind Other SectValueSizeName  
1 FUNC LOCL 00xb 0x4000000000001104 0test  
...  
10FUNCLOCL00xb0x40000000000012000func  
Ch a n gin g Ma p files w ith -k a n d +n od efa u ltm a p  
The linker automatically maps sections from input object files onto  
output segments in executable files. These options to the ldcommand  
allow you to change the linkers default mapping.  
Use the -kfilename option to provide a memory map. The linker uses  
the file specified by filename as the output file memory map.  
The +nodefaultmapoption used with -koption prevents the linker  
from concatenating the default memory map to the map provided by  
filename. If you specify +nodefaultmap, the linker does not append the  
default mapfile to your mapfile. If you do not specify +nodefaultmap  
with -k, the linker appends the output file to the default mapfile.  
NOTE  
In most cases, the linker produces a correct executable without the use of  
the mapfile option. The mapfile option is an advanced feature of the  
linker toolset intended for systems programming use, not application  
programming use. When using the mapfile option, you can create  
executable files that do not execute.  
For more information on mapfiles and examples using these options, see  
Appendix A, Using Mapfiles,” on page 295.  
Chapter 3  
95  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
Ign or in g Dyn a m ic Pa th En vir on m en t  
Va r ia bles w ith +n oen vva r  
Use the +noenvvarto instruct the dynamic loader not to look at the  
environment variables relating to dynamic path searching at runtime. It  
ignores LD_LIBRARY_PATHand SHLIB_PATHenvironment variables.  
This option is on by default in with ld +compat. It is off by default with  
ld +std.  
For example, if libbar.slhas dependent library libfee.slthat is i  
./at link time, but is moved to /tmpby runtime:  
ld main.o -L. -lbar -lc  
export LD_LIBRARY_PATH=/tmp  
mv libbar.sl /tmp  
a.out  
called bar()  
called fee()  
mv /tmp/libbar.sl ./  
ld main.o +noenvvar -L. -lbar -lc  
mv libbar.sl /tmp  
a.out  
dld.sl: Unable to find library “libbar.sl”  
Lin k in g in 64-bit Mod e w ith +std  
Use the +stdoption to instructs the linker to do a 64-bit mode link. This  
is the default mode. For more information, see Using the 64-bit Mode  
Linker with +compat or +std.  
Lin k in g in 32-bit Mod e Style w ith +com p a t  
Use the +compatoption to instruct the linker to do a 32-bit mode style  
link. For more information, see Using the 64-bit Mode Linker with  
+compat or +std.  
Con tr ollin g Ou tp u t fr om th e Un w in d Ta ble  
w ith +str ip w in d  
Use the +stripunwindoption to suppress output of the unwind table.  
ld -b foo.o -o libfoo.sl +stripunwind  
elfdump -U libfoo.sl  
libfoo.sl:  
96  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
Selectin g Ver bose Ou tp u t w ith +vtyp e  
Use the +vtypeoption to get verbose output about specified elements of  
the link operation. The following values specify the type:  
Pa r a m eter  
Descr ip tion  
files  
Dump information about each object file loaded.  
ld main.o +vtype files -L. -lfile1 -lfile2 -lc  
Loading main.o:  
Loading ./libfile1.sl:  
Loading ./libfile2.sl:  
Loading /usr/lib/pa20_64/libc.2:  
Loading /usr/lib/pa20_64/libdl.1:  
libraries  
sections  
Dump information about libraries searched.  
ld main.o +vtype libraries -L. -lfile1 -lfile2 -lc  
Searching /usr/lib/pa20_64/libc.a:  
Selecting /usr/lib/pa20_64/libc.a[printf.o] to  
resolve printf  
Selecting /usr/lib/pa20_64/libc.a[data.o] to  
resolve __iob  
...  
Dump information about each section added to the  
output file.  
ld main.o +vtype sections -L. -lfile1 -lfile2 -lc  
main.o:  
section .text PROG_BITS AX 116 8 added to text  
segment  
section .PARISC.unwind UNWIND 16 4 added to text  
segment  
section .data PROG_BITS AW 96 8 added to data  
segment  
symbols  
Dump information about global symbols  
referenced/defined from/in the input files.  
ld main.o +vtype symbols -L. -lfile1 -lfile2 -lc  
main.o:  
main is DEFINED GLOBAL FUNC  
printf is UNDEF GLOBAL FUNC  
lib1_func is UNDEF GLOBAL FUNC  
lib2_func is UNDEF GLOBAL FUNC  
./libfile1.s:  
printf is UNDEF GLOBAL FUNC  
_DYNAMIC is DEFINED GLOBAL OBJECT  
lib1_func is DEFINED GLOBAL FUNC  
...  
all  
Dump all of the above. Same as -v.  
Chapter 3  
97  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Using 64-bit Mode Linker Options  
ld main.o +vtype all -L. -lfile1 -lfile2 -lc  
Loading main.o:  
main.o:  
main is DEFINED GLOBAL FUNC  
printf is UNDEF GLOBAL FUNC  
lib1_func is UNDEF GLOBAL FUNC  
lib2_func is UNDEF GLOBAL FUNC  
main.o:  
section .text PROG_BITS AX 116 8 added to text  
segment  
section .PARISC.unwind UNWIND 16 4 added to text  
segment  
section .data PROG_BITS AW 96 8 added to data  
segment  
Loading ./libfile1.sl:  
./libfile1.sl:  
...  
Lin k in g w ith th e 64-bit cr t0.o Sta r tu p File  
In 32-bit mode, you must always include crt0.oon the link line.  
In 64-bit mode, you must include crt0.oon the link line for all fully  
archive links (ld -noshared) and in compatibility mode (+compat). You  
do not need to include the crt0.ostartup file on the ldcommand line  
for shared bound links. In 64-bit mode, the dynamic loader, dld.sl, does  
some of the startup duties previously done by crt0.o.  
See The crt0.o Startup File” on page 43, and crt0(3) manual page for  
more information.  
98  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Linker Compatibility Warnings  
Lin k er Com p a tibility Wa r n in gs  
Beginning with the HP-UX 10.20 release, the linker generates  
compatibility warnings. These warnings include HP 9000 architecture  
issues, as well as linker features that may change over time.  
Compatibility warnings can be turned off with the  
+vnocompatwarningslinker option. Also, detailed warnings can be  
turned on with the +vallcompatwarningslinker option. See the ld(1)  
man page for a description of these options.  
Link-time compatibility warnings include the following:  
Linking PA-RISC 2.0 object files on any system — PA-RISC 1.0  
programs run on 1.1 and 2.0 systems. PA-RISC 2.0 programs do not  
run on 1.1 or 1.0 systems. See Also PA-RISC Changes in Hardware  
Compatibility” on page 21.  
Dynamic linking with -A — If you do dynamic linking with -A, you  
should migrate to using the shared library management routines  
described in Chapter 6, Shared Library Management Routines,” on  
page 195. These routines are also described in the sh_load(3X) and  
dl*(3X) man page.  
The 64-bit mode linker does not support the -A option.  
Procedure call parameter and return type checking (which can be  
specified with -C) — The 32-bit linker checks the number and types of  
parameters in procedure calls across object modules. In a future  
release, you should expect HP compilers to perform cross-module type  
checking, instead of the linker. This impacts HP Pascal and HP  
Fortran programs.  
The 64-bit mode linker does not support the -C option.  
Duplicate names found for code and data symbols — The 32-bit linker  
can create a program that has a code and data symbol with the same  
name. In the HP-UX 11.00 release, the 64-bit mode linker adopts a  
single name space for all symbols. This means that code and data  
symbols cannot share the same name. Renaming the conflicting  
symbols solves this problem.  
Chapter 3  
99  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Linker Compatibility Warnings  
Unsatisfied symbols found when linking to archive libraries — If you  
specify the -voption with the +vallcompatwarningsoption and  
link to archive libraries, you may see new warnings. For an example,  
see Linking to Archive Libraries with Unsatisfied Symbols” in this  
chapter.  
Versioning within a shared library — If you do versioning within a  
shared library with the HP_SHLIB_VERSION(C and C++); or the  
SHLIB_VERSION(Fortran and Pascal) compiler directive, you should  
migrate to the industry standard and faster-performing library-level  
versioning. See Library-Level Versioning” on page 150 to learn how  
to do library-level versioning. In the HP-UX 11.00 release, the 64-bit  
mode linker does not support internal library versioning.  
Lin k in g to Ar ch ive Libr a r ies w ith Un sa tisfied  
Sym bols  
If you link a program that contains a reference to an archive library, and  
the archive library contains an undefined symbol, you may see the  
following warning:  
ld: (Warning) The file library.a(x.o) has not been fully  
checked for unsatisfied symbols. This behavior may  
change in future releases.  
The 32-bit mode linker does not include an object from an archive library  
simply because it contains a needed definition of an uninitialized global  
data symbol. Instead, it changes the existing undefined symbol to an  
uninitialized data symbol. This symbol has the same size as the  
definition of the global variable in the library.  
For example, given these source files:  
archive.c  
int foo;  
/* definition of uninitialized  
global data symbol  
*/  
void func()  
{
unsat();  
}
main.c  
extern int foo; /* declaration of global data symbol */  
main()  
{
100  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Linker Compatibility Warnings  
printf ("\tfoo = %d\n", foo);  
}
If these files are compiled and linked as:  
cc -c main.c  
cc -c archive.c  
ar rv liba.a archive.o  
ld /opt/langtools/lib/crt0.o -v \  
+vallcompatwarnings main.o liba.a -lc -o test  
The linker issues the following warning:  
ld: (Warning) The file liba.a(archive.o) has not been fully  
checked for unsatisfied symbols. This behavior may change  
in future releases.  
due to an unresolved symbol for unsat().  
In the HP-UX 11.00 release, the linker includes the archive library object  
definition rather than fixing up the external reference.  
Chapter 3  
101  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tasks  
Linker Compatibility Warnings  
102  
Chapter3  
Download from Www.Somanuals.com. All Manuals Search And Download.  
4
Lin k er Tools  
This chapter describes the linker toolset, which provides several tools to  
help you find symbols, display and modify object files, and determine link  
order. Some of these tools are specific to a particular object file type;  
others are available in both 32-bit and 64-bit mode.  
The following table lists the linker toolset.  
Tool  
chatr  
Mod e  
Descr ip tion  
32-bit/  
64-bit  
Displays or modifies the internal attributes of  
an object file. See Changing a Program's  
Attributes with chatr(1).  
elfdump  
fastbind  
ldd  
64-bit  
Displays the contents of an ELF object file.  
See Viewing the Contents of an Object File  
with elfdump(1).  
32-bit/  
64-bit  
Improves startup time of programs that use  
shared libraries. See Improving Program  
Start-up with fastbind(1).  
64-bit  
Lists dynamic dependencies of executable files  
and shared libraries. Viewing library  
dependencies with ldd(1).  
lorder  
nm  
32-bit/  
64-bit  
Finds ordering relationship for an object  
library. SeeFinding Object Library Ordering  
Relationships with lorder(1).  
32-bit/  
64-bit  
Displays the symbol table of an object file. See  
“Viewing Symbols in an Object file with  
nm(1)”.  
size  
32-bit/  
64-bit  
Prints sizes of object file elements. See  
“Viewing the Size of Object File Elements  
with size(1).  
strip  
32-bit/  
64-bit  
Strips symbol and debugging information  
from an object file, executable, or archive  
library. See Reducing Storage Space with  
strip(1).  
103  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Changing a Program's Attributes with chatr(1)  
Ch a n gin g a P r ogr a m 's Attr ibu tes w ith  
ch a tr (1)  
The chatrcommand (see chatr(1)) allows you to change various program  
attributes that were determined at link time. When run without any  
options, chatrdisplays the attributes of the specified file.  
Usin g ch a tr for 32-bit P r ogr a m Attr ibu tes  
The following table summarizes the options you can use to change  
various attributes:  
To d o th is:  
Use th is op tion :  
32-bit mode only: Set the file's magic number to SHARE_MAGIC.  
-n  
-q  
32-bit mode only: Set the file's magic number to DEMAND_MAGIC.  
32-bit mode only: Change the files magic number from EXEC_MAGIC -M  
to SHMEM_MAGIC.  
32-bit mode only: Change the files magic number from  
-N  
SHMEM_MAGICto EXEC_MAGIC.  
Use immediate binding for all libraries loaded at program startup. -B immediate  
Use deferred binding for all libraries loaded at program startup. -B deferred  
Use nonfatal binding. Must be specified with -B immediateor -B -B nonfatal  
deferred.  
Use restricted binding. Must be specified with -B immediateor -B -B restricted  
deferred.  
a
Enable run-time use of the path list specified with the +boption at +b enable  
link time.  
Disable run-time use of the path list specified with the +boption at +b disable  
link time.  
104  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Changing a Program's Attributes with chatr(1)  
To d o th is:  
Use th is op tion :  
a
Enable the use of the SHLIB_PATHenvironment variable to perform  
run-time path list lookup of shared libraries.  
+s enable  
Disable the use of the SHLIB_PATHenvironment variable to perform +s disable  
run-time path list lookup of shared libraries.  
32-bit mode only: Do not subject a library to path list lookup, even if +llibname  
path lists are provided. That is, use default library path stored in  
the executable.  
32-bit mode only: Subject a library to path list lookup if directory  
path lists are provided. Useful for libraries that were specified with  
a full path name at link time.  
-llibname  
Set the virtual memory page size for data segments.  
Set the virtual memory page size for instructions.  
+pd size  
+pi size  
Assist branch prediction on PA-RISC 2.0 systems. Programs must be +k  
linked with +Ostaticprediction.  
Request static branch prediction.  
+r  
a. If +b enableand +s enableare both specified, the order in which they appear  
determines which search path is used first.  
Usin g ch a tr for 64-bit P r ogr a m Attr ibu tes  
In 64-bit mode, chatrsupports two different command syntaxes. One is  
compatible with the 32-bit command. Use it to modify files that have only  
a single text segment and data segment. The second command syntax  
allows you specify selected segments to modify. The following sections  
list the additional 64-bit mode options for the chatrcommand.  
For the 32-bit compatible syntax:  
Chapter 4  
105  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Changing a Program's Attributes with chatr(1)  
To d o th is:  
Use th is op tion :  
Set the modification bit for the files data  
segment(s).  
+md  
Set the modification bit for the files text  
segment(s).  
+mi  
Set the code bit for the files data segment(s).  
Set the code bit for the files text segment(s).  
+cd  
+ci  
+z  
Enable lazy swap on all data segments. Do not  
use with non-data segments.  
For the 64-bit only syntax:  
To d o th is:  
Use th is op tion :  
Set the code bit for a specified segment.  
+c  
Enables or disables lazy swap allocation for  
dynamically allocated segments (such as the  
stack or heap).  
+dz  
Set the modification bit for a specified segment.  
Set the page size for a specified segment.  
+m  
+p  
Identify a segment using a segment index  
number.  
+si  
Identify a segment using an address.  
+sa  
Use all segments in the file for a set of attribute +sall  
modifications.  
Enable lazy swap on a specific segment (using the +z  
second command syntax). Do not use with  
non-data segments.  
106  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing Symbols in an Object file with nm(1)  
View in g Sym bols in a n Object file w ith  
n m (1)  
The nm(1) command displays the symbol table of each specified object.  
file can be a relocatable object file or an executable object file, or an  
archive of relocatable or executable object files.  
nmprovides three general output formats: the default (neither pnor –P  
specified), –p, and –P. See the nm(1) man page for a detailed description  
of the output formats.  
Use Th is  
Op tion  
To  
Prefix each output line with the name of the object file or archive, file.  
–A  
Equivalent to –r.  
64-bit mode ELF files only: Demangle C++ names before printing them.  
–C  
Display the value and size of a symbol in decimal. This is the default for the –d  
default format or the –p format. Equivalent to -t d.  
Display only external and static symbols. This option is ignored (see –f).  
Display full output. This option is in force by default.  
Display only external (global) symbol information.  
Do not display the output header data.  
–e  
–f  
–g  
–h  
–l  
Distinguish between weak and global symbols by appending *to the key  
letter of weak symbols. Only takes effect with -pand/or -P.  
Sort symbols by name, in ascending collation order, before they are printed. –n  
This is the default. To turn off this option, use -N.  
Display symbols in the order in which they appear in the symbol table.  
–N  
–o  
Display the value and size of a symbol in octal. Equivalent to -t o.  
Chapter 4  
107  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing Symbols in an Object file with nm(1)  
Use Th is  
Op tion  
To  
Display information in a blank-separated output format. Each symbol name –p  
is preceded by its value (blanks if undefined) and one of the letters  
A
B
C
D
R
S
absolute  
bss symbol  
common symbol  
data symbol  
section region  
tstorage symbol (32-bit mode SOM files only) If the symbol  
is local (nonexternal), the type letter is in lowercase. If the  
symbol is a secondary definition, the type letter is followed  
by the letter S. Note that pis not compatible with –P.  
T
U
text symbol  
undefined  
Display information in a portable output format as specified below, to  
-P  
standard output. Note that -Pis not compatible with -P.  
32-bit mode SOM files only: Silence some warning messages.  
-q  
-r  
Prefix each output line with the name of the object file or archive, file.  
Equivalent to –A.  
64-bit mode ELF files only: Print the section index instead of the section  
-s  
name.  
Display each numeric value in the specified format. format can be one of:  
–t format  
d
Display the value and size of a symbol in decimal. This is  
the default for the default format or the pformat.  
Equivalent to -d.  
o
x
Display the value and size of a symbol in octal. Equivalent  
to -o.  
Display the value and size of a symbol in hexadecimal.  
This is the default for the Pformat. Equivalent to -x.  
108  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing Symbols in an Object file with nm(1)  
Use Th is  
Op tion  
To  
32-bit mode SOM files only: Truncate every name that would otherwise  
overflow its column and place an asterisk as the last character in the  
displayed name to mark it as truncated. If Aor ris also specified, the file  
prefix is truncated first.  
–T  
By default, nmprints the entire name of the symbols listed. Since object files  
can have symbol names with an arbitrary number of characters, a name that  
is longer than the width of the column set aside for names overflows its  
column, forcing every column after the name to be misaligned.  
Display undefined symbols only.  
–u  
–U  
–v  
–V  
-x  
Print the usage menu.  
Sort symbols by value before they are printed.  
Display the executing version of the nmcommand on standard error.  
Displays the value and size of a symbol in hexadecimal. this is the default  
for the -Pformat. Equivalent to -t x.  
Examples  
Display which object files have undefined references for the symbol  
leap”:  
"nm –rup *.o | grep leap"  
Display which object files have a definition for the text symbol leap”:  
nm –rp *.o | awk ’{ if\  
($3 == " "T" " && $4 == " "leap" ") { print $0 } }’"  
To view the symbols defined in an object file, use the nmcommand.  
The following 32-bit mode example shows output from running nm -p  
on the func.oand main.oobject files.  
$nm -p func.o  
Other symbols created from compiling.  
1073741824 d $THIS_DATA$  
1073741824 d $THIS_SHORTDATA$  
1073741824 b $THIS_BSS$  
1073741824 d $THIS_SHORTBSS$  
0000000000 T sum_n  
Global definitions of sum_n.  
$ nm -p main.o  
Chapter 4  
109  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing Symbols in an Object file with nm(1)  
0000000000 U $global$  
compiling.  
Other symbols created from  
1073741824 d $THIS_DATA$  
1073741872 d $THIS_SHORTDATA$  
1073741872 b $THIS_BSS$  
1073741872 d $THIS_SHORTBSS$  
0000000000 T main  
Global definition of main.  
0000000000 U printf  
0000000000 U scanf  
0000000000 U sum_n  
The first column shows the address of each symbol or reference. The  
last column shows the symbol name. The second column denotes the  
symbol's type:  
T
U
d
b
indicates a global definition.  
indicates an external reference.  
indicates a local definition of data.  
indicates a local definition of uninitialized data  
(bss).  
Thus, a global definition of sum_nis found in func.o. An external  
reference to sum_nis found in main.o. External references to the C  
printfand scanfroutines are found in main.o. For details on the  
use of nm, see nm(1).  
110  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing the Contents of an Object File with elfdump(1)  
View in g th e Con ten ts of a n Object File  
w ith elfd u m p (1)  
NOTE  
The elfdumpcommand works on 64-bit executables or shared libraries.  
The elfdump(1) command displays information contained in ELF format  
object files, archives, and shared libraries.  
Use the following options to select the information you want to display:  
Use th is  
To view th e con ten ts.  
op tion  
Symbol table entries.  
Archive headers from an archive library.  
String table(s).  
-t  
-a  
-c  
-f  
-g  
-h  
-L  
File header.  
Global symbols from an archive.  
Section headers.  
The .dynamic section in shared libraries and  
dynamically linked program files.  
Optional headers (program headers).  
Relocations.  
-o  
-r  
-s  
-U  
Section contents.  
Unwind table.  
elfdumpprovides the following additional options to modify your  
selections:  
Chapter 4  
111  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing the Contents of an Object File with elfdump(1)  
Op tion  
-H  
Mod ifies  
Ca u ses elfd u m p to  
all  
Select output format in hexadecimal, octal, or decimal.  
Suppress title printing.  
-p  
-S  
-C  
all  
-h,-o  
Display headers in short format.  
-c, -r,  
Demangle C++ symbol names before displaying them.  
-s, -t  
With -H, ignored.  
With -nname, display the symbol whose unmangled name  
matches name, and prints its symbol name as a demangled  
name.  
-Dnum  
-h, -s  
Display the section whose index is num.  
+Dnum2 -h, -s  
Display the sections in the range 1 to num2.  
With -D, display the sections in the range num to num2.  
-Dnum  
-r  
Display the relocation whose index is num.  
+Dnum2 -r  
Display only the relocations which apply to the section(s) in the  
range.  
+sname -c, -t  
Display the section specified by name.  
-nname  
-h, -r,  
Display information about the section specified by name.  
-s  
-nname -t  
-Tnum -t  
+Tnum2 -t  
Display information about the symbol entry specified by name.  
Display the symbol whose index is num.  
Display the symbols in the range 0 to num2.  
With-T, display the symbols in the range num to num2.  
112  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing library dependencies with ldd(1)  
View in g libr a r y d ep en d en cies w ith  
ld d (1)  
NOTE  
The lddcommand works on 64-bit executables or shared libraries.  
The ldd(1) command lists the dynamic dependencies of executable files  
or shared libraries. ldddisplays verbose information about dynamic  
dependencies and symbol references:  
Execu ta ble  
All shared libraries that would be loaded as a result of  
executing the file.  
Sh a r ed libr a r y All shared libraries that would be loaded as a result of  
loading the library.  
ldduses the same algorithm as the dynamic loader  
(/usr/lib/pa20_64/dld.sl) to locate the shared libraries.  
ldddoes not list shared libraries explicitly loaded using dlopen(3X) or  
shl_load(3X).  
lddprints the record of shared library path names to stdout. It prints  
the optional list of symbol resolution problems to stderr.  
Use th e  
op tion  
To d o th is  
Check reference to data symbols.  
-d  
-r  
-s  
Check reference to data and code symbols.  
Displays the search path used to locate the shared  
libraries.  
Display all dependency relationships.  
-v  
Examples  
By default, lddprints simple dynamic path information, including  
the dependencies recorded in the executable (or the shared library)  
followed by the physical location where the dynamic loader finds  
these libraries.  
Chapter 4  
113  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing library dependencies with ldd(1)  
$ldd a.out  
./libx.sl =>./libx.sl  
libc.2 =>/lib/pa20_64/libc.2  
libdl.1 =>/lib/pa20_64/libdl.1  
The -voption causes lddto print dependency relationship along with  
the dynamic path information.  
$ldd -v a.out  
find library=./libx.sl; required by a.out  
./libx.sl =>./libx.sl  
find library=libc.2; required by a.out  
libc.2 =>/lib/pa20_64/libc.2  
find library=libdl.1; required by /lib/pa20_64/libc.2  
libdl.1 =>/lib/pa20_64/libdl.1  
The -roption to causes it to analyze all symbol references and print  
information about unsatisfied code and data symbols.  
$ldd -r a.out  
./libx.sl=>./libx.sl  
libc.2=>/lib/pa20_64/libc.2  
libdl.1=>/lib/pa20_64/libdl.1  
symbol not found: val1 (./libx.sl)  
symbol not found: count (./libx.sl)  
symbol not found: func1 (./libx.sl)  
symbol not found: func2 (./libx.sl)  
114  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Viewing the Size of Object File Elements with size(1)  
View in g th e Size of Object File Elem en ts  
w ith size(1)  
The size(1) command produces section size information for each section  
in your specified object files. It displays the size of the text, data and bss  
(uninitialized data) sections with the total size of the object file. If you  
specify an archive file, the information for all archive members is  
displayed.  
Use the following options to display information for your specified files:  
Use th is  
To d isp la y  
op tion  
Sizes in decimal (default).  
Sizes in octal.  
-d  
-o  
-x  
-V  
-v  
Sizes in hexadecimal.  
Version information about the sizecommand.  
Verbose list of the subspaces in the object files. Each  
subspace is listed on a separate line with its size,  
physical address, and virtual address.  
64-bit mode only: Size of each allocatable section (=.  
-f  
-F  
64-bit mode only: Size and permission bits of each  
loadable segment=.  
64-bit mode only: Sizes of non loadable segments or non -n  
allocatable sections.  
Chapter 4  
115  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Reducing Storage Space with strip(1)  
Red u cin g Stor a ge Sp a ce w ith str ip (1)  
The strip(1) command removes the symbol table and line number  
information from object files, including archives. Thereafter, no symbolic  
debugging access is available for that file. The purpose of this command  
is to reduce file storage overhead consumed by the object file. Use this  
command on production modules that have been debugged and tested.  
The effect is nearly identical to using the -soption of ld.  
You can control the amount of information stripped from the symbol  
table by using the following options:  
Use th is  
op tion  
To  
Strip line number information only; do not strip any  
symbol table information.  
-l  
Do not strip static or external symbol information.  
-x  
-r  
32-bit mode only: Reset the relocation indexes into the  
symbol table. This option allows stripto be run on  
relocatable files, in which case the effect is also to strip  
only symbolic debugging information and unloadable  
data.  
Print the version of the stripcommand to stderr.  
-V  
NOTE  
The -land -xoptions are synonymous because the symbol table  
contains only static and external symbols. Either option strips only  
symbolic debugging information and unloadable data.  
If there are any relocation entries in the object file and any symbol table  
information is to be stripped, stripissues a message and terminates  
without stripping the specified file unless the -roption is used.  
116  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Reducing Storage Space with strip(1)  
If you execute stripon an archive file (see ar(4)), it removes the archive  
symbol table. The archive symbol table must be restored by executing ar  
with its soperator (see ar(1)) before the ldcommand (see ld (1)) can use  
the archive. stripissues appropriate warning messages when this  
situation occurs.  
Chapter 4  
117  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Improving Program Start-up with fastbind(1)  
Im p r ovin g P r ogr a m Sta r t-u p w ith  
fa stbin d (1)  
The fastbind(1) command prepare an incomplete executable for faster  
program start-up. It can improve the start-up time of programs that use  
shared libraries (incomplete executables) by storing information about  
needed shared library symbols in the executable file.  
fastbindperforms analysis on the symbols used to bind an executable  
and all of its dependent shared libraries, and stores this information in  
the executable file. The next time the executable is run, the dynamic  
loader (/usr/lib/dld.slfor 32-bit mode or  
/usr/lib/pa20_64/dld.slfor 64-bit mode) detects that this  
information is available, and uses it to bind the executable instead of  
using the standard search method for binding the symbols.  
Because fastbindwrites the fastbind information in the executable file,  
you must have write permission on the executable file. If the executable  
file being analyzed is being run as another process or the file is locked  
against modifications by the kernel, the fastbindcommand fails.  
If the shared libraries that an executable is dependent on are modified  
after the fastbind information is created, the dynamic loader silently  
reverts to standard search method for binding the symbols. The fastbind  
information can be re–created by running fastbindon the executable  
again. fastbindautomatically erases the old fastbind information and  
generate the new one.  
Use th is  
op tion  
To d o th is  
Remove the fastbind information from the executable, -n  
returning it to the same state it as was in before you  
ran fastbindon it.  
Normally, if fastbinddetects any unsatisfied symbols -u  
while building the fastbind information, it generates an  
error message and does not modify the executable file.  
When you invoke fastbindwith the -uoption  
however, it allows unresolved symbols.  
118  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Improving Program Start-up with fastbind(1)  
The 32-bit mode fastbindcommand does not work with EXEC_MAGIC  
executables.  
fastbindeffectively enforces the binding modes bind-restricted and  
bind-immediate. For example, consider an executable linked  
bind-deferred, which calls a function foo()defined in an implicitly  
loaded library. Before the actual call is made, if it explicitly loads a  
shared library (using shl_load(3X) with BIND_FIRST) having a  
definition for foo()when foo()is finally called, it is resolved from the  
explicitly-loaded library. But after running fastbind, the symbol foo()  
is resolved from the implicitly-loaded library.  
For more information about fastbind and performance, see Improving  
Shared Library Start-Up Time with fastbind” on page 293.  
Example  
To run fastbindon the executable file a.out:  
$fastbind a.out  
To later remove the fastbind information from the executable file  
a.out  
$fastbind -n a.out  
Chapter 4  
119  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Linker Tools  
Finding Object Library Ordering Relationships with lorder(1)  
Fin d in g Object Libr a r y Or d er in g  
Rela tion sh ip s w ith lor d er (1)  
The lorder command finds the ordering relation for an object library. You  
can specify one or more object or archive library files (see ar(1)) on the  
command line or read those files from standard input. The standard  
output is a list of pairs of object file names, meaning that the first file of  
the pair refers to external identifiers defined in the second.  
You can process the output with tsortto find an ordering of a library  
suitable for one-pass access by ld(see tsort(1) and ld(1)). The linker ldis  
capable of multiple passes over an archive in the archive format and does  
not require that you use lorderwhen building an archive. Using the  
lordercommand may, however, allow for a slightly more efficient access  
of the archive during the link-edit process.  
The symbol table maintained by arallows ldto randomly access  
symbols and files in the archive, making the use of lorderunnecessary  
when building archive libraries (see ar(1)).  
lorderoverlooks object files whose names do not end with .o, even  
when contained in library archives, and attributes their global symbols  
and references to some other file.  
Examples  
Build a new library from existing .ofiles:  
$ar cr library ‘lorder *.o | tsort‘  
When creating libraries with so many objects that the shell cannot  
properly handle the *.oexpansion, the following technique may  
prove useful:  
$ls |grep ’.o$’|lorder|tsort|xargs ar cq library  
120  
Chapter4  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
5
Cr ea tin g a n d Usin g Libr a r ies  
Many libraries come with HP-UX. You can also create and use your own  
libraries on HP-UX. This chapter provides information on the following  
topics:  
General Information about Shared and Archive Libraries  
Overview of Shared and Archive Libraries”  
What are Archive Libraries?”  
What are Shared Libraries?”  
Example Program Comparing Shared and Archive Libraries”  
Shared Libraries with Debuggers, Profilers, and Static Analysis”  
Creating Libraries on HP-UX  
Creating Shared Libraries”  
Creating Archive Libraries”  
Using Libraries on HP-UX  
Switching from Archive to Shared Libraries”  
Summary of HP-UX Libraries”  
Caution When Mixing Shared and Archive Libraries”  
Using Shared Libraries in 64-bit Mode  
Internal Name Processing”  
Dynamic Path Searching for Shared Libraries”  
Shared Library Symbol Binding Semantics”  
Mixed Mode Shared Libraries”  
64-bit Mode Library Examples”  
Chapter 5  
121  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Overview of Shared and Archive Libraries  
Over view of Sh a r ed a n d Ar ch ive  
Libr a r ies  
HP-UX supports two kinds of libraries: a r ch ive and sh a r ed . A shared  
library is also called a d ll (dynamically linked library), particularly in  
the context of the 64-bit mode linker. Archive libraries are the more  
traditional of the two. The following table summarizes differences  
between archive and shared libraries.  
Com p a r in g  
Ar ch ive  
Suffix is .a.  
Sh a r ed (or d ll)  
file name suffix  
Suffix is .slor .number representing a  
particular version of the library.  
object code  
Made from relocatable  
object code.  
Made from p osition -in d ep en d en t object  
code, created by compiling with the +zor  
+Zcompiler option. Can also be created in  
assembly language (see Chapter 7,  
Position-Independent Code,” on page  
259).  
creation  
Combine object files with  
Combine PIC object files with the ld  
the arcommand  
command  
122  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Overview of Shared and Archive Libraries  
Com p a r in g  
Ar ch ive  
Sh a r ed (or d ll)  
address binding Addresses of library  
subroutines and data are  
Addresses of library subroutines are  
bound at run time. Addresses of data in  
a.outare bound at link time; addresses of  
data in shared libraries are bound at run  
time.  
resolved at link time.  
a.outfiles  
Contains all library  
Does not contain library routines; instead,  
contains a lin k a ge ta ble that is filled in  
with the addresses of routines and shared  
library data. An a.outthat uses shared  
libraries is known as an in com p lete  
execu ta ble, and is almost always much  
smaller than a complete executable.  
routines or data (external  
references) referenced in  
the program. An a.outfile  
that does not use shared  
libraries is known as a  
com p lete execu ta ble.  
run time  
Each program has its own  
copy of archive library  
routines.  
Shared library routines are shared among  
all processes that use the library.  
Almost all system libraries are available both as a shared library and as  
an archive library for 32-bit mode in the directory /usr/liband for  
64-bit mode in /usr/lib/pa20_lib. Archive library file names end  
with .awhereas shared library file names end with .sl. For example, in  
32-bit mode, the archive C library libcis /usr/lib/libc.aand the  
shared version is /usr/lib/libc.sl. In 64-bit mode, the archive C  
library libcis /usr/lib/pa20_64/libc.aand the shared version is  
/usr/lib/pa20_64/libc.sl  
If both shared and archived versions of a library exist, lduses the one  
that it finds first in the default library search path. If both versions exist  
in the same directory, lduses the shared version. For example,  
compiling the C program prog.ccauses ccto invoke the linker with a  
command like this:  
For 32-bit mode: ld /opt/langtools/lib/crt0.o prog.o -lc  
For 64-bit mode:  
ld /opt/langtools/lib/pa20_64/crt0.o prog.o -lc  
The -lcoption instructs the linker to search the C library, libcor  
libc/pa20_64, to resolve unsatisfied references from prog.o. If a  
shared libcexists (/usr/lib/libc.slor  
/usr/lib/pa20_64/libc.sl), lduses it instead of the archive libc  
Chapter 5  
123  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Overview of Shared and Archive Libraries  
(/usr/lib/libc.aor /usr/lib/pa20_64/libc.a). You can, however,  
override this behavior and select the archive version of a library with the  
-aoption or the -l:option. These are described in Choosing Archive or  
Shared Libraries with -a” on page 63 and Specifying Libraries with -l  
and l:” on page 87.  
In addition to the system libraries provided on HP-UX, you can create  
your own archive and shared libraries. To create archive libraries,  
combine object files with the arcommand, as described in Overview of  
Creating an Archive Library. To create shared libraries, use ldto  
combine object files containing position-independent code (PIC), as  
described in Creating Shared Libraries.  
For more information, see Caution When Mixing Shared and Archive  
Libraries.  
124  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
What are Archive Libraries?  
Wh a t a r e Ar ch ive Libr a r ies?  
An a r ch ive libr a r y contains one or more object files and is created with  
the arcommand. When linking an object file with an archive library, ld  
searches the library for global definitions that match up with external  
references in the object file. If a match is found, ldcopies the object file  
containing the global definition from the library into the a.outfile. In  
short, any routines or data a program needs from the library are copied  
into the resulting a.outfile.  
NOTE  
For 32-bit only:  
If the only definition referenced in an object file of an archive library is a  
common symbol, only that common symbol is copied into the a.outand  
not the entire object file. This helps reduce the size of the a.outfile.  
Exa m p le  
For example, in 32-bit mode, suppose you write a C program that calls  
printffrom the libclibrary. “Linking with an Archive Library” shows  
how the resulting a.outfile would look if you linked the program with  
the archive version of libc.  
Figu r e 5-1  
Lin k in g w ith a n Ar ch ive Libr a r y  
Chapter 5  
125  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
What are Shared Libraries?  
Wh a t a r e Sh a r ed Libr a r ies?  
Like an archive library, a sh a r ed libr a r y contains object code. However,  
ldtreats shared libraries quite differently from archive libraries. When  
linking an object file with a shared library, lddoes not copy object code  
from the library into the a.outfile; instead, the linker simply notes in  
the a.outfile that the code calls a routine in the shared library. An  
a.outfile that calls routines in a shared library is known as an  
incomplete executable.  
Th e Dyn a m ic Loa d er d ld .sl  
When an incomplete executable begins execution, the HP-UX d yn a m ic  
loa d er (see dld.sl(5)) looks at the a.outfile to see what libraries the  
a.outfile needs during execution. In 32-bit mode, the startup code in  
crt0.oactivates the dynamic loader. In 64-bit mode, the kernel  
activates the dynamic loader for a 64-bit a.out.The dynamic loader then  
loads and maps any required shared libraries into the process's address  
space — known as a tta ch in g the libraries. A program calls shared  
library routines indirectly through a lin k a ge ta ble that the dynamic  
loader fills in with the addresses of the routines. By default, the dynamic  
loader places the addresses of shared library routines in the linkage  
table as the routines are called — known as d efer r ed bin d in g.  
Im m ed ia te bin d in g is also possible — that is, binding all required  
symbols in the shared library at program startup. In either case, any  
routines that are already loaded are shared.  
Consequently, linking with shared libraries generally results in smaller  
a.outfiles than linking with archive libraries. Therefore, a clear benefit  
of using shared libraries is that it can reduce disk space and virtual  
memory requirements.  
NOTE  
In prior releases, data defined by a shared library was copied into the  
program file at link time. All references to this data, both in the libraries  
and in the program file, referred to the copy in the executable file.  
With the HP-UX 10.0 release, however, this data copying is eliminated.  
Data is accessed in the shared library itself. The code in the executable  
file references the shared library data indirectly through a linkage  
pointer, in the same way that a shared library would reference the data.  
126  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
What are Shared Libraries?  
Defa u lt Beh a vior Wh en Sea r ch in g for  
Libr a r ies a t Ru n Tim e  
By default, if the dynamic loader cannot find a shared library from the  
list, it generates a run-time error and the program aborts. For example,  
in 32-bit mode, suppose that during development, a program is linked  
with the shared library liblocal.slin your current working directory  
(say, /users/hyperturbo):  
$ ld /opt/langtools/lib/crt0.o prog.o -lc liblocal.sl  
In 32-bit mode, the linker records the path name of liblocal.slin the  
a.outfile as /users/hyperturbo/liblocal.sl. When shipping this  
application to users, you must ensure that (1) they have a copy of  
liblocal.slon their system, and (2) it is in the same location as it was  
when you linked the final application. Otherwise, when the users of your  
application run it, the dynamic loader will look for  
/users/hyperturbo/liblocal.sl, fail to find it, and the program  
will abort.  
In 64-bit mode, the linker records ./liblocal.sl.  
This is more of a concern with non-standard libraries—that is, libraries  
not found in /usr/libor /usr/lib/pa20_64. There is little chance of  
the standard libraries not being in these directories.  
Ca u tion on Usin g Dyn a m ic Libr a r y Sea r ch in g  
If different versions of a library exist on your system, be aware that the  
dynamic loader may get the wrong version of the library when dynamic  
library searching is enabled with SHLIB_PATHor +b. For instance, you  
may want a program to use the PA1.1 libraries found in the  
/usr/lib/pa1.1directory; but through a combination of SHLIB_PATH  
settings and +boptions, the dynamic loader ends up loading versions  
found in /usr/libinstead. If this happens, make sure that  
SHLIB_PATHand +bare set to avoid such conflicts.  
Chapter 5  
127  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Example Program Comparing Shared and Archive Libraries  
Exa m p le P r ogr a m Com p a r in g Sh a r ed  
a n d Ar ch ive Libr a r ies  
As an example, suppose two separate programs, prog1and prog2, use  
shared libcroutines heavily. Suppose that the a.outportion of prog1  
is 256Kb in size, while the prog2a.outportion is 128Kb. Assume also  
that the shared libcis 512Kb in size. Figure 5-2 shows how physical  
memory might look when both processes run simultaneously. Notice that  
one copy of libcis shared by both processes. The total memory  
requirement for these two processes running simultaneously is 896Kb  
(256Kb + 128Kb + 512Kb).  
Figu r e 5-2  
Tw o P r ocesses Sh a r in g libc  
Compare this with the memory requirements if prog1and prog2had  
been linked with the archive version of libc. As shown in Figure 5-3,  
1428Kb of memory are required (768Kb + 640Kb). The numbers in this  
example are made up, but it is true in general that shared libraries  
reduce memory requirements.  
128  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Example Program Comparing Shared and Archive Libraries  
Figu r e 5-3  
Tw o P r ocesses w ith Th eir Ow n Cop ies of libc  
Chapter 5  
129  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Shared Libraries with Debuggers, Profilers, and Static Analysis  
Sh a r ed Libr a r ies w ith Debu gger s,  
P r ofiler s, a n d Sta tic An a lysis  
As of the HP-UX 10.0 release, debugging of shared libraries is supported  
by the HP/DDE debugger. For details on how to debug shared libraries,  
refer to the HP/ DDE Debugger User's Guide.  
Profiling with profand gprofand static analysis are not allowed on  
shared libraries.  
130  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Archive Libraries  
Cr ea tin g Ar ch ive Libr a r ies  
Two steps are required to create an archive library:  
1. Compile one or more source files to create object files containing  
r eloca ta ble object cod e.  
2. Combine these object files into a single a r ch ive libr a r y file with the  
arcommand.  
Shown below are the commands you would use to create an archive  
library called libunits.a:  
cc -Aa -c length.c volume.c mass.c  
ar r libunits.a length.o volume.o mass.o  
These steps are described in detail in Overview of Creating an Archive  
Library.  
Other topics relevant to archive libraries are:  
Contents of an Archive File”  
Example of Creating an Archive Library”  
Replacing, Adding, and Deleting an Object Module”  
Summary of Keys to the ar(1) Command”  
Archive Library Location”  
Over view of Cr ea tin g a n Ar ch ive Libr a r y  
To create an archive library:  
1. Create one or more object files containing relocatable object code.  
Typically, each object file contains one function, procedure, or data  
structure, but an object file could have multiple routines and data.  
2. Combine these object files into a single archive library file with the ar  
command. Invoke arwith the rkey.  
(“Keys” are like command line options, except that they do not require  
a preceding -.)  
Chapter 5  
131  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Archive Libraries  
Figure 5-4 summarizes the procedure for creating archive libraries from  
three C source files (file1.c, file2.c, and file3.c). The process is  
identical for other languages, except that you would use a different  
compiler.  
Figu r e 5-4  
Cr ea tin g a n Ar ch ive Libr a r y  
Con ten ts of a n Ar ch ive File  
An archive library file consists of four main pieces:  
1. a h ea d er str in g, "!<arch>\n", identifying the file as an archive file  
created by ar(\nrepresents the newline character)  
2. a sym bol ta ble, used by the linker and other commands to find the  
location, size, and other information for each routine or data item  
contained in the library  
3. an optional str in g ta ble used by the linker to store file names that  
are greater than 15 bytes long (only created if a long file name is  
encountered)  
4. object m od u les, one for each object file specified on the arcommand  
line  
To see what object modules a library contains, run arwith the tkey,  
which displays a table of contents. For example, to view the table of  
contents” for libm.a:  
$ ar t /usr/lib/libm.a  
Run ar with the t key.  
132  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Archive Libraries  
cosh.o  
Object modules are displayed.  
erf.o  
fabs.o  
floor.o  
. . . .  
This indicates that the library was built from object files named cosh.o,  
erf.o, fabs.o, floor.o, and so forth. In other words, module names  
are the same as the names of the object files from which they were  
created.  
Exa m p le of Cr ea tin g a n Ar ch ive Libr a r y  
Suppose you are working on a program that does several conversions  
between English and Metric units. The routines that do the conversions  
are contained in three C-language files shown:  
len gth .c - Rou tin e to Con ver t Len gth Un its  
float  
{
in_to_cm(float in) /* convert inches to centimeters */  
return (in * 2.54);  
}
volu m e.c - Rou tin e to Con ver t Volu m e Un its  
float  
{
gal_to_l(float gal) /* convert gallons to liters */  
return (gal * 3.79);  
}
m a ss.c - Rou tin e to Con ver t Ma ss Un its  
float  
{
oz_to_g(float oz)  
/* convert ounces to grams */  
return (oz * 28.35);  
}
During development, each routine is stored in a separate file. To make  
the routines easily accessible to other programmers, they should be  
stored in an archive library. To do this, first compile the source files,  
either separately or together on the same command line:  
$ cc -Aa -c length.c volume.c mass.c  
Compile them together.  
length.c:  
volume.c:  
mass.c:  
$ ls *.o  
List the .o files.  
length.o  
mass.o  
volume.o  
Chapter 5  
133  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Archive Libraries  
Then combine the .ofiles by running arwith the rkey, followed by the  
library name (say libunits.a), followed by the names of the object files  
to place in the library:  
$ ar r libunits.a length.o volume.o mass.o  
ar: creating libunits.a  
To verify that arcreated the library correctly, view its contents:  
$ ar t libunits.a  
length.o  
Use ar with the t key.  
volume.o  
mass.o  
All the .o modules are included; it worked.  
Now suppose you've written a program, called convert.c, that calls  
several of the routines in the libunits.alibrary. You could compile the  
main program and link it to libunits.awith the following cc  
command:  
$ cc -Aa convert.c libunits.a  
Note that the whole library name was given, and the -loption was not  
specified. This is because the library was in the current directory. If you  
move libunits.ato /usr/libbefore compiling, the following  
command line will work instead:  
$ cc -Aa convert.c -lunits  
Linking with archive libraries is covered in detail in Chapter 3, Linker  
Tasks,” on page 51.  
Rep la cin g, Ad d in g, a n d Deletin g a n Object  
Mod u le  
Occasionally you may want to replace an object module in a library, add  
an object module to a library, or delete a module completely. For instance,  
suppose you add some new conversion routines to length.c(defined in  
the previous section) and want to include the new routines in the library  
libunits.a. You would then have to replace the length.omodule in  
libunits.a.  
Rep la cin g or Ad d in g a n Object Mod u le  
To replace or add an object module, use the rkey (the same key you use  
to create a library). For example, to replace the length.oobject module  
in libunits.a:  
$ ar r libunits.a length.o  
134  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Archive Libraries  
Deletin g a n Object Mod u le  
To delete an object module from a library, use the dkey. For example, to  
delete volume.ofrom libunits.a:  
$ ar d libunits.a volume.o  
$ ar t libunits.a  
length.o  
Delete volume.o.  
List the contents.  
mass.o  
volume.o is gone.  
Su m m a r y of Keys to th e a r (1) Com m a n d  
When used to create and manage archive libraries, ar's syntax is:  
ar [-] keys archive [modules] ...  
archive is the name of the archive library. modules is an optional list of  
object modules or files. See ar(1) for the complete list of keys and options.  
Usefu l a r Keys  
Here are some useful arkeys and their modifiers:  
key  
d
Description  
Delete the modules from the archive.  
r
Replace or add the modules to the archive. If archive  
exists, arreplaces modules specified on the command  
line. If archive does not exist, arcreates a new archive  
containing the modules.  
t
u
Display a table of contents for the archive.  
Used with the r, this modifier tells arto replace only  
those modules with creation dates later than those in  
the archive.  
v
x
Display verbose output.  
Extracts object modules from the library. Extracted  
modules are placed in .ofiles in the current directory.  
Once an object module is extracted, you can use nmto  
view the symbols in the module.  
For example, when used with the vflag, the tflag creates a verbose table  
of contents — including such information as module creation date and  
file size:  
Chapter 5  
135  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Archive Libraries  
$ ar tv libunits.a  
rw-rr  
rw-rr  
rw-rr  
265/  
265/  
265/  
20  
20  
20  
230 Feb 2 17:19 1990 length.o  
228 Feb 2 16:25 1990 mass.o  
230 Feb 2 16:24 1990 volume.o  
The next example replaces length.oin libunits.a, only if length.o  
is more recent than the one already contained in libunits.a:  
$ ar ru libunits.a length.o  
cr t0.o  
In 64-bit mode, the crt0.ostartup file is not needed for shared bound  
links because dld.sldoes some of the startup duties previously done by  
crt0.o. You still need to include crt0.oon the link line for all fully  
archive links (ld -noshared). In 32-bit mode, crt0.omust always be  
included on the link line.  
Users who link by letting the compilers such as ccinvoke the linker do  
not have include crt0.oon the link line.  
Ar ch ive Libr a r y Loca tion  
After creating an archive library, you will probably want to save it in a  
location that is easily accessible to other programmers who might want  
to use it. There are two main choices for places to put the library:  
in the 32-bit /usr/libor 64-bit /user/lib/pa20_64directory  
in the 32-bit /usr/local/libor /usr/contrib/libdirectory  
Usin g /u sr /lib a n d /u sr /lib/p a 20_64  
Since the linker searches /usr/libor /usr/lib/pa20_64by default,  
you might want to put your archive libraries there. You would eliminate  
the task of entering the entire library path name each time you compile  
or link.  
The drawbacks of putting the libraries in /usr/libor  
/usr/lib/pa20_64are:  
You usually need super-user (system administrator) privileges to  
write to the directory.  
You could overwrite an HP-UX system library that resides in the  
directory.  
136  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Archive Libraries  
Check with your system administrator before attempting to use  
/usr/libor /usr/lib/pa20_64.  
Usin g /u sr /loca l/lib or /u sr /con tr ib/lib  
The /usr/local/liband /usr/local/lib/pa20_64library typically  
contain libraries created locally — by programmers on the system;  
/usr/contrib/liband /usr/contrib/lib/pa20_64contain  
libraries supplied with HP-UX but not supported by Hewlett-Packard.  
Programmers can create their own libraries for both 32-bit and 64-bit  
code using the same library name. Although lddoes not automatically  
search these directories, they are still often the best choice for locating  
user-defined libraries because the directories are not write-protected.  
Therefore, programmers can store the libraries in these directories  
without super-user privileges. Use -L/usr/local/libor  
-L/usr/contrib/libfor 32-bit libraries, or  
-L/usr/local/lib/pa20_64or -L/usr/contrib/lib/pa20_64for  
64-bit libraries to tell the linker to search these directories.  
Chapter 5  
137  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
Cr ea tin g Sh a r ed Libr a r ies  
Two steps are required to create a shared library:  
1. Creating Position-Independent Code (PIC)” by compiling with +z.  
2. Creating the Shared Library with ld” by linking with -b.  
Shown below are the commands you would use to create a shared library  
called libunits.sl:  
$ cc -Aa -c +z length.c volume.c mass.c  
$ ld -b -o libunits.sl length.o volume.o mass.o  
Other topics relevant to shared libraries are:  
Shared Library Dependencies”  
Updating a Shared Library”  
“Version Control with Shared Libraries”  
Shared Library Location”  
Improving Shared Library Performance”  
Cr ea tin g Position -In d ep en d en t Cod e (P IC)  
The first step in creating a shared library is to create object files  
containing p osition -in d ep en d en t cod e (P IC). There are two ways to  
create PIC object files:  
Compile source files with the +zor +Zcompiler option, described  
below.  
Write assembly language programs that use appropriate addressing  
modes, described in Chapter 7, Position-Independent Code,” on page  
259.  
In 32-bit mode, the +zand +Zoptions force the compiler to generate PIC  
object files. In 64-bit mode, the +Zoption is the default.  
138  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
Exa m p le Usin g +z  
Suppose you have some C functions, stored in length.c, that convert  
between English and Metric length units. To compile these routines and  
create PIC object files with the C compiler, you could use this command:  
$ cc -Aa -c +z length.c  
The +z option creates PIC.  
You could then link it with other PIC object files to create a shared  
library, as discussed in Creating the Shared Library with ld.  
Com p a r in g +z a n d +Z  
In 32-bit mode, the +zand +Zoptions are essentially the same. Normally,  
you compile with +z. However, in some instances — when the number of  
referenced symbols per shared library exceeds a predetermined limit —  
you must recompile with the +Zoption instead. In this situation, the  
linker displays an error message and tells you to recompile the library  
with +Z.  
In 64-bit mode, +Z is the default and the compilers ignore the options  
and generate PIC code.  
Com p iler Su p p or t for +z a n d +Z  
In 32-bit mode, the C, C++, FORTRAN, and Pascal compilers support the  
+zand +Zoptions.  
In 64-bit mode, +Zis the default for the C and C++ compilers.  
Cr ea tin g th e Sh a r ed Libr a r y w ith ld  
To create a shared library from one or more PIC object files, use the  
linker, ld, with the -boption. By default, ldwill name the library  
a.out. You can change the name with the -ooption.  
For example, suppose you have three C source files containing routines to  
do length, volume, and mass unit conversions. They are named  
length.c, volume.c, and mass.c, respectively. To make a shared  
library from these source files, first compile all three files using the +z  
option, then combine the resulting .ofiles with ld. Shown below are the  
commands you would use to create a shared library named  
libunits.sl:  
Chapter 5  
139  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
$ cc -Aa -c +z length.c volume.c mass.c  
length.c:  
volume.c:  
mass.c:  
$ ld -b -o libunits.sl length.o volume.o mass.o  
Once the library is created, be sure it has read and execute permissions  
for all users who will use the library. For example, the following chmod  
command allows read/execute permission for all users of the  
libunits.sllibrary:  
$ chmod +r+x libunits.sl  
This library can now be linked with other programs. For example, if you  
have a C program named convert.cthat calls routines from  
libunits.sl, you could compile and link it with the cccommand:  
$ cc -Aa convert.c libunits.sl  
In 32-bit mode, once the executable is created, the library should not be  
moved because the absolute path name of the library is stored in the  
executable. (In 64-bit mode, ./libunit.slis stored in the  
executable.)For details, see Shared Library Location.  
For details on linking shared libraries with your programs, see Chapter  
3, Linker Tasks,” on page 51.  
NOTE  
If you are linking any C++ object files to create an executable or a shared  
library, you must use the CCcommand to link. This ensures that  
c++patchexecutes and chains together your nonlocal static constructors  
and destructors. If you use ld, the library or executable may not work  
correctly and you will probably not get any error messages. For more  
information see the HP C++ Programmer's Guide.  
Sh a r ed Libr a r y Dep en d en cies  
You can specify additional shared libraries on the ldcommand line when  
creating a shared library. The created shared library is said to have a  
d ep en d en cy on the specified libraries, and these libraries are known as  
d ep en d en t libr a r ies or su p p or tin g libr a r ies. When you load a  
library with dependencies, all its dependent libraries are loaded too. For  
example, suppose you create a library named libdep.slusing the  
command:  
$ ld -b -o libdep.sl mod1.o mod2.o -lcurses -lcustom  
140  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
Thereafter, any programs that load libdep.sl— either explicitly with  
shl_loador implicitly with the dynamic loader when the program  
begins execution — also automatically load the dependent libraries  
libcurses.sland libcustom.sl.  
There are two additional issues that may be important to some shared  
library developers:  
When a shared library with dependencies is loaded, in what order are  
the dependent libraries loaded?  
Where are all the dependent libraries placed in relation to other  
already loaded libraries? That is, where are they placed in the  
process's shared library search list used by the dynamic loader?  
Th e Or d er in Wh ich Libr a r ies Ar e Loa d ed (Loa d  
Gr a p h )  
When a shared library with dependencies is loaded, the dynamic loader  
builds a load graph to determine the order in which the dependent  
libraries are loaded.  
For example, suppose you create three libraries — libQ, libD, and libP  
using the ldcommands below. The order in which the libraries are  
built is important because a library must exist before you can specify it  
as a dependent library.  
$ ld -b -o libQ.sl modq.o -lB  
$ ld -b -o libD.sl modd.o -lQ -lB  
$ ld -b -o libP.sl modp.o -lA -lD -lQ  
The dependency lists for these three libraries are:  
libQdepends on libB  
libDdepends on libQand libB  
libPdepends on libA, libD, and libQ  
+-->libA.sl  
|
libP.sl-->libD------+  
|
|
|
v
+-->libQ.sl-->libB.sl  
For 32-bit m od e. The loader uses the following algorithm in 32-bit  
mode:  
Chapter 5  
141  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
ifthe library has not been visited then  
mark the library as visited.  
ifthe library has a dependency list then  
traverse the list in reverse order.  
Place the library at the head of the load list.  
Shown below are the steps taken to form the load graph when libPis  
loaded:  
1. mark P, traverse Q  
2. mark Q, traverse B  
3. mark B, loa d B  
4. loa d Q  
5. traverse D  
6. mark D, traverse B  
7. Bis already marked, so skip B, traverse Q  
8. Qis already marked, so skip Q  
9. loa d D  
10. mark A, loa d A  
11. loa d P  
The resulting load graph is:  
libPlibAlibDlibQlibB  
For 64-bit m od e. The dynamic loader uses the following algorithm in  
64-bit mode:  
ifthe library has not been visited then  
mark the library as visited;  
append the library at the end of the list.  
ifthe library has a dependency list then  
traverse the list in reverse order.  
Shown below are the steps taken to form the load graph when libPis  
loaded:  
1. mark P, loa d P  
2. traverse P  
142  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
3. mark A, loa d A  
4. mark D, loa d D  
5. mark Q, loa d Q  
6. traverse D  
7. Dis already marked, so skip D  
8. traverse Q  
9. Qis already marked, so skip Q  
10. traverse Q  
11. Qis already marked, so skip Q  
12. traverse B  
13. mark B, loa d B  
14. traverse B  
15. Bis already marked, so skip B  
The resulting load graph is:  
libPlibAlibDlibQlibB  
P la cin g Loa d ed Libr a r ies in th e Sea r ch List  
Once a load graph is formed, the libraries must be added to the shared  
library search list, thus binding their symbols to the program. If the  
initial library is an implicitly loaded library (that is, a library that is  
automatically loaded when the program begins execution), the libraries  
in the load graph are appended to the library search list. For example, if  
libPis implicitly loaded, the library search list is:  
<current search list> libPlibAlibDlibQlibB  
The same behavior occurs for libraries that are explicitly loaded with  
shl_load, but without the BIND_FIRSTmodifier (see BIND_FIRST  
Modifier” on page 220 for details). If BIND_FIRSTis specified in the  
shl_loadcall, then the libraries in the load graph are inserted before  
the existing search list. For example, suppose libPis loaded with this  
call:  
lib_handle = shl_load("libP.sl", BIND_IMMEDIATE | BIND_FIRST, 0);  
Then the resulting library search list is:  
Chapter 5  
143  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
libPlibAlibDlibQlibB<current search list>  
Up d a tin g a Sh a r ed Libr a r y  
The ldcommand cannot replace or delete object modules in a shared  
library. Therefore, to update a shared library, you must relink the library  
with all the object files you want the library to include. For example,  
suppose you fix some routines in length.c(from the previous section)  
that were giving incorrect results. To update the libunits.sllibrary to  
include these changes, you would use this series of commands:  
$ cc -Aa -c +z length.c  
$ ld -b -o libunits.sl length.o volume.o mass.o  
Any programs that use this library will now be using the new versions of  
the routines. That is, you do not have to relink any programs that use this  
shared library. This is because the routines in the library are attached to  
the program at run time.  
This is one of the advantages of shared libraries over archive libraries: if  
you change an archive library, you must relink any programs that use  
the archive library. With shared libraries, you need only recreate the  
library.  
In com p a tible Ch a n ges to a Sh a r ed Libr a r y  
If you make incompatible changes to a shared library, you can use library  
versioning to provide both the old and the new routines to ensure that  
programs linked with the old routines continue to work. See Version  
Control with Shared Libraries” for more information on version control  
of shared libraries.  
Sh a r ed Libr a r y Loca tion  
You can place shared libraries in the same locations as archive libraries  
(see Archive Library Location). Again, this is typically  
/usr/local/liband /usr/contrib/lib(32-bit mode) or  
/user/local/lib/pa20_64and /usr/contrib/lib/pa20_64(64  
bit mode) for application libraries, and /usr/lib(32-bit mode) or  
/user/lib/pa20_64(64-bit mode) for system libraries. However, these  
are just suggestions.  
144  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
Prior to the HP-UX 9.0 release, moving a shared library caused any  
programs that were linked with the library to fail when they tried to load  
the library. Prior to 9.0, you were required to relink all applications that  
used the library if the library was moved to a different directory.  
Beginning with the HP-UX 9.0 release, a program can search a list of  
directories at run time for any required libraries. Thus, libraries can be  
moved after an application has been linked with them. To search for  
libraries at run time, a program must know which directories to search.  
There are two ways to specify this directory search information:  
Store a directory path list in the program with the linker option +b  
path_list.  
Link the program with +s, enabling the program to use the path list  
defined by the SHLIB_PATHenvironment variable at run time.  
For 64-bit programs, you can also use the LD_LIBRARY_PATH  
environment variable, and the +soption is enabled by default.  
For details on the use of these options, refer to Moving Libraries after  
Linking with +b” on page 84 and Moving Libraries After Linking with  
+s and SHLIB_PATH” on page 86.  
Im p r ovin g Sh a r ed Libr a r y Per for m a n ce  
This section describes methods you can use to improve the run-time  
performance of shared libraries. If, after using the methods described  
here, you are still not satisfied with the performance of your program  
with shared libraries, try linking with archive libraries instead to see if it  
improves performance. In general, though, archive libraries will not  
provide great performance improvements over shared libraries.  
Usin g P r ofile-Ba sed Op tim iza tion on Sh a r ed Libr a r ies  
You can perform profile-based optimization on your shared libraries to  
improve their performance. See Profile-Based Optimization” on page  
274 for more information.  
Exp or tin g On ly th e Requ ir ed Sym bols  
Normally, all global variables and procedure definitions are exported  
from a shared library. In other words, any procedure or variable defined  
in a shared library is made visible to any code that uses this library. In  
addition, the compilers generate internal” symbols that are exported.  
Chapter 5  
145  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
You may be surprised to find that a shared library exports many more  
symbols than necessary for code that uses the library. These extra  
symbols add to the size of the library's symbol table and can even  
degrade performance (since the dynamic loader has to search a  
larger-than-necessary number of symbols).  
One possible way to improve shared library performance is to export only  
those symbols that need exporting from a library. To control which  
symbols are exported, use either the +eor the -hoption to the ld  
command. When +eoptions are specified, the linker exports only those  
symbols specified by +eoptions. The -hoption causes the linker to hide  
the specified symbols. (For details on using these options, see Hiding  
Symbols with -h” on page 81 and Exporting Symbols with +e” on page  
79.)  
As an example, suppose you've created a shared library that defines the  
procedures init_progand quit_progand the global variable  
prog_state. To ensure that only these symbols are exported from the  
library, specify these options when creating the library:  
+e init_prog +e quit_prog +e prog_state  
If you have to export many symbols, you may find it convenient to use the  
-cfile option, which allows you to specify linker options in file. For  
instance, you could specify the above options in a file named  
export_optsas:  
+e init_prog  
+e quit_prog  
+e prog_state  
Then you would specify the following option on the linker command line:  
-c export_opts  
(For details on the -coption, see Passing Linker Options in a file with  
-c” on page 86.)  
P la cin g Fr equ en tly-Ca lled Rou tin es Togeth er  
When the linker creates a shared library, it places the PIC object  
modules into the library in the order in which they are specified on the  
linker command line. The order in which the modules appear can greatly  
affect performance. For instance, consider the following modules:  
a.o  
Calls routines in c.oheavily, and its routines are  
called frequently by c.o.  
146  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
b.o  
c.o  
A huge module, but contains only error routines that  
are seldom called.  
Contains routines that are called frequently by a.o,  
and calls routines in a.ofrequently.  
If you create a shared library using the following command line, the  
modules will be inserted into the library in alphabetical order:  
$ ld -b -o libabc.sl *.o  
The potential problem with this ordering is that the routines in a.oand  
c.oare spaced far apart in the library. Better virtual memory  
performance could be attained by positioning the modules a.oand c.o  
together in the shared library, followed by the module b.o. The following  
command will do this:  
$ ld -b -o libabc.sl a.o c.o b.o  
One way to help determine the best order to specify the object files is to  
gather profile data for the object modules; modules that are frequently  
called should be grouped together on the command line.  
Another way is to use the lorder(1) and tsort(1) commands. Used together  
on a set of object modules, these commands determine how to order the  
modules so that the linker only needs a single pass to resolve references  
among the modules. A side-effect of this is that modules that call each  
other may be positioned closer together than modules that don't. For  
instance, suppose you have defined the following object modules:  
Module  
a.o  
Calls Routines in Module  
x.oy.o  
x.oy.o  
none  
b.o  
d.o  
e.o  
none  
x.o  
d.o  
y.o  
d.o  
Then the following command determines the one-pass link order:  
$ lorder ?.o | tsort  
Pipe lorder's output to tsort.  
a.o  
b.o  
e.o  
x.o  
Chapter 5  
147  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Creating Shared Libraries  
y.o  
d.o  
Notice that d.ois now closer to x.oand y.o, which call it. However, this  
is still not the best information to use because a.oand b.oare  
separated from x.oand y.oby the module e.o, which is not called by  
any modules. The actual optimal order might be more like this:  
a.o b.o x.o y.o d.o e.o  
Again, the use of lorderand tsortis not perfect, but it may give you  
leads on how to best order the modules. You may want to experiment to  
see what ordering gives the best performance.  
Ma k in g Sh a r ed Libr a r ies Non -Wr ita ble  
You may get an additional performance gain by ensuring that no shared  
libraries have write permissions. Programs that use more than one  
writable library can experience significantly degraded loading time. The  
following chmodcommand gives shared libraries the correct permissions  
for best load-time performance:  
$ chmod 555 libn a m e  
Usin g th e +ESlit Op tion to cc  
Normally, the C compiler places constant data in the data space. If such  
data is used in a shared library, each process will get its own copy of the  
data, in spite of the fact that the data is constant and should not change.  
This can result in some performance degradation.  
To get around this, use the C compiler's +ESlitoption, which places  
constant data in the $LIT$text space (or in 64-bit mode, in a .texttext  
segment) instead of the data space. This results in one copy of the  
constant data being shared among all processes that use the library.  
NOTE  
This option requires that programs not write into constant strings and  
data. In addition, structures with embedded initialized pointers won't  
work because the pointers cannot be relocated since they are in read-only  
$TEXT$space. In this case, the linker outputs the error message  
"Invalid loader fixup needed".  
148  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
Ver sion Con tr ol w ith Sh a r ed Libr a r ies  
HP-UX provides two ways to support incompatible versions of shared  
library routines. Library-Level Versioning” describes how you create  
multiple versions of a shared library. “Intra-Library Versioning”  
describes how a single shared library can have multiple versions of an  
object module. Library-level versioning is recommended over  
intra-library versioning.  
NOTE  
Beginning with HP-UX Release 11.00, the 64-bit linker toolset supports  
only library-level versioning.  
Wh en to Use Sh a r ed Libr a r y Ver sion in g  
For the most part, updates to a shared library should be completely  
upward-compatible; that is, updating a shared library won't usually  
cause problems for programs that use the library. But sometimes — for  
example, if you add a new parameter to a routine — updates cause  
undesirable side-effects in programs that call the old version of the  
routine. In such cases, it is desirable to retain the old version as well as  
the new. This way, old programs will continue to run and new programs  
can use the new version of the routine.  
Here are some guidelines to keep in mind when making changes to a  
library:  
When creating the first version of a shared library, carefully consider  
whether or not you will need versioning. It is easier to use  
library-level versioning from the start.  
When creating the first version of a shared library using intra-library  
versioning, version control is not an issue: The default version  
number is satisfactory.  
When creating future revisions of a library, you must determine when  
a change represents an incompatible change, and thus deserves a new  
version. Some examples of incompatible changes are as follows:  
Chapter 5  
149  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
As a general rule, when an exported function is changed such that  
calls to the function from previously compiled object files should  
not resolve to the new version, the change is incompatible. If the  
new version can be used as a wholesale replacement for the old  
version, the change is compatible.  
For exported data, any change in either the initial value or the  
size represents an incompatible change.  
Any function that is changed to take advantage of an incompatible  
change in another module should be considered incompatible.  
Ma in ta in in g Old Ver sion s of Libr a r y Mod u les  
When using shared library versioning, you need to save the old versions  
of modules in the library:  
With library-level versioning, when an incompatible change is made  
to a module, the entire old version of the library must be retained  
along with the new version.  
With intra-library versioning, when an incompatible change is made  
to a module, all the old versions of the module should be retained  
along with the new version. The new version number should  
correspond to the date the change was made. If several modules are  
changed incompatibly in a library, it is a good idea to give all modules  
the same version date.  
Libr a r y-Level Ver sion in g  
HP-UX 10.0 adds a new library-level versioning scheme that allows you  
to maintain multiple versions of shared libraries when you make  
incompatible changes to the library. By maintaining multiple versions,  
applications linked with the older versions continue to run with the older  
libraries, while new applications link and run with the newest version of  
the library. Library-level versioning is very similar to the library  
versioning on UNIX System V Release 4.  
How to Use Libr a r y-Level Ver sion in g  
To use library-level versioning, follow these steps:  
150  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
1. Name the first version of your shared library with an extension of .0  
(that's the number zero), for example libA.0. Use the +hoption to  
designate the internal name of the library, for example, libA.0:  
ld -b *.o -o libA.0 +h libA.0  
Creates the shared library libA.0.  
2. Since the linker still looks for libraries ending in .slwith the -l  
option, create a symbolic link from the usual name of the library  
ending in .slto the actual library. For example, libA.slpoints to  
libA.0:  
ln -s libA.0 libA.sl  
libA.sl is a symbolic link to libA.0.  
3. Link applications as usual, using the -loption to specify libraries.  
The linker searches for libA.sl, as usual. However, if the library it  
finds has an internal name, the linker places the internal name of the  
library in the executable's shared library dependency list. When you  
run the application, the dynamic loader loads the library named by  
this internal name. For example:  
ld /opt/langtools/lib/crt0.o prog.o -lA -lc Binds a.out with libA.0.  
Cr ea tin g a New, In com p a tible Ver sion of th e Libr a r y  
When you create a new version of the library with incompatible changes,  
repeat the above steps except increment the number in the suffix of the  
shared library file name. That is, create libA.1rather than libA.0and  
set the symbolic link libA.slto point to libA.1. Applications linked  
with libA.0continue to run with that library while new applications  
link and run with libA.1. Continue to increment the suffix number for  
subsequent incompatible versions, for example libA.2, libA.3, and so  
forth.  
Migr a tin g a n Existin g Libr a r y to Use Libr a r y-Level  
Ver sion in g  
If you have an existing library you can start using library-level  
versioning. First rename the existing library to have the extension .0.  
Then create the new version of the library with the extension .1and an  
internal name using the .1extension. Create a symbolic link with the  
extension .slto point to the .1library.  
Chapter 5  
151  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
When you run a program that uses shared libraries and was linked  
before HP-UX 10.0, the dynamic loader first attempts to open the shared  
library ending in .0. If it cannot find that library, it attempts to open the  
library ending in .sl.  
Th e +h Op tion a n d In ter n a l Na m es  
The +hoption gives a library an internal name for library-level  
versioning. Use +hto create versioned libraries:  
+h internal_name  
internal_name is typically the same name as the library file itself, for  
example libA.1as in +h libA.1. When you link with a library that  
has an internal name, the linker puts the internal_name in the shared  
library dependency list of the executable or shared library being created.  
When running the resulting executable or shared library, it is the library  
named by this internal name that the dynamic loader loads.  
You can include a relative or absolute path with the internal name, but  
you must ensure the dynamic loader can find the library from this name  
using its normal search process.  
For 32-bit mode, if internal_name includes a relative path (that is, a path  
not starting with /), the internal name stored by the linker is the  
concatenation of the actual path where the library was found and  
internal_name, including the relative path. When the resulting program  
is run, if the dynamic loader cannot find the library at this location, the  
program will not run.  
If internal_name includes an absolute path (that is, a path starting with  
/), the internal name stored by the linker is simply the internal_name,  
including the absolute path. When the resulting program is run, if the  
dynamic loader cannot find the library at this location, the program will  
not run.  
For 64-bit mode, see Internal Name Processing” for more information.  
File System Lin k s to Sh a r ed Libr a r ies  
This section discusses the situation where you have used the ln(1)  
command to create file system links to shared library files. For example:  
$ ld -b -o /X/libapp.sl *.o  
Create shared library.  
$ ln -s /X/libapp.sl /tmp/libmine.sl Make the link.  
152  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
Figu r e 5-5  
During a link, the linker records the file name of the opened library in  
the shared library list of the output file. However, if the shared library is  
a file system link to the actual library, the linker does not record the  
name of the library the file system link points to. Rather it records the  
name of the file system link.  
For example, if /tmp/libmine.slis a file system link to  
/X/libapp.sl, the following command records /tmp/libmine.slin  
a.out, not /X/libapp.slas might be expected:  
$ ld /opt/langtools/lib/crt0.o main.o -L /tmp -lmine -lc  
To use library-level versioning in this situation, you must set up  
corresponding file system links to make sure older applications linked  
with the older libraries run with these libraries. Otherwise, older  
applications could end up running with newer shared libraries. In  
addition, you must include the absolute path name in the internal name  
of the new library.  
For example, in 32-bit mode, to make the above example work correctly  
with library-level versioning, first implement library-level versioning  
with the actual library /X/libapp.sland include the absolute path in  
the internal name of the new library:  
$ mv /X/libapp.sl /X/libapp.0  
$ ld -b -o /X/libapp.1 +h /X/libapp.1 *.o  
$ ln -s /X/libapp.1 /X/libapp.sl  
Rename old version.  
Create new version.  
Set up symbolic link.  
Then set up the corresponding file system links:  
$ ln -s /X/libapp.0 /tmp/libmine.0  
$ ln -s /X/libapp.1 /tmp/libmine.1  
$ rm /tmp/libmine.sl  
Link to old version.  
Link to new version.  
Remove old link.  
$ ln -s /X/libapp.sl /tmp/libmine.sl Link to the link.  
Chapter 5  
153  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
Figu r e 5-6  
With these links in place, the loader will load /X/libapp.0when  
running the a.outfile created above. New applications will link and run  
with /X/libapp.1.  
NOTE  
Renaming the old version of the .0version library only works for 32-bit  
mode.  
For 64-bit mode programs, the dynamic loader only loads the library  
recorded in the dynamic load table. You should use library-lever  
versioning and create your 64-bit shared library with an internal name  
unless the library will not be versioned in the future.  
Usin g sh l_loa d (3X) w ith Libr a r y-Level Ver sion in g  
Once library level versioning is used, calls to shl_load(3X) should specify  
the actual version of the library to be loaded. For example, if libA.slis  
now a symbolic link to libA.1, then calls to dynamically load this  
library should specify the latest version available when the application is  
compiled as shown below:  
shl_load("libA.1", BIND_DEFERRED, 0);  
This insures that when the application is migrated to a system that has  
a later version of libAavailable, the actual version desired is the one  
that is dynamically loaded.  
In tr a -Libr a r y Ver sion in g  
Intra-library versioning is a second method of maintaining multiple  
incompatible versions of shared library routines. Library-level  
versioning is recommended over intra-library versioning.  
This section provides information on the following topics:  
The Version Number Compiler Directive”  
154  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
Shared Library Dependencies and Version Control”  
Adding New Versions to a Shared Library”  
Specifying a Version Date”  
Th e Ver sion Nu m ber Com p iler Dir ective  
With intra-library versioning, you assign a ver sion n u m ber to any  
module in a shared library. The version number applies to all global  
symbols defined in the module's source file. The version number is a date,  
specified with a compiler directive in the source file. The syntax of the  
version number directive depends on the language:  
C and C++:  
FORTRAN:  
Pascal:  
#pragma HP_SHLIB_VERSION"date"  
$SHLIB_VERSION 'date'  
$SHLIB_VERSION 'date'$  
The date argument in all three directives is of the form month/year. The  
month must be 1through 12, corresponding to January through  
December. The year can be specified as either the last two digits of the  
year (94for 1994) or a full year specification (1994). Two-digit year codes  
from 00through 40represent the years 2000 through 2040.  
This directive should only be used if incompatible changes are made to a  
source file. If a version number directive is not present in a source file,  
the version number of all symbols defined in the object module defaults  
to 1/90.  
Sh a r ed Libr a r y Dep en d en cies a n d Ver sion Con tr ol  
A shared library as a whole can be thought of as having a version  
number itself. This version number is the most recent of the versioned  
symbols in the library and any dependent libraries.  
When a shared library is built with a dependent shared library, the  
version number of the dependent library used during the link is recorded  
with the dependency.  
When shl_load(3X) is called to load a shared library, the latest version of  
the library is loaded. If that library has dependencies, the dynamic  
loader (dld.sl(5)) will load the versions of the dependent libraries that  
were recorded in the dependency list. Note that these are not necessarily  
the most recent versions of the dependent libraries. When dld.slloads  
a particular version of a shared library, it will load the same version of  
any dependent libraries.  
Chapter 5  
155  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
If a shared library lists a second shared library as a dependency, dld.sl  
will generate an error if the second shared library has a version number  
which is older than the version number recorded with the dependency.  
This means that the first library was built using a more recent version of  
the second library than the version that dld.slcurrently finds.  
Ad d in g New Ver sion s to a Sh a r ed Libr a r y  
To rebuild a shared library with new versions of object files, run ldagain  
with the newly compiled object files. For example, suppose you want to  
add new functionality to the routines in length.c, making them  
incompatible with existing programs that call libunits.sl. Before  
making the changes, make a copy of the existing length.cand name it  
oldlength.c. Then change the routines in length.cwith the version  
directive specifying the current month and date. The following shows the  
new length.cfile:  
#pragma HP_SHLIB_VERSION "11/93" /* date is November 1993 */  
/*  
* New version of "in_to_cm" also returns a character string  
* "cmstr" with the converted value in ASCII form.  
*/  
float  
/
{
in_to_cm(float in, char *cmstr)  
/* convert in to cm *  
. . .  
/* build "cmstr" */  
return(in * 2.54);  
}
. . . /* other length conversion routines */  
To update libunits.slto include the new length.croutines, copy the  
old version of length.oto oldlength.o; then compile length.cand  
rebuild the library with the new length.oand oldlength.o:  
$ cp length.c oldlength.c  
$ mv length.o oldlength.o  
. . .  
$ cc -Aa -c +z length.c  
$ ld -b -o libunits.sl oldlength.o \  
Save the old source.  
Save old length.o.  
Make new length.c.  
Make new length.o.  
Relink the library.  
volume.o mass.o length.o  
Thereafter, any programs linked with libunits.sluse the new  
versions of length-conversion routines defined in length.o. Programs  
linked with the old version of the library still use those routines from  
oldlength.o. For details on linking with shared libraries, see Chapter  
3, Linker Tasks,” on page 51.  
156  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Version Control with Shared Libraries  
Sp ecifyin g a Ver sion Da te  
When adding modules to a library for a particular release of the library,  
it is best to give all modules the same version date. For example, if you  
complete file1.oon 04/93, file2.oon 05/93, and file3.oon 07/93, it  
would be best to give all the modules the same version date, say 07/93.  
The reason for doing this is best illustrated with an example. Suppose in  
the previous example you gave each module a version date corresponding  
to the date it was completed: 04/93 for file1.o, 05/93 for file2.o, and  
07/93 for file3.o. You then build the final library on 07/93 and link an  
application a.outwith the library. Now suppose that you introduce an  
incompatible change to function foofound in file1.o, set the version  
date to 05/93, and rebuild the library. If you run a.outwith the new  
version of the library, a.outwill get the new, incompatible version of  
foobecause its version date is still earlier than the date the application  
was linked with the original library!  
Chapter 5  
157  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Switching from Archive to Shared Libraries  
Sw itch in g fr om Ar ch ive to Sh a r ed  
Libr a r ies  
There are cases where a program may behave differently when linked  
with shared libraries than when linked with archive libraries. These are  
the result of subtle differences in the algorithms the linker uses to  
resolve symbols and combine object modules. This section covers these  
considerations. (See also Caution When Mixing Shared and Archive  
Libraries.)  
Libr a r y Pa th Na m es  
As discussed previously, in 32-bit mode, ldrecords the absolute path  
names of any shared libraries searched at link time in the a.outfile.  
When the program begins execution, the dynamic loader attaches any  
shared libraries that were specified at link time. Therefore, you must  
ensure that any libraries specified at link time are also present in the  
same location at run time.  
For 64-bit naming, see Internal Name Processing” for more information.  
Relyin g on Un d ocu m en ted Lin k er Beh a vior  
Occasionally, programmers may take advantage of linker behavior that  
is undocumented but has traditionally worked. With shared libraries,  
such programming practices might not work or may produce different  
results. If the old behavior is absolutely necessary, linking with archive  
libraries only (-a archive) produces the old behavior.  
For example, suppose several definitions and references of a symbol exist  
in different object and archive library files. By specifying the files in a  
particular link order, you could cause the linker to use one definition over  
another. But doing so requires an understanding of the subtle (and  
undocumented) symbol resolution rules used by the linker, and these  
rules are slightly different for shared libraries. So makefiles or shell  
scripts that took advantage of such linker behavior prior to the support  
of shared libraries may not work as expected with shared libraries.  
158  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Switching from Archive to Shared Libraries  
More commonly, programmers may take advantage of undocumented  
linker behavior to minimize the size of routines copied into the a.out  
files from archive libraries. This is no longer necessary if all libraries are  
shared.  
Although it is impossible to characterize the new resolution rules exactly,  
the following rules always apply:  
If a symbol is defined in two shared libraries, the definition used at  
run time is the one that appeared first, regardless of where the  
reference was.  
The linker treats shared libraries more like object files.  
As a consequence of the second rule, programs that call wrapper libraries  
may become larger. (A w r a p p er libr a r y is a library that contains  
alternate versions of C library functions, each of which performs some  
bookkeeping and then calls the actual C function. For example, each  
function in the wrapper library might update a counter of how many  
times the actual C routine is called.) With archive libraries, if the  
program references only one routine in the wrapper library, then only the  
wrapper routine and the corresponding routine from the C library are  
copied into the a.outfile. If, on the other hand, a shared wrapper library  
and archive C library are specified, in that order, then all routines that  
can be referenced by any routine in the wrapper library are copied from  
the C library. To avoid this, link with archive or shared versions for both  
the wrapper library and C library, or use an archive version of the  
wrapper library and a shared version of the C library.  
Absolu te Vir tu a l Ad d r esses  
Writing code that relies on the linker to locate a symbol in a particular  
location or in a particular order in relation to other symbols is known as  
making an im p licit a d d r ess d ep en d en cy. Because of the nature of  
shared libraries, the linker cannot always preserve the exact ordering of  
symbols declared in shared libraries. In particular, variables declared in  
a shared library may be located far from the main program's virtual  
address space, and they may not reside in the same relative order within  
the library as they were linked. Therefore, code that has implicit address  
dependencies may not work as expected with shared libraries.  
An example of an implicit address dependency is a function that assumes  
that two global variables that were defined adjacently in the source code  
will actually be adjacent in virtual memory. Since the linker may  
Chapter 5  
159  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Switching from Archive to Shared Libraries  
rearrange data in shared libraries, this is no longer guaranteed. Another  
example is a function that assumes variables it declares statically (for  
example, C staticvariables) reside below the reserved symbol _endin  
memory (see end(3)). In general, it is a bad idea to depend on the relative  
addresses of global variables, because the linker may move them around.  
In assembly language, using the address of a label to calculate the size of  
the immediately preceding data structure is not affected: the assemblers  
still calculate the size correctly.  
Sta ck Usa ge  
To load shared libraries, a program must have a copy of the dynamic  
loader (dld.sl) mapped into its address space. This copy of the dynamic  
loader shares the stack with the program. The dynamic loader uses the  
stack during startup and whenever a program calls a shared library  
routine for the first time. If you specify -B immediate, the dynamic  
loader uses the stack at startup only.  
NOTE  
For 32-bit mode only:  
Although it is not recommended programming practice, some programs  
may use stack space above” the program's current stack. To preserve the  
contents above” the program's logical top of the stack, the dynamic  
loader attempts to use stack space far away from program's stack  
pointer. If a program is doing its own stack manipulations, such as those  
implemented by a threads” package, the dynamic loader may  
inadvertently use stack space that the program had reserved for another  
thread. Programs doing such stack manipulations should link with  
archive libraries, or at least use immediate binding, if this could  
potentially cause problems.  
Also be aware that if a program sets its stack pointer to memory  
allocated in the heap, the dynamic loader may use the space directly  
above” the top of this stack when deferred binding of symbols is used.  
Ver sion Con tr ol  
You can maintain multiple versions of a shared library using  
library-level versioning. This allows you to make incompatible changes  
to shared libraries and ensure programs linked with the older versions  
continue to run. (See Library-Level Versioning” for more information.)  
160  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Switching from Archive to Shared Libraries  
Debu gger Lim ita tion s  
Shared libraries can be debugged just like archive libraries with few  
exceptions. For details on debugging shared libraries, refer to the  
HP/ DDE Debugger User's Guide or the HP-UX Symbolic Debugger  
User's Guide.  
Usin g th e ch r oot Com m a n d w ith Sh a r ed  
Libr a r ies  
Some users may use the chrootsuper-user command when developing  
and using shared libraries. This affects the path name that the linker  
stores in the executable file. For example, if you chrootto the directory  
/users/hyperturboand develop an application there that uses the  
shared library libhype.slin the same directory, ldrecords the path  
name of the library as /libhype.sl. If you then exit from the chrooted  
directory and attempt to run the application, the dynamic loader won't  
find the shared library because it is actually stored in  
/users/hyperturbo/libhype.sl, not in /libhype.sl.  
Conversely, if you move a program that uses shared libraries into a  
chrooted environment, you must have a copy of the dynamic loader,  
dld.sl, and all required shared libraries in the correct locations.  
P r ofilin g Lim ita tion s  
Profiling with the prof(1) and gprof(1) commands and the monitor  
library function is only possible on a contiguous chunk of the main  
program (a.out). Since shared libraries are not contiguous with the  
main program in virtual memory, they cannot be profiled. You can still  
profile the main program, though. If profiling of libraries is required,  
relink the application with the archive version of the library, using the  
-a archiveoption.  
Chapter 5  
161  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Summary of HP-UX Libraries  
Su m m a r y of HP -UX Libr a r ies  
What libraries your system has depends on what components were  
purchased. For example, if you didn't purchase Starbase Display List,  
you won't have the Starbase Display List library on your system.  
HP-UX library routines are described in detail in sections 2 and 3 of the  
HP-UX Reference. Routines in section 2 are known as system ca lls,  
because they provide low-level system services; they are found in libc.  
Routines in section 3 are other higher-level” library routines and are  
found in several different libraries including libc.  
Each library routine, or group of library routines, is documented on a  
m a n p a ge. Man pages are sorted alphabetically by routine name and  
have the general form routine(nL), where:  
routine  
is the name of the routine, or group of closely related  
routines, being documented.  
n
is the HP-UX Reference section number: 2 for system  
calls, 3 for other library routines.  
L
is a letter designating the library in which the routine  
is stored.  
For example, the printf(3S) man page describes the standard  
input/output libcroutines printf, nl_printf, fprintf,  
nl_fprintf, sprintf, and nl_sprintf. And the pipe(2) man page  
describes the pipesystem call.  
The major library groups defined in the HP-UX Reference are shown  
below:  
NOTE  
Certain language-specific libraries are not documented in the HP-UX  
Reference; instead, they are documented with the appropriate language  
documentation. For example, all FORTRAN intrinsics (MAX, MOD, and so  
forth) are documented in the HP FORTRAN/ 9000 Programmer's  
Reference.  
Group  
Description  
162  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Summary of HP-UX Libraries  
(2)  
These functions are known as system calls. They  
provide low-level access to operating system services,  
such as opening files, setting up signal handlers, and  
process control. These routines are located in libc.  
(3C)  
(3S)  
These are standard C library routines located in libc.  
These functions comprise the Standard input/output  
routines (see stdio(3S)). They are located in libc.  
(3M)  
These functions comprise the Math library. The linker  
searches this library under the -lmoption (for the  
SVID math library) or the -lMoption (for the POSIX  
math library).  
(3G)  
(3I)  
These functions comprise the Graphics library.  
These functions comprise the Instrument support  
library.  
(3X)  
Various specialized libraries. The names of the  
libraries in which these routines reside are  
documented on the man page.  
The routines marked by (2), (3C), and (3S) comprise the standard C  
library libc. The C, C++, FORTRAN, and Pascal compilers  
automatically link with this library when creating an executable  
program.  
For more information on these libraries, see C, A Reference Manual by  
Samual P. Harbison and Guy L. Steele J r., published in 1991 by  
Prentice-Hall, or UNIX System V Libraries by Baird Peterson, published  
in 1992 by Van Nostrand Reinhold, or C Programming for UNIX by John  
Valley, published in 1992 by Sams Publishing. For more information on  
system calls see Advanced UNIX Programming by Marc J. Rochkind,  
published in 1985 by Prentice-Hall or Advanced Programming in the  
UNIX Environment by W. Richard Stevens, published in 1992 by  
Addison-Wesley.  
Chapter 5  
163  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Ca u tion Wh en Mixin g Sh a r ed a n d  
Ar ch ive Libr a r ies  
Mixing shared and archive libraries in an application is not  
recommended and should be avoided. That is, an application should use  
only shared libraries or only archive libraries.  
Mixing shared and archive libraries can lead to unsatisfied symbols,  
hidden definitions, and duplicate definitions and cause an application to  
abort or exhibit incorrect behavior at run time. The following examples  
illustrate some of these problems.  
Exa m p le 1: Un sa tisfied Sym bols  
This example (in 32-bit and 64-bit +compatmode) shows how mixing  
shared and archive libraries can cause a program to abort. Suppose you  
have a main program, main(), and three functions, f1(), f2(), and  
f3()each in a separate source file. main()calls f1()and f3()but not  
f2():  
$ cc -c main.c f1.c f2.c  
$ cc -c +z f3.c  
Compile to relocatable object code.  
Compile to position-independent code  
Figu r e 5-7  
Next suppose you put f3.ointo the shared library lib3.sland f1.o  
and f2.ointo the archive library lib12.a:  
$ ld -b -o lib3.sl f3.o  
Create a shared library.  
$ ar qvc lib12.a f1.o f2.o Create an archive library.  
164  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-8  
Now link the main with the libraries and create the executable a.out:  
$ cc main.o lib12.a lib3.sl  
.
Link the program  
Figu r e 5-9  
When you run a.out, it runs correctly. Now suppose you need to modify  
f3()to call f2():  
Chapter 5  
165  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-10  
Compile the new f3()and rebuild the shared library lib3.sl:  
$ cc -c +z f3.c  
Compile to relocatable code  
.$ ld -b -o lib3.sl f3.o Create a new shared library.  
Figu r e 5-11  
P r oblem  
Here's where the problem can occur. If you do not relink the application,  
main.o, and just run a.outwith the new version of lib3.sl, the  
program will abort since f2()is not available in the application. The  
reference to f2()from f3()remains unsatisfied, producing an error in  
32-bit mode:  
166  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-12  
$ a.out  
/usr/lib/dld.sl: Unresolved symbol: f2 (code) from  
/users/steve/dev/lib3.sl  
Abort(coredump)  
Exa m p le 2: Usin g sh l_loa d (3X)  
This example (in 32-bit and 64-bit +compatmode shows how mixing  
archive libraries and shared libraries using shl_load(3X) can lead to  
unsatisfied symbols and cause a program to abort.  
If a library being loaded depends on a definition that does not exist in the  
application or any of the dependent shared libraries, the application will  
abort with an unsatisfied definition at run time. This seems obvious  
enough when an application is first created. However, over time, as the  
shared libraries evolve, new symbol imports may be introduced that were  
not originally anticipated. This problem can be avoided by ensuring that  
shared libraries maintain accurate dependency lists.  
Suppose you have a main program, main(), and three functions, f1(),  
f2(), and f3()each in a separate source file. main()calls f1()and  
uses shl_load()to call f3(). main()does not call f2():  
$ cc -c main.c f1.c f2.c Compile to relocatable object code  
$ cc -c +z f3.c  
Compile to position-independent code  
Chapter 5  
167  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-13  
Next suppose you put f3.ointo the shared library lib3.sland f1.o  
and f2.ointo the archive library lib12.a:  
$ ld -b -o lib3.sl f3.o  
Create a shared library.  
$ ar qvc lib12.a f1.o f2.o Create an archive library.  
Figu r e 5-14  
Now link the main with the archive library and create the executable  
a.out:  
$ cc main.o lib12.a -ldld  
Link the program.  
168  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-15  
When you run a.out, it runs correctly. Now suppose you need to modify  
f3()to call f2():  
Figu r e 5-16  
P r oblem  
Here is where a problem can be introduced. If you compile the new f3()  
and rebuild the shared library lib3.slwithout specifying the  
dependency on a shared library containing f2(), calls to f3()will abort.  
$ cc -c +z f3.c  
$ ld -b -o lib3.sl f3.o  
Compile to position-independent code.  
Error! Missing library containing f2().  
Chapter 5  
169  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-17  
Here's where the problem shows up. If you do not relink the application,  
main.o, and just run a.outwith the new version of lib3.sl, the  
program will abort since f2()is not available in the program's address  
space. The reference to f2()from f3()remains unsatisfied, generating  
the 32-bit error message:  
Figu r e 5-18  
$ a.out  
Illegal instruction (coredump)  
170  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Exa m p le 3: Hid d en Defin ition s  
This example shows how mixing archive libraries and shared libraries  
can lead to multiple definitions in the application and unexpected  
results. If one of the definitions happens to be a data symbol, the results  
can be catastrophic. If any of the definitions are code symbols, different  
versions of the same routine could end up being used in the application.  
This could lead to incompatibilities.  
Duplicate definitions can occur when a dependent shared library is  
updated to refer to a symbol contained in the program file but not visible  
to the shared library. The new symbol import must be satisfied somehow  
by either adding the symbol to the library or by updating the shared  
library dependency list. Otherwise the application must be relinked.  
Using an archive version of libcin an application using shared libraries  
is the most common cause of duplicate definitions. Remember that  
symbols not referenced by a shared library at link time will not be  
exported by default.  
NOTE  
Duplicate definitions can be avoided if any or all symbols that may be  
referenced by a shared library are exported from the application at link  
time. Shared libraries always reference the first occurrence of a  
definition. In the following example the first definition is in the  
executable file, a.out. See the -Eoption and +esymbol option described  
in ld(1) and Exporting Symbols from main with -E” on page 81,  
Exporting Symbols with +ee” on page 81, and Exporting Symbols with  
+e” on page 79.  
The following example illustrates this situation. Suppose you have a  
main program, main(), and three functions, f1(), f2(), and f3()each  
in a separate source file. main()calls f1(), f2(), and f3().  
$ cc -c main.c  
$ cc -c +z f1.c f2.c f3.c  
Compile to relocatable code.  
Compile to position-independent code.  
Chapter 5  
171  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-19  
Next suppose you put f3.ointo the shared library lib3.sland f1.o  
and f2.ointo the archive library lib12.a. Also put f1.oand f2.ointo  
the shared library lib12.sl:  
$ ld -b -o lib3.sl f3.o  
$ ld -b -o lib12.sl f1.o f2.o Create a shared library.  
$ ar qvc lib12.a f1.o f2.o Create an archive library.  
Create a shared library.  
Figu r e 5-20  
Now link the main with the archive library lib12.aand the shared  
library lib3.sland create the executable a.out:  
$ cc main.o lib12.a lib3.sl  
Link the program.  
172  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-21  
When you run a.out, it runs correctly. Now suppose you need to modify  
f3()to call f2():  
Figu r e 5-22  
Compile the new f3()and rebuild the shared library lib3.sl,  
including the new dependency on f2()in lib12.sl:  
$ cc -c +z f3.c  
Compile to PIC.  
$ ld -b -o lib3.sl f3.o -L . -l12  
Create library with dependency.  
Chapter 5  
173  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-23  
P r oblem  
Here's where the problem can occur in 32-bit and 64-bit +compatmodes.  
If you do not relink the application, main.o, and just run a.outwith the  
new version of lib3.sl, the program will execute successfully, but it  
will execute two different versions of f2(). main()calls f2()in the  
program file a.outand f3()calls f2()in lib12.sl. Even though  
f2()is contained within the application, it is not visible to the shared  
library, lib3.sl.  
174  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Caution When Mixing Shared and Archive Libraries  
Figu r e 5-24  
Su m m a r y of Mixin g Sh a r ed a n d Ar ch ive  
Libr a r ies  
Applications that depend on shared libraries should not use archive  
libraries to satisfy symbol imports in a shared library. This suggests that  
only a shared version of libcshould be used in applications using  
shared libraries. If an archive version of a dependent library must be  
used, all of its definitions should be explicitly exported with the -Eor +e  
options to the linker to avoid multiple definitions.  
Providers of shared libraries should make every effort to prevent these  
kinds of problems. In particular, if a shared library provider allows  
unsatisfied symbols to be satisfied by an archive version of libc, the  
application that uses the library may fail if the shared library is later  
updated and any new libcdependencies are introduced. New  
dependencies in shared libraries can be satisfied by maintaining  
accurate dependency lists. However, this can lead to multiple  
occurrences of the same definition in an application if the definitions are  
not explicitly exported.  
Chapter 5  
175  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
Usin g Sh a r ed Libr a r ies in 64-bit m od e  
In the HP-UX 11.00 release, HP provides an industry-standard linker  
toolset for programs linked in 64-bit mode. The new toolset consists of a  
linker, dynamic loader, object file class library, and an object file tool  
collection. Although compatibility between the current and previous  
toolset is an important goal, some differences exist between these  
toolsets.  
The 64-bit mode linker toolset introduces different types of shared  
libraries. (In SVR4 Unix, shared libraries are sometimes called d lls.)  
Com p a tibility m od e sh a r ed libr a r y: Using the 64-bit mode linker,  
a compatibility mode shared library is basically a library built with  
ld -b +compatthat has dependent shared libraries. The +compat  
option affects the way the linker and loader search for dependent  
libraries of a shared library and records their names.  
Sta n d a r d m od e sh a r ed libr a r y: A standard mode shared library is  
a library built with ld -bor ld -b +stdwith dependent shared  
libraries.  
NOTE  
If you specify ld -b +compatwith no dependent libraries, you create a  
shared library that has no mode —neither compatibility mode nor  
standard mode.  
The linker handles these libraries in different way with regard to  
internal naming and library search modes.  
In ter n a l Na m e P r ocessin g  
For both 32-bit mode and 64-bit mode, you specify shared library internal  
names using ld +h name However, their dependent libraries’ internal  
names may not be recorded the same way in a standard mode link.  
In an ld +compatlink, the linker treats the internal names like it does  
in 32-bit mode:  
If the dependent librarys internal name is rooted (starts with /”), it  
is inserted as is in the DT_HP_NEEDEDentry. If it was specified with  
-l, the dynamic path bit is set to TRUEin the DT_HP_NEEDEDentry.  
176  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
If the dependent librarys internal name contains a relative path, the  
internal name is inserted at the end of the path where the shared  
library is found at link time, replacing the librarys lename in the  
DT_HP_NEEDEDentry. If the library is specified with -l, the dynamic  
path bit is set to TRUE.  
If the dependent librarys internal name contains no path, it is  
inserted at the end of the path where the shared library is found at  
link time, replacing the librarys lename. If the library is specified  
with -l, the dynamic path bit is set to TRUE.  
If the dependent shared library does not have an internal name, the  
path where the library is found and the library filename is recorded  
in the DT_HP_NEEDEDentry. If specified with -l, the dynamic path  
bit is set to TRUE.  
If the shared libraries are specified with a relative or no path in this  
mode, the linker expands the current working directory when  
constructing the DT_HP_NEEDEDentry. So instead of getting  
something like ./libdk.sl, you get /home/your_dir/libdk.sl.  
All DT_HP_NEEDEDentries with the dynamic path bit set are subject  
to dynamic path lookup.  
In standard mode, the linker treats shared library names as follows:  
If the dependent shared library has an internal name, it is recorded  
in the DT_NEEDEDentry.  
otherwise  
If the dependent shared library is specified with the -lor -l:  
option, only the libname.ext is recorded in the DT_NEEDEDentry.  
otherwise  
The path of the dependent shared library as seen on the link line is  
recorded in the DT_NEEDEDentry.  
All DT_NEEDEDentries with no "/" in the libname are subject to  
dynamic path lookup.  
Dyn a m ic Pa th Sea r ch in g for Sh a r ed Libr a r ies  
In the 64-bit mode of the linker toolset (selected by default or with the  
+stdoption), any library whose name has no "/" character in it becomes  
a candidate for dynamic path searching. Also, the linker always uses the  
Chapter 5  
177  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
LD_LIBRARY_PATHand the SHLIB_PATHenvironment variable to add  
directories to the run time search path for shared libraries, unless the ld  
+noenvvaroption is set.  
In the 32-bit mode of the linker toolset (selected by the +compat option),  
the linker enables run-time dynamic path searching when you link a  
program with the -llibrary and +bpath_name options. Or, you can use  
the -llibrary option with the +spath_name option. When programs are  
linked with +s, the dynamic loader searches directories specified by the  
SHLIB_PATHenvironment variable to find shared libraries.  
The following example shows dynamic path searching changes for 64-bit  
mode.  
ld /opt/langtools/lib/crt0.o main.o \ Subject to  
-lfoo -o main  
dynamic path searching.  
In 32-bit mode, mainaborts at run time if libfoo.slis moved from its  
standard location, /usr/libor /usr/ccs/lib. The linker does not do  
dynamic path searching unless you specify the +b or +s options to the ld  
or chatr commands. In 64-bit mode, the dynamic loader searches for  
libfoo.slin the directories specified by the LD_LIBRARY_PATHand  
SHLIB_PATHenvironment variables.  
Sh a r ed Libr a r y Sym bol Bin d in g Sem a n tics  
Symbol binding resolution, both at link time and run time, changes  
slightly in the 64-bit mode HP-UX linker toolset. The symbol binding  
policy is more compatible with other open systems.  
This section covers the following topics:  
Link-time symbol resolution in shared libraries  
Resolution of unsatisfied shared library references  
Promotion of uninitialized global variables  
Symbol searching in dependent libraries  
Lin k -Tim e Sym bol Resolu tion in Sh a r ed Libr a r ies  
In the 64-bit mode of the linker toolset, the linker remembers all symbols  
in a shared library for the duration of the link. Global definitions satisfy  
trailing references, and unsatisfied symbols remaining in shared  
libraries are reported.  
178  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
The 32-bit mode linker does not remember the definition of a procedure  
in a shared library unless it was referenced in previously scanned object  
files.  
If you have function names that are duplicated in a shared and archive  
library, the 64-bit mode linker may reference a different version of a  
procedure than is referenced by the 32-bit mode linker. This change can  
lead to unexpected results.  
For example, given these source files:  
sharedlib.c  
void afunc()  
{
printf("\tin SHARED library procedure 'afunc'\n");  
}
unsat.c  
void bfunc()  
{
afunc();  
}
archive.c  
void afunc()  
{
printf ("\tin ARCHIVE library procedure 'afunc'\n");  
}
main.c  
main()  
{
bfunc();  
}
If these files are compiled and linked as:  
cc -c main.c unsat.c archive.c  
cc -c +z sharedlib.c  
ld -b sharedlib.o -o libA.sl  
ar rv libB.a archive.o  
cc main.o libA.sl unsat.o libB.a -o test1  
The 32-bit linker toolset produces:  
$ test1  
in ARCHIVE library procedure `afunc'  
Chapter 5  
179  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
At link time, there is an outstanding unsatisfied symbol for afunc()  
when libBis found. The exported symbol for afunc()is not  
remembered after libA.slis scanned. At run time, the afunc()symbol  
that is called is the one that came from the archive library, which resides  
in test1.  
The 64-bit mode linker toolset produces:  
$ test1  
in SHARED library procedure `afunc'  
The 64-bit mode linker remembers the symbol for afunc(), and  
archive.owill not be pulled out of libB.a. The shared library version  
of afuncis called during execution. This behavior is consistent with  
other SVR4 systems.  
Resolu tion of Un sa tisfied Sh a r ed Libr a r y Refer en ces  
In the 64-bit mode linker toolset, the dynamic loader requires that all  
symbols referenced by all loaded libraries be satisfied at the appropriate  
time. This is consistent with other SVR4 systems.  
The 32-bit mode linker toolset accepts unresolved symbols in some cases.  
For example, if an entry point defined in an object file is never reachable  
from the main program file, the unresolved symbol is allowed. You can  
use the +vshlibunsatslinker option to find unresolved symbols in  
shared libraries.  
For example, given these source files:  
lib1.c  
void a()  
{
}
lib2.c  
extern int unsat;  
void b()  
{
unsat = 14;  
}
main.c  
main()  
{
a();  
}
180  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
If these files are compiled and linked as:  
cc -c main.c  
cc -c +z lib1.c lib2.c  
ld -b lib1.o lib2.o -o liba.sl  
cc main.o liba.sl -o test2  
Using the 32-bit mode linker, test2executes without error. The module  
in liba.slcreated from lib2.ois determined to be unreachable  
during execution, so the global symbol for unsat(in lib2.o) is not  
bound.  
The 64-bit mode linker toolset reports an unsatisfied symbol error for  
unsatat link time or at run time if the program were made executable.  
P r om otion of Un in itia lized Globa l Da ta Item s  
In the 64-bit mode linker toolset, the linker expands and promotes  
uninitialized global data symbols in object files linked into a shared  
library to global data objects, exactly like executable files. This is  
standard with other SVR4 systems.  
The result of this change is that load-time symbol resolution for one of  
these objects stops at the first one encountered, instead of continuing  
through all loaded libraries to see if an initialized data object exists.  
For example, given these source files:  
a.c  
int object;  
void a()  
{
/* Uninitialized global data symbol */  
printf ("\tobject is %d\n", object);  
}
b.c  
int object =1; /* Initialized global data symbol */  
void b()  
{
}
main.c  
main()  
{
a();  
}
If these files are compiled and linked as:  
Chapter 5  
181  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
cc -c main.c  
cc -c +z a.c b.c  
ld -b a.o -o libA.sl  
ld -b b.o -o libB.sl  
cc main.o libA.sl libB.sl -o test3  
The 32-bit mode linker toolset produces:  
$ test3  
object is 1  
The 32-bit mode linker toolset defines the objectglobal variable in  
libA.slas a stor a ge exp or t sym bol. The dynamic loader, when  
searching for a definition of objectto satisfy the import request in  
libA.sl, does not stop with the storage export in that library. It  
continues to see if there is a d a ta exp or t sym bol for the same symbol  
definition.  
The 64-bit mode linker toolset produces:  
$ test 3  
object is 0  
The 64-bit mode linker toolset does not allow storage exports from a  
shared library. The uninitialized variable called objectin a.oturns  
into a data export in libA.sl, with an initial value of 0. During symbol  
resolution for the import request from that same library, the dynamic  
loader stops with the first seen definition.  
Sym bol Sea r ch in g in Dep en d en t Libr a r ies  
In the 64-bit mode linker toolset, the linker searches d ep en d en t  
libr a r ies in a breadth-first order for symbol resolution. This means it  
searches libraries linked to the main program file before libraries linked  
to shared libraries. This behavior change is consistent with other SVR4  
systems. The linker also searches siblings of a dependent shared library  
before its children. For example, using the structure described in Figure  
5-25, if libD had dependent libraries libDK and libLH, libD, libE, libF,  
then libDK, libLH would be searched in that order. The dlopenlibrary  
management routines and executable files (a.out) created by the linker  
with the +stdoption (default) use the br ea d th -r st sea r ch order.  
The 32-bit mode linker toolset searches dependent libraries in a  
depth-first order. This means it searches dependent shared library files  
in the order in which they are linked to shared libraries. The shl_load  
library management routines and executable files (a.out) created by the  
linker with the +compatoption use the d ep th -r st sea r ch order.  
182  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
NOTE  
If you have data or function names that are duplicated in different  
shared libraries, the 64-bit mode linker may link in a different version of  
a procedure than the current release. This can lead to unexpected  
results.  
Figure 5-25 shows an example program with shared libraries (the  
shaded boxes are libA.sldependent libraries; and the example does  
not consider libDKor libLH) and compares the two search methods:  
Figu r e 5-25  
Sea r ch Or d er of Dep en d en t Libr a r ies  
a .ou t  
libB  
libE  
libA  
libD  
libC  
libF  
libDK  
libLH  
In 64-bit breadth-first search mode:  
a.out --> libA --> libB --> libC -->libD --> libE --> libF --> LibDK --> libLH  
In 32-bit depth-first search mode:  
a.out --> libA --> libD --> libDK--> libLH --> libE --> LibF --> libB --> libC  
The commands to build the libraries and the executable in Figure 5-25  
are shown below. Note the link order of libraries in steps 2 and 3:  
Chapter 5  
183  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
1. First, the dependent shared libraries for libAare built. (Other  
libraries are also built.)  
ld -b libD.o -o libD.sl libA dependent shared library  
ld -b libE.o -o libE.sl libA dependent shared library  
ld -b libF.o -o libF.sl libA dependent shared library  
ld -b libB.o -o libB.sl  
ld -b libC.o -o libC.sl  
2. Next, libA.ois linked to its dependent libraries and libA.slis  
built.  
ld -b libA.o -lD -lE -lF -o libA.sl  
3. Finally, main.ois linked to its shared libraries.  
cc main.o -lA -lB -lC -o main  
In the 32-bit mode linker toolset, if a procedure called same_name()is  
defined in libD.sland libB.sl, maincalls the procedure defined in  
libD.sl. In 64-bit linker toolset, maincalls same_name()in libB.sl.  
If you use mixed mode shared libraries, the search mechanism may  
produce unexpected results.  
For the following command, libA.sland its dependent libB.slare  
compatibility mode libraries and libC.sland libD.slare standard  
mode libraries.  
ld -b libF.o +compat -L.-lA -lC -o LibF.sl  
libF.slis a compatibility mode library, but is dependent libC.slis a  
standard mode library. The linker uses depth-first searching  
mechanisms because the highest-level library is in compatability mode.  
Mixed Mod e Sh a r ed Libr a r ies  
A mixed mode shared library is a library whose children are all of one  
type (for example, +compat), but whose grandchildren may be of the  
other mode. This poses some problems when linking and loading the  
libraries. To help resolve this, the linker treats each library as having  
any mode. Therefore, when it sees a compatibility mode library, it  
searches for it using the 32-bit-style algorithms. For any standard mode  
library, it uses the 64-bit-style algorithms.Only the load order of the  
libraries themselves is fixed between depth-first or breadth-first.  
184  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
If you use mixed mode shared libraries, you get behavior based on the  
first mode encountered. At runtime, the dynamic loader does a  
depth-first search if the dependent libraries at the highest level are  
compatibility mode libraries. Otherwise, it does breadth-first searching.  
This applies to all dependent libraries of the incomplete executable file.  
The loader cannot toggle back and forth between depth-first and  
breadth-first at the library level, so the first dependent library it sees  
determines which search method to use.  
For example:  
# build standard mode dlls  
# libfile1.sl is a dependent of libfile2.sl  
ld -b file1.o -o libfile1.sl +h libfile1.1  
ld -b file2.o -o libfile2.sl +h libfile2.1 -L. -lfile1  
# build compatibility mode dlls  
# libfile3.sl is a dependent of libfile4.sl  
ld -b file3.o -o libfile3.sl +h libfile3.1  
ld -b file4.o -o libfile4.sl +h libfile4.1 -L. -lfile3 +compat  
ln -s libfile1.sl libfile1.1  
ln -s libfile3.sl libfile3.1  
# build a dll using both standard and compatibility mode dependent  
dlls  
# since we didn’t specify +compat, the resulting dll is a standard  
mode dll  
ld -b file5.o -o libfile5.sl +h libfile5.1 -L. -lfile4 -lfile2  
ln -s libfile4.sl libfile4.1  
ln -s libfile2.sl libfile2.1  
ld main.o -L. -lfile5 -lc  
The resulting a.outhas standard mode dependents, libfile5.sland  
libc.sl. libfile5.slhas two dependents,: libfile4.sland  
libfile2.sl. libfile4.slis a compatibility mode library, and has a  
dependent, libfile3.sl. libfile2.slis a standard mode library,  
and has a dependent, libfile1.sl. The dynamic loader does a  
breadth-first search of all dependent libraries needed by a.outbecause  
the link was done without +compatand libfile5.slis a standard  
Chapter 5  
185  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
mode library. The loader uses 64-bit mode search techniques on all  
libraries except for libfile3.sl, in which case it uses 32-mode search  
techniques.  
NOTE  
Embedded path inheritance is not applied to any mixed mode shared  
library and its descendents. It is only applied to libraries in an a.out  
linked with +compat. Embedded path inheritance does not apply to a  
breadth-first search mechanism.  
64-bit Mod e Libr a r y Exa m p les  
The examples demonstrate the behavior of compatibility and standard  
mode shared libraries created by the 64-bit mode linker toolset:  
Libr a r y Exa m p le: Cr ea tin g a 64-bit Mod e  
Com p a tibility Mod e Sh a r ed Libr a r y.  
The following example creates a compatibility mode shared library.  
ld -b file1.o -o libfile1.sl +h libfile1.1  
ld -b file2.o -o libfile2.sl +h ./libfile2.1  
ld -b file3.o -o libfile3.sl +h /var/tmp/libfile3.1  
ld -b file4.o -o libfile4.sl  
ld -b +compat file3a.o -o libfile3a.sl -L. -lfile -lfile3 +h  
libfile3a.1  
ld -b +compat file2a.o -o libfile2a.sl libfile2.sl ./libfile4.sl  
+b /var/tmp  
elfdump -L libfile3a.sl libfile2a.sl  
libfile3a.sl:  
*** Dynamic Section ***  
Index  
Tag Value  
0 HPNeeded1:./libfile1.1 subject to dynamic path lookup  
1 HPNeeded1:/var/tmp/libfile3.1 subject to dyanmic path lookup  
2 Sonamelibfile3a.1  
...  
libfile2a.sl:  
*** Dynamic Section ***  
Index  
Tag  
Value  
0 HPNeeded 0:/home/knish/./libfile2.1 not subject to dynamic path  
lookup  
1 HPNeeded 0:./libfile4.sl not subject to dynamic path lookup  
2 Rpath  
...  
/var/tmp  
186  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
Libr a r y Exa m p le: Cr ea tin g a 64-bit Sta n d a r d Mod e  
Sh a r ed Libr a r y  
The following example builds a standard mode library.  
ld -b file1.o -o libfile1.sl +h libfile1.1  
ld -b file2.o -o libfile2.sl +h ./libfile2.1  
ld -b file3.o -o libfile3.sl +h /var/tmp/libfile3.1  
ld -b file4.o -o libfile4.sl  
ld -b file3a.o -o libfile3a.sl -L. -lfile1 -lfile3 +h libfile3a.1  
ld -b file2a.o -o libfile2a.sl libfile2.sl ./libfile4.sl +b  
/var/tmp  
elfdump -L libfile3a.sl libfile2a.sl  
libfile3a.sl:  
*** Dynamic Section ***  
Index Tag Value/Ptr  
0 Needed libfile1.1 subject to dynamic path lookup  
1 Needed /var/tmp/libfile3.1not subject to dynamic path  
lookup--internal pathname has a / ”  
2 Soname libfile3a.1  
3 Rpath  
...  
.
libfile2a.sl:  
*** Dynamic Section ***  
Index Tag Value/Ptr  
0 Needed ./libfile2.1 not subject to dynamic path lookup  
1 Needed ./libfile4.sl not subject to dynamic path lookup  
2 Rpath /var/tmp  
...  
The dynamic loader does dynamic path searching for libfile1.sl.. It  
does not do dynamic path searching for libfile2.sl, libfile3.sl,  
and libfile4.sl.  
Libr a r y exa m p le: 64-bit Mod e Dyn a m ic Pa th  
Sea r ch in g  
This example of dynamic path searching demonstrates differences  
between compatibility mode and standard mode dependent shared  
libraries. The example builds standard mode libraries and does a  
standard mode link. By default, the dynamic loader looks at the  
environment variables LD_LIBRARY_PATHand SHLIB_PATHto find the  
shared libraries.  
# build standard mode shared libraries  
#libfile1.sl is a dependent of libfile2.sl  
Chapter 5  
187  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
ld -b file1.o -o libfile1.sl +h libfile1.1  
ld -b file2.o -o libfile2.sl +h libfile2.1 -L. -lfile1  
ld main.o -L. -lfile2 -lc  
# move dependent lib so dld can’t find it  
# dld won’t find library because we didn’t set the environment  
# variable LD_LIBRARY_PATH and SHLIB_PATH  
# By default, dld will look at the environment variables  
# LD_LIBRARY_PATH and  
# SHLIB_PATH when doing dynamic path searching unless +noenvvar  
# is specified  
mv libfile2.sl /var/tmp  
ln -s /var/tmp/libfile2.sl /var/tmp/libfile2.1  
a.out  
dld.sl: Unable to find library ‘libfile2.1’  
export SHLIB_PATH=/var/tmp  
a.out  
in file1  
in file2  
Libr a r y Exa m p le: 64-bit Mod e Com p a tibility Mod e  
Lin k  
This example builds a compatibility mode library and does a  
compatibility mode link. The +soption is not specified at link time, so  
the dynamic loader does not look at any environment variables to do  
dynamic path searching.  
# build compatibility mode dlls  
# libfile1.sl is a dependent of libfile2.sl  
ld -b file1.o -o libfile1.sl +h libfile1.1  
ld -b file2.o -o libfile2.sl +h libfile2.1 -L. -lfile1 +compat  
ln -s libfile1.sl libfile1.1  
ld main.o +compat -L. -lfile2 -lc  
# move dependent lib so dld can’t find it. Even when we specify  
SHLIB_PATH dld won’t be  
# able to find the dependent because we didn’t link with +s  
mv libfile2.sl /var/tmp  
ln -s /var/tmp/libfile2.sl /var/tmp/libfile2.1  
a.out  
dld.sl: Unable to find library ‘1:./libfile2.1’  
export SHLIB_PATH=/var/tmp  
a.out  
dld.sl: Unable to find library ‘1:./libfile2.1’  
You can use chatr +sto enable a.outin file1and file2:  
chatr +s enable a.out  
188  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
Libr a r y Exa m p le: Usin g 64-bit Mod e Com p a tibility  
a n d Sta n d a r d Sh a r ed Libr a r ies  
This example mixes compatibility and standard mode shared libraries. It  
uses 32-it-style linking and loading for the compatibility mode libraries  
and 64-bit-style linking and loading for standard mode libraries.  
# build standard mode dlls  
# libfile1.sl is a dependent of libfile2  
ld -b file1.o -o libfile1.sl +h libfile1.1  
mkdir TMP  
ld -b +b $pwd/TMP file2.o -o libfile2.sl +h libfile2.1 -L. -lfile1  
# build compatibility mode dlls  
# libfile3.sl is a dependent of libfile4  
ld -b file3.o -o libfile3.sl +h libfile3.1  
ld -b file4.o -o libfile4.sl +b $pwd/TMP +h libfile4.1 +compat -L.  
-lfile3  
ln -s libfile1.sl libfile1.1  
ln -s libfile3.sl libfile3.1  
mv libfile1.sl TMP  
mv libfile3.sl TMP  
cd TMP  
ln -s libfile1.sl libfile1.1  
ln -s libfile3.sl libfile3.1  
cd ..  
# link with +b so ld will use RPATH at link time to find  
# libfile1.sl (standard mode dll)  
# the linker will not use RPATH to find libfile3.sl  
# (compatibility mode dll)  
# Note that this is true in both a standard mode link and a  
# compatibility mode link. The  
# linker never uses RPATH to find any compatibility mode dlls  
ld -b +b pwd/TMP main.o -o libfile5.sl +h libfile5.1 -L. -lfile2  
-lfile4  
ld: Can’t find dependent library “./libfile3.sl”  
ld -b +b pwd/TMP main.o -o libfile5a.sl +h libfile5.1 -L. -lfile2  
-lfile4 +compat  
ld: Can’t find dependent library “./libfile3.sl”  
Com p a r in g Br ea d th -r st a n d Dep th -r st Sea r ch in  
64-bit Mod e  
For the following libraries, with the dependencies:  
lib1.sl has dependents lib2.sl, lib3.sl, and lib4.sl  
lib2.sl has dependents lib2a.sl and lib2b.sl  
lib3.sl has dependents lib3a.sl and lib3b.sl  
lib3a.sl has dependent lib3aa.sl  
Chapter 5  
189  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
+-->lib2a.sl  
|
+-->lib2.sl-->lib2b.sl  
|
lib1.sl-->lib3.sl-->lib3a.sl-->lib3aa.sl  
|
|
|
+-->lib3b.sl  
+-->lib4.sl  
In breadth-first searching, the load order is siblings before children:  
lib1.sl->lib2.sl->lib3.sl->lib4.sl->lib2a.sl->lib2b.sl->lib3a.sl-  
>lib3b.sl->lib3aa.sl  
In depth-first searching, the load order is children before siblings:  
lib1.sl->lib2.sl->lib2a.sl->lib2b.sl->lib3.sl->lib3a.sl->lib3aa.s  
l->lib3b.sl->lib4.sl  
Libr a r y Exa m p le: Usin g RPATHw ith Sta n d a r d Mod e  
Sh a r ed Libr a r y  
In the following example, the linker uses the embedded RPATH at link  
time to find the dependent library. For compatibility mode shared  
libraries, embedded RPATHs are ignored.  
ld -b bar.o -o libbar.sl  
ld -b foo.o -o libfoo.sl -L. -lbar +b /var/tmp  
# ld should look in /var/tmp to find libbar.sl since libfoo.sl  
# has an embedded RPATH of  
# /var/tmp  
mv libbar.sl /var/tmp  
ld main.o -L. -lfoo -lc  
# For compatibility mode dlls, embedded RPATHs are ignored  
ld -b bar.o -o libbar.sl  
ld -b foo.o -o libfoo.sl +compat -L. -lbar +b /var/tmp  
# ld won’t find libbar.sl since it does not look at embedded RPATHs  
mv libbar.sl /var/tmp  
ld main.o -L. -lfoo +compat -lc  
ld: Can’t find dependent library “libbar.sl”  
Fatal error.  
Lin k in g Libr a r ies w ith +b pa th list  
The following examples compare 32-bit and 64-bit mode linking with the  
ld +b pathlist option. The dynamic loader uses the directory specified  
by the -Loption at link time for dynamic library lookup at run time, if  
you do not use the +boption.  
190  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
Libr a r y Exa m p le: Lin k in g to Libr a r ies w ith +b pa th _list in  
64-bit Mod e. In this example, the program maincalls a shared library  
routine in libbar.sl. The routine in libbar.slin turn calls a routine  
in the shared library libme.sl. The +blinker option indicates the  
search path for libme.slwhen linking libbar.sl. (You use +b  
path_list with libraries specified with the -l library or -l:library  
options.)  
cc -c +DD64 me.c  
ld -b me.o -o libme.sl  
ld -b bar.o -o libbar.sl -L. -lme +b /var/tmp  
mv libme.sl /var/tmp  
ld main.o -L. -lbar -lc  
In 64-bit mode, the linker finds libme.slin /var/tmpbecause the +b  
/var/tmpoption is used when linking libbar.sl. Since -lmewas  
specified when linking libbar.sl, libme.slis subject to run-time  
dynamic path searching.  
When linking main.o, the link order in the above example is:  
1. ./libbar.slfound  
2. ./libme.sl not found  
3. /var/tmp/libme.sl found  
4. ./libc.sl not found  
5. /usr/lib/pa20_64/libc.sl found  
In the above example, if you type:  
ld main.o -L. -lbar -lc  
mv libme.sl /var/tmp  
instead of:  
mv libme.sl /var/tmp  
ld main.o -L. -lbar -lc  
the linker findslibme.slin ./at link time, and the dynamic loader  
finds libme.slin /var/tmpat run time.  
At run time, the dynamic loader searches paths to resolve external  
references made by mainin the following order:  
1. LD_LIBRARY_PATHto find libbar.slnot found  
2. SHLIB_PATHto find libbar.slnot found  
Chapter 5  
191  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
3. ./libbar.sl(./libbar.sl) found  
4. LD_LIBRARY_PATHto find libme.slnot found  
5. SHLIB_PATHto find libme.slnot found  
6. /var/tmp/libme.slfound  
7. LD_LIBRARY_PATHto find libc.slnot found  
8. SHLIB_PATHto find libc.slnot found  
9. ./libc.slnot found  
10. /usr/lib/pa20_64/libc.slfound  
Libr a r y Exa m p le: Lin k in g to Libr a r ies w ith +b pa th _list in  
32-bit Mod e. This example is the same as Library Example: Linking  
to Libraries with +b path_list in 64-bit Mode, but this time the program  
is compiled in 32-bit mode.  
cc -c +DD32 me.c  
ld -b me.o -o libme.sl  
ld -b bar.o -o libbar.sl -L. -lme +b /var/tmp  
ld main.o -L. -lbar -lc  
mv libme.sl /var/tmp  
When linking main.o, the link order is:  
1. ./libbar.slfound  
2. ./libme.slfound  
3. ./libc.slnot found  
4. /usr/lib/libc.slfound  
In the above example, if you type:  
mv libme.sl /var/tmp  
ld main.o -L. -lbar -lc  
instead of:  
ld main.o -L. -lbar -lc  
mv libme.sl /var/tmp  
the linker issues the following error:  
ld: Can’t find dependent library ./libme.sl  
Fatal Error  
192  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
The linker does not look in /var/tmpto find shared libraries because in  
32-bit mode the directories specified by +b pathname are only searched  
at run time.  
Because libme.slis specified with the -loption, it is subject to  
dynamic path searching.  
At run time, the dynamic loader looks for shared libraries used by main  
in the following order:  
1. ./libbar.slfound  
2. /var/tmp/libme.slfound  
3. ./libc.slnot found  
4. /usr/lib/libc.slfound  
NOTE  
In 32-bit mode, the dynamic loader does not search the default  
directories to find libme.slat run time. In 64 bit mode, by default, the  
dynamic loader looks in the default directories.  
Chapter 5  
193  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Creating and Using Libraries  
Using Shared Libraries in 64-bit mode  
194  
Chapter5  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
6
Sh a r ed Libr a r y Ma n a gem en t  
Rou tin es  
You can explicitly load and use shared libraries from your program. The  
linker toolset provides two families of load routines, shl_loadand  
dlopen. The shl_loadroutines support the shared library mechanisms  
provided in previous version of HP-UX. The dlopenroutines (available  
for 64-bit mode only) use Unix SVR4 compatible mechanism for library  
management.  
NOTE  
NOTE  
Both families of routines support initializer and terminator routines. The  
64-bit mode linker supports init/fini and 10.X release mechanisms. The  
32-bit mode linker supports only the style used for the 10.X releases.  
Support for shl_loadlibrary management routines may be  
discontinued in a future 64-bit HP-UX release. You are encouraged to  
migrate to the dlopenfamily of routines for shared library management  
if you use the 64-bit mode linker toolset.  
Chapter 6  
195  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Shared Library Management Routine Summaries  
Sh a r ed Libr a r y Ma n a gem en t Rou tin e  
Su m m a r ies  
The following sections introduce the shared library management  
routines available for the HP-UX 11.00 release.  
Th e sh l_loa d Rou tin e Su m m a r y  
The shl_loadfamily of shared library management routines are  
available for both the 32-bit and 64-bit mode linker.  
All of the shl_loadfamily routines use the same user interface in 32-bit  
and 64-bit mode linking.  
Use the following shl_loadroutines for shared library management:  
Rou tin e  
Action  
shl_loadand  
cxxshl_load  
Explicitly load a shared library and a C++  
shared library, respectively. They have the  
same syntax. shl_load()lets you load a  
compatibility or standard mode shared library.  
It does depth-first searching.  
shl_findsym  
Finds the address of a global symbol in a  
shared library.  
shl_getand  
shl_get_r  
Get information about currently loaded  
libraries. shl_get_ris a thread-safe version  
of shl_getwith the same syntax.  
shl_gethandle  
and  
shl_gethandle_r  
Get descriptor information about a loaded  
shared library. shl_gethandle_ris a  
thread-safe version of shl_gethandlewith  
the same syntax.  
196  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Shared Library Management Routine Summaries  
Rou tin e  
Action  
shl_definesym  
Adds a new symbol to the global shared library  
symbol table.  
shl_getsymbols  
Returns a list of symbols in a shared library.  
shl_unloadand  
cxxshl_load  
Unload a shared library and a C++ shared  
library, respectively. They have the same  
syntax.  
Except for shl_getand shl_gethandle, all these routines are thread  
safe.  
These routines are described in the shl_load(3x) man page.  
Th e d lop en Rou tin es Su m m a r y  
The dlopenfamily of shared library management routines is available  
only for the 64-bit linker.  
The dlopenfamily of routines use Unix SVR4 shared library  
mechanisms.  
Use the following dl*routines for shared library management:  
Rou tin e  
dlopen  
Action  
Loads a shared library. This routine does  
breadth-first searching.  
dlerror  
dlsym  
Prints the last error message recorded by dld.  
Gets the address of a symbol in a shared library.  
Returns information on a loaded module.  
Returns information about a loaded module.  
dlget  
dlmodinfo  
dlgetname  
Retrieves the name of a loaded module given a  
load model descriptor.  
dlclose  
Unloads a shared library previously loaded by  
dlopen().  
Chapter 6  
197  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Shared Library Management Routine Summaries  
All the dlopenroutines are thread-safe.  
These routines are described in the dl*(3C) man pages.  
Rela ted Files a n d Com m a n d s  
These commands and files provide more information about using shared  
library management routines.  
Com m a n d /File  
Action  
a.out(4)  
Executable file from assembler, compiler, and  
linker output.  
cc(1)  
Command to invoke the HP-UX C compiler.  
System loader.  
exec(2)  
ld(1)  
Command to invoke the linker.  
198  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Shared Library Header Files  
Sh a r ed Libr a r y Hea d er Files  
The shl_loadfamily of shared library management routines use some  
special data types (structures) and constants defined in the C-language  
header file /usr/include/dl.h. When using these functions from C  
programs, be sure to include dl.h:  
#include <dl.h>  
If you are using HP C++, also include /opt/CC/include/CC/cxxdl.h.  
Similarly, if you are using the dlopenfamily of routines, include  
/usr/include/dlfcn.h.  
#include <dlfnc.h>  
If an error occurs when calling shared library management routines, the  
system error variable errnois set to an appropriate error value.  
Constants are defined for these error values in /usr/include/errno.h  
(see errno(2)). Thus, if a program checks for these error values, it must  
include errno.h:  
#include <errno.h>  
Throughout this section, all examples are given in C. To learn how to call  
these routines from C++, FORTRAN, or Pascal, refer to the  
inter-language calling conventions described in the compiler  
documentation.  
Chapter 6  
199  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Using Shared Libraries with cc and ld Options  
Usin g Sh a r ed Libr a r ies w ith cc a n d ld  
Op tion s  
In 32-bit mode, you can access the shl_loadfamily of routines  
specifying the -ldldoption on the cc(1) or ld(1) command line. In 64-bit  
mode, you can access the shl_loadand dlopenroutines by specifying  
either -ldldor -ldlon the command line.  
Some 32-bit mode implementations do not, by default, export all symbols  
defined by a program (instead exporting only those symbols imported by  
a shared library seen at link time). Use the -Eoption to ldto ensure that  
all symbols defined in the program are available to the loaded libraries.  
This is the default behavior in 64-bit mode.  
To create shared libraries, compile source files and link the resultant  
object files with the -bwith the ccor ldcommand.  
200  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
In itia lizer s for Sh a r ed Libr a r ies  
A shared library can have an initialization routine—known as an  
in itia lizer that is called when the load module (a shared library or  
executable) is loaded (initializer) or explicitly unloaded (terminator).  
Typically, an initializer is used to initialize a shared library's data when  
the library is loaded.  
When a program begins execution its initializers are called before any  
other user code is executed.This allow for setup at initialization and  
cleanup at termination. Also, when a shared library is explicitly loaded  
using shl_loador dlopenor unloaded using shl_unloador dlclose,  
it initializers and terminators are called at the appropriate time.  
In 64-bit mode, you can specify initializers and terminators even for  
archive libraries or nonshared executables.  
Styles of In itia lizer s  
The linker supports two different types of initializers and terminators:  
HP-UX 10.X style.  
Init/fini style.  
NOTE  
The 32-bit mode linker supports only the HP-UX 10.X style initializers.  
See 32-bit Mode Initializers” for more information.  
The 64-bit mode linker supports both of these styles.See 64-bit Mode  
Initializers” for more information.  
HP -UX-10.X-Style In itia lizer s  
HP-UX 10.X style initializers are the same type supported in all HP-UX  
10.X releases. These are called both before the users code is started or a  
shared library is loaded (using shl_loador dlopen) as well as when  
the shared library is unloaded (using shl_unloador dlclose). The  
linker option +Iis used to create this type of initializer. The function  
returns nothing but takes two arguments. The first is a handle to the  
shared library being initialized. This handle can be used in calling  
shl_loadroutines. The second is set to non-zero at startup and zero at  
program termination.  
Chapter 6  
201  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
$ ld -b foo.o +I my_10x_init -o libfoo.sl  
#include <dl.h>  
void my_10x_init(shl_t handle, int loading)  
{
/* handle is the shl_load API handle for the shared library being  
initialized. */  
/* loading is non-zero at startup and zero at termination. */  
if (loading) {  
... do some initializations ...  
} else {  
... do some clean up ...  
}
}
NOTE  
Unlike 32-bit mode, the 64-bit HP-UX 10.X style initiators are called  
when unloading implicitly lordered shared libraries.  
See 32-bit Mode Initializers” for more information on using these  
initiators.  
In it/Fin i Style In itia lizer s  
This style uses init and fini functions to handle initialization operations.  
In it. Inits are called before the users code starts or when a shared  
library is loaded. They are functions which take no arguments and  
return nothing. The C compiler pragma init” is used to declare them.  
For example:  
#pragma init “my_init”  
void my_init() { ... do some initializations ... }  
The ldcommand supports the +initoption to specify the initializer.  
Fin i. Finis are called after the users code terminates by either calling  
the libc exit function, returning from the main or _startfunctions, or  
when the shared library which contains the fini is unloaded from  
memory. Like inits, these also take no arguments and return nothing.  
The C compiler pragma ni” is used to create them. For example:  
#pragma fini “my_fini”  
void my_fini() { ... do some clean up ... }  
202  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
The ldcommand supports the +finioption to specify theterminator.  
32-bit Mod e In itia lizer s  
The 32-bit mode linker supports HP-UX 10.X style initializers.  
This section contains the following topics:  
Using HP-UX 10.X Style Initializers  
Declaring the Initializer with the +I Option”  
Initializer Syntax”  
Example: An Initializer for Each Library”  
Example: A Common Initializer for Multiple Libraries”  
Usin g HP -UX 10.X Style In itia lizer s  
The initializer is called for libraries that are loaded implicitly at program  
startup, or explicitly with shl_load.  
When calling initializers for implicitly loaded libraries, the dynamic  
loader waits until all libraries have been loaded before calling the  
initializers. It calls the initializers in d ep th -r st or d er that is, the  
initializers are called in the reverse order in which the libraries are  
searched for symbols. All initializers are called before the main program  
begins execution.  
When calling the initializer for explicitly loaded libraries, the dynamic  
loader waits until any dependent libraries are loaded before calling the  
initializers. As with implicitly loaded libraries, initializers are called in  
depth-first order.  
Note that initializers can be disabled for explicitly loaded libraries with  
the BIND_NOSTARTflag to shl_load. For more information, see The  
shl_load and cxxshl_load Routines.  
Decla r in g th e In itia lizer w ith th e +I Op tion  
To declare the name of the initializer, use the +Ilinker option when  
creating the shared library. The syntax of the +Ioption is:  
+I initializer  
where initializer is the initializer's name.  
Multiple initializers may be called by repeating the +Iinitializer option.  
Chapter 6  
203  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
For example, to create a shared library named libfoo.slthat uses an  
initializer named init_foo, use this linker command line:  
$ ld -b -o libfoo.sl libfoo.o +I init_foo  
Or d er of Execu tion of Mu ltip le In itia lizer s . Multiple  
initializers are executed in the same order that they appear on the  
command line; they are unloaded in reverse order. (This applies only to  
the calling order within a shared library, not across multiple shared  
libraries.)  
NOTE  
Initializers are not executed when unloading shared libraries which were  
implicitly loaded since the program exits without re-entering the  
dynamic loader to unload them. Initializers are only called during the  
explicit unloading of a shared library.  
Initializers behave the same as other symbols; once they are bound they  
cannot be overridden with a new symbol through the use of  
shl_definesym()or by loading a more visible occurrence of the  
initializer symbol with the BIND_FIRSTflag. What this means is that  
once the initializer is executed upon a load, it is guaranteed to be the  
same initializer that is called on an explicit unload.  
In itia lizer Syn ta x  
void initializer( shl_t handle,  
int loading )  
initializer  
handle  
The name of the initializer as specified with the +I  
linker option.  
The initializer is called with this parameter set to the  
handle of the shared library for which it was invoked.  
loading  
The initializer is called with this parameter set to 1  
(true) when the shared library is loaded and 0 (false)  
when the library is unloaded.  
The initializers cannot be defined as local definitions. Initializers cannot  
be hidden through the use of the -hoption when building a shared  
library.  
It is strongly recommended that initializers be defined with names which  
do not cause name collisions with other user-defined names in order to  
avoid overriding behavior of shared library symbol binding.  
204  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
Accessin g In itia lizer s' Ad d r esses . Prior to the HP-UX 10.0  
release, initializer's addresses could be accessed through the initializer  
field of the shared library descriptor which is returned from a call to  
shl_get(). To support multiple initializers, the shl_getsymbols()  
routine has been enhanced to support the return of the initializer's  
address.  
If only one initializer is specified for a given library, its address is still  
available through the initializer field of a shared library descriptor. If  
more than one initializer is specified, the initializer field will be set to  
NO_INITIALIZER. Access to multiple initializers can then be  
accomplished through the use of shl_getsymbols(). (The  
shl_getsymbols()routine can also access a single initializer.)  
NOTE  
shl_getsymbols()may not return the initializer which was invoked  
for a given library if a more visible initializer symbol is defined after the  
library being queried has been loaded. This can occur through the use of  
shl_definesym()and by explicitly loading a more visible symbol using  
the BIND_FIRSTflag upon loading.  
To access initializers, a new flag, INITIALIZERS, has been defined for  
the shl_getsymbols()routine. It can be ORed with the NO_VALUES  
and GLOBAL_VALUESflags. For example,  
shl_getsymbols(handle,  
TYPE_PROCEDURE,  
INITIALIZERS | GLOBAL_VALUES,  
malloc,  
&symbol_array);  
If the GLOBAL_VALUESmodifier is not used and the initializer is defined  
in another shared library or in the program file, shl_getsymbols()  
does not find the initializer for the requested library because it is not  
defined within the library.  
For more information on the usage of shl_getsymbols(), see The  
shl_getsymbols Routine.  
Exa m p le: An In itia lizer for Ea ch Libr a r y  
One way to use initializers is to define a unique initializer for each  
library. For instance, the following example shows the source code for a  
library named libfoo.slthat contains an initializer named init_foo:  
Chapter 6  
205  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
C Source for libfoo.sl  
#include <stdio.h>  
#include <dl.h>  
/*  
* This is the local initializer that is called when the libfoo.sl  
* is loaded and unloaded:  
*/  
void init_foo(shl_t hndl, int loading)  
{
if (loading)  
printf(“libfoo loaded\n”);  
else  
printf(“libfoo unloaded\n”);  
}
float in_to_cm(float in)  
/* convert inches to  
centimeters */  
{
return (in * 2.54);  
}
float gal_to_l(float gal)  
/* convert gallons to litres  
/* convert ounces to grams */  
*/  
{
return (gal * 3.79);  
}
float oz_to_g(float oz)  
{
return (oz * 28.35);  
}
You can use the +Ilinker option to register a routine as an initializer.  
Here are the commands to create libfoo.sland to register init_foo  
as the initializer:  
$ cc -Aa -c +z libfoo.c  
$ ld -b -o libfoo.sl +I init_foo libfoo.o  
To use this technique with multiple libraries, each library should have a  
unique initializer name. The following example program loads and  
unloads libfoo.sl.  
C Source for testlib  
#include <stdio.h>  
#include <dl.h>  
main()  
{
float (*in_to_cm)(float), (*gal_to_l)(float), (*oz_to_g)(float);  
shl_t hndl_foo;  
/*  
* Load libfoo.sl and find the required symbols:  
*/  
if ((hndl_foo = shl_load(“libfoo.sl”,  
BIND_IMMEDIATE, 0)) == NULL)  
perror(“shl_load: error loading libfoo.sl”), exit(1);  
206  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
if (shl_findsym(&hndl_foo, “in_to_cm”, TYPE_PROCEDURE,  
(void *) &in_to_cm))  
perror(“shl_findsym: error finding in_to_cm”), exit(1);  
if (shl_findsym(&hndl_foo, “gal_to_l”, TYPE_PROCEDURE,  
(void *) &gal_to_l))  
perror(“shl_findsym: error finding gal_to_l”), exit(1);  
if (shl_findsym(&hndl_foo, “oz_to_g”, TYPE_PROCEDURE,  
(void *) &oz_to_g))  
perror(“shl_findsym: errror finding oz_to_g”), exit(1);  
/*  
* Call routines from libfoo.sl:  
*/  
printf(“1.0in = %5.2fcm\n”, (*in_to_cm)(1.0));  
printf(“1.0gal = %5.2fl\n”, (*gal_to_l)(1.0));  
printf(“1.0oz = %5.2fg\n”, (*oz_to_g)(1.0));  
/*  
* Unload the library:  
*/  
shl_unload(hndl_foo);  
}
The following is the output of running the testlibprogram:  
Output of testlib  
libfoo loaded  
1.0in = 2.54cm  
1.0gal = 3.79l  
1.0oz = 28.35g  
libfoo unloaded  
Exa m p le: A Com m on In itia lizer for Mu ltip le Libr a r ies  
Rather than have a unique initializer for each library, libraries could  
have one initializer that calls the actual initialization code for each  
library. To use this technique, each library declares and references the  
same initializer (for example, _INITIALIZER), which calls the  
appropriate initialization code for each library.  
This is easily done by defining loadand unloadfunctions in each  
library. When _INITIALIZERis called, it uses shl_findsymto find and  
call the loador unloadfunction (depending on the value of the loading  
flag).  
The following example shows the source for an _INITIALIZERfunction:  
Chapter 6  
207  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
C Source for _INITIALIZER (file init.c)  
#include <dl.h>  
/*  
* Global initializer used by shared libraries that have  
* registered it:  
*/  
void _INITIALIZER(shl_t hand, int loading)  
{
void (*load_unload)();  
if (loading)  
shl_findsym(&hand, “load”, TYPE_PROCEDURE, (void *)  
&load_unload);  
else  
shl_findsym(&hand, “unload”, TYPE_PROCEDURE, (void *)  
&load_unload(;  
(*load_unload( ();  
}
/* call the function */  
The following two source files show shared libraries that have registered  
_INITIALIZER.  
C Source for libunits.sl  
#include <stdio.h>  
#include <dl.h>  
void load()  
{
/* called after libunits.sl loaded */  
printf(“libunits.sl loaded\n”);  
}
void unload()  
/* called after libunits.sl unloaded  
*/  
{
printf(“libunits.sl unloaded\n”);  
}
extern void _INITIALIZER();  
float in_to_cm(float in)  
/* convert inches to centimeters */  
/* convert gallons to litres */  
/* convert ounces to grams */  
{
return (in * 2.54);  
}
float gal_to_l(float gal)  
{
return (gal * 3.79);  
}
float oz_to_g(float oz)  
{
return (oz * 28.35);  
}
208  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
C Source for libtwo.sl  
#include <stdio.h>  
void load()  
/* called after libtwo.sl loaded */  
/* called after libtwo.sl unloaded  
{
printf(“libtwo.sl loaded\n”);  
}
void unload()  
*/  
{
printf(“libtwo.sl unloaded\n”);  
}
extern void _INITIALIZER();  
void (*init_ptr)() = _INITIALIZER;  
void foo()  
{
printf(“foo called\n”);  
}
void bar()  
{
printf(“bar called\n”);  
}
Here are the commands used to build these libraries:  
$ cc -Aa -c +z libunits.c  
$ ld -b -o libunits.sl +I _INITIALIZER libunits.o  
$ cc -Aa -c +z libtwo.c  
$ ld -b -o libtwo.sl +I _INITIALIZER libtwo.o  
The following is an example program that loads these two libraries:  
C Source for testlib2  
#include <stdio.h>  
#include <dl.h>  
main()  
{
float (*in_to_cm)(float), (*gal_to_l)(float), (*oz_to_g)(float);  
void (*foo)(), (*bar)();  
shl_t hndl_units, hndl_two;  
/*  
* Load libunits.sl and find the required symbols:  
*/  
if ((hndl_units = shl_load(“libunits.sl”, BIND_IMMEDIATE, 0)) ==  
NULL)  
perror(“shl_load: error loading libunits.sl”), exit(1);  
if (shl_findsym(&hndl_units, “in_to_cm”,  
TYPE_PROCEDURE, (void *) &in_to_cm))  
perror(“shl_findsym: error finding in_to_cm”), exit(1);  
if (shl_findsym(&hndl_units, “gal_to_l”,  
TYPE_PROCEDURE, (void *) &gal_to_l))  
perror(“shl_findsym: error finding gal_to_l”), exit(1);  
if (shl_findsym(&hndl_units, “oz_to_g”,  
Chapter 6  
209  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
TYPE_PROCEDURE, (void *) &oz_to_g))  
perror(“shl_findsym: errror finding oz_to_g”), exit(1);  
/*  
* Load libtwo.sl and find the required symbols:  
*/  
if ((hndl_two = shl_load(“libtwo.sl”, BIND_IMMEDIATE, 0)) ==  
NULL)  
perror(“shl_load: error loading libtwo.sl”), exit(1);  
if (shl_findsym(&hndl_two, “foo”, TYPE_PROCEDURE, (void *) &foo))  
perror(“shl_findsym: error finding foo”), exit(1);  
if (shl_findsym(&hndl_two, “bar”, TYPE_PROCEDURE, (void *) &bar))  
perror(“shl_findsym: error finding bar”), exit(1);  
/*  
* Call routines from libunits.sl:  
*/  
printf(“1.0in = %5.2fcm\n”, (*in_to_cm)(1.0));  
printf(“1.0gal = %5.2fl\n”, (*gal_to_l)(1.0));  
printf(“1.0oz = %5.2fg\n”, (*oz_to_g)(1.0));  
/*  
* Call routines from libtwo.sl:  
*/  
(*foo)();  
(*bar)();  
/*  
* Unload the libraries so we can see messages displayed by  
initializer:  
*/  
shl_unload(hndl_units);  
shl_unload(hndl_two);  
}
Here is the compiler command used to create the executable testlib2:  
$ cc -Aa -Wl,-E -o testlib2 testlib2.c init.c -ldld  
Note that the -Wl,-Eoption is required to cause the linker to export all  
symbols from the main program. This allows the shared libraries to find  
the _INITIALIZERfunction in the main executable.  
Finally, the output from running testlib2is shown:  
Ou tp u t of testlib2  
libfoo loaded  
1.0in = 2.54cm  
1.0gal = 3.79l  
1.0oz = 28.35g  
libfoo unloaded  
64-bit Mod e In itia lizer s  
The 64-bit mode linker support both styles of initializers:  
HP-UX 10.X style: see HP-UX-10.X-Style Initializers” and 32-bit  
Mode Initializers” for more information.  
210  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
Init/Fini style: see Init/Fini Style Initializers” and the topics  
described in this section:  
Init and Fini Usage Example”  
Ordering Within an Executable or Shared Library”  
Ordering Among Executables and Shared Libraries”  
In it a n d Fin i Usa ge Exa m p le  
This example consists of three shared libraries lib1.sl, lib2.sland  
lib3.sl. The lib1.sl depends on lib3.sl. The main program (a.out)  
depends on lib1.sland lib2.sl. Each shared library has an init  
style initializer and a finistyle terminator. The lib1.sland lib2.sl  
uses linker options (+initand +fini) to specify the initializers and  
terminators and lib3.sluses compiler pragmas.  
C source for lib1.sl (file lib1.c):  
lib1()  
{
printf(“lib1\n”);  
}
void  
lib1_init()  
{
printf(“lib1_init\n”);  
}
void  
lib1_fini()  
{
printf(“lib1_fini\n”);  
}
C source for lib2.sl (file lib2.c):  
lib2()  
{
printf(“lib2\n”);  
}
void  
lib2_init()  
{
printf(“lib2_init\n”);  
}
void  
lib2_fini()  
{
printf(“lib2_fini\n”);  
}
Chapter 6  
211  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
C source for lib3.sl (file lib3.c):  
lib3()  
{
printf(“lib3\n”);  
}
#pragma init “lib3_init”  
void  
lib3_init()  
{
printf(“lib3_init\n”);  
}
#pragma fini “lib3_fini”  
void  
lib3_fini()  
{
printf(“lib3_fini\n”);  
}
Commands used to build these libraries:  
$ cc +DD64 lib1.c lib2.c lib3.c main.c -c;  
$ ld -b lib3.o -o lib3.sl;  
$ ld -b +init lib2_init +fini lib2_fini lib2.o -o lib2.sl;  
$ ld -b +init lib1_init +fini lib1_fini lib1.o ./lib3.sl -o \  
lib1.sl;  
$ cc -L. +DD64 main.o -l1 -l2 -lc;  
Output from running a.out:  
lib2_init  
lib3_init  
lib1_init  
lib1  
lib2  
lib3  
lib1_fini  
lib3_fini  
lib2_fini  
Or d er in g With in a n Execu ta ble or Sh a r ed Libr a r y  
Multiple initializers/terminators within the same load module (an  
executable or shared library) are called in an order following these rules:  
Inits in .o(object) files or .a(archive) files are called in the reverse  
order of the link line.  
Finis in .oor .afiles are called in forward order of the link line.  
212  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
HP-UX 10.X style initializers are called in forward order of the +I  
options specified on the link line when loading a shared library. They  
are then called in reverse order when unloading the library.  
HP-UX 10.X style initializers are called after inits and before finis.  
Any inits or finis in archive (.a) files are called only if the .owhich  
contains it is used during the link. Use the linker -voption to  
determine which .ofiles within an archive file were used.  
Shared libraries on the link line (dependent libraries) follow the  
ordering described in Ordering Among Executables and Shared  
Libraries.  
For example, the linker command:  
$ ld -b first_64bit.o -l:libfoo.sl second_64bit.o my_64bit.a +I  
first_10x_init +I second_10x_init -o libbar.sl  
results in the following order when library is loaded:  
1. inits from any .ofiles used in my_64bit.a  
2. inits in second_64bit.o  
3. inits in first_64bit.o  
4. first_10x_init  
5. second_10x_init  
and the following order when library is unloaded:  
1. second_10x_init  
2. first_10x_init  
3. finis in first_64bit.o  
4. finis in second_64bit.o  
5. finis from any .ofiles used in my_64bit.a  
NOTE  
libfoo.slis ignored in this example. It follows the rules in Ordering  
Among Executables and Shared Libraries.  
Or d er in g Am on g Execu ta bles a n d Sh a r ed Libr a r ies  
When multiple load modules have initializers/terminators, the following  
rules apply to ordering:  
Chapter 6  
213  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Initializers for Shared Libraries  
When loading, the inits and HP-UX 10.X initializers of any dependent  
libraries are called before the ones in the current library.  
When unloading, the finis and HP-UX 10.X initializers of any  
dependent libraries are called after the finis of the current library.  
If a shared library is itself a dependent of one of its dependents (a  
“circular” dependency), no ordering between them is guaranteed.  
For example, given three libraries: libA.sl, libB.sl, libC.sl. If  
libA.slwere linked as (libB.sland libC.slare dependent”  
libraries of libA.sl):  
$ ld -b foo.o -lB -lC -o libA.sl  
One possible ordering while loading is:  
inits in C  
inits in B  
inits in A  
and while unloading is:  
finis inA  
finis in B  
finis in C  
214  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Th e sh l_loa d Sh a r ed Libr a r y  
Ma n a gem en t Rou tin es  
This section describes the shl_loadfamily of shared library  
management routines.  
NOTE  
You can use these routines in both 32-bit and 64-bit mode. Support for  
these routines may be discontinues in a future 64-bit HP-UX release. If  
you use these routines in 64-bit mode, consider converting your  
programs to the dl*family of shared library management routines.  
Th e sh l_loa d a n d cxxsh l_loa d Rou tin es  
Explicitly loads a library.  
Syn ta x  
shl_t shl_load( const char * path,  
int flags,  
long address )  
Pa r a m eter s  
path  
A null-terminated character string containing the path  
name of the shared library to load.  
flags  
Specifies when the symbols in the library should be  
bound to addresses. It must be one of these values,  
defined in <dl.h>:  
BIND_IMMEDIATE  
Bind the addresses of all symbols immediately upon  
loading the library.  
BIND_DEFERRED  
Bind the addresses when they are first referenced.  
Be aware that BIND_IMMEDIATEcauses the binding of  
all symbols, and the resolution of all imports, even from  
older versioned modules in the shared library. If  
symbols are not accessible because they come from old  
modules, they are unresolved and shl_loadmay fail.  
Chapter 6  
215  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
In addition to the above values, the flags parameter  
can be ORed with the following values:  
BIND_NONFATAL  
Allow binding of unresolved symbols.  
BIND_VERBOSE  
Make dynamic loader display verbose messages when  
binding symbols.  
BIND_FIRST  
Insert the loaded library before all others in the  
current link order.  
DYNAMIC_PATH  
Causes the dynamic loader to perform dynamic library  
searching when loading the library. The +sand +b  
options to the ldcommand determine the directories  
the linker searches. This is the default mode for the  
64-bit mode linker if +compatlinker option is not  
specified.  
BIND_NOSTART  
Causes the dynamic loader to not call the initializer,  
even if one is declared for the library, when the library  
is loaded or on a future call to shl_loador dlopen.  
This also inhibits a call to the initializer when the  
library is unloaded.  
BIND_RESTRICTED  
Causes the search for a symbol definition to be  
restricted to those symbols that were visible when the  
library was loaded.  
BIND_TOGETHER  
Causes the library being loaded and all its dependent  
libraries to be bound together rather than each  
independently. Use this when you have interdependent  
libraries and you are using BIND_FIRST.  
BIND_BREADTH_FIRST  
64-bit mode only:  
216  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Causes the dependent libraries to be loaded breadth  
first. By default, the 64-bit mode shl_loadloads  
dependent libraries depth-first.  
These flags are discussed in detail inshl_load  
Example.  
address  
Specifies the virtual address at which to attach the  
library. Set this parameter to 0(zero) to tell the system  
to choose the best location. This argument is currently  
ignored; mapping a library at a user-defined address is  
not currently supported.  
Retu r n Va lu e  
If successful, shl_loadreturns a sh a r ed libr a r y h a n d le of type  
shl_t. This address can be used in subsequent calls to shl_close,  
shl_findsym, shl_gethandle, and shl_gethandle_r. Otherwise,  
shl_loadreturns a shared library handle of NULLand sets errnoto one  
of these error codes (from <errno.h>):  
ENOEXEC  
ENOSYM  
ENOMEM  
The specified path is not a shared library, or a format  
error was detected in this or another library.  
A symbol needed by this library or another library  
which this library depends on could not be found.  
There is insufficient room in the address space to load  
the shared library.  
EINVAL  
ENOENT  
EACCESS  
The requested shared library address was invalid.  
The specified path does not exist.  
Read or execute permission is denied for the specified  
path.  
Descr ip tion  
A program needs to explicitly load a library only if the library was not  
linked with the program. This typically occurs only when the library  
cannot be known at link time — for example, when writing programs  
that must support future graphics devices.  
Chapter 6  
217  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
However, programs are not restricted to using shared libraries only in  
that situation. For example, rather than linking with any required  
libraries, a program could explicitly load libraries as they are needed.  
One possible reason for doing this is to minimize virtual memory  
overhead. To keep virtual memory resource usage to a minimum, a  
program could load libraries with shl_loadand unload with  
shl_unloadwhen the library is no longer needed. However, it is  
normally not necessary to incur the programming overhead of loading  
and unloading libraries yourself for the sole reason of managing system  
resources.  
Note that if shared library initializers have been declared for an  
explicitly loaded library, they are called after the library is loaded. For  
details, see Initializers for Shared Libraries.  
To explicitly load a shared library, use the shl_loadroutine. If loading a  
C++ library, use the cxxshl_loadroutine. This ensures that  
constructors of nonlocal static objects are executed when the library is  
loaded. The syntax of cxxshl_loadis the same as that of shl_load.  
In 64-bit mode, shl_loadlets you load a compatibility or standard mode  
shared libraries. The BIND_BREADTH_FIRSTflag overrides the default  
depth-first loading mechanism.  
sh l_loa d Usa ge  
Since the library was not specified at link time, the program must get the  
library name at run time. Here are some practical ways to do this:  
Hard-code the library name into the program (the easiest method).  
Get the library name from an environment variable using the getenv  
library routine (see getenv(3C)).  
Get the library path name from the command line through argv.  
Read the library name from a configuration file.  
Prompt for the library path name at run time.  
If successful, shl_loadreturns a shared library handle (of type shl_t),  
which uniquely identifies the library. This handle can then be passed to  
the shl_findsymor shl_unloadroutine.  
218  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Once a library is explicitly loaded, use the shl_findsymroutine to get  
pointers to functions or data contained in the library; then call or  
reference them through the pointers. This is described in detail inThe  
shl_findsym Routine.  
sh l_loa d Exa m p le  
The following example shows the source for a function named load_lib  
that explicitly loads a library specified by the user. The user can specify  
the library in the environment variable SHLPATHor as the only  
argument on the command line. If the user chooses neither of these  
methods, the function prompts for the library path name.  
The function then attempts to load the specified library. If successful, it  
returns the shared library handle, of type shl_t. If an error occurs, it  
displays an error message and exits. This function is used later in The  
shl_findsym Routine.  
load_lib — Function to Load a Shared Library  
#include  
defs  
#include  
definition  
#include  
*/  
<stdio.h>  
/* contains standard I/O  
*/  
<stdlib.h>  
*/  
<dl.h>  
/* contains getenv  
/* contains shared library type defs  
shl_t load_lib(int argc,  
{
char * argv[])  
/* pass argc and argv from main */  
/* temporarily holds library  
/* holds library path  
shl_t  
handle */  
char  
lib_handle;  
lib_path[MAXPATHLEN];  
name  
*/  
char  
*env_ptr;  
/* points to SHLPATH variable  
value */  
/*  
* Get the shared library path name:  
*/  
if (argc > 1)  
*/  
/* library path given on command line  
strcpy(lib_path, argv[1]);  
else /* get lib_path from SHLPATH variable  
*/  
{
env_ptr = getenv(“SHLPATH”);  
if (env_ptr != NULL)  
strcpy(lib_path, env_ptr);  
else  
/* prompt user for shared library path  
*/  
{
printf(“Shared library to use >> “);  
scanf(“%s”, lib_path);  
}
Chapter 6  
219  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
}
/*  
* Dynamically load the shared library using BIND_IMMEDIATE  
binding:  
*/  
lib_handle = shl_load( lib_path, BIND_IMMEDIATE, 0);  
if (lib_handle == NULL)  
perror(“shl_load: error loading library”), exit(1);  
return lib_handle;  
}
BIND_NONF ATAL Mod ifier  
If you load a shared library with the BIND_IMMEDIATEflag and the  
library contains unresolved symbols, the load fails and sets errnoto  
ENOSYM. ORing BIND_NONFATALwith BIND_IMMEDIATEcauses  
shl_loadto allow the binding of unresolved symbols to be deferred if  
their later use can be detected — for example:  
shl_t libH;  
. . .  
libH = shl_load("libxyz.sl", BIND_IMMEDIATE | BIND_NONFATAL, 0);  
However, data symbol binding cannot be deferred, so using the  
BIND_NONFATALmodifier does not allow the binding of unresolved data  
symbols.  
BIND_VERBOSE Mod ifier  
If BIND_VERBOSEis ORed with the flags parameter, the dynamic loader  
displays messages for all unresolved symbols. This option is useful to see  
exactly which symbols cannot be bound. Typically, you would use this  
with BIND_IMMEDIATEto debug unresolved symbols — for example:  
shl_t libH;  
. . .  
libH = shl_load("libxyz.sl", BIND_IMMEDIATE | BIND_VERBOSE, 0);  
BIND_F IRST Mod ifier  
If BIND_FIRSTis ORed with the flags parameter, the loaded library is  
inserted before all other loaded shared libraries in the symbol resolution  
search order. This has the same effect as placing the library first in the  
link order — that is, the library is searched before other libraries when  
resolving symbols. This is used with either BIND_IMMEDIATEor  
BIND_DEFERRED— for example:  
shl_t libH;  
. . .  
libH = shl_load("libpdq.sl", BIND_DEFERRED | BIND_FIRST, 0);  
220  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
BIND_FIRSTis typically used when you want to make the symbols in a  
particular library more visible than the symbols of the same name in  
other libraries. Compare this with the default behavior, which is to  
append loaded libraries to the link order.  
DYNAMIC_PATH Mod ifier  
The flag DYNAMIC_PATHcan also be ORed with the flags parameter,  
causing the dynamic loader to search for the library using a path list  
specified by the +boption at link time or the SHLIB_PATHenvironment  
variable at run time.  
BIND_NOSTART Mod ifier  
The flag BIND_NOSTARTinhibits execution of initializers for the library.  
BIND_RESTRICTED Mod ifier  
This flag is most useful with the BIND_DEFERREDflag; it has no effect  
with BIND_IMMEDIATE. It is also useful with the BIND_NONFATALflag.  
When used with only the BIND_DEFERREDflag, it has this behavior:  
When a symbol is referenced and needs to be bound, this flag causes the  
search for the symbol definition to be restricted to those symbols that  
were visible when the library was loaded. If a symbol definition cannot  
be found within this restricted set, it results in a run-time  
symbol-binding error.  
When used with BIND_DEFERREDand the BIND_NONFATALmodifier, it  
has the same behavior, except that when a symbol definition cannot be  
found, the dynamic loader will then look in the global symbol set. If a  
definition still cannot be found within the global set, a run-time  
symbol-binding error occurs.  
BIND_TOGETHER Mod ifier  
BIND_TOGETHERmodifies the behavior of BIND_FIRST. When the  
library being loaded has dependencies, BIND_FIRSTcauses each  
dependent library to be loaded and bound separately. If the libraries  
have interdependencies, the load may fail because the needed symbols  
are not available when needed.  
Chapter 6  
221  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
BIND_FIRST | BIND_TOGETHERcauses the library being loaded and its  
dependent libraries to be bound all at the same time, thereby resolving  
interdependencies. If you are not using BIND_FIRST, libraries are bound  
together by default so this option has no effect.  
BIND_BREADTH_F IRST Mod ifier  
64-bit mode only:  
This flag causes the dependent libraries to be loaded breadth first. By  
default, the 64-bit mode shl_loadloads dependent libraries depth-first.  
This modifier overrides the default load order.  
Bin d in g F la gs Exa m p les  
Suppose you have the libraries libE.sl, libF.sl, and libG.sl. The  
libElibrary depends on libFand libFdepends on libG. In addition,  
libGdepends on libFlibFand libGare interdependent. Your  
program loads libE.slwith shl_load().  
When using BIND_DEFERREDor BIND_IMMEDIATEwithout  
BIND_FIRST, these libraries are loaded such that all symbols are visible  
and the interdependencies are resolved:  
shl_t libE;  
libE = shl_load("libE.sl", BIND_IMMEDIATE, 0);  
shl_load succeeds.  
When using BIND_IMMEDIATE | BIND_FIRST, however, libGis loaded  
and bound first and since it depends on libF, an error results because  
the needed symbols in libFare not yet available:  
libE = shl_load("libE.sl", BIND_IMMEDIATE | BIND_FIRST, 0);  
shl_load fails.  
Using BIND_IMMEDIATE | BIND_FIRST | BIND_TOGETHERloads  
libE, libF, and libGtogether and correctly resolves all symbols:  
libE = shl_load("libE.sl", BIND_IMMEDIATE | BIND_FIRST | BIND_TOG  
ETHER, 0);  
shl_load succeeds.  
Th e sh l_n d sym Rou tin e  
Obtains the address of an exported symbol from a shared library. To call  
a routine or access data in an explicitly loaded library, rst get the  
address of the routine or data with shl_findsym.  
222  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Syn ta x  
int shl_findsym( shl_t * handle,  
const char * sym,  
short type,  
void * value )  
Pa r a m eter s  
handle  
A pointer to a shared library handle of the library to  
search for the symbol name sym. This handle could be  
obtained from the shl_getroutine (described in the  
The shl_get and shl_get_r Routines). handle can also  
point to:  
NULL  
If a pointer to NULLis specified,  
shl_findsymsearches all loaded  
libraries for sym. If sym is found,  
shl_findsymsets handle to a  
pointer to the handle of the shared  
library containing sym. This is useful  
for determining which library a  
symbol resides in. For example, the  
following code sets handleto a  
pointer to the handle of the library  
containing symbol _foo:  
shl_t handle;  
handle = NULL;  
shl_findsym(&handle,"_foo",...);  
PROG_HANDLE This constant, defined in dl.h, tells  
shl_findsymto search for the  
symbol in the program itself. This  
way, any symbols exported from the  
program can be accessed explicitly.  
sym  
type  
A null-terminated character string containing the  
name of the symbol to search for.  
The type of symbol to look for. It must be one of the  
following values, defined in <dl.h>:  
TYPE_PROCEDURE  
Look for a function or procedure.  
TYPE_DATA  
Chapter 6  
223  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Look for a symbol in the data segment (for example,  
variables).  
TYPE_UNDEFINED  
Look for any symbol.  
TYPE_STORAGE  
32-bit mode only.  
TYPE_TSTORAGE  
32-bit mode only.  
value  
A pointer in which shl_findsymstores the address of  
sym, if found.  
Retu r n Va lu e  
If successful, shl_findsymreturns an integer (int) value zero. If  
shl_findsymcannot find sym, it returns 1 and sets errnoto zero. If  
any other errors occur, shl_findsymreturns 1 and sets errnoto one  
of these values (defined in <errno.h>):  
ENOEXEC  
ENOSYM  
EINVAL  
A format error was detected in the specified library.  
A symbol on which sym depends could not be found.  
The specified handle is invalid.  
Descr ip tion  
To call a routine or access data in an explicitly loaded library, rst get the  
address of the routine or data with shl_findsym.  
To call a routine in an explicitly loaded library  
1. declare a pointer to a function of the same type as the function in the  
shared library  
2. using shl_findsymwith the type parameter set to  
TYPE_PROCEDURE, find the symbol in the shared library and assign  
its address to the function pointer declared in Step 1  
3. call the pointer to the function obtained in Step 2, with the correct  
number and type of arguments  
To access data in an explicitly loaded library  
224  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
1. declare a pointer to a data structure of the same type as the data  
structure to access in the library  
2. using shl_findsymwith the type parameter set to TYPE_DATA, find  
the symbol in the shared library and assign its address to the pointer  
declared in Step 1  
3. access the data through the pointer obtained in Step 2  
sh l_n d sym Exa m p le  
Suppose you have a set of libraries that output to various graphics  
devices. Each graphics device has its own library. Although the actual  
code in each library varies, the routines in these shared libraries have  
the same name and parameters, and the global data is the same. For  
instance, they all have these routines and data:  
gopen()  
opens the graphics device for output  
closes the graphics device  
gclose()  
move2d(x,y)  
draw2d(x,y)  
maxX  
moves to pixel location x,y  
draws to pixel location x,y from current x,y  
contains the maximum X pixel location on the output  
device  
maxY  
contains the maximum Y pixel location on the output  
device  
The following example shows a C program that can load any supported  
graphics library at run time, and call the routines and access data in the  
library. The program calls load_lib(see load_lib — Function to Load a  
Shared Library) to load the library.  
Load a Shared Library and Call Its Routines and Access Its Data  
#include <stdio.h>  
#include <stdlib.h>  
#include <dl.h>  
/*  
/* contains standard I/O defs  
/* contains getenv definition  
*/  
*/  
/* contains shared library type defs */  
* Define linker symbols:  
*/  
#define GOPEN “gopen”  
#define GCLOSE “gclose”  
#define MOVE2D “move2d”  
#define DRAW2D “draw2d”  
#define MAXX  
#define MAXY  
“maxX”  
“maxY”  
Chapter 6  
225  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
shl_t load_lib(int argc, char * argv[]);  
main(int argc,  
char * argv[])  
{
shl_t lib_handle;  
/* handle of shared library  
/* opens the graphics device  
/* closes the graphics device  
*/  
*/  
*/  
int (*gopen)(void);  
int (*gclose)(void);  
int (*move2d)(int, int); /* moves to specified x,y location */  
int (*draw2d)(int, int); /* draw line to specified x,y location*/  
int *maxX;  
int *maxY;  
/* maximum X pixel on device  
/* maximum Y pixel on device  
*/  
*/  
lib_handle = load_lib(argc, argv); /* load required shared library */  
/*  
* Get addresses of all functions and data that will be used:  
*/  
if (shl_findsym(&lib_handle, GOPEN, TYPE_PROCEDURE, (void *) &gopen))  
perror(“shl_findsym: error finding function gopen”), exit(1);  
if (shl_findsym(&lib_handle, GCLOSE, TYPE_PROCEDURE, (void *) &gclose))  
perror(“shl_findsym: error finding function gclose”), exit(1);  
if (shl_findsym(&lib_handle, MOVE2D, TYPE_PROCEDURE, (void *) &move2d))  
perror(“shl_findsym: error finding function move2d”), exit(1);  
if (shl_findsym(&lib_handle, DRAW2D, TYPE_PROCEDURE, (void *) &draw2d))  
perror(“shl_findsym: error finding function draw2d”), exit(1);  
if (shl_findsym(&lib_handle, MAXX, TYPE_DATA, (void *) &maxX))  
perror(“shl_findsym: error finding data maxX”), exit(1);  
if (shl_findsym(&lib_handle, MAXY, TYPE_DATA, (void *) &maxY))  
perror(“shl_findsym: error finding data maxY”), exit(1);  
/*  
* Using the routines, draw a line from (0,0) to (maxX,maxY):  
*/  
(*gopen)();  
/* open the graphics device  
/* move to pixel 0,0  
*/  
*/  
(*move2d)(0,0);  
(*draw2d)(*maxX,*maxY);  
(*gclose)();  
/* draw line to maxX,maxY pixel */  
/* close the graphics device  
*/  
}
Shown below is the compile line for this program, along with the  
commands to set SHLPATHappropriately before running the program.  
SHLPATHis declared and used by load_lib(), defined inThe shl_load  
and cxxshl_load Routines” example. Notice that load_lib()is compiled  
here along with this program. Finally, this example assumes you have  
created a graphics library, libgrphdd.sl:  
$ cc -Aa -o drawline shl_findsym.c load_lib.c -ldld  
$ SHLPATH=/usr/lib/libgrphdd.sl  
$ export SHLPATH  
$ drawline  
Th e sh l_get a n d sh l_get_r Rou tin es  
Obtains information on the currently loaded libraries.  
226  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Syn ta x  
int shl_get( int index,  
struct shl_descriptor **desc )  
Pa r a m eter s  
index  
Specifies an ordinal number of the shared library in the  
process. For libraries loaded implicitly (at startup  
time), index is the ordinal number of the library as it  
appeared on the command line. For example, if libc  
was the first library specified on the ldcommand line,  
then libchas an index of 1. For explicitly loaded  
libraries, index corresponds to the order in which the  
libraries were loaded, starting after the ordinal  
number of the last implicitly loaded library. Two index  
values have special meaning:  
0
Refers to the main program itself  
1  
Refers to the dynamic loader  
(dld.sl).  
A shared library's index can be modified during  
program execution by either of the following events:  
The program loads a shared library with the  
BIND_FIRSTmodifier to shl_load. This  
increments all the shared library indexes by one.  
The program unloads a shared library with  
shl_unload. Any libraries following the unloaded  
library have their index decremented by one.  
desc  
Returns a pointer to a statically allocated buffer  
(struct shl_descriptor **) containing a shared  
library descriptor. The structure contains these  
important fields:  
tstart  
The start address (unsigned long)  
of the shared library text segment.  
tend  
The end address (unsigned long) of  
the shared library text segment.  
dstart  
The start address (unsigned long)  
of the shared library data segment.  
Chapter 6  
227  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
dend  
The end address (unsigned long) of  
the shared library bss segment. The  
data and bss segments together form  
a contiguous memory block starting  
at dstartand ending at dend.  
handle  
The shared library's handle (type  
shl_t).  
filename  
A character array containing the  
library's path name as specified at  
link time or at explicit load time.  
initializer A pointer to the shared library's  
initializer routine (see Initializers  
for Shared Libraries. It is NULLif  
there is no initializer. This field is  
useful for calling the initializer if it  
was disabled by the BIND_NOSTART  
flag to shl_load.  
If the shared library has multiple  
initializers, this field will also be set  
to NULL. Multiple initializers can be  
found with shl_getsymbols,  
described later in this chapter.  
This buffer is statically allocated. Therefore, if a  
program intends to use any of the members of the  
structure, the program should make a copy of the  
structure before the next call to shl_get. Otherwise,  
shl_getwill overwrite the static buffer when called  
again.  
Retu r n Va lu e  
If successful, shl_getreturns an integer value 0. If the index value  
exceeds the number of currently loaded libraries, shl_getreturns 1  
and sets errnoto EINVAL.  
228  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Descr ip tion  
To obtain information on currently loaded libraries, use the shl_get  
function. If you are programming in a threaded environment, use the  
thread-safe version shl_get_rwhich is the same as shl_getin all  
other respects. (See Programming with Threads on HP-UX for more  
information about threads.)  
Other than obtaining interesting information, this routine is of little use  
to most programmers. A typical use might be to display the names and  
starting/ending address of all shared libraries in a process's virtual  
memory address space.  
Exa m p le  
The function show_loaded_libsshown below displays the name and  
start and end address of the text and data/bss segments the library  
occupies in a process's virtual address space.  
show_loaded_libs — Display Library Information  
#include  
#include  
void  
<stdio.h>  
<dl.h>  
/* contains standard I/O defs  
/* contains shared library type defs  
*/  
*/  
show_loaded_libs(void)  
{
int  
idx;  
struct shl_descriptor *desc;  
printf(“SUMMARY of currently loaded libraries:\n”);  
printf(“%-25s %10s %10s %10s %10s\n”,  
“___library___”, “_tstart_”, “__tend__”, “_dstart_”, “__dend__”);  
idx = 0;  
for (idx = 0; shl_get(idx, &desc) != -1; idx++)  
printf(“%-25s %#10lx %#10lx %#10lx %#10lx\n”,  
desc->filename, desc->tstart, desc->tend, desc->dstart, desc->dend);  
}
Calling this function from a C program compiled with shared libcand  
libdldproduced the following output:  
SUMMARY of currently loaded libraries:  
___library___  
./a.out  
_tstart_  
0x1000  
__tend__  
_dstart_  
__dend__  
0x1918 0x40000000 0x40000200  
/usr/lib/libdld.sl 0x800ac800 0x800ad000 0x6df62800 0x6df63000  
/usr/lib/libc.sl  
0x80003800 0x80091000 0x6df63000 0x6df85000  
Chapter 6  
229  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Th e sh l_geth a n d le a n d sh l_geth a n d le_r  
Rou tin es  
Returns descriptor information about a loaded shared library.  
Syn ta x  
int shl_gethandle( shl_t handle,  
struct shl_descriptor **desc )  
Pa r a m eter s  
handle  
The handle of the shared library you want information  
about. This handle is the same as that returned by  
shl_load.  
desc  
Points to shared library descriptor information — the  
same information returned by the shl_getroutine.  
The buffer used to store this desc information is static,  
meaning that subsequent calls to shl_gethandlewill  
overwrite the same area with new data. Therefore, if  
you need to save the desc information, copy it  
elsewhere before calling shl_gethandleagain.  
Retu r n Va lu e  
If handle is not valid, the routine returns 1 and sets errnoto EINVAL.  
Otherwise, shl_gethandlereturns 0.  
Descr ip tion  
The shl_gethandleroutine returns descriptor information about a  
loaded shared library. If you are programming in a threaded  
environment, use the thread-safe version shl_gethandle_rwhich is  
the same as shl_gethandlein all other respects. (See Programming  
with Threads on HP-UX for more information about threads.)  
Exa m p le  
The following function named show_lib_infodisplays information  
about a shared library, given the library's handle.  
show_lib_info — Display Information for a Shared Library  
#include <stdio.h>  
#include <dl.h>  
230  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
int show_lib_info(shl_t libH)  
{
struct shl_descriptor *desc;  
if (shl_gethandle(libH, &desc) == -1)  
{
fprintf(stderr, "Invalid library handle.\\n");  
return -1;  
}
printf("library path:  
printf("text start:  
printf("text end:  
printf("data start:  
printf("data end:  
return 0;  
%s\\n", desc->filename);  
%#10lx\\n", desc->tstart);  
%#10lx\\n", desc->tend);  
%#10lx\\n", desc->dstart);  
%#10lx\\n", desc->dend);  
}
Th e sh l_d efin esym Rou tin e  
Adds new symbols to the global shared library symbol table.  
Syn ta x  
int shl_definesym( const char *sym,  
short type,  
long value,  
int flags )  
Pa r a m eter s  
sym  
A null-terminated string containing the name of the  
symbol to change or to add to the process's shared  
library symbol table.  
type  
The type of symbol — either TYPE_PROCEDUREor  
TYPE_DATA.  
value  
If value falls in the address range of a currently loaded  
library, an association will be made and the symbol is  
undefined when the library is unloaded. (Note that  
memory dynamically allocated with malloc(3C) does  
not fall in the range of any library.) The defined symbol  
may be overridden by a subsequent call to this routine  
or by loading a more visible library that provides a  
definition for the symbol.  
flags  
Must be set to zero.  
Chapter 6  
231  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Retu r n Va lu e  
If successful, shl_definesymreturns 0. Otherwise, it returns 1 and  
sets errnoaccordingly. See shl_definesym(3X) for details.  
Descr ip tion  
The shl_definesymfunction allows you to add a new symbol to the  
global shared library symbol table. Use of this routine will be  
unnecessary for most programmers.  
There are two main reasons to add or change shared library symbol table  
entries:  
to generate symbol definitions as the program runs — for example,  
aliasing one symbol with another  
to override a current definition  
Symbol definitions in the incomplete executable may also be redefined  
with certain restrictions:  
The incomplete executable always uses its own definition for any data  
(storage) symbol, even if a more visible one is provided.  
The incomplete executable only uses a more visible code symbol if the  
main program itself does not provide a definition.  
Th e sh l_getsym bols Rou tin e  
The shl_getsymbolsfunction retrieves symbols that are imported  
(referenced) or exported (defined) by a shared library. This information is  
returned in an allocated array of records, one for each symbol. Most  
programmers do not need to use this routine.  
Syn ta x  
int shl_getsymbols( shl_t handle,  
short type,  
int flags,  
void * (*memfunc)(),  
struct shl_symbol **symbols )  
232  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Pa r a m eter s  
handle  
The handle of the shared library whose symbols you  
want to retrieve. If handle is NULL, shl_getsymbols  
returns symbols that were defined with the  
shl_definesymroutine.  
type  
Defines the type of symbol to retrieve. It must be one of  
the following values, which are defined as constants in  
<dl.h>:  
TYPE_PROCEDURE  
Retrieve only function or procedure symbols.  
TYPE_DATA  
Retrieve only symbols from the data segment (for  
example, variables).  
TYPE_UNDEFINED  
Retrieve all symbols, regardless of type.  
TYPE_STORAGE  
32-bit mode only.  
TYPE_TSTORAGE  
32-bit mode only.  
flags  
Defines whether to retrieve import or export symbols  
from the library. An im p or t sym bol is an external  
reference made from a library. An exp or t sym bol is a  
symbol definition that is referenced outside the library.  
In addition, any symbol defined by shl_definesymis  
an export symbol. Set this argument to one of the  
following values (defined in <dl.h>):  
IMPORT_SYMBOLS  
To return import symbols.  
EXPORT_SYMBOLS  
To return export symbols.  
INITIALIZERS  
To return initializer symbols.  
Chapter 6  
233  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
One of the following modifiers can be ORed with both  
the EXPORT_SYMBOLSand the INITIALIZERSflags:  
NO_VALUES  
Do not calculate the valuefield of  
the shl_symbolstructure for  
symbols. The valuefield has an  
undefined value.  
GLOBAL_VALUES  
For symbols that are defined in  
multiple libraries, this flag causes  
shl_getsymbolsto return the  
most-visible occurrence, and to set  
the valueand handlefields of the  
shl_symbolstructure (defined in  
the description of the symbols  
parameter).  
memfunc  
symbols  
Points to a function that has the same interface (calling  
conventions and return value) as malloc(3C). The  
shl_getsymbolsfunction uses this function to  
allocate memory to store the array of symbol records,  
symbols.  
This points to an array of symbol records for all  
symbols that match the criteria determined by the type  
and value parameters. The type of these records is  
struct shl_symbol, defined in <dl.h>as:  
struct shl_symbol {  
char * name;  
short type;  
void * value;  
shl_t handle;  
};  
The members of this structure are described in The  
shl_symbol Structure.  
Retu r n Va lu e  
If successful, shl_getsymbolsreturns the number of symbols found;  
otherwise, 1 is returned and shl_getsymbolssets errnoto one of  
these values:  
ENOEXEC  
A format error was detected in the specified library.  
234  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
ENOSYM  
Some symbol required by the shared library could not  
be found.  
EINVAL  
ENOMEM  
The specified handle is invalid.  
memfunc failed to allocate the requested memory.  
Th e sh l_sym bol Str u ctu r e  
The members of the shl_symbolstructure are defined as follows:  
name  
type  
Contains the name of a symbol.  
Contains the symbol's type: TYPE_PROCEDURE,  
TYPE_DATA, or TYPE_STORAGE. TYPE_STORAGEis a  
data symbol used for C uninitialized global variables or  
FORTRAN common blocks.  
value  
Contains the symbol's address. It is valid only if  
EXPORT_SYMBOLSis specified without the NO_VALUES  
modifier.  
handle  
Contains the handle of the shared library in which the  
symbol is found, or NULLin the case of symbols defined  
by shl_definesym. It is valid only if  
EXPORT_SYMBOLSor INITIALIZERSwere requested  
without the NO_VALUESmodifier. It is especially useful  
when used with the GLOBAL_VALUESmodifier, allowing  
you to determine the library in which the most-visible  
definition of a symbol occurs.  
sh l_getsym bols Exa m p le  
show_symbols — Display Shared Library Symbols” shows the source for  
a function named show_symbolsthat displays shared library symbols.  
The syntax of this routine is defined as:  
int show_symbols(shl_t hndl,  
short type,  
int  
flags)  
hndl  
The handle of the shared library whose symbols you  
want to display.  
Chapter 6  
235  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
type  
The type of symbol you want to display. This is the  
same as the type parameter to shl_getsymbolsand  
can have these values: TYPE_PROCEDURE, TYPE_DATA,  
or TYPE_UNDEFINED. If it is TYPE_UNDEFINED,  
show_symbolsdisplays the type of each symbol.  
flags  
This is the same as the flags parameter. It can have the  
value EXPORT_SYMBOLSor IMPORT_SYMBOLS. In  
addition, it can be ORed with NO_VALUESor  
GLOBAL_VALUES. If EXPORT_SYMBOLSis specified  
without being ORed with NO_VALUES, show_symbols  
displays the address of each symbol.  
show_symbols — Display Shared Library Symbols  
#include <dl.h>  
#include <stdio.h>  
#include <stdlib.h>  
int show_symbols(shl_t  
hndl,  
type,  
flags)  
short  
int  
{
int  
num_symbols, sym_idx;  
struct shl_symbol *symbols, *orig_symbols;  
num_symbols = shl_getsymbols(hndl, type, flags, malloc,  
&symbols);  
if (num_symbols < 0) {  
printf(“shl_getsymbols failed\n”);  
exit(1);  
}
orig_symbols = symbols;  
for (sym_idx = 0; sym_idx < num_symbols; sym_idx++)  
{
printf(“  
%-30s”, symbols->name); /* display symbol name  
*/  
if (type == TYPE_UNDEFINED) /* display type if TYPE_UNDEFINED */  
switch (symbols->type) {  
case TYPE_PROCEDURE:  
printf(“ PROCEDURE”);  
break;  
case TYPE_DATA:  
printf(“ DATA  
break;  
“);  
case TYPE_STORAGE:  
printf(“ STORAGE “);  
}
if ((flags & EXPORT_SYMBOLS)  
/* export symbols requested  
/* NO_VALUES was NOT  
*/  
&& (flags & NO_VALUES)==0)  
specified */  
printf(“ 0x%8X”, symbols->value); /* so display symbol’s  
address */  
printf(“\n”);  
/* terminate output line  
*/  
symbols++;  
/* move to next symbol record  
236  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
*/  
}
free(orig_symbols);  
/* free memory allocated by  
malloc */  
return num_symbols;  
*/  
}
/* return the number of symbols  
The following example shows the source for a program named  
show_all.cthat calls show_symbolsto show all imported and  
exported symbols for every loaded shared library. It uses shl_getto get  
the library handles of all loaded libraries.  
show_all — Use show_symbols to Show All Symbols  
#include <dl.h>  
#include <stdio.h>  
/* prototype for show_syms */  
int show_syms(shl_t hndl, short type, int flags);  
main()  
{
int  
idx, num_syms;  
struct shl_descriptor * desc;  
for (idx=0; shl_get(idx, &desc) != -1; idx++) /* step through  
libs */  
{
printf(“[%s]\n”, desc->filename); /* show imports & exports for  
each */  
printf(“ Imports:\n”);  
num_syms = show_symbols(desc->handle, TYPE_UNDEFINED,  
IMPORT_SYMBOLS);  
printf(“  
printf(“ Exports:\n”);  
TOTAL SYMBOLS: %d\n”, num_syms);  
num_syms = show_symbols(desc->handle, TYPE_UNDEFINED,  
EXPORT_SYMBOLS);  
printf(“  
}
TOTAL SYMBOLS: %d\n”, num_syms);  
}
The show_allprogram shown above was compiled with the command:  
$ cc -Aa -o show_all show_all.c show_symbols.c -ldld  
NOTE  
The following output for the example will differ in 64-bit mode. For  
example, STORAGEis not supported.  
The output produced by running this program is shown below:  
[show_all]  
Imports:  
errno  
_start  
malloc  
free  
STORAGE  
PROCEDURE  
PROCEDURE  
PROCEDURE  
PROCEDURE  
exit  
Chapter 6  
237  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
printf  
shl_get  
PROCEDURE  
PROCEDURE  
PROCEDURE  
PROCEDURE  
shl_getsymbols  
__d_trap  
TOTAL SYMBOLS: 9  
Exports:  
environ  
errno  
DATA  
0x40001018  
0x400011CC  
0x40001008  
0x400011C8  
0x4000100C  
0x400011D0  
0x40001018  
STORAGE  
DATA  
_SYSTEM_ID  
__dld_loc  
STORAGE  
DATA  
_FPU_MODEL  
_end  
DATA  
DATA  
_environ  
__d_trap  
PROCEDURE 0x7AFFF1A6  
PROCEDURE 0x7AFFF1BE  
main  
TOTAL SYMBOLS: 9  
[/usr/lib/libc.1]  
Imports:  
_res_rmutex  
errno  
STORAGE  
STORAGE  
STORAGE  
STORAGE  
STORAGE  
STORAGE  
STORAGE  
STORAGE  
STORAGE  
STORAGE  
STORAGE  
_regrpc_rmutex  
_yellowup_rmutex  
_FPU_MODEL  
_environ_rmutex  
_iop_rmutex  
_rpcnls_rmutex  
_switch_rmutex  
_mem_rmutex  
_dir_rmutex  
Th e sh l_u n loa d a n d cxxsh l_u n loa d Rou tin es  
Unloads or frees up space for a shared library.  
Syn ta x  
int shl_unload(shl_t handle)  
Pa r a m eter s  
handle  
The handle of the shared library you wish to unload.  
The handle value is obtained from a previous call to  
shl_load, shl_findsym, or shl_get.  
Retu r n Va lu e  
If successful, shl_unloadreturns 0. Otherwise, shl_unloadreturns 1  
and sets errnoto an appropriate value:  
EINVAL  
Indicates the specified handle is invalid.  
238  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The shl_load Shared Library Management Routines  
Descr ip tion  
To unload a shared library, use the shl_unloadfunction. One reason to  
do this is to free up the private copy of shared library data and swap  
space allocated when the library was loaded with shl_load. (This is  
done automatically when a process exits.)  
Another reason for doing this occurs if a program needs to replace a  
shared library. For example, suppose you implement some sort of shell or  
interpreter, and you want to load and execute user programs” which are  
actually shared libraries. So you load one program, look up its entry  
point, and call it. Now you want to run a different program. If you do not  
unload the old one, its symbol definitions might get in the way of the new  
library. So you should unload it before loading the new library.  
Note that if shared library initializers have been declared for a shared  
library, they will be called when the shared library is explicitly unloaded.  
For details, see Initializers for Shared Libraries.  
If unloading a C++ library, use the cxxshl_unloadroutine. This  
ensures that destructors of nonlocal static objects are executed when the  
library is unloaded. The syntax of cxxshl_unloadis the same as that of  
shl_unload.  
Usa ge  
When a library is unloaded, existing linkages to symbols in an unloaded  
library are not invalidated. Therefore, the programmer must ensure that  
the program does not reference symbols in an unloaded library as  
undefined behavior will result. In general, this routine is recommended  
only for experienced programmers.  
In 32-bit mode the shl_unloadroutine unloads a shared library  
irrespective of whether other shared libraries depend on it. In 64-bit  
mode shl_unloadunloads a shared library only if no other shared  
library depend on it.  
Chapter 6  
239  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
Th e d lop en Sh a r ed Libr a r y  
Ma n a gem en t Rou tin es  
This section describes the dl*family of shared library management  
routines.  
NOTE  
Use these routines in 64-bit mode only  
Th e d lop en Rou tin e  
Opens a shared library.  
Syn ta x  
void *dlopen(const char *file, int mode);  
Pa r a m eter s  
Pa r m  
file  
Defin ition  
Used to construct a pathname to the shared library file.  
If files contain a slash character (/), dlopenuses the file argument itself as the  
pathname. If not, dlopensearches a series of directories for file.  
Any directories specified by the environment variable LD_LIBRARY_PATH.  
Any directories specified by the RPATHof the calling load module.  
The directories /usr/lib/pa20_64and usr/ccs/lib/pa20_64.  
240  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
Pa r m  
Defin ition  
flags  
Mod e  
Defin ition  
RTLD_LAZY  
Under this mode, only references to data symbols are  
relocated when the library t is loaded. References to functions  
are not relocated until a given function is invoked for the first  
time. This mode should result in better performance, since a  
process may not reference all of the functions in any given  
shared object.  
RTLD_NOW  
Under this mode, all necessary relocations are performed  
when the library is first loaded. This can cause some wasted  
effort, if relocations are performed for functions that are  
never referenced, but is useful for applications that need to  
know as soon as an object is loaded that all symbols  
referenced during execution are available.  
RTLD_GLOBAL  
RTLD_LOCAL  
The shared library's symbols are made available for the  
relocation processing of any other object. In addition, symbol  
lookup using dlopen(0, mode)and an associated dlsym()  
allows objects loaded with RTLD_GLOBALto be searched.  
The shared librarys symbols are made available for  
relocation processing only to objects loaded in the same  
dlopeninvocation.  
If neither RTLD_GLOBALnor RTLD_LOCALare specified, the  
default is RTLD_LOCAL.  
Retu r n Va lu es  
A successful dlopencall returns to the process a handle which the  
process can use on subsequent calls to dlsymand dlclose. This value  
should not be interpreted in any way by the process.  
dlopenreturns NULL under the following conditions:  
file cannot be found.  
file cannot be opened for reading.  
file is not a shared object.  
An error occurs during the process of loading file or relocating its  
symbolic references.  
Chapter 6  
241  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
More detailed diagnostic information is available through dlerror.  
Descr ip tion  
dlopenis one of a family of routines that give the user direct access to  
the dynamic linking facilities. dlopenmakes a shared library specified  
by a file available to a running process. A shared library may specify  
other objects that it needs” in order to execute properly. These  
dependencies are specified by DT_NEEDEDentries in the.dynamic section  
of the original shared library. Each needed shared library may, in turn,  
specify other needed shared libraries. All such shared libraries are  
loaded along with the original shared library as a result of the call to  
dlopen.  
If the value of file is 0, dlopenprovides a handle on a “global symbol  
shared library.” This shared library provides access to the symbols from  
an ordered set of shared libraries consisting of the original a.out, all of  
the shared libraries that were loaded at program startup along with the  
a.out, and all shared libraries loaded using a dlopenoperation along  
with the RTLD_GLOBALflag. As the latter set of shared libraries can  
change during execution, the set identified by handle can also change  
dynamically.  
Only a single copy of an shared library file is brought into the address  
space, even if dlopenis invoked multiple times in reference to the file,  
and even if different pathnames are used to reference the file.  
When a shared library is brought into the address space of a process, it  
can contain references to symbols whose addresses are not known until  
the shared library is loaded. These references must be relocated before  
the symbols can be accessed. The mode parameter governs when these  
relocations take place and may have the following values (defined in  
Parameters): RTLD_LAZYand RTLD_NOW.  
Any shared library loaded by dlopenthat requires relocations against  
global symbols can reference the following:  
Symbols in the original a.out.  
Any shared libraries loaded at program startup, from the shared  
library itself.  
Any shared library included in the same dlopeninvocation.  
Any shared libraries that were loaded in any dlopeninvocation that  
specified the RTLD_GLOBALflag.  
242  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
To determine the scope of visibility for the symbols loaded with a dlopen  
invocation, bitwise OR the mode parameter with one of the following  
values: RTLD_GLOBALor RTLD_LOCAL.  
If neither RTLD_GLOBALnor RTLD_LOCALare specified, the default is  
RTLD_LOCAL.  
If a file is specified in multiple dlopeninvocations, mode is interpreted  
at each invocation. Note, however, that once RTLD_NOWhas been  
specified, the linker operation completes all relocations, rendering any  
further RTLD_NOWoperations redundant and any further RTLD_LAZY  
operations irrelevant. Similarly note that once you specify  
RTLD_GLOBAL, the shared library maintains the RTLD_GLOBALstatus  
regardless of any previous or future specification of RTLD_LOCAL, as long  
as the shared library remains in the address space [see dlclose(3C)].  
Symbols introduced into a program through calls to dlopenmay be used  
in relocation activities. Symbols so introduced may duplicate symbols  
already defined by the program or previous dlopenoperations. To  
resolve the ambiguities such a situation might present, the resolution of  
a symbol reference to a symbol definition is based on a symbol resolution  
order. Two such resolution orders are defined: load and dependency  
ordering.  
Load order establishes an ordering among symbol definitions using  
the temporal order in which the shared libraries containing the  
definitions were loaded, such that the definition first loaded has  
priority over definitions added later. Load ordering is used in  
relocation processing.  
Dependency ordering uses a breadth-first” order starting with a  
given shared library, then all of its dependencies, then any  
dependents of those, iterating until all dependencies are satisfied.  
The dlsymfunction uses dependency ordering, except when the global  
symbol shared library is obtained via a dlopenoperation on file with a  
value 0. The dlsymfunction uses load ordering on the global symbol  
shared library.  
When a dlopenoperation first makes it accessible, an shared library  
and its dependent shared libraries are added in dependency order. Once  
all shared libraries are added, relocations are performed using load  
order. Note that if an shared library and its dependencies have been  
loaded by a previous dlopeninvocation or on startup, the load and  
dependency order may yield different resolutions.  
Chapter 6  
243  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
The symbols introduced by dlopenoperations and available through  
dlsymare those which are exported” as symbols of global scope by the  
shared library. For shared libraries, such symbols are typically those that  
were specified in (for example) C source code as having externlinkage.  
For a.outfiles, only a subset of externally visible symbols are typically  
exported: specifically those referenced by the shared libraries with which  
the a.outis linked. The exact set of exported symbols for any shared  
library or the a.outcan be controlled using the linker [see ld(1)].  
NOTE  
The environment variable LD_LIBRARY_PATHshould contain a  
colon-separated list of directories, in the same format as the PATH  
variable [see sh(1)]. LD_LIBRARY_PATHis ignored if the process’ real  
user id is different from its effective user id or its real group id is  
different from its effective group id [see exec(2)] or if the process has  
acquired any privileges [see tfadmin(1M)].  
Exa m p le  
The following example shows how to use dlopento load a shared library.  
The RTLD_GLOBALflag enables global visibility to symbols in lib1.sl.  
The RTLD_LAZYflag indicates that only references to data symbols are to  
be relocated and all function symbol references are to be delayed until  
their first invocation.  
#include <stdio.h>  
#include <dlfcn.h>  
int main(int argc, char **argv)  
{
void* handle;  
handle = dlopen(“./lib1.sl”, RTLD_GLOBAL | RTLD_LAZY);  
if (handle == NULL) {  
printf(“Cannot load library\n”);  
}
}
Th e d ler r or Rou tin e  
Gets diagnostic information.  
Syn ta x  
char *dlerror(void);  
244  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
Descr ip tion  
dlerrorreturns a null-terminated character string (with no trailing  
newline character) that describes the last error that occurred during  
dynamic linking processing. If no dynamic linking errors have occurred  
since the last invocation of dlerror, it returns NULL. Thus, invoking  
dlerrora second time, immediately following a prior invocation, results  
in NULL being returned.  
NOTE  
The messages returned by dlerrormay reside in a static buffer that is  
overwritten on each call to dlerror. Application code should not write to  
this buffer. Programs wishing to preserve an error message should make  
their own copies of that message.  
Exa m p le  
The following code sequence shows how to use dlerrorto get diagnostic  
information.  
void*handle;  
/* Try to load a non-existing library */  
handle = dlopen(“invalid.sl”, RTLD_GLOBAL | RTLD_LAZY);  
if (handle == NULL) {  
printf(“%s\n”, dlerror());  
}
Th e d lsym Rou tin e  
Gets the address of a symbol in shared library.  
Syn ta x  
void *dlsym(void *handle, const char *name);  
Chapter 6  
245  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
Pa r a m eter s  
Pa r a m eter  
handle  
Defin ition  
Either the value returned by a call to dlopenor  
the special flag RTLD_NEXT. In the former case,  
the corresponding shared library must not have  
been closed using dlclose.  
name  
The symbol's name as a character string.  
Retu r n Va lu es  
If handle does not refer to a valid shared library opened by dlopen, or if  
the named symbol cannot be found within any of the shared libraries  
associated with handle, dlsymreturns NULL. The dlerrorroutine  
provides more detailed diagnostic information.  
Descr ip tion  
dlsymallows a process to obtain the address of a symbol defined within  
a shared library previously opened by dlopen.  
The dlsymroutine searches for the named symbol in all shared libraries  
loaded automatically as a result of loading the shared library referenced  
by handle [see dlopen(3C)].  
If handle is RTLD_NEXT, the search begins with the next” shared library  
after the shared library from which dlsymwas invoked. Shared libraries  
are searched using a load order symbol resolution algorithm [see  
dlopen(3C)]. The next” shared library, and all other shared libraries  
searched, are either of global scope (because they were loaded at startup  
or as part of a dlopenoperation with the RTLD_GLOBALflag) or are  
shared libraries loaded by the same dlopenoperation that loaded the  
caller of dlsym.  
Usa ge  
RTLD_NEXTcan be used to navigate an intentionally created hierarchy of  
multiply defined symbols created through interposition. For example, if a  
program wished to create an implementation of mallocthat embedded  
some statistics gathering about memory allocations, such an  
implementation could define its own mallocwhich would gather the  
246  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
necessary information, and use dlsymwith RTLD_NEXTto find the real”  
malloc, which would perform the actual memory allocation. Of course,  
this real” malloccould be another user-defined interface that added its  
own value and then used RTLD_NEXTto find the system malloc.  
Exa m p les  
The following example shows how to use dlopenand dlsymto access  
either function or data objects. (For simplicity, error checking has been  
omitted.)  
void *handle;  
int i, *iptr;  
int (*fptr)(int);  
/* open the needed object */  
handle = dlopen("/usr/mydir/mylib.so", RTLD_LAZY);  
/* find address of function and data objects */  
fptr = (int (*)(int))dlsym(handle, "some_function");  
iptr = (int *)dlsym(handle, "int_object");  
/* invoke function, passing value of integer as a parameter */  
i = (*fptr)(*iptr);  
The next example shows how to use dlsymwith RTLD_NEXTto add  
functionality to an existing interface. (Error checking has been omitted.)  
extern void record_malloc(void *, size_t);  
void *  
malloc(size_t sz)  
{
void *ptr;  
void *(*real_malloc)(size_t);  
real_malloc = (void * (*) (size_t))  
dlsym(RTLD_NEXT, "malloc");  
ptr = (*real_malloc)(sz);  
record_malloc(ptr, sz);  
return ptr;  
}
Chapter 6  
247  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
Th e d lget Rou tin e  
Retrieves information about a loaded module (program or shared  
library).  
Syn ta x  
void *dlget(unsigned int index,  
struct load_module_desc *desc,  
size_t desc_size);  
Pa r a m eter s  
Pa r a m eter  
Defin ition  
index  
Specifies the requested shared library by its placement  
on the dynamic loader's search list. An index of zero  
requests information about the program file itself. An  
index of -1 requests info about the dynamic loader.  
desc  
Must be preallocated by the user. The structure  
members are filled in by the dynamic loader with  
information about the requested shared library.  
desc_size  
Specifies the size in bytes of the load_module_desc  
structure sent in by the user.  
Retu r n Va lu es  
If successful, dlgetreturns a handle for the shared library as defined by  
the return value from dlopen(). If a call to dlgetis unsuccessful, a  
NULL pointer is returned and desc remains unchanged.  
Descr ip tion  
dlgetis one of a family of routines that give the user direct access to the  
dynamic linking facilities. dlgetretrieves information about a load  
module from an index specifying the placement of a load module in the  
dynamic loaders search list.  
A load_module_desc structure has the following members:  
248  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
struct load_module_desc {  
unsigned long text_base;  
unsigned long text_size;  
unsigned long data_base;  
unsigned long data_size;  
unsigned long unwind_base;  
unsigned long linkage_ptr;  
unsigned long phdr_base;  
unsigned long tls_size;  
unsigned long tls_start_addr;  
}
Exa m p le  
The following code sequence shows how to use dlgetto retrieve  
information about loaded modules. The following code sequence prints  
the text base of all loaded modules:  
void*  
int  
struct  
handle;  
index;  
load_module_desc desc;  
for (index = 0; ; i++) {  
handle = dlget(i, &desc, sizeof(struct load_module_desc));  
if (handle = NULL) {  
printf(“%s\n”, dlerror());  
break;  
}
else {  
printf(“library %d text base = %lx\n”, index,  
desc.text_base);  
}
}
Th e d lm od in fo Rou tin e  
Retrieves information about a loaded module (program or shared  
library).  
Syn ta x  
cc [flag...] file...  
#include <dlfcn.h>  
-ldl [library]...  
unsigned long dlmodinfo(unsigned long ip_value,  
struct load_module_desc *desc,  
size_t desc_size,  
void *(*read_tgt_mem)(void* buffer,  
unsigned long ptr,  
size_t bufsiz,  
int ident),  
Chapter 6  
249  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
int ident_parm,  
uint64_t load_map_parm);  
Pa r a m eter s  
Pa r a m eter  
ip_value  
Descr ip tion  
An address. The instruction pointer value of the requested library.  
desc  
A buffer of memory allocated by the user program. The dynamic  
loader fills this in with module information.  
desc_size  
Size in bytes of the desc buffer.  
read_tgm_mem  
A pointer to a function used by dlmodinfoto retrieve needed  
information.  
If the value is NULL, the dynamic loader uses its own internal data  
structures to find the correct load module and ignore the  
ident_parm and load_map_parm parameters.  
buffer  
ptr  
A buffer supplied by dlmodinfoto read into.  
The virtual memory address to read from.  
Tthe size of buffer in bytes.  
bufsiz  
ident  
The value of the ident_parm parameter to dlmodinfo.  
ident_parm  
Only used to pass the fourth parameter to read_tgt_mem.  
load_map_parm  
Only used when calling through read_tgt_mem. Contains the  
starting address of the load map.  
Retu r n Va lu es  
If successful, dlmodinforeturns a handle for the shared library as  
defined by the return value from dlopen(). NULL is returned  
otherwise. The return values are type-converted to unsigned long  
Descr ip tion  
dlmodinfois one of a family of routines that give the user direct access  
to the dynamic linking facilities. The dlmodinforoutine retrieves  
information about a load module from a given address value. dlmodinfo  
250  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
searches all currently loaded load modules looking for a load module  
whose address range (address range of all loaded segments) holds the  
given address value. The dlmodinforoutine fills the load_module_desc  
with information from the matching load module.  
read_tgm_mem allows dlmodinfoto find a load module in one process  
on behalf of another. The calling process passes a callback via  
read_tgt_mem in order to read memory in a different process address  
space from the one in which dlmodinforesides. ip_value,  
load_map_parm, and ptr from read_tgt_mem can be pointers to shared  
libraries in another process.  
If the calling process calls dlmodinfowith a callback registered via  
read_tgt_mem, it must supply the starting address of the target process’  
load map in the load_map_parm parameter to dlmodinfo. This can be  
retrieved from the DT_HP_LOAD_MAPentry in the .dynamic section in the  
target executable file.  
Exa m p le  
The following code sequence shows how to use dlmodinfoto retrieve  
information about a load module. In this example the dlmodinfois  
provided with the address of a function foo. The address of foois  
matched with the address range (the address range of all loaded  
segments) of all load modules. The dlmodinfofills in the  
load_module_desc with information form the matching load module.  
void foo()  
{
printf(“foo\n”);  
}
int retrieve_info()  
{
unsigned  
longhandle;  
struct  
load_module_desc desc;  
handle = dlmodinfo((unsigned long) &foo,  
&desc,  
sizeof(struct load_module_desc),  
NULL,  
0,  
0);  
if (handle != 0) {  
printf(“text base = %lx\n”, desc.text_base);  
}
}
Chapter 6  
251  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
Th e d lgetn a m e Rou tin e  
Retrieves the name of a load module given a load module descriptor.  
Syn ta x  
char *dlgetname(struct load_module_desc *desc,  
size_t desc_size,  
void *(*read_tgt_mem)(void* buffer,  
unsigned long long ptr,  
size_t bufsiz,  
int ident),  
int ident_parm,  
unsigned long long load_map_parm);  
Pa r a m eter s  
Pa r a m eter  
Descr ip tion  
desc  
A buffer of memory allocated by the user program. The dynamic  
loader fills this in with module information.  
desc_size  
Size in bytes of the desc buffer.  
read_tgm_mem  
A pointer to a function used by dlmodinfoto retrieve needed  
information.  
If the value is NULL, the dynamic loader uses its own internal data  
structures to find the correct load module and ignore the  
ident_parm and load_map_parm parameters.  
buffer  
ptr  
A buffer supplied by dlmodinfoto read into.  
The virtual memory address to read from.  
The size of buffer in bytes.  
bufsiz  
ident  
The value of the ident_parm parameter to dlmodinfo.  
ident_parm  
Only used to pass the fourth parameter to read_tgt_mem.  
load_map_parm  
Only used when calling through read_tgt_mem. Contains the  
starting address of the load map.  
252  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
Retu r n Va lu es  
dlgetnamereturns the pathname of a load module represented by desc.  
If desc does not describe a loaded module, dlgetnamereturns NULL.  
Descr ip tion  
dlgetnameis one of a family of routines that give the user direct access  
to the dynamic linking facilities.  
The read_tgt_mem, ident_parm, and load_map_parm parameters are  
identical to those for dlmodinfo.  
The caller of dlgetnamemust copy the return value to insure that it is  
not corrupted.  
Exa m p le  
The following code sequence shows how to use dlgetnameto retrieve the  
pathname of a load module. This example uses dlgetto get a  
load_module_desc of the required load module and passes that  
load_module_desc to dlgetnameto retrieve the pathname.  
void*handle;  
struct  
char*  
load_module_desc desc;  
dll_name;  
/* Get load module of the index’th shared library */  
handle = dlget(1, &desc, sizeof(struct load_module_desc));  
/* Retrieve pathname of the shared library */  
dll_name = dlgetname(&desc,  
sizeof(struct load_module_desc),  
NULL,  
0,  
NULL);  
printf(“pathname of 1st shared library : %s\n”, dll_name);  
Th e d lclose Rou tin e  
Closes a shared library.  
Syn ta x  
int dlclose(void *handle);  
Chapter 6  
253  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
Pa r a m eter s  
Pa r m  
Defin ition  
Value returned by a previous invocation of dlopen.  
handle  
Retu r n Va lu es  
If the referenced shared library was successfully closed, dlclose  
returns 0. If the shared library could not be closed, or if handle does not  
refer to an open shared library, dlclosereturns a non-0 value. More  
detailed diagnostic information is available through dlerror.  
Descr ip tion  
dlclosedisassociates a shared library previously opened by dlopen  
from the current process. Once an shared library has been closed using  
dlclose, dlsymno longer has access to its symbols. All shared  
libraries loaded automatically as a result of invoking dlopenon the  
referenced shared library [see dlopen(3C)] are also closed.  
A successful invocation of dlclosedoes not guarantee that the shared  
libraries associated with handle have actually been removed from the  
address space of the process. shared libraries loaded by one invocation of  
dlopenmay also be loaded by another invocation of dlopen. The same  
shared library may also be opened multiple times. An shared library is  
not removed from the address space until all references to that shared  
library through an explicit dlopeninvocation have been closed and all  
other shared libraries implicitly referencing that shared library have  
also been closed. Once an shared library has been closed by dlclose,  
referencing symbols contained in that shared library can cause  
undefined behavior.  
Exa m p le  
The following example shows how to use dlcloseto unload a shared  
library:  
void*  
int  
handle;  
ret_value;  
handle = dlopen(“./lib1.sl”, RTLD_GLOBAL | RTLD_LAZY);  
254  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
The dlopen Shared Library Management Routines  
if (handle == NULL) {  
printf(“%s\n”, dlerror());  
}
ret_value = dlclose(handle);  
if (ret_value != 0) {  
printf(“%s\n”, dlerror());  
}
Chapter 6  
255  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Dynamic Loader Compatibility Warnings  
Dyn a m ic Loa d er Com p a tibility  
Wa r n in gs  
Starting with the HP-UX 10.20 release, the dynamic loader generates  
compatibility warnings. These warnings include linker toolset features  
that may change over time. To display run-time compatibility warnings,  
set the _HP_DLDOPTSenvironment variable as follows:  
export _HP_DLDOPTS=-warnings Turn on compatibility warnings  
The following sections provide information about the dynamic loader  
compatibility warnings.  
Un su p p or ted Sh a r ed Libr a r y Ma n a gem en t  
Rou tin es  
The following shared library management shl_load(3X) routines may  
become unsupported in a future HP-UX release:  
shl_definesym()  
shl_get()  
shl_get_r()  
shl_gethandle()  
shl_gethandle_r()  
shl_getsymbols()  
When these routines become unsupported, the SVR4 dlopen (3C) family  
of routines will be the only dynamic loading routines supported.  
Un su p p or ted Sh a r ed Libr a r y Ma n a gem en t  
F la gs  
The following shared library management shl_load(3X) flags may  
become unsupported in a future HP-UX-release:  
BIND_FIRST  
BIND_NOSTART  
BIND_RESTRICTED  
256  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Dynamic Loader Compatibility Warnings  
BIND_TOGETHER  
BIND_NONFATAL  
BIND_VERBOSE  
DYNAMIC_PATH  
The following shl_findsym()flags may become unsupported in a  
future release:  
TYPE_PROCEDURE  
TYPE_DATA  
TYPE_STORAGE  
NOTE  
The for HP-UX Release 11.00 64-bit mode linker does not support the  
TYPE_STORAGE flag  
Chapter 6  
257  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Shared Library Management Routines  
Dynamic Loader Compatibility Warnings  
258  
Chapter6  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
7
Position -In d ep en d en t Cod e  
This chapter discusses  
What Is Relocatable Object Code?”  
What is Absolute Object Code?”  
What Is Position-Independent Code?”  
Generating Position-Independent Code”  
This chapter is useful mainly to programmers who want to write  
position-independent assembly language code, or who want to convert  
existing assembly language programs to be position-independent. It is  
also of interest to compiler developers. This chapter assumes you have a  
good understanding of virtual memory concepts and memory  
management.  
NOTE  
Throughout this chapter, examples of PIC are shown in assembly code.  
For the corresponding information for 64-bit mode, see 64-bit Runtime  
Architecture for PA-RISC 2.0 available from the HP-UX Software  
Transition Toolkit (STK) at http://www.software.hp.com/STK/.  
Chapter 7  
259  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
What Is Relocatable Object Code?  
Wh a t Is Reloca ta ble Object Cod e?  
Reloca ta ble object cod e is machine code that is generated by  
compilers and assemblers and stored in relocatable object files, or .o  
files. A relocatable object file contains symbolic references to locations  
defined within the compilation unit as well as symbolic references to  
locations defined outside the compilation unit. The object file also  
contains relocation information. The linker uses this information to  
replace the symbolic references with actual addresses.  
For example, if you write a program that references the external variable  
errno, the object code created by the compiler contains only a symbolic  
reference to errnosince errnois not defined in your program. Only  
when the linker links this object code does the reference to errnochange  
(relocate) to an absolute address in virtual memory.  
If your program defines a global variable, the compiler assigns a  
relocatable address to that variable. The compiler also marks all  
references to that variable as relocatable. The linker replaces the  
references to the variable with the absolute address of the variable.  
260  
Chapter7  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
What is Absolute Object Code?  
Wh a t is Absolu te Object Cod e?  
Absolu te object cod e is machine code that contains references to  
actual addresses within the program's address space. When the linker  
combines relocatable object files to build a program file, or a.outfile, it  
writes absolute object code into the file. Thus, when the program is  
executed, its routines and data must reside at the addresses determined  
by the linker.  
Note that absolute object code does not contain p h ysica l a d d r esses.  
Physical addresses refer to exact locations in physical memory. Instead,  
absolute object code contains virtual addresses within a process's  
address space. These virtual addresses are mapped to physical addresses  
by the HP-UX virtual memory management system.  
Because program files contain absolute virtual addresses, the HP-UX  
program loader, exec, must always load the code and data into the same  
location within a process's address space. Because this code always  
resides at the same location within the address space, and because it  
contains virtual addresses, it is not suitable for shared libraries,  
although it can be shared by several processes running the same  
program.  
Chapter 7  
261  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
What Is Position-Independent Code?  
Wh a t Is Position -In d ep en d en t Cod e?  
Position -in d ep en d en t cod e (P IC) is a form of absolute object code  
that does not contain any absolute addresses and therefore does not  
depend on where it is loaded in the process's virtual address space. This  
is an important property for building shared libraries.  
In order for the object code in a shared library to be fully shareable, it  
must not depend on its position in the virtual address space of any  
particular process. The object code in a shared library may be attached at  
different points in different processes, so it must work independent of  
being located at any particular position, hence the term  
position-independent code.  
Position independence is achieved by two mechanisms: First,  
P C-r ela tive addressing is used wherever possible for branches within  
modules. Second, in d ir ect a d d r essin g through a per-process lin k a ge  
ta ble is used for all accesses to global variables, or for inter-module  
procedure calls and other branches and literal accesses where  
PC-relative addressing cannot be used. Global variables must be  
accessed indirectly since they may be allocated in the main program's  
address space, and even the relative position of the global variables may  
vary from one process to another.  
The HP-UX dynamic loader (see dld.sl(5)) and the virtual memory  
management system work together to find free space at which to attach  
position-independent code within a process's address space. The dynamic  
loader also resolves any virtual addresses that might exist in the library.  
Calls to PIC routines are accomplished through a p r oced u r e lin k a ge  
ta ble (P LT), which is built by the linker. Similarly, references to data are  
accomplished through a d a ta lin k a ge ta ble (DLT). Both tables reside  
in a process's data segment. The dynamic loader fills in these tables with  
the absolute virtual addresses of the routines and data in a shared  
library at run time (known as bin d in g). Because of this, PIC can be  
loaded and executed anywhere that a process has free space.  
On compilers that support PIC generation, the +zand +Zoptions cause  
the compiler to create PIC relocatable object code.  
262  
Chapter7  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
Generating Position-Independent Code  
Gen er a tin g Position -In d ep en d en t Cod e  
To be position-independent, object code must restrict all references to  
code and data to either PC-relative or indirect references, where all  
indirect references are collected in a single linkage table that can be  
initialized on a per-process basis by dld.sl.  
Register 19 (%r19) is the designated pointer to the linkage table. The  
linker generates stu bs that ensure %r19always points to the correct  
value for the target routine and that handle the inter-space calls needed  
to branch between shared libraries.  
The linker generates an im p or t stu b for each external reference to a  
routine. The call to the routine is redirected to branch to the import stub,  
which obtains the target routine address and the new linkage table  
pointer value from the current linkage table; it then branches to an  
export stub for the target routine. In 32-bit mode, the linker generates an  
exp or t stu b for each externally visible routine in a shared library or  
program file. The export stub is responsible for trapping the return from  
the target routine in order to handle the inter-space call required  
between shared libraries and program files.  
NOTE  
The 64-bit mode linker does not require or support export stubs.  
Shown below is the PIC code generated for import and export stubs. Note  
that this code is generated automatically by the linker; you don't have to  
generate the stubs yourself.  
;Import Stub (Incomplete Executable)  
X': ADDIL L'lt_ptr+ltoff,%dp  
; get procedure entry point  
LDW  
LDW  
R'lt_ptr+ltoff(%r1),%r21  
R'lt_ptr+ltoff+4(%r1),%r19 ; get new r19 value.  
LDSID (%r21),%r1  
MTSP  
BE  
STW  
%r1,%sr0  
0(%sr0,%r21)  
%rp,-24(%sp)  
; branch to target  
; save rp  
;Import Stub (Shared Library)  
X': ADDIL L'ltoff,%r19  
; get procedure entry point  
LDW  
LDW  
R'ltoff(%r1),%r21  
R'ltoff+4(%r1),%r19  
; get new r19 value  
LDSID (%r21),%r1  
MTSP  
BE  
STW  
%r1,%sr0  
0(%sr0,%r21)  
%rp,-24(%sp)  
; branch to target  
; save rp  
;Export Stub (Shared libs and Incomplete Executables)  
X': BL,N  
X,%rp ; trap the return  
Chapter 7  
263  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
Generating Position-Independent Code  
NOP  
LDW  
-24(%sp),%rp  
; restore the original rp  
LDSID (%rp),%r1  
MTSP  
BE,N  
%r1,%sr0  
0(%sr0,%rp) ; inter-space return  
For Mor e In for m a tion :  
The remainder of this section describes how compilers generate PIC for  
the following addressing situations:  
PIC Requirements for Compilers and Assembly Code”  
Long Calls”  
Long Branches and Switch Tables”  
Assigned GOTO Statements”  
Literal References”  
Global and Static Variable References”  
Procedure Labels”  
You can use these guidelines to write assembly language programs that  
generate PIC object code. For details on assembly language, refer to the  
Assembler Reference Manual and PA-RISC 2.0 Architecture.  
P IC Requ ir em en ts for Com p iler s a n d  
Assem bly Cod e  
The linkage table pointer register, %r19, must be stored at %sp32 by all  
PIC routines. This can be done once on procedure entry. %r19must also  
be restored on return from a procedure call. The value should have been  
stored in %sp32 (and possibly in a callee-saves register). If the PIC  
routine makes several procedure calls, the routine should copy %r19into  
a callee-saves register as well, to avoid a memory reference when  
restoring %r19upon return from each procedure call. Just like %r27  
(%dp), the compilers treat %r19as a reserved register whenever PIC  
mode is in effect.  
In general, references to code are handled by the linker, and the  
compilers act differently only in the few cases where they would have  
generated long calls or long branches. References to data, however, need  
a new fixup request to identify indirect references through the linkage  
table, and the code generated will change slightly.  
264  
Chapter7  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
Generating Position-Independent Code  
NOTE  
Any code which is PIC or which makes calls to PIC must follow the  
standard procedure call mechanism.  
When linking files produced by the assembler, the linker exports only  
those assembly language routines that have been explicitly exported as  
entry(that is, symbols of type ST_ENTRY). Compiler generated  
assembly code does not explicitly export routines with the entrytype  
specified, so the assembly language programmer must ensure that this is  
done with the .EXPORTpseudo-op.  
For example: In assembly language, a symbol is exported using  
.EXPORT foo, type  
where type can be code, data, entry, and others. To ensure that foois  
exported from a shared library, the assembly statement must be:  
.EXPORT foo,entry  
Lon g Ca lls  
Normally, the compilers generate a single-instruction call sequence using  
the BLinstruction. The compilers can be forced to generate a long call  
sequence when the module is so large that the BLis not guaranteed to  
reach the beginning of the subspace. In the latter case, the linker can  
insert a stub. The existing long call sequence is three instructions, using  
an absolute target address:  
LDIL  
BLE  
COPY  
L'target,%r1  
R'target(%sr4,%r1)  
%r1,%rp  
When the PIC option is in effect, the compilers must generate the  
following instruction sequence, which is PC-relative:  
BL  
ADDIL  
.+8,%rp  
; get pc into rp  
L'target - $L0 + 4, %rp  
; add pc-rel offset to rp  
LDO  
R'target - $L1 + 8(%r1), %r1  
(%r1), %r31  
$L0: LDSID  
$L1: MTSP  
BLE  
%r31, %sr0  
0(%sr0,%r1)  
COPY  
%r31,%rp  
Lon g Br a n ch es a n d Sw itch Ta bles  
Long branches are similar to long calls, but are only two instructions  
because the return pointer is not needed:  
Chapter 7  
265  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
Generating Position-Independent Code  
LDIL  
BE  
L'target,%r1  
R'target(%sr4,%r1)  
For PIC, these two instructions must be transformed into four  
instructions, similar to the long call sequence:  
BL  
.+8,%r1  
; get pc into r1  
ADDIL  
LDO  
L'target-L,%r1  
R'target-L,%r1  
0(%r1)  
; add pc-relative offset  
; add pc-relative offset  
; and branch  
L:  
BV,N  
The only problem with this sequence occurs when the long branch is in a  
switch table, where each switch table entry is restricted to two words. A  
long branch within a switch table must allocate a linkage table entry and  
make an indirect branch:  
LDW  
BV,N  
T'target(%r19),%r1 ; load LT entry  
0(%r1) ; branch indirect  
Here, the T' operator indicates a new fixup request supported by the  
linker for linkage table entries.  
Assign ed GOTO Sta tem en ts  
ASSIGNstatements in FORTRAN must be converted to a PC-relative  
form. The existing sequence forms the absolute address in a register  
before storing it in the variable:  
LDIL  
LDO  
L'target,tmp  
R'target(tmp),tmp  
This must be transformed into the following four-instruction sequence:  
BL  
.+8,tmp  
; get rp into tmp  
DEPI  
ADDIL  
LDO  
0,31,2,tmp  
; zero out low-order 2 bits  
L:  
L'target-L,tmp ; get pc-rel offset  
R'target-L(%r1),tmp  
Liter a l Refer en ces  
References to literals in the text space are handled exactly like ASSIGN  
statements (shown above). The LDOinstruction can be replaced with LDW  
as appropriate.  
An opportunity for optimization in both cases is to share a single label (L)  
throughout a procedure, and let the result of BLbecome a common  
sub-expression. Thus only the first literal reference within a procedure is  
expanded to three instructions; the rest remain two instructions.  
266  
Chapter7  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
Generating Position-Independent Code  
Globa l a n d Sta tic Va r ia ble Refer en ces  
References to global or static variables currently require two instructions  
either to form the address of a variable, or to load or store the contents of  
the variable:  
; to form the address of a variable  
ADDIL  
LDO  
L'var-$global$+x,%dp  
R'var-$global$+x(%r1),tmp  
; to load the contents of a variable  
ADDIL  
LDW  
L'var-$global$+x,%dp  
R'var-$global$+x(%r1),tmp  
These sequences must be converted to equivalent sequences using the  
linkage table pointer in %r19:  
; to form the address of a variable  
LDW  
LDO  
T'var(%r19),tmp1  
x(tmp1),tmp2  
; omit if x == 0  
; to load the contents of a variable  
LDW  
LDW  
T'var(%r19),tmp1  
x(tmp1),tmp2  
Note that the T' fixup on the LDWinstruction allows for a 14-bit signed  
offset, which restricts the DLT to be 16Kb. Because %r19points to the  
middle of the DLT, we can take advantage of both positive and negative  
offsets. The T' fixup specifier should generate a DLT_RELfixup proceeded  
by an FSELoverride fixup. If the FSELoverride fixup is not generated,  
the linker assumes that the fixup mode is LD/RDfor DLT_RELfixups. In  
order to support larger DLT table sizes, the following long form of the  
above data reference must be generated to reference tables that are  
larger. If the DLT table grows beyond the 16Kb limit, the linker emits an  
error indicating that the user must recompile using the +Zoption which  
produces the following long-load sequences for data reference:  
; form the address of a variable  
ADDIL  
LDW  
LT'var,%r19  
RT'var(%r1),tmp1  
x(tmp1),tmp2  
LDO  
; omit if x == 0  
; load the contents of a variable  
ADDIL  
LDW  
LDW  
LT'var,%r19  
RT'var(%r1),tmp1  
x(tmp1),tmp2  
P r oced u r e La bels  
The compilers already mark procedure label constructs so that the linker  
can process them properly. No changes are needed to the compilers.  
Chapter 7  
267  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Position-Independent Code  
Generating Position-Independent Code  
When building shared libraries and incomplete executables, the linker  
modifies the p la bel calculation (produced by the compilers in both  
shared libraries and incomplete executables) to load the contents of a  
DLT entry, which is built for each symbol associated with a  
CODE_PLABELfixup.  
In shared libraries and incomplete executables, a plabel value is the  
address of a PLT entry for the target routine, rather than a procedure  
address; therefore $$dyncallmust be used when calling a routine with  
a procedure label. The linker sets the second-to-last bit in the procedure  
label to flag this as a special PLT procedure label. The $$dyncall  
routine checks this bit to determine which type of procedure label has  
been passed, and calls the target procedure accordingly.  
In order to generate a procedure label that can be used for shared  
libraries and incomplete executables, assembly code must specify that a  
procedure address is being taken (and that a plabel is wanted) by using  
the P' assembler fixup mode. For example, to generate an assembly  
plabel, the following sequence must be used:  
LDIL LP'function,%r1  
LDO RP'function(%r1), %r22  
; Now to call the routine  
BL $$dyncall, %r31 ; r22 is the input register for $$dyncall  
COPY %r31, %r2  
This code sequence generates the necessary PLABELfixups that the  
linker needs in order to generate the proper procedure label. The  
dyncallmillicode routine in /usr/lib/milli.amust be used to call a  
procedure using this type of procedure label; that is, a BLor BVwill not  
work).  
268  
Chapter7  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
8
Wa ys to Im p r ove Per for m a n ce  
The linker provides several ways you can improve your application  
performance.  
Linker Optimizations” describes how the linker -Ooption removes  
unnecessary ADDILinstructions and dead” or unused procedures.  
Options to Improve TLB Hit Ratesdescribes performance  
improvements in Translation Lookaside Buffer (TLB) hit rates.  
Profile-Based Optimization” describes how the linker can position  
your code in the object file or shared library to improve performance.  
Improving Shared Library Start-Up Time with fastbind” describes  
how to improve shared library performance by saving startup  
information and bypassing the lookup process when running an  
application.  
Chapter 8  
269  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Linker Optimizations  
Lin k er Op tim iza tion s  
The linker supports the -Ooption which performs the following  
optimizations at link time:  
optimizes references to data by removing unnecessary ADDIL  
instructions from the object code.  
removes procedures that can never be reached.  
These optimizations can be separately enabled or disabled with the  
+O[no]fastaccessand +O[no]procelimoptions respectively. The -O  
linker option simply combines enabling of these into one option. For  
example, the following ldcommand enables linker optimizations and  
results in a smaller, faster executable:  
$ ld -O -o prog /usr/ccs/lib/crt0.o prog.o -lm -lc  
To enable one or the other optimization only, use the appropriate +O  
option:  
$ ld +Ofastaccess -o prog /usr/ccs/lib/crt0.o prog.o -lm -lc  
$ ld +Oprocelim -o prog /usr/ccs/lib/crt0.o prog.o -lm -lc  
In vok in g Lin k er Op tim iza tion s fr om th e  
Com p ile Lin e  
The compilers automatically call the linker with the +Ofastaccessand  
+Oprocelimoptions if compiler optimization level 4 is selected. For  
example, the following cccommand invokes full compiler optimization  
as well as linker optimization:  
$ cc -o prog +O4 prog.c  
O4 invokes +Ofastaccess and +Oprocelim  
If invoked with +O4, the compilers generate object code in such a way  
that code optimization is done at link time. Thus, the linker does a better  
job of optimizing code that was compiled with +O4.  
When the compile and link phases are invoked by separate commands,  
specify +O4on both command lines. For example:  
$ cc -c +O4 prog.c  
$ cc -o prog +O4 prog.o  
invokes compiler optimizations  
invokes linker optimizations  
270  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Linker Optimizations  
NOTE  
With the HP-UX 10.0 release, you can also invoke linker optimizations at  
levels 2 and 3 by using the +Ofastaccessor +Oprocelimoption.  
See Also:  
For a brief description of compiler optimization options see Selecting an  
Optimization Level with PBO. For a complete description, see your  
compiler manuals or online help.  
In com p a tibilities w ith oth er Op tion s  
The -O, +Ofastaccess, and +Oprocelimoptions are incompatible with  
these linker options:  
-b  
These options have no effect on position-independent  
code, so they are not useful when building shared  
libraries with ld -b.  
-A  
-r  
-D  
Dynamic linking is incompatible with link-time  
optimization.  
Relocatable linking is incompatible with link-time  
optimization.  
Setting the offset of the data space is incompatible with  
link-time optimization.  
The linker issues a warning when such conflicts occur. If you require any  
of these features, do not use the linker optimization options.  
Un u sed P r oced u r e Elim in a tion w ith  
+Op r ocelim  
Unused or dead” procedure elimination is the process of removing  
unreferenced procedures from the $TEXT$ space of an executable or  
shared library to reduce the size of the program or library.  
Dead procedure elimination is performed after all symbols have been  
resolved prior to any relocation. It works on a per subspace basis. That is,  
only entire subspaces are removed and only if all procedures in the  
subspace are unreferenced. Typically, if a relocatable link (ld -r) has  
not been performed and the code is not written in assembly, every  
procedure is in its own subspace. Relocatable links may merge  
Chapter 8  
271  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Linker Optimizations  
subspaces. Merged subspaces can prevent the removal of dead  
procedures. Therefore, it is optimal to have each procedure in its own  
subspace.  
Com p lete Execu ta bles  
For com p lete execu ta bles, dead procedure elimination removes any  
text subspaces that are not referenced from another subspace. Self  
references, such as recursive procedures or subspaces with multiple  
procedures that call each other, are not considered outside references  
and are therefore candidates for removal.  
If the address of a procedure is taken, the subspace within which it  
resides is not removed. If a subspace is referenced in any way by a fixup  
representing a reference other than a PC-relative call or an absolute call  
it is not removed.  
In com p lete Execu ta bles  
For in com p lete execu ta bles, dead procedure elimination works the  
same as for complete executables except that no exported symbols or  
their dependencies are removed. If an incomplete executable contains a  
symbol that is to be referenced by a shared library and is not exported, it  
is removed if the other conditions discussed above hold.  
Sh a r ed Libr a r ies  
In shared libraries only symbols that are not referenced and not exported  
are removed. In shared libraries all symbols that are not of local scope  
are exported. Therefore only locally scoped symbols not referenced are  
removed.  
Reloca ta ble Objects  
When performing a relocatable link with the -roption, dead procedure  
elimination is disabled since the only possible gain would be the removal  
of unreferenced local procedures. Objects resulting from a relocatable  
link are subject to dead procedure elimination upon a final link.  
Affects on Sym bolic Debu ggin g  
Any procedure that has symbolic debug information associated with it is  
not removed. Procedures that do not have symbolic debug information  
associated with them but are included in a debug link are removed if  
they are not referenced.  
272  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Options to Improve TLB Hit Rates  
Op tion s to Im p r ove TLB Hit Ra tes  
To improve Translation Lookaside Buffer (TLB) hit rates in an  
application running on a PA 8000-based system, use the following linker  
or chatrvirtual memory page setting options:  
+pdsize requests a specified data page size of 4K bytes, 16K, 64K,  
256K, 1M, 4M, 16M, 64M, 256M, or L. Use Lto specify the largest  
page size available. The actual page size may vary if the requested  
size can not be fulfilled.  
+pisize requests a specified instruction page size. (See +pdsize for  
size values.)  
The default data and instruction page size is 4K bytes on PA-RISC  
systems.  
The PA-RISC 2.0 architecture supports multiple page sizes, from 4K  
bytes to 64M bytes, in multiples of four. This enables large contiguous  
regions to be mapped into a single TLB entry. For example, if a  
contiguous 4MB of memory is actively used, 1000 TLB entries are  
created if the page size is 4K bytes, but only 64 TLB entries are created if  
the page size is 64K bytes.  
Applications and benchmarks have larger and larger working-set sizes.  
Therefore, the linker and chatrTLB page setting options can help boost  
performance by improving TLB hit rates.  
Some scientific applications benefit from large data pages. Alternatively,  
some commercial applications benefit from large instruction page sizes.  
Examples:  
To set the virtual memory page size by using the linker:  
ld +pd 64K +pi 16K /opt/langtools/lib/crt0.o myprog.o -lc  
To set the page size from HP C and HP Fortran:  
cc -Wl,+pd,64K,+pi,16K myprog.c  
f90 -Wl,+pd,64K,+pi,16K myprog.f  
To set the page size by using chatr:  
chatr +pd 64K +pi 16K a.out  
Chapter 8  
273  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
P r ofile-Ba sed Op tim iza tion  
In p r ofile-ba sed op tim iza tion (PBO), the compiler and linker work  
together to optimize an application based on profile data obtained from  
running the application on a typical input data set. For instance, if  
certain procedures call each other frequently, the linker can place them  
close together in the a.outfile, resulting in fewer instruction cache  
misses, TLB misses, and memory page faults when the program runs.  
Similar optimizations can be done at the ba sic block levels of a  
procedure. Profile data is also used by the compiler for other general  
tasks, such as code scheduling and register allocation.  
Gen er a l In for m a tion a bou t P BO  
When to Use PBO”  
Restrictions and Limitations of PBO”  
Compatibility with 9.0 PBO”  
Usin g P BO  
How to Use PBO”  
Instrumenting (+I/-I)”  
Profiling”  
Optimizing Based on Profile Data (+P/-P)”  
Selecting an Optimization Level with PBO”  
Using PBO to Optimize Shared Libraries”  
Using PBO with ld -r”  
NOTE  
The compiler interface to PBO is currently supported only by the C, C++,  
and FORTRAN compilers.  
274  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
Wh en to Use P BO  
PBO should be the last level of optimization you use when building an  
application. As with other optimizations, it should be performed after an  
application has been completely debugged.  
Most applications will benefit from PBO. The two types of applications  
that will benefit the most from PBO are:  
Applications that exhibit poor instruction memory locality. These are  
usually large applications in which the most common paths of  
execution are spread across multiple compilation units. The loops in  
these applications typically contain large numbers of statements,  
procedure calls, or both.  
Applications that are branch-intensive. The operations performed in  
such applications are highly dependent on the input data. User  
interface managers, database managers, editors, and compilers are  
examples of such applications.  
Of course, the best way to determine whether PBO will improve an  
application's performance is to try it.  
NOTE  
Under some conditions, PBO is incompatible with programs that  
explicitly load shared libraries. Specifically, PBO will not function  
properly if the shl_loadroutine has either the BIND_FIRSTor the  
BIND_NOSTARTflags set. For more information about explicit loading of  
shared libraries, see The shl_load and cxxshl_load Routines” on page  
215.  
How to Use P BO  
Profile-based optimization involves these steps:  
1. Instrument the application — prepare the application so that it will  
generate profile data.  
2. Profile the application — create profile data that can be used to  
optimize the application.  
3. Optimize the application — generate optimized code based on the  
profile data.  
Chapter 8  
275  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
A Sim p le Exa m p le  
Suppose you want to apply PBO to an application called sample. The  
application is built from a C source file sample.c. Discussed below are  
the steps involved in optimizing the application.  
Step 1 Instrumentation  
First, compile the application for instrumentation and level 2  
optimization:  
$ cc -v -c +I -O sample.c  
/opt/langtools/lbin/cpp sample.c /var/tmp/ctm123  
/opt/ansic/lbin/ccom /var/tmp/ctm123 sample.o -O2 -I  
$ cc -v -o sample.inst +I -O sample.o  
/usr/ccs/bin/ld /opt/langtools/lib/icrt0.o -u main \  
-o sample.inst sample.o -I -lc  
At this point, you have an instrumented program called sample.inst.  
Step 2 Profile  
Assume you have two representative input files to use for profiling,  
input.file1and input.file2. Now execute the following three  
commands:  
$ sample.inst < input.file1  
$ sample.inst < input.file2  
$ mv flow.data sample.data  
The first invocation of sample.instcreates the flow.datafile and  
places an entry for that executable file in the data file. The second  
invocation increments the counters for sample.instin the flow.data  
file. The third command moves the flow.datafile to a file named  
sample.data.  
Step 3 Optimize  
To perform profile based optimizations on this application, relink the  
program as follows:  
$ cc -v -o sample.opt +P +pgm sample.inst \  
+df sample.data sample.o  
/usr/ccs/bin/ld /usr/ccs/lib/crt0.o -u main -o sample.opt \  
+pgm sample.inst +df sample.data sample.o -P -lc  
Note that it was not necessary to recompile the source file. The +pgm  
option was used because the executable name used during  
instrumentation, sample.inst, does not match the current output file  
name, sample.opt. The +dfoption is necessary because the profile  
database file for the program has been moved from flow.datato  
sample.data.  
276  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
In str u m en tin g (+I/-I)  
Although you can use the linker alone to perform PBO, the best  
optimizations result if you use the compiler as well; this section describes  
this approach.  
To instrument an application (with C, C++, and FORTRAN), compile the  
source with the +Icompiler command line option. This causes the  
compiler to generate a .ofile containing intermediate code, rather than  
the usual object code. (In ter m ed ia te cod e is a representation of your  
code that is lower-level than the source code, but higher level than the  
object code.) A file containing such intermediate code is referred to as an  
I-SOM file.  
After creating an I-SOM file for each source file, the compiler invokes the  
linker as follows:  
1. In 32-bit mode, instead of using the startup file  
/usr/ccs/lib/crt0.o, the compiler specifies a special startup file  
named /opt/langtools/lib/icrt0.o. When building a shared  
library, the compiler uses /usr/ccs/lib/scrt0.o. In 64-bit mode,  
the linker automatically adds  
/usr.css/lib/pa20_64/fdp_init.oor  
/usr.css/lib/pa20_64/fdp_init_sl.oto the link when detects  
that -I crt0.ois not changed.  
2. The compiler passes the -Ioption to the linker, causing it to place  
instrumentation code in the resulting executable.  
You can see how the compiler invokes the linker by specifying the -v  
option. For example, to instrument the file sample.c, to name the  
executable sample.inst, to perform level 2 optimizations (the compiler  
option -Ois equivalent to +O2), and to see verbose output (-v):  
$ cc -v -o sample.inst +I -O sample.c  
/opt/langtools/lbin/cpp sample.c /var/tmp/ctm123  
/opt/ansic/lbin/ccom /var/tmp/ctm123 sample.o -O2 -I  
/usr/ccs/bin/ld /opt/langtools/lib/icrt0.o -u main -o \  
sample.inst sample.o -I -lc  
Notice in the linker command line (starting with /usr/ccs/bin/ld),  
the application is linked with /opt/langtools/lib/icrt0.oand the  
-Ioption is given.  
To save the profile data to a file other than flow.datain the current  
working directory, use the FLOW_DATAenvironment variable as  
described in Specifying a Different flow.data with FLOW_DATA”.  
Chapter 8  
277  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
Th e Sta r tu p File icr t0.o  
The icrt0.ostartup file uses the atexit system call to register the  
function that writes out profile data. (For 64-bit mode, the initialization  
code is in /usr/ccs/lib/pa20_64/fdp_init.0.) That function is  
called when the application exits.  
atexitallows a fixed number of functions to be registered from a user  
application. Instrumented applications (those linked with -I) will have  
one less atexitcall available. One or more instrumented shared  
libraries will use a single additional atexitcall. Therefore, an  
instrumented application that contains any number instrumented  
shared libraries will use two of the available atexitcalls.  
For details on atexit, see atexit(2).  
Th e -ILin k er Op tion  
When invoked with the -Ioption, the linker instruments all the  
specified object files. Note that the linker instruments regular object files  
as well as I-SOM files; however, with regular object files, only procedure  
call instrumentation is added. With I-SOM files, additional  
instrumentation is done within procedures.  
For instance, suppose you have a regular object file named foo.ocreated  
by compiling without the +Ioption, and you compile a source file bar.c  
with the +Ioption and specify foo.oon the compile line:  
$ cc -c foo.c  
$ cc -v -o foobar -O +I bar.c foo.o  
/opt/langtools/lbin/cpp bar.c /var/tmp/ctm456  
/opt/ansic/lbin/ccom /var/tmp/ctm456 bar.o -O2 -I  
/usr/ccs/bin/ld /opt/langtools/lib/icrt0.o -u main -o foobar \  
bar.o foo.o -I -lc  
In this case, the linker instruments both bar.oand foo.o. However,  
since foo.ois not an I-SOM file, only its procedure calls are  
instrumented; basic blocks within procedures are not instrumented. To  
instrument foo.cto the same extent, you must compile it with the +I  
option — for example:  
$ cc -v -c +I -O foo.c  
/opt/langtools/lbin/cpp foo.c /var/tmp/ctm432  
/opt/ansic/lbin/ccom /var/tmp/ctm432 foo.o -O2 -I  
$ cc -v -o foobar -O +I bar.c foo.o  
/opt/langtools/lbin/cpp bar.c /var/tmp/ctm456  
/opt/ansic/lbin/ccom /var/tmp/ctm456 bar.o -O2 -I  
/usr/ccs/bin/ld /opt/langtools/lib/icrt0.o -u main -o foobar \  
bar.o foo.o -I -lc  
278  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
A simpler approach would be to compile foo.cand bar.cwith a single  
cccommand:  
$ cc -v +I -O -o foobar bar.c foo.c  
/opt/langtools/lbin/cpp bar.c /var/tmp/ctm352  
/opt/ansic/lbin/ccom /var/tmp/ctm352 bar.o -O2 -I  
/opt/langtools/lbin/cpp foo.c /var/tmp/ctm456  
/opt/ansic/lbin/ccom /var/tmp/ctm456 foo.o -O2 -I  
/usr/ccs/bin/ld /opt/langtools/lib/icrt0.o -u main -o foobar \  
bar.o foo.o -I -lc  
Cod e Gen er a tion fr om I-SOMs  
As discussed in Looking inside” a Compiler” on page 38, a compiler  
driver invokes several phases. The last phase before linking is cod e  
gen er a tion . When using PBO, the compilation process stops at an  
intermediate code level. The PA-RISC code generation and optimization  
phase is invoked by the linker. The code generator is  
/opt/langtools/lbin/ucomp.  
NOTE  
Since the code generation phase is delayed until link time with PBO,  
linking can take much longer than usual when using PBO. Compile  
times are faster than usual, since code generation is not performed.  
P r ofilin g  
After instrumenting a program, you can run it one or more times to  
generate profile data, which is ultimately used to perform the  
optimizations in the final step of PBO.  
This section provides information on the following profiling topics:  
Choosing Input Data”  
The flow.data File”  
Storing Profile Information for Multiple Programs”  
Sharing the flow.data File Among Multiple Processes”  
Forking an Instrumented Application”  
Ch oosin g In p u t Da ta  
For best results from PBO, use representative input data when running  
an instrumented program. Input data that represents rare cases or error  
conditions is usually not effective for profiling. Run the instrumented  
program with input data that closely resembles the data in a typical  
Chapter 8  
279  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
user's environment. Then, the optimizer will focus its efforts on the parts  
of the program that are critical to performance in the user's  
environment. You should not have to do a large number of profiling runs  
before the optimization phase. Usually it is adequate to select a small  
number of representative input data sets.  
Th e flow.d a ta File  
When an instrumented program terminates with the exit(2) system call,  
special code in the 32-bit icrt0.ostartup file or the 64-bit  
/usr/ccs/lib/pa20_64/fdp_init.ofile writes profile data to a file  
called flow.datain the current working directory. This file contains  
binary data, which cannot be viewed or updated with a text editor. The  
flow.datafile is not updated when a process terminates without calling  
exit. That happens, for example, when a process aborts due to an  
unexpected signal, or when program calls exec(2) to replace itself with  
another program.  
There are also certain non-terminating processes (such as servers,  
daemons, and operating systems) which never call exit. For these  
processes, you must programmatically write the profile data to the  
flow.datafile. In order to do so, a process must call a routine called  
_write_counters(). This routine is defined in the icrt0.ofile. A  
stub routine with the same name is present in the crt0.ofile so that the  
source does not have to change when instrumentation is not being done.  
If flow.datadoes not exist, the program creates it; if flow.data  
exists, the program updates the profile data.  
As an example, suppose you have an instrumented program named  
prog.inst, and two representative input data files named  
input_file1and input_file2. Then the following lines would create  
a flow.datafile:  
$ prog.inst < input_file1  
$ ls flow.data  
flow.data  
$ prog.inst < input_file2  
The flow.datafile includes profile data from both input files.  
To save the profile data to a file other than flow.datain the current  
working directory, use the FLOW_DATAenvironment variable as  
described in Specifying a Different flow.data with FLOW_DATA”.  
280  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
Stor in g P r ofile In for m a tion for Mu ltip le P r ogr a m s  
A single flow.datafile can store information for multiple programs.  
This allows an instrumented program to spawn other instrumented  
programs, all of which share the same flow.datafile.  
To allow multiple programs to save their data in the same flow.data  
file, a program's profile data is uniquely identified by the executable's  
basename (see basename(1)), the executable's file size, and the time the  
executable was last modified.  
Instead of using the executable's basename, you can specify a basename  
by setting the environment variable PBO_PGM_PATH. This is useful when  
a number of programs are actually linked to the same instrumented  
executables.  
For example, consider profiling the ls, lsfand lsxcommands. (lsxis  
lswith the -xoption and lsfis lswith the -Foption.) Since the three  
commands could be linked to the same instrumented executables, the  
developer might want to collect profile data under a single basename by  
setting PBO_PGM_PATH=ls. If PBO_PGM_PATH=lswere not set, profile  
data would be saved under the ls, the lsf, and the lsxbasenames.  
When an instrumented program begins execution, it checks whether the  
basename, size, and time-stamp match those in the existing flow.data  
file. If the basename matches but the size or time-stamp does not match,  
that probably means that the program has been relinked since it last  
created profile data. In this case, the following error message will be  
issued:  
program: Can't update counters. Profile data exists  
but does not correspond to this executable. Exit.  
You can fix this problem any one of these ways:  
Remove or rename the existing flow.datafile.  
Run the instrumented program in a different working directory.  
Set the FLOW_DATAenvironment variable so that profile data is  
written to a file other than flow.data.  
Rename the instrumented program.  
Chapter 8  
281  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
Sh a r in g th e flow.d a ta File Am on g Mu ltip le P r ocesses  
A flow.datafile can potentially be accessed by several processes at the  
same time. For example, this could happen when you run more than one  
instrumented program at the same time in the same directory, or when  
profiling one program while linking another with -P.  
Such asynchronous access to the file could potentially corrupt the data.  
To prevent simultaneous access to the flow.datafile in a particular  
directory, a lock file called flow.lockis used. Instrumented programs  
that need to update the flow.datafile and linker processes that need to  
read it must first obtain access to the lock file. Only one process can hold  
the lock at any time. As long as the flow.datafile is being actively read  
and written, a process will wait for the lock to become available.  
A program that terminates abnormally may leave the flow.datafile  
inactive but locked. A process that tries to access an inactive but locked  
flow.datafile gives up after a short period of time. In such cases, you  
may need to remove the flow.lockfile.  
If an instrumented program fails to obtain the database lock, it writes  
the profile data to a temporary file and displays a warning message  
containing the name of the file. You could then use the +dfoption along  
with the +Poption while optimizing, to specify the name of the  
temporary file instead of the flow.datafile.  
If the linker fails to obtain the lock, it displays an error message and  
terminates. In such cases, wait until all active processes that are reading  
or writing a profile database file in that directory have completed. If no  
such processes exist, remove the flow.lockfile.  
For k in g a n In str u m en ted Ap p lica tion  
When instrumenting an application that creates a copy of itself with the  
forksystem call, you must ensure that the child process calls a special  
function named _clear_counters(), which clears all internal profile  
data. If you don't do this, the child process inherits the parent's profile  
data, updating the data as it executes, resulting in inaccurate  
(exaggerated) profile data when the child terminates. The following code  
segment shows a valid way to call _clear_counters:  
if ((pid = fork()) == 0) /* this is the child process */  
{
_clear_counters();  
. . .  
/* reset profile data for child */  
/* other code for the child */  
}
282  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
The function _clear_countersis defined in icrt0.o. It is also defined  
as a stub (an empty function that does nothing) in crt0.o. This allows  
you to use the same source code without modification in the  
instrumented and un-instrumented versions of the program.  
Op tim izin g Ba sed on P r ofile Da ta (+P /-P )  
The final step in PBO is optimizing a program using profile data created  
in the profiling phase. To do this, rebuild the program with the +P  
compiler option. As with the +Ioption, the +Poption causes the compiler  
to generate an I-SOM .ofile, rather than the usual object code, for each  
source file.  
Note that it is not really necessary to recompile the source files; you  
could, instead, specify the I-SOM .ofiles that were created during the  
instrumentation phase. For instance, suppose you have already created  
an I-SOM file named foo.ofrom foo.cusing the +Icompiler option;  
then the following commands are equivalent in effect:  
cc +P foo.c  
cc +P foo.o  
Both commands invoke the linker, but the second command doesn't  
compile before invoking the linker.  
Th e -P Lin k er Op tion  
After creating an I-SOM file for each source file, the compiler driver  
invokes the linker with the -Poption, causing the linker to optimize all  
the .ofiles. As with the +Ioption, the driver uses  
/opt/langtools/lbin/ucompto generate code and perform various  
optimizations.  
To see how the compiler invokes the linker, specify the -voption when  
compiling. For instance, suppose you have instrumented prog.cand  
gathered profile data into flow.data. The following example shows how  
the compiler driver invokes the linker when +Pis specified:  
$ cc -o prog -v +P prog.o  
/usr/ccs/bin/ld /usr/ccs/lib/crt0.o -u main -o prog \  
prog.o -P -lc  
Notice how the program is now linked with /usr/ccs/lib/crt0.o  
instead of /opt/langtools/lib/icrt0.obecause the profiling code is  
no longer needed.  
Chapter 8  
283  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
Usin g Th e flow.d a ta File  
By default, the code generator and linker look for the flow.datafile in  
the current working directory. In other words, the flow.datafile  
created during the profiling phase should be located in the directory  
where you relink the program.  
Sp ecifyin g a Differ en t flow.d a ta File w ith +d f  
What if you want to use a flow.datafile from a different directory than  
where you are linking? Or what if you have renamed the flow.datafile  
— for example, if you have multiple flow.datafiles created for different  
input sets? The +dfoption allows you to override the default +Pbehavior  
of using the file flow.datain the current directory. The compiler passes  
this option directly to the linker.  
For example, suppose after collecting profile data, you decide to rename  
flow.datato prog.prf. You could then use the +dfoption as follows:  
$ cc -v -o prog +P +df prog.prf prog.o  
/usr/ccs/bin/ld /usr/ccs/lib/crt0.o -u main -o prog \  
+df prog.prf prog.o -P -lc  
The +dfoption overrides the effects of the FLOW_DATAenvironment  
variable.  
Sp ecifyin g a Differ en t flow.d a ta w ith F LOW_DATA  
The FLOW_DATAenvironment variable provides another way to override  
the default flow.datafile name and location. If set, this variable  
defines an alternate file name for the profile data file.  
For example, to use the file /home/adam/projX/prog.datainstead of  
flow.data, set FLOW_DATA:  
$ FLOW_DATA=/home/adam/projX/prog.data  
$ export FLOW_DATA  
Bourne and Korn shell  
$ setenv FLOW_DATA /home/adam/projX/prog.data C shell  
In ter a ction betw een F LOW_DATA a n d +d f  
If an application is linked with +dfand -P, the FLOW_DATAenvironment  
variable is ignored. In other words, +dfoverrides the effects of  
FLOW_DATA.  
284  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
Sp ecifyin g a Differ en t P r ogr a m Na m e (+p gm )  
When retrieving a program's profile data from the flow.datafile, the  
linker uses the program's basename as a lookup key. For instance, if a  
program were compiled as follows, the linker would look for the profile  
data under the name foobar:  
$ cc -v -o foobar +P foo.o bar.o  
/usr/ccs/bin/ld /usr/ccs/lib/crt0.o -u main -o foobar \  
foo.o bar.o -P -lc  
This works fine as long as the name of the program is the same during  
the instrumentation and optimization phases. But what if the name of  
the instrumented program is not the same as name of the final optimized  
program? For example, what if you want the name of the instrumented  
application to be different from the optimized application, so you use the  
following compiler commands?  
$ cc -O +I -o prog.inst prog.c  
$ prog.inst < input_file1  
Instrument prog.inst.  
Profile it, storing the data  
under the name prog.inst.  
$ prog.inst < input_file2  
$ cc +P -o prog.opt prog.c  
Optimize it, but name it prog.opt.  
The linker would be unable to find the program name prog.optin the  
flow.datafile and would issue the error message:  
No profile data found for the program prog.opt in flow.data  
To get around this problem, the compilers and linker provide the +pgm  
name option, which allows you to specify a program name to look for in  
the flow.datafile. For instance, to make the above example work  
properly, you would include +pgm prog.inston the final compile line:  
$ cc +P -o prog.opt +pgm prog.inst prog.c  
Like the +dfoption, the +pgmoption is passed directly to the linker.  
Selectin g a n Op tim iza tion Level w ith P BO  
When -Pis specified, the code generator and linker perform profile-based  
optimizations on any I-SOM or regular object files found on the linker  
command line. In addition, optimizations will be performed according to  
the optimization level you specified with a compiler option when you  
instrumented the application. Briefly, the compiler optimization options  
are:  
+O0  
+O1  
Minimal optimization. This is the default.  
Basic block level optimization.  
Chapter 8  
285  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
+O2  
+O3  
+O4  
Full optimization within each procedure in a file. (Can  
also be invoked as -O.)  
Full optimization across all procedures in an object file.  
Includes subprogram inlining.  
Full optimization across entire application, performed  
at link time. (Invokes ld +Ofastaccess  
+Oprocelim.) Includes inlining across multiple files.  
NOTE  
Be aware that +O3and +O4are incompatible with symbolic debugging.  
The only compiler optimization levels that allow for symbolic debugging  
are +O2and lower.  
For more detailed information on compiler optimization levels, see your  
compiler documentation.  
PBO has the greatest impact when it is combined with level 2 or greater  
optimizations. For instance, this compile command combines level 2  
optimization with PBO (note that the compiler options +O2and -Oare  
equivalent):  
$ cc -v -O +I -c prog.c  
/opt/langtools/lbin/cpp prog.c /var/tmp/ctm123  
/opt/ansic/lbin/ccom /var/tmp/ctm123 prog.o -O2 -I  
$ cc -v -O +I -o prog prog.o  
/usr/ccs/bin/ld /opt/langtools/lib/icrt0.o -u main -o prog \  
prog.o -I -lc  
The optimizations are performed along with instrumentation. However,  
profile-based optimizations are not performed until you compile later  
with +P:  
$ cc -v +P -o prog prog.o  
/usr/ccs/bin/ld /usr/ccs/lib/crt0.o -u main \  
-o prog prog.o -P -lc  
Usin g P BO to Op tim ize Sh a r ed Libr a r ies  
Beginning with the HP-UX 10.0 release, the -Ilinker option can be used  
with -bto build a shared library with instrumented code. Also, the -P,  
+df, and +pgmcommand-line options are compatible with the -boption.  
To profile shared libraries, you must set the environment variable  
SHLIB_FLOW_DATAto the file that receives profile data. Unlike  
FLOW_DATA, SHLIB_FLOW_DATAhas no default output file. If  
SHLIB_FLOW_DATAis not set, profile data is not collected. This allows  
you to activate or suspend the profiling of instrumented shared libraries.  
286  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
Note that you could set SHLIB_FLOW_DATAto flow.datawhich is the  
same file as the default setting for FLOW_DATA. But, again, profile data  
will not be collected from shared libraries unless you explicitly set  
SHLIB_FLOW_DATAto some output file.  
The following is a simple example for instrumenting, profiling, and  
optimizing a shared library:  
$ cc +z +I -c -O libcode.c  
Create I-SOM files.  
$ ld -b -I libcode.o -o mylib.inst.sl Create instrumented sl.  
$ cc main.c mylib.inst.sl  
$ export SHLIB_FLOW_DATA=./flow.data  
profile data  
Creat executablea.outile.  
Specify output file for  
$ a.out < input_file  
Run instrumented executable  
with representative input data  
$ ld -b -P +pgm mylib.inst.sl \  
libcode.o -o mylib.sl  
Perform PBO.  
Note that the name used in the database will be the output pathname  
specified when the instrumented library is linked (mylib.inst.slin  
the example above), regardless of how the library might be moved or  
renamed after it is created.  
Usin g P BO w ith ld -r  
Beginning with the HP-UX 10.0 release, you can take greater advantage  
of PBO on merged object files created with the -rlinker option.  
Briefly, ld -rcombines multiple .ofiles into a single .ofile. It is often  
used in large product builds to combine objects into more manageable  
units. It is also often used in combination with the linker -hoption to  
hide symbols that may conflict with other subsystems in a large  
application. (See Hiding Symbols with -h” on page 81 for more  
information on ld -h.)  
In HP-UX 10.0, the subspaces in the merged .ofile produced by ld -r  
are relocatable which allows for greater optimization.  
The following is a simple example of using PBO with ld -r:  
$ cc +I -c file1.c file2.c  
Create individual I-SOM files  
$ ld -r -I -o reloc.o file1.o file2.o Build relocatable, merged file.  
$ cc +I -o a.out reloc.o  
$ a.out < input_file  
Create instrumented executable file.  
Run instrumented executable with  
representative input data.  
$ ld -r -P +pgm a.out -o reloc.o \  
file1.o file2.o  
$ cc +P -o a.out reloc.o  
Rebuild relocatable file for PBO.  
Perform PBO on the final executable file.  
Chapter 8  
287  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
Notice in the example above, that the +pgmoption was necessary because  
the output file name differs from the instrumented program file name.  
NOTE  
If you are using -rand C++ templates, check "Known Limitations" in the  
HP C++ Release Notes for possible limitations.  
Restr iction s a n d Lim ita tion s of P BO  
This section describes restrictions and limitations you should be aware of  
when using Profile-Based Optimization.  
“Temporary Files”  
Source Code Changes and PBO”  
Profile-Based Optimization (PBO) and High-Level Optimization  
(HLO)”  
I-SOM File Restrictions”  
PBO calls malloc()during the instrumentation (+I) phase. If you  
replace libcmalloc(3C) calls with your own version of malloc(), use  
the same parameter list (data types, order, number, and meaning of  
parameters) as the HP version. (For information on malloc(), see  
malloc(3C).)  
Tem p or a r y Files  
The linker does not modify I-SOM files. Rather, it compiles, instruments,  
and optimizes the code, placing the resulting temporary object file in a  
directory specified by the TMPDIRenvironment variable. If PBO fails due  
to inadequate disk space, try freeing up space on the disk that contains  
the $TMPDIRdirectory. Or, set TMPDIRto a directory on a disk with more  
free space.  
Sou r ce Cod e Ch a n ges a n d P BO  
To avoid the potential problems described below, PBO should only be  
used during the final stages of application development and performance  
tuning, when source code changes are the least likely to be made.  
Whenever possible, an application should be re-profiled after source code  
changes have been made.  
288  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
What happens if you attempt to optimize a program using profile data  
that is older than the source files? For example, this could occur if you  
change source code and recompile with +P, but don't gather new profile  
data by re-instrumenting the code.  
In that sequence of events, optimizations will still be performed.  
However, full profile-based optimizations will be performed only on those  
procedures whose internal structure has not changed since the profile  
data was gathered. For procedures whose structure has changed, the  
following warning message is generated:  
ucomp warning: Code for name changed since profile  
database file flow.data built. Profile data for name  
ignored. Consider rebuilding flow.data.  
Note that it is possible to make a source code change that does not affect  
the control flow structure of a procedure, but which does significantly  
affect the profiling data generated for the program. In other words, a  
very small source code change can dramatically affect the paths through  
the program that are most likely to be taken. For example, changing the  
value of a program constant that is used as a parameter or loop limit  
value might have this effect. If the user does not re-profile the  
application after making source code changes, the profile data in the  
database will not reflect the effects of those changes. Consequently, the  
transformations made by the optimizer could degrade the performance of  
the application.  
P r ofile-Ba sed Op tim iza tion (P BO) a n d High -Level  
Op tim iza tion (HLO)  
High-level optimization, or HLO, consists of a number of optimizations,  
including inlining, that are automatically invoked with the +O3and +O4  
compiler options. (Inlining is an optimization that replaces each call to a  
routine with a copy of the routine's actual code.) +O3performs HLO on  
each module while +O4performs HLO over the entire program and  
removes unnecessary ADDIL instructions. Since HLO distorts profile  
data, it is suppressed during the instrumentation phases of PBO.  
When +Iis specified along with +O3or +O4, an I-SOM file is generated.  
However, HLO is not performed during I-SOM generation. When the  
I-SOM file is linked, using the +Poption to do PBO, HLO is performed,  
taking advantage of the profile data.  
Exa m p le . The following example illustrates high-level optimization  
with PBO:  
Chapter 8  
289  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
$ cc +I +O3 -c file.c Create I-SOM for instrumentation.  
$ cc +I +O3 file.o  
Link with instrumentation.  
$ a.out < input_file Run instrumented executable with representative input  
data.  
$ cc +P +O3 file.o  
Perform PBO and HLO.  
Replace +O3with +O4in the above example to get HLO over the entire  
program and ADDIL elimination. (You may see a warning when using  
+O4at instrumentation indicating that the +O4option is being ignored.  
You can ignore this warning.)  
I-SOM File Restr iction s  
For the most part, there are not many noticeable differences between  
I-SOM files and ordinary object files. Exceptions are noted below.  
ld . Linking object files compiled with the +Ior +Poption takes much  
longer than linking ordinary object files. This is because in addition to  
the work that the linker already does, the code generator must be run on  
the intermediate code in the I-SOM files. On the other hand, the time to  
compile a file with +Ior +Pis relatively fast since code generation is  
delayed until link time.  
All options to ldshould work normally with I-SOM files with the  
following exceptions:  
-r  
The -roption works with both -Iand -P. However, it  
produces an object file, not an I-SOM file. In 64-bit  
mode, use -I, -P, or the +nosectionmergeoption on  
a -rlinker command to allow procedures to be  
positioned independently. Without these options, a -r  
link merges procedures into a single section.  
-s  
-G  
Do not use this option with -I. However, there is no  
problem using this option with -P.  
Do not use this option with -I. There is no problem  
using this option with -P.  
-A  
-N  
Do not use this option with -Ior -P.  
Do not use this option with -Ior -P.  
290  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
n m . The nmcommand works on I-SOM files. However, since code  
generation has not yet been performed, some of the imported symbols  
that might appear in an ordinary relocatable object file will not appear in  
an I-SOM file.  
a r . I-SOM files can be manipulated with arin exactly the same way  
that ordinary relocatable files can be.  
str ip . Do not run stripon files compiled with +Ior +P. Doing so  
results in an object file that is essentially empty.  
Com p iler Op tion s . Except as noted below, all cc, CC, and f77  
compiler options work as expected when specified with +Ior +P:  
-g  
-G  
This option is incompatible with +Iand +P.  
This option is incompatible with +I, but compatible  
with +P(as long as the insertion of the gproflibrary  
calls does not affect the control flow graph structure of  
the procedures.)  
-p  
This option is incompatible with +Ioption, but is  
compatible with +P(as long as the insertion of the  
profcode does not affect the control flow graph  
structure of the procedures.)  
-s  
-S  
You should not use this option together with +I. Doing  
so will result in an object file that is essentially empty.  
This option is incompatible with +Iand +Poptions  
because assembly code is not generated from the  
compiler in these situations. Currently, it is not  
possible to get assembly code listings of code generated  
by +Iand +P.  
-y/+y  
The same restrictions apply to these options that were  
mentioned for -gabove.  
+o  
This option is incompatible with +Iand +P. Currently,  
you cannot get code offset listings for code generated by  
+Iand +P.  
Com p a tibility w ith 9.0 P BO  
PBO is largely compatible between the 9.0 and 10.0 releases.  
Chapter 8  
291  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Profile-Based Optimization  
I-SOM files created under 9.0 are completely acceptable in the 10.0  
environment.  
However, it is advantageous to re-profile programs under 10.0 in order to  
achieve improved optimization. Although you can use profile data in  
flow.datafiles created under 9.0, the resulting optimization will not  
take advantage of 10.0 enhancements. In addition, a warning is  
generated stating that the profile data is from a previous release. See the  
section called Profiling” in this chapter for more information.  
See the section called Profiling” for more information about the warning  
generated for profile data generated from a previous release.  
292  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Improving Shared Library Start-Up Time with fastbind  
Im p r ovin g Sh a r ed Libr a r y Sta r t-Up  
Tim e w ith fa stbin d  
The fastbindtool improves the start-up time of programs that use  
shared libraries. When fastbindis invoked, it caches r eloca tion  
information inside the executable file. The next time the executable file  
runs, the dynamic loader uses this cached information to bind the  
executable instead of searching for symbols.  
The syntax for fastbind is:  
fastbind [ -n] [ -u]  
incomplete executable…  
where:  
-n  
-u  
Removes fastbinddata from the executable.  
Performs fastbindeven when unresolved symbols are  
found. (By default, fastbind stops when it cannot  
resolve symbols.)  
Usin g fa stbin d  
You can create and delete fastbindinformation for an executable file  
after it has been linked with shared libraries. You can invoke fastbind  
from the linker or use the fastbindtool directly. You can set the  
_HP_DLDOPTSenvironment variable to find out if fastbindinformation  
is out-of-date and to turn off fastbindat run time.  
In vok in g th e fa stbin d Tool  
To invoke fastbindon an in com p lete execu ta ble file, verify that your  
executable has write access (because fastbind writes to the file) and then  
run fastbind.  
$ ls -l main  
-rwxrwxrwx  
1 janet  
191  
28722 Feb 20 09:11 main  
$ fastbind main  
The fastbindtool generates fastbindinformation for mainand  
rewrites mainto contain this information.  
Chapter 8  
293  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Ways to Improve Performance  
Improving Shared Library Start-Up Time with fastbind  
In vok in g fa stbin d fr om th e Lin k er  
To invoke fastbind from ld, pass the request to the linker from your  
compiler by using the -Wl,+fboptions. For example:  
$ ld -b convert.o volume.o -o libunits.sl  
$ cc -Aa -Wl,+fb main.c -o main \  
libunits.sl -lc  
Build the shared library.  
Link main to the shared  
library. Perform fastbind.  
The linker performs fastbindafter it creates the executable file.  
How to Tell if fa stbin d In for m a tion is Cu r r en t  
By default, when the dynamic loader finds that fastbindinformation is  
out-of-date, it silently reverts back to the standard method for binding  
symbols. To find out if an executable file has out-of-date fastbind  
information, set the _HP_DLDOPTSenvironment variable as follows:  
$ export _HP_DLDOPTS=-fbverbose  
$ main  
/usr/lib/dld.sl: Fastbind data is out of date  
The dynamic loader provides a warning when the fastbindinformation  
is out-of-date.  
Rem ovin g fa stbin d In for m a tion fr om a File  
To remove fastbindinformation from a file, use the fastbindtool with  
the -noption. For example:  
$ fastbind -n main  
Remove fastbind information from main.  
Tu r n in g off fa stbin d a t Ru n Tim e  
To use the standard search method for binding symbols, instead of the  
fastbindinformation in an executable file, set the _HP_DLDOPTS  
environment variable as follows:  
export _HP_DLDOPTS=-nofastbind  
Turns off fastbind at run time.  
For Mor e In for m a tion :  
See the fastbind(1) man page.  
294  
Chapter8  
Download from Www.Somanuals.com. All Manuals Search And Download.  
A
Usin g Ma p files  
The ldcommand automatically maps sections from input object files  
onto output segments in executable files. The mapfile option allows you  
to change the default mapping provided by the linker.  
NOTE  
NOTE  
The mapfile option is supported only in 64-bit mode linking.  
In most cases, the linker produces a correct executable without the use of  
the mapfile option. The mapfile option is an advanced feature of the  
linker toolset intended for system programming use, not for application  
programming use. When using the mapfile option, you can easily create  
executable files that do not execute.  
295  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Controlling Maples with the -k Option  
Con tr ollin g Ma p files w ith th e -k Op tion  
The -koption to ldspecifies a text file containing mapfile directives:  
ld -k mapfile [flags] files ...  
The ldcommand automatically maps sections from input object files  
onto output segments in executable files. The mapfile option allows you  
to change the default mapping provided by the linker.  
Use the -kfilename option to specify a text file that contains mapfile  
directives. The linker appends the specified mapfile to the default  
mapfile unless you specify the +nodefaultmapoption.  
Ma p file Exa m p le: Usin g -k len a m e (w ith ou t  
+n od efa u ltm a p Op tion ):  
cat mapfile  
text = LOAD ?RX V0x1000;  
text : .rodata;  
text : .PARISC.milli;  
text : .dynamic;  
text : .dynsym;  
text : .dynstr;  
text : .hash;  
text : $PROGBITS ?AX;  
text : .PARISC.unwind;  
text : $UNWIND;  
data = LOAD ?RW V0x4000000040001000;  
data : .opd;  
data : .plt;  
data : .dlt;  
data : .data;  
data : $PROGBITS ?AW!S;  
data : .sdata;  
data : $PROGBITS ?AWS;  
data : .sbss;  
data : $NOBITS ?AWS;  
data : .bss;  
data : $NOBITS ?AW!S;  
note = NOTE;  
note : $NOTE;  
ld main.o -k mapfile -lc  
elfdump -h -S a.out  
a.out:  
*** Section Header ***  
Index TypeVaddr  
Offset  
Size  
Name  
296  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Controlling Maples with the -k Option  
1 DYNM 00000000000012a8 00000000000002a8 00000120 .dynamic  
1 DYNM 00000000000011c8 00000000000001c8 00000120 .dynamic  
2 DYNS 00000000000012e8 00000000000002e8 00000270 .dynsym  
3 STRT 0000000000001558 0000000000000558 00000113 .dynstr  
4 HASH 0000000000001670 0000000000000670 000000a4 .hash  
5 PBIT 0000000000001718 0000000000000718 00000044 .text  
6 PBIT 000000000000175c 000000000000075c 00000018 .interp  
10 RELA 0000000000001778 0000000000000778 00000000 .rela.opd  
15 PBIT 4000000040001020 0000000000001020 00000010 .plt  
16 PBIT 4000000040001030 0000000000001030 00000000 .dlt  
17 PBIT 4000000040001030 0000000000001030 00000000 .data  
18 PBIT 4000000040001030 0000000000001030 00000000 .HP.init  
19 PBIT 4000000040001030 0000000000001030 00000000 .preinit  
20 PBIT 4000000040001030 0000000000001030 00000000 .init  
21 PBIT 4000000040001030 0000000000001030 00000000 .fini  
22 PBIT 4000000040001030 0000000000001030 00000008 .sdata  
23 NOBI 4000000040001038 0000000000001038 00000008 .bss  
24 NOBI 0000000000000000 0000000000001038 00000000 .tbss  
25 STRT 0000000000000000 0000000000001038 000001b2 .strtab  
26 SYMT 0000000000000000 00000000000011ec 000004b0 .symtab  
27 STRT 0000000000000000 000000000000169c 000000de .shstrtab  
Appendix A  
297  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Changing Mapfiles with -k filename and +nodefaultmap  
Ch a n gin g Ma p files w ith -k len a m e a n d  
+n od efa u ltm a p  
The +nodefaultmapoption used with -koption prevents the linker  
from concatenating the default memory map to the map provided by  
filename. If you specify +nodefaultmap, the linker does not append the  
default mapfile to your mapfile. If you do not specify +nodefaultmap  
with -k, the linker appends the default to the output file.  
Ma p file Exa m p le: Usin g -k m a pfile a n d  
+nodefaultmap  
cat mapfile  
text = LOAD ?RX V0x1000;  
text : .rodata;  
text : .PARISC.milli;  
text : .dynamic;  
text : .dynsym;  
text : .dynstr;  
text : .hash;  
text : $PROGBITS ?AX;  
text : .PARISC.unwind;  
text : $UNWIND;  
data = LOAD ?RW V0x4000000040001000;  
data : .opd;  
data : .plt;  
data : .dlt;  
data : .data;  
data : $PROGBITS ?AW!S;  
data : .sdata;  
data : $PROGBITS ?AWS;  
data : .sbss;  
data : $NOBITS ?AWS;  
data : .bss;  
data : $NOBITS ?AW!S;  
note = NOTE;  
note : $NOTE;  
ld main.o +nomapfile -k mapfile -lc  
elfdump -h -S a.out  
a.out:  
*** Section Header ***  
Index TypeVaddr  
Offset  
Size  
Name  
1 DYNM 00000000000011c8 00000000000001c8 00000120 .dynamic  
2 DYNS 00000000000012e8 00000000000002e8 00000270 .dynsym  
3 STRT 0000000000001558 0000000000000558 00000113 .dynstr  
4 HASH 0000000000001670 0000000000000670 000000a4 .hash  
298  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Changing Mapfiles with -k filename and +nodefaultmap  
5 PBIT 0000000000001718 0000000000000718 00000044 .text  
6 PBIT 000000000000175c 000000000000075c 00000018 .interp  
7 RELA 0000000000001778 0000000000000778 00000000 .rela.HP.init  
8 RELA 0000000000001778 0000000000000778 00000000 .rela.init  
9 RELA 0000000000001778 0000000000000778 00000000 .rela.fini  
10RELA 0000000000001778 0000000000000778 00000000 .rela.opd  
11RELA 0000000000001778 0000000000000778 00000018 .rela.plt  
12RELA 0000000000001790 0000000000000790 00000000 .rela.dlt  
13UNWI 0000000000001790 0000000000000790 00000010 .PARISC.unwind  
14PBIT 4000000040001000 0000000000001000 00000020 .opd  
15PBIT 4000000040001020 0000000000001020 00000010 .plt  
16PBIT 4000000040001030 0000000000001030 00000000 .dlt  
17PBIT 4000000040001030 0000000000001030 00000000 .data  
18PBIT 4000000040001030 0000000000001030 00000000 .HP.init  
19PBIT 4000000040001030 0000000000001030 00000000 .preinit  
20PBIT 4000000040001030 0000000000001030 00000000 .init  
21PBIT 4000000040001030 0000000000001030 00000000 .fini  
22PBIT 4000000040001030 0000000000001030 00000008 .sdata  
23NOBI 4000000040001038 0000000000001038 00000008 .bss  
24NOBI 0000000000000000 0000000000001038 00000000 .tbss  
25STRT 0000000000000000 0000000000001038 000001b2 .strtab  
26SYMT 0000000000000000 00000000000011ec 000004b0 .symtab  
27STRT 0000000000000000 000000000000169c 000000de .shstrtab  
Appendix A  
299  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Simple Maple  
Sim p le Ma p file  
The following directives show how a simple mapfile would appear:  
# text segment  
text = LOAD ?RX;  
text : .rodata ?A;  
text : $PROGBITS ?AX;  
# data segment  
data = LOAD ?RW;  
data : $PROGBITS ?AW!S;  
data : $PROGBITS ?AWS;  
data : $NOBITS ?AWS;  
data : $NOBITS ?AW!S;  
# note segment  
note = NOTE;  
note : $NOTE;  
# non-segment  
nonsegment = NONSEGMENT;  
300  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Default HP-UX Release 11.0 Mapfile  
Defa u lt HP -UX Relea se 11.0 Ma p file  
The HP-UX Release 11.0 64-bit linker uses the following default mapfile:  
# text segment  
text = LOAD ?RXc V0x4000000000001000;  
text : .dynamic;  
text : .dynsym;  
text : .dynstr;  
text : .hash;  
text : $REL ?A;  
text : $RELA ?A;  
text : $UNWIND ?A;  
text : $PROGBITS ?A!X!W;  
text : .PARISC.milli;  
text : .text;  
text : $PROGBITS ?AX!W;  
# data segment  
data : .hdata;  
data =LOAD ?RWmo V0x8000000000001000;  
data : .data;  
data : $PROGBITS ?AW!S;  
data : .opd;  
data : .plt;  
data : .dlt;  
data : .sdata;  
data : $PROGBITS ?AWS;  
data : .sbss;  
data : $NOBITS ?AWS;  
data : .bss;  
data : $NOBITS ?AW!S;  
data : .hbss  
# Thread specific storage segment  
thread_specific = HP_TLS ?RW;  
thread_specific : .tbss;  
Appendix A  
301  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Default HP-UX Release 11.0 Mapfile  
thread_specific : $NOBITS ?AWT;  
# Note segment  
note = NOTE;  
note : $NOTE;  
# non-segment  
nonsegment = NONSEGMENT;  
nonsegment : .debug_header;  
nonsegment : .debug_gntt;  
nonsegment : .debug_ntt;  
nonsegment : .debug_slt;  
nonsegment : .debug_vt;  
302  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Dening Syntax for Maple Directives  
Defin in g Syn ta x for Ma p file Dir ectives  
A mapfile can have zero or more mapfile directives. There are two types  
of mapfile directives: segm en t d ecla r a tion s and section m a p p in g  
d ir ectives. The directives can span across lines and are terminated by a  
semicolon.  
The following syntax conventions are used to describe the directives:  
[...]*means zero or more  
[...]+means one or more  
[...] means optional  
The section_names and segment_names are the same as a C identifier  
except that a period (.) is treated as a letter.  
A number can be hexadecimal, following the same syntax as the C  
language.  
The section, segment, file, and symbol names are case-sensitive.  
A string of characters following #and ending at a new-line is  
considered a comment.  
Appendix A  
303  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Dening Maple Segment Declarations  
Defin in g Ma p file Segm en t Decla r a tion s  
A segment declaration can create a new segment with a set of attributes  
or change the attributes of an existing segment.  
segment_name = {segment_attribute_value}* ;  
The segment attributes and their valid values are as follows:  
Attr ibu te  
Va lu e  
segment_type  
segment_flags  
virtual_address  
physical_address  
alignment  
LOAD(default), HP_TLS, NOTE, NONSEGMENT  
?[R][W][X][s][l][m][c][k][g][o]  
Vnumber  
Pnumber  
Anumber  
NOTEsegments cannot be assigned any segment attribute other than  
a segment_type.  
If you do not specify virtual_address, physical_address and  
alignment, the linker calculates these values as it builds the  
executable. If you specify both a virtual_address and an alignment for  
a segment, the virtual_address value takes priority.  
An alignment value greater than the file system block size (4K) also  
specifies the page size. In that case, the value of the alignment is also  
the size of the page. The operating system uses the largest page size  
available that is no greater than the value of the alignment when  
mapping a segment.  
The segment_type NONSEGMENTdescribes sections placed at the end of  
the executable file. The linker does not create a program header entry  
for this segment.  
Segm en t F la gs  
Segment declarations support the following segment flags:  
304  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Dening Maple Segment Declarations  
F la g  
Action  
R
W
X
Readable  
Writable  
Executable  
The default segment_flags for a LOADable segment is ?RWX.  
Segment declarations support the following special flags:  
F la g  
Action  
s
Enables static branch prediction on a segment. This flag is  
not set by default. (Dynamic branch prediction is the default.)  
l
m
Enables lazy swap allocation for a segment. This flag is not  
set by default. (The lazy swap is disabled by default.)  
Sets the modification” hint for a segment. When this flag is  
set, it indicates that the program expects to modify the pages  
in the segment. If not set, the program does not expect to  
modify any pages in the segment, even though it may have  
permission to do so. This flag is not set by default. (The  
modification hint is off by default.)  
c
Sets the code” hint for a segment. When this flag is set, it  
indicates that the segment mostly contains code that may be  
executed. When not set, it indicates that it is unlikely that  
the segment contains code. This flag is not set by default.  
(The code hint is off by default.)  
Appendix A  
305  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Dening Maple Segment Declarations  
F la g  
Action  
k
g
Locks a particular segment into memory when loaded. This  
flag is set off for all segments.  
Groups segments together. A segment declared with gflag is  
grouped with a segment preceding it in the mapfile. Any  
number of segments can be grouped together. The grouping  
affects the way in which addresses are assigned to segments.  
The segments in one group are assigned consecutive virtual  
addresses.  
o
Tells the linker that all the segment attributes declared for  
this segment can be changed or modified to achieve space  
and/or time optimization. When this flag is set, the linker  
considers all other segment attribute specifications (for this  
segment) as hints and change or modify them as it thinks fit  
for space and/or time optimization.  
Ma p file Segm en t Decla r a tion Exa m p les  
The following example declares a segment with segment_type LOAD  
and segment_flags readable and executable.  
text = LOAD ?RX;  
The following example declares a LOADable segment (default) with  
segment_flags readable and writable. The virtual_address and  
alignment values are set to V0x80000000and A0x1000respectively.  
mydata = ?RW V0x80000000 A0x1000;  
306  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Dening Maple Section Mapping Directives  
Defin in g Ma p file Section Ma p p in g  
Dir ectives  
A section mapping directive specifies how the linker should map the  
input section onto output segments. This directive tells the linker what  
attributes of a section must be matched in order to map that section into  
the named segment. The set of attribute values that a section must have  
to map into a specific segment is called the en tr a n ce cr iter ia .  
segment_name : {section_attribute_value}* ;  
The section attributes and their valid values are as follows:  
Section  
Attr ibu te  
Va lu e  
section_name  
section_type  
Any valid section name  
$PROGBITS, $NOBITS, $UNWIND, $NOTE, $REL,  
$RELA  
section_flags  
?[[!]A][[!]W][[!]X][[!][S]][[!][T][[!][R]  
F la g  
Va lu e  
A
W
X
S
T
R
Allocatable (takes up virtual memory)  
Writable  
Executable  
Short data  
TLS(thread local storage)  
Static branch prediction  
At most one section_type can be specified in a mapping directive.  
Appendix A  
307  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Dening Maple Section Mapping Directives  
If a section flag is preceded by an exclamation mark (!), it indicates  
that the flag should not be set to meet the entrance criteria.  
If you do not specify section_flags, the flag can have any value to  
meet the entrance criteria.  
S1 : ?XR;  
The linker maps all executable sections with static branch prediction  
enabled onto segment S1.  
The section_name attribute indicates that the linker should map the  
input sections with the specified name onto the named segment.  
text : .rodata;  
An input section can satisfy more than one entrance criteria.  
S1 : $PROGBITS;  
S2 : $PROGBITS;  
In this case, all sections with section type $PROGBITSare mapped  
onto segment S1as the first rule takes precedence.  
An AND relationship exits between attributes specified on the same  
line. An OR relationship exits between attributes specified for the  
same segment that span more than one line.  
Example 1:  
All sections with section_type $PROGBITSand section_flags AX  
(allocatable and executable) are mapped onto the text segment.  
text : $PROGBITS ?AX;  
Example 2  
text : $PROGBITS ?AX;  
text : .rodata;  
In this case, the linker maps a section onto the text segment if:  
Its section_type is $PROGBITSand section_flags is AX.  
(or)  
Its section_name is .rodata.  
308  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Internal Map Structure  
In ter n a l Ma p Str u ctu r e  
The linker use a default map structure corresponding to the default  
mapfile. When you use the mapfile option with the ldcommand, the  
linker appends the default mapfile to the end of your user-specified  
mapfile. (You can override the default mapfile by using the  
+nodefaultmapoption.)  
P la cem en t of Segm en ts in a n Execu ta ble  
As it processes each segment declaration in the mapfile, the linker  
compares it with the existing list of segment declarations as follows:  
If the segment does not exist already, but another with the same  
segment_type exists, the linker adds the segment after all of the  
existing segments with the same segment_type.  
If no segment with the same segment_type exists, the linker adds the  
new segment to the list to maintain the following order based on  
segment_type:  
LOAD  
HP_TLS  
NOTE  
NONSEGMENT  
If segments of same type already exists, the linker adds the new  
segment after the last segment with the same type.  
Ma p p in g In p u t Section s to Segm en ts  
As each section mapping directive in a mapfile is read in, the linker  
creates a new entrance criteria and appends it to the existing list of  
entrance criteria. It applies the entrance criteria in the order in which  
they are specified in the mapfile. The linker maps out the input sections  
in the same order as their matching entrance criteria.  
Appendix A  
309  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Internal Map Structure  
Figu r e A-1  
310  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Internal Map Structure  
Figure A-1 shows the map structure. The entrance criteria boxes  
correspond to the information from the section mapping directives and  
the segment attribute descriptors correspond to the information from the  
segment declarations. The output section descriptors boxes group the  
sections that fall under each segment based on their section attributes.  
The linker associates each entrance criteria with a list of output section  
descriptors. In Figure A-1, the entrance criteria are labeled with  
numbers to illustrate their associated output section descriptors.  
The linker performs the following steps when mapping sections to  
segments:  
1. When a section is read in, the liner checks the list of entrance criteria  
looking for a match. All specified criteria must be matched. When an  
entrance criteria matches, the linker traverses its associated output  
section descriptor” list.  
2. If the section attribute values match those of an existing output  
section descriptor exactly, the linker places the section at the end of  
the list of sections associated with that output section descriptor.  
3. If no matching output section descriptor is found, but output section  
descriptors of the same section_type exists, the linker creates a new  
output section descriptor with the same attribute values as the  
section and adds that section to the new output section descriptor. It  
places the new output section descriptor after the last output section  
descriptor with the same section type.  
4. If no other output section descriptor of the indicated section_type  
exists, the linker creates a new output section descriptor and  
associates the section with the new output section descriptor. It  
places the new output section descriptor after the last output section  
descriptor associated with that entrance criteria.  
5. If no entrance criteria match is found, the linker places the section at  
the end of the nonsegment. It does not create a program header  
entry for the nonsegment.  
The following rules apply when the linker adds a new output section  
descriptor to a list of output section descriptors associated with an  
entrance criteria:  
If an entrance criteria selects both $PROGBITSand $NOBITSsections,  
the linker enforces an order such that the $PROGBITSsections  
precede $NOBITSsections.  
Appendix A  
311  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Internal Map Structure  
If an entrance criteria selects both S(short data) and !S(non-short  
data) sections, the layout of the sections depends on section_type and  
Sflag status.The linker maintains the following order:  
$PROGBITSand !S  
$PROGBITSand S  
$NOBITSand S  
$NOBITSand !S  
The linker always tries to group all $NOBITSsections at the end of  
the data segment. If it does not place a $NOBITSsection at the end of  
the data segment because of user-specified mapping directives, the  
linker converts that section to a $PROGBITSsection and zero-fills the  
section contents. The linker issues a warning message when it  
converts a $NOBITSsection into a $PROGBITSsection.  
In ter a ction betw een User -d efin ed a n d  
Defa u lt Ma p file Dir ectives  
The linker adds the section mapping directives from the default mapfile  
after the user-specified mapping directives. The following rules apply if  
the you declare a built-in segment (a segment defined in the default  
mapfile):  
If the segment_type and segment_flags” differ from the default  
mapfile declarations, the linker issues a warning and uses the  
user-specified segment_type and/or segment_flags for that segment.  
If your segment declaration does not specify a  
segment_attribute_value, the linker takes it from the default mapfiles  
segment declaration.  
The linker completely ignores the default mapfile if you use the  
option +nodefaultmapon the ldcommand line.  
312  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Maple Option Error Messages  
Ma p file Op tion Er r or Messa ges  
Fa ta l Er r or s  
The following conditions can result in a fatal error:  
Specifying more than one -koption on the command line  
Mapfile cannot be opened or read  
The linker finds a syntax error in the mapfile  
More than one segment_type, segment_flags, virtual_address,  
physical_address or alignment value appears on a single declaration  
line  
More than one section_name, section_type, or section_flags value  
appears on a single directive line  
A user-defined virtual address causes a segment to overlap the  
previous segment  
Wa r n in gs  
The following conditions can produce a warning message:  
A physical_address or a virtual_address value is specified for any  
segment other than a LOADable segment. The directive is ignored.  
A second declaration for the same segment changes an attribute  
value. The second declaration overrides the original.  
An attribute value for a built-in segment is changed.  
Appendix A  
313  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Using Mapfiles  
Maple Option Error Messages  
314  
AppendixA  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
a bsolu te object cod e Machine  
routines and data. When a symbol  
code that contains absolute virtual is bound, it is accessible to the  
addresses. Created by the linker  
when it combines relocatable  
object files.  
program.  
br ea d th -r st sea r ch or d er The  
dependent library search  
a r ch ive libr a r y A library,  
created by the arcommand, which  
contains one or more object  
algorithm used when linking and  
loading 64-bit applications.  
modules. By convention, archive  
library file names end with .a.  
Compare with "shared library."  
bss segm en t A segment of  
memory in which uninitialized  
data is stored. Compare with "text  
segment" and "data segment." For  
details, refer to a.out(4).  
a tta ch in g a sh a r ed libr a r y The  
process the dynamic loader goes  
through of mapping the shared  
library code and data into a  
process's address space, relocating  
any pointers in the shared library  
data that depend on actual virtual  
addresses, allocating the bss  
segment, and binding routines and  
data in the shared library to the  
program.  
bu ffer A temporary holding area  
for data. Buffers are used to  
perform input and output more  
efficiently.  
ch ild A process that is spawned by  
a process (a sub-process).  
cod e gen er a tion A phase of  
compilation in which object code is  
created.  
ba sic block A contiguous section  
of assembly code, produced by  
compilation, that has no branches  
in except at the top, and no  
com p ila tion p h a se A particular  
step performed during compilation  
branches out except at the bottom. — for example, pre-processing,  
lexical analysis, parsing, code  
bin d in g The process the dynamic  
loader goes through of filling in a  
process's procedure linkage tables  
and data linkage tables with the  
addresses of shared library  
generation, linking.  
com p lete execu ta ble An  
executable (a.out) file that does  
not use shared libraries. It is  
"complete" because all of its library  
Glossary  
315  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
code is contained within it.  
Compare with "incomplete  
executable."  
-b…), other libraries were  
specified on the command line. See  
also "dependent library."  
cr t0.o file See sta r tu p file.  
d ep en d en t libr a r y A library  
that was specified on the command  
line when building a shared library  
(with ld -b…). See "dependency."  
d a ta exp or t sym bol An  
initialized global variable that may  
be referenced outside of the library.  
d ep th -r st sea r ch or d er The  
dependent library search  
d a ta lin k a ge ta ble A linkage  
table that stores the addresses of  
data items.  
alogrithm used when linking and  
loading in 32-bit mode. Searching  
a list starting at the end of the list  
and moving toward the head.  
Shared library initialization  
routines are invoked by traversing  
the list of loaded shared libraries  
depth-first.  
d a ta segm en t A segment of  
memory containing a program's  
initialized data. Compare with "bss  
segment" and "text segment." For  
details, refer to a.out(4).  
d efer r ed bin d in g The process of  
waiting to bind a procedure until a  
program references it. Deferred  
binding can save program startup  
time. Compare with "immediate  
binding."  
d ll See "dynamic loading library."  
DLT See "data linkage table."  
d r iver A program that calls other  
programs.  
d em a n d -loa d a ble When a  
process is "demand-loadable," its  
pages are brought into physical  
memory only when they are  
accessed.  
d yn a m ic lin k in g The process of  
linking an object module with a  
running program and loading the  
module into the program's address  
space.  
d ep en d en cy Occurs when a  
shared library depends on other  
libraries — that is, when the  
shared library was built (with ld  
d yn a m ic loa d er Code that  
attaches a shared library to a  
program. See dld.sl(5).  
316  
Glossary  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
d yn a m ic loa d in g libr a r y An  
SVR4 term for a shared library.  
exter n a l r efer en ce A reference  
to a symbol defined outside an  
object file.  
d yn a m ic sea r ch p a th The  
process that allows the location of  
shared libraries to be specified at  
runtime.  
feed ba ck -d ir ected p osition in g  
An optimization technique  
wherein procedures are relocated  
in a program, based on profiling  
data obtained from running the  
program. Feedback-directed  
positioning is one of the  
en tr y p oin t The location at  
which a program starts running  
after HP-UX loads it into memory.  
The entry point is defined by the  
symbol $START$in crt0.o.  
optimizations performed during  
profile-based optimization.  
exp licit loa d in g The process of  
using the shl_load(3X) function to  
load a shared library into a  
running program.  
file d escr ip tor A file descriptor is  
returned by the open(2), creat(2),  
and dup(2) system calls. The file  
descriptor is used by other system  
calls (for example, read(2),  
write(2), and close(2)) to refer to a  
the file.  
exp or t stu b A short code  
segment generated by the linker  
for a global definition in a shared  
library. External calls to shared  
library procedures go through the  
export stub. See also im p or t stu b.  
filter s Programs that accept input  
data and modify it in some way  
before passing it on. For example,  
the prcommand is a filter.  
exp or t sym bol A symbol  
definition that may be referenced  
outside the library.  
flu sh The process of emptying a  
buffer's contents and resetting its  
internal data structures.  
exp or tin g a sym bol Making a  
symbol visible to code outside the  
module in which the symbol was  
defined. This is usually done with  
the +eor -Eoption.  
globa l d efin ition A definition of a  
procedure, function, or data item  
that can be accessed by code in  
another object file.  
Glossary  
317  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
h ea d er str in g A string,  
im p or t sym bol An external  
"!<arch>\n", which identifies a  
file as an archive created by ar(\n  
represents the newline character).  
reference made from a library.  
in com p lete execu ta ble An  
executable (a.out) file that uses  
shared libraries. It is "incomplete"  
because it does not actually  
contain the shared library code  
that it uses; instead, the shared  
library code is attached when the  
program runs. Compare with  
"complete executable."  
h id in g a sym bol Making a  
symbol invisible to code outside the  
module in which the symbol was  
defined. Accomplished with the -h  
linker option.  
im m ed ia te bin d in g By default,  
the dynamic loader attempts to  
bind all symbols in a shared  
library when a program starts up  
known as "immediate binding."  
Compare with "deferred binding."  
in d ir ect a d d r essin g The process  
of accessing a memory location  
through a memory address that is  
stored in memory or a register.  
im p licit a d d r ess d ep en d en cy  
in itia lizer An initialization  
routine that is called when a  
shared library is loaded or  
unloaded.  
Writing code that relies on the  
linker to locate a symbol in a  
particular location or in a  
particular order in relation to  
other symbols.  
in ter m ed ia te cod e A  
representation of object code that  
is at a lower level than the source  
code, but at a higher level than the  
object code.  
im p licit loa d in g Occurs when  
the dynamic loader automatically  
loads any required libraries when  
a program starts execution.  
I-SOM Intermediate code-System  
Object Module. Used during  
profile-based optimizations and  
level 4 optimization.  
Compare with "explicit" loading.  
im p or t stu b A short code segment  
generated by the linker for  
external references to shared  
library routines. See also exp or t  
stu b.  
libr a r y A file containing object  
code for subroutines and data that  
can be used by programs.  
318  
Glossary  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
lin k or d er The order in which  
object files and libraries are  
specified on the linker command  
line.  
m a gic n u m ber A number that  
identifies how an executable file  
should be loaded. Possible values  
are SHARE_MAGIC,  
DEMAND_MAGIC, and  
lin k -ed it p h a se The compilation EXEC_MAGIC. Refer to magic(4) for  
phase in which the compiler calls  
the linker to create an executable  
(a.out) file from object modules  
and libraries.  
details.  
m a n p a ge A page in the HP-UX  
Reference. Man page references  
take the form title(section), where  
title is the name of the page and  
section is the section in which the  
page can be found. For example,  
open(2) refers to the open(2) page  
in section 2 of the HP-UX  
lin k a ge ta ble A table containing  
the addresses of shared library  
routines and data. A process calls  
shared library routines and  
accesses shared library data  
indirectly through the linkage  
table.  
Reference. Or use the man(1)  
command to view man pages, for  
example, man open.  
loa d gr a p h A list of dependent  
shared libraries in the order in  
m a p le The file which describes  
which the libraries are to be loaded the mapping of input sections to  
by the dynamic loader. Any  
executable program or shared  
library with dependencies has a  
load graph.  
segments in an output file.  
m illicod e Special-purpose  
routines written in assembly  
language and designed for  
performance.  
loca l d efin ition A definition of a  
routine or data that is accessible  
only within the object file in which  
it is defined.  
n on fa ta l bin d in g Like  
immediate binding, nonfatal  
immediate binding causes all  
required symbols to be bound at  
program startup. The main  
difference from immediate binding  
lock file A file used to ensure that  
only one process at a time can  
access data in a particular file.  
Glossary  
319  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
is that program execution  
P IC See "position-independent  
continues even if the dynamic  
loader cannot resolve symbols.  
code."  
p ip e An input/output channel  
intended for use between two  
processes: One process writes into  
the pipe, while the other reads.  
object cod e See r eloca ta ble  
object cod e.  
object file A file containing  
machine language instructions and  
data in a form that the linker can  
use to create an executable  
program.  
P LT See "procedure linkage table."  
p osition -in d ep en d en t cod e  
Object code that contains no  
absolute addresses. All addresses  
are specified relative to the  
program counter or indirectly  
through the linkage table.  
object m od u le A file containing  
machine language code and data in  
a form that the linker can use to  
create an executable program or  
shared library.  
Position-independent code can be  
used to create shared libraries.  
p a r en t p r ocess The process that  
spawned a particular process. See  
also "process ID."  
p r a gm a A C directive for  
controlling the compilation of  
source.  
P BO See "profile-based  
optimization."  
p r oced u r e lin k a ge ta ble A  
linkage table that stores the  
addresses of procedures and  
functions.  
P C-r ela tive A form of machine-  
code addressing in which  
addresses are referenced relative  
to the program counter register, or  
PC register.  
p r ocess ID An integer that  
uniquely identifies a process.  
Sometimes referred to as "PID."  
p h ysica l a d d r ess A reference to  
an exact physical memory location  
(as opposed to virtual memory  
location).  
p r ofile-ba sed op tim iza tion A  
kind of optimization in which the  
compiler and linker work together  
to optimize an application based on  
320  
Glossary  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
profile data obtained from running section m a p p in g d ir ective A  
the application on a typical input  
data set.  
mapfile directive which specifies  
how the linker should map the  
input sections onto the output  
segments.  
r eloca ta ble object cod e  
Machine code that is generated by  
compilers and assemblers. It is  
relocatable in the sense that it  
does not contain actual addresses;  
instead, it contains symbols  
segm en t d ecla r a tion A mapfiel  
directive which creates a new  
section or edits the attributes of an  
existing segment.  
corresponding to actual addresses.  
The linker decides where to place  
these symbols in virtual memory,  
and changes the symbols to  
sh a r ed execu ta ble An a.out  
file whose text segment is  
shareable by multiple processes.  
absolute virtual addresses.  
sh a r ed libr a r y A library, created  
by the ldcommand, which  
contains one or more PIC object  
modules. Shared library file names  
end with .sl. Compare with  
"archive library."  
r eloca tion The process of revising  
code and data addresses in  
relocatable object code. This occurs  
when the linker must combine  
object files to create an executable  
program. It also occurs when the  
dynamic loader loads a shared  
library into a process's address  
space.  
sh a r ed libr a r y h a n d le A  
descriptor of type shl_t(type  
defined in <dl.h>), which shared  
library management routines use  
to refer to a loaded shared library.  
r estr icted bin d in g A type of  
binding in which the dynamic  
loader restricts its search for  
symbols to those that were visible  
when a library was loaded.  
sta n d a r d er r or The default  
stream for sending error messages  
usually connected to the screen.  
sta n d a r d in p u t The default  
stream for collecting character  
input data — usually connected to  
the keyboard.  
RPATH The variable which  
contains the search path for  
dynamic libraries.  
Glossary  
321  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
sta n d a r d in p u t/ou tp u t libr a r y  
example, shared-library calls), long  
branches, and preserving calling  
interfaces across modules (for  
example, parameter relocation).  
Refer to the manual PA-RISC  
Procedure Calling Conventions  
Reference Manual. See also  
A collection of routines that  
provide efficient and portable  
input/output services for most C  
programs.  
sta n d a r d ou tp u t The default  
stream for sending character  
output data — usually connected  
to the screen.  
im p or t stu b and exp or t stu b.  
su p p or tin g libr a r y A library  
that was specified on the command  
line when building a shared library  
(with ld -b…). Same as  
sta r tu p file Also known as  
crt0.o, this is the first object file  
that is linked with an executable  
program. It contains the program's  
entry point. The startup code does  
such things as retrieving command  
line arguments into the program at  
run time, and activating the  
d ep en d en t libr a r y.  
sym bol n a m e The name by  
which a procedure, function, or  
data item is referred to in an object  
module.  
dynamic loader (dld.sl(5)) to load  
any required shared libraries.  
sym bol ta ble A table, found in  
object and archive files, which lists  
the symbols (procedures or data)  
defined and referenced in the file.  
For symbols defined in the file, an  
offset is stored.  
stor a ge exp or t sym bol An  
uninitialized global variable that  
may be referenced outside of the  
library.  
system ca lls System library  
routines that provide low-level  
system services; they are  
documented in section 2 of the HP-  
UX Reference.  
str ea m A data structure of type  
FILE *used by various input/  
output routines.  
stu b A short code segment  
inserted into procedure calling  
sequences by the linker. Stubs are  
used for very specific purposes,  
such as inter-space calls (for  
text segm en t A segment of read-  
only memory in which a program's  
machine language instructions are  
322  
Glossary  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
typically stored. Compare with  
"bss segment" and "data segment."  
For details, refer to a.out(4).  
u m a sk A field of bits (set by the  
umask(1) command) that turns off  
certain file permissions for newly  
created files.  
ver sion n u m ber A number that  
differentiates different versions of  
routines in a shared library.  
w r a p p er libr a r y A library that  
contains alternate versions of  
library functions, each of which  
performs some bookkeeping and  
then calls the actual function.  
Glossary  
323  
Download from Www.Somanuals.com. All Manuals Search And Download.  
Glossa r y  
324  
Glossary  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
Sym bols  
+pd chatr option, 273  
+pd linker option, 273  
+pgm compiler/linker option,  
285  
+pi chatr option, 273  
+pi linker option, 273  
+s linker option, 86, 104, 145,  
178  
A
$LIT$ text space and  
performance, 148  
-A linker option, 99, 271, 290  
-A name linker option, 28  
-a search linker option, 63  
a.out executable file  
$START$ symbol, 43  
_start symbol, 43  
$START$ symbol, 43  
$TEXT$ space and performance,  
148  
+b linker option, 176, 178  
+b path_list linker option, 84,  
104, 145  
aouthdr.h header file, 67  
attributes, changing, 104  
creating, 36  
+std linker option, 25, 90, 91  
+stripunwind linker option, 25,  
96  
+cg linker option, 28  
+compat linker option, 25, 90  
+DA compiler option, 21  
+df compiler and linker option,  
282, 284  
entry point, 43, 317  
filehdr.h header file, 67  
format, 44  
+vtype linker option, 25, 97  
+y compiler option, 291  
+z and +Z compiler options, 122,  
138, 262  
header structure, 67  
permissions, 45  
+df option, 276  
.0 suffix for shared library, 46,  
122, 150  
+dpv linker option, 28  
+e linker option, 79, 84, 146  
+ee linker option, 81  
+ESlit option to cc, 148  
+fb linker option, 294  
+fini linker option, 202  
+h linker option, 152  
+hideallsymbols linker option,  
25, 95  
renaming, 55  
som_exec_auxhdr structure,  
.1 suffix for shared library, 151  
.a suffix for archive library, 46,  
122  
67  
-Aa ANSI C compiler option, 36  
absolute object code, 261, 315  
accessing online help, 33  
ADDIL elimination, 270  
alloc_load_space function, 72  
aouthdr.h header file, 67  
ar command, 131, 136  
adding object modules, 134  
deleting object modules, 135  
extracting modules, 135  
keys, summary, 135  
replacing object modules, 134  
using with I-SOM files, 291  
verbose output, 135  
.sl suffix for shared library, 46,  
122  
/opt/langtools/lib/icrt0.o startup  
file, 277, 278  
/usr/ccs/lib/scrt0.o startup file,  
+I compiler option, 277, 278  
+I linker option, 203  
+init linker option, 202  
+noallowunsats linker option,  
25, 94  
277  
/usr/contrib/lib directory, 136  
/usr/lib directory, 47, 136  
/usr/lib/libp directory, 47  
/usr/local/lib directory, 136  
_clear_counters function, 282  
_HP_DLDOPTS environment  
variable, 294  
+nodefaultmap linker option,  
25, 95, 296, 298  
+noenvvar linker option, 25, 96  
+noforceload linker option, 25,  
93  
archive library  
_start symbol, 43  
adding object modules, 134  
compared with shared, 122,  
124  
_write_counters() routine, 280  
+nosectionmerge linker option,  
290  
Nu m er ics  
+o compiler option, 291  
+O level optimization option,  
270  
+Ofastaccess linker option, 270  
+Olevel optimization option, 285  
+Oprocelim linker option, 270  
+P compiler option, 283  
contents, 132  
creating, 131, 133  
32-bit mode initializers, 203  
creation dates, 135  
64-bit mode  
definition of, 125, 315  
deleting object modules, 135  
extracting modules, 135  
header string, 132  
compatibility mode, 90  
linker options, 90  
standard mode, 90  
Index  
325  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
linking, 93  
loading, 93  
location, 136  
restricted, 59, 104, 321  
BIND-NONFATAL flag to  
shl_load, 220  
code generation, 315  
default libraries, 46  
driver, 38  
migrating to shared library,  
158, 161  
breadth-first search order, 182,  
flow.data file, specifying with  
+df, 282, 284  
315  
mixing with shared libraries,  
bss segment, 315  
buffer, 315  
-G option, 291  
164  
-g option, 291  
naming, 122  
incompatibilities with PBO,  
replacing object modules, 134  
selecting at link time, 63  
symbol table, 132, 322  
assembler  
291  
C
instrumenting for PBO with  
+I, 277, 278  
-c compiler option, 55  
-c filename linker option, 86  
-C linker option, 28, 99  
C++  
library search path,  
augmenting with (-Wl,-L),  
53  
internal pseudo-op, 160  
position-independent code, 264  
atexit function, 278  
attaching a shared library, 48,  
126, 315  
linking with CC command, 41,  
link-edit phase, 38  
linker interface, 42  
naming the a.out file (-o), 55  
optimization levels and PBO,  
285  
140  
shared library, explicit loading,  
215, 240  
shared library, explicit  
unloading, 238  
B
optimizing using PBO data  
(+P), 283  
-B bind linker option, 49, 58, 60  
-b linker option, 82, 139, 271  
basic block, 274, 315  
BIND_BREADTH_FIRST flag to  
shl_load, 222  
CC command for linking C++  
programs, 41, 140  
changes  
overview, 36  
-p option, 291  
future release, 32  
phases, 38, 315  
changing a shared library, 144  
chatr command, 84, 104  
child process, 315  
position-independent code (+z  
and +Z), 138  
BIND_DEFERRED flag to  
shl_load, 215  
profile-based optimization,  
274, 292  
BIND_FIRST flag to shl_load,  
59, 143, 220  
chmod and shared library  
performance, 148  
-S option, 291  
BIND_IMMEDIATE flag to  
shl_load, 215  
chroot command and shared  
libraries, 161  
-s option, 291  
specifying libraries (-l), 55  
suppressing link-edit phase (-  
c), 55  
BIND_NOSTART flag to  
shl_load, 221  
code generation, 277, 279, 315  
code symbol, 28  
BIND_RESTRICTED flag to  
shl_load, 221  
compatibility mode, 90  
compatibility warnings, 99  
compiler  
verbose output (-v), 38, 54  
-Wl option, 53  
BIND_TOGETHER flag to  
shl_load, 221  
-y option, 291  
+df option, 282, 284  
+I option, 277, 278  
+o option, 291  
complete executable, 122, 316  
BIND_VERBOSE flag to  
shl_load, 220  
crt0.o  
32-bit mode link, 57  
64-bit mode link, 98  
crt0.o startup file, 43, 55, 277,  
322  
binding, 48, 122, 262, 315  
deferred, 49, 104, 126, 316  
immediate, 58, 104, 126, 318  
nonfatal, 59, 104, 320  
+P option, 283  
+y option, 291  
+z and +Z options, 138, 262  
-c option, 55  
cxxdl.h header file, 199  
326  
Index  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
cxxshl_load function for C++,  
driver, 38, 316  
file  
215  
DT_NEEDED entry, 176  
dyn_load function, 72, 74, 75, 78  
dynamic library search, 84, 104,  
144, 145  
descriptor, 317  
cxxshl_unload function for C++,  
lock file, 282, 319  
filehdr.h header file, 67  
filters, 317  
238  
-dynamic linker option, 25, 93  
dynamic linking, 65, 93, 271,  
316  
fini, 202  
D
fini pragma, 202  
-D linker option, 271  
data copy elimination in shared  
libraries, 126  
flow.data file, 280, 284  
empty, 280  
dynamic loader, 48, 126, 262,  
316  
location, 284  
data export symbol, 316  
data linkage table, 262, 316  
data references, optimizing, 270  
data segment, 316  
stack usage problems, 160  
dynamic path searching, 178,  
317  
lock file (flow.lock), 282  
renaming with +df, 282, 284  
sharing among processes, 282  
storing data for multiple  
programs, 281  
DYNAMIC_PATH flag to  
shl_load, 221  
data symbol, 28  
dead procedure elimination,  
270, 271  
dynprog program, 70  
writing with _write_counters(),  
280  
debugging optimized code, 286  
debugging shared libraries, 130,  
161  
flow.lock file, 282  
E
FLOW_DATA environment  
variable, 284  
-E linker option, 81, 84  
-e linker option, 66  
default libraries, 46  
default mapfile, 298, 301  
deferred binding, 49, 104, 126,  
316  
DEMAND_MAGIC, 28, 44  
demand-loaded executable, 316  
dependency, shared library, 140,  
316  
flush, 317  
ELF object file format, 24, 111  
elfdump command, 24, 111  
entry point, 43, 317  
flush_cache function, 68, 78  
fork function and profile-based  
optimization, 282  
environment variables, 96  
exec function, 48  
G
EXEC_MAGIC, 28, 44  
explicit loading, 215, 240, 317  
export stub, 263, 317  
-G compiler option, 291  
-g compiler option, 291  
-G linker option, 290  
gcrt0.o startup file, 43  
global data symbols, 181  
global definition, 40, 317  
gprof profiler, 130  
dependent library, 30, 140, 316  
depth-first search order, 182,  
203, 316  
export symbol, 233, 317  
exporting main program symbols  
(-E), 81, 84, 317  
descriptor, file, 317  
dl* family summary, 197  
dl.h header file, 199  
dlclose function, 253  
dlerror function, 244  
dlget function, 248  
exporting shared library symbols  
(+e), 79, 84, 146, 317  
external reference, 40, 317  
graphics library, 163  
F
H
dlgetname function, 252  
dll, 176  
fastbind, 293  
-h linker option, 81, 84, 146  
handle, shared library, 217, 321  
hard links to shared libraries,  
152  
header file  
aouthdr.h, 67  
fastbind command, 118  
dlmodinfo function, 249  
dlopen family summary, 197  
dlopen function, 240  
dlsym function, 245  
-fbverbose to _HP_DLDOPTS,  
294  
feedback-directed positioning,  
317  
Index  
327  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
cxxdl.h, 199  
declaring, 203  
+b option, 176, 178  
+b path_list option, 84, 104,  
145  
dl.h, 199, 215, 223, 233  
errno.h, 199, 217, 224  
filehdr.h, 67  
fini, 202  
for shared libraries, 201, 210  
HP-UX 10.X, 201  
+compat option, 90  
+df option, 282, 284  
+e option, 79, 84, 146  
+ee option, 81  
header string, 132, 318  
header structure, 67  
ordering, 212, 213  
HP-UX 10.X style, 201, 203,  
hiding shared library symbols (-  
h), 81, 82, 84, 146, 318  
high-level optimization, 289  
HP_SHLIB_VERSION pragma,  
28, 99, 155  
init,221002  
+fini option, 202  
init/fini, 202  
+hideallsymbols option, 95  
+I option, 203  
example, 211  
ordering, 212  
+init option, 202  
HP-UX 10.X initializers, 201  
HP-UX Reference, 162  
style, 210  
+noallowunsats option, 94  
+nodefaultmap option, 95,  
296, 298  
init/fini style, 201  
multiple, 203, 204  
order of execution, 204  
ordering  
+noenvvar option, 96  
+noforceload option, 93  
+nosectionmerge option, 290  
+pd option, 273  
I
-I linker option, 277, 278  
icrt0.o startup file, 277, 278  
immediate binding, 58, 104,  
126, 318  
executable, 212, 213  
shared library, 212, 213  
syntax, 204  
+pgm option, 285  
inlining, 289  
+pi option, 273  
implicit address dependency,  
159, 318  
instrumenting for PBO with +I  
and -I, 277, 278  
+s option, 86, 104, 145, 178  
+std option, 90, 91  
+stripunwind option, 96  
+vtype option, 97  
implicit loading, 318  
import stub, 263, 318  
import symbol, 318  
importing main program  
symbols, 81, 84  
intermediate code, 277, 318  
internal assembler pseudo-op,  
160  
64-bit mode options, 25  
-A option, 65, 271, 290  
-a search option, 63  
a.out file permissions, 45  
archive libraries, selecting (-a),  
63  
internal name, 176  
internal name of shared library,  
152  
incompatible changes to a shared  
library, 144  
intra-library versioning, 28, 154  
Invalid loader fixup needed  
message, 148  
incomplete executable, 122, 126,  
318  
archive libraries, selecting (-l  
), 88  
indirect addressing, 262, 318  
I-SOM file, 277, 318  
and PBO, 290  
init, 202  
-B bind option, 49  
init pragma, 202  
-b option, 139, 271  
binding, choosing (-B), 49  
-c option, 86  
init/fini  
K
example, 211  
init/fini initializers, 202  
initializer, 318  
-k linker option, 25, 95, 296, 298  
C++ programs, linking, 41, 140  
code generation, 279  
combining object files into one  
(-r), 80, 83, 271, 290  
compiler interface, 38, 42  
-D option, 271  
+I linker option, 203  
32-bit mode, 203  
L
-L dir linker option, 47, 57  
-l linker option, 88  
-l option, 55, 87  
ld  
64-bit mode, 210  
example, 211  
accessing addresses, 205  
328  
Index  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
data segment, placing after  
libraries, specifying (-l), 55, 87  
library basename, specifying (-l  
), 88  
SHLIB_PATH environment  
variable, 86, 104, 145  
symbol table information,  
stripping (-s, -x), 89, 290  
unshared executables (-N), 290  
verbose output (-v), 54  
-x option, 89  
text (-N), 66  
data space offset, setting (-D),  
271  
library search path,  
augmenting (-L), 47, 53  
library search path, overriding  
(LPATH), 47, 57  
DEMAND_MAGIC magic  
number (-q), 45  
duplicate symbol definitions,  
47  
link order, 47, 88, 147, 158  
link-edit phase, 38  
link-edit phase, suppressing,  
55  
ld options  
dynamic library search of  
SHLIB_PATH, enabling  
(+s), 86, 104, 145  
64-bit mode, 25  
LD_LIBRARY_PATH  
environment variable, 96,  
178  
dynamic library search path,  
specifying (+b), 84, 104,  
145  
magic number, 44  
-N option, 45, 290  
-n option, 45  
ldd command, 113  
LDOPTS environment variable,  
dynamic linking (-A), 65, 271,  
-noshared option, 93  
-O optimization option, 270  
-o option, 55  
290  
libc,81763  
dynamic linking (-R), 65, 316  
-dynamic option, 93  
-E option, 81, 84  
libelf(3x) routines, 24  
libm, libM libraries, 163  
library, 46, 318  
optimization, 270  
optimizing using PBO data (-  
P), 283  
-e option, 66  
archive, 122, 124, 315  
default, 46  
entry point, specifying (-e), 66  
EXEC_MAGIC magic number  
(-N), 45  
option file (-c), 86  
output file (-o), 55  
-P option, 283  
dependent, 140, 316  
intra-library versioning, 28  
location, 127, 136  
exporting main program  
symbols (-E), 81, 84  
exporting shared library  
symbols (+e), 79, 84, 146  
flow.data file, specifying with  
+df, 282, 284  
performance with PBO, 279,  
290  
naming conventions, 46  
search path, augmenting (-L),  
47, 53, 57  
profiling (-G), 290  
program name for PBO,  
changing (+pgm), 285  
-q option, 45  
search path, overriding  
(LPATH), 47, 57  
FLOW_DATA environment  
variable, 284  
-R offset option, 65, 316  
-r option, 80, 83, 271, 290  
relocation, 42  
searching of shared libraries,  
30  
-G option, 290  
shared, 122, 124, 321  
specifying with -l, 55, 87  
supporting, 140, 322  
system, 162  
-h option, 81, 84, 146  
hiding shared library symbols  
(-h), 81, 84, 146  
resolution rules, 158  
-s option, 89, 290  
SHARE_MAGIC magic  
number (-n), 45  
-I option, 277, 278  
instrumenting for PBO with -I,  
277, 278  
version control, shared library,  
149, 157  
shared libraries, building (-b),  
139, 271  
wrapper, 159, 323  
-k option, 95, 296, 298  
-L dir option, 47, 53, 57  
-l option, 55, 87, 88  
LDOPTS environment  
variable, 87  
shared libraries, selecting (-a),  
library dependencies, 113  
library-level versioning, 150  
link order, 47, 88, 147, 158, 319  
linkage table, 122, 126, 262, 319  
63  
shared libraries, selecting (-l  
), 88  
shared libraries, updating, 144 link-edit phase, 38, 319  
Index  
329  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
suppressing, 55  
linker  
math library (libm, libM), 163  
mcrt0.o startup file, 43  
mixed mode shared library, 184  
mixing shared and archive  
libraries, 164  
online help, 33  
optimization  
compatibility features, 23  
+Olevel compiler option, 285  
compiler optimization level  
and PBO, 285  
options  
64-bit mode, 25, 90  
SVR4-compliant features, 23  
linker tool summary, 103  
linker toolset  
example using shl_load(3X),  
data references, 270  
dead procedure elimination,  
270  
167  
example with hidden  
definitions, 171  
unsupported features, 28  
linking C++ programs, 41, 140  
links with ln(1) to shared  
libraries, 152  
level 1 through level 4, 285  
profile-based optimization,  
274, 292  
potential problems, 164  
unsatisfied symbol example,  
164  
unused procedure elimination,  
link-time behavior changes, 28  
load graph, shared library, 141  
loading a shared library, 126,  
215, 240  
model command, 22  
moving shared libraries after  
linking, 84, 104, 158  
271  
using PBO data (+P/-P), 283  
P
local definition, 40, 319  
lock file, 282, 319  
N
-p compiler option, 291  
-P linker option, 283  
parent process, 320  
PA-RISC 2.0 object files, 21, 99  
PBO_PGM_PATH environment  
variable, 281  
-n linker option, 28, 45  
-N option, 45, 66, 290  
naming libraries, 46  
nlist function, 68  
lorder command, 147  
LPATH environment variable,  
47, 57  
nm command, 107  
M
and PBO, 291  
PC-relative addressing, 262, 320  
magic number, 44  
nonfatal binding, 59, 104, 320  
-noshared linker option, 25, 93  
performance  
malloc() and PBO, 288  
man page, 162, 319  
mapfile, 95, 295, 296, 319  
default, 298, 301  
shared library, 60, 145  
permissions  
a.out executable file, 45  
shared library, 148  
phases  
O
-o compiler/linker option, 55  
-O linker option, 270  
object code  
entrance criteria, 307  
internal structure, 309  
section mapping directive, 307,  
321  
compiler, 38, 315  
physical address, 261, 320  
pipe, 320  
absolute, 261  
position-independent, 262  
relocatable, 260  
segment  
plabel and PIC, 268  
position-independent code, 262,  
263, 268, 320  
mapping sections, 309  
segment declaration, 304, 321  
segment placement, 309  
mapfile directive, 296  
default, 312  
object file, 320  
external reference, 40  
global definition, 40  
local definition, 40  
symbol name, 40, 322  
symbol table, 40, 322  
symbol types, 109  
assembly language, 264  
creating, 122, 138  
POSIX  
section mapping directive, 303  
segment declaration, 303  
user-defined, 312  
math library (libM), 163  
pragma, 320  
"fini", 202  
using nm to view symbols, 107  
object module, 132, 320  
mapfile linker option, 25  
"init", 202  
330  
Index  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
HP_SHLIB_VERSION  
malloc(), 288  
RPATH, 321  
pragma, 28  
nm command, 291  
optimization levels, selecting,  
285  
run-time behavior changes, 30  
run-time path environment  
variables, 30  
SHLIB_VERSION pragma, 28  
procedure labels and PIC, 268  
procedure linkage table, 262,  
320  
optimizing with +P and -P, 283  
overview, 274  
S
process ID, 320  
PBO_PGM_PATH  
-S compiler option, 291  
-s compiler option, 291  
-S linker option, 28  
prof profiler, 130  
environment variable, 281  
profile data file, 280, 284  
profile data for multiple  
programs, 281  
profile-based optimization, 274,  
292, 321  
-s linker option, 89, 290  
scrt0.o startup file, 43, 277  
search order for shared library  
symbols, 143  
+df option, 282, 284  
+I and -I options, 277, 278  
+P and -P options, 283  
_clear_counters function, 282  
-A linker option, 290  
ar command, 291  
profiling phase, 279  
program name, changing  
(+pgm), 285  
search path  
-r linker option, 287, 290  
restrictions, 288  
dynamic, 317  
section mapping directive, 303,  
307, 321  
atexit function, 278  
-s linker option, 290  
scrt0.o startup file, 277  
shared library optimization,  
286  
-b linker option, 286  
basic block, 274, 315  
code generation, 279  
compatibility with 9.0, 291  
compiler incompatibilities, 291  
crt0.o startup file, 277, 278  
disk space usage, 288  
empty flow.data file, 280  
example, 276  
segment, 95, 309, 321  
segment declaration, 303, 304,  
321  
source code changes, 288  
strip command, 291  
temporary files, 288  
when to use, 275  
SHARE_MAGIC, 28, 44  
shared executable, 321  
shared library, 321  
+h option, 152  
profiling  
accessing explicitly loaded  
routines and data, 222  
attaching, 48, 126, 315  
binding, 48, 122, 126, 315  
compared with archive, 122,  
124  
data file for PBO, 280, 284  
phase of PBO, 279  
search path, 47  
flow.data file, 280, 284  
flow.data file, renaming with  
+df, 282, 284  
shared libraries, 130, 161  
program start-up, 118  
FLOW_DATA environment  
variable, 284  
compatibility mode, 176  
forking an instrumented  
application, 282  
Q
creating, 139  
-Q linker option, 28  
cxxdl.h header file, 199  
data copy eliminated, 126  
data linkage table, 262, 316  
debugging, 130, 161  
deferred binding, 49, 104, 126  
definition of, 126, 129  
dependency, 140, 316  
dependent library, 140, 316  
dl.h header file, 199  
-G linker option, 290  
high-level optimization,  
interaction with, 289  
icrt0.o startup file, 277, 278  
instrumenting with +I and -I,  
277, 278  
-q linker option, 28, 45  
R
-r linker option, 83, 271, 290  
C++ limitation, 288  
profile-based optimization, 287  
relocatable object code, 260, 321  
relocation, 42, 321  
I-SOM file restrictions, 290  
limitations, 288  
linker performance, 279, 290  
lock file, 282  
restricted binding, 59, 104, 321  
Index  
331  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
dynamic library search, 144,  
145  
naming, 46, 122, 139  
new versions, 156  
BIND_BREADTH_FIRST flag,  
222  
BIND_DEFERRED flag, 215  
BIND_FIRST flag, 59, 143,  
220  
BIND_IMMEDIATE flag, 215  
BIND_NONFATAL flag, 220  
BIND_NOSTART flag, 221  
BIND_RESTRICTED flag, 221  
BIND_TOGETHER flag, 221  
BIND_VERBOSE flag, 220  
DYNAMIC_PATH flag, 221  
library-level versioning, 154  
shl_load routine  
dynamic loader, 48, 126, 262,  
nonfatal binding, 59, 104, 320  
performance, 60, 145  
permissions, 148  
316  
dynamic loader stack usage  
problems, 160  
position-independent code, 138  
procedure linkage table, 262,  
320  
explicit loading, 215, 240, 317  
explicit unloading, 238  
exporting symbols, 79, 82, 84,  
146, 317  
profile-based optimization, 286  
profiling, 130, 161  
file system links, 152  
handle, 217, 321  
restricted binding, 59, 104,  
321  
hiding symbols, 81, 82, 84,  
146, 318  
search list, 143  
search order  
immediate binding, 58, 104,  
breadth-first, 315  
with cc options, 200  
126  
depth-first, 316  
with ld options, 200  
importing main program  
symbols, 81, 84  
selecting at link time, 63  
standard mode, 176  
supporting library, 140, 322  
symbol binding, 178  
symbolic links, 152  
shl_load symbol structure to  
shl_getsymbols, 235  
incomplete executable, 126,  
shl_t type, 217  
318  
shl_unload function, 238  
SHLIB_FLOW_DATA  
environment variable, 286  
SHLIB_PATH environment  
variable, 86, 104, 145, 178  
SHLIB_VERSION directive, 99,  
155  
initializer, 201, 210  
ordering, 212, 213  
initializer style  
terminator, 201  
unsatisfied references, 180  
updating, 144  
HP-UX 10.X, 201  
init/fini, 201  
using chroot during  
development, 161  
internal name (+h), 152  
intra-library versioning, 154  
library-level versioning, 150  
linkage table, 122, 126, 262,  
319  
version control, 149, 157  
version date format, 157  
version number, 155, 323  
virtual memory usage, 128,  
129  
SHLIB_VERSION pragma, 28  
size command, 115  
som_exec_auxhdr structure, 67  
stack usage and the dynamic  
loader, 160  
linking, 93  
links with ln(1), 152  
link-time symbol resolution,  
178  
shl_definesym function, 60, 231  
shl_findsym function, 222  
shl_get function, 226  
shl_get_r thread-safe function,  
226  
standard error, 321  
standard I/O library, 163, 322  
standard input, 321  
load graph, 141  
standard mode, 90  
loading routines, 126  
location, 127, 144, 158  
management, 199, 239  
migrating to, 158, 161  
mixed mode, 184  
standard output, 322  
startup file, 43, 277, 322  
storage export symbol, 322  
stream, 322  
shl_gethandle function, 230  
shl_gethandle_r thread-safe  
function, 230  
shl_getsymbols function, 232  
shl_load family summary, 196  
shl_load function, 59, 215  
strip command, 89, 116  
and PBO, 291  
mixing with archive libraries,  
164  
stub, 322  
moving, 84, 104, 158  
332  
Index  
Download from Www.Somanuals.com. All Manuals Search And Download.  
In d ex  
suffix for shared and archive  
umask command, 45, 323  
unloading a shared library, 238  
unused procedure elimination,  
270, 271  
libraries, 46  
supporting library, 140, 322  
SVID math library (libm), 163  
symbol  
unwind table, 96  
code, duplicate, 28  
updating a shared library, 144  
data, duplicate, 28  
hiding, 95  
V
linker-defined, 26  
-v compiler/linker option, 38, 54  
version control, shared library,  
149, 157  
searching dependent libraries,  
182  
unsatisfied, 94  
+h option, 152  
symbol binding semantics, 178  
symbol name, 40, 99, 322  
symbol searching of dependent  
libraries, 30  
date format, 157  
intra-library versioning, 154  
library-level versioning, 150  
version number, 155, 323  
virtual address dependency, 159  
virtual memory usage and  
shared libraries, 128, 129  
symbol table, 116  
archive library, 132, 322  
object file, 40, 322  
stripping from a.out file, 89  
symbol type, 109  
W
symbol, duplicate definitions, 47  
symbolic links to shared  
libraries, 152  
warnings for compatibility, 99  
where to put archive libraries,  
136  
system call, 162, 322  
system libraries, 162  
location, 136, 144  
where to put shared libraries,  
144  
-Wl compiler option, 53, 54  
wrapper library, 159, 323  
write permissions and shared  
library performance, 148  
T
-T linker option, 28  
temporary files and PBO, 288  
terminators  
X
for shared library, 201  
text segment, 323  
-x linker option, 89  
threads programming  
shl_get_r function, 226  
shl_gethandle_r function, 230  
thread-safe support in linker, 50  
tsort command, 147  
Y
-y compiler option, 291  
U
ucomp code generator, 279  
Index  
333  
Download from Www.Somanuals.com. All Manuals Search And Download.  

Invacare High Chair 1108526 User Manual
Invacare Mobility Aid 1081003 User Manual
JBL Portable Speaker 1X 1Xtreme One User Manual
John Deere Impact Driver AT 3203 J User Manual
John Lewis Beverage Dispenser JLWFF1552 User Manual
Jura Capresso Espresso Maker 65349R3 User Manual
JVC Car Stereo System GET0467 001A User Manual
Karcher Water System 600 CD User Manual
Kenwood Car Speaker KFC 1023C User Manual
Kenwood Stereo System VR 9070 User Manual