283
2550 Garcia Avenue Mountain View, CA 94043 U.S.A. Linker and Libraries Guide A Sun Microsystems, Inc. Business

Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

  • Upload
    others

  • View
    17

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

2550 Garcia AvenueMountain View, CA 94043U.S.A.

Linker and Libraries Guide

A Sun Microsystems, Inc. Business

Page 2: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

PleaseRecycle

1995 Sun Microsystems, Inc. 2550 Garcia Avenue, Mountain View, California 94043-1100 U.S.A.

All rights reserved. This product or document is protected by copyright and distributed under licenses restricting its use,copying, distribution, and decompilation. No part of this product or document may be reproduced in any form by any meanswithout prior written authorization of Sun and its licensors, if any.

Portions of this product may be derived from the UNIX® system, licensed from UNIX System Laboratories, Inc., a wholly ownedsubsidiary of Novell, Inc., and from the Berkeley 4.3 BSD system, licensed from the University of California. Third-partysoftware, including font technology in this product, is protected by copyright and licensed from Sun’s suppliers.

RESTRICTED RIGHTS LEGEND: Use, duplication, or disclosure by the government is subject to restrictions as set forth insubparagraph (c)(1)(ii) of the Rights in Technical Data and Computer Software clause at DFARS 252.227-7013 and FAR 52.227-19.The product described in this manual may be protected by one or more U.S. patents, foreign patents, or pending applications.

TRADEMARKSSun, Sun Microsystems, the Sun logo, SunSoft, the SunSoft logo, Solaris, SunOS, OpenWindows, DeskSet, ONC, ONC+, and NFSare trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. UNIX is a registeredtrademark in the United States and other countries, exclusively licensed through X/Open Company, Ltd. OPEN LOOK is aregistered trademark of Novell, Inc. PostScript and Display PostScript are trademarks of Adobe Systems, Inc. The PowerPCname is a trademark of International Business Machines Corporation.

All SPARC trademarks are trademarks or registered trademarks of SPARC International, Inc. in the United States and othercountries. SPARCcenter, SPARCcluster, SPARCompiler, SPARCdesign, SPARC811, SPARCengine, SPARCprinter, SPARCserver,SPARCstation, SPARCstorage, SPARCworks, microSPARC, microSPARC-II, and UltraSPARC are licensed exclusively to SunMicrosystems, Inc. Products bearing SPARC trademarks are based upon an architecture developed by Sun Microsystems, Inc.

The OPEN LOOK® and Sun™ Graphical User Interfaces were developed by Sun Microsystems, Inc. for its users and licensees.Sun acknowledges the pioneering efforts of Xerox in researching and developing the concept of visual or graphical userinterfaces for the computer industry. Sun holds a non-exclusive license from Xerox to the Xerox Graphical User Interface, whichlicense also covers Sun’s licensees who implement OPEN LOOK GUIs and otherwise comply with Sun’s written licenseagreements.

X Window System is a trademark of X Consortium, Inc.

THIS PUBLICATION IS PROVIDED “AS IS” WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED,INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR APARTICULAR PURPOSE, OR NON-INFRINGEMENT.

THIS PUBLICATION COULD INCLUDE TECHNICAL INACCURACIES OR TYPOGRAPHICAL ERRORS. CHANGES AREPERIODICALLY ADDED TO THE INFORMATION HEREIN. THESE CHANGES WILL BE INCORPORATED IN NEWEDITIONS OF THE PUBLICATION. SUN MICROSYSTEMS, INC. MAY MAKE IMPROVEMENTS AND/OR CHANGES INTHE PRODUCT(S) AND/OR THE PROGRAMS(S) DESCRIBED IN THIS PUBLICATION AT ANY TIME.

Page 3: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

iii

Contents

Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

1. Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Link-Editing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2

Runtime Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Dynamic Executables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Shared Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Related Topics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Dynamic Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4

Application Binary Interfaces. . . . . . . . . . . . . . . . . . . . . . . . . 5

Support Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2. Link-Editor. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

Invoking the Link-Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

Direct Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Using a Compiler Driver . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9

Page 4: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

iv Linker and Libraries Guide—November 1995

Specifying the Link-Editor Options. . . . . . . . . . . . . . . . . . . . . . . 10

Input File Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Archive Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Shared Object Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

Linking with Additional Libraries. . . . . . . . . . . . . . . . . . . . . 14

Initialization and Termination Sections . . . . . . . . . . . . . . . . 19

Symbol Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Symbol Resolution. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Undefined Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

Tentative Symbol Order Within the Output File . . . . . . . . . 31

Defining Additional Symbols. . . . . . . . . . . . . . . . . . . . . . . . . 32

Reducing Symbol Scope . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 37

Generating the Output Image . . . . . . . . . . . . . . . . . . . . . . . . . . . 42

Link-Editor Support Interface . . . . . . . . . . . . . . . . . . . . . . . . . . . 43

Invoking the Support Interface . . . . . . . . . . . . . . . . . . . . . . . 43

Support Interface Functions . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Support Interface Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 46

Debugging Aids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

3. Runtime Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Locating Shared Object Dependencies . . . . . . . . . . . . . . . . . . . . 54

Directories Searched by the Runtime Linker . . . . . . . . . . . . 55

Relocation Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

Symbol Lookup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Page 5: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Contents v

When Relocations are Performed . . . . . . . . . . . . . . . . . . . . . 60

Relocation Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61

Loading Additional Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62

Initialization and Termination Routines . . . . . . . . . . . . . . . . . . . 64

Security . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64

Runtime Linking Programming Interface. . . . . . . . . . . . . . . . . . 65

Loading Additional Objects . . . . . . . . . . . . . . . . . . . . . . . . . . 67

Relocation Processing . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 69

Obtaining New Symbols. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 73

Debugging Aids . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

4. Shared Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83

Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84

Recording a Shared Object Name . . . . . . . . . . . . . . . . . . . . . 86

Shared Objects with Dependencies . . . . . . . . . . . . . . . . . . . . . . . 89

Dependency Ordering. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Shared Objects as Filters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

Generating a Standard Filter . . . . . . . . . . . . . . . . . . . . . . . . . 92

Generating an Auxiliary Filter . . . . . . . . . . . . . . . . . . . . . . . . 95

Performance Considerations . . . . . . . . . . . . . . . . . . . . . . . . . . . . 96

Useful Tools . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

The Underlying System . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100

Position-Independent Code . . . . . . . . . . . . . . . . . . . . . . . . . . 100

Maximizing Shareability. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

Page 6: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

vi Linker and Libraries Guide—November 1995

Minimizing Paging Activity . . . . . . . . . . . . . . . . . . . . . . . . . . 105

Relocations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

Profiling Shared Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111

5. Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

Overview. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 115

Interface Compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116

Internal Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

Creating a Version Definition . . . . . . . . . . . . . . . . . . . . . . . . . 118

Binding to a Version Definition . . . . . . . . . . . . . . . . . . . . . . . 126

Specifying a Version Binding . . . . . . . . . . . . . . . . . . . . . . . . . 132

Relocatable Objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

External Versioning . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135

Coordination of Versioned Filenames . . . . . . . . . . . . . . . . . . 136

6. Object Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

ELF Header. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142

ELF Identification . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

Special Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

String Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

Symbol Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

Relocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 167

Page 7: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Contents vii

Versioning Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 181

Note Section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Dynamic Linking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Program Header . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189

Program Loading (Processor-Specific) . . . . . . . . . . . . . . . . 195

Runtime Linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

Hash Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

Initialization and Termination Functions . . . . . . . . . . . . . . . 225

7. Mapfile Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227

Using the Mapfile Option . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

Mapfile Structure and Syntax . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

Segment Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229

Mapping Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

Size-Symbol Declarations . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

File Control Directives . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

Mapping Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 236

Mapfile Option Defaults . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Internal Map Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240

Error Messages . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Fatal Errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 244

A. Link-Editor Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

Static Mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

Page 8: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

viii Linker and Libraries Guide—November 1995

Building a Relocatable Object. . . . . . . . . . . . . . . . . . . . . . . . . 246

Building a Static Executable . . . . . . . . . . . . . . . . . . . . . . . . . . 246

Dynamic Mode. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

Building a Shared Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . 246

Building a Dynamic Executable. . . . . . . . . . . . . . . . . . . . . . . 248

B. Versioning Quick Reference . . . . . . . . . . . . . . . . . . . . . . . . . . . . 249

Naming Conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

Defining a Shared Object’s Interface . . . . . . . . . . . . . . . . . . . . . . 251

Versioning a Shared Object . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

Versioning an Existing (Non-versioned) Shared Object . . . 253

Updating a Versioned Shared Object. . . . . . . . . . . . . . . . . . . . . . 253

Adding New Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 254

Internal Implementation Changes. . . . . . . . . . . . . . . . . . . . . 255

New Symbols and Internal Implementation Changes . . . . 255

Migrating Symbols to a Standard Interface . . . . . . . . . . . . . 256

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 261

Page 9: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

ix

Figures

Figure 1-1 Static or Dynamic Link-editing . . . . . . . . . . . . . . . . . . . . . . . . . . 3

Figure 3-1 A Single dlopen(3X) Request . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70

Figure 3-2 Multiple dlopen(3X) Requests . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Figure 3-3 Multiple dlopen(3X) Requests With A Common Dependency 72

Figure 6-1 Object File Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 140

Figure 6-2 Data Encoding ELFDATA2LSB . . . . . . . . . . . . . . . . . . . . . . . . . . 148

Figure 6-3 Data Encoding ELFDATA2MSB . . . . . . . . . . . . . . . . . . . . . . . . . 148

Figure 6-4 String Table. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

Figure 6-5 Note Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187

Figure 6-6 Example Note Segment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 188

Figure 6-13 Symbol Hash Table . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 224

Figure 7-1 Simple Map Structure . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241

Page 10: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

x Linker and Libraries Guide—November 1995

Page 11: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

xi

Tables

Table 6-1 32-Bit Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

Table 6-2 ELF File Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Table 6-3 ELF Machines. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 143

Table 6-4 ELF Versions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144

Table 6-5 e_ident[ ] Identification Index . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Table 6-6 Magic Number . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 146

Table 6-7 File Class . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Table 6-8 Data Encoding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147

Table 6-9 Special Section Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

Table 6-10 Section Types, sh_type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

Table 6-11 Section Header Table Entry: Index 0 . . . . . . . . . . . . . . . . . . . . . 155

Table 6-12 Section Attribute Flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155

Table 6-13 sh_link and sh_info Interpretation . . . . . . . . . . . . . . . . . . . . . . . 156

Table 6-14 Special Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

Table 6-15 String Table Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 161

Table 6-16 Symbol Table Initial Entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162

Page 12: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

xii Linker and Libraries Guide—November 1995

Table 6-17 Symbol Binding, ELF32_ST_BIND . . . . . . . . . . . . . . . . . . . . . . . 163

Table 6-18 Symbol Types, ELF32_ST_TYPE . . . . . . . . . . . . . . . . . . . . . . . . . 165

Table 6-19 Symbol Table Entry: Index 0 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 166

Table 6-20 SPARC Relocation Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 173

Table 6-21 x86 Relocation Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 176

Table 6-22 Relocation Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 178

Table 6-25 Version Dependency Indexes . . . . . . . . . . . . . . . . . . . . . . . . . . . 184

Table 6-28 Segment Types, p_type. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191

Table 6-29 Segment Flag Bits, p_flags . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193

Table 6-30 Segment Permissions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 194

Table 6-34 Example SPARC Shared Object Segment Addresses. . . . . . . . 203

Table 6-35 Example x86 Shared Object Segment Addresses . . . . . . . . . . . 203

Table 6-36 Dynamic Array Tags, d_tag . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208

Table 7-1 Mapfile Segment Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 230

Table 7-2 Section Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 234

Page 13: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

xiii

Preface

Solaris™ provides an environment in which application developers can buildapplications and libraries using the link-editor ld(1) , and execute theseutilities with the aid of the runtime linker ld.so.1 . For many applicationdevelopers, the fact that the link-editor is called via the compilation system,and that the runtime linker may play a part in the execution of theirapplication, is mildly interesting. This manual is for those who wish tounderstand more fully the concepts involved.

About This ManualThis manual describes the operations of the Solaris link-editor and runtimelinker. Special emphasis is placed on the generation and use of shared objectsbecause of their importance in a dynamic runtime environment.

Intended Audience

This manual is intended for a range of programmers who are interested in theSolaris linkers, from the curious beginner to the advanced user:

• Beginners learn the principle operations of the link-editor and runtimelinker.

• Intermediate programmers learn to build, and use, efficient custom libraries.

• Advanced programmers, such as language-tools developers, learn how tointerpret and generate object files.

Page 14: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

xiv Linker and Libraries Guide—November 1995

Not many programmers should find it necessary to read this manual fromcover to cover.

Organization

Chapter 1, “Introduction”, gives an overview of the linking processes underSolaris. This chapter is intended for all programmers.

Chapter 2, “Link-Editor”, describes the functions of the link-editor, its twomodes of linking (static and dynamic), scope and forms of input, and forms ofoutput. This chapter is intended for all programmers.

Chapter 3, “Runtime Linker”, describes the execution environment andprogram-controlled runtime binding of code and data. This chapter is intendedfor all programmers.

Chapter 4, “Shared Objects”, gives definitions of shared objects, describes theirmechanisms, and explains how to build and use them. This chapter is intendedfor all programmers.

Chapter 5, “Versioning”, describes how to manage the evolution of an interfaceprovided by a dynamic object.

Chapter 6, “Object Files”, is a reference chapter on ELF files. This chapter isintended for advanced programmers.

Chapter 7, “Mapfile Option”, describes the mapfile directives to the linker,which specify the layout of the output file. This chapter is intended foradvanced programmers.

Appendix A, “Link-Editor Quick Reference”, gives an overview of the mostcommonly used link-editor options, and is intended for all programmers.

Appendix B, “Versioning Quick Reference”, gives naming conventions andguidelines for versioning shared objects, and is intended for all programmers.

Throughout this document, all command-line examples use sh(1) syntax, andall programming examples are written in the C language.

Page 15: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

1

Introduction 1

This manual describes the operations of the Solaris link-editor and runtimelinker, together with the objects on which they operate. The basic operation ofthe Solaris linkers involves the combination of objects and the connection ofsymbolic references from one object to the symbolic definitions within another.This operation is often referred to as binding.

The main areas this manual expands upon are:

• The Link-Editor

The link-editor, ld(1) , concatenates one or more input files (eitherrelocatable objects, shared objects, or archive libraries) to produce oneoutput file (either a relocatable object, an executable application, or a sharedobject). The link-editor is most commonly invoked as part of thecompilation environment (see cc(1) ).

• The Runtime Linker

The runtime linker, ld.so.1 1, processes dynamic executables and sharedobjects at runtime, and binds them to create a runable process.

1. ld.so.1 is a special case of a shared object and therefore allows itself to be versioned. Here a version numberof 1 is used, however later releases of Solaris might provide higher version numbers.

Page 16: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

2 Linker and Libraries Guide—November 1995

1

• Shared Objects (sometimes referred to as Shared Libraries)

Shared objects are one form of output from the link-edit phase. However,their importance in creating a powerful, flexible runtime environmentwarrants a section of its own.

• Object Files

The Solaris linkers work with files that conform to the executable and linkingformat (ELF).

These areas, although separable into individual topics, have a great deal ofoverlap. While explaining each area, this document brings together theconnecting principles and designs.

Link-EditingLink-editing takes a variety of input files, from cc(1) , as(1) or ld(1) , andconcatenates and interprets the data within these input files to form a singleoutput file. Although the link-editor provides numerous options, the outputfile produced is one of four basic types:

• Relocatable object – a concatenation of input relocatable objects, which can beused in subsequent link-edit phases.

• Static executable – a concatenation of input relocatable objects that has allsymbolic references bound to the executable, and thus represents a ready-to-run process.

• Dynamic executable – a concatenation of input relocatable objects thatrequires intervention by the runtime linker to produce a runable process. Itssymbolic references might still need to be bound at runtime, and it mighthave one or more dependencies in the form of shared objects.

• Shared object – a concatenation of input relocatable objects that providesservices that might be bound to a dynamic executable at runtime. Theshared object might also have dependencies on other shared objects.

These output files, and the key link-editor options used to create them, areshown in Figure 1-1 on page 3.

Dynamic executables and shared objects, are often referred to jointly as dynamicobjects, and are the main focus of this document.

Page 17: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Introduction 3

1

Figure 1-1 Static or Dynamic Link-editing

Runtime LinkingRuntime linking involves the binding of objects, usually generated from one ormore previous link-edits, to generate a runable process. During the generationof these objects by the link-editor, the binding requirements are verified andappropriate bookkeeping information is added to each object to allow theruntime linker to map, relocate, and complete the binding process.

During the execution of the process, the facilities of the runtime linker are alsomade available and can be used to extend the process’ address space by addingadditional shared objects on demand. The two most common componentsinvolved in runtime linking are dynamic executables and shared objects.

Dynamic Executables

Dynamic executables are applications that are executed under the control of aruntime linker. These applications usually have dependencies in the form ofshared objects, which are located and bound by the runtime linker to create arunable process. Dynamic executables are the default output file generated bythe link-editor.

ld

-dn -dy

-r -G

Relocatableobject

Staticexecutable

Dynamicexecutable

Sharedobject

Page 18: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

4 Linker and Libraries Guide—November 1995

1

Shared Objects

Shared objects provide the key building block to a dynamically linked system.Basically, a shared object is similar to a dynamic executable, however sharedobjects usually have no entry point and they have not yet been assigned avirtual address.

Dynamic executables usually have dependencies on one or more sharedobjects. That is, the shared object(s) must be bound to the dynamic executableto produce a runable process. Because shared objects can be used by manyapplications, aspects of their construction directly affect shareability,versioning and performance.

It is useful to distinguish the processing of shared objects by either the link-editor or the runtime linker by referring to the environments in which theshared objects are being used:

• The compilation environment. Here, shared objects are processed by thelink-editor to generate dynamic executables or other shared objects. Theshared objects become dependencies of the output file being generated.

• The runtime environment. Here, shared objects are processed by the runtimelinker, together with a dynamic executable, to produce a runable process.

Related Topics

Dynamic Linking

Dynamic linking is a term often used to embrace those portions of the link-editing process that generate dynamic executables and shared objects, togetherwith the runtime linking of these objects to generate a runable process.Dynamic linking allows multiple applications to use the code provided by ashared object by enabling the application to bind to the shared object atruntime.

By separating an application from the services of standard libraries, dynamiclinking also increases the portability and extensibility of an application. Thisseparation between the interface of a service and its implementation enables thesystem to evolve while maintaining application stability, and is a crucial factorin providing an application binary interface (ABI). Dynamic linking is thepreferred compilation method for Solaris applications.

Page 19: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Introduction 5

1

Application Binary Interfaces

To enable the asynchronous evolution of system and application components,binary interfaces between these facilities are defined. The Solaris linkersoperate upon these interfaces to assemble applications for execution. Althoughall components handled by the Solaris linkers have binary interfaces, onefamily of such interfaces of particular interest to applications writers is theSystem V Application Binary Interface.

The System V Application Binary Interface, or ABI, defines a system interface forcompiled application programs. Its purpose is to document a standard binaryinterface for application programs on systems that implement the System VInterface Definition, Third Edition. Solaris provides for the generation andexecution of ABI-conformant applications. On SPARC systems, the ABI iscontained as a subset of the SPARC® Compliance Definition (SCD).

Many of the topics covered in the following chapters are influenced by the ABI.For more detailed information see the appropriate ABI manuals.

Support Tools

Together with the objects mentioned in the previous sections come severalsupport tools and libraries. These tools provide for the analysis and inspectionof these objects and the linking processes. Among these tools are: nm(1) ,dump(1) , ldd(1) , pvs(1 ), elf(3E) , and a linker debugging support library.Throughout this document many discussions are augmented with examples ofthese tools use.

Page 20: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

6 Linker and Libraries Guide—November 1995

1

Page 21: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

7

Link-Editor 2

OverviewThe link-editing process builds an output file from one or more input files. Thebuilding of the output file is directed by the options supplied to the link-editortogether with the input sections provided by the input files.

All files are represented in the executable and linking format (ELF). For acomplete description of the ELF format see Chapter 6, “Object Files”. For thisintroduction, however, it is first necessary to introduce two ELF structures,sections and segments.

Sections are the smallest indivisible units that can be processed within an ELFfile. Segments are a collection of sections that represent the smallest individualunits that can be mapped to a memory image by exec(2) or by the runtimelinker.

Although there are many types of ELF sections, they all fall into two categorieswith respect to the link-editing phase:

• Sections that contain program data, whose interpretation is meaningful onlyto the application itself (such as the program instructions .text and theassociated data .data and .bss).

• Sections that contain link-editing information (such as the symbol tableinformation found from .symtab and .strtab, and relocation information suchas .rela.text).

Page 22: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

8 Linker and Libraries Guide—November 1995

2

Basically, the link-editor concatenates the program data sections into the outputfile. The link-editing information sections are interpreted by the link-editor tomodify other sections or to generate new output information sections used inlater processing of the output file.

The following simple breakdown of link-editor functionality introduces thetopics covered in this chapter:

• It verifies and checks for consistency all the options passed to it.

• It concatenates sections of the same characteristics (for example, type,attributes and name) from the input relocatable objects to form new sectionswithin the output file. These concatenated sections can in turn be associatedto output segments.

• It reads symbol table information from both relocatable objects and sharedobjects to verify and unite references with definitions, and usually generatesa new symbol table, or tables, within the output file.

• It reads relocation information from the input relocatable objects and appliesthis information to the output file by updating other input sections. Inaddition, output relocation sections might be generated for use by theruntime linker.

• It generates program headers that describe any segments created.

• It generates a dynamic linking information section if necessary, whichprovides information such as shared object dependencies to the runtimelinker.

The process of concatenating like sections and associating sections to segments iscarried out using default information within the link-editor. The default sectionand segment handling provided by the link-editor is usually sufficient for mostlink-edits. However, these defaults can be manipulated using the -M optionwith an associated mapfile (see Chapter 7, “Mapfile Option” for moredetails).

Invoking the Link-EditorYou can either run the link-editor directly from the command-line or have acompiler driver invoke it for you. In the following two sections both methodsare expanded upon. However, the latter is the preferred choice, as thecompilation environment is often the consequence of a complex andoccasionally changing series of operations known only to compiler drivers.

Page 23: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 9

2

Direct Invocation

When you invoke the link-editor directly, you have to supply every object fileand library required to build the intended output. The link-editor makes noassumptions about the object modules or libraries you meant to use in buildingthe output. For example, when you issue the command:

the link-editor builds a dynamic executable named a.out using only the inputfile test.o . For the a.out to be a useful executable, it should include start-upand exit processing code. This code can be language or operating systemspecific, and is usually provided through files supplied by the compilerdrivers.

Additionally, you can also supply your own initialization and terminationcode. This code must be encapsulated and labeled correctly for it to becorrectly recognized and made available to the runtime linker. Thisencapsulation and labeling is also provided through files supplied by thecompiler drivers.

In practice, there is little reason to invoke the link-editor directly.

Using a Compiler Driver

The conventional way to use the link-editor is through a language-specificcompiler driver. You supply the compiler driver,cc(1) , f77(1) , etc., with theinput files that make up your application, and the compiler driver addsadditional files and default libraries to complete the link-edit. These additionalfiles can be seen by expanding the compilation invocation, for example:

$ ld test.o

$ cc -# -o prog main.o/usr/ccs/bin/ld -dy /opt/COMPILER/crti.o /opt/COMPILER/crt1.o \/usr/ccs/lib/values-Xt.o -o prog main.o \-YP,/opt/COMPILER/lib:/usr/ccs/lib:/usr/lib -Qy -lc \/opt/COMPILER/crtn.o

Page 24: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

10 Linker and Libraries Guide—November 1995

2

Note – This is an example; the actual files included by your compiler driverand the mechanism used to display the link-editor invocation might differ.

Specifying the Link-Editor OptionsMost options to the link-editor can be passed through the compiler drivercommand-line. For the most part the compiler and the link-editor options donot conflict. Where a conflict arises, the compiler drivers usually provide acommand-line syntax that allows you to pass specific options to the link-editor.However, you can instead provide options to the link-editor by setting theLD_OPTIONS environment variable. For example:

Here the -R and -L options will be interpreted by the link-editor and prependedto any command-line options received from the compiler driver.

The link-editor parses the entire option list looking for any invalid options orany options with invalid associated arguments. When either of these cases isfound, a suitable error message is generated, and when the error is deemedfatal the link-edit terminates. For example:

Here the illegal option -X is identified, and the illegal argument to the -zoption is caught by the link-editor’s checking. If an option requiring anassociated argument is mistakenly specified twice the link-editor will provide asuitable warning but will continue with the link-edit. For example:

$ LD_OPTIONS=“-R /home/me/libs -L /home/me/libs“ cc -o prog \main.c -lfoo

$ ld -X -z sillydefs main.old: illegal option -- Xld: fatal: option -z has illegal argument ‘sillydefs’

$ ld -e foo ...... -e bar main.old: warning: option -e appears more than once, first setting taken

Page 25: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 11

2

The link-editor also checks the option list for any fatal inconsistences. Forexample:

After processing all options, and if no fatal error conditions have beendetected, the link-editor proceeds to process the input files.

See Appendix A, “Link-Editor Quick Reference” for the most commonly usedlink-editor options, and the ld(1) manual page for a complete description ofall link-editor options.

Input File ProcessingThe link-editor reads input files in the order in which they appear on thecommand-line. Each file is opened and inspected to determine its ELF file typeand so determine how it must be processed. The file types applicable as inputfor the link-edit are determined by the binding mode of the link-edit, eitherstatic or dynamic.

Under static linking the link-editor will accept only relocatable objects orarchive libraries as input files. Under dynamic linking the link-editor will alsoaccept shared objects.

Relocatable objects represent the most basic input file type to the link-editingprocess. The program data sections within these files are concatenated into theoutput file image being generated. The link-edit information sections areorganized for later use, but will not become part of the output file image, asnew sections will be generated to take their places. Symbols are gathered into aspecial internal symbol table that allows for their verification and resolution,and eventually for the creation of one or more symbol tables in the outputimage.

Although any input file can be specified directly on the link-edit command-line, archive libraries and shared objects are commonly specified using the -loption (see “Linking with Additional Libraries” on page 14 for coverage of thismechanism and how it relates to the two different linking modes). However,even though shared objects are often referred to as shared libraries, and both of

$ ld -dy -r main.old: fatal: option -dy and -r are incompatible

Page 26: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

12 Linker and Libraries Guide—November 1995

2

these objects can be specified using the same option, the interpretation ofshared objects and archive libraries is quite different. The next two sectionsexpand upon these differences.

Archive Processing

Archives are built using ar(1) , and usually consist of a collection ofrelocatable objects with an archive symbol table. This symbol table provides anassociation of symbol definitions with the objects that supply these definitions.When the link-editor reads an archive, it uses information within the internalsymbol table it is creating to select only the objects from the archive it requiresto complete the binding process. To be more precise, the link-editor will extracta relocatable object from an archive if:

• The archive contains a symbol definition that satisfies a symbol reference(sometimes referred to as an undefined symbol) presently held in thelink-editor’s internal symbol table, or

• The archive contains a data symbol definition that satisfies a tentative symboldefinition presently held in the link-editor’s internal symbol table. Anexample of this is a FORTRAN COMMON block definition which will causethe extraction of a relocatable object that defines the same DATA symbol.

Note – A weak symbol reference will not cause the extraction of an object froman archive. Weak symbols are expanded upon in section “Simple Resolutions”on page 22.

The link-editor will make multiple passes through an archive extractingrelocatable objects as needed to satisfy the symbol information beingaccumulated in the link-editor internal symbol table. Once the link-editor hasmade a complete pass through the archive without extracting any relocatableobjects, it will move on to process the next input file. This mechanism ofextracting from the archive only the relocatable objects needed at the time thearchive was encountered means that the position of the archive within theinput file list can be significant (see “Position of an Archive on the Command-Line” on page 16 for more details).

Note – Although the link-editor will make multiple passes through an archiveto resolve symbols, this mechanism can be quite costly for large archivescontaining random organizations of relocatable objects. In these cases it is

Page 27: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 13

2

recommended that tools like lorder(1) and tsort(1) be used to order therelocatable objects within the archive and so reduce the number of passes thelink-editor must carry out.

Shared Object Processing

Shared objects are indivisible, whole units that have been generated by aprevious link-edit of one or more input files. When the link-editor processes ashared object the entire contents of the shared object become a logical part ofthe resulting output file image. The shared object is not copied physicallyduring the link-edit as its actual inclusion is deferred until process execution.This logical inclusion means that all symbol entries defined in the shared objectare made available to the link-editing process.

The shared object’s program data sections and most of the link-editing informationsections are unused by the link-editor, as these will be interpreted by theruntime linker when the shared object is bound to generate a runable process.However, the occurrence of a shared object will be remembered, andinformation will be stored in the output file image to indicate that this object isa dependency and must be made available at runtime.

If a shared object has dependencies on other shared objects, these too will beprocessed. This processing will occur after all command-line input files havebeen processed. These shared objects will be used to complete the symbolresolution process, however their names will not be recorded as dependenciesin the output file image being generated.

Although the position of a shared object on the link-edit command-line has lesssignificance than it does for archive processing, it can have a global effect.Multiple symbols of the same name are allowed to occur between relocatableobjects and shared objects, and between multiple shared objects (see “SymbolResolution” on page 21 for more details).

The order of shared objects processed by the link-editor is maintained in thedependency information stored in the output file image. As the runtime linkerreads this information it will load the specified shared objects in the sameorder. Therefore, the link-editor and the runtime linker will select the firstoccurrence of a symbol of a multiply defined series of symbols.

Page 28: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

14 Linker and Libraries Guide—November 1995

2

Note – Multiple symbol definitions, and thus the information to describe theinterposing of one definition of a symbol for another, are reported in the loadmap output generated using the -m option.

Linking with Additional Libraries

Although the compiler drivers will often ensure that appropriate libraries arespecified to the link-editor, it is frequently necessary for you to supply yourown. Shared objects and archives can be specified by explicitly naming theinput files required to the link-editor, but a more common and more flexiblemethod involves using the link-editor’s -l option.

Library Naming Conventions

By convention, shared objects are usually designated by the prefix lib and thesuffix .so , and archives are designated by the prefix lib and the suffix .a . Forexample, libc.so is the shared object version of the standard C library madeavailable to the compilation environment, and libc.a is its archive version.

These conventions are recognized by the -l option of the link-editor. Thisoption is commonly used to supply additional libraries to a link-edit. Thefollowing example:

directs the link-editor to search for libfoo.so , and if it does not find it, tosearch for libfoo.a , before moving on to the next directory to be searched.

Note – There is a naming convention regarding the compilation environmentand the runtime environment use of shared objects. The compilationenvironment uses the simple .so suffix, whereas the runtime environmentcommonly uses the suffix with an additional version number. See “NamingConventions” on page 84, and “Coordination of Versioned Filenames” onpage 136 for more details.

$ cc -o prog file1.c file2.c -lfoo

Page 29: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 15

2

When link-editing in dynamic mode, you can choose to link with a mix ofshared objects and archives. When link-editing in static mode, only archivelibraries are acceptable for input.

When in dynamic mode and using the -l option to enable a library search, thelink-editor will first search in a given directory for a shared object that matchesthe specified name. If no match is found the link-editor will then look for anarchive library in the same directory. When in static mode and using the -loption, only archive libraries will be sought.

Linking with a Mix of Shared Objects and Archives

Although the library search mechanism, in dynamic mode, searches a givendirectory for a shared object, and then an archive library, finer control of thetype of search required can be achieved using the -B option.

By specifying the -Bdynamic and -Bstatic options on the command-line, asmany times as required, the library search can be toggled between sharedobjects or archives respectively. For example, to link an application with thearchive libfoo.a and the shared object libbar.so , issue the followingcommand:

The -Bstatic and -Bdynamic keywords are not exactly symmetrical. Whenyou specify -Bstatic , the link-editor does not accept shared objects as inputuntil the next occurrence of -Bdynamic . However, when you specify-Bdynamic , the link-editor will first look for shared objects and then archivesin any given directory.

In the previous example it is more precise to say that the link-editor firstsearches for libfoo.a, and then for libbar.so , and if that fails, forlibbar.a . Finally, it will search for libc.so , and if that fails, libc.a .

Another example of using these options is in the creation of an ABI-conforming application. For example:

$ cc -o prog main.o file1.c -Bstatic -lfoo -Bdynamic -lbar

$ cc -o prog main.c file1.c -lsys -Bstatic

Page 30: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

16 Linker and Libraries Guide—November 1995

2

Here all the basic system routines defined in libsys.so will be bound to thisshared object. Because the compiler driver appends a -lc to the optionssupplied to the link-editor, and because the -Bstatic has instructed thelink-editor to search for archive libraries only, any remaining undefinedsymbols will be resolved by extracting the appropriate relocatable objects fromlibc.a .

Position of an Archive on the Command-Line

The position of an archive on the command-line can affect the output file beingproduced. The link-editor searches an archive only to resolve undefined ortentative external references it has previously seen. Once this search iscompleted and the required relocatable objects have been extracted, the archivewill not be available to resolve any new symbols obtained from the input filesthat follow the archive on the command-line. For example, the command

directs the link-editor to search libfoo.a only to resolved symbol referencesthat have been obtained from file1.c; libfoo.a will not be available toresolve symbol references from file2.c or file3.c .

Note – As a rule, it is best to specify any archives at the end of the command-line unless multiple-definition conflicts require you to do otherwise.

Directories Searched by the Link-Editor

All previous examples assumed that the link-editor knows where to search forthe libraries listed on the command-line. By default the link-editor knows ofonly two standard places to look for libraries, /usr/ccs/lib and /usr/lib .All other directories to be searched must be added to the link-editor’s searchpath explicitly.

There are two ways to change the link-editor search path: using a command-line option, or using an environment variable.

$ cc -o prog file1.c -Bstatic -lfoo file2.c file3.c -Bdynamic

Page 31: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 17

2

Using a Command-Line OptionThe -L option can be used to add a new pathname to the library search path.This option affects the search path at the point it is encountered on thecommand-line. For example, the command

searches path1 (then /usr/ccs/lib and /usr/lib ) to find libfoo , butsearches path1 and then path2 (and then /usr/ccs/lib and /usr/lib ) tofind libbar .

Pathnames defined using the -L option are used only by the link-editor. Theyare not recorded in the output file image created for use by the runtime linker.

Note – You must specify -L if you want the link-editor to search for libraries inyour current directory. You can use a period (.) to represent the currentdirectory.

The -Y option can be used to change the default directories searched by thelink-editor. The argument supplied with this option takes the form of a colonseparated list of directories. For example, the command

searches for libfoo only in the directories /opt/COMPILER/lib and/home/me/lib . The directories specified using the -Y option can besupplemented by using the -L option.

Using an Environment VariableYou can also use the environment variable LD_LIBRARY_PATH, which takes acolon-separated list of directories, to add to the link-editor’s library searchpath. In its most general form, LD_LIBRARY_PATH takes two directory listsseparated by a semicolon. The first list is searched before the list(s) supplied onthe command-line, and the second list is searched after.

$ cc -o prog main.o -Lpath1 file1.c -lfoo file2.c -Lpath2 -lbar

$ cc -o prog main.c -YP,/opt/COMPILER/lib:/home/me/lib -lfoo

Page 32: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

18 Linker and Libraries Guide—November 1995

2

Here is the combined effect of setting LD_LIBRARY_PATH and calling thelink-editor with several -L occurrences:

The effective search path will be dir1:dir2:path1:path2...pathn:dir3:/usr/ccs/lib:/usr/lib .

If no semicolon is specified as part of the LD_LIBRARY_PATH definition thespecified directory list is interpreted after any -L options. For example:

Here the effective search path will be path1:path2...pathn:dir1:dir2:/usr/ccs/lib:/usr/lib .

Note – This environment variable can also be used to augment the search pathof the runtime linker (see “Directories Searched by the Runtime Linker” onpage 55 for more details). To prevent this environment variable frominfluencing the link-editor the -i option can be used.

Directories Searched by the Runtime Linker

The runtime linker knows of only one standard place to look for libraries,/usr/lib . All other directories to be searched must be added to the runtimelinker’s search path explicitly.

When a dynamic executable or shared object is linked with additional sharedobjects, these shared objects are recorded as dependencies that must be locatedagain during process execution by the runtime linker. During the link-edit, oneor more pathnames can be recorded in the output file. These pathnames will beused by the runtime linker to search for any shared object dependencies. Theserecorded pathnames are referred to as a runpath.

$ LD_LIBRARY_PATH=dir1:dir2;dir3$ export LD_LIBRARY_PATH$ cc -o prog main.c -Lpath1 ... -Lpath2 ... -Lpathn -lfoo

$ LD_LIBRARY_PATH=dir1:dir2$ export LD_LIBRARY_PATH$ cc -o prog main.c -Lpath1 ... -Lpath2 ... -Lpathn -lfoo

Page 33: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 19

2

Note – No matter how you modify the runtime linker’s library search path, itslast element is always /usr/lib .

The - R option, which takes a colon-separated list of directories, can be used torecord a runpath in a dynamic executable or shared library. For example:

will record the runpath /home/me/lib:/home/you/lib in the dynamicexecutable prog . The runtime linker will use these paths, and then the defaultlocation /usr/lib , to locate any shared object dependencies. In this case, thisrunpath will be used to locate libfoo.so.1 and libbar.so.1 .

The link-editor accepts multiple -R options and will concatenate each of thesespecifications, separated by a colon. Thus, the above example can also beexpressed as:

Note – A historic alternative to specifying the -R option is to set theenvironment variable LD_RUN_PATH, and make this available to thelink-editor. The scope and function of LD_RUN_PATH and -R are identical, butwhen both are specified, -R supersedes LD_RUN_PATH.

Initialization and Termination Sections

The .init and .fini section types provide for runtime initialization andtermination processing. These section types are concatenated from the inputrelocatable objects like any other sections. However, the compiler drivers canalso supply .init and .fini sections as part of the additional files they add to thebeginning and end of the your input-file list.

These files have the effect of encapsulating the .init and .fini code intoindividual functions that are identified by the reserved symbol names _initand _fini respectively.

$ cc -o prog main.c -R/home/me/lib:/home/you/lib -Lpath1 \- Lpath2 file1.c file2.c -lfoo -lbar

$ cc -o prog main.c -R/home/me/lib -Lpath1 \-R/home/you/lib - Lpath2 file1.c file2.c -lfoo -lbar

Page 34: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

20 Linker and Libraries Guide—November 1995

2

When building a dynamic executable or shared object, the link-editor recordsthese symbol addresses in the output file’s image so they can be called by theruntime linker during initialization and termination processing. See“Initialization and Termination Routines” on page 64 for more details on theruntime processing of these sections.

The creation of .init and .fini sections can be carried out directly using anassembler, or some compilers can offer special primitives to simplify theirdeclaration. For example, the following code segments result in a call to thefunction foo being placed in an .init section, and a call to the function barbeing placed in a .fini section:

Care should be taken when designing initialization and termination code thatcan be included in both a shared object and archive library. If this code isspread throughout several relocatable objects within an archive library, thenthe link-edit of an application using this archive can extract only a portion ofthe modules, and therefore only a portion of the initialization and terminationcode. At runtime, only this portion of code will be executed.

The same application built against the shared object will have all theaccumulated initialization and termination code executed at runtime when theshared object is mapped in as one of the application’s dependencies.

#pragma init (foo)#pragma fini (bar)

foo(){ /* Perform some initialization processing. */ ......}

bar(){ /* Perform some termination processing. */ .......}

Page 35: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 21

2

Symbol ProcessingDuring input file processing, all local symbols from the input relocatable objectsare passed through to the output file image. All global symbols are accumulatedinternally within the link-editor. This internal symbol table is searched for eachnew global symbol entry processed to determine if a symbol with the samename has already been encountered from a previous input file. If so, a symbolresolution process is called to determine which of the two entries is to be kept.

On completion of input file processing, and providing no fatal error conditionshave been encountered during symbol resolution, the link-editor determines ifany unbound symbol references (undefined symbols) remain that will causethe link-edit to fail.

Finally, the link-editor’s internal symbol table is added to the symbol table(s)of the image being created.

The following sections expand upon symbol resolution and undefined symbolprocessing.

Symbol Resolution

Symbol resolution runs the entire spectrum, from simple and intuitive tocomplex and perplexing. Resolutions can be carried out silently by thelink-editor, be accompanied by warning diagnostics, or result in a fatal errorcondition.

The resolution of two symbols depends on the symbols’ attributes, the type offile providing the symbol and the type of file being generated. For a completedescription of symbol attributes see “Symbol Table” on page 162. For thefollowing discussions, however, it is worth identifying three basic symboltypes:

• Undefined symbols. These symbols have been referenced in a file but havenot been assigned a storage address.

• Tentative symbols. These symbols have been created within a file but havenot yet been sized or allocated in storage. They appear as uninitialized Csymbols, or FORTRAN COMMON blocks within the file.

• Defined symbols. These symbols have been created and assigned storageaddresses and space within the file.

Page 36: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

22 Linker and Libraries Guide—November 1995

2

In its simplest form, symbol resolution involves the use of a precedencerelationship that has defined symbols dominating tentative symbols, which inturn dominate undefined symbols.

The following C code example shows how these symbol types can begenerated (undefined symbols are prefixed with u_ , tentative symbols areprefixed with t_ , and defined symbols are prefixed with d_):

Simple Resolutions

These symbol resolutions are by far the most common, and result when twosymbols with similar characteristics are detected, and one symbol takesprecedence over the other. This symbol resolution is carried out silently by thelink-editor. For example, for symbols with the same binding, a reference to anundefined symbol from one file will be bound to, or satisfied by, a defined ortentative symbol definition from another file. Or, a tentative symbol definitionfrom one file will be bound to a defined symbol definition from another file.

$ cat main.cextern int u_bar;extern int u_foo();

int t_bar;int d_bar = 1;

d_foo(){ return (u_foo(u_bar, t_bar, d_bar));}$ cc -o main.o -c main.c$ nm -x main.o

[Index] Value Size Type Bind Other Shndx Name...............[8] |0x00000000|0x00000000|NOTY |GLOB |0x0 |UNDEF |u_foo[9] |0x00000000|0x00000040|FUNC |GLOB |0x0 |2 |d_foo[10] |0x00000004|0x00000004|OBJT |GLOB |0x0 |COMMON |t_bar[11] |0x00000000|0x00000000|NOTY |GLOB |0x0 |UNDEF |u_bar[12] |0x00000000|0x00000004|OBJT |GLOB |0x0 |3 |d_bar

Page 37: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 23

2

Symbols that undergo resolution can have either a global or weak binding.Weak bindings have less precedence than global binding, and so symbols withdifferent bindings are resolved according to a slight alteration of the simplerules outlined above. But first, it is worth introducing how weak symbols canbe produced.

Weak symbols can be defined individually or as aliases to global symbols usinga pragma definition:

Notice that the weak alias foo is assigned the same attributes as the globalsymbol _foo . This relationship will be maintained by the link-editor and willresult in the symbols being assigned the same value in the output image.

In symbol resolution, weak defined symbols will be silently overridden by anyglobal definition of the same name.

Another form of simple symbol resolution occurs between relocatable objectsand shared objects, or between multiple shared objects, and is termedinterposition. In these cases, if a symbol is multiply defined, the relocatableobject, or the first definition between multiple shared objects, will be silentlytaken by the link-editor. The relocatable object’s definition, or the first shared

$ cat main.c#pragma weak bar#pragma weak foo = _foo

int bar = 1;

_foo(){ return (bar);}$ cc -o main.o -c main.c$ nm -x main.o

[Index] Value Size Type Bind Other Shndx Name...............[7] |0x00000000|0x00000004|OBJT |WEAK |0x0 |3 |bar[8] |0x00000000|0x00000028|FUNC |WEAK |0x0 |2 |foo[9] |0x00000000|0x00000028|FUNC |GLOB |0x0 |2 |_foo

Page 38: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

24 Linker and Libraries Guide—November 1995

2

object’s definition, is said to interpose on all other definitions. This interpositioncan be used to override the functionality provided by one shared object by adynamic executable or another shared object.

The combination of weak symbols and interposition provides a very usefulprogramming technique. For example, the standard C library provides severalservices that you are allowed to redefine. However, ANSI C defines a set ofstandard services that must be present on the system and cannot be replaced ina strictly conforming program.

The function fread(3S) , for example, is an ANSI C library function, whereasthe system function read(2) is not. A conforming ANSI C program must beable to redefine read(2) , and still use fread(3S) in a predictable way.

The problem here is that read(2) underlies the fread(3S) implementationin the standard C library, and so it would seem that a program that redefinesread(2) might confuse the fread(3S) implementation. To guard againstthis, ANSI C states that an implementation cannot use a name that is notreserved to it, and by using the pragma directive shown below:

you can define just such a reserved name, and from it generate an alias for thefunction read(2) . Thus, you can quite freely define your own read()function without compromising the fread(3S) implementation, which in turnis implemented to use the _read() function.

The link-editor will not complain of your redefinition of read() , either whenlinking against the shared object or archive version of the standard C library. Inthe former case, interposition will take its course, whereas in the latter case, thefact that the C library’s definition of read(2) is weak allows it to be quietlyoverridden.

By using the link-editor’s -m option, a list of all interposed symbol references,along with section load address information, is written to the standard output.

# pragma weak read = _read

Page 39: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 25

2

Complex Resolutions

Complex resolutions occur when two symbols of the same name are foundwith differing attributes. In these cases the link-editor will select the mostappropriate symbol and will generate a warning message indicating thesymbol, the attributes that conflict, and the identity of the file from which thesymbol definition is taken. For example:

Here, two files with a definition of the data item array have different sizerequirements. A similar diagnostic is produced if the symbols’ alignmentrequirements differed. In both of these cases the diagnostic can be suppressedby using the link-editor’s -t option.

$ cat foo.cint array[1];

$ cat bar.cint array[2] = { 1, 2 };

$ cc -dn -r -o temp.o foo.c bar.cld: warning: symbol `array’ has differing sizes: (file foo.o value=0x4; file bar.o value=0x8); bar.o definition taken

Page 40: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

26 Linker and Libraries Guide—November 1995

2

Another form of attribute difference is the symbol’s type. For example:

Here the symbol bar has been defined as both a data item and a function.

Note – types in this context are the symbol types that can be expressed in ELF.They are not related to the data types as employed by the programminglanguage except in the crudest fashion.

In cases like this, the relocatable object definition will be taken when theresolution occurs between a relocatable object and a shared object, or, the firstdefinition will be taken when the resolution occurs between two sharedobjects. When such resolutions occur between symbols of different bindings(weak or global), a warning will also be produced.

Inconsistences between symbol types are not suppressed by the link-editor’s-t option.

Fatal Resolutions

Symbol conflicts that cannot be resolved result in a fatal error condition. In thiscase an appropriate error message is provided indicating the symbol nametogether with the names of the files that provided the symbols, and no output

$ cat foo.cbar(){ return (0);}$ cc -o libfoo.so -G -K pic foo.c$ cat main.cint bar = 1;

main(){ return (bar);}$ cc -o main main.c -L. -lfoold: warning: symbol `bar’ has differing types: (file main.o type=OBJT; file ./libfoo.so type=FUNC); main.o definition taken

Page 41: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 27

2

file will be generated. Although the fatal condition is sufficient to terminate thelink-edit, all input file processing will first be completed. In this manner allfatal resolution errors can be identified.

The most common fatal error condition exists when two relocatable objectsboth define symbols of the same name, and neither symbol is a weakdefinition:

Here foo.c and bar.c have conflicting definitions for the symbol bar . Sincethe link-editor cannot determine which should dominate, it will usually giveup. However, the link-editor’s -z muldefs option can be used to suppressthis error condition, and allows the first symbol definition to be taken.

Undefined Symbols

After all input files have been read and all symbol resolution is complete, thelink-editor will search the internal symbol table for any symbol references thathave not been bound to symbol definitions. These symbol references arereferred to as undefined symbols. The effect of these undefined symbols on thelink-edit process can vary according to the type of output file being generated,and possibly the type of symbol.

$ cat foo.cint bar = 1;

$ cat bar.cbar(){ return (0);}

$ cc -dn -r -o temp.o foo.c bar.cld: fatal: symbol `bar’ is multiply defined: (file foo.o and file bar.o);ld: fatal: File processing errors. No output written to int.o

Page 42: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

28 Linker and Libraries Guide—November 1995

2

Generating an Executable

When the link-editor is generating an executable output file, the link-editor’sdefault behavior is to terminate the link-edit with an appropriate errormessage should any symbols remain undefined. A symbol remains undefinedwhen a symbol reference in a relocatable object is never matched to a symboldefinition:

In a similar manner, a symbol reference within a shared object that is nevermatched to a symbol definition when the shared object is being used to build adynamic executable, will also result in an undefined symbol:

$ cat main.cextern int foo();main(){ return (foo());}

$ cc -o prog main.cUndefined first referenced symbol in filefoo main.old: fatal: Symbol referencing errors. No output written to prog

$ cat foo.cextern int bar;foo(){ return (bar);}

$ cc -o libfoo.so -G -K pic foo.c$ cc -o prog main.c -L. -lfooUndefined first referenced symbol in filebar ./libfoo.sold: fatal: Symbol referencing errors. No output written to prog

Page 43: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 29

2

If you wish to allow undefined symbols, as in cases like the previous example,then the default fatal error condition can be suppressed by using thelink-editor’s -z nodefs option.

Note – Care should be taken when using the -z nodefs option. If anunavailable symbol reference is required during the execution of a process, afatal runtime relocation error will occur. Although this error can be detectedduring the initial execution and testing of an application, more complexexecution paths can result in this error condition taking much longer to detect,which can be time consuming and costly.

Symbols can also remain undefined when a symbol reference in a relocatableobject is bound to a symbol definition in an implicitly defined shared object. Forexample, continuing with the files main.c and foo.c used in the previousexample:

Here prog is being built with an explicit reference to libbar.so , and becauselibbar.so has a dependency on libfoo.so , an implicit reference tolibfoo.so from prog is established.

Because main.c made a specific reference to the interface provided bylibfoo.so , then prog really has a dependency on libfoo.so . However, onlyexplicit shared object dependencies are recorded in the output file beinggenerated. Thus, prog will fail to run if a new version of libbar.so isdeveloped that no longer has a dependency on libfoo.so .

$ cat bar.cint bar = 1;

$ cc -o libbar.so -R. -G -K pic bar.c -L. -lfoo$ ldd libbar.so libfoo.so => ./libfoo.so

$ cc -o prog main.c -L. -lbarUndefined first referenced symbol in filefoo main.o (symbol belongs toimplicit dependency ./libfoo.so)ld: fatal: Symbol referencing errors. No output written to prog

Page 44: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

30 Linker and Libraries Guide—November 1995

2

For this reason, bindings of this type are deemed fatal, and the implicitreference must be made explicit by referencing the library directly during thelink-edit of prog (the required reference is hinted at in the fatal error messageshown in this example).

Generating a Shared Object

When the link-editor is generating a shared object, it will by default allowundefined symbols to remain at the end of the link-edit. This allows the sharedobject to import symbols from either relocatable objects or other shared objectswhen it is used to build a dynamic executable. The link-editor’s -z defsoption can be used to force a fatal error if any undefined symbols remain.

Weak Symbols

Weak symbol references that are not bound during a link-edit will not result ina fatal error condition, no matter what output file type is being generated.

If a static executable is being generated, the symbol will be converted to anabsolute symbol and assigned a value of zero.

If a dynamic executable or shared object is being produced, the symbol will beleft as an undefined weak reference. During process execution, the runtimelinker will search for this symbol, and if it does not find a match, will bind thereference to an address of zero instead of generating a fatal runtime relocationerror.

Page 45: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 31

2

Within the confines of position-independent code (see section “Position-Independent Code” on page 100 for more information), these undefined weakreferenced symbols can provide a useful mechanism for testing for theexistence of functionality. For example, let’s take the following C codefragment which exists in the shared object libfoo.so.1 :

When an application is built that references libfoo.so.1 , the link-edit willsuccessfully complete regardless of whether a definition for the symbol foo isfound. If, during execution of the application the function address testsnonzero, the function will be called. However, if the symbol definition is notfound, the function address will test zero, and so will not be called.

Tentative Symbol Order Within the Output File

Contributions from input files usually appear in the output file in the order oftheir contribution. An exception occurs when processing tentative symbols andtheir associated storage. These symbols are not fully defined until theirresolution is complete. If the resolution occurs as a result of encountering adefined symbol from a relocatable object, then the order of appearance will bethat which would have occurred for the definition.

#pragma weak foo

extern void foo(char *);

voidbar(char * path){ void (* fptr)();

if ((fptr = foo) != 0) (* fptr)(path);}

Page 46: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

32 Linker and Libraries Guide—November 1995

2

If it is desirable to control the ordering of a group of symbols, then anytentative definition should be redefined to a zero-initialized data item. Forexample, the following tentative definitions result in a reordering of the dataitems within the output file compared to the original order described in thesource file foo.c :

By defining these symbols as initialized data items, the relative ordering ofthese symbols within the input file is carried over to the output file:

Defining Additional Symbols

Besides the symbols provided from any input files, you can also supplyadditional symbol references or definitions to a link-edit. In the simplest form,symbol references can be generated using the link-editor’s -u option. Greaterflexibility is provided with the link-editor’s -M option and an associatedmapfile which allows you to define symbol references and a variety ofsymbol definitions.

$ cat foo.cchar A_array[0x10];char B_array[0x20];char C_array[0x30];$ cc -o prog main.c foo.c$ nm -vx prog | grep array[32] |0x00020754|0x00000010|OBJT |GLOB |0x0 |15 |A_array[34] |0x00020764|0x00000030|OBJT |GLOB |0x0 |15 |C_array[42] |0x00020794|0x00000020|OBJT |GLOB |0x0 |15 |B_array

$ cat foo.cchar A_array[0x10] = { 0 };char B_array[0x20] = { 0 };char C_array[0x30] = { 0 };$ cc -o prog main.c foo.c$ nm -vx prog | grep array[32] |0x000206bc|0x00000010|OBJT |GLOB |0x0 |12 |A_array[42] |0x000206cc|0x00000020|OBJT |GLOB |0x0 |12 |B_array[34] |0x000206ec|0x00000030|OBJT |GLOB |0x0 |12 |C_array

Page 47: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 33

2

The -u option provides a mechanism for generating a symbol reference fromthe link-edit command line. This option can be used to perform a link-editentirely from archives, or to provide additional flexibility in selecting theobjects to extract from multiple archives (see section “Archive Processing” onpage 12 for an overview of archive extraction).

For example, let’s take the generation of a dynamic executable from therelocatable object main.o which makes reference to the symbols foo and bar .You wish to obtain the symbol definition foo from the relocatable objectfoo.o contained in lib1.a , and the symbol definition bar from therelocatable object bar.o contained in lib2.a .

However, the archive lib1.a also contains a relocatable object defining thesymbol bar (presumably of differing functionality to that provided inlib2.a ). To specify the required archive extraction, the following link-edit canbe used:

Here, the -u option generates a reference to the symbol foo . This referencewill cause extraction of the relocatable object foo.o from the archive lib1.a .As the first reference to the symbol bar occurs in main.o , which isencountered after lib1.a has been processed, the relocatable object bar.owill be obtained from the archive lib2.a .

Note – This simple example assumes that the relocatable object foo.o fromlib1.a does not directly, or indirectly, reference the symbol bar . If it did thenthe relocatable object bar.o will also be extracted from lib1.a during itsprocessing (see section “Archive Processing” on page 12 for a discussion of thelink-editor’s multi-pass processing of an archive).

A more extensive set of symbol definitions can be provided using thelink-editor’s -M option and an associated mapfile . The syntax for thesemapfile entries is:

$ cc -o prog -L. -u foo -l1 main.o -l2

[ name ] { scope: symbol [ = [ type ] [ value ] [ size ] ];};

Page 48: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

34 Linker and Libraries Guide—November 1995

2

• name represents a label for this set of symbol definitions, and if present,identifies a version definition within the image. See Chapter 5, “Versioning”for more details.

• scope indicates the visibility of the symbols’ binding within the output filebeing generated. This can have either the value local or global . All symbolsdefined with a mapfile are treated as global in scope during the link-editprocess. That is, they will be resolved against any other symbols of the samename obtained from any of the input files. However, symbols defined aslocal scope will be reduced to symbols with a local binding within anyexecutable or shared object file being generated.

• symbol is the name of the symbol required. If the name is not followed byany symbol attributes then the result will be the creation of a symbolreference. This reference is exactly the same as would be generated using the-u option discussed earlier in this section. If the symbol name is followedby an optional “=” character then a symbol definition will be generatedusing the associated attributes.

When in local scope, this symbol name can be defined as the special auto-reduction directive “*”. This directive results in all global symbols, notexplicitly defined to be global in the mapfile , being given a local bindingwithin any executable or shared object file being generated.

• type indicates the symbols’ type attribute and can be either data , function orcommon . The former two type attributes result in an absolute symboldefinition (see “Symbol Table” on page 162). The latter type attribute resultsin a tentative symbol definition.

• value indicates the symbols’ value attribute and takes the form of Vnumber.

• size indicates the symbols’ size attribute and takes the form of Snumber.

If either a version definition or the auto-reduction directive is specified, thenversioning information is recorded in the image created. If this image is anexecutable or shared object, then any symbol reduction is also applied.

If the image being created is a relocatable object, then by default no symbolreduction is applied. In this case, any symbol reductions are recorded as part ofthe versioning information, and these reductions will be applied when therelocatable object is finally used to generate an executable or shared object.

A more detailed description of the versioning information is provided inChapter 5, “Versioning”.

Page 49: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 35

2

The remainder of this section presents several examples of using this mapfilesyntax.

The following example shows how three symbol references can be defined andused to extract members of an archive. Although this archive extraction can beachieved by specifying multiple -u options to the link-edit, this example alsoshows how the eventual scope of a symbol can be reduced to local:

$ cat foo.cfoo(){ (void) printf(“foo: called from lib.a\n”);}$ cat bar.cbar(){ (void) printf(“bar: called from lib.a\n”);}$ cat main.cextern void foo(), bar();

main(){ foo(); bar();}$ ar -rc lib.a foo.o bar.o main.o$ cat mapfile{ local: foo; bar; global: main;};$ cc -o prog -M mapfile lib.a$ progfoo: called from lib.abar: called from lib.a$ nm -x prog | egrep “main$|foo$|bar$”[28] |0x00010604|0x00000024|FUNC |LOCL |0x0 |7 |foo[30] |0x00010628|0x00000024|FUNC |LOCL |0x0 |7 |bar[49] |0x0001064c|0x00000024|FUNC |GLOB |0x0 |7 |main

Page 50: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

36 Linker and Libraries Guide—November 1995

2

The significance of reducing a symbol’s scope from global to local is covered inmore detail in the section “Reducing Symbol Scope” on page 38.

The following example shows how two absolute symbol definitions can bedefined and used to resolve the references from the input file main.c :

When obtained from an input file, symbol definitions for functions or dataitems are usually associated with elements of data storage. As a mapfiledefinition is insufficient to be able to construct this data storage, these symbolsmust remain as absolute values.

However, a mapfile can also be used to define a common , or tentative,symbol. Unlike other types of symbol definition, tentative symbols do notoccupy storage within a file, but define storage that must be allocated at run-time. Therefore, symbol definitions of this kind can contribute to the storageallocation of the output file being generated.

$ cat main.cextern int foo();extern int bar;

main(){ (void) printf(“&foo = %x\n”, &foo); (void) printf(“&bar = %x\n”, &bar);}$ cat mapfile{ global: foo = FUNCTION V0x400; bar = DATA V0x800;};$ cc -o prog -M mapfile main.c$ prog&foo = 400&bar = 800$ nm -x prog | egrep “foo$|bar$”[37] |0x00000800|0x00000000|OBJT |GLOB |0x0 |ABS |bar[42] |0x00000400|0x00000000|FUNC |GLOB |0x0 |ABS |foo

Page 51: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 37

2

A feature of tentative symbols, that differs from other symbol types, is thattheir value attribute indicates their alignment requirement. A mapfiledefinition can therefore be used to realign tentative definitions obtained fromthe input files of a link-edit.

The following example shows the definition of two tentative symbols. Thesymbol foo defines a new storage region whereas the symbol bar is actuallyused to change the alignment of the same tentative definition within the filemain.c :

Note – The above symbol resolution diagnostic can be suppressed by using thelink-editor’s -t option.

$ cat main.cextern int foo;int bar[0x10];

main(){ (void) printf(“&foo = %x\n”, &foo); (void) printf(“&bar = %x\n”, &bar);}$ cat mapfile{ global: foo = COMMON V0x4 S0x200; bar = COMMON V0x100 S0x40;};$ cc -o prog -M mapfile main.cld: warning: symbol ‘bar’ has differing alignments: (file mapfile value=0x100; file main.o value=0x4); largest value applied$ prog&foo = 20940&bar = 20900$ nm -x prog | egrep “foo$|bar$”[37] |0x00020900|0x00000040|OBJT |GLOB |0x0 |16 |bar[42] |0x00020940|0x00000200|OBJT |GLOB |0x0 |16 |foo

Page 52: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

38 Linker and Libraries Guide—November 1995

2

Reducing Symbol Scope

In the previous section it was shown how symbol definitions defined to havelocal scope within a mapfile can be used to reduce the symbol’s eventualbinding. This mechanism can play an important role in reducing the symbol’svisibility to future link-edits that use the generated file as part of their input. Infact, this mechanism can provide for the precise definition of a file’s interface,and so restrict the functionality made available to others.

For example, let’s take the generation of a simple shared object from the filesfoo.c and bar.c . The file foo.c contains the global symbol foo whichprovides the service that you wish to make available to others. The file bar.ccontains the symbols bar and str which provide the underlyingimplementation of the shared object. A simple build of the shared object willusually result in all three of these symbols having global scope:

You can now use the functionality offered by this shared object as part of thelink-edit of another application. References to the symbol foo will be bound tothe implementation provided by the shared object.

$ cat foo.cextern const char * bar();

const char * foo(){ return (bar());}$ cat bar.cconst char * str = “returned from bar.c”;

const char * bar(){ return (str);}$ cc -o lib.so.1 -G foo.c bar.c$ nm -x lib.so.1 | egrep “foo$|bar$|str$”[29] |0x000104d0|0x00000004|OBJT |GLOB |0x0 |12 |str[32] |0x00000418|0x00000028|FUNC |GLOB |0x0 |6 |bar[33] |0x000003f0|0x00000028|FUNC |GLOB |0x0 |6 |foo

Page 53: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 39

2

However, because of their global binding, direct reference to the symbols barand str is also possible. This can have dangerous consequences, as the youmight later change the implementation underlying the function foo , and in sodoing unintentionally cause an existing application that had bound to bar orstr fail or misbehave.

Another consequence of the global binding of the symbols bar and str is thatthey can be interposed upon by symbols of the same name (the interposition ofsymbols within shared objects is covered in section “Simple Resolutions” onpage 22). This interposition can be intentional and be used as a means ofcircumventing the intended functionality offered by the shared object. On theother hand, this interposition can be unintentional, and simply be the result ofthe application and the shared object using the same common symbol name.

When developing the shared object you can protect against this type ofscenario by reducing the scope of the symbols bar and str to a local binding,for example:

Here the symbols bar and str are no longer available as part of the sharedobjects interface. Thus these symbols cannot be referenced, or interposed upon,by an external object. You have effectively defined an interface for the sharedobject. This interface can be managed while hiding the details of theunderlying implementation.

This symbol scope reduction has an additional performance advantage. Thesymbolic relocations against the symbols bar and str that would have beennecessary at runtime are now reduced to relative relocations. This reduces theruntime overhead of initializing and processing the shared object (see section“When Relocations are Performed” on page 106 for details of symbolicrelocation overhead).

$ cat mapfile{ local: bar; str;};$ cc -o lib.so.1 -M mapfile -G foo.c bar.c$ nm -x lib.so.1 | egrep “foo$|bar$|str$”[27] |0x000003dc|0x00000028|FUNC |LOCL |0x0 |6 |bar[28] |0x00010494|0x00000004|OBJT |LOCL |0x0 |12 |str[33] |0x000003b4|0x00000028|FUNC |GLOB |0x0 |6 |foo

Page 54: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

40 Linker and Libraries Guide—November 1995

2

As the number of symbols processed during a link-edit gets large, the ability todefine each local scope reduction within a mapfile becomes harder tomaintain. An alternative, and more flexible mechanism, allows you to definethe shared objects interface in terms of the global symbols that should

be maintained, and instructs the link-editor to reduce all other symbols to localbinding. This mechanism is achieved using the special auto-reduction directive“*”. For example, the previous mapfile definition can be rewritten to definefoo as the only global symbol required in the output file generated:

This example also defines a version name, lib.so.1.1 , as part of themapfile directive. This version name establishes an internal version definitionthat defines the files symbolic interface. The creation of a version definition isrecommended, and forms the foundation of an internal versioning mechanismthat can be used throughout the evolution of the file. See Chapter 5,“Versioning” for more details on this topic.

$ cat mapfilelib.so.1.1 { global: foo; local: *;};$ cc -o lib.so.1 -M mapfile -G foo.c bar.c$ nm -x lib.so.1 | egrep “foo$|bar$|str$”[30] |0x00000370|0x00000028|FUNC |LOCL |0x0 |6 |bar[31] |0x00010428|0x00000004|OBJT |LOCL |0x0 |12 |str[35] |0x00000348|0x00000028|FUNC |GLOB |0x0 |6 |foo

Page 55: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 41

2

Whenever a version name is specified, all global symbols must be assigned to aversion definition. If any global symbols remain unassigned to a versiondefinition the link-editor will generate a fatal error condition:

When generating an executable or shared object, any symbol reduction resultsin the recording of version definitions within the output image, together withthe reduction of the appropriate symbols. By default, when generating arelocatable object, the version definitions are created, but the symbolreductions are not processed. The result is that the symbol entries for anysymbol reductions will still remain global. For example, using the previousmapfile and associated relocatable objects, an intermediate relocatable objectis created which shows no symbol reduction:

However, the version definitions created within this image record the fact thatsymbol reductions are required. When the relocatable object is eventually usedto generate an executable or shared object, the symbol reductions will occur. Inother words, the link-editor reads and interprets symbol reduction informationcontained in relocatable objects in the same manner as it can process the datafrom a mapfile .

$ cat mapfilelib.so.1.1 { global: foo;};$ cc -o lib.so.1 -M mapfile -G foo.c bar.cUndefined first referenced symbol in filestr bar.o (symbol has no version assigned)bar bar.o (symbol has no version assigned)ld: fatal: Symbol referencing errors. No output written tolib.so.1

$ ld -o lib.o -M mapfile -r foo.o bar.o$ nm -x lib.o | egrep “foo$|bar$|str$”[17] |0x00000000|0x00000004|OBJT |GLOB |0x0 |3 |str[19] |0x00000028|0x00000028|FUNC |GLOB |0x0 |1 |bar[20] |0x00000000|0x00000028|FUNC |GLOB |0x0 |1 |foo

Page 56: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

42 Linker and Libraries Guide—November 1995

2

Thus, the intermediate relocatable object produced in the previous example cannow be used to generate a shared object:

Symbol reductions can be forced to occur when building a relocatable object byusing the link-editor’s -B reduce option:

Generating the Output ImageOnce all input file processing and symbol resolution is completed with no fatalerrors, the link-editor will start generating the output file image.

The link-editor establishes what additional sections must be generated tocomplete the output file image. These include the symbol tables that containlocal symbol definitions from the input files, together with the global and weaksymbol information that has been collected in its internal symbol table.

Also included are any output relocation and dynamic information sectionsrequired by the runtime linker. Once all the output section information hasbeen established, the total output file size is calculated and the output fileimage is created accordingly.

When building a dynamic executable or shared object, two symbol tables areusually generated. The .dynsym, and its associated string table .dynstr, containonly global, weak and section symbols. These sections become part of the textsegment which is mapped as part of the process image at runtime. This allowsthe runtime linker to read these sections and perform any necessaryrelocations.

$ cc -o lib.so.1 -G lib.o$ nm -x lib.so.1 | egrep “foo$|bar$|str$”[22] |0x000104a4|0x00000004|OBJT |LOCL |0x0 |14 |str[24] |0x000003dc|0x00000028|FUNC |LOCL |0x0 |8 |bar[36] |0x000003b4|0x00000028|FUNC |GLOB |0x0 |8 |foo

$ ld -o lib.o -M mapfile -B reduce -r foo.o bar.o$ nm -x lib.o | egrep “foo$|bar$|str$”[15] |0x00000000|0x00000004|OBJT |LOCL |0x0 |3 |str[16] |0x00000028|0x00000028|FUNC |LOCL |0x0 |1 |bar[20] |0x00000000|0x00000028|FUNC |GLOB |0x0 |1 |foo

Page 57: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 43

2

The .symtab, and its associated string table .strtab, contain all the symbolscollected from the input file processing. These sections are not mapped as partof the process image, and can even be stripped from the image using thelink-editor’s -s option, or after the link-edit using strip(1) .

During the generation of the symbol tables reserved symbols are created. Thesehave special meaning to the linking process and should not be defined in yourcode:

• _etext, the first location after the text segment.

• _edata, the first location after initialized data.

• _end, the first location after all data.

• _DYNAMIC, the address of the dynamic information section (the .dynamicsection).

• _GLOBAL_OFFSET_TABLE_, the position-independent reference to alink-editor supplied table of addresses (the .got section). This table isconstructed from position-independent data references occurring in objectsthat have been compiled with the -K pic option (see “Position-Independent Code” on page 100 for more information).

• _PROCEDURE_LINKAGE_TABLE_, the position-independent reference to alink-editor supplied table of addresses (the .plt section). This table isconstructed from position-independent function references occurring inobjects that have been compiled with the -K pic option (see “Position-Independent Code” on page 100 for more information).

If the link-editor is generating an executable, it will look for additional symbolsto define the executable’s entry point. If a symbol was specified using thelink-editor’s -e option it will be used. Otherwise the link-editor will look forthe reserved symbol names _start , and then main . If none of these symbolsexists, the first address of the text segment will be used.

Having created the output file, all data sections from the input files are copiedto the new image. Any relocations specified in the input files are applied to theoutput image. Any new relocation information that must be generated,together with all the other link-editor generated information, is also written tothe new image.

Page 58: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

44 Linker and Libraries Guide—November 1995

2

Link-Editor Support InterfaceThe link-editor provides a support library interface that allows informationregarding the link-edit to be obtained. This facility provides for input fileinspection, and to some degree, input file data modification of those files thatcomprise a link-edit. You should be intimately familiar with the elf(3E)structures and file format when using this interface.

Invoking the Support Interface

The link-editor will accept one or more support libraries provided by theSGS_SUPPORT environment variable or with the link-editor’s -S option. Theenvironment variable consists of a colon separated list of support libraries:

The -S option specifies a single support library. Multiple -S options can bespecified:

Each support library represents a shared object. The link-editor performs adlopen(3X) on each shared object, in the order they are specified. If both theenvironment variable and -S options are encountered then the shared objectsspecified with the environment variable are processed first. Each supportlibrary is then searched, using dlsym(3X) , for any support interface routines.These support routines are then called at various stages of the link-editingprocess.

By default, the Solaris support library libldstab.so.1 is used by thelink-editor to process compiler generated debugging information containedwithin input relocatable objects. This default processing is suppressed if youinvoke the link-editor with any support libraries specified using the -S option.If this default processing is required in addition to your support libraryservices, then libldstab.so.1 should be explicitly added to the list ofsupport libraries supplied to the link-editor.

$ SGS_SUPPORT=./support.so.1 cc ...

$ ld -S ./support.so.1 -S libldstab.so.1 ...

Page 59: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 45

2

Support Interface Functions

The following interface functions can be provided by a support library. Theseinterfaces are defined in the header file link.h . All interface arguments arebasic C types or ELF types (see elf(3E) ). The ELF data types can be examinedwith the elf access library libelf (see man Pages(3): Library Routines” for adescription of libelf contents).

The function ld_start() is called after the initial pass of the link-editorcommand line. It indicates the output file that will be generated, and flags thestart of input file processing:

name is the output filename being created. etype is the output file type, which iseither ET_DYN, ET_REL, or ET_EXEC (as defined in sys/elf.h ). caller is theapplication calling the interface which in this case is ld .

The function ld_atexit() is called on completion of the link-edit:

status is the exit(2) code that will be returned by the link-editor and is eitherEXIT_FAILURE , or EXIT_SUCCESS (as defined in stdlib.h ).

The function ld_file() is called for each input file processed. The call ismade before any processing of the files data is carried out:

name is the input file about to be processed. kind indicates the input files’ typewhich is either ELF_K_AR, or ELF_K_ELF (as defined in libelf.h ). flagsprovides more detailed information on how the link-editor came aboutobtaining the file and can be either LD_SUP_DERIVED (the file name wasderived from a -l expansion), LD_SUP_INHERITED (the file was obtained as adependency of a command-line shared object), or LD_SUP_EXTRACTED (the file

void ld_start(const char * name, const Elf32_Half etype, const char * caller);

void ld_atexit(int status);

void ld_file(const char * name, const Elf_Kind kind, int flags, Elf * elf);

Page 60: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

46 Linker and Libraries Guide—November 1995

2

was extracted from an archive). If no flags values are specified then the inputfile has been explicitly named on the command-line. elf is a pointer to the filesELF descriptor.

The function ld_section() is called for each section of the input file beforeany processing of the sections data is carried out:

name is the input section name. shdr is a pointer to the associated sectionheader. sndx is the sections index within the input file. data is a pointer to theassociated data buffer. elf is a pointer to the files ELF descriptor.

Modification of the data is permitted by reallocating the data itself andreassigning the Elf_Data buffers d_buf pointer. Any modification to the datashould insure the correct setting of the Elf_Data buffers d_size element. Forinput sections that will become part of the output image, setting the d_sizeelement to zero will effectively remove the data from the output image.

Note – Any sections that are stripped by the use of the link-editors -s optionwill not be reported to any ld_section() routines.

void ld_section(const char * name, Elf32_Shdr * shdr, Elf32_Word sndx, Elf_Data * data, Elf * elf);

Page 61: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 47

2

Support Interface Example

The following example creates a support library that prints the section namesof any relocatable object files processed as part of a link-edit.

$ cat support.c#include <link.h>

static int indent = 0;

voidld_start(const char * name, const Elf32_Half type, const char * caller){ (void) printf(“output image: %s\n”, name);}

voidld_file(const char * name, const Elf_Kind kind, int flags, Elf * elf){ if (flags & LD_SUP_EXTRACTED) indent += 2; else indent = 2;

(void) printf(“%*sfile: %s\n”, indent, ““, name);}

voidld_section(const char * name, Elf32_Shdr * shdr, Elf32_Word sndx, Elf_Data * data, Elf * elf){ Elf32_Ehdr * ehdr = elf32_getehdr(elf);

if (ehdr->e_type == ET_REL) (void) printf(“%*s section [%ld]: %s\n”, indent, ““, sndx, name);}

Page 62: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

48 Linker and Libraries Guide—November 1995

2

This support library is dependent upon libelf to provide the ELF accessfunction elf32_getehdr(3E) which is used to determine the input file type:

The following link-edit shows the section diagnostics resulting from theconstruction of a trivial application from a relocatable object and a localarchive library. The invocation of the support library, in addition to defaultdebugging information processing, is brought about by the -S option usage:

$ cc -o support.so.1 -G -K pic support.c -lelf

$ LD_OPTIONS=-S./support.so.1:libldstab.so.1 cc -o prog main.c \ -L. -lfoooutput image: prog file: /opt/COMPILER/crti.o section [1]: .shstrtab section [2]: .text ....... file: /opt/COMPILER/crt1.o section [1]: .shstrtab section [2]: .text ....... file: /opt/COMPILER/values-xt.o section [1]: .shstrtab section [2]: .text ....... file: main.o section [1]: .shstrtab section [2]: .text ....... file: ./libfoo.a file: ./libfoo.a(foo.o) section [1]: .shstrtab section [2]: .text ....... file: /usr/lib/libc.so file: /opt/COMPILER/crtn.o section [1]: .shstrtab section [2]: .text ....... file: /usr/lib/libdl.so.1

Page 63: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 49

2

Note – The number of sections displayed in this example have been reduced tosimplify the output. Also, the files included by the compiler driver can vary.

Debugging AidsProvided with the Solaris linkers is a debugging library that allows you totrace the link-editing process in more detail. This library helps you understand,or debug, the link-edit of your own applications or libraries. This is a visualaid, and although the type of information displayed using this library isexpected to remain constant, the exact format of the information might changeslightly from release to release.

Some of the debugging output might be unfamiliar if you do not have anintimate knowledge of ELF. However, many aspects can be of general interestto you.

Page 64: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

50 Linker and Libraries Guide—November 1995

2

Debugging is enabled by using the -D option, and all output produced isdirected to the standard error. This option must be augmented with one ormore tokens to indicate the type of debugging required. The tokens availablecan be displayed by using -Dhelp . For example:

Note – The above is an example, and shows the options meaningful to thelink-editor. The exact options might differ from release to release.

As most compiler drivers will interpret the -D option during theirpreprocessing phase, the LD_OPTIONS environment variable is a suitablemechanism for passing this option to the link-editor.

$ ld -Dhelpdebug:debug: For debugging the link-editing of an application:debug: LD_OPTIONS=-Doption1,option2 cc -o prog ...debug: or,debug: ld -Doption1,option2 -o prog ...debug: where placement of -D on the command line is significantdebug: and options can be switched off by prepending with `!’.debug:debug:debug: args display input argument processingdebug: detail provide more information in conjunction with otherdebug: optionsdebug: entry display entrance criteria descriptorsdebug: files display input file processing (files and libraries)debug: help display this help messagedebug: libs display library search paths; detail flag shows actualdebug: library lookup (-l) processingdebug: map display map file processingdebug: reloc display relocation processingdebug: sections display input section processingdebug: segments display available output segments and address/offsetdebug: processing; detail flag shows associated sectionsdebug: support display support library processingdebug: symbols display symbol table processing;debug: detail flag shows resolution and linker table additiondebug: versions display version processing

Page 65: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor 51

2

The following example shows how input files can be traced. This can beespecially useful in determining what libraries have been located, or whatrelocatable objects have been extracted from an archive during a link-edit:

Here the member foo.o is extracted from the archive library libfoo.a tosatisfy the link-edit of prog . Notice that the archive is searched twice (again) toverify that the extraction of foo.o did not warrant the extraction of additionalrelocatable objects. More than one “again” display indicates that the archive isa candidate for ordering using lorder(1) and tsort(1) .

By using the symbols token you can determine what symbol caused anarchive member to be extracted, and which object made the initial symbolreference:

Here the symbol foo is referenced by main.o and is added to the link-editor’sinternal symbol table. This symbol reference causes the extraction of therelocatable object foo.o from the archive libfoo.a .

Note – The above output has been simplified for this document.

$ LD_OPTIONS=-Dfiles cc -o prog main.o -L. -lfoo............debug: file=main.o [ ET_REL ]debug: file=./libfoo.a [ archive ]debug: file=./libfoo.a(foo.o) [ ET_REL ]debug: file=./libfoo.a [ archive ] (again)............

$ LD_OPTIONS=-Dsymbols cc -o prog main.o -L. -lfoo............debug: symbol table processing; input file=main.o [ ET_REL ]............debug: symbol[7]=foo (global); addingdebug:debug: symbol table processing; input file=./libfoo.a [ archive ]debug: archive[0]=bardebug: archive[1]=foo (foo.o) resolves undefined or tentative symboldebug:debug: symbol table processing; input file=./libfoo(foo.o) [ ET_REL ].............

Page 66: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

52 Linker and Libraries Guide—November 1995

2

By using the detail token together with the symbols token, the details ofsymbol resolution during input file processing can be observed:

Here, the original undefined symbol foo from main.o has been overriddenwith the symbol definition from the extracted archive member foo.o . Thedetailed symbol information reflects the attributes of each symbol.

From the above example, it should be apparent that using some of thedebugging tokens can produce a wealth of output. In cases where areinterested only in the activity around a subset of the input files, the -D optioncan be placed directly in the link-edit command-line, and toggled on and off.For example:

Here the display of symbol processing will be switched on only during theprocessing of the library libbar .

Note – To obtain the link-edit command-line it might be necessary to expandthe compilation line from any driver being used. See “Using a CompilerDriver” on page 9 for more details.

$ LD_OPTIONS=-Dsymbols,detail cc -o prog main.o -L. -lfoo............debug: symbol table processing; input file=main.o [ ET_REL ]............debug: symbol[7]=foo (global); addingdebug: entered 0x000000 0x000000 NOTY GLOB UNDEF REF_REL_NEEDdebug:debug: symbol table processing; input file=./libfoo.a [ archive ]debug: archive[0]=bardebug: archive[1]=foo (foo.o) resolves undefined or tentative symboldebug:debug: symbol table processing; input file=./libfoo.a(foo.o) [ ET_REL ]debug: symbol[1]=foo.c.............debug: symbol[7]=bar (global); addingdebug: entered 0x000000 0x000004 OBJT GLOB 3 REF_REL_NEEDdebug: symbol[8]=foo (global); resolving [7][0]debug: old 0x000000 0x000000 NOTY GLOB UNDEF main.odebug: new 0x000000 0x000024 FUNC GLOB 2 ./libfoo.a(foo.o)debug: resolved 0x000000 0x000024 FUNC GLOB 2 REF_REL_NEED

$ ld .... -o prog main.o -L. -Dsymbols -lbar -D!symbols ....

Page 67: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

53

Runtime Linker 3

OverviewAs part of the initialization and execution of a dynamic executable, an interpreteris called to complete the binding of the application to its shared objectdependencies. In Solaris this interpreter is referred to as the runtime linker.

During the link-editing of a dynamic executable, a special .interp section,together with an associated program header, are created. This section containsa pathname specifying the program’s interpreter. The default name suppliedby the link-editor is that of the runtime linker - /usr/lib/ld.so.1 .

During the process of executing a dynamic executable (see exec(2) ) thekernel maps the file (see mmap(2) ), and using the program header information(see “Program Header” on page 189), locates the name of the requiredinterpreter. The kernel maps this interpreter and transfers control to it, passingsufficient information to allow the interpreter to continue binding theapplication and then run it.

In addition to initializing an application the runtime linker provides servicesthat allow the application to extend its address space by mapping additionalshared objects and binding to symbols within them.

The following is a simple breakdown of the runtime linkers functionality, andintroduces the topics covered in this chapter:

• It analyzes the executable’s dynamic information section (.dynamic) anddetermines what shared object dependencies are required.

Page 68: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

54 Linker and Libraries Guide—November 1995

3

• It locates and maps in these dependencies, and analyzes their dynamicinformation sections to determine if any additional shared objectdependencies are required.

• Once all shared object dependencies are located and mapped, the runtimelinker performs any necessary relocations to bind these objects inpreparation for process execution.

• It calls any initialization functions provided by the shared objectdependencies.

• It passes control to the application.

• During the application’s execution, the runtime linker can be called upon toperform any delayed function binding.

• The application can also call upon the runtime linker’s services to acquireadditional shared objects by dlopen(3X) , and bind to symbols within theseobjects with dlsym(3X) .

Locating Shared Object DependenciesUsually, during the link-edit of a dynamic executable, one or more sharedobjects are explicitly referenced. These shared objects are recorded asdependencies within the dynamic executable (see “Shared Object Processing”on page 13 for more information).

The runtime linker first locates this dependency information and uses it tolocate and map the associated shared objects. These shared objectdependencies are processed in the same order as they were referenced duringthe link-edit of the executable.

Once all the dynamic executable’s dependencies are mapped, they too areinspected, in the order they are mapped, to locate any additional shared objectdependencies. This process continues until all dependent shared objects arelocated and mapped. This technique results in a breadth-first ordering of alldependent shared objects.

Page 69: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 55

3

Directories Searched by the Runtime Linker

The runtime linker knows of only one standard place to look for shared objectdependencies, /usr/lib . Any dependency specified as a simple filename willbe prefixed with this default directory name and the resulting pathname willbe used to locate the actual file.

The actual shared object dependencies of any dynamic executable or sharedobject can be displayed using ldd(1) . For example, the file /usr/bin/cathas the following dependencies:

Here, the file /usr/bin/cat has a dependency, or needs, the fileslibintl.so.1 , libw.so.1 , libc.so.1 and libdl.so.1 .

The shared object dependencies actually recorded in a file can be inspected byusing the dump(1) command to display the file’s .dynamic section, andreferencing any entries that have a NEEDED tag. For example:

Notice that the dependency libdl.so.1 , displayed in the previous ldd(1)example, is not recorded in the file /usr/bin/cat . This is because ldd(1)shows the total dependencies of the specified file, and libdl.so.1 is actuallya dependency of /usr/lib/libc.so.1 .

$ ldd /usr/bin/cat libintl.so.1 => /usr/lib/libintl.so.1 libw.so.1 => /usr/lib/libw.so.1 libc.so.1 => /usr/lib/libc.so.1 libdl.so.1 => /usr/lib/libdl.so.1

$ dump -Lvp /usr/bin/cat

/usr/bin/cat:[INDEX] Tag Value[1] NEEDED libintl.so.1[2] NEEDED libw.so.1[3] NEEDED libc.so.1.........

Page 70: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

56 Linker and Libraries Guide—November 1995

3

In the previous dump(1) example the dependencies are expressed as simplefilenames - in other words there is no ‘/’ in the name. The use of a simplefilename requires the runtime linker to build the required pathname from a setof rules. Filenames that contain an embedded ‘/’ will be used as-is.

The simple filename recording is the standard, most flexible mechanism ofrecording dependencies, and is provided by using the -l option of thelink-editor (see “Linking with Additional Libraries” on page 14, and “NamingConventions” on page 84 for additional information on this topic).

Frequently, shared objects are distributed in a directory other than /usr/lib .If a dynamic executable or shared object needs to locate dependencies inanother directory, the runtime linker must explicitly be told to search thisdirectory.

The recommended way to indicate additional search paths to the runtimelinker is to record a runpath during the link-edit of the dynamic executable orshared object (see “Directories Searched by the Runtime Linker” on page 18 fordetails on recording this information).

Any runpath recording can be displayed using dump(1) and referring to theentry that has the RPATH tag. For example:

Here, prog has a dependency on libfoo.so.1 and requires the runtimelinker to search directories /home/me/lib and /home/you/lib before itlooks in the default location /usr/lib .

Another way to add to the runtime linker’s search path is to set theenvironment variable LD_LIBRARY_PATH. This environment variable (which isanalyzed once at process startup) can be set to a colon-separated list ofdirectories, and these directories will be searched by the runtime linker before

$ dump -Lvp prog

prog:[INDEX] Tag Value[1] NEEDED libfoo.so.1[2] NEEDED libc.so.1[3] RPATH /home/me/lib:/home/you/lib.........

Page 71: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 57

3

any runpath specification or default directory. This environment variable iswell suited for debugging purposes such as forcing an application to bind to alocal shared object. For example:

Here the file prog from the previous example will be bound to libfoo.so.1found in the present working directory.

Although useful as a temporary mechanism of influencing the runtime linker’ssearch path, the use of this environment variable is strongly discouraged inproduction software. Any dynamic executables that can reference thisenvironment variable will have their search paths augmented, which can resultin an overall degradation in performance. Also, as pointed out in “Using anEnvironment Variable” on page 17, and “Directories Searched by the RuntimeLinker” on page 18, this environment variable affects the link-editor.

If a shared object dependency cannot be located, ldd(1) will indicate that theobject cannot be found, and any attempt to execute the application will resultin an appropriate error message from the runtime linker:

Note – Any runtime linker error that results from the failure of an underlyingsystem call will result in the system error code value being displayed as part ofthe associated diagnostic message. This value can be interpreted more fully byreferencing /usr/include/sys/errno.h .

Relocation ProcessingOnce the runtime linker has located and mapped all the shared objectdependencies required by an application, it then processes each object andperforms any necessary relocations.

$ LD_LIBRARY_PATH=. prog

$ ldd prog libfoo.so.1 => (not found) libc.so.1 => /usr/lib/libc.so.1 libdl.so.1 => /usr/lib/libdl.so.1$ progld.so.1: prog: fatal: libfoo.so.1: can’t open file: errno=2

Page 72: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

58 Linker and Libraries Guide—November 1995

3

During the link-editing of an object, any relocation information supplied withthe input relocatable objects is applied to the output file. However, whenbuilding a dynamic executable or shared object, many of the relocations cannotbe completed at link-edit time because they require logical addresses that areknown only when the objects are mapped into memory. In these cases thelink-editor generates new relocation records as part of the output file image,and it is this information that the runtime linker must now process.

For a more detailed description of the many relocation types, see “RelocationTypes (Processor Specific)” on page 170. However, for the purposes of thisdiscussion it is convenient to categorize relocations into one of two types:

• Non-symbolic relocations.

• Symbolic relocations.

The relocation records for an object can be displayed by using dump(1) . Forexample:

Here, the file libbar.so.1 contains two relocation records that indicate thatthe global offset table (the .got section) must be updated.

The first relocation is a simple relative relocation that can be seen from itsrelocation type and from the fact that the symbol index (Symndx) field is zero.This relocation needs to use the base address at which the object was mappedinto memory to update the associated .got offset.

The second relocation requires the address of the symbol foo . To complete thisrelocation the runtime linker must locate this symbol from the dynamicexecutable or shared objects that have so far been mapped.

$ dump -rvp libbar.so.1

libbar.so.1:

.rela.got:Offset Symndx Type Addend

0x10438 0 R_SPARC_RELATIVE 00x1043c foo R_SPARC_GLOB_DAT 0

Page 73: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 59

3

Symbol Lookup

When the runtime linker looks up a symbol, it does so by searching in eachobject, starting with the dynamic executable, and progressing through eachshared object in the same order in which the objects were mapped.

As discussed in previous sections, ldd(1) will list the shared objectdependencies of a dynamic executable in the order in which they are mapped.Therefore, if the shared object libbar.so.1 requires the address of symbolfoo to complete its relocation, and this shared object is a dependency of thedynamic executable prog:

Then, the runtime linker will first look for foo in the dynamic executableprog , then in the shared object /home/me/lib/libfoo.so.1 , and finally inthe shared object /home/me/lib/libbar.so.1 .

Note – Symbol lookup can be an expensive operation, especially as the size ofsymbol names increases, and the numbers of shared object dependenciesincrease. This aspect of performance is discussed in more detail in“Performance Considerations” on page 96.

Interposition

The runtime linkers mechanism of searching for a symbol first in the dynamicexecutable and then in each of the shared object dependencies means that thefirst occurrence of the required symbol will satisfy the search. Therefore, ifmore than one instance of the same symbol exists, the first instance willinterpose on all others.

$ ldd prog libfoo.so.1 => /home/me/lib/libfoo.so.1 libbar.so.1 => /home/me/lib/libbar.so.1

Page 74: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

60 Linker and Libraries Guide—November 1995

3

When Relocations are Performed

Having briefly described the relocation process, together with thesimplification of relocations into the two types, non-symbolic and symbolic, itis also useful to distinguish relocations by when they are performed. Thisdistinction arises due to the type of reference being made to the relocated offset,and can be either:

• A data reference.

• A function reference.

A data reference refers to an address that is used as a data item by theapplication code. The runtime linker has no knowledge of the application code,and so does not know when this data item will be referenced. Therefore, alldata relocations must be carried out during process initialization, before theapplication gains control.

A function reference refers to the address of a function that will be called by theapplication code. During the compilation and link-editing of any dynamicmodule, calls to global functions are relocated to become calls to a procedurelinkage table entry (these entries make up the .plt section).

These .plt entries are constructed so that when first called control is passed tothe runtime linker. The runtime linker will look up the required symbol andrewrite information in the application so that any future calls to this .plt entrywill go directly to the function.This mechanism allows relocations of this typeto be deferred until the first instance of a function being called, a process that issometimes referred to as lazy binding.

The runtime linker’s default mode of performing lazy binding can beoverridden by setting the environment variable LD_BIND_NOW to any non-nullvalue. This environment variable setting causes the runtime linker to performboth data reference and function reference relocations during processinitialization, before transferring control to the application. For example:

Here, all relocations within the file prog and within its shared objectdependencies will be processed before control is transferred to the application.

$ LD_BIND_NOW=yes prog

Page 75: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 61

3

Relocation Errors

The most common relocation error occurs when a symbol cannot be found.This condition will result in an appropriate runtime linker error message andthe termination of the application. For example:

Here the symbol bar , which is referenced in the file libfoo.so.1 , can not belocated.

Note – During the link-edit of a dynamic executable any potential relocationerrors of this sort will be flagged as fatal undefined symbols (see “Generatingan Executable” on page 28 for examples). This runtime relocation error canoccur if the link-edit of main used a different version of the shared objectlibbar.so.1 that contained a symbol definition for bar , or if the -z nodefsoption was used as part of the link-edit.

If a relocation error of this type occurs because a symbol used as a datareference cannot be located, the error condition will occur immediately duringprocess initialization. However, because of the default mode of lazy binding, ifa symbol used as a function reference cannot be found, the error condition willoccur after the application has gained control.

This latter case can take minutes or months, or might never occur, dependingon the execution paths exercised throughout the code. To guard against errorsof this kind, the relocation requirements of any dynamic executable or sharedobject can be validated using ldd(1) .

$ ldd prog libfoo.so.1 => ./libfoo.so.1 libc.so.1 => /usr/lib/libc.so.1 libbar.so.1 => ./libbar.so.1 libdl.so.1 => /usr/lib/libdl.so.1$ progld.so.1: prog: fatal: relocation error: symbol not found: bar: \referenced in ./libfoo.so.1

Page 76: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

62 Linker and Libraries Guide—November 1995

3

When the -d option is specified with ldd(1) , all shared object dependencieswill be printed and all data reference relocations will be processed. If a datareference cannot be resolved, a diagnostic message will be produced. From theprevious example this reveals:

When the -r option is specified with ldd(1) , all data and function referencerelocations will be processed, and if either cannot be resolved a diagnosticmessage will be produced.

Loading Additional ObjectsThe previous sections have described how the runtime linker initializes aprocess from the dynamic executable and its shared object dependencies asthey were defined during the link-editing of each module. The runtime linkeralso provides an additional level of flexibility by allowing you to introducenew objects during process initialization.

The environment variable LD_PRELOAD can be initialized to a shared object orrelocatable object filename, or a string of filenames separated by white space.These objects are mapped after the dynamic executable and before any sharedobject dependencies. For example:

$ ldd -d prog libfoo.so.1 => ./libfoo.so.1 libc.so.1 => /usr/lib/libc.so.1 libbar.so.1 => ./libbar.so.1 libdl.so.1 => /usr/lib/libdl.so.1 symbol not found: bar (./libfoo.so.1)

$ LD_PRELOAD=./newstuff.so.1 prog

Page 77: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 63

3

Here the dynamic executable prog will be mapped, followed by the sharedobject newstuff.so.1 , and then by the shared object dependencies definedwithin prog . The order in which these objects are processed can be displayedusing ldd(1) :

Another example is:

Here the preloading is a little more complex and time consuming. The runtimelinker first link-edits the relocatable objects foo.o and bar.o to generate ashared object that is maintained in memory. This memory image is theninserted between the dynamic executable and the normal shared objectdependencies in exactly the same manner as the shared objectnewstuff.so.1 was preloaded in the previous example. Again, the order inwhich these objects are processed can be displayed with ldd(1) :

These mechanisms of inserting a shared object after a dynamic executable takethe concept of interposition, introduced on page 59, to another level. Using thesemechanisms, it is possible to experiment with a new implementation of afunction that resides in a standard shared object. By preloading just thatfunction it will interpose on the original. Thus the old functionality can becompletely hidden with the new preloaded version.

Another use of preloading is to augment a function that resides in a standardshared object. Here the intention is to have the new symbol interpose on theoriginal, allowing the new function to carry out some additional processing,while still having it call through to the original function. This mechanism

$ LD_PRELOAD=./newstuff.so.1 ldd prog ./newstuff.so.1 => ./newstuff.so libc.so.1 => /usr/lib/libc.so.1

$ LD_PRELOAD=”./foo.o ./bar.o” prog

$ LD_PRELOAD=”./foo.o ./bar.o” ldd prog ./foo.o => ./foo.o ./bar.o => ./bar.o libc.so.1 => /usr/lib/libc.so.1

Page 78: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

64 Linker and Libraries Guide—November 1995

3

requires either a symbol alias to be associated with the original function (see“Simple Resolutions” on page 22), or the ability to look up the originalsymbol’s address (see “Using Interposition” on page 75).

Initialization and Termination RoutinesBefore transferring control to the application, the runtime linker processes anyinitialization (.init) and termination (.fini) sections found in any of the sharedobject dependencies. These sections, and the symbols that describe them, werecreated during the link-editing of the shared objects (see “Initialization andTermination Sections” on page 19).

Any initialization routines for shared object dependencies are called in reverseload order - in other words, the reverse order of the shared objects displayedwith ldd(1) .

Any termination routines for shared object dependencies are organized suchthat they can be recorded by atexit(3C) . Termination routines are thereforecalled in load order when the process calls exit(2) .

Although this initialization and termination calling sequence seems quitestraightforward, be careful about placing too much emphasis on this sequence,as the ordering of shared objects can be affected by both shared object andapplication development (see “Dependency Ordering” on page 90 for moredetails).

Note – Any .init or .fini sections within the dynamic executable are called fromthe application itself by the process start-up and termination mechanismsupplied by the compiler driver. The dynamic executable’s .init section is calledlast, after all the shared object dependency’s .init sections are executed. Thedynamic executable’s .fini section is called first, before the shared objectdependency’s .fini sections are executed.

SecuritySecure processes have some restrictions applied to the evaluation of theirdependencies to prevent malicious dependency substitution or symbolinterposition.

Page 79: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 65

3

The runtime linker categorizes a process as secure if the user is not the root,and either the real users and effective users identifiers are not equal (seegetuid(2) and geteuid(2) ), or the real group and effective groupidentifiers are not equal (see getgid(2) and getegid(2) ).

If an LD_LIBRARY_PATH environment variable is in effect (see “DirectoriesSearched by the Runtime Linker” on page 55) for a secure process, then onlythe trusted directories specified by this variable will be used to augment theruntime linker’s search rules. Presently, the only trusted directory known tothe runtime linker is /usr/lib .

In a secure process, any runpath specifications provided by the application orany of it’s dependencies (see “Directories Searched by the Runtime Linker” onpage 55), will be used provided they are full pathnames - in other words thepathname starts with a ‘/’.

Additional objects may be loaded with a secure process using the LD_PRELOADenvironment variable (see “Loading Additional Objects” on page 67) providedthe objects are specified as simple filenames - in other words there is no ‘/’ inthe name. These objects will be located subject to the search path restrictionspreviously described.

In a secure process, any dependencies that consist of simple filenames will beprocessed using the pathname restrictions outlined above. Dependencies thatare expressed as full or relative pathnames will be used as is. Therefore, thedeveloper of a secure process should insure that the target directory referencedas a full or relative pathname dependency is suitably protected from maliciousintrusion.

When creating a secure process, it is recommended that relative pathnames notbe used to express dependencies or to construct dlopen(3x) pathnames. Thisrestriction should be applied to the application and to all dependencies.

Runtime Linking Programming InterfaceThe previous discussions described how the shared object dependenciesspecified during the link-edit of an application are processed by the runtimelinker during process initialization. In addition to this mechanism, theapplication can extend its address space during its execution by binding toadditional shared objects. This extensibility is provided by allowing the

Page 80: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

66 Linker and Libraries Guide—November 1995

3

application to request the same services of the runtime linker as used toprocess the shared object’s dependencies specified during the link-edit of theapplication.

This delayed object binding has several advantages:

• By processing a shared object when it is required rather than during theinitialization of an application, start-up time can be greatly reduced. In fact,the shared object might not be required if its services are not needed duringa particular run of the application, such as for help or debugginginformation.

• The application can choose between several different shared objectsdepending on the exact services required, such as for a networking protocol.

• Any shared objects added to the process address space during execution canbe freed after use.

The following is a typical scenario that an application can perform to access anadditional shared object, and introduces the topics covered in the next sections:

• A shared object is located and added to the address space of a runningapplication using dlopen(3X) . Any dependencies this shared object has arelocated and added at this time.

• The shared object(s) added are relocated, and any initialization sectionswithin the new shared object(s) are called.

• The application locates symbols within the added shared object(s) usingdlsym(3X) . The application can then reference the data or call the functionsdefined by these new symbols.

• After the application has finished with the shared object(s) the addressspace can be freed using dlclose(3X) . Any termination sections withinthe shared object(s) being freed will be called at this time.

• Any error conditions that occur as a result of using these runtime linkerinterface routines can be displayed using dlerror(3X) .

The services of the runtime linker are defined in the header file dlfcn.h andare made available to an application by the shared object libdl.so.1 . Forexample:

$ cc -o prog main.c -ldl

Page 81: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 67

3

Here the file main.c can make reference to any of the dlopen(3X) family ofroutines, and the application prog will be bound to these routines at runtime.

Loading Additional Objects

Additional shared objects can be added to a running process’s address spaceusing dlopen(3X) . This function takes a filename and a binding mode asarguments, and returns a handle to the application. This handle can be used tolocate symbols for use by the application using dlsym(3X) .

If the filename is specified as a simple filename - in other words, there is no ‘/’in the name, then the runtime linker will use a set of rules to build anappropriate pathname. Filenames that contain a ‘/’ will be used as-is.

These search path rules are exactly the same as are used to locate any initialshared object dependencies (see “Directories Searched by the Runtime Linker”on page 55). For example, if the file main.c contains the following codefragment:

then to locate the shared object foo.so.1 , the runtime linker will use anyLD_LIBRARY_PATH definition present at process initialization, followed by anyrunpath specified during the link-edit of prog , and finally the default location/usr/lib .

#include <stdio.h>#include <dlfcn.h>

main(int argc, char ** argv){ void * handle; .....

if ((handle = dlopen(“foo.so.1”, RTLD_LAZY)) == NULL) { (void) printf(“dlopen: %s\n”, dlerror()); exit (1); } .....

Page 82: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

68 Linker and Libraries Guide—November 1995

3

If the filename is specified as:

then the runtime linker will search for the file only in the present workingdirectory.

Note – It is recommended that any shared object specified using dlopen(3X)be referenced by its versioned filename (for more information on versioning see“Coordination of Versioned Filenames” on page 136).

If the required shared object cannot be located, dlopen(3X) will return aNULL handle. In this case dlerror(3X) can be used to display the true reasonfor the failure. For example:

The errno value can be referenced in /usr/include/sys/errno.h .

If the shared object being added by dlopen(3X) has dependencies on othershared objects, they too will be brought into the process’s address space.

If the shared object specified by dlopen(3X) , or any of its dependencies, arealready part of the process image, then the shared objects will not be processedany further, but a valid handle will still be returned to the application. Thismechanism prevents the same shared object from being mapped more thanonce, and allows an application to obtain a handle to itself. For example, if themain.c example contained the following code:

then the handle returned from dlopen(3X) can be used to locate symbolswithin the application itself, within any of the shared object dependenciesloaded as part of the process’s initialization, or within any objects added to theprocess’s address space using a dlopen(3X) that specified the RTLD_GLOBALflag.

if ((handle = dlopen(“./foo.so.1”, RTLD_LAZY)) == NULL) {

$ cc -o prog main.c -ldl$ progdlopen: ld.so.1: prog: fatal: foo.so.1: can’t open file: errno=2

if ((handle = dlopen((const char *)0, RTLD_LAZY)) == NULL) {

Page 83: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 69

3

Relocation Processing

As described in “Relocation Processing” on page 57, after locating andmapping any shared objects, the runtime linker must process each object andperform any necessary relocations. Any shared objects brought into theprocess’s address space with dlopen(3X) must also be relocated in the samemanner.

For simple applications this process might be quite uninteresting. However, forusers who have more complex applications with many dlopen(3X) callsinvolving many shared objects, possibly with common dependencies, this topiccan be quite important.

Relocations can be categorized according to when they occur. The defaultbehavior of the runtime linker is to process all data reference relocations atinitialization and all function references during process execution, amechanism commonly referred to as lazy binding.

This same mechanism is applied to any shared objects added withdlopen(3X) when the mode is defined as RTLD_LAZY. An alternative is torequire all relocations of a shared object to be performed immediately whenthe shared object is added, and this can be achieved by using a mode ofRTLD_NOW.

Relocations can also be categorized into non-symbolic and symbolic. Theremainder of this section covers issues regarding symbolic relocations,regardless of when these relocations occur, with a focus on some of thesubtleties of symbol lookup.

Symbol Lookup

If a shared object acquired by dlopen(3X) refers to a global symbol, theruntime linker will locate this symbol in the same manner as any other symbollookup.

The runtime linker will first look in the dynamic executable, and then look ineach of the shared objects provided during the initialization of the process.However, if the symbol is still not found, the runtime linker will continue thesearch, looking in the shared object acquired through the dlopen(3X) and inany of its dependencies.

Page 84: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

70 Linker and Libraries Guide—November 1995

3

For example, let’s take the dynamic executable prog , and the shared objectB.so.1 , each of which has the following (simplified) dependencies:

If prog acquires the shared object B.so.1 by dlopen(3X) , then any symbolrequired to relocate the shared objects B.so.1 and C.so.1 will first be lookedfor in prog , followed by A.so.1 , followed by B.so.1 , and finally in C.so.1 .

In this simple case, it might be easier to think of the shared objects acquiredthrough the dlopen(3X) as if they had been added to the end of the originallink-edit of the application. For example, the objects referenced above can beexpressed diagrammatically:

Figure 3-1 A Single dlopen(3X) Request

Any symbol lookup required by the objects acquired from the dlopen(3X) ,shown as shaded blocks, will proceed from the dynamic executable progthrough to the final shared object C.so.1 .

Note – Objects added to the process address space do not affect the normalsymbol lookup required by either the application or its initial shared objectdependencies. For example, if A.so.1 requires a function relocation after theabove dlopen(3X) has occurred, the runtime linker’s normal search for therelocation symbol will be to look in prog and then A.so.1 , but not to followthrough and look in B.so.1 or C.so.1 .

$ ldd prog A.so.1 => ./A.so.1$ ldd B.so.1 C.so.1 => ./C.so.1

prog A.so.1 B.so.1 C.so.1

Page 85: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 71

3

This symbol lookup algorithm is established by assigning lookup scopes to eachobject. These scopes maintain associations between objects based on theirintroduction into the process address space, and on any dependencyrelationships between the objects.

All objects obtained during the process’s initialization are assigned a globalscope. Any object within the global scope can be used by any other object toprovide symbols for relocation.

The shared objects associated with a given dlopen(3X) are assigned a uniquelocal scope that insures that only objects associated with the same dlopen(3X)are allowed to look up symbols within themselves and their relateddependencies.

This concept of defining associations between objects becomes more clear inapplications that carry out more than one dlopen(3X) . For example, if theshared object D.so.1 has the following dependency:

and the prog application was to dlopen(3X) this shared object in addition to theshared object B.so.1 , then diagrammatically the symbol lookup relationshipbetween the objects can be represented as:

Figure 3-2 Multiple dlopen(3X) Requests

$ ldd D.so.1 E.so.1 => ./E.so.1

prog A.so.1

C.so.1B.so.1

D.so.1 E.so.1

Page 86: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

72 Linker and Libraries Guide—November 1995

3

If both B.so.1 and D.so.1 contain a definition for the symbol foo , and bothC.so.1 and E.so.1 contain a relocation that requires this symbol, thenbecause of the association of objects defined by the runtime linker, C.so.1 willbe bound to the definition in B.so.1 , and E.so.1 will be bound to thedefinition in D.so.1 . This mechanism is intended to provide the most intuitivebinding of shared objects obtained from multiple calls to dlopen(3X) .

When shared objects are used in the scenarios that have so far been described,the order in which each dlopen(3X) occurs has no effect on the resultingsymbol binding. However, when shared objects have common dependenciesthe resultant bindings can be affected by the order in which the dlopen(3X)calls are made.

Take for example the shared objects O.so.1 and P.so.1 , which have the samecommon dependency:

In this example, the prog application will dlopen(3X) each of these sharedobjects. Because the shared object Z.so.1 is a common dependency of bothO.so.1 and P.so.1 it will be assigned both of the local scopes that are associatedwith the two dlopen(3X) calls. Diagrammatically this can be represented as:

Figure 3-3 Multiple dlopen(3X) Requests With A Common Dependency

$ ldd O.so.1 Z.so.1 => ./Z.so.1$ ldd P.so.1 Z.so.1 => ./Z.so.1

prog A.so.1

O.so.1

P.so.1

Z.so.1

Page 87: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 73

3

The result is that Z.so.1 will be available for both O.so.1 and P.so.1 tolook up symbols, but more importantly, as far as dlopen(3X) ordering isconcerned, Z.so.1 will also be able to look up symbols in both O.so.1 andP.so.1 .

Therefore, if both O.so.1 and P.so.1 contain a definition for the symbol foowhich is required for a Z.so.1 relocation, the actual binding that occurs isunpredictable because it will be affected by the order of the dlopen(3X) calls.If the functionality of symbol foo differs between the two shared objects inwhich it is defined, the overall outcome of executing code within Z.so.1might vary depending on the application’s dlopen(3x) ordering.

There is one final convolution involving the mode of a dlopen(3X) . Allprevious examples have revolved around the shared objects obtained by adlopen(3X) each having a unique local scope, or a combination of localscopes if a shared object is a common dependency. It is also possible to give ashared object a global scope by augmenting the mode argument with theRTLD_GLOBAL flag. Under this mode, any shared objects obtained through adlopen(3X) can be used by any other objects to locate symbols.

In addition, any object obtained by dlopen(3X) with the RTLD_GLOBAL flagwill also be available for symbol lookup using dlopen(0) (see “LoadingAdditional Objects” on page 67).

Obtaining New Symbols

A process can obtain the address of a specific symbol using dlsym(3X) . Thisfunction takes a handle and a symbol name, and returns the address of thesymbol to the caller. The handle directs the search for the symbol in thefollowing manner:

• The handle returned from a dlopen(3X) of a named shared object will allowsymbols to be obtained from that shared object, or from any of itsdependencies.

• The handle returned from a dlopen(3X) of a file whose value is 0 will allowsymbols to be obtained from the dynamic executable, from any of itsinitialization dependencies, or from any object obtained by a dlopen(3X)with the RTLD_GLOBAL mode.

• The special handle RTLD_NEXT will allow symbols to be obtained from thenext associated shared object.

Page 88: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

74 Linker and Libraries Guide—November 1995

3

The first example is probably the most common. Here an application will addadditional shared objects to its address space and use dlsym(3X) to locatefunction or data symbols. The application then uses these symbols to call uponservices provided in these new shared objects. For example, let’s take the filemain.c that contains the following code:

Here the symbols foo and bar will be searched for in the file foo.so.1followed by any shared object dependencies that are associated with this file.The function foo is then called with the single argument bar as part of thereturn statement.

If the application prog is built using the above file main.c , and its initialshared object dependencies are:

#include <stdio.h>#include <dlfcn.h>

main(){ void * handle; int * dptr, (* fptr)();

if ((handle = dlopen(“foo.so.1”, RTLD_LAZY)) == NULL) { (void) printf(“dlopen: %s\n”, dlerror()); exit (1); }

if (((fptr = (int (*)())dlsym(handle, “foo”)) == NULL) || ((dptr = (int *)dlsym(handle, “bar”)) == NULL)) { (void) printf(“dlsym: %s\n”, dlerror()); exit (1); }

return ((*fptr)(*dptr));}

$ ldd prog libdl.so.1 => /usr/lib/libdl.so.1 libc.so.1 => /usr/lib/libc.so.1

Page 89: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 75

3

then if the filename specified in the dlopen(3X) had the value 0, the symbolsfoo and bar will be searched for in prog , followed by/usr/lib/libdl.so.1 , and finally /usr/lib/libc.so.1 .

Once the handle has indicated the root at which to start a symbol search, thesearch mechanism follows the same model as was described in “SymbolLookup” on page 59.

If the required symbol cannot be located, dlsym(3X) will return a NULL value.In this case dlerror(3X) can be used to indicate the true reason for thefailure. For example;

Here the application prog was unable to locate the symbol bar .

Using Interposition

The special handle RTLD_NEXT allows an application to locate the next symbolin a symbol scope. For example, if the application prog contained thefollowing code fragment:

then foo will be searched for in the shared objects associated with prog , inthis case, /usr/lib/libdl.so.1 and then /usr/lib/libc.so.1 . If thiscode fragment was contained in the file B.so.1 from the example shown inFigure 3-2 on page 71, then foo will be searched for in the associated sharedobject C.so.1 only.

$ progdlsym: ld.so.1: main: fatal: dlsym: can’t find symbol bar

if ((fptr = (int (*)())dlsym(RTLD_NEXT, “foo”)) == NULL) { (void) printf(“dlsym: %s\n”, dlerror()); exit (1); }

return ((*fptr)());

Page 90: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

76 Linker and Libraries Guide—November 1995

3

Using RTLD_NEXT provides a means to exploit symbol interposition. Forexample, a shared object function can be interposed upon by a precedingshared object, which can then augment the processing of the original function.If the following code fragment is placed in the shared object malloc.so.1 :

Then by interposing this shared object between the system library/usr/lib/libc.so.1 where malloc(3C) usually resides, any calls to thisfunction will be interposed on before the original function is called to completethe allocation:

#include <sys/types.h>#include <dlfcn.h>#include <stdio.h>

void *malloc(size_t size){ static void * (* fptr)() = 0; char buffer[50];

if (fptr == 0) { fptr = (void * (*)())dlsym(RTLD_NEXT, “malloc”); if (fptr == NULL) { (void) printf(“dlopen: %s\n”, dlerror()); return (0); } }

(void) sprintf(buffer, “malloc: %#x bytes\n”, size); (void) write(1, buffer, strlen(buffer)); return ((*fptr)(size));}

$ cc -o malloc.so.1 -G -K pic malloc.c$ cc -o prog file1.o file2.o ..... -R. malloc.so.1$ progmalloc: 0x32 bytesmalloc: 0x14 bytes..........

Page 91: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 77

3

Alternatively, this same interposition can be achieved by:

Note – Users of any interposition technique must be careful to handle anypossibility of recursion. The previous example formats the diagnostic messageusing sprintf(3S) , instead of using printf(3S) directly, to avoid anyrecursion caused by printf(3S) ’s use of malloc(3C) .

The use of RTLD_NEXT within a dynamic executable or preloaded shared objectprovides a predictable and useful interpositioning technique. However, careshould be taken when using this technique in a generic shared objectdependency, as the actual load order of shared objects is not always predictable(see “Dependency Ordering” on page 90).

Debugging AidsProvided with the Solaris linkers is a debugging library that allows you totrace the runtime linking process in more detail. This library helps youunderstand, or debug, the execution of applications or libraries. This is a visualaid, and although the type of information displayed using this library isexpected to remain constant, the exact format of the information might changeslightly from release to release.

Some of the debugging output might be unfamiliar to those who do not havean intimate knowledge of the runtime linker. However, many aspects can be ofgeneral interest to you.

Debugging is enabled by using the environment variable LD_DEBUG. Alldebugging output is prefixed with the process identifier and by default isdirected to the standard error. This environment variable must be augmentedwith one or more tokens to indicate the type of debugging required.

$ cc -o malloc.so.1 -G -K pic malloc.c$ cc -o prog main.c$ LD_PRELOAD=./malloc.so.1 progmalloc: 0x32 bytesmalloc: 0x14 bytes..........

Page 92: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

78 Linker and Libraries Guide—November 1995

3

The tokens available with this debugging option can be displayed by usingLD_DEBUG=help. Any dynamic executable can be used to solicit thisinformation, as the process itself will terminate following the display of theinformation. For example:

Note – The above is an example, and shows the options meaningful to theruntime linker. The exact options might differ from release to release.

The environment variable LD_DEBUG_OUTPUT can be used to specify an outputfile for use instead of the standard error. The output file name will be suffixedwith the process identifier.

Debugging of secure applications is not allowed.

$ LD_DEBUG=help prog11693:11693: For debugging the run-time linking of an application:11693: LD_DEBUG=option1,option2 prog11693: enables diagnostics to the stderr. The additional11693: option:11693: LD_DEBUG_OUTPUT=file11693: redirects the diagnostics to an output file created11593: using the specified name and the process id as a11693: suffix. All output is prepended with the process id.11693:11693:11693: bindings display symbol binding; detail flag shows11693: absolute:relative addresses11693: detail provide more information in conjunction with other11693: options11693: files display input file processing (files and libraries)11693: help display this help message11693: libs display library search paths11693: reloc display relocation processing11693: symbols display symbol table processing;11693: detail flag shows resolution and linker table addition11693: versions display version processing

$

Page 93: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 79

3

One of the most useful debugging options is to display the symbol bindingsthat occur at runtime. For example, let’s take a very trivial dynamic executablethat has a dependency on two local shared objects:

The runtime symbol bindings can be displayed by settingLD_DEBUG=bindings :

Here, the symbol bar , which is required by a data relocation, is bound beforethe application gains control. Whereas the symbol foo , which is required by afunction relocation, is bound after the application gains control when the

$ cat bar.cint bar = 10;$ cc -o bar.so.1 -Kpic -G bar.c

$ cat foo.cfoo(int data){ return (data);}$ cc -o foo.so.1 -Kpic -G foo.c

$ cat main.cextern int foo();extern int bar;

main(){ return (foo(bar));}$ cc -o prog main.c -R/tmp:. foo.so.1 bar.so.1

$ LD_DEBUG=bindings prog11753: .......11753: binding file=prog to file=./bar.so.1: symbol bar11753: .......11753: transferring control: prog11753: .......11753: binding file=prog to file=./foo.so.1: symbol foo11753: .......

Page 94: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

80 Linker and Libraries Guide—November 1995

3

function is first called. This demonstrates the default mode of lazy binding. Ifthe environment variable LD_BIND_NOW is set, all symbol bindings will occurbefore the application gains control.

Additional information regarding the real, and relative addresses of the actualbinding locations can be obtained by setting LD_DEBUG=bindings,detail .

When the runtime linker performs a function relocation it rewrites the .pltentry associated with the function so that any subsequent calls will go directlyto the function. The environment variable LD_BIND_NOT can be set to anyvalue to prevent this .plt update. By using this variable together with thedebugging request for detailed bindings, you can get a complete runtimeaccount of all function binding. The output from this combination can beexcessive, and the performance of the application will be degraded.

Another aspect of the runtime environment that can be displayed involves thevarious search paths used. For example, the search path mechanism used tolocate any shared library dependencies can be displayed by settingLD_DEBUG=libs :

Here, the runpath recorded in the application prog affects the search for thetwo dependencies foo.so.1 and bar.so.1 .

$ LD_DEBUG=libs prog11775:11775: find library=foo.so.1; searching11775: search path=/tmp:. (RPATH from file prog)11775: trying path=/tmp/foo.so.111775: trying path=./foo.so.111775:11775: find library=bar.so.1; searching11775: search path=/tmp:. (RPATH from file prog)11775: trying path=/tmp/bar.so.111775: trying path=./bar.so.111775: .......

Page 95: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Runtime Linker 81

3

In a similar manner, the search paths of each symbol lookup can be displayedby setting LD_DEBUG=symbols. If this is combined with a bindings request,a complete picture of the symbol relocation process can be obtained:

Note – In the previous example the symbol bar is not searched for in theapplication prog . This is due to an optimization used when processing copyrelocations (see “Profiling Shared Objects” on page 111 for more details of thisrelocation type).

$ LD_DEBUG=bindings,symbols11782: .......11782: symbol=bar; lookup in file=./foo.so.1 [ ELF ]11782: symbol=bar; lookup in file=./bar.so.1 [ ELF ]11782: binding file=prog to file=./bar.so.1: symbol bar11782: .......11782: transferring control: prog11782: .......11782: symbol=foo; lookup in file=prog [ ELF ]11782: symbol=foo; lookup in file=./foo.so.1 [ ELF ]11782: binding file=prog to file=./foo.so.1: symbol foo11782: .......

Page 96: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

82 Linker and Libraries Guide—November 1995

3

Page 97: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

83

Shared Objects 4

OverviewShared objects are one form of output created by the link-editor, and aregenerated by specifying the -G option. For example:

Here the shared object libfoo.so.1 is generated from the input file foo.c .

Note – This is a simplified example of generating a shared object. Usually,additional options are recommended, and these will be discussed insubsequent sections of this chapter.

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

$ cc -o libfoo.so.1 -G -K pic foo.c

Page 98: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

84 Linker and Libraries Guide—November 1995

4

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

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

The following sections expand upon the use of shared objects within thecompilation and runtime environments (these environments are introduced in“Shared Objects” on page 4). Issues that complement and help coordinate theuse of shared objects within these environments are covered, together withtechniques that maximize the efficiency of shared objects.

Naming ConventionsNeither the link-editor, nor the runtime linker, interprets any file by virtue ofits filename. All files are inspected to determine their ELF type (see “ELFHeader” on page 142). From this information the processing requirements ofthe file are deduced. However, shared objects usually follow one of twonaming conventions depending on whether they are being used as part of thecompilation environment or the run-time environment.

When used as part of the compilation environment, shared objects are read andprocessed by the link-editor. Although these shared objects can be specified byexplicit filenames as part of the command-line passed to the link-editor, it ismore common that the -l option be used to take advantage of the link-editor’slibrary search capabilities (see “Shared Object Processing” on page 13).

For a shared object to be applicable to this link-editor processing it should bedesignated with the prefix lib and the suffix .so . For example,/usr/lib/libc.so is the shared object representation of the standard Clibrary made available to the compilation environment.

When used as part of the runtime environment, shared objects are read andprocessed by the runtime linker. Here it might be necessary to allow for changein the exported interface of the shared object over a series of software releases.This interface change can be anticipated and supported by providing theshared object as a versioned filename.

Page 99: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 85

4

A versioned filename commonly takes the form of a .so suffix followed by aversion number. For example, /usr/lib/libc.so.1 is the shared objectrepresentation of version one of the standard C library made available to theruntime environment.

If a shared object is never intended for use within a compilation environmentits name might drop the conventional lib prefix. Examples of shared objectsthat fall into this category are those used solely with dlopen(3X) . A suffix of.so is still recommended to indicate the actual file type, and a version numberis strongly recommended to provide for the correct binding of the shared objectacross a series of software releases.

Note – The shared object name used in a dlopen(3X) is usually representedas a simple filename - in other words there is no ‘/’ in the name. Thisconvention provides flexibility by allowing the runtime linker to use a set ofrules to locate the actual file (see “Loading Additional Objects” on page 62 formore details).

In Chapter 5, “Versioning”, the concept of versioning a shared objects interfaceover a series of software releases is described in more detail. In addition, amechanism for coordinating the naming conventions between shared objectsused in both the compilation and runtime environments is presented. But first,a mechanism that allows a shared object to record its own runtime name isdescribed.

Page 100: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

86 Linker and Libraries Guide—November 1995

4

Recording a Shared Object Name

The recording of a dependency in a dynamic executable or shared object will, bydefault, be the filename of the associated shared object as it is referenced by thelink-editor. For example, the following dynamic executables, built against thesame shared object libfoo.so , result in different interpretations of the samedependency:

As these examples show, this mechanism of recording dependencies can resultin inconsistencies due to different compilation techniques. Also, the location ofa shared object as referenced during the link-edit might differ from theeventual location of the shared object on an installed system.

To provide a more consistent means of specifying dependencies, shared objectscan record within themselves the filename by which they should be referencedat runtime.

During the link-edit of a shared object, its runtime name can be recordedwithin the shared object itself by using the -h option. For example:

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

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

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

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

Page 101: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 87

4

Here, the shared object’s runtime name libfoo.so.1 , is recorded within thefile itself. This identification is known as an soname, and its recording can bedisplayed using dump(1) and referring to the entry that has the SONAME tag.For example:

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

Therefore, if this new version of libfoo.so is used during the creation of thedynamic executable prog from the previous example, all three methods ofbuilding the executable result in the same dependency recording:

In the examples shown above, the -h option is used to specify a simplefilename - in other words there is no ‘/’ in the name. This convention isrecommended, as it provides flexibility by allowing the runtime linker to use aset of rules to locate the actual file (see “Locating Shared Object Dependencies”on page 54 for more details).

$ dump -Lvp ../tmp/libfoo.so

../tmp/libfoo.so:[INDEX] Tag Value[1] SONAME libfoo.so.1.........

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

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

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

Page 102: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

88 Linker and Libraries Guide—November 1995

4

Inclusion of Shared Objects in Archives

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

An archive can be built from one or more shared objects and then used togenerate a dynamic executable or shared object. Shared objects can be extractedfrom the archive to satisfy the requirements of the link-edit (see “ArchiveProcessing” on page 12 for more details on the criteria for archive extraction).However, unlike the processing of relocatable objects, which are concatenatedto the output file being created, any shared objects extracted from the archivewill be recorded as dependencies.

The name of an archive member is constructed by the link-editor and is aconcatenation of the archive name and the object within the archive. Forexample:

As it is highly unlikely that a file with this concatenated name will exist atruntime, providing an soname within the shared object is the only means ofgenerating a meaningful runtime filename for the dependency.

Note – The run-time linker does not extract objects from archives. Therefore, inthe above example it will be necessary for the required shared objectdependencies to be extracted from the archive and made available to theruntime environment.

Recorded Name Conflicts

When shared objects are used to build a dynamic executable or another sharedobject, the link-editor performs several consistency checks to insure that anydependency names that will be recorded in the output file are unique.

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

Page 103: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 89

4

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

A similar error condition will occur if the filename of a shared object that doesnot have a recorded soname matches the soname of another shared object usedduring the same link-edit.

If the runtime name of a shared object being generated matches one of itsdependencies the link-editor will also report a name conflict. For example:

Shared Objects with DependenciesAlthough most of the examples presented in this chapter so far have shownhow shared object dependencies are maintained in dynamic executables, it isquite common for shared objects to have their own dependencies (this wasintroduced in “Shared Object Processing” on page 13).

In “Directories Searched by the Runtime Linker” on page 55, the search rulesused by the runtime linker to locate shared object dependencies are covered. Ifa shared object does not reside in the default directory /usr/lib , then the

$ cc -o libfoo.so -G -K pic -h libsame.so.1 foo.c$ cc -o libbar.so -G -K pic -h libsame.so.1 bar.c$ cc -o prog main.o -L. -lfoo -lbarld: fatal: file ./libbar.so: recording name `libsame.so.1’ \ matches that provided by file ./libfoo.sold: fatal: File processing errors. No output written to prog

$ cc -o libbar.so -G -K pic -h libsame.so.1 bar.c -L. -lfoold: fatal: file ./libfoo.so: recording name `libsame.so.1’ \ matches that supplied with -h optionld: fatal: File processing errors. No output written to libfoo.so

Page 104: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

90 Linker and Libraries Guide—November 1995

4

runtime linker must explicitly be told where to look. The preferred mechanismof indicating any requirement of this kind is to record a runpath in the objectthat has the dependencies by using the link-editor’s -R option. For example:

Here, the shared object libfoo.so has a dependency on libbar.so , which isexpected to reside in the directory /home/me/lib at runtime.

It is the responsibility of the shared object to specify any runpath required tolocate its dependencies. Any runpath specified in the dynamic executable willonly be used to locate the dependencies of the dynamic executable, it will notbe used to locate any dependencies of the shared objects.

However, the environment variable LD_LIBRARY_PATH has a more globalscope, and any pathnames specified using this variable will be used by theruntime linker to search for any shared object dependencies. Although usefulas a temporary mechanism of influencing the runtime linker’s search path, theuse of this environment variable is strongly discouraged in productionsoftware (see “Directories Searched by the Runtime Linker” on page 55 for amore extensive discussion).

Dependency OrderingIn most of the examples in this document, dependencies of dynamicexecutables and shared objects are portrayed as unique and relatively simple(the breadth-first ordering of dependent shared objects is described in“Locating Shared Object Dependencies” on page 54). From these examples, theordering of shared objects as they are brought into the process address spacemight seem very intuitive and predictable.

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

libfoo.so:

**** DYNAMIC SECTION INFORMATION ****.dynamic :[INDEX] Tag Value[1] NEEDED libbar.so[2] RPATH /home/me/lib.........

Page 105: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 91

4

However, when dynamic executables and shared objects have dependencies onthe same common shared objects, the order in which the objects are processedcan become less predictable.

For example, assume a shared object developer generates libfoo.so.1 withthe following dependencies:

If you create a dynamic executable, prog , using this shared object, and alsodefine an explicit dependency on libC.so.1 , then the resulting shared objectorder will be:

Therefore, had the developer of the shared object libfoo.so.1 placed arequirement on the order of processing of its dependencies, this requirementwill be compromised by the construction of the dynamic executable prog .

Developers who place special emphasis on symbol interposition (see “SymbolLookup” on page 59, “Symbol Lookup” on page 69 and “Using Interposition”on page 75), and .init section processing (see “Initialization and TerminationRoutines” on page 64), should be aware of this potential change in sharedobject processing order.

Shared Objects as FiltersA filter is a special form of shared object used to provide indirection to analternative shared object. Two forms of shared object filter exist:

• a standard filter

• an auxiliary filter

$ ldd libfoo.so.1 libA.so.1 => ./libA.so.1 libB.so.1 => ./libB.so.1 libC.so.1 => ./libC.so.1

$ cc -o prog main.c -R. -L.-lC -lfoo$ ldd prog libC.so.1 => ./libC.so.1 libfoo.so.1 => ./libfoo.so.1 libA.so.1 => ./libA.so.1 libB.so.1 => ./libB.so.1

Page 106: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

92 Linker and Libraries Guide—November 1995

4

A standard filter, in essence, consists solely of a symbol table, and provides amechanism of abstracting the compilation environment from the runtimeenvironment. A link-edit using the filter will reference the symbols providedby the filter itself, however the implementation to which the symbol referencesis provided from an alternative source at runtime.

Standard filters are identified using the link-edit’s -F flag. This flag takes anassociated filename indicating the shared object to be used to supply symbolsat runtime. This shared object is referred to as the filtee.

If the filtee cannot be processed at runtime, or any symbol defined by the filtercannot be located within the filtee, a fatal runtime error will occur.

An auxiliary filter has a similar mechanism, however the filter itself contains animplementation corresponding to its symbols. A link-edit using the filter willreference the symbols provided by the filter itself, however the implementationcan be provided from an alternative source at runtime.

Auxiliary filters are identified during the link-edit’s -f flag. This flag takes anassociated filename indicating the shared object which might be used to supplysymbols at runtime. This shared object is referred to as the filtee

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

Generating a Standard Filter

First let’s define a filtee, libbar.so.1 , on which this filter technology will beapplied. This filtee might be built from several relocatable objects. One of theseobjects originates from the file bar.c , and supplies the symbols foo and bar :

$ cat bar.cchar * bar = “bar”;

char * foo(){ return(“defined in bar.c”);}$ cc -o libbar.so.1 -G -K pic .... bar.c ....

Page 107: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 93

4

A standard filter, libfoo.so.1 , is generated for the symbols foo and bar ,and indicates the association to the filtee libbar.so.1 . For example:

Note – Here the environment variable LD_OPTIONS is used to circumvent thiscompiler driver from interpreting the -F option as one of its own.

If the link-editor references the standard filter libfoo.so.1 to build adynamic executable or shared object, it will use the information from the filterssymbol table during symbol resolution (see “Symbol Resolution” on page 21for more details).

At runtime, any reference to the symbols of the filter will result in theadditional loading of the filtee libbar.so.1 . The runtime linker will use thisfiltee to resolve any symbols defined by libfoo.so.1 .

For example, the following dynamic executable, prog , references the symbolsfoo and bar which are resolved during link-edit from the filter libfoo.so.1 :

$ cat foo.cchar * bar = 0;

char * foo(){}

$ LD_OPTIONS=”-F libbar.so.1” \ cc -o libfoo.so.1 -G -K pic -h libfoo.so.1 -R. foo.c$ ln -s libfoo.so.1 libfoo.so$ dump -Lv libfoo.so.1 | egrep “SONAME|FILTER”[1] SONAME libfoo.so.1[2] FILTER libbar.so.1

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

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

Page 108: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

94 Linker and Libraries Guide—November 1995

4

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

Note – In this example, the filtee libbar.so.1 is uniquely associated to thefilter libfoo.so.1 and is not available to satisfy symbol lookup from anyother objects that might be loaded as a consequence of executing prog .

Standard filters provide a mechanism for defining a subset interface of anexisting shared object. This mechanism is used in Solaris to create the sharedobjects /usr/lib/libsys.so.1 and /usr/lib/libdl.so.1 . The formerprovides a subset of the standard C library /usr/lib/libc.so.1 . Thissubset represents the ABI-conforming functions and data items that reside inthe C library that must be imported by a conforming application.

The latter defines the user interface to the runtime linker itself. This interfaceprovides an abstraction between the symbols referenced in a compilationenvironment (from libdl.so.1 ) and the actual implementation bindingproduced within the runtime environment (from ld.so.1 ).

As the code in a standard filter is never referenced at runtime, there is no pointin adding content to any functions defined within the filter. Any filter codemight require relocations, which will result in an unnecessary overhead whenprocessing the filter at runtime. Functions are best defined as empty routines.

Care should also be taken when generating the data symbols within a filter.Data items should always be initialized to insure that they result in referencesfrom dynamic executables. Some of the more complex symbol resolutionscarried out by the link-editor require knowledge of a symbol’s attributes,including the symbols size (see “Symbol Resolution” on page 21 for moredetails).

Therefore, it is recommended that the symbols in the filter be generated so thattheir attributes match those of the symbols in the filtee. This insures that thelink-editing process will analyze the filter in a manner compatible with thesymbol definitions used at runtime.

Page 109: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 95

4

Generating an Auxiliary Filter

The creation of an auxiliary filter is essentially the same as for a standard filter(see “Generating a Standard Filter” on page 92 for more details). First let’sdefine a filtee, libbar.so.1 , on which this filter technology will be applied.This filtee might be built from several relocatable objects. One of these objectsoriginates from the file bar.c , and supplies the symbol foo :

A standard filter, libfoo.so.1 , is generated for the symbols foo and bar ,and indicates the association to the filtee libbar.so.1 . For example:

Note – Here the environment variable LD_OPTIONS is used to circumvent thiscompiler driver from interpreting the -f option as one of its own.

If the link-editor references the auxiliary filter libfoo.so.1 to build adynamic executable or shared object, it will use the information from the filterssymbol table during symbol resolution (see “Symbol Resolution” on page 21for more details).

$ cat bar.cchar * foo(){ return(“defined in bar.c”);}$ cc -o libbar.so.1 -G -K pic .... bar.c ....

$ cat foo.cchar * bar = “foo”;

char * foo(){ return (“defined in foo.c”);}$ LD_OPTIONS=”-f libbar.so.1” \ cc -o libfoo.so.1 -G -K pic -h libfoo.so.1 -R. foo.c$ ln -s libfoo.so.1 libfoo.so$ dump -Lv libfoo.so.1 | egrep “SONAME|AUXILIARY”[1] SONAME libfoo.so.1[2] AUXILIARY libbar.so.1

Page 110: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

96 Linker and Libraries Guide—November 1995

4

At runtime, any reference to the symbols of the filter will result in a search forthe filtee libbar.so.1 . If this filtee is found the runtime linker will use thisfiltee to resolve any symbols defined by libfoo.so.1 . If the filtee was notfound, or a symbol from the filter is not found in the filtee, then the originalvalue of the symbol within the filter is used.

For example, the following dynamic executable, prog , references the symbolsfoo and bar which are resolved during link-edit from the filter libfoo.so.1 :

The execution of the dynamic executable prog results in the function foo()being obtained from the filtee libbar.so.1 , not from the filter libfoo.so.1 .However, the data item bar is obtained from the filter libfoo.so.1 , as thissymbol has no alternative definition in the filtee libbar.so.1 .

Auxiliary filters provide a mechanism for defining an alternative interface ofan existing shared object. This mechanism is used in Solaris to provideoptimized functionality within platform specific shared objects.

Performance ConsiderationsA shared object can be used by multiple applications within the same system.The performance of a shared object therefore can have far reaching effects, notonly on the applications that use it, but on the system as a whole.

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

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

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

Page 111: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 97

4

Useful Tools

Before discussing performance it is useful to be aware of some available toolsand their use in analyzing the contents of an ELF file.

Frequently reference is made to the size of either the sections or the segmentsthat are defined within an ELF file (for a complete description of the ELFformat see Chapter 6, “Object Files”). The size of a file can be displayed usingthe size(1) command. For example:

The first example indicates the size of the shared objects text, data and bss, acategorization that has traditionally been used throughout previous releases ofthe SunOS operating system. The ELF format provides a finer granularity forexpressing data within a file by organizing the data into sections. The secondexample displays the size of each of the file’s loadable sections.

Sections are allocated to units known as segments, some of which describe howportions of a file will be mapped into memory. These loadable segments can bedisplayed by using the dump(1) command and examining the LOAD entries.For example:

$ size -x libfoo.so.159c + 10c + 20 = 0x6c8

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

$ dump -ov libfoo.so.1

libfoo.so.1: ***** PROGRAM EXECUTION HEADER *****Type Offset Vaddr PaddrFilesz Memsz Flags Align

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

LOAD 0x630 0x10630 0x00x10c 0x12c rwx 0x10000

Page 112: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

98 Linker and Libraries Guide—November 1995

4

Here, there are two segments in the shared object libfoo.so.1 , commonlyreferred to as the text and data segments. The text segment is mapped to allowreading and execution of its contents (r-x), whereas the data segment ismapped to allow its contents to be modified (rwx). Notice that the memorysize (Memsz) of the data segment differs from the file size (Filesz). Thisdifference accounts for the .bss section, which is actually part of the datasegment.

Programmers however, usually think of a file in terms of the symbols thatdefine the functions and data elements within their code. These symbols can bedisplayed using nm(1) . For example:

$ nm -x libfoo.so.1

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

Page 113: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 99

4

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

Using the output from both the previous nm(1) and dump(1) examples, theassociation of the functions _init , foo and _fini to the sections .init, .textand .fini can be seen. These sections, because of their read-only nature, are partof the text segment.

Similarly, it can be seen that the data arrays data and bss are associated withthe sections .data and .bss respectively. These sections, because of their writablenature, are part of the data segment.

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

Armed with this tool information, you can analyze the location of code anddata within any ELF file you generate. This knowledge will be useful whenfollowing the discussions in later sections.

$ dump -hv libfoo.so.1

libfoo.so.1: **** SECTION HEADER TABLE ****[No] Type Flags Addr Offset Size Name.........[7] PBIT -AI 0x538 0x538 0x1c .init

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

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

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

Page 114: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

100 Linker and Libraries Guide—November 1995

4

The Underlying System

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

Relocations within the shared object are processed to bind symbolic referencesto their appropriate definitions. This results in the calculation of true virtualaddresses which could not be derived at the time the shared object wasgenerated by the link-editor. These relocations usually result in updates toentries within the process’s data segment(s).

The memory management scheme underlying the dynamic linking of sharedobject’s share memory among processes at the granularity of a page. Memorypages can be shared as long as they are not modified at runtime. If a processwrites to a page of a shared object when writing a data item, or relocating areference to a shared object, it generates a private copy of that page. Thisprivate copy will have no effect on other users of the shared object, however,this page will have lost any benefit of sharing between other processes. Textpages that become modified in this manner are referred to as impure.

The segments of a shared object that are mapped into memory fall into twobasic categories; the text segment, which is read-only, and the data segmentwhich is read-write (see “Useful Tools” on page 97 on how to obtain thisinformation from an ELF file). An overriding goal when developing a sharedobject is to maximize the text segment and minimize the data segment. Thisoptimizes the amount of code sharing while reducing the amount of processingneeded to initialize and use a shared object. The following sections presentmechanisms that can help achieve this goal.

Position-Independent Code

To create programs that require the smallest amount of page modification atrun time, the compiler will generate position-independent code under the-K pic option. Whereas the code within a dynamic executable is usually tiedto a fixed address in memory, position-independent code can be loadedanywhere in the address space of a process. Because the code is not tied to aspecific address, it will execute correctly without page modification at adifferent address in each process that uses it.

Page 115: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 101

4

When you use position-independent code, relocatable references are generatedin the form of an indirection which will use data in the shared object’s datasegment. The result is that the text segment code will remain read-only, and allrelocation updates will be applied to corresponding entries within the datasegment. See “Global Offset Table (Processor-Specific)” on page 213,“Procedure Linkage Table” on page 215 and “Procedure Linkage Table” onpage 218 for more details on the use of these two sections.

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

A shared object that requires relocations against its text segment can beidentified by using dump(1) and inspecting the output for any TEXTREL entry.For example:

Note – The value of the TEXTREL entry is irrelevant, its presence in a sharedobject indicates that text relocations exist.

A recommended practice to prevent the creation of a shared object thatcontains text relocations is to use the link-editor’s -z text flag. This flagcauses the link-editor to generate diagnostics indicating the source of any nonposition-independent code used as input, and results in a failure to generatethe intended shared object. For example:

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

$ cc -o libfoo.so.1 -z text -G -R. foo.cText relocation remains referenced against symbol offset in filefoo 0x0 foo.obar 0x8 foo.old: fatal: relocations remain against allocatable but non-writable sections

Page 116: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

102 Linker and Libraries Guide—November 1995

4

Here, two relocations are generated against the text segment because of thenon-position-independent code generated from the file foo.o . Where possible,these diagnostics will indicate any symbolic references that are required tocarry out the relocations. In this case the relocations are against the symbolsfoo and bar .

Besides not using the -K pic option, the most common cause of creating textrelocations when generating a shared object is by including hand writtenassembler code that has not been coded with the appropriate position-independent prototypes.

Note – By using the compiler’s ability to generate an intermediate assemblerfile, the coding techniques used to enable position-independence can usuallybe revealed by experimenting with some simple test case source files.

A second form of the position-independence flag, -K PIC , is also available onsome processors, and provides for a larger number of relocations to beprocessed at the cost of some additional code overhead (see cc(1) for moredetails).

Maximizing Shareability

As mentioned in “The Underlying System” on page 100, only a shared object’stext segment is shared by all processes that use it, its data segment typically isnot. Each process that uses a shared object usually generates a private memorycopy of its entire data segment as data items within the segment are written to.A goal is to reduce the data segment, either by moving data elements that willnever be written to the text segment, or by removing the data items completely.

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

Page 117: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 103

4

Move Read-Only Data to Text

Any data elements that are read-only should be moved into the text segment.This can be achieved using const declarations. For example, the followingcharacter string will reside in the .data section, which is part of the writabledata segment:

whereas, the following character string will reside in the .rodata section, whichis the read-only data section contained within the text segment:

Although reducing the data segment by moving read-only elements into thetext segment is an admirable goal, moving data elements that requirerelocations can be counter productive. For example, given the array of strings:

it might at first seem that a better definition is:

thereby insuring that the strings and the array of pointers to these strings areplaced in a .rodata section. The problem with this definition is that even thoughthe user perceives the array of addresses as read-only, these addresses must berelocated at runtime. This definition will therefore result in the creation of textrelocations. This definition is best represented as:

so that the array strings are maintained in the read-only text segment, but thearray pointers are maintained in the writable data segment where they can besafely relocated.

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

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

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

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

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

Page 118: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

104 Linker and Libraries Guide—November 1995

4

Note – Some compilers, when generating position-independent code, candetect read-only assignments that will result in runtime relocations, and willarrange for placing such items in writable segments (for example .picdata).

Collapse Multiply-Defined Data

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

The main candidates for this sort of data reduction are strings. String usage ina shared object can be investigated using strings(1) . For example:

will generate a sorted list of the data strings within the file libfoo.so.1 .Each entry in the list is prefixed with the number of occurrences of the string.

Use Automatic Variables

Permanent storage for data items can be removed entirely if the associatedfunctionality can be designed to use automatic (stack) variables. Any removalof permanent storage will usually result in a corresponding reduction in thenumber of runtime relocations required.

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

foo(){ ...... (void) fprintf(stderr, Errmsg, error); ......

$ strings -10 libfoo.so.1 | sort | uniq -c | sort -rn

Page 119: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 105

4

Allocate Buffers Dynamically

Large data buffers should usually be allocated dynamically rather than beingdefined using permanent storage. Often this will result in an overall saving inmemory, as only those buffers needed by the present invocation of anapplication will be allocated. Dynamic allocation also provides greaterflexibility by allowing the buffer’s size to change without effectingcompatibility.

Minimizing Paging Activity

Many of the mechanisms discussed in the previous section “MaximizingShareability” on page 102 will help reduce the amount of paging encounteredwhen using shared objects. Here some additional generic softwareperformance considerations are covered.

Any process that accesses a new page will cause a page fault. As this is anexpensive operation, and because shared objects can be used by manyprocesses, any reduction in the number of page faults generated by accessing ashared object will benefit the process and the system as a whole.

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

It is also advisable to isolate related functionality to its own shared object. Thestandard C library has historically been built containing many unrelatedfunctions, and only rarely, for example, will any single executable useeverything in this library. Because of its widespread use, it is also somewhatdifficult to determine what set of functions are really the most frequently used.In contrast, when designing a shared object from scratch it is better to maintainonly related functions within the shared object. This will improve locality ofreference and usually has the side effect of reducing the object’s overall size.

Page 120: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

106 Linker and Libraries Guide—November 1995

4

Relocations

In “Relocation Processing” on page 57 the mechanisms by which the runtimelinker relocates dynamic executables and shared objects to create a runableprocess was covered. “Symbol Lookup” on page 59, and “When Relocationsare Performed” on page 60 categorized this relocation processing into twoareas to simplify and help illustrate the mechanisms involved. These same twocategorizations are also ideally suited for considering the performance impactof relocations.

Symbol Lookup

When the runtime linker needs to look up a symbol, it does so by searching ineach object, starting with the dynamic executable, and progressing througheach shared object in the same order that the objects are mapped. In manyinstances the shared object that requires a symbolic relocation will turn out tobe the provider of the symbol definition.

If this is the case, and the symbol used for this relocation is not required as partof the shared object’s interface, then this symbol is a strong candidate forconversion to a static or automatic variable. A symbol reduction can also beapplied to removed symbols from a shared objects interface (see “ReducingSymbol Scope” on page 38 for more details). By making these conversions thelink-editor will incur the expense of processing any symbolic relocation againstthese symbols during the shared object’s creation.

The only global data items that should be visible from a shared object are thosethat contribute to its user interface. However, frequently this is a hard goal toaccomplish, as global data are often defined to allow reference from two ormore functions located in different source files. Nevertheless, any reduction inthe number of global symbols exported from a shared object will result inlower relocation costs and an overall performance improvement.

When Relocations are Performed

All data reference relocations must be carried out during process initializationbefore the application gains control, whereas any function reference relocationscan be deferred until the first instance of a function being called. By reducingthe number of data relocations, the runtime initialization of a process will bereduced.

Page 121: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 107

4

Initialization relocation costs can also be deferred by converting datarelocations into function relocations, for example, by returning data items by afunctional interface. This conversion usually results in a perceivedperformance improvement as the initialization relocation costs are effectivelyspread throughout the process’s lifetime. It is also possible that some of thefunctional interfaces will never be called by a particular invocation of aprocess, thus removing their relocation overhead altogether.

The advantage of using a functional interface can be seen in the next section“Copy Relocations”. This section examines a special, and somewhat expensive,relocation mechanism employed between dynamic executables and sharedobjects, and provides an example of how this relocation overhead can beavoided.

Copy Relocations

Shared objects are usually built with position-independent code. References toexternal data items from code of this type employs indirect addressing througha set of tables (see “Position-Independent Code” on page 100 for more details).These tables are updated at runtime with the real address of the data items,which allows access to the data without the code itself being modified.

Dynamic executables however, are generally not created from position-independent code. Therefore it would seem that any references to external datathey make can only be achieved at runtime by modifying the code that makesthe reference. Modifying any text segment is something to be avoided, and so arelocation technique is employed to solve this reference which is known as acopy relocation.

When the link-editor is used to build a dynamic executable, and a reference toa data item is found to reside in one of the dependent shared objects, space isallocated in the dynamic executable’s .bss, equivalent in size to the data itemfound in the shared object. This space is also assigned the same symbolic nameas defined in the shared object. Along with this data allocation, the link-editorgenerates a special copy relocation record that will instruct the runtime linkerto copy the data from the shared object to this allocated space within thedynamic executable.

Page 122: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

108 Linker and Libraries Guide—November 1995

4

Because the symbol assigned to this space is global, it will be used to satisfyany references from any shared objects. The effect of this is that the dynamicexecutable inherits the data item, and any other objects within the process thatmake reference to this item will be bound to this copy. The original data fromwhich the copy is made effectively becomes unused.

This mechanism is best explained with an example. This example uses an arrayof system error messages that is maintained within the standard C library. Inprevious SunOS operating system releases, the interface to this informationwas provided by two global variables, sys_errlist[] , and sys_nerr . Thefirst variable provided the array of error message strings, while the secondconveyed the size of the array itself. These variables were commonly usedwithin an application in the following manner:

Here the application is using the function error to provide a focal point toobtain the system error message associated with the number errnumb .

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

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

Page 123: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 109

4

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

Here the link-editor has allocated space in the dynamic executable’s .bss toreceive the data represented by sys_errlist and sys_nerr . These data willbe copied from the C library by the runtime linker at process initialization.Thus, each application that uses these data will get a private copy of the datain its own data segment.

There are actually two downsides to this technique. First, each application paysa performance penalty for the overhead of copying the data at run time.Secondly, the size of the data array sys_errlist has now become part of theC library’s interface. If the size of this array were to change, presumably asnew error messages are added, any dynamic executables that reference thisarray have to undergo a new link-edit to be able to access any of the new errormessages. Without this new link-edit, the allocated space within the dynamicexecutable is insufficient to hold the new data.

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

**** RELOCATION INFORMATION ****

.rela.bss:Offset Symndx Type Addend

0x2090c sys_nerr R_SPARC_COPY 00x20910 sys_errlist R_SPARC_COPY 0..........

Page 124: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

110 Linker and Libraries Guide—November 1995

4

These drawbacks can be eliminated if the data required by a dynamicexecutable are provided by a functional interface. The ANSI C functionstrerror(3C) illustrates this point. This function is implemented such that itwill return a pointer to the appropriate error string based on the error numbersupplied to it. One implementation of this function might be:

The error routine in foo.c can now be simplified to use this functionalinterface, which in turn will remove any need to perform the original copyrelocations at process initialization.

Additionally, because the data are now local to the shared object the data areno longer part of its interface, which allows the shared object the flexibility ofchanging the data without adversely effecting any dynamic executables thatuse it. Eliminating data items from a shared object’s interface will generallyimprove performance while making the shared object’s interface and codeeasier to maintain.

Although copy relocations should be avoided, ldd(1) , when used with eitherthe -d or -r options, can be used to verify any that exist within a dynamicexecutable.

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

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

Page 125: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 111

4

For example, if the dynamic executable prog had originally been built againstthe shared object libfoo.so.1 such that the following two copy relocationshad been recorded:

and a new version of this shared object is supplied which contains differentdata sizes for these symbols:

then running ldd(1) against the dynamic executable will reveal:

Here ldd(1) informs us that the dynamic executable will copy as much dataas the shared object has to offer, but only accepts as much as its allocated spaceallows.

Profiling Shared Objects

The runtime linker is capable of generating profiling information for anyshared objects processed during the running of an application. This is possiblebecause the runtime linker is responsible for binding shared objects to an

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

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

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

Page 126: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

112 Linker and Libraries Guide—November 1995

4

application and is therefore able to intercept any global function bindings (thesebindings take place through .plt entries - see “When Relocations arePerformed” on page 60 for details of this mechanism).

The profiling of a shared object is enabled by specifying its name with theLD_PROFILE environment variable. You can analyze one shared object at atime using this environment variable. However, the setting of the environmentvariable can be used to analyze one or more applications use of the sharedobject. In the following example the use of libc by the single invocation of thecommand ls(1) is analyzed:

In the following example the environment variable setting will cause anyapplications use of libc to accumulate the analyzed information for theduration that the environment variable is set:

When profiling is enabled, a profile data file is created, if it doesn’t alreadyexist, and is mapped by the runtime linker. In the above examples this data fileis /var/tmp/libc.so.1.profile . You can also specify an alternativedirectory to store the profile data using the LD_PROFILE_OUTPUT environmentvariable.

This profile data file is used to deposit profil(2) data and call countinformation related to the specified shared objects use. This profiled data canbe directly examined with gprof(1) .

Note – gprof(1) is most commonly used to analyze the gmon.out profiledata created by an executable that has been compiled with the -xpg option ofcc(1) . The runtime linkers profile analysis does not require any code to becompiled with this option. Applications whose dependent shared objects arebeing profiled should not make calls to profil(2) , because this system calldoes not provide for multiple invocations within the same process. For the

$ LD_PROFILE=libc.so.1 ls -l

$ LD_PROFILE=libc.so.1; export LD_PROFILE$ ls -l$ make$ ...

Page 127: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Shared Objects 113

4

same reason, these applications must not be compiled with the -xpg option ofcc(1) , as this compiler generated mechanism of profiling is also built on topof profil(2) .

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

Page 128: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

114 Linker and Libraries Guide—November 1995

4

The following example shows a performance analysis of libc over a build ofseveral applications within a source hierarchy:

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

Note – The profiling of shared objects is multi-threaded safe except in the casewhere one thread calls fork(2) while another thread is updating the profiledata information. The use of fork1(2 ) removes this restriction.

$ LD_PROFILE=libc.so.1 ; export LD_PROFILE$ make......$ gprof -b /usr/lib/libc.so.1 /var/tmp/libc.so.1.profile

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

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

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

Page 129: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

115

Versioning 5

OverviewELF objects processed by the link-editors provide many global symbols towhich other objects can bind. These symbols describe the object’s applicationbinary interface (ABI). During the evolution of an object this interface canchange due to the addition or deletion of global symbols. In addition, theobjects evolution can involve internal implementation changes.

Versioning refers to several techniques that can be applied to an object toindicate interface and implementation changes. These techniques provide forthe objects controlled evolution while maintaining backward compatibility.

This chapter describes how an object’s ABI can be defined, classifies howchanges to this interface can affect backward compatibility, and presentsmodels by which interface and implementation changes can be incorporatedinto new releases of the object.

The focus of this chapter is the runtime interfaces of dynamic executables andshared objects. The techniques used to describe and manage changes withinthese dynamic objects are presented in generic terms. A common set of namingconventions and versioning scenarios, as applied to shared objects, can befound in Appendix B, “Versioning Quick Reference.

It is important that developers of dynamic objects be aware of the ramificationsof an interface change, and understand how such changes can be managed,especially in regards to maintaining backward compatibility with previouslyshipped objects.

Page 130: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

116 Linker and Libraries Guide—November 1995

5

The global symbols made available by any dynamic object represent theobject’s public interface. Frequently, the number of global symbols remaining inan object at the end of a link-edit are more than you would like to make public.These global symbols derive from the interrelationships required between therelocatable objects used to build the object, and represent private interfaceswithin the object itself.

A precursor to defining an object’s binary interface is to first define only thoseglobal symbols you wish to make publicly available from the object beingcreated. These public symbols can be established using the link-editor’s -Moption and an associated mapfile as part of the final link-edit. This techniqueis introduced in “Reducing Symbol Scope” on page 38. This public interfaceestablishes one or more version definitions within the object being created, andforms the foundation for the addition of new interfaces as the object evolves.

The following sections build upon this initial public interface. First though, it isuseful to understand how various changes to an interface can be categorized sothat they can be managed appropriately.

Interface CompatibilityThere are many types of change that can be made to an object. In their simplestterms these changes can be categorized into one of two groups:

• compatible updates. These updates are additive, in that all previouslyavailable interfaces remain intact.

• incompatible updates. These updates have changed the existing interface insuch a way that existing users of the interface can fail or behave incorrectly.

The following list attempts to clarify some common object changes into one ofthe above categorizations:

• the addition of a symbol - a compatible update.

• the removal of a symbol - an incompatible update.

• the addition of an argument to a non-varargs(5) function - an incompatiblechange.

• the removal of an argument from a function - an incompatible update.

• the change of size, or content, of a data item to a function or as an externaldefinition - an incompatible change.

Page 131: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 117

5

• a bug fix, or internal enhancement to a function - a compatible changeproviding the semantic properties of the object remain unchanged,otherwise, this is an incompatible change.

Note – It is possible, because of interposition, that the addition of a symbol canconstitute an incompatible update, such that the new symbol might conflict withan applications use of that symbol. However, this does seem rare in practice assource level name space management is commonly used.

Compatible updates can be accommodated by maintaining version definitionsinternal to the object being generated. Incompatible updates can beaccommodated by producing a new object with a new external versioned name.Both of these versioning techniques allow for the selective binding ofapplications as well as verification of correct version binding at runtime. Thesetwo techniques are explored in more detail in the following sections.

Internal VersioningA dynamic object can have associated with it one or more internal versiondefinitions. Each version definition is commonly associated with one or moresymbol names. A symbol name can only be associated with one versiondefinition, however a version definition can inherit the symbols from otherversion definitions. Thus, a structure exists to define one or more independent,or related, version definitions within the object being created. As new changesare made to the object, new version definitions can be added to express thesechanges.

There are two consequences of providing version definitions within a sharedobject:

• Dynamic objects that are built against this shared object can record theirdependency on the version definitions they bind to. These versiondependencies will be verified at runtime to insure that the appropriateinterfaces, or functionality, are available for the correct execution of anapplication.

• Dynamic objects can select only those version definitions of a shared objectthat they wish to bind to during their link-edit. This mechanism allowsdevelopers to control their dependency on a shared object to the interfaces,or functionality, that provide the most flexibility.

Page 132: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

118 Linker and Libraries Guide—November 1995

5

Creating a Version Definition

Version definitions commonly consist of an association of symbol names to aunique version name. These associations are established within a mapfile andsupplied to the final link-edit of an object using the link-editor’s -M option(this technique was introduced in the section “Reducing Symbol Scope” onpage 38).

A version definition is established whenever a version name is specified aspart of the mapfile directive. In the following example two source files arecombined, together with mapfile directives, to produce an object with adefined public interface:

Here, the symbol foo1 is the only global symbol defined to provide the sharedobject’s public interface. The special auto-reduction directive “*” causes thereduction of all other global symbols to have local binding within the objectbeing generated (this directive is introduced in “Defining Additional Symbols”

$ cat foo.cextern const char * _foo1;

void foo1(){ (void) printf(_foo1);}

$ cat data.cconst char * _foo1 = “string used by foo1()\n”;

$ cat mapfileSUNW_1.1 { # Release X global: foo1; local: *;};$ cc -o libfoo.so.1 -M mapfile -G foo.o data.o$ nm -x libfoo.so.1 | grep “foo.$”[33] |0x0001058c|0x00000004|OBJT |LOCL |0x0 |17 |_foo1[35] |0x00000454|0x00000034|FUNC |GLOB |0x0 |9 |foo1

Page 133: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 119

5

on page 32). The associated version name, SUNW_1.1, causes the generation ofa version definition. Thus, the shared object’s public interface consists of theinternal version definition SUNW_1.1, associated with the global symbol foo1 .

Whenever a version definition, or the auto-reduction directive, are used togenerate an object, a base version definition is also created. This base version isdefined using the name of the file itself, and is used to associate any reservedsymbols generated by the link-editor (see “Generating the Output Image” onpage 42 for a list of these reserved symbols).

The version definitions contained within an object can be displayed usingpvs(1) with the -d option:

Here, the object libfoo.so.1 has an internal version definition namedSUNW_1.1, together with a base version definition libfoo.so.1 .

Note – The link-editor’s -z noversion option allows mapfile directedsymbol reduction to be performed but suppresses the creation of versiondefinitions.

$ pvs -d libfoo.so.1 libfoo.so.1; SUNW_1.1;

Page 134: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

120 Linker and Libraries Guide—November 1995

5

Starting with this initial version definition, it is possible for the object to evolveby adding new interfaces and updated functionality. For example, a newfunction, foo2 , together with its supporting data structures, can be added tothe object by updating the source files foo.c and data.c :

A new version definition, SUNW_1.2, can be created to define a new interfacerepresenting the symbol foo2 . In addition, this new interface can be defined toinherit the original version definition SUNW_1.1.

The creation of this new interface is important as it identifies the evolution ofthe object and enables users to verify and select the interfaces to which theybind. These concepts are covered in more detail in “Binding to a VersionDefinition” on page 126 and in “Specifying a Version Binding” on page 132.

$ cat foo.cextern const char * _foo1;extern const char * _foo2;

void foo1(){ (void) printf(_foo1);}

void foo2(){ (void) printf(_foo2);}

$ cat data.cconst char * _foo1 = “string used by foo1()\n”;const char * _foo2 = “string used by foo2()\n”;

Page 135: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 121

5

The following example shows the mapfile directives that create these twointerfaces:

Here, the symbols foo1 and foo2 are both defined to be part of the sharedobject’s public interface. However, each of these symbols is assigned to adifferent version definition; foo1 is assigned to SUNW_1.1, and foo2 isassigned to SUNW_1.2.

$ cat mapfileSUNW_1.1 { # Release X global: foo1; local: *;};

SUNW_1.2 { # Release X+1 global: foo2;} SUNW_1.1;

$ cc -o libfoo.so.1 -M mapfile -G foo.o data.o$ nm -x libfoo.so.1 | grep “foo.$”[33] |0x00010644|0x00000004|OBJT |LOCL |0x0 |17 |_foo1[34] |0x00010648|0x00000004|OBJT |LOCL |0x0 |17 |_foo2[36] |0x000004bc|0x00000034|FUNC |GLOB |0x0 |9 |foo1[37] |0x000004f0|0x00000034|FUNC |GLOB |0x0 |9 |foo2

Page 136: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

122 Linker and Libraries Guide—November 1995

5

These version definitions, their inheritance, and their symbol association canbe displayed using pvs(1) together with the -d , -v and -s options:

Here, the version definition SUNW_1.2 has a dependency on the versiondefinition SUNW_1.1.

The inheritance of one version definition by another is a useful technique thatreduces the version information that will eventually be recorded by any objectthat binds to a version dependency. Version inheritance is covered in moredetail in the section “Binding to a Version Definition” on page 126.

Any internal version definition will have an associated version definition symbolcreated. As shown in the previous pvs(1) example, these symbols aredisplayed when using the -v option. The use of these symbols will be coveredin the section “Binding to a Weak Version Definition” on page 130.

Creating a Weak Version Definition

Internal changes to an object that do not require the introduction of a newinterface definition, can be defined by creating a weak version definition.Examples of such changes are bug fixes or performance improvements.

Such a version definition is empty, in that it has no global interface symbolsassociated with it.

$ pvs -dsv libfoo.so.1 libfoo.so.1: _end; _GLOBAL_OFFSET_TABLE_; _DYNAMIC; _edata; _PROCEDURE_LINKAGE_TABLE_; _etext; SUNW_1.1: foo1; SUNW_1.1; SUNW_1.2: {SUNW_1.1}: foo2; SUNW_1.2

Page 137: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 123

5

For example, if the data file data.c , used in the previous examples, isupdated to provide more detailed string definitions:

then a weak version definition can be introduced to identify this change:

Here, the empty version definition is signified by the weak label. These weakversion definitions allow applications to verify the existence of a particularimplementation by binding to the version definition associated with thatfunctionality. The section, “Binding to a Version Definition” on page 126,illustrates how these definitions can be used in more detail.

$ cat data.cconst char * _foo1 = “string used by function foo1()\n”;const char * _foo2 = “string used by function foo2()\n”;

$ cat mapfileSUNW_1.1 { # Release X global: foo1; local: *;};

SUNW_1.2 { # Release X+1 global: foo2;} SUNW_1.1;

SUNW_1.2.1 { } SUNW_1.2; # Release X+2

$ cc -o libfoo.so.1 -M mapfile -G foo.o data.o$ pvs -dv libfoo.so.1 libfoo.so.1; SUNW_1.1; SUNW_1.2: {SUNW_1.1}; SUNW_1.2.1 [WEAK]: {SUNW_1.2};

Page 138: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

124 Linker and Libraries Guide—November 1995

5

Defining Unrelated Interfaces

The previous examples have shown how new version definitions added to anobject have inherited any existing version definitions. It is also possible tocreate version definitions that are unique and independent. In the followingexample, two new files, bar1.c and bar2.c , are added to the objectlibfoo.so.1 . These files contribute two new symbols, bar1 and bar2 ,respectively:

These two symbols are intended to define two new public interfaces. Neither ofthese new interfaces are related to each other, however each expresses adependency on the original SUNW_1.2 interface.

$ cat bar1.cextern void foo1();

void bar1(){ foo1();}$ cat bar2.cextern void foo2();

void bar2(){ foo2();}

Page 139: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 125

5

The following mapfile definition creates this required association:

Again, the version definitions created in libfoo.so.1 using this mapfile ,and their related dependencies, can be inspected using pvs(1) :

The following sections explore how these version definition recordings can beused to verify runtime binding requirements and control the bindingrequirements of an object during its creation.

$ cat mapfileSUNW_1.1 { # Release X global: foo1; local: *;};

SUNW_1.2 { # Release X+1 global: foo2;} SUNW_1.1;

SUNW_1.2.1 { } SUNW_1.2; # Release X+2

SUNW_1.3a { # Release X+3 global: bar1;} SUNW_1.2;

SUNW_1.3b { # Release X+3 global: bar2;} SUNW_1.2;

$ cc -o libfoo.so.1 -M mapfile -G foo.o bar.o data.o$ pvs -dv libfoo.so.1 libfoo.so.1; SUNW_1.1; SUNW_1.2: {SUNW_1.1}; SUNW_1.2.1 [WEAK]: {SUNW_1.2}; SUNW_1.3a: {SUNW_1.2}; SUNW_1.3b: {SUNW_1.2};

Page 140: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

126 Linker and Libraries Guide—November 1995

5

Binding to a Version Definition

When a dynamic executable or shared object is built against other sharedobjects, these dependencies are recorded in the resulting object (see “SharedObject Processing” on page 13 and “Recording a Shared Object Name” onpage 86 for more details). If these shared object dependencies also containversion definitions then an associated version dependency will be recorded in theresulting object.

The following example takes the data files from the previous section andgenerates a shared object suitable for a compile time environment. This sharedobject, libfoo.so.1 , will be used in following binding examples:

In effect, there are six public interfaces being offered by this shared object. Fourof these interfaces (SUNW_1.1, SUNW_1.2, SUNW_1.3a and SUNW_1.3b)define a set of functions, one interface (SUNW_1.2.1 ) describes an internal

$ cc -o libfoo.so.1 -h libfoo.so.1 -M mapfile -G foo.o bar.o \data.o$ ln -s libfoo.so.1 libfoo.so$ pvs -dsv libfoo.so.1 libfoo.so.1: _end; _GLOBAL_OFFSET_TABLE_; _DYNAMIC; _edata; _PROCEDURE_LINKAGE_TABLE_; _etext; SUNW_1.1: foo1; SUNW_1.1; SUNW_1.2: {SUNW_1.1}: foo2; SUNW_1.2; SUNW_1.2.1 [WEAK]: {SUNW_1.2}: SUNW_1.2.1; SUNW_1.3a: {SUNW_1.2}: bar1; SUNW_1.3a; SUNW_1.3b: {SUNW_1.2}: bar2; SUNW_1.3b

Page 141: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 127

5

implementation change to the shared object, and one interface (libfoo.so.1 )defines several reserved labels. Dynamic objects that build with this object willrecord which of these interfaces they bind to.

The following example builds an application that references both symbolsfoo1 and foo2 . The versioning dependency information recorded in theapplication can be examined using pvs(1) with the -r option:

In this example, the application prog has really bound to the two interfacesSUNW_1.1 and SUNW_1.2, as these interfaces have provided the globalsymbols foo1 and foo2 respectively.

However, since version definition SUNW_1.1 is defined within libfoo.so.1as being inherited by the version definition SUNW_1.2, it is only necessary torecord the latter version dependency. This normalization of version definitiondependencies reduces the amount of version information that must bemaintained within an object and processed at runtime.

Since the application prog was built against the shared object’simplementation containing the weak version definition SUNW_1.2.1 , thisdependency is also recorded. Even though this version definition is defined toinherit the version definition SUNW_1.2, the version’s weak nature precludesits normalization with SUNW_1.1, and results in a separate dependencyrecording.

Had there been multiple weak version definitions that inherit from each otherthen these definitions will be normalized in the same manner as non-weakversion definitions are.

$ cat prog.cextern void foo1();extern void foo2();

main(){ foo1(); foo2();}$ cc -o prog prog.c -L. -R. -lfoo$ pvs -r prog libfoo.so.1 (SUNW_1.2, SUNW_1.2.1);

Page 142: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

128 Linker and Libraries Guide—November 1995

5

Note – The recording of a version dependency can be suppressed by thelink-editor’s -z noversion option.

Having recorded these version definition dependencies, the runtime linkervalidates the existence of the required version definitions in the objects boundto when the application is executed. This validation can be displayed usingldd(1) with the -v option. For example, by running ldd(1) on theapplication prog , the version definition dependencies are shown to be foundcorrectly in the shared object libfoo.so.1 :

Note – ldd(1) with the -v option implies verbose output, in that a recursivelist of all dependencies, together with all versioning requirements, will begenerated.

If a non-weak version definition dependency cannot be found, a fatal error willoccur during application initialization. Any weak version definitiondependency that cannot be found is silently ignored. For example, if theapplication prog was run in an environment in which libfoo.so.1 onlycontained the version definition SUNW_1.1, then the following fatal error willoccur:

$ ldd -v prog

find library=libfoo.so.1; required by prog libfoo.so.1 => ./libfoo.so.1 find version=libfoo.so.1; libfoo.so.1 (SUNW_1.2) => ./libfoo.so.1 libfoo.so.1 (SUNW_1.2.1) => ./libfoo.so.1 ....

$ pvs -dv libfoo.so.1 libfoo.so.1; SUNW_1.1;$ progld.so.1: prog: fatal: libfoo.so.1: version ‘SUNW_1.2’ not \found (required by file prog)

Page 143: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 129

5

Had the application prog not recorded any version definition dependencies,the nonexistence of the required interface symbol foo2 will have manifesteditself sometime during the execution of the application as a fatal relocationerror (see “Relocation Errors” on page 61). This relocation error might occur atprocess initialization, during process execution, or might not occur at all if theexecution path of the application did not call the function foo2 .

Recording version definition dependencies provides an alternative, andimmediate indication of the availability of the interfaces required by theapplication.

If the application prog was run in an environment in which libfoo.so.1only contained the version definitions SUNW_1.1 and SUNW_1.2, then all non-weak version definition requirements will be satisfied. The absence of the weakversion definition SUNW_1.2.1 is deemed nonfatal, and so no runtime errorcondition will be generated. However, ldd(1) can be used to display allversion definitions that cannot be found:

Note – If an object requires a version definition from a given dependency, andat runtime an implementation of that dependency is found that contains noversion definition information, the version verification of the dependency willbe silently ignored. This policy provides a level of backward compatibility asthe transition from non-versioned to versioned shared objects is taken. ldd(1)however, can still be used to display any version requirement discrepancies.

$ pvs -dv libfoo.so.1 libfoo.so.1; SUNW_1.1; SUNW_1.2: {SUNW_1.1};$ progstring used by foo1()string used by foo2()$ ldd prog libfoo.so.1 => ./libfoo.so.1 libfoo.so.1 (SUNW_1.2.1) => (version not found) ...........

Page 144: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

130 Linker and Libraries Guide—November 1995

5

Binding to a Weak Version Definition

Recall that weak version definitions are used to mark an internalimplementation change, and are well suited to indicating bug fixes andperformance improvements made to an object. If you require the existence of aweak version definition for the correct execution of an application, then anexplicit dependency on this version definition can be generated.

Establishing such a dependency can be important when a bug fix, orperformance improvement, become critical for the application to functioncorrectly.

Each version definition maintained within an object has an absolute versiondefinition symbol associated with it. For example, the shared objectlibfoo.so.1 containing the version definitions shown in previous exampleshas the following version definition symbols:

By making explicit reference to a version definition’s symbol, an explicitdependency on that version definition is created. This explicit reference alsocauses the version definition to be promoted from a weak to a strongdependency.

$ pvs -dsv libfoo.so.1 | fgrep SUNW_1 SUNW_1.1: SUNW_1.1; SUNW_1.2: {SUNW_1.1}: SUNW_1.2; SUNW_1.2.1 [WEAK]: {SUNW_1.2}: SUNW_1.2.1; SUNW_1.3a: {SUNW_1.2}: SUNW_1.3a; SUNW_1.3b: {SUNW_1.2}: SUNW_1.3b;

Page 145: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 131

5

Therefore, the application prog can be built to enforce the requirement that theSUNW_1.2.1 interface be made available at runtime. A reference to the versiondefinition can be generated using the link-editor’s -u option:

Here, prog has been built with an explicit dependency on the interfacesSUNW_1.1, SUNW_1.2, and SUNW_1.2.1 . Because the version definitionSUNW_1.2.1 is promoted to a strong version, it is also normalized with itsdependency SUNW_1.2. At runtime, if the version definition SUNW_1.2.1cannot be found, a fatal error will be generated.

Verifying Versions in Additional Objects

Version definition symbols also provide a mechanism for verifying the versionrequirements of an object obtained by dlopen(3X) . Any object added to theprocess’s address space using this function will have no automatic versiondependency verification carried out by the runtime linker. Thus, it is theresponsibility of the caller of this function to verify that any versioningrequirements are met.

$ cat progextern void foo1();extern void foo2();

main(){ foo1(); foo2();}$ cc -u SUNW_1.2.1 -o prog prog.c -L. -R. -lfoo$ pvs -r prog libfoo.so.1 (SUNW_1.2.1);

Page 146: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

132 Linker and Libraries Guide—November 1995

5

The presence of a required version definition can be verified by looking up theassociated version definition symbol using dlsym(3X) . The following exampleshows the shared object libfoo.so.1 being added to a process bydlopen(3X) and verified to insure that the interface SUNW_1.2 is available:

Specifying a Version Binding

When building a dynamic object against a shared object containing versiondefinitions, it is possible to instruct the link-editor to limit the binding tospecific version definitions. Effectively, the link-editor allows you to control anobject’s binding to specific interfaces.

An object’s binding requirements can be controlled using a file control directive.This directive is supplied using the link-editor’s -M option and an associatedmapfile . The syntax for these version control mapfile directives is shownbelow:

#include <stdio.h>#include <dlfcn.h>

main(){ void * handle; const char * file = “libfoo.so.1”; const char * vers = “SUNW_1.2”; ....

if ((handle = dlopen(file, RTLD_LAZY)) == NULL) { (void) printf(“dlopen: %s\n”, dlerror()); exit (1); }

if (dlsym(handle, vers) == NULL) { (void) printf(“fatal: %s: version ‘%s’ not found\n”, file, vers); exit (1); } ....

name - version [ version ... ] ;

Page 147: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 133

5

• name - represents the name of the shared object dependency. This nameshould match the shared object’s compilation environment name as used bythe link-editor (see “Library Naming Conventions” on page 14).

• version - represents the version definition name within the shared object thatshould be made available for binding. Multiple version definitions can bespecified.

There are a couple of scenarios where this binding control can be useful:

• If a shared object has been versioned to define unique and independentversions, possibly defining different standards interfaces, then theapplication can insure that its bindings meet the requirements of a specificinterface.

• If a shared object has been versioned over several software releases,application developers can restrict themselves to the interfaces that wereavailable in a previous software release. Thus, an application can be builtusing the latest release of the shared object in the knowledge that theapplication’s interface requirements can be met by a previous release of theshared object.

The following is an example of using the version control mechanism. Thisexample continues to use the shared object libfoo.so.1 containing thefollowing version interface definitions:

$ pvs -ds libfoo.so.1 libfoo.so.1: _end; _GLOBAL_OFFSET_TABLE_; _DYNAMIC; _edata; _PROCEDURE_LINKAGE_TABLE_; _etext; SUNW_1.1: foo1; SUNW_1.2: foo2;

Page 148: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

134 Linker and Libraries Guide—November 1995

5

The version definitions SUNW_1.1 and SUNW_1.2 represent interfaces withinlibfoo.so.1 that were made available in software Release X andRelease X+1 respectively. An application can be built to bind only to theinterfaces available in Release X by using the following version controlmapfile directive:

For example, if you develope an application, prog , and wish to insure that theapplication will run on Release X , then the application can only use theinterfaces available in that release. If the application mistakenly references thesymbol foo2 , then the application’s noncompliance to the required interfacewill be signalled by the link-editor as an undefined symbol error:

To be compliant with the SUNW_1.1 interface, you must remove the reference tofoo2 . This can be achieved either by reworking the application to remove therequirement on foo2 , or by adding an implementation of foo2 to the build ofthe application.

$ cat mapfilelibfoo.so - SUNW_1.1;

$ cat prog.cextern void foo1();extern void foo2();

main(){ foo1(); foo2();}$ cc -o prog prog.c -M mapfile -L. -R. -lfooUndefined first referenced symbol in filefoo2 prog.o (symbol belongs to \unavailable version ./libfoo.so (SUNW_1.2))ld: fatal: Symbol referencing errors. No output written to prog

Page 149: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 135

5

Relocatable Objects

The preceding sections have described how version information can berecorded and used within dynamic objects. Relocatable objects can maintainversioning information in a similar manner, however there are one or twosubtle differences in how this information is used.

Any version definitions supplied to the link-edit of a relocatable object arerecorded in exactly the same format as has been described in previousexamples. However, by default, symbol reduction is not carried out on theobject being created. Instead, when the relocatable object is finally used asinput to the generation of a dynamic object, the version recording itself will beused to determine the symbol reductions to apply.

In addition, any version definitions found in relocatable objects will bepropagated to the dynamic object. For an example of version processing inrelocatable objects see “Reducing Symbol Scope” on page 38.

External VersioningRuntime references to a shared object should always refer to the files versionfilename. Commonly this is expressed as a filename suffixed with a versionnumber. When a shared object’s interface changes in an incompatible manner -such that it will break old applications - a new shared object should bedistributed with a new versioned filename. In addition, the original versionedfilename must still be distributed to provide the interfaces required by the oldapplications.

By providing shared objects as separate versioned filenames within theruntime environment, applications built over a series of software releases canbe guaranteed that the interface against which they were built is available forthem to bind during their execution.

The following section describes how to coordinate the binding of an interfacebetween the compilation and runtime environments.

Page 150: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

136 Linker and Libraries Guide—November 1995

5

Coordination of Versioned Filenames

In the section “Naming Conventions” on page 84 it was stated that during alink-edit the most common method to input shared objects was to use the -loption. This option will use the link-editor’s library search mechanism tolocate shared objects that are prefixed with lib and suffixed with .so .

However, at runtime any shared object dependencies should exist in theirversioned name form. Instead of maintaining two distinct shared objects thatfollow these naming conventions, the most common mechanism ofcoordinating these objects involves creating file system links between the twofilenames.

To make the runtime shared object libfoo.so.1 available to the compilationenvironment it is necessary to provide a symbolic link from the compilationfilename to the runtime filename. For example:

Note – Either a symbolic or hard link can be used. However, as adocumentation and diagnostic aid, symbolic links are more useful.

Here, the shared object libfoo.so.1 has been generated for the runtimeenvironment. Generating a symbolic link libfoo.so , has also enabled thisfile’s use in a compilation environment. For example:

Here the link-editor will process the relocatable object main.o with theinterface described by the shared object libfoo.so.1 which it will find byfollowing the symbolic link libfoo.so .

$ cc -o libfoo.so.1 -G -K pic foo.c$ ln -s libfoo.so.1 libfoo.so$ ls -l libfoo*lrwxrwxrwx 1 usr grp 11 1991 libfoo.so -> libfoo.so.1-rwxrwxr-x 1 usr grp 3136 1991 libfoo.so.1

$ cc -o prog main.o -L. -lfoo

Page 151: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning 137

5

If over a series of software releases, new versions of this shared object aredistributed with changed interfaces, the compilation environment can beconstructed to use the interface that is applicable by changing the symboliclink. For example:

Here, three major versions of the shared object are available. Two of theseshared objects, libfoo.so.1 and libfoo.so.2 , provide the dependenciesfor existing applications. libfoo.so.3 offers the latest major release forbuilding and running new applications.

Using this symbolic link mechanism itself is insufficient to coordinate thecorrect binding of a shared object from its use in the compilation environmentto its requirement in the runtime environment. As the example presentlystands, the link-editor will record in the dynamic executable prog the filenameof the shared object it has processed, which in this case will be the compilationenvironment filename:

This means that when the application prog is executed, the runtime linker willsearch for the dependency libfoo.so , and consequently this will bind towhichever file this symbolic link is pointing.

To provide the correct runtime name to be recorded as a dependency, theshared object libfoo.so.1 should be built with an soname definition. Thisdefinition identifies the shared objects runtime name, and is used as the

$ ls -l libfoo*lrwxrwxrwx 1 usr grp 11 1993 libfoo.so -> libfoo.so.3-rwxrwxr-x 1 usr grp 3136 1991 libfoo.so.1-rwxrwxr-x 1 usr grp 3237 1992 libfoo.so.2-rwxrwxr-x 1 usr grp 3554 1993 libfoo.so.3

$ dump -Lv prog

prog: **** DYNAMIC SECTION INFORMATION ****.dynamic:[INDEX] Tag Value[1] NEEDED libfoo.so.........

Page 152: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

138 Linker and Libraries Guide—November 1995

5

dependency name by any object that links against this shared object. Thisdefinition can be provided using the -h option during the link-edit of theshared object itself. For example:

This symbolic link and the soname mechanism has established a robustcoordination between the shared object naming conventions of the compilationand runtime environments, one in which the interface processed during thelink-edit is accurately recorded in the output file generated. This recordingensures that the intended interface will be furnished at runtime.

$ cc -o libfoo.so.1 -G -K pic -h libfoo.so.1 foo.c$ ln -s libfoo.so.1 libfoo.so$ cc -o prog main.o -L. -lfoo$ dump -Lv prog

prog: **** DYNAMIC SECTION INFORMATION ****.dynamic:[INDEX] Tag Value[1] NEEDED libfoo.so.1.........

Page 153: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

139

Object Files 6

IntroductionThis chapter describes the executable and linking format (ELF) of the objectfiles produced by the assembler and link-editor. There are three main types ofobject files:

• A relocatable file holds code and data suitable to be linked with other objectfiles to create an executable or shared object file, or another relocatableobject.

• An executable file holds a program that is ready to execute. The file specifieshow exec(2) creates a program’s process image.

• A shared object file holds code and data suitable to be linked in twocontexts. First, the link-editor can process it with other relocatable andshared object files to create other object files. Second, the runtime linkercombines it with a dynamic executable file and other shared objects to createa process image.

The first section in this chapter, “File Format” on page 140, focuses on theformat of object files and how that pertains to building programs. The secondsection, “Dynamic Linking” on page 189, focuses on how the format pertains toloading programs.

Programs manipulate object files with the functions contained in the ELFaccess library, libelf . Refer to man Pages(3): Library Routines” for adescription of libelf contents.

Page 154: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

140 Linker and Libraries Guide—November 1995

6

File FormatAs indicated, object files participate in both program linking and programexecution. For convenience and efficiency, the object file format providesparallel views of a file’s contents, reflecting the differing needs of theseactivities. Figure 6-1 shows an object file’s organization.

Figure 6-1 Object File Format

An ELF header resides at the beginning of an object file and holds a road mapdescribing the file’s organization.

Sections represent the smallest indivisible units that may be processed withinan ELF file. Segments are a collection of sections that represent the smallestindividual units that may be mapped to a memory image by exec(2) or bythe runtime linker.

Sections hold the bulk of object file information for the linking view:instructions, data, symbol table, relocation information, and so on.Descriptions of sections appear in the first part of this chapter. The second partof this chapter discusses segments and the program execution view of the file.

Linking view

ELF header

Program header tableoptional

Section 1

. . .

Section n

. . .

. . .

Section header table

Execution view

ELF header

Program header table

Segment 1

Segment 2

. . .

Section header tableoptional

Page 155: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 141

6

A program header table, if present, tells the system how to create a processimage. Files used to build a process image (executables and shared objects)must have a program header table; relocatable objects do not need one.

A section header table contains information describing the file’s sections. Everysection has an entry in the table; each entry gives information such as thesection name, the section size, and so forth. Files used in link-editing musthave a section header table; other object files may or may not have one.

Note – Although the figure shows the program header table immediately afterthe ELF header, and the section header table following the sections; actual filesmay differ. Moreover, sections and segments have no specified order. Only theELF header has a fixed position in the file.

Data Representation

As described here, the object file format supports various processors with 8-bitbytes and 32-bit architectures. Nevertheless, it is intended to be extensible tolarger (or smaller) architectures.

Object files therefore represent some control data with a machine-independentformat, making it possible to identify object files and interpret their contents ina common way. Remaining data in an object file use the encoding of the targetprocessor, regardless of the machine on which the file was created.

All data structures that the object file format defines follow the natural size andalignment guidelines for the relevant class. If necessary, data structures containexplicit padding to ensure 4-byte alignment for 4-byte objects, to force

Table 6-1 32-Bit Data Types

Name Size Alignment Purpose

Elf32_Addr 4 4 Unsigned program address

Elf32_Half 2 2 Unsigned medium integer

Elf32_Off 4 4 Unsigned file offset

Elf32_Sword 4 4 Signed large integer

Elf32_Word 4 4 Unsigned large integer

unsigned char 1 1 Unsigned small integer

Page 156: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

142 Linker and Libraries Guide—November 1995

6

structure sizes to a multiple of 4, and so forth. Data also have suitablealignment from the beginning of the file. Thus, for example, a structurecontaining an Elf32_Addr member will be aligned on a 4-byte boundarywithin the file.

Note – For portability, ELF uses no bit-fields.

ELF Header

Some object file control structures can grow, because the ELF header containstheir actual sizes. If the object file format changes, a program may encountercontrol structures that are larger or smaller than expected. Programs mighttherefore ignore extra information. The treatment of missing informationdepends on context and will be specified if and when extensions are defined.

The ELF header has the following structure (defined in sys/elf.h ):

e_identThe initial bytes mark the file as an object file and provide machine-independent data with which to decode and interpret the file’s contents.Complete descriptions appear in “ELF Identification” on page 146.

#define EI_NIDENT 16

typedef struct { unsigned char e_ident[EI_NIDENT]; Elf32_Half e_type; Elf32_Half e_machine; Elf32_Word e_version; Elf32_Addr e_entry; Elf32_Off e_phoff; Elf32_Off e_shoff; Elf32_Word e_flags; Elf32_Half e_ehsize; Elf32_Half e_phentsize; Elf32_Half e_phnum; Elf32_Half e_shentsize; Elf32_Half e_shnum; Elf32_Half e_shstrndx;} Elf32_Ehdr;

Page 157: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 143

6

e_typeThis member identifies the object file type.

Although the core file contents are unspecified, type ET_CORE is reserved tomark the file. Values from ET_LOPROC through ET_HIPROC (inclusive) arereserved for processor-specific semantics. Other values are reserved and willbe assigned to new object file types as necessary.

e_machineThis member’s value specifies the required architecture for an individualfile.

Table 6-2 ELF File Identifiers

Name Value Meaning

ET_NONE 0 No file type

ET_REL 1 Relocatable file

ET_EXEC 2 Executable file

ET_DYN 3 Shared object file

ET_CORE 4 Core file

ET_LOPROC 0xff00 Processor-specific

ET_HIPROC 0xffff Processor-specific

Table 6-3 ELF Machines

Name Value Meaning

EM_NONE 0 No machine

EM_M32 1 AT&T WE 32100

EM_SPARC 2 SPARC

EM_386 3 Intel 80386

EM_68K 4 Motorola 68000

EM_88K 5 Motorola 88000

EM_486 6 Intel 80486

EM_860 7 Intel 80860

EM_MIPS 8 MIPS RS3000 Big-Endian

Page 158: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

144 Linker and Libraries Guide—November 1995

6

Other values are reserved and will be assigned to new machines asnecessary. Processor-specific ELF names use the machine name todistinguish them. For example, the flags mentioned below use the prefixEF_; a flag named WIDGET for the EM_XYZ machine would be calledEF_XYZ_WIDGET.

e_versionThis member identifies the object file version.

The value 1 signifies the original file format; extensions will create newversions with higher numbers. The value of EV_CURRENT changes asnecessary to reflect the current version number.

e_entryThis member gives the virtual address to which the system first transferscontrol, thus starting the process. If the file has no associated entry point,this member holds zero.

e_phoffThis member holds the program header table’s file offset in bytes. If the filehas no program header table, this member holds zero.

EM_MIPS_RS3_LE 10 MIPS RS3000 Little-Endian

EM_RS6000 11 RS6000

EM_PA_RISC 15 PA-RISC

EM_nCUBE 16 nCUBE

EM_VPP500 17 Fujitsu VPP500

EM_SPARC32PLUS 18 Sun SPARC 32+

EM_PPC 20 PowerPC

Table 6-4 ELF Versions

Name Value Meaning

EV_NONE 0 Invalid version

EV_CURRENT >=1 Current version

Table 6-3 ELF Machines

Name Value Meaning

Page 159: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 145

6

e_shoffThis member holds the section header table’s file offset in bytes. If the filehas no section header table, this member holds zero.

e_flagsThis member holds processor-specific flags associated with the file. Flagnames take the form EF_machine _flag . This member is presently zero forSPARC, x86, and PowerPC.

e_ehsizeThis member holds the ELF header’s size in bytes.

e_phentsizeThis member holds the size in bytes of one entry in the file’s programheader table; all entries are the same size.

e_phnumThis member holds the number of entries in the program header table. Thusthe product of e_phentsize and e_phnum gives the table’s size in bytes. Ifa file has no program header table, e_phnum holds the value zero.

e_shentsizeThis member holds a section header’s size in bytes. A section header is oneentry in the section header table; all entries are the same size.

e_shnumThis member holds the number of entries in the section header table. Thusthe product of e_shentsize and e_shnum gives the section header table’ssize in bytes. If a file has no section header table, e_shnum holds the valuezero.

e_shstrndxThis member holds the section header table index of the entry associatedwith the section name string table. If the file has no section name stringtable, this member holds the value SHN_UNDEF. See “Sections” on page 148and “String Table” on page 161 for more information.

Page 160: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

146 Linker and Libraries Guide—November 1995

6

ELF Identification

As mentioned above, ELF provides an object file framework to supportmultiple processors, multiple data encodings, and multiple classes ofmachines. To support this object file family, the initial bytes of the file specifyhow to interpret the file, independent of the processor on which the inquiry ismade and independent of the file’s remaining contents.

The initial bytes of an ELF header (and an object file) correspond to thee_ident member.

These indexes access bytes that hold the following values:

EI_MAG0 - EI_MAG3A file’s first 4 bytes hold a magic number, identifying the file as an ELF objectfile.

Table 6-5 e_ident[ ] Identification Index

Name Value Purpose

EI_MAG0 0 File identification

EI_MAG1 1 File identification

EI_MAG2 2 File identification

EI_MAG3 3 File identification

EI_CLASS 4 File class

EI_DATA 5 Data encoding

EI_VERSION 6 File version

EI_PAD 7 Start of padding bytes

EI_NIDENT 16 Size of e_ident[]

Table 6-6 Magic Number

Name Value Position

ELFMAG0 0x7f e_ident[EI_MAG0]

ELFMAG1 ’E’ e_ident[EI_MAG1]

ELFMAG2 ’L’ e_ident[EI_MAG2]

ELFMAG3 ’F’ e_ident[EI_MAG3]

Page 161: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 147

6

EI_CLASSThe next byte, e_ident[EI_CLASS] , identifies the file’s class, or capacity.

The file format is designed to be portable among machines of various sizes,without imposing the sizes of the largest machine on the smallest. ClassELFCLASS32 supports machines with files and virtual address spaces up to4 gigabytes; it uses the basic types defined above.

Class ELFCLASS64 is reserved for 64-bit architectures. Its appearance hereshows how the object file may change, but the 64-bit format is otherwiseunspecified. Other classes will be defined as necessary, with different basictypes and sizes for object file data.

EI_DATAByte e_ident[EI_DATA] specifies the data encoding of the processor-specific data in the object file. The following encodings are currentlydefined.

More information on these encodings appears below. Other values arereserved and will be assigned to new encodings as necessary.

EI_VERSIONByte e_ident[EI_VERSION] specifies the ELF header version number.Currently, this value must be EV_CURRENT, as explained in Table 6-4 onpage 144 for e_version .

Table 6-7 File Class

Name Value Meaning

ELFCLASSNONE 0 Invalid class

ELFCLASS32 1 32-bit objects

ELFCLASS64 2 64-bit objects

Table 6-8 Data Encoding

Name Value Meaning

ELFDATANONE 0 Invalid data encoding

ELFDATA2LSB 1 See below

ELFDATA2MSB 2 See below

Page 162: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

148 Linker and Libraries Guide—November 1995

6

EI_PADThis value marks the beginning of the unused bytes in e_ident . Thesebytes are reserved and set to zero; programs that read object files shouldignore them. The value of EI_PAD will change in the future if currentlyunused bytes are given meanings.

A file’s data encoding specifies how to interpret the basic objects in a file. Asdescribed above, class ELFCLASS32 files use objects that occupy 1, 2, and 4bytes. Under the defined encodings, objects are represented as shown below.Byte numbers appear in the upper left corners.

Encoding ELFDATA2LSB specifies 2’s complement values, with the leastsignificant byte occupying the lowest address.

Figure 6-2 Data Encoding ELFDATA2LSB

Encoding ELFDATA2MSB specifies 2’s complement values, with the mostsignificant byte occupying the lowest address.

Figure 6-3 Data Encoding ELFDATA2MSB

Sections

An object file’s section header table lets you locate all file’s sections. Thesection header table is an array of Elf32_Shdr structures as described below.A section header table index is a subscript into this array. The ELF header’s

0x01 010

0x0102 02 010 1

0x01020304 04 03 02 010 1 2 3

0x01 010

0x0102 01 020 1

0x01020304 01 02 03 040 1 2 3

Page 163: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 149

6

e_shoff member gives the byte offset from the beginning of the file to thesection header table; e_shnum tells how many entries the section header tablecontains; e_shentsize gives the size in bytes of each entry.

Some section header table indexes are reserved; an object file does not havesections for these special indexes.

SHN_UNDEFThis value marks an undefined, missing, irrelevant, or otherwisemeaningless section reference. For example, a symbol defined relative tosection number SHN_UNDEF is an undefined symbol.

Note – Although index 0 is reserved as the undefined value, the section headertable contains an entry for index 0. That is, if the e_shnum member of the ELFheader says a file has 6 entries in the section header table, they have theindexes 0 through 5. The contents of the initial entry are specified later in thissection.

SHN_LORESERVEThis value specifies the lower bound of the range of reserved indexes.

SHN_LOPROC - SHN_HIPROCValues in this inclusive range are reserved for processor-specific semantics.

SHN_ABSThis value specifies absolute values for the corresponding reference. Forexample, symbols defined relative to section number SHN_ABS haveabsolute values and are not affected by relocation.

Table 6-9 Special Section Indexes

Name Value

SHN_UNDEF 0

SHN_LORESERVE 0xff00

SHN_LOPROC 0xff00

SHN_HIPROC 0xff1f

SHN_ABS 0xfff1

SHN_COMMON 0xfff2

SHN_HIRESERVE 0xffff

Page 164: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

150 Linker and Libraries Guide—November 1995

6

SHN_COMMONSymbols defined relative to this section are common symbols, such asFORTRAN COMMON or unallocated C external variables. These symbols aresometimes referred to as tentative.

SHN_HIRESERVEThis value specifies the upper bound of the range of reserved indexes. Thesystem reserves indexes between SHN_LORESERVE and SHN_HIRESERVE,inclusive; the values do not reference the section header table. That is, thesection header table does not contain entries for the reserved indexes.

Sections contain all information in an object file except the ELF header, theprogram header table, and the section header table. Moreover, object files’sections satisfy several conditions:

• Every section in an object file has exactly one section header describing it.Section headers may exist that do not have a section.

• Each section occupies one contiguous (possibly empty) sequence of byteswithin a file.

• Sections in a file may not overlap. No byte in a file resides in more than onesection.

• An object file may have inactive space. The various headers and the sectionsmight not cover every byte in an object file. The contents of the inactive dataare unspecified.

A section header has the following structure (defined in sys/elf.h ):

typedef struct { Elf32_Word sh_name; Elf32_Word sh_type; Elf32_Word sh_flags; Elf32_Addr sh_addr; Elf32_Off sh_offset; Elf32_Word sh_size; Elf32_Word sh_link; Elf32_Word sh_info; Elf32_Word sh_addralign; Elf32_Word sh_entsize;} Elf32_Shdr;

Page 165: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 151

6

sh_nameThis member specifies the name of the section. Its value is an index into thesection header string table section (see “String Table” on page 161), givingthe location of a null-terminated string. Section names and their descriptionsare in Table 6-14 on page 157.

sh_typeThis member categorizes the section’s contents and semantics. Section typesand their descriptions are in Table 6-10 on page 152.

sh_flagsSections support 1-bit flags that describe miscellaneous attributes. Flagdefinitions are inTable 6-12 on page 155.

sh_addrIf the section is to appear in the memory image of a process, this membergives the address at which the section’s first byte should reside. Otherwise,the member contains 0.

sh_offsetThis member gives the byte offset from the beginning of the file to the firstbyte in the section. Section type SHT_NOBITS, described below, occupies nospace in the file, and its sh_offset member locates the conceptualplacement in the file.

sh_sizeThis member gives the section’s size in bytes. Unless the section type isSHT_NOBITS, the section occupies sh_size bytes in the file. A section oftype SHT_NOBITS may have a nonzero size, but it occupies no space in thefile.

sh_linkThis member holds a section header table index link, whose interpretationdepends on the section type. Table 6-13 on page 156 describes the values.

sh_infoThis member holds extra information, whose interpretation depends on thesection type. Table 6-13 on page 156 below describes the values.

sh_addralignSome sections have address alignment constraints. For example, if a sectionholds a double-word, the system must ensure double-word alignment forthe entire section. That is, the value of sh_addr must be congruent to 0,

Page 166: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

152 Linker and Libraries Guide—November 1995

6

modulo the value of sh_addralign . Currently, only 0 and positive integralpowers of two are allowed. Values 0 and 1 mean the section has noalignment constraints.

sh_entsizeSome sections hold a table of fixed-size entries, such as a symbol table. Forsuch a section, this member gives the size in bytes of each entry. Themember contains 0 if the section does not hold a table of fixed-size entries.

A section header’s sh_type member specifies the section’s semantics:

Table 6-10 Section Types, sh_type

Name Value

SHT_NULL 0

SHT_PROGBITS 1

SHT_SYMTAB 2

SHT_STRTAB 3

SHT_RELA 4

SHT_HASH 5

SHT_DYNAMIC 6

SHT_NOTE 7

SHT_NOBITS 8

SHT_REL 9

SHT_SHLIB 10

SHT_DYNSYM 11

SHT_SUNW_verdef 0x6ffffffd

SHT_SUNW_verneed 0x6ffffffe

SHT_SUNW_versym 0x6fffffff

SHT_LOPROC 0x70000000

SHT_HIPROC 0x7fffffff

SHT_LOUSER 0x80000000

SHT_HIUSER 0xffffffff

Page 167: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 153

6

SHT_NULLThis value marks the section header as inactive; it does not have anassociated section. Other members of the section header have undefinedvalues.

SHT_PROGBITSThe section holds information defined by the program, whose format andmeaning are determined solely by the program.

SHT_SYMTAB, SHT_DYNSYMThese sections hold a symbol table. Typically a SHT_SYMTAB sectionprovides symbols for link-editing. As a complete symbol table, it maycontain many symbols unnecessary for dynamic linking. Consequently, anobject file may also contain a SHT_DYNSYM section, which holds a minimalset of dynamic linking symbols, to save space. See “Symbol Table” onpage 162 for details.

SHT_STRTAB, SHT_DYNSTRThese sections hold a string table. An object file may have multiple stringtable sections. See “String Table” on page 161 for details.

SHT_RELAThe section holds relocation entries with explicit addends, such as typeElf32_Rela for the 32-bit class of object files. An object file may havemultiple relocation sections. See “Relocation” on page 167 for details.

SHT_HASHThe section holds a symbol hash table. All dynamically linked object filesmust contain a symbol hash table. Currently, an object file may have onlyone hash table, but this restriction may be relaxed in the future. See “HashTable” on page 224 for details.

SHT_DYNAMICThe section holds information for dynamic linking. Currently, an object filemay have only one dynamic section, but this restriction may be relaxed inthe future. See “Dynamic Section” on page 207 for details.

SHT_NOTEThe section holds information that marks the file in some way. See “NoteSection” on page 187 for details.

Page 168: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

154 Linker and Libraries Guide—November 1995

6

SHT_NOBITSA section of this type occupies no space in the file but otherwise resemblesSHT_PROGBITS. Although this section contains no bytes, the sh_offsetmember contains the conceptual file offset.

SHT_RELThe section holds relocation entries without explicit addends, such as typeElf32_Rel for the 32-bit class of object files. An object file may havemultiple relocation sections. See “Relocation” on page 167 for details.

SHT_SHLIBThis section type is reserved but has unspecified semantics. Programs thatcontain a section of this type do not conform to the ABI.

SHT_SUNW_verdefThe section contains definitions of fine-grained versions defined by this file.

SHT_SUNW_verneedThe section contains descriptions of fine-grained dependencies required forthe execution of an image.

SHT_SUNW_versymThe section contains a table describing the relationship of symbols to theversion definitions offered by the file.

SHT_LOPROC - SHT_HIPROCValues in this inclusive range are reserved for processor-specific semantics.

SHT_LOUSERThis value specifies the lower bound of the range of indexes reserved forapplication programs.

SHT_HIUSERThis value specifies the upper bound of the range of indexes reserved forapplication programs. Section types between SHT_LOUSER andSHT_HIUSER may be used by the application, without conflicting withcurrent or future system-defined section types.

Page 169: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 155

6

Other section type values are reserved. As mentioned before, the sectionheader for index 0 (SHN_UNDEF) exists, even though the index marksundefined section references. This entry holds the following:

A section header’s sh_flags member holds 1-bit flags that describe thesection’s attributes:

If a flag bit is set in sh_flags , the attribute is on for the section. Otherwise,the attribute is off or does not apply. Undefined attributes are reserved and setto zero.

SHF_WRITEThe section contains data that should be writable during process execution.

Table 6-11 Section Header Table Entry: Index 0

Name Value Note

sh_name 0 No name

sh_type SHT_NULL Inactive

sh_flags 0 No flags

sh_addr 0 No address

sh_offset 0 No file offset

sh_size 0 No size

sh_link SHN_UNDEF No link information

sh_info 0 No auxiliary information

sh_addralign 0 No alignment

sh_entsize 0 No entries

Table 6-12 Section Attribute Flags

Name Value

SHF_WRITE 0x1

SHF_ALLOC 0x2

SHF_EXECINSTR 0x4

SHF_MASKPROC 0xf0000000

Page 170: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

156 Linker and Libraries Guide—November 1995

6

SHF_ALLOCThe section occupies memory during process execution. Some controlsections do not reside in the memory image of an object file; this attribute isoff for those sections.

SHF_EXECINSTRThe section contains executable machine instructions.

SHF_MASKPROCAll bits included in this mask are reserved for processor-specific semantics.

Two members in the section header, sh_link and sh_info , hold specialinformation, depending on section type.

Table 6-13 sh_link and sh_info Interpretation

sh_type sh_link sh_info

SHT_DYNAMIC The section header index ofthe associated string table.

0

SHT_HASH The section header index ofthe associated symbol table.

0

SHT_RELSHT_RELA

The section header index ofthe associated symbol table.

The section header index ofthe section to which therelocation applies.

SHT_SYMTABSHT_DYNSYM

The section header index ofthe associated string table.

One greater than the symboltable index of the last localsymbol (binding STB_LOCAL).

SHT_SUNW_verdef The section header index ofthe associated string table.

The number of versiondefinitions within the section.

SHT_SUNW_verneed The section header index ofthe associated string table.

The number of versiondependencies within thesection.

SHT_SUNW_versym The section header index ofthe associated symbol table.

0

other SHN_UNDEF 0

Page 171: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 157

6

Special Sections

Various sections hold program and control information. Sections in the listbelow are used by the system and have the indicated types and attributes.

Table 6-14 Special Sections (1 of 2)

Name Type Attribute

.bss SHT_NOBITS SHF_ALLOC + SHF_WRITE

.comment SHT_PROGBITS None

.data SHT_PROGBITS SHF_ALLOC + SHF_WRITE

.data1 SHT_PROGBITS SHF_ALLOC + SHF_WRITE

.dynamic SHT_DYNAMIC SHF_ALLOC + SHF_WRITE

.dynstr SHT_STRTAB SHF_ALLOC

.dynsym SHT_DYNSYM SHF_ALLOC

.fini SHT_PROGBITS SHF_ALLOC + SHF_EXECINSTR

.got SHT_PROGBITS See “.got” on page 158

.hash SHT_HASH SHF_ALLOC

.init SHT_PROGBITS SHF_ALLOC + SHF_EXECINSTR

.interp SHT_PROGBITS See “.interp” on page 159

.note SHT_NOTE None

.plt SHT_PROGBITS See “.plt” on page 159

.relname SHT_REL See “.relname, .relaname” on page 159

.relaname SHT_RELA See “.relname, .relaname” on page 159

.rodata SHT_PROGBITS SHF_ALLOC

.rodata1 SHT_PROGBITS SHF_ALLOC

.shstrtab SHT_STRTAB None

.strtab SHT_STRTAB See “.strtab” on page 160

Page 172: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

158 Linker and Libraries Guide—November 1995

6

.bssThis section holds uninitialized data that contribute to the program’smemory image. By definition, the system initializes the data with zeroswhen the program begins to run. The section occupies no file space, asindicated by the section type, SHT_NOBITS.

.commentThis section holds comment information.

.data, .data1These sections hold initialized data that contribute to the program’smemory image.

.dynamicThis section holds dynamic linking information.

.dynstrThis section holds strings needed for dynamic linking, most commonly thestrings that represent the names associated with symbol table entries.

.dynsymThis section holds the dynamic linking symbol table. See “Symbol Table” onpage 162 for details.

.finiThis section holds executable instructions that contribute to the processtermination code. That is, when a program exits normally, the systemarranges to execute the code in this section.

.gotThis section holds the global offset table. See “Global Offset Table(Processor-Specific)” on page 213 for more information.

.symtab SHT_SYMTAB See “.symtab” on page 160

.text SHT_PROGBITS SHF_ALLOC + SHF_EXECINSTR

.SUNW_version SHT_SUNW_verdefSHT_SUNW_verneedSHT_SUNW_versym

SHF_ALLOC

Table 6-14 Special Sections (2 of 2)

Name Type Attribute

Page 173: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 159

6

.hashThis section holds a symbol hash table. See “Hash Table” on page 224 formore information.

.initThis section holds executable instructions that contribute to the processinitialization code. That is, when a program starts to run, the systemarranges to execute the code in this section before calling the program entrypoint.

.interpThis section holds the path name of a program interpreter. See “ProgramInterpreter” on page 204 for more information.

.noteThis section holds information in the format that “Note Section” onpage 187 describes.

.pltThis section holds the procedure linkage table. For PowerPC only, theSHT_NOBITS type may also be used. See “Procedure Linkage Table” onpage 215, “Procedure Linkage Table” on page 218, and “Procedure LinkageTable” on page 221 for more information.

.rel name, .rela nameThese sections hold relocation information, as “Relocation” on page 167describes. If the file has a loadable segment that includes relocation, thesections’ attributes will include the SHF_ALLOC bit; otherwise, that bit willbe off. Conventionally, name is supplied by the section to which therelocations apply. Thus a relocation section for .text normally will have thename .rel.text or .rela.text.

.rodata, .rodata1These sections hold read-only data that typically contribute to a non-writable segment in the process image. See “Program Header” on page 189for more information.

.shstrtabThis section holds section names.

Page 174: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

160 Linker and Libraries Guide—November 1995

6

.strtabThis section holds strings, most commonly the strings that represent thenames associated with symbol table entries. If the file has a loadablesegment that includes the symbol string table, the section’s attributes willinclude the SHF_ALLOC bit; otherwise, that bit will be off.

.symtabThis section holds a symbol table, as “Symbol Table” on page 162 describes.If the file has a loadable segment that includes the symbol table, thesection’s attributes will include the SHF_ALLOC bit; otherwise, that bit willbe off.

.textThis section holds the text or executable instructions of a program.

.SUNW_versionSections of this name hold versioning information. See “VersioningInformation” on page 181 for more information.

Section names with a dot (. ) prefix are reserved for the system, althoughapplications may use these sections if their existing meanings are satisfactory.Applications may use names without the prefix to avoid conflicts with systemsections. The object file format lets one define sections not in the list above. Anobject file may have more than one section with the same name.

Section names reserved for a processor architecture are formed by placing anabbreviation of the architecture name ahead of the section name. The nameshould be taken from the architecture names used for e_machine . Forexample, .Foo.psect is the psect section defined by the FOO architecture.

Existing extensions use their historical names.

Preexisting Extensions:

.conflict .liblist .lit8 .sdata

.debug .line .reginfo .stab

.gptab .lit4 .sbss .tdesc

Page 175: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 161

6

String Table

String table sections hold null-terminated character sequences, commonlycalled strings. The object file uses these strings to represent symbol and sectionnames. One references a string as an index into the string table section.

The first byte, which is index zero, is defined to hold a null character. Likewise,a string table’s last byte is defined to hold a null character, ensuring nulltermination for all strings. A string whose index is zero specifies either noname or a null name, depending on the context.

An empty string table section is permitted; its section header’s sh_sizemember will contain zero. Nonzero indexes are invalid for an empty stringtable.

A section header’s sh_name member holds an index into the section headerstring table section, as designated by the e_shstrndx member of the ELFheader. The following figures show a string table with 25 bytes and the stringsassociated with various indexes.

Figure 6-4 String Table

The table below shows the strings of the string table above:

Table 6-15 String Table Indexes

Index String

0 none

1 name.

7 Variable

11 able

16 able

24 null string

0 \0 n a m e . \0 V a r

20 \0 \0 x x \0

10 i a b l e \0 a b l e

Index +0 +1 +2 +3 +4 +5 +6 +7 +8 +9

Page 176: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

162 Linker and Libraries Guide—November 1995

6

As the example shows, a string table index may refer to any byte in the section.A string may appear more than once; references to substrings may exist; and asingle string may be referenced multiple times. Unreferenced strings also areallowed.

Symbol Table

An object file’s symbol table holds information needed to locate and relocate aprogram’s symbolic definitions and references. A symbol table index is asubscript into this array. Index 0 both designates the first entry in the table andserves as the undefined symbol index. The contents of the initial entry arespecified later in this section.

A symbol table entry has the following format (defined in sys/elf.h ):

st_nameThis member holds an index into the object file’s symbol string table, whichholds the character representations of the symbol names. If the value isnonzero, it represents a string table index that gives the symbol name.Otherwise, the symbol table entry has no name.

Note – External C symbols have the same names in C and in object files’symbol tables.

Table 6-16 Symbol Table Initial Entry

Name Value

STN_UNDEF 0

typedef struct { Elf32_Word st_name; Elf32_Addr st_value; Elf32_Word st_size; unsigned char st_info; unsigned char st_other; Elf32_Half st_shndx;} Elf32_Sym;

Page 177: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 163

6

st_valueThis member gives the value of the associated symbol. Depending on thecontext, this may be an absolute value, an address, and so forth. See“Symbol Values” on page 167.

st_sizeMany symbols have associated sizes. For example, a data object’s size is thenumber of bytes contained in the object. This member holds 0 if the symbolhas no size or an unknown size.

st_infoThis member specifies the symbol’s type and binding attributes. A list of thevalues and meanings appears below. The following code shows how tomanipulate the values (defined in sys/elf.h ):

st_otherThis member currently holds 0 and has no defined meaning.

st_shndxEvery symbol table entry is defined in relation to some section; this memberholds the relevant section header table index. Some section indexes indicatespecial meanings. See Table 6-10 on page 152

A symbol’s binding determines the linkage visibility and behavior.

#define ELF32_ST_BIND(i) ((i) >> 4)#define ELF32_ST_TYPE(i) ((i) & 0xf)#define ELF32_ST_INFO(b, t) (((b)<<4)+((t)&0xf))

Table 6-17 Symbol Binding, ELF32_ST_BIND

Name Value

STB_LOCAL 0

STB_GLOBAL 1

STB_WEAK 2

STB_LOPROC 13

STB_HIPROC 15

Page 178: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

164 Linker and Libraries Guide—November 1995

6

STB_LOCALLocal symbols are not visible outside the object file containing theirdefinition. Local symbols of the same name may exist in multiple fileswithout interfering with each other.

STB_GLOBALGlobal symbols are visible to all object files being combined. One file’sdefinition of a global symbol will satisfy another file’s undefined referenceto the same global symbol.

STB_WEAKWeak symbols resemble global symbols, but their definitions have lowerprecedence.

STB_LOPROC- STB_HIPROCValues in this inclusive range are reserved for processor-specific semantics.

Global and weak symbols differ in two major ways:

• When the link-editor combines several relocatable object files, it does notallow multiple definitions of STB_GLOBAL symbols with the same name. Onthe other hand, if a defined global symbol exists, the appearance of a weaksymbol with the same name will not cause an error. The link-editor honorsthe global definition and ignores the weak ones. Similarly, if a commonsymbol exists (that is, a symbol with the st_index field holdingSHN_COMMON), the appearance of a weak symbol with the same name doesnot cause an error. The link-editor uses the common definition and ignoresthe weak one.

• When the link-editor searches archive libraries (see “Archive Processing” onpage 12), it extracts archive members that contain definitions of undefinedor tentative, global symbols. The member’s definition may be either a globalor a weak symbol. The link-editor does not extract archive members toresolve undefined weak symbols. Unresolved weak symbols have a zerovalue.

In each symbol table, all symbols with STB_LOCAL binding precede the weakand global symbols. As “Sections” on page 148 describes, a symbol tablesection’s sh_info section header member holds the symbol table index for thefirst non-local symbol.

Page 179: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 165

6

A symbol’s type provides a general classification for the associated entity.

STT_NOTYPEThe symbol type is not specified.

STT_OBJECTThe symbol is associated with a data object, such as a variable, an array, andso forth.

STT_FUNCThe symbol is associated with a function or other executable code.

STT_SECTIONThe symbol is associated with a section. Symbol table entries of this typeexist primarily for relocation and normally have STB_LOCAL binding.

STT_FILEConventionally, the symbol’s name gives the name of the source fileassociated with the object file. A file symbol has STB_LOCAL binding, itssection index is SHN_ABS, and it precedes the other STB_LOCAL symbols forthe file, if it is present. Symbol index 1 of the SHT_SYMTAB is an STT_FILEsymbol representing the file itself. Conventionally, this is followed by thefiles STT_SECTION symbols, and any global symbols that have beenreduced to locals (see “Reducing Symbol Scope” on page 38, and Chapter 5,“Versioning” for more details).

STT_LOPROC- STT_HIPROCValues in this inclusive range are reserved for processor-specific semantics.

Table 6-18 Symbol Types, ELF32_ST_TYPE

Name Value

STT_NOTYPE 0

STT_OBJECT 1

STT_FUNC 2

STT_SECTION 3

STT_FILE 4

STT_LOPROC 13

STT_HIPROC 15

Page 180: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

166 Linker and Libraries Guide—November 1995

6

Function symbols (those with type STT_FUNC) in shared object files havespecial significance. When another object file references a function from ashared object, the link-editor automatically creates a procedure linkage tableentry for the referenced symbol. Shared object symbols with types other thanSTT_FUNC will not be referenced automatically through the procedure linkagetable.

If a symbol’s value refers to a specific location within a section, its sectionindex member, st_shndx , holds an index into the section header table. As thesection moves during relocation, the symbol’s value changes as well, andreferences to the symbol continue to point to the same location in the program.Some special section index values give other semantics:

SHN_ABSThe symbol has an absolute value that will not change because of relocation.

SHN_COMMONThe symbol labels a common block that has not yet been allocated. Thesymbol’s value gives alignment constraints, similar to a section’ssh_addralign member. That is, the link-editor will allocate the storage forthe symbol at an address that is a multiple of st_value . The symbol’s sizetells how many bytes are required.

SHN_UNDEFThis section table index means the symbol is undefined. When the link-editor combines this object file with another that defines the indicatedsymbol, this file’s references to the symbol will be bound to the actualdefinition.

As mentioned above, the symbol table entry for index 0 (STN_UNDEF) isreserved; it holds the following:

Table 6-19 Symbol Table Entry: Index 0

Name Value Note

st_name 0 No name

st_value 0 Zero value

st_size 0 No size

Page 181: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 167

6

Symbol Values

Symbol table entries for different object file types have slightly differentinterpretations for the st_value member.

• In relocatable files, st_value holds alignment constraints for a symbolwhose section index is SHN_COMMON.

• In relocatable files, st_value holds a section offset for a defined symbol.That is, st_value is an offset from the beginning of the section thatst_shndx identifies.

• In executable and shared object files, st_value holds a virtual address. Tomake these files’ symbols more useful for the runtime linker, the sectionoffset (file interpretation) gives way to a virtual address (memoryinterpretation) for which the section number is irrelevant.

Although the symbol table values have similar meanings for different objectfiles, the data allow efficient access by the appropriate programs.

Relocation

Relocation is the process of connecting symbolic references with symbolicdefinitions. For example, when a program calls a function, the associated callinstruction must transfer control to the proper destination address atexecution. In other words, relocatable files must have information thatdescribes how to modify their section contents, thus allowing executable andshared object files to hold the right information for a process’s program image.Relocation entries are these data.

st_info 0 No type, local binding

st_other 0

st_shndx SHN_UNDEF No section

Table 6-19 Symbol Table Entry: Index 0

Name Value Note

Page 182: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

168 Linker and Libraries Guide—November 1995

6

Relocation entries can have the following structure (defined in sys/elf.h ):

r_offsetThis member gives the location at which to apply the relocation action. Fora relocatable file, the value is the byte offset from the beginning of thesection to the storage unit affected by the relocation. For an executable fileor a shared object, the value is the virtual address of the storage unitaffected by the relocation.

r_infoThis member gives both the symbol table index with respect to which therelocation must be made and the type of relocation to apply. For example, acall instruction’s relocation entry will hold the symbol table index of thefunction being called. If the index is STN_UNDEF, the undefined symbolindex, the relocation uses 0 as the symbol value. Relocation types areprocessor-specific; descriptions of their behavior appear below. When thetext below refers to a relocation entry’s relocation type or symbol tableindex, it means the result of applying ELF32_R_TYPE or ELF32_R_SYM,respectively, to the entry’s r_info member:

r_addendThis member specifies a constant addend used to compute the value to bestored into the relocatable field.

typedef struct { Elf32_Addr r_offset; Elf32_Word r_info;} Elf32_Rel;

typedef struct { Elf32_Addr r_offset; Elf32_Word r_info; Elf32_Sword r_addend;} Elf32_Rela;

#define ELF32_R_SYM(i) ((i)>>8)#define ELF32_R_TYPE(i) ((unsigned char)(i))#define ELF32_R_INFO(s, t) (((s)<<8)+(unsigned char)(t))

Page 183: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 169

6

As shown above, only Elf32_Rela entries contain an explicit addend. Entriesof type Elf32_Rel store an implicit addend in the location to be modified.SPARC and PowerPC use Elf32_Rela entries and x86 uses Elf32_Relentries.

A relocation section references two other sections: a symbol table and a sectionto modify. The section header’s sh_info and sh_link members, described in“Sections” on page 148 earlier, specify these relationships. Relocation entriesfor different object files have slightly different interpretations for ther_offset member.

• In relocatable files, r_offset holds a section offset. That is, the relocationsection itself describes how to modify another section in the file; relocationoffsets designate a storage unit within the second section.

• In executable and shared object files, r_offset holds a virtual address. Tomake these files’ relocation entries more useful for the runtime linker, thesection offset (file interpretation) gives way to a virtual address (memoryinterpretation).

Although the interpretation of r_offset changes for different object files toallow efficient access by the relevant programs, the relocation types’ meaningsstay the same.

Page 184: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

170 Linker and Libraries Guide—November 1995

6

Relocation Types (Processor Specific)

On SPARC, relocation entries describe how to alter the following instructionand data fields (bit numbers appear in the lower box corners):

byte8

half16

word32

disp30

disp22

imm22

7 0

15 0

31 0

31 29 0

0

0

31

31

21

21

simm13031 12

simm11031 10

simm10031 9

disp19031 19

disp14031 21 19

d213

simm7031 6

xword6463 0

Page 185: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 171

6

On x86, relocation entries describe how to alter the following instruction anddata fields (bit numbers appear in the lower box corners):

word32 specifies a 32-bit field occupying 4 bytes with an arbitrary bytealignment. These values use the same byte order as other word values in thex86 architecture):

On PowerPC, relocation entries describe how to alter the following instructionand data fields (bit numbers appear in the lower box corners)

Calculations below assume the actions are transforming a relocatable file intoeither an executable or a shared object file. Conceptually, the link-editor mergesone or more relocatable files to form the output. It first decides how to combineand locate the input files, then updates the symbol values, and finally performsthe relocation. Relocations applied to executable or shared object files aresimilar and accomplish the same result. Descriptions below use the followingnotation:

31 0

word32

31 0

3 2 1 0 0x0102030401 02 03 04

half16

word32

word30

15 0

31 0

31 29 0

low1431 29 0

031 629low24

16

Page 186: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

172 Linker and Libraries Guide—November 1995

6

Ameans the addend used to compute the value of the relocatable field.

Bmeans the base address at which a shared object is loaded into memoryduring execution. Generally, a shared object file is built with a 0 base virtualaddress, but the execution address is different. See “Program Header” onpage 189 for more information about the base address.

Gmeans the offset into the global offset table at which the address of therelocation entry’s symbol resides during execution. See “Global Offset Table(Processor-Specific)” on page 213 for more information.

GOTmeans the address of the global offset table. See “Global Offset Table(Processor-Specific)” on page 213 for more information.

Lmeans the place (section offset or address) of the procedure linkage table entryfor a symbol. A procedure linkage table entry redirects a function call to theproper destination. The link-editor builds the initial procedure linkage table,and the runtime linker modifies the entries during execution. See“Procedure Linkage Table” on page 215, “Procedure Linkage Table” onpage 218, or “Procedure Linkage Table” on page 221 for more information.

Pmeans the place (section offset or address) of the storage unit beingrelocated (computed using r_offset ).

Smeans the value of the symbol whose index resides in the relocation entry.

SPARC relocation entries apply to bytes (byte8), half-words (half16), or words(the others). x86 relocation entries apply to words. PowerPC relocation entriesapply to half-words and to words. In any case, the r_offset value designatesthe offset or virtual address of the first byte of the affected storage unit. Therelocation type specifies which bits to change and how to calculate their values.

Page 187: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 173

6

SPARC and PowerPC use only Elf32_Rela relocation entries with explicitaddends. Thus the r_addend member serves as the relocation addend. x86uses only Elf32_Rel relocation entries, the field to be relocated holds theaddend. In all cases the addend and the computed result use the same byteorder.

SPARC: Relocation Types

Note – Field names in the following table tell whether the relocation typechecks for overflow . A calculated relocation value may be larger than theintended field, and a relocation type may verify (V) the value fits or truncate(T) the result. As an example, V-simm13 means that the computed value maynot have significant, nonzero bits outside the simm13 field.

Table 6-20 SPARC Relocation Types (1 of 2)

Name Value Field Calculation

R_SPARC_NONE 0 None None

R_SPARC_8 1 V-byte8 S + A

R_SPARC_16 2 V-half16 S + A

R_SPARC_32 3 V-word32 S + A

R_SPARC_DISP8 4 V-byte8 S + A - P

R_SPARC_DISP16 5 V-half16 S + A - P

R_SPARC_DISP32 6 V-disp32 S + A - P

R_SPARC_WDISP30 7 V-disp30 (S + A - P) >> 2

R_SPARC_WDISP22 8 V-disp22 (S + A - P) >> 2

R_SPARC_HI22 9 T-imm22 (S + A) >> 10

R_SPARC_22 10 V-imm22 S + A

R_SPARC_13 11 V-simm13 S + A

R_SPARC_LO10 12 T-simm13 (S + A) & 0x3ff

R_SPARC_GOT10 13 T-simm13 G & 0x3ff

R_SPARC_GOT13 14 V-simm13 G

R_SPARC_GOT22 15 T-simm22 G >> 10

R_SPARC_PC10 16 T-simm13 (S + A - P) & 0x3ff

Page 188: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

174 Linker and Libraries Guide—November 1995

6

Some relocation types have semantics beyond simple calculation:

R_SPARC_GOT10This relocation type resembles R_SPARC_LO10, except it refers to theaddress of the symbol’s global offset table entry and additionally instructsthe link-editor to build a global offset table.

R_SPARC_PC22 17 V-disp22 (S + A - P) >> 10

R_SPARC_WPLT30 18 V-disp30 (L + A - P) >> 2

R_SPARC_COPY 19 None None

R_SPARC_GLOB_DAT 20 V-word32 S + A

R_SPARC_JMP_SLOT 21 None See below

R_SPARC_RELATIVE 22 V-word32 B + A

R_SPARC_UA32 23 V-word32 S + A

R_SPARC_PLT32 24 V-word32 L + A

R_SPARC_HIPLT22 25 T-imm22 (L + A) >> 10

R_SPARC_LOPLT10 26 T-simm13 (L + A) & 0x3ff

R_SPARC_PCPLT32 27 V-word32 L + A - P

R_SPARC_PCPLT22 28 V-disp22 (L + A - P) >> 10

R_SPARC_PCPLT10 29 V-simm12 (L + A - P) & 0x3ff

R_SPARC_10 30 V_simm10 S + A

R_SPARC_11 31 V_simm11 S + A

R_SPARC_WDISP16 40 V-d2/disp14 (S + A - P) >> 2

R_SPARC_WDISP19 41 V-disp19 (S + A - P) >> 2

R_SPARC_7 43 V-imm7 S + A

R_SPARC_5 44 V-imm5 S + A

R_SPARC_6 45 V-imm6 S + A

Table 6-20 SPARC Relocation Types (2 of 2)

Name Value Field Calculation

Page 189: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 175

6

R_SPARC_GOT13This relocation type resembles R_SPARC_13, except it refers to the addressof the symbol’s global offset table entry and additionally instructs the link-editor to build a global offset table.

R_SPARC_GOT22This relocation type resembles R_SPARC_22, except it refers to the addressof the symbol’s global offset table entry and additionally instructs the link-editor to build a global offset table.

R_SPARC_WPLT30This relocation type resembles R_SPARC_WDISP30, except it refers to theaddress of the symbol’s procedure linkage table entry and additionallyinstructs the link-editor to build a procedure linkage table.

R_SPARC_COPYThe link-editor creates this relocation type for dynamic linking. Its offsetmember refers to a location in a writable segment. The symbol table indexspecifies a symbol that should exist both in the current object file and in ashared object. During execution, the runtime linker copies data associatedwith the shared object’s symbol to the location specified by the offset. See“Copy Relocations” on page 107 for more details.

R_SPARC_GLOB_DATThis relocation type resembles R_SPARC_32, except it sets a global offsettable entry to the address of the specified symbol. The special relocationtype allows you to determine the correspondence between symbols andglobal offset table entries.

R_SPARC_JMP_SLOTThe link-editor creates this relocation type for dynamic linking. Its offsetmember gives the location of a procedure linkage table entry. The runtimelinker modifies the procedure linkage table entry to transfer control to thedesignated symbol address.

R_SPARC_RELATIVEThe link-editor creates this relocation type for dynamic linking. Its offsetmember gives the location within a shared object that contains a valuerepresenting a relative address. The runtime linker computes thecorresponding virtual address by adding the virtual address at which theshared object is loaded to the relative address. Relocation entries for thistype must specify 0 for the symbol table index.

Page 190: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

176 Linker and Libraries Guide—November 1995

6

R_SPARC_UA32This relocation type resembles R_SPARC_32, except it refers to an unalignedword. That is, the word to be relocated must be treated as four separate byteswith arbitrary alignment, not as a word aligned according to thearchitecture requirements.

x86: Relocation Types

Some relocation types have semantics beyond simple calculation:

R_386_GOT32This relocation type computes the distance from the base of the global offsettable to the symbol’s global offset table entry. It also tells the link-editor tobuild a global offset table.

R_386_PLT32This relocation type computes the address of the symbol’s procedurelinkage table entry and tells the link-editor to build a procedure linkagetable.

R_386_COPY

Table 6-21 x86 Relocation Types

Name Value Field Calculation

R_386_NONE 0 none none

R_386_32 1 word32 S + A

R_386_PC32 2 word32 S + A - P

R_386_GOT32 3 word32 G + A

R_386_PLT32 4 word32 L + A - P

R_386_COPY 5 none none

R_386_GLOB_DAT 6 word32 S

R_386_JMP_SLOT 7 word32 S

R_386_RELATIVE 8 word32 B + A

R_386_GOTOFF 9 word32 S + A - GOT

R_386_GOTPC 10 word32 GOT + A - P

R_386_32PLT 11 word32 L + A

Page 191: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 177

6

The link-editor creates this relocation type for dynamic linking. Its offsetmember refers to a location in a writable segment. The symbol table indexspecifies a symbol that should exist both in the current object file and in ashared object. During execution, the runtime linker copies data associatedwith the shared object’s symbol to the location specified by the offset. See“Copy Relocations” on page 107

R_386_GLOB_DATThis relocation type is used to set a global offset table entry to the address ofthe specified symbol. The special relocation type lets one determine thecorrespondence between symbols and global offset table entries.

R_386_JMP_SLOTThe link-editor creates this relocation type for dynamic linking. Its offsetmember gives the location of a procedure linkage table entry. The runtimelinker modifies the procedure linkage table entry to transfer control to thedesignated symbol address.

R_386_RELATIVEThe link-editor creates this relocation type for dynamic linking. Its offsetmember gives the location within a shared object that contains a valuerepresenting a relative address. The runtime linker computes thecorresponding virtual address by adding the virtual address at which theshared object is loaded to the relative address. Relocation entries for thistype must specify 0 for the symbol table index.

R_386_GOTOFFThis relocation type computes the difference between a symbol’s value andthe address of the global offset table. It also tells the link-editor to build theglobal offset table.

R_386_GOTPCThis relocation type resembles R_386_PC32, except it uses the address ofthe global offset table in its calculation. The symbol referenced in thisrelocation normally is _GLOBAL_OFFSET_TABLE_, which also tells the link-editor to build the global offset table.

PowerPC: Relocation TypesThe following general rules apply to the interpretation of the relocation typesin Table 6-22:

Page 192: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

178 Linker and Libraries Guide—November 1995

6

• "+" and "- " denote 32-bit modulus addition and subtraction, respectively.">>" denotes arithmetic right shifting (shifting with sign copying) of thevalue of the left operand by the number of bits given by the right operand.

• For relocation types in which the names contain the string 14 or the string16 , the upper 17 bits of the value computed before shifting must all be thesame. For relocation types whose names contain the string 24 , the upper 7bits of the value computed before shifting must all be the same. Forrelocation types whose names contain the string 14 or the string 24 , the low2 bits of the value computed before shifting must all be zero.

• #hi( value) and #lo( value) denote the most and least significant 16 bits,respectively, of the indicated value. That is,

#lo( x) = ( x & 0xFFFF) and #hi( x) = (( x >> 16)& 0xFFFF)

The “high adjusted” value, #ha(value), compensates for #lo() being treatedas a signed number.

#ha( x) = ((( x >> 16) + (( x & 0x8000) ? 1 : 0)) & 0xFFFF).

• Reference in a calculation to the value G implicitly creates a GOT entry forthe indicated symbol.

Table 6-22 Relocation Types

Name Value Field Calculation

R_PPC_NONE 0 none none

R_PPC_ADDR32 1 word32 S + A

R_PPC_ADDR24 2 low24* (S + A) >> 2

R_PPC_ADDR16 3 half16* S + A

R_PPC_ADDR16_LO 4 half16 #lo(S + A)

R_PPC_ADDR16_HI 5 half16 #hi(S + A)

R_PPC_ADDR16_HA 6 half16 #ha(S + A)

R_PPC_ADDR14 7 low14* (S + A) >> 2

R_PPC_ADDR14_BRTAKEN 8 low14* (S + A) >> 2

R_PPC_ADDR14_BRNTAKEN 9 low14* (S + A) >> 2

R_PPC_REL24 10 low24* (S + A - P) >> 2

R_PPC_REL14 11 low14* (S + A - P) >> 2

Page 193: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 179

6

Relocation types with special semantics are described below. Relocation valuesnot in the above table and less than 101 or greater than 200 are reserved. Valuesin the range 101-200 and names beginning with "R_PPC_EMB_" have beenassigned for embedded system use.

The relocation types whose Field column entry contains an asterisk are subjectto failure if the value computed does not fit in the allocated bits.

The relocation types in which the names include _BRTAKEN or _BRNTAKENspecify whether the branch prediction bit (bit 10) should indicate that thebranch will be taken or not taken, respectively. For an unconditional branch,the branch prediction bit must be 0.

R_PPC_GOT16*These relocation types resemble the corresponding R_PPC_ADDR16* types,except that they refer to the address of the symbol's global offset table entryand additionally instruct the link-editor to build a global offset table.

R_PPC_PLTREL24

R_PPC_REL14_BRTAKEN 12 low14* (S + A - P) >> 2

R_PPC_REL14_BRNTAKEN 13 low14* (S + A - P) >> 2

R_PPC_GOT16 14 half16* G + A

R_PPC_GOT16_LO 15 half16 #lo(G + A)

R_PPC_GOT16_HI 16 half16 #hi(G + A)

R_PPC_GOT16_HA 17 half16 #ha(G + A)

R_PPC_PLTREL24 18 low24* (L + A - P) >> 2

R_PPC_COPY 19 none none

R_PPC_GLOB_DAT 20 word32 S + A

R_PPC_JMP_SLOT 21 none see below

R_PPC_RELATIVE 22 word32 B + A

R_PPC_LOCAL24PC 23 low24* see below

R_PPC_UADDR32 24 word32 S + A

R_PPC_UADDR16 25 half16* S + A

Table 6-22 Relocation Types (Continued)

Name Value Field Calculation

Page 194: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

180 Linker and Libraries Guide—November 1995

6

This relocation type refers to the address of the symbol's procedure linkagetable entry and additionally instructs the link-editor to build a procedurelinkage table. There is an implicit assumption that the procedure linkagetable for a module will be within +/- 32 megabytes of an instruction thatbranches to it, so that the R_PPC_PLTREL24 relocation type is the only oneneeded for relocating branches to procedure linkage table entries.

R_PPC_COPYThe link-editor creates this relocation type for dynamic linking. Its offsetmember refers to a location in a writable segment. The symbol table indexspecifies a symbol that should exist both in the current object file and in ashared object. During execution, the dynamic linker copies data associatedwith the shared object's symbol to the location specified by the offset.

R_PPC_GLOB_DATThis relocation type resembles R_PPC_ADDR32, except that it sets a globaloffset table entry to the address of the specified symbol. The specialrelocation type allows one to determine the correspondence betweensymbols and global offset table entries.

R_PPC_JMP_SLOTThe link-editor creates this relocation type for dynamic linking. Its offsetmember gives the location of a procedure linkage table entry. The dynamiclinker modifies the procedure linkage table entry to transfer control to thedesignated symbol's address (see the section “Procedure Linkage Table” onpage 221).

R_PPC_LOCAL24PCThis relocation type resembles R_PPC_REL24, except that it uses the valueof the symbol within the object, not an interposed value, for S in itscalculation. The symbol referenced in this relocation normally is_GLOBAL_OFFSET_TABLE_, which additionally instructs the link-editor tobuild the global offset table.

R_PPC_RELATIVEThe link-editor creates this relocation type for dynamic linking. Its offsetmember gives a location within a shared object that contains a valuerepresenting a relative address. The dynamic linker computes thecorresponding virtual address by adding the virtual address at which theshared object was loaded to the relative address. Relocation entries for thistype must specify 0 for the symbol table index.

Page 195: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 181

6

R_PPC_UADDR*These relocation types are the same as the corresponding R_PPC_ADDR*types, except that the datum to be relocated is allowed to be unaligned.

Versioning Information

Objects created by the link-editor may contain two types of versioninginformation:

• version definitions provide associations of global symbols and areimplemented using sections of type SHT_SUNW_verdef andSHT_SUNW_versym.

• version dependencies indicate the version definition requirements from otherobject dependencies and are implemented using sections of typeSHT_SUNW_verneed.

The structures that form these sections are defined in sys/link.h . Sectionsthat contain versioning information are named .SUNW_version.

Version Definition Section

This section is defined by the type SHT_SUNW_verdef. If this section exists aSHT_SUNW_versym section must also exist. Using these two structures anassociation of symbols to version definitions is maintained within the file (see“Creating a Version Definition” on page 118 for more details). Elements of thissection have the following structure:

typedef struct { Elf32_Half vd_version; Elf32_Half vd_flags; Elf32_Half vd_ndx; Elf32_Half vd_cnt; Elf32_Word vd_hash; Elf32_Word vd_aux; Elf32_Word vd_next;} Elf32_Verdef;

typedef struct { Elf32_Addr vda_name; Elf32_Word vda_next;} Elf32_Verdaux;

Page 196: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

182 Linker and Libraries Guide—November 1995

6

vd_versionThis member identifies the version of the structure itself.

The value 1 signifies the original section format; extensions will create newversions with higher numbers. The value of VER_DEF_CURRENT changes asnecessary to reflect the current version number.

vd_flagsThis member holds version definition specific information.

The base version definition is always present when version definitions, orsymbol auto-reduction has been applied to the file. The base version providesa default version for the files reserved symbols (see “Generating the OutputImage” on page 42). A weak version definition has no symbols associatedwith it (see “Creating a Weak Version Definition” on page 122 for moredetails).

vd_ndxThis member holds the version index. Each version definition has a uniqueindex that is used to associate SHT_SUNW_versym entries to the appropriateversion definition.

vd_cntThis member indicates the number of elements in the Elf32_Verdauxarray.

Table 6-23Version Definition Structure Versions

Name Value Meaning

VER_DEF_NONE 0 Invalid version

VER_DEF_CURRENT >=1 Current version

Table 6-24Version Definition Section Flags

Name Value Meaning

VER_FLG_BASE 0x1 Version definition of the file itself

VER_FLG_WEAK 0x2 Weak version identifier

Page 197: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 183

6

vd_hashThis member holds the hash value of the version definition name (this valueis generated using the same hashing function described in “Hash Table” onpage 224).

vd_auxThis member holds the byte offset, from the start of this Elf32_Verdefentry, to the Elf32_Verdaux array of version definition names. The firstelement of the array must exist and points to the version definition stringthis structure defines. Additional elements may be present, the numberbeing indicated by the vd_cnt value. These elements represent thedependencies of this version definition. Each of these dependencies willhave its own version definition structure.

vd_nextThis member holds the byte offset, from the start of this Elf32_Verdefstructure, to the next Elf32_Verdef entry.

vda_nameThis member holds a string table offset to a null-terminated string, givingthe name of the version definition.

vda_nextThis member holds the byte offset, from the start of this Elf32_Verdauxentry, to the next Elf32_Verdaux entry.

Version Symbol Section

This section is defined by the type SHT_SUNW_versym, and consists of anarray of elements having the following structure:

typedef Elf32_Half Elf32_Versym;

Page 198: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

184 Linker and Libraries Guide—November 1995

6

The number of elements of the array must equal the number of symbol tableentries contained in the associated symbol table (determined by the sectionssh_link value). Each element of the array contains a single index that mayhave the following values:

Any index values greater than VER_NDX_GLOBAL must correspond to thevd_ndx value of an entry in the SHT_SUNW_verdef section. If no index valuesgreater than VER_NDX_GLOBAL exist then no SHT_SUNW_verdef section needbe present.

Table 6-25 Version Dependency Indexes

Name Value Meaning

VER_NDX_LOCAL 0 Symbol has local scope

VER_NDX_GLOBAL 1 Symbol has global scope (assigned tobase version definition)

>1 Symbol has global scope (assigned touser-defined version definition)

Page 199: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 185

6

Version Dependency Section

This section is defined by the type SHT_SUNW_verneed. This sectioncompliments the dynamic dependency requirements of the file by indicatingthe version definitions required from these dependencies. Only if adependency contains version definitions will a recording be made in thissection. Elements of this section have the following structure:

vn_versionThis member identifies the version of the structure itself.

The value 1 signifies the original section format; extensions will create newversions with higher numbers. The value of VER_NEED_CURRENT changesas necessary to reflect the current version number.

vn_cntThis member indicates the number of elements in the Elf32_Vernauxarray.

typedef struct { Elf32_Half vn_version; Elf32_Half vn_cnt; Elf32_Addr vn_file; Elf32_Word vn_aux; Elf32_Word vn_next;} Elf32_Verneed;

typedef struct { Elf32_Word vna_hash; Elf32_Half vna_flags; Elf32_Half vna_other; Elf32_Addr vna_name; Elf32_Word vna_next;} Elf32_Vernaux;

Table 6-26Version Dependency Structure Versions

Name Value Meaning

VER_NEED_NONE 0 Invalid version

VER_NEED_CURRENT >=1 Current version

Page 200: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

186 Linker and Libraries Guide—November 1995

6

vn_fileThis member holds a string table offset to a null-terminated string, givingthe filename having a version dependency. This name will match one of the.dynamic dependencies (refer to “DT_NEEDED” on page 209) found in thefile.

vn_auxThis member holds the byte offset, from the start of this Elf32_Verneedentry, to the Elf32_Vernaux array of version definitions required from theassociated file dependency. There must exist at least one versiondependency. Additional version dependencies may be present, the numberbeing indicated by the vn_cnt value.

vn_nextThis member holds the byte offset, from the start of this Elf32_Verneedentry, to the next Elf32_Verneed entry.

vna_hashThis member holds the hash value of the version dependency name (thisvalue is generated using the same hashing function described in “HashTable” on page 224).

vna_flagsThis member holds version dependency specific information.

A weak version dependency indicates an original binding to a weak versiondefinition. See “Creating a Version Definition” on page 118 for more details.

vna_otherThis member is presently unused.

vna_nameThis member holds a string table offset to a null-terminated string, givingthe name of the version dependency.

vna_nextThis member holds the byte offset, from the start of this Elf32_Vernauxentry, to the next Elf32_Vernaux entry.

Table 6-27Version Dependency Structure Flags

Name Value Meaning

VER_FLG_WEAK 0x2 Weak version identifier

Page 201: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 187

6

Note Section

Sometimes a vendor or system builder needs to mark an object file with specialinformation that other programs will check for conformance, compatibility, andso forth. Sections of type SHT_NOTE and program header elements of typePT_NOTE can be used for this purpose.

The note information in sections and program header elements holds anynumber of entries, each of which is an array of 4-byte words in the format ofthe target processor. Labels are shown on Figure 5-7 to help explain noteinformation organization, but they are not part of the specification.

Figure 6-5 Note Information

namesz and nameThe first namesz bytes in name contain a null-terminated characterrepresentation of the entry’s owner or originator. There is no formalmechanism for avoiding name conflicts. By convention, vendors use theirown name, such as “XYZ Computer Company,” as the identifier. If no nameis present, namesz contains 0. Padding is present, if necessary, to ensure 4-byte alignment for the descriptor. Such padding is not included in namesz .

descsz and descThe first descsz bytes in desc hold the note descriptor. If no descriptor ispresent, descsz contains 0. Padding is present, if necessary, to ensure4-byte alignment for the next note entry. Such padding is not included indescsz .

namesz

descsz

type

name. . .

desc. . .

Page 202: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

188 Linker and Libraries Guide—November 1995

6

typeThis word gives the interpretation of the descriptor. Each originator controlsits own types; multiple interpretations of a single type value may exist.Thus, a program must recognize both the name and the type to understanda descriptor. Types currently must be nonnegative.

To illustrate, the following note segment holds two entries.

Figure 6-6 Example Note Segment

Note – The system reserves note information with no name (namesz==0 ) andwith a zero-length name (name[0]==’\0’ ) but currently defines no types. Allother names must have at least one non-null character.

X Y Z

\0 padC o

7

0

1

7

8

3

X

C

Y Z

\0o pad

word0

word1

namesz

descsz

type

namesz

descsz

type

name

desc

No descriptor

+0 +1 +2 +3

name

Page 203: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 189

6

Dynamic LinkingThis section describes the object file information and system actions that createrunning programs. Some information here applies to all systems; informationspecific to one processor resides in sections marked accordingly.

Executable and shared object files statically represent programs. To executesuch programs, the system uses the files to create dynamic programrepresentations, or process images. A process image has segments that containits text, data, stack, and so on. The major subsections of this section are:

• “Program Header” describes object file structures that are directly involvedin program execution. The primary data structure, a program header table,locates segment images in the file and contains other information needed tocreate the memory image of the program.

• “Program Loading (Processor-Specific)” describes the information used toload a program into memory.

• “Runtime Linker” describes the information used to specify and resolvesymbolic references among the object files of the process image.

Program Header

An executable or shared object file’s program header table is an array ofstructures, each describing a segment or other information the system needs toprepare the program for execution. An object file segment contains one or moresections, as described in “Segment Contents” on page 194.

Program headers are meaningful only for executable and shared object files. Afile specifies its own program header size with the ELF header’s e_phentsizeand e_phnum members. See “ELF Header” on page 142 for more information.

Page 204: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

190 Linker and Libraries Guide—November 1995

6

A program header has the following structure (defined in sys/elf.h):

p_typeThis member tells what kind of segment this array element describes or howto interpret the array element’s information. Type values and their meaningsare specified in Table 6-28 on page 191.

p_offsetThis member gives the offset from the beginning of the file at which the firstbyte of the segment resides.

p_vaddrThis member gives the virtual address at which the first byte of the segmentresides in memory.

p_paddrOn systems for which physical addressing is relevant, this member isreserved for the segment’s physical address. Because the system ignoresphysical addressing for application programs, this member has unspecifiedcontents for executable files and shared objects.

p_fileszThis member gives the number of bytes in the file image of the segment; itmay be zero.

p_memszThis member gives the number of bytes in the memory image of thesegment; it may be zero.

p_flagsThis member gives flags relevant to the segment. Defined flag values appearbelow.

typedef struct { Elf32_Word p_type; Elf32_Off p_offset; Elf32_Addr p_vaddr; Elf32_Addr p_paddr; Elf32_Word p_filesz; Elf32_Word p_memsz; Elf32_Word p_flags; Elf32_Word p_align;} Elf32_Phdr;

Page 205: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 191

6

p_alignAs “Program Loading (Processor-Specific)” on page 195 describes, loadableprocess segments must have congruent values for p_vaddr and p_offset ,modulo the page size. This member gives the value to which the segmentsare aligned in memory and in the file. Values 0 and 1 mean no alignment isrequired. Otherwise, p_align should be a positive, integral power of 2, andp_vaddr should equal p_offset , modulo p_align .

Some entries describe process segments; others give supplementaryinformation and do not contribute to the process image. Segment entries mayappear in any order, except as explicitly noted below. Defined type valuesfollow; other values are reserved for future use.

PT_NULLThe array element is unused; other members’ values are undefined. Thistype lets the program header table contain ignored entries.

PT_LOADThe array element specifies a loadable segment, described by p_fileszand p_memsz. The bytes from the file are mapped to the beginning of thememory segment. If the segment’s memory size (p_memsz) is larger thanthe file size (p_filesz ), the extra bytes are defined to hold the value 0 and

Table 6-28 Segment Types, p_type

Name Value

PT_NULL 0

PT_LOAD 1

PT_DYNAMIC 2

PT_INTERP 3

PT_NOTE 4

PT_SHLIB 5

PT_PHDR 6

PT_LOPROC 0x70000000

PT_HIPROC 0x7fffffff

Page 206: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

192 Linker and Libraries Guide—November 1995

6

to follow the segment’s initialized area. The file size may not be larger thanthe memory size. Loadable segment entries in the program header tableappear in ascending order, sorted on the p_vaddr member.

PT_DYNAMICThe array element specifies dynamic linking information. See “DynamicSection” on page 207 for more information.

PT_INTERPThe array element specifies the location and size of a null-terminated pathname to invoke as an interpreter. This segment type is meaningful only forexecutable files (though it may occur for shared objects); it may not occurmore than once in a file. If it is present, it must precede any loadablesegment entry. See “Program Interpreter” on page 204 for furtherinformation.

PT_NOTEThe array element specifies the location and size of auxiliary information.See “Note Section” on page 187 below for details.

PT_SHLIBThis segment type is reserved but has unspecified semantics.

PT_PHDRThe array element, if present, specifies the location and size of the programheader table itself, both in the file and in the memory image of the program.This segment type may not occur more than once in a file. Moreover, it mayoccur only if the program header table is part of the memory image of theprogram. If it is present, it must precede any loadable segment entry. See“Program Interpreter” on page 204 for further information.

PT_LOPROC- PT_HIPROCValues in this inclusive range are reserved for processor-specific semantics.

Note – Unless specifically required elsewhere, all program header segmenttypes are optional. That is, a file’s program header table may contain onlythose elements relevant to its contents.

Page 207: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 193

6

Base Address

Executable and shared object files have a base address, which is the lowestvirtual address associated with the memory image of the program’s object file.One use of the base address is to relocate the memory image of the programduring dynamic linking.

An executable or shared object file’s base address is calculated duringexecution from three values: the memory load address, the maximum pagesize, and the lowest virtual address of a program’s loadable segment. As“Program Loading (Processor-Specific)” on page 195 describes, the virtualaddresses in the program headers might not represent the actual virtualaddresses of the program’s memory image.

To compute the base address, you determine the memory address associatedwith the lowest p_vaddr value for a PT_LOAD segment. You then obtain thebase address by truncating the memory address to the nearest multiple of themaximum page size. Depending on the kind of file being loaded into memory,the memory address might or might not match the p_vaddr values.

Segment Permissions

A program to be loaded by the system must have at least one loadable segment(although this is not required by the file format). When the system createsloadable segments’ memory images, it gives access permissions as specified inthe p_flags member. All bits included in the PF_MASKPROC mask arereserved for processor-specific semantics.

If a permission bit is 0, that type of access is denied. Actual memorypermissions depend on the memory management unit, which may vary fromone system to another. Although all flag combinations are valid, the system

Table 6-29 Segment Flag Bits, p_flags

Name Value Meaning

PF_X 0x1 Execute

PF_W 0x2 Write

PF_R 0x4 Read

PF_MASKPROC 0xf0000000 Unspecified

Page 208: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

194 Linker and Libraries Guide—November 1995

6

may grant more access than requested. In no case, however, will a segmenthave write permission unless it is specified explicitly. The following figureshows both the exact flag interpretation and the allowable flag interpretation.

For example, typical text segments have read and execute, but not writepermissions. Data segments normally have read, write, and executepermissions.

Segment Contents

An object file segment comprises one or more sections, though this fact istransparent to the program header. Whether the file segment holds one ormany sections also is immaterial to program loading. Nonetheless, variousdata must be present for program execution, dynamic linking, and so on. Thediagrams below illustrate segment contents in general terms. The order andmembership of sections within a segment may vary; moreover, processor-specific constraints may alter the examples below.

Text segments contain read-only instructions and data, in sections describedearlier in this chapter. Data segments contain writable data and instructions.See “Special Sections” on page 157 for a list of all special sections. Use dump(1)to see which sections are in a particular executable file.

Table 6-30 Segment Permissions

Flags Value Exact Allowable

None 0 All access denied All access denied

PF_X 1 Execute only Read, execute

PF_W 2 Write only Read, write, execute

PF_W + PF_X 3 Write, execute Read, write, execute

PF_R 4 Read only Read, execute

PF_R + PF_X 5 Read, execute Read, execute

PF_R + PF_W 6 Read, write Read, write, execute

PF_R + PF_W + PF_X 7 Read, write, execute Read, write, execute

Page 209: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 195

6

A PT_DYNAMIC program header element points at the .dynamic section, asexplained in “Dynamic Section” on page 207 later. The .got and .plt sectionsalso hold information related to position-independent code and dynamiclinking.

The .plt may reside in a text or a data segment, depending on the processor. See“Global Offset Table (Processor-Specific)” on page 213, “Procedure LinkageTable” on page 215, “Procedure Linkage Table” on page 218, and “ProcedureLinkage Table” on page 221 for details.

As previously described in “Section Header”, the .bss section has the typeSHT_NOBITS. Although it occupies no space in the file, it contributes to thesegment’s memory image. Normally, these uninitialized data reside at the endof the segment, thereby making p_memsz larger than p_filesz in theassociated program header element.

Program Loading (Processor-Specific)

As the system creates or augments a process image, it logically copies a file’ssegment to a virtual memory segment. When, and if, the system physicallyreads the file depends on the program’s execution behavior, system load, andso forth.

A process does not require a physical page unless it references the logical pageduring execution, and processes commonly leave many pages unreferenced.Therefore delaying physical reads frequently obviates them, improving systemperformance. To obtain this efficiency in practice, executable and shared objectfiles must have segment images whose file offsets and virtual addresses arecongruent, modulo the page size.

Virtual addresses and file offsets for SPARC and PowerPC segments arecongruent modulo 64K (0x10000 ). Virtual addresses and file offsets for x86segments are congruent modulo 4K (0x1000 ). By aligning segments to themaximum page size, the files are suitable for paging regardless of physicalpage size.

Page 210: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

196 Linker and Libraries Guide—November 1995

6

The following example presents the SPARC version.

Figure 6-7 SPARC: Executable File (64 K alignment)

Table 6-31 SPARC: Program Header Segments (64 K alignment)

Member Text Data

p_type PT_LOAD PT_LOAD

p_offset 0x100 0x2bf00

p_vaddr 0x10100 0x4bf00

p_paddr Unspecified Unspecified

p_filesize 0x2be00 0x4e00

p_memsz 0x2be00 0x5e24

p_flags PF_R + PF_X PF_R + PF_W + PF_X

p_align 0x10000 0x10000

File Virtual address File offset

ELF header0

Program header table

Other information

0x100 Text segment 0x10100

. . .

0x2be00 bytes 0x3beff

0x2bf00 Data segment 0x4bf00

. . .

0x4e00 bytes 0x50cff

0x30d00 Other information

. . .

Page 211: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 197

6

The following example presents the x86 version.

Figure 6-8 x86: Executable File (4 K alignment)

Table 6-32 x86: Program Header Segments (4 K alignment)

Member Text Data

p_type PT_LOAD PT_LOAD

p_offset 0x100 0x2bf00

p_vaddr 0x8048100 0x8074f00

p_paddr Unspecified Unspecified

p_filesize 0x2be00 0x4e00

p_memsz 0x2be00 0x5e24

p_flags PF_R + PF_X PF_R + PF_W + PF_X

p_align 0x1000 0x1000

File Virtual address File offset

ELF header0

Program header table

Other information

0x100 Text segment 0x8048100

. . .

0x2be00 bytes 0x8073eff

0x2bf00 Data segment 0x8074f00

. . .

0x4e00 bytes 0x8079cff

0x30d00 Other information

. . .

Page 212: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

198 Linker and Libraries Guide—November 1995

6

The following example presents the PowerPC version.

Figure 6-9 PowerPC: Executable File (4 K alignment)

Although the example’s file offsets and virtual addresses are congruentmodulo the maximum page size for both text and data, up to four file pageshold impure text or data (depending on page size and file system block size).

Table 6-33 PowerPC: Program Header Segments (4 K alignment)

Member Text Data

p_type PT_LOAD PT_LOAD

p_offset 0x100 0x2bf00

p_vaddr 0x2048100 0x2074f00

p_paddr Unspecified Unspecified

p_filesize 0x2be00 0x4e00

p_memsz 0x2be00 0x5e24

p_flags PF_R + PF_X PF_R + PF_W + PF_X

p_align 0x1000 0x1000

File Virtual address File offset

ELF header0

Program header table

Other information

0x100 Text segment 0x2048100

. . .

0x2be00 bytes 0x2073eff

0x2bf00 Data segment 0x2074f00

. . .

0x4e00 bytes 0x2079cff

0x30d00 Other information

. . .

Page 213: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 199

6

• The first text page contains the ELF header, the program header table, andother information.

• The last text page holds a copy of the beginning of data.

• The first data page has a copy of the end of text.

• The last data page may contain file information not relevant to the runningprocess. Logically, the system enforces the memory permissions as if eachsegment is complete and separate; segments’ addresses are adjusted toensure each logical page in the address space has a single set of permissions.In the examples above, the region of the file holding the end of text and thebeginning of data will be mapped twice: at one virtual address for text andat a different virtual address for data.

The end of the data segment requires special handling for uninitialized data,which the system defines to begin with zero values. Thus, if a file’s last datapage includes information not in the logical memory page, the extraneous datamust be set to zero, not the unknown contents of the executable file.

Impurities in the other three pages are not logically part of the process image;whether the system expunges them is unspecified. The memory image for thisprogram follows, assuming 4 Kilobyte (0x1000) pages. For simplicity, theseexamples illustrates only one page size.

Page 214: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

200 Linker and Libraries Guide—November 1995

6

Figure 6-10 SPARC: Process Image Segments

Contents SegmentVirtual Address

Header Padding 0x10000

0x100 bytes

0x10100 Text segment

Text . . .

0x2be00 bytes

0x3bf00

Data segment

. . .

0x4e00 bytes

Data

0x4b000

Data Padding0x100 bytes

Text Padding0x100 bytes

0x4bf00

0x50d00 Uninitialized Data

0x1024 zero bytes

0x51d24 Page Padding

0x2dc zero bytes

Page 215: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 201

6

Figure 6-11 x86: Process Image Segments

Contents SegmentVirtual Address

Header Padding 0x8048000

0x100 bytes

0x8048100 Text segment

Text . . .

0x2be00 bytes

0x8073f00

Data segment

. . .

0x4e00 bytes

Data

0x8074000

Data Padding0x100 bytes

Text Padding0x100 bytes

0x8074f00

0x8079d00 Uninitialized Data

0x1024 zero bytes

0x807ad24 Page Padding

0x2dc zero bytes

Page 216: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

202 Linker and Libraries Guide—November 1995

6

Figure 6-12 PowerPC: Process Image Segments

One aspect of segment loading differs between executable files and sharedobjects. Executable file segments typically contain absolute code. For theprocess to execute correctly, the segments must reside at the virtual addressesused to build the executable file. Thus the system uses the p_vaddr valuesunchanged as virtual addresses.

Contents SegmentVirtual Address

Header Padding 0x2000000

0x100 bytes

0x2000100 Text segment

Text . . .

0x2be00 bytes

0x202bf00

Data segment

. . .

0x4e00 bytes

Data

0x202c000

Data Padding0x100 bytes

Text Padding0x100 bytes

0x202cf00

0x2031d00 Uninitialized Data

0x1024 zero bytes

0x2032d24 Page Padding

0x2dc zero bytes

Page 217: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 203

6

On the other hand, shared object segments typically contain position-independent code. (For background, see “Link-Editor” on page 7.) This lets asegment’s virtual address change from one process to another, withoutinvalidating execution behavior.

Though the system chooses virtual addresses for individual processes, itmaintains the segments’ relative positions. Because position-independent codeuses relative addressing between segments, the difference between virtualaddresses in memory must match the difference between virtual addresses inthe file.

The following tables show possible shared object virtual address assignmentsfor several processes, illustrating constant relative positioning. The table alsoillustrates the base address computations.

Table 6-34 Example SPARC Shared Object Segment Addresses

Source Text Data Base Address

File 0x200 0x2a400 0x0

Process 1 0xc0000200 0xc002a400 0xc0000000

Process 2 0xc0010200 0xc003c400 0xc0010000

Process 3 0xd0020200 0xd004a400 0xd0020000

Process 4 0xd0030200 0xd005a400 0xd0030000

Table 6-35 Example x86 Shared Object Segment Addresses

Source Text Data Base Address

File 0x200 0x2a400 0x0

Process 1 0x80000200 0x8002a400 0x80000000

Process 2 0x80081200 0x800ab400 0x80081000

Process 3 0x900c0200 0x900ea400 0x900c0000

Process 4 0x900c6200 0x900f0400 0x900c6000

Page 218: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

204 Linker and Libraries Guide—November 1995

6

Unlike the SPARC and x86, which load shared object segments in a singleregion, the PowerPC can load shared object segments in two regions. ThePowerPC Application Binary Interface states that region 1 (0x10000 toUSRTEXT) and region 2 (user_stack_limit to program_break_address) can beused for dynamic segments. Using the address space depicted by region 1 is anoptimization that causes the relative addresses to fall within a 32M range,limited by the relative address branch instructions on PowerPC. The allocationis done in the following order:

Region 1: 0x10000 to USERTEXT

Allocation is from high end to low end.

Region 2: program_break_address to user_stack_limit

Allocation is from high end to low end.

Program Interpreter

An executable file may have one PT_INTERP program header element. Duringexec(2) , the system retrieves a path name from the PT_INTERP segment andcreates the initial process image from the interpreter file’s segments. That is,instead of using segment images of the original executable files, the systemcomposes a memory image for the interpreter. It then is the interpreter’sresponsibility to receive control from the system and provide an environmentfor the application program.

The interpreter receives control in one of two ways. First, it may receive a filedescriptor to read the executable file, positioned at the beginning. It can usethis file descriptor to read and/or map the executable file’s segments intomemory. Second, depending on the executable file format, the system may loadthe executable file into memory instead of giving the interpreter an open filedescriptor.

With the possible exception of the file descriptor, the interpreter’s initialprocess state matches what the executable file has received. The interpreteritself may not require a second interpreter. An interpreter may be either ashared object or an executable file.

Page 219: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 205

6

• A shared object (the normal case) is loaded as position-independent, withaddresses that may vary from one process to another; the system creates itssegments in the dynamic segment area used by mmap(2) and relatedservices. Consequently, a shared object interpreter typically will not conflictwith the original executable file’s original segment addresses.

• An executable file is loaded at fixed addresses; the system creates itssegments using the virtual addresses from the program header table.Consequently, an executable file interpreter’s virtual addresses may collidewith the first executable file; the interpreter is responsible for resolvingconflicts.

Runtime Linker

When building an executable file that uses dynamic linking, the link-editoradds a program header element of type PT_INTERP to an executable file,telling the system to invoke the runtime linker as the program interpreter.exec(2) and the runtime linker cooperate to create the process image for theprogram, which entails the following actions:

• Adding the executable file’s memory segments to the process image;

• Adding shared object memory segments to the process image;

• Performing relocations for the executable file and its shared objects;

• Closing the file descriptor that was used to read the executable file, if onewas given to the runtime linker;

• Calling any .init section provided in the objects mapped; see “Initializationand Termination Functions” on page 225

• Transferring control to the program, making it look as if the program hadreceived control directly from exec(2) .

The link-editor also constructs various data that assist the runtime linker forexecutable and shared object files. As shown above in “Program Header,” thesedata reside in loadable segments, making them available during execution.(Once again, recall the exact segment contents are processor-specific.)

• A .dynamic section with type SHT_DYNAMIC holds various data. Thestructure residing at the beginning of the section holds the addresses ofother dynamic linking information.

• The .hash section with type SHT_HASH holds a symbol hash table.

Page 220: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

206 Linker and Libraries Guide—November 1995

6

• The .got and .plt sections with type SHT_PROGBITS hold two separatetables: the global offset table and the procedure linkage table. Sectionsbelow explain how the runtime linker uses and changes the tables to creatememory images for object files.

As explained in “Program Loading (Processor-Specific)” on page 195, sharedobjects may occupy virtual memory addresses that are different from theaddresses recorded in the file’s program header table. The runtime linkerrelocates the memory image, updating absolute addresses before theapplication gains control. Although the absolute address values will be correctif the library is loaded at the addresses specified in the program header table,this normally is not the case.

If the process environment (see exec(2) ) contains a variable namedLD_BIND_NOW with a non-null value, the runtime linker processes allrelocation before transferring control to the program. For example, each of theenvironment entries

specifies this behavior. The runtime linker can evaluate procedure linkage tableentries lazily, so avoiding resolution and relocation overhead for functions thatare not called. See “Procedure Linkage Table” on page 215, “Procedure LinkageTable” on page 218, and “Procedure Linkage Table” on page 221 for moreinformation.

LD_BIND_NOW=1LD_BIND_NOW=onLD_BIND_NOW=off

Page 221: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 207

6

Dynamic Section

If an object file participates in dynamic linking, its program header table willhave an element of type PT_DYNAMIC. This “segment” contains the .dynamicsection. A special symbol, _DYNAMIC, labels the section, which contains anarray of the following structures (defined in sys/link.h ):

For each object with this type, d_tag controls the interpretation of d_un .

d_valThese Elf32_Word objects represent integer values with variousinterpretations.

d_ptrThese Elf32_Addr objects represent program virtual addresses. Asmentioned previously, a file’s virtual addresses might not match thememory virtual addresses during execution. When interpreting addressescontained in the dynamic structure, the runtime linker computes actualaddresses, based on the original file value and the memory base address.For consistency, files do not contain relocation entries to correct addresses inthe dynamic structure.

typedef struct { Elf32_Sword d_tag; union { Elf32_Word d_val; Elf32_Addr d_ptr; Elf32_Off d_off; } d_un;} Elf32_Dyn;

Page 222: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

208 Linker and Libraries Guide—November 1995

6

The following table summarizes the tag requirements for executable andshared object files. If a tag is marked mandatory, then the dynamic linking arraymust have an entry of that type. Likewise, optional means an entry for the tagmay appear but is not required.

Table 6-36 Dynamic Array Tags, d_tag (1 of 2)

Name Value d_un Executable Shared Object

DT_NULL 0 Ignored Mandatory Mandatory

DT_NEEDED 1 d_val Optional Optional

DT_PLTRELSZ 2 d_val Optional Optional

DT_PLTGOT 3 d_ptr Optional Optional

DT_HASH 4 d_ptr Mandatory Mandatory

DT_STRTAB 5 d_ptr Mandatory Mandatory

DT_SYMTAB 6 d_ptr Mandatory Mandatory

DT_RELA 7 d_ptr Mandatory Optional

DT_RELASZ 8 d_val Mandatory Optional

DT_RELAENT 9 d_val Mandatory Optional

DT_STRSZ 10 d_val Mandatory Mandatory

DT_SYMENT 11 d_val Mandatory Mandatory

DT_INIT 12 d_ptr Optional Optional

DT_FINI 13 d_ptr Optional Optional

DT_SONAME 14 d_val Ignored Optional

DT_RPATH 15 d_val Optional Ignored

DT_SYMBOLIC 16 Ignored Ignored Optional

DT_REL 17 d_ptr Mandatory Optional

DT_RELSZ 18 d_val Mandatory Optional

DT_RELENT 19 d_val Mandatory Optional

DT_PLTREL 20 d_val Optional Optional

DT_DEBUG 21 d_ptr Optional Ignored

DT_TEXTREL 22 Ignored Optional Optional

DT_JMPREL 23 d_ptr Optional Optional

Page 223: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 209

6

DT_NULLAn entry with a DT_NULL tag marks the end of the _DYNAMIC array.

DT_NEEDEDThis element holds the string table offset of a null-terminated string, givingthe name of a needed dependency. The offset is an index into the tablerecorded in the DT_STRTAB entry. See “Shared Object Dependencies” onpage 213 for more information about these names. The dynamic array maycontain multiple entries with this type. These entries’ relative order issignificant, though their relation to entries of other types is not.

DT_PLTRELSZThis element holds the total size, in bytes, of the relocation entriesassociated with the procedure linkage table. If an entry of type DT_JMPRELis present, a DT_PLTRELSZ must accompany it.

DT_PLTGOTThis element holds an address associated with the procedure linkage tableand/or the global offset table.

DT_HASHThis element points to the symbol hash table, described in “Hash Table” onpage 224. This hash table refers to the symbol table indicated by theDT_SYMTAB element.

DT_VERDEF 0x6ffffffc d_ptr Optional Optional

DT_VERDEFNUM 0x6ffffffd d_val Optional Optional

DT_VERNEED 0x6ffffffe d_ptr Optional Optional

DT_VERNEEDNUM 0x6fffffff d_val Optional Optional

DT_AUXILIARY 0x7ffffffd d_val Unspecified Optional

DT_USED 0x7ffffffe d_val Optional Optional

DT_FILTER 0x7fffffff d_val Unspecified Optional

DT_LOPROC 0x70000000 Unspecified Unspecified Unspecified

DT_HIPROC 0x7fffffff Unspecified Unspecified Unspecified

Table 6-36 Dynamic Array Tags, d_tag (2 of 2)

Name Value d_un Executable Shared Object

Page 224: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

210 Linker and Libraries Guide—November 1995

6

DT_STRTABThis element holds the address of the string table, described in the first partof this chapter. Symbol names, dependency names, and other stringsrequired by the runtime linker reside in this table.

DT_SYMTABThis element holds the address of the symbol table, described in the firstpart of this chapter, with Elf32_Sym entries for the 32-bit class of files.

DT_RELAThis element holds the address of a relocation table, described in the firstpart of this chapter. Entries in the table have explicit addends, such asElf32_Rela for the 32-bit file class.

An object file may have multiple relocation sections. When building therelocation table for an executable or shared object file, the link-editorcatenates those sections to form a single table. Although the sections remainindependent in the object file, the runtime linker sees a single table. Whenthe runtime linker creates the process image for an executable file or adds ashared object to the process image, it reads the relocation table and performsthe associated actions.

If this element is present, the dynamic structure must also have DT_RELASZand DT_RELAENT elements. When relocation is mandatory for a file, eitherDT_RELA or DT_REL may occur (both are permitted but not required).

DT_RELASZThis element holds the total size, in bytes, of the DT_RELA relocation table.

DT_RELAENTThis element holds the size, in bytes, of the DT_RELA relocation entry.

DT_STRSZThis element holds the size, in bytes, of the string table.

DT_SYMENTThis element holds the size, in bytes, of a symbol table entry.

DT_INITThis element holds the address of the initialization function, discussed in“Initialization and Termination Functions” on page 225 later.

Page 225: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 211

6

DT_FINIThis element holds the address of the termination function, discussed in“Initialization and Termination Functions” on page 225 later.

DT_SONAMEThis element holds the string table offset of a null-terminated string, givingthe name of the shared object. The offset is an index into the table recordedin the DT_STRTAB entry. See Section , “Shared Object Dependencies,” onpage 213 for more information about these names.

DT_RPATHThis element holds the string table offset of a null-terminated search librarysearch path string, discussed in “Shared Objects with Dependencies” onpage 89. The offset is an index into the table recorded in the DT_STRTABentry.

DT_SYMBOLICThis element’s presence in a shared object library alters the runtime linker’ssymbol resolution algorithm for references within the library. Instead ofstarting a symbol search with the executable file, the runtime linker startsfrom the shared object itself. If the shared object fails to supply thereferenced symbol, the runtime linker then searches the executable file andother shared objects as usual.

DT_RELThis element is similar to DT_RELA, except its table has implicit addends,such as Elf32_Rel for the 32-bit file class. If this element is present, thedynamic structure must also have DT_RELSZ and DT_RELENT elements.

DT_RELSZThis element holds the total size, in bytes, of the DT_REL relocation table.

DT_RELENTThis element holds the size, in bytes, of the DT_REL relocation entry.

DT_PLTRELThis member specifies the type of relocation entry to which the procedurelinkage table refers. The d_val member holds DT_REL or DT_RELA, asappropriate. All relocations in a procedure linkage table must use the samerelocation.

DT_DEBUGThis member is used for debugging.

Page 226: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

212 Linker and Libraries Guide—November 1995

6

DT_TEXTRELThis member’s absence signifies that no relocation entry should cause amodification to a non-writable segment, as specified by the segmentpermissions in the program header table. If this member is present, one ormore relocation entries might request modifications to a non-writablesegment, and the runtime linker can prepare accordingly.

DT_JMPRELIf present, this entry’s d_ptr member holds the address of relocation entriesassociated solely with the procedure linkage table. Separating theserelocation entries lets the runtime linker ignore them during processinitialization, if lazy binding is enabled. If this entry is present, the relatedentries of types DT_PLTRELSZ and DT_PLTREL must also be present.

DT_VERDEFHolds the address of the version definition table, described in the first partof this chapter, with Elf32_Verdef entries for the 32-bit class of files. Seesection “Version Definition Section” on page 181 for more information.Elements within these entries contain indexes into the table recorded in theDT_STRTAB entry.

DT_VERDEFNUMThis element specifies the number of entries in the version definition table.

DT_VERNEEDHolds the address of the version dependency table, described in the firstpart of this chapter, with Elf32_Verneed entries for the 32-bit class of files.See section “Version Dependency Section” on page 185 for moreinformation. Elements within these entries contain indexes into the tablerecorded in the DT_STRTAB entry.

DT_VERNEEDNUMThis element specifies the number of entries in the version dependencytable.

DT_AUXILIARYHolds the string table offset of a null-terminated string that names an object.The offset is an index into the table recorded in the DT_STRTAB entry.Symbols in the auxiliary object will be used in preference to the symbolswithin this object.

Page 227: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 213

6

DT_FILTERHolds the string table offset of a null-terminated string that names an object.The offset is an index into the table recorded in the DT_STRTAB entry. Thesymbol table of this object acts as a filter for the symbol table of the namedobject.

DT_LOPROC - DT_HIPROCValues in this inclusive range are reserved for processor-specific semantics.

Except for the DT_NULL element at the end of the array and the relative orderof DT_NEEDED elements, entries may appear in any order. Tag values notappearing in the table are reserved.

Shared Object Dependencies

When the runtime linker creates the memory segments for an object file, thedependencies (recorded in DT_NEEDED entries of the dynamic structure) tellwhat shared objects are needed to supply the program’s services. Byrepeatedly connecting referenced shared objects and their dependencies, theruntime linker builds a complete process image.

When resolving symbolic references, the runtime linker examines the symboltables with a breadth-first search. That is, it first looks at the symbol table ofthe executable program itself, then at the symbol tables of the DT_NEEDEDentries (in order), then at the second level DT_NEEDED entries, and so on.

Note – Even when a shared object is referenced multiple times in thedependency list, the runtime linker will connect the object only once to theprocess.

Names in the dependency list are copies either of the DT_SONAME strings orthe path names of the shared objects used to build the object file.

Global Offset Table (Processor-Specific)

Position-independent code cannot, in general, contain absolute virtualaddresses. Global offset tables hold absolute addresses in private data, thusmaking the addresses available without compromising the position-

Page 228: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

214 Linker and Libraries Guide—November 1995

6

independence and shareability of a program’s text. A program references itsglobal offset table using position-independent addressing and extracts absolutevalues, thus redirecting position-independent references to absolute locations.

Initially, the global offset table holds information as required by its relocationentries (see “Relocation” on page 167 for more information). After the systemcreates memory segments for a loadable object file, the runtime linkerprocesses the relocation entries, some of which will be typeR_SPARC_GLOB_DAT (for SPARC), R_386_GLOB_DAT (for x86), orR_PPC_GLOB_DAT (for PowerPC) referring to the global offset table.

The runtime linker determines the associated symbol values, calculates theirabsolute addresses, and sets the appropriate memory table entries to theproper values. Although the absolute addresses are unknown when the link-editor builds an object file, the runtime linker knows the addresses of allmemory segments and can thus calculate the absolute addresses of the symbolscontained therein.

If a program requires direct access to the absolute address of a symbol, thatsymbol will have a global offset table entry. Because the executable file andshared objects have separate global offset tables, a symbol’s address mayappear in several tables. The runtime linker processes all the global offset tablerelocations before giving control to any code in the process image, thusensuring the absolute addresses are available during execution.

The table’s entry zero is reserved to hold the address of the dynamic structure,referenced with the symbol _DYNAMIC. This allows a program, such as theruntime linker, to find its own dynamic structure without having yet processedits relocation entries. This is especially important for the runtime linker,because it must initialize itself without relying on other programs to relocateits memory image.

The system may choose different memory segment addresses for the sameshared object in different programs; it may even choose different libraryaddresses for different executions of the same program. Nonetheless, memorysegments do not change addresses once the process image is established. Aslong as a process exists, its memory segments reside at fixed virtual addresses.

Page 229: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 215

6

A global offset table’s format and interpretation are processor-specific. ForSPARC, x86, and PowerPC processors, the symbol__GLOBAL_OFFSET_TABLE_ may be used to access the table.

The symbol _GLOBAL_OFFSET_TABLE_ may reside in the middle of the .gotsection, allowing both negative and nonnegative subscripts into the array ofaddresses.

SPARC: Procedure Linkage Table

As the global offset table converts position-independent address calculations toabsolute locations, the procedure linkage table converts position-independentfunction calls to absolute locations. The link-editor cannot resolve executiontransfers (such as function calls) from one executable or shared object toanother. So, the link-editor puts the program transfer control to entries in theprocedure linkage table.

On SPARC architectures, procedure linkage tables reside in private data. Theruntime linker determines the destinations’ absolute addresses and modifiesthe procedure linkage table’s memory image accordingly. The runtime linkerthus redirects the entries without compromising the position-independenceand shareability of the program’s text. Executable files and shared object fileshave separate procedure linkage tables.

The first four procedure linkage table entries are reserved. (The originalcontents of these entries are unspecified, despite the example, below.) Eachentry in the table occupies 3 words (12 bytes), and the last table entry isfollowed by a nop instruction.

A relocation table is associated with the procedure linkage table. TheDT_JMP_REL entry in the _DYNAMIC array gives the location of the firstrelocation entry. The relocation table has one entry, in the same sequence, foreach procedure linkage table entry. Except the first four entries, the relocationtype is R_SPARC_JMP_SLOT, the relocation offset specifies the address of thefirst byte of the associated procedure linkage table entry, and the symbol tableindex refers to the appropriate symbol.

extern Elf32_Addr _GLOBAL_OFFSET_TABLE_[];

Page 230: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

216 Linker and Libraries Guide—November 1995

6

To illustrate procedure linkage tables, the figure below shows four entries: twoof the four initial reserved entries, the third is a call to name1, and the fourth isa call to name2. The example assumes the entry for name2 is the table’s lastentry and shows the following nop instruction. The left column shows theinstructions from the object file before dynamic linking. The right columndemonstrates a possible way the runtime linker might fix the procedurelinkage table entries.Code Example 6-1 SPARC: Procedure Linkage Table Example

Following the steps below, the runtime linker and program jointly resolve thesymbolic references through the procedure linkage table. Again, the stepsdescribed below are for explanation only. The precise execution-time behaviorof the runtime linker is not specified.

Object File Memory Segment

.PLT0:unimpunimpunimp

.PLT1:unimpunimpunimp...

.PLT0:save %sp,-64,%spcall runtime-linkernop

.PLT1:.word identificationunimpunimp...

....PLT101:

sethi (.-.PLT0),%g1ba,a .PLT0nop

.PLT102:sethi (.-.PLT0),%g1ba,a .PLT0nop

....PLT101:

sethi (.-.PLT0),%g1sethi %hi(name1),%g1jmp1 %g1+%lo(name1),%g0

.plt102:sethi (.-.PLT0),%g1sethi %hi(name2),%g1jmp1 %g1+%lo(name2),%g0

nop nop

Page 231: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 217

6

1. When first creating the memory image of the program, the runtime linkerchanges the initial procedure linkage table entries, making them transfercontrol to one of the runtime linker’s own routines. It also stores a word ofidentification information in the second entry. When it receives control, it canexamine this word to find what object called it.

2. All other procedure linkage table entries initially transfer to the first entry,letting the runtime linker gain control at the first execution of each tableentry. For example, the program calls name1, which transfers control to thelabel .PLT101 .

3. The sethi instruction computes the distance between the current and theinitial procedure linkage table entries, .PLT101 and .PLT0, respectively. Thisvalue occupies the most significant 22 bits of the %g1 register. In thisexample, &g1 contains 0x12f000 when the runtime linker receives control.

4. Next, the ba,a instruction jumps to .PLT0 , establishing a stack frame andcalls the runtime linker.

5. With the identification value, the runtime linker gets its data structures forthe object, including the relocation table.

6. By shifting the %g1 value and dividing by the size of the procedure linkagetable entries, the runtime linker calculates the index of the relocation entryfor name1. Relocation entry 101 has type R_SPARC_JMP_SLOT, its offsetspecifies the address of .PLT101 , and its symbol table index refers to name1.Thus, the runtime linker gets the symbol’s real value, unwinds the stack,modifies the procedure linkage table entry, and transfers control to thedesired destination.

Although the runtime linker does not have to create the instruction sequencesunder the Memory Segment column, it might. If it did, some points deservemore explanation.

• To make the code reentrant, the procedure linkage table’s instructions arechanged in a particular sequence. If the runtime linker is fixing a function’sprocedure linkage table entry and a signal arrives, the signal handling codemust be able to call the original function with predictable (and correct)results.

• The runtime linker changes two words to convert an entry. It updates eachword automatically. Reentrancy is achieved by first overwriting the nopwith the jmp1 instruction, and then patching the ba,a to be sethi . If areentrant function call happens between the two word updates, the jmp1

Page 232: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

218 Linker and Libraries Guide—November 1995

6

resides in the delay slot of the ba,a instruction, and cancels the delayinstruction. So, the runtime linker gains control a second time. Althoughboth invocations of the runtime linker modify the same procedure linkagetable entry, their changes do not interfere with each other.

• The first sethi instruction of a procedure linkage table entry can fill thedelay slot of the previous entry’s jmp1 instruction. Although the sethichanges the value of the %g1 register, the previous contents can be safelydiscarded.

• After conversion, the last procedure linkage table entry (.PLT102 above)needs a delay instruction for its jmp1 . The required, trailing nop fills thisdelay slot.

The LD_BIND_NOW environment variable changes dynamic linking behavior. Ifits value is non-null, the runtime linker processes R_SPARC_JMP_SLOTrelocation entries (procedure linkage table entries) before transferring controlto the program. If LD_BIND_NOW is null, the runtime linker evaluates linkagetable entries on the first execution of each table entry.

x86: Procedure Linkage Table

As for SPARC, the procedure linkage table redirects position-independentfunction calls to absolute locations. The link-editor cannot resolve executiontransfers (such as function calls) from one executable or shared object toanother. So, the link-editor has the program transfer control to entries in theprocedure linkage table.

On x86 architectures, procedure linkage tables reside in shared text, but theyuse addresses in the private global offset table. The runtime linker determinesthe destinations’ absolute addresses and modifies the global offset table’smemory image accordingly. The runtime linker thus redirects the entrieswithout compromising the position-independence and shareability of theprogram’s text. Executable files and shared object files have separate procedurelinkage tables.

Page 233: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 219

6

Code Example 6-2 x86: Procedure Linkage Table Example

Following the steps below, the runtime linker and program cooperate toresolve the symbolic references through the procedure linkage table and theglobal offset table.

1. When first creating the memory image of the program, the runtime linkersets the second and third entries in the global offset table to special values.Steps below explain these values.

2. If the procedure linkage table is position-independent, the address of theglobal offset table must be in %ebx . Each shared object file in the processimage has its own procedure linkage table, and control transfers to aprocedure linkage table entry only from within the same object file. So, thecalling function must set the global offset table base register before it callsthe procedure linkage table entry.

.PLT0: pushl got_plus_4jmp *got_plus_8nop; nopnop; nop

.PLT1: jmp *name1_in_GOTpushl $offsetjmp .PLT0@PC

.PLT2: jmp *name2_in_GOTpushl $offsetjmp .PLT0@PC...

.PLT0: pushl 4(%ebx)jmp *8(%ebx)nop; nopnop; nop

.PLT1: jmp *name1@GOT(%ebx)pushl $offsetjmp .PLT0@PC

.PLT2: jmp *name2@GOT(%ebx)pushl $offsetjmp .PLT0@PC...

Page 234: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

220 Linker and Libraries Guide—November 1995

6

3. For example, the program calls name1, which transfers control to the label.PLT1 .

4. The first instruction jumps to the address in the global offset table entry forname1. Initially, the global offset table holds the address of the followingpushl instruction, not the real address of name1.

5. So, the program pushes a relocation offset (offset ) on the stack. Therelocation offset is a 32-bit, nonnegative byte offset into the relocation table.the designated relocation entry has the type R_386_JMP_SLOT, and itsoffset specifies the global offset table entry used in the previous jmpinstruction. The relocation entry also contains a symbol table index, whichthe runtime linker uses to get the referenced symbol, name1.

6. After pushing the relocation offset, the program jumps to .PLT0 , the firstentry in the procedure linkage table. The pushl instruction pushes thevalue of the second global offset table entry (got_plus_4 or 4(%ebx) ) onthe stack, giving the runtime linker one word of identifying information.The program then jumps to the address in the third global offset table entry(got_plus_8 or 8(%ebx) ), to jump to the runtime linker.

7. The runtime linker unwinds the stack, checks the designated relocationentry, gets the symbol’s value, stores the actual address of name1 in itsglobal offset entry table, and jumps to the destination.

8. Subsequent executions of the procedure linkage table entry transfer directlyto name1, without calling the runtime linker again. This is because the jmpinstruction at .PLT1 jumps to name1 instead of falling through to thepushl instruction.

The LD_BIND_NOW environment variable changes dynamic linking behavior. Ifits value is non-null, the runtime linker processes R_386_JMP_SLOT relocationentries (procedure linkage table entries) before transferring control to theprogram. If LD_BIND_NOW is null, the runtime linker evaluates linkage tableentries on the first execution of each table entry.

Page 235: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 221

6

PowerPC: Procedure Linkage Table

As for SPARC and Intel, the procedure linkage table redirects position-independent function calls to absolute locations. The link editor cannot resolveexecution transfers (such as function calls) from one executable or sharedobject to another. So, the link editor has the program transfer control to entriesin the procedure linkage table.

For the PowerPC, the procedure linkage table (the .plt section) is notinitialized in the executable or shared object file. Instead, the link editor simplyreserves space for it and the dynamic linker initializes it and manages itaccording to its own, possibly implementation-dependent needs, subject to thefollowing constraints:

• The first 18 words (72 bytes) of the procedure linkage table are reserved foruse by the dynamic linker. There shall be no branches from the executable orshared object into these first 18 words.

• If the executable or shared object requires N procedure linkage table entries,the link editor reserves 3*N words (12*N bytes) following the 18 reservedwords. The first 2*N of these words are the procedure linkage table entriesthemselves. The link-editor directs calls to bytes (72 + (i-1)*8 ), for ibetween 1 and N inclusive. The remaining N words (4*N bytes) are reservedfor use by the dynamic linker.

As mentioned before, a relocation table is associated with the procedurelinkage table. The DT_JMPREL entry in the _DYNAMIC array gives the locationof the first relocation entry. The relocation table's entries parallel the procedurelinkage table entries in a one-to-one correspondence. That is, relocation tableentry 1 applies to procedure linkage table entry 1, and so on. The relocationtype for each entry shall be R_PPC_JMP_SLOT, the relocation offset shallspecify the address of the first byte of the associated procedure linkage tableentry, and the symbol table index shall reference the appropriate symbol.

To illustrate procedure linkage tables, “Procedure Linkage Table Example.” onpage 222 shows how the dynamic linker might initialize the procedure linkagetable when loading the executable or shared object.

Page 236: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

222 Linker and Libraries Guide—November 1995

6

Code Example 6-3 PowerPCProcedure Linkage Table Example.

Following the steps below, the dynamic linker and the program cooperate toresolve symbolic references through the procedure linkage table. Again, thesteps described below are for explanation only. The precise execution-timebehavior of the dynamic linker is not specified.

.word 0 # tag word - no register savingPLTresolve: addis r12,r0,dynamic_linker@ha addi r12,r12,dynamic_linker@l mtctr r12 addis r12,r0,symtab_addr@ha addi r12,r12,symtab_addr@l bctr.PLTcall: addis r11,r11,.PLTtable@ha lwz r11,.PLTtable@lo(r11 mtctr r11) bctr nop nop nop nop nop nop nop nop.PLT1: addi r11,r0,4*0 b .PLTresolve . . ..PLTi: addi r11,4*i b .PLTresolve . . ..PLTN: addi r11,4*(N-1) b .PLTresolve

.PLTtable: <N word table begins here>

Page 237: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 223

6

1. As shown above, all procedure linkage table entries initially transfer to.PLTresolve , allowing the dynamic linker to gain control at the firstexecution of each table entry. For illustration, assume the program callsname, which transfers control to the label .PLTi . The procedure linkagetable entry loads into r11 four times the index of the relocation entry for.PLTi and branches to .PLTresolve , which then calls into the dynamiclinker with a pointer to the symbol table for the object in r12 .

2. The dynamic linker finds relocation entry i corresponding to the index inr11 . It will have type R_PPC_JMP_SLOT, its offset will specify the addressof .PLTi , and its symbol table index will reference name.

3. Knowing this, the dynamic linker finds the symbol's “real” value. It thenmodifies the code at .PLTi in one of two ways. If the target symbol isreachable from .PLTi by a branch instruction, it overwrites the “lir11,4*i” instruction at .PLTi with a branch to the target. On the otherhand, if the target symbol is not reachable from .PLTi , the dynamic linkerloads the target address into word.PLTtable+4*(i-1) and overwrites the “b .PLTresolve” with a“b .PLTcall” .

4. Subsequent executions of the procedure linkage table entry will transfercontrol directly to the function, either directly or by using .PLTcall ,without invoking the dynamic linker.

For PLT indexes greater than or equal to 2^14 , only the even indexes shall beused and four words shall be allocated for each entry. If the above scheme isused, this allows four instructions for loading the index and branching to.PLTresolve or .PLTcall , instead of only two.

The LD_BIND_NOW environment variable can change dynamic linkingbehavior. If its value is non-null, the dynamic linker resolves the function callbinding at load time, before transferring control to the program. That is, thedynamic linker processes relocation entries of type R_PPC_JMP_SLOT duringprocess initialization. Otherwise, the dynamic linker evaluates procedurelinkage table entries lazily, delaying symbol resolution and relocation until thefirst execution of a table entry.

Page 238: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

224 Linker and Libraries Guide—November 1995

6

Hash Table

A hash table of Elf32_Word objects supports symbol table access. The symboltable to which the hashing is associated is specified in the sh_link entry ofthe hash table’s section header (refer to Table 6-13 on page 156). Labels appearbelow to help explain the hash table organization, but they are not part of thespecification.

Figure 6-13 Symbol Hash Table

The bucket array contains nbucket entries, and the chain array containsnchain entries; indexes start at 0. Both bucket and chain hold symbol tableindexes. Chain table entries parallel the symbol table. The number of symboltable entries should equal nchain ; so, symbol table indexes also select chaintable entries.

A hashing function accepts a symbol name and returns a value that may beused to compute a bucket index. Consequently, if the hashing function returnsthe value x for some name, bucket [x%nbucket] gives an index y into boththe symbol table and the chain table. If the symbol table entry is not the onedesired, chain[y] gives the next symbol table entry with the same hash value.

One can follow the chain links until either the selected symbol table entryholds the desired name or the chain entry contains the value STN_UNDEF.

nbucket

nchain

bucket [0]

. . .bucket [nbucket - 1]

chain [0]

. . .chain [nchain - 1]

Page 239: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Object Files 225

6

Initialization and Termination Functions

After the runtime linker has built the process image and performed therelocations, each shared object gets the opportunity to execute someinitialization code. These initialization functions are called in the reverse of theorder at which they are encountered.

Similarly, shared objects may have termination functions, which are executedwith the atexit(3C) mechanism after the base process begins its terminationsequence. Refer to atexit(3C) for more information. These terminationfunctions are called in the order they are encountered.

Shared objects designate their initialization and termination functions throughthe DT_INIT and DT_FINI entries in the dynamic structure, described in“Dynamic Section” above. Typically, the code for these functions resides in the.init and .fini sections, mentioned in “Sections” on page 148 earlier.

Note – Although the atexit(3C) termination processing normally will bedone, it is not guaranteed to have executed upon process death. In particular,the process will not execute the termination processing if it calls _exit() or ifthe process dies because it received a signal that it neither caught nor ignored.

unsigned longelf_Hash(const unsigned char *name){

unsigned long h = 0, g;

while (*name){

h = (h << 4) + *name++;if (g = h & 0xf0000000)

h ^= g >> 24;h &= ~g;

}return h;

Page 240: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

226 Linker and Libraries Guide—November 1995

6

Page 241: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

227

Mapfile Option 7

IntroductionThe link-editor automatically and intelligently maps input sections fromrelocatable objects to segments within the output file object. The -M optionwith an associated mapfile allows you to change the default mappingprovided by the link-editor.

In particular, this mapfile option allows you to:

• Declare segments and specify values for segment attributes such as segmenttype, permissions, addresses, length, and alignment.

• Control mapping of input sections to segments by specifying the attributevalues necessary in a section to map to a specific segment (the attributes aresection name, section type, and permissions) and by specifying which objectfile(s) the input sections should be taken from, if necessary.

• Declare a global-absolute symbol that is assigned a value equal to the size ofa specified segment (by the link-editor) and that can be referenced fromobject files.

The mapfile option allows users of ifiles (an option previously available told(1) that used link-editor command language directives) to convert tomapfiles . All other facilities previously available for ifiles, other than thosementioned above, are not available with the mapfile option.

Page 242: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

228 Linker and Libraries Guide—November 1995

7

Note – When using the mapfile option, be aware that you can easily createa.out files that do not execute. The link-editor knows how to produce acorrect a.out without the use of the mapfile option. The mapfile option isintended for system programming use, not application programming use.

Using the Mapfile OptionTo use the mapfile option, you must:

• Enter the mapfile directives into a file, for example mapfile

• Supply the following option on the ld(1) command line:

-M mapfile

If the mapfile is not in your current directory, include the full path name; nodefault search path exists.

Mapfile Structure and SyntaxYou can enter four basic types of directives into a mapfile :

• Segment declarations.

• Mapping directives.

• Size-symbol declarations.

• File control directives.

Each directive can span more than one line and can have any amount of whitespace (including new-lines) as long as it is followed by a semicolon. You canenter zero or more directives in a mapfile . (Entering zero directives causes thelink-editor to ignore the mapfile and use its own defaults.)

Typically, segment declarations are followed by mapping directives, that is,you declare a segment and then define the criteria by which a section becomespart of that segment. If you enter a mapping directive or size-symboldeclaration without first declaring the segment to which you are mapping(except for built-in segments, explained later), the segment is given defaultattributes as explained below. Such segment is then an “implicitly declaredsegment.”

Page 243: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Mapfile Option 229

7

Size-symbol declarations, and file control directives can appear anywhere in amapfile .

The following sections describe each directive type. For all syntax discussions,the following notations apply:

• All entries in constant width , all colons, semicolons, equal signs, and at(@) signs are typed in literally.

• All entries in italics are substitutable.

• { ... }* means “zero or more.”

• { ... }+ means “one or more.”

• [ ... ] means “optional.”

• section_names and segment_names follow the same rules as C identifierswhere a period (.) is treated as a letter (for example, .bss is a legal name).

• section_names, segment_names, file_names, and symbol_names are casesensitive; everything else is not case sensitive.

• Spaces (or new-lines) may appear anywhere except before a number or in themiddle of a name or value.

• Comments beginning with # and ending at a new-line may appearanywhere that a space may appear.

Segment Declarations

A segment declaration creates a new segment in the a.out or changes theattribute values of an existing segment. (An existing segment is one that youpreviously defined or one of the three built-in segments described below.)

A segment declaration has the following syntax:

segment_name = {segment_attribute_value}*;

Page 244: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

230 Linker and Libraries Guide—November 1995

7

For each segment_name, you can specify any number of segment_attribute_valuesin any order, each separated by a space. (Only one attribute value is allowedfor each segment attribute.) The segment attributes and their valid values areas follows:

There are three built-in segments with the following default attribute values:

• text (LOAD, ?RX, no virtual_address, physical_address, or length specified,alignment values set to defaults per CPU type)

• data (LOAD, ?RWX, no virtual_address, physical_address, or length specified,alignment values set to defaults per CPU type)

• note (NOTE)

The link-editor behaves as if these segments are declared before your mapfileis read in. See “Mapfile Option Defaults” on page 239 for more information.

Note the following when entering segment declarations:

• A number can be hexadecimal, decimal, or octal, following the same rules asin the C language.

• No space is allowed between the V, P, L, R, or A and the number.

• The segment_type value can be either LOAD or NOTE.

• The segment_type value defaults to LOAD.

Table 7-1 Mapfile Segment Attributes

Attribute Value

segment_type LOADNOTE

segment_flags ? [R] [W] [X] [O]

virtual_address Vnumber

physical_address Pnumber

length Lnumber

rounding Rnumber

alignment Anumber

Page 245: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Mapfile Option 231

7

• The segment_flags values are R for readable, W for writable, X for executable,and O for order. No spaces are allowed between the question mark (?) andthe individual flags that make up the segment_flags value.

• The segment_flags value for a LOAD segment defaults to RWX.

• NOTE segments cannot be assigned any segment attribute value other than asegment_type.

• Implicitly declared segments default to segment_type value LOAD,segment_flags value RWX, a default virtual_address, physical_address, andalignment value, and have no length limit.

Note – the link-editor calculates the addresses and length of the currentsegment based on the previous segment’s attribute values. Also, even thoughimplicitly declared segments default to “no length limit,” machine memorylimitations still apply.

• LOAD segments can have an explicitly specified virtual_address value and/orphysical_address value, as well as a maximum segment length value.

• If a segment has a segment_flags value of ? with nothing following, the valuedefaults to not readable, not writable, and not executable.

• The alignment value is used in calculating the virtual address of thebeginning of the segment. This alignment only affects the segment for whichit is specified; other segments still have the default alignment unless theiralignments are also changed.

• If any of the virtual_address, physical_address, or length attribute values arenot set, the link-editor calculates these values as it builds the a.out .

• If an alignment value is not specified for a segment, it is set to the built-indefault. (The default differs from one CPU to another and may even differbetween kernel versions. You should check the appropriate documentationfor these numbers).

• If both a virtual_address and an alignment value are specified for a segment,the virtual_address value takes priority.

• If a virtual_address value is specified for a segment, the alignment field in theprogram header contains the default alignment value.

Page 246: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

232 Linker and Libraries Guide—November 1995

7

• If the rounding value is set for a segment, that segments virtual address willbe rounded to the next address that conforms to the value given. This valueonly effects the segments that it is specified for. If no value is given norounding is performed.

The ?N flag lets you control whether the ELF header, and any programheaders, will be included as part of the first loadable segment. By default, theELF header and program headers are included with the first segment, as theinformation in these headers is used within the mapped image (commonly bythe runtime linker). The use of the ?N option causes the virtual addresscalculations for the image to start at the first section of the first segment.

The ?O flag lets you control the order of sections in the final relocatable object,executable file or shared object. This flag is intended for use in conjunctionwith the -xF option to the compiler(s). When a file is compiled with the -xFoption, each function in that file is placed in a separate section with the sameattributes as the .text section. These sections are now called.text%function_name.

For example, a file containing three functions main() , foo() and bar() ,when compiled with the -xF option, will yield an object file with text for thethree functions in sections called .text%main, .text%foo and .text%bar. Becausethe -xF option forces one function per section, the use of the ?O flag to controlthe order of sections in effect controls the order of functions.

Consider the following user-defined mapfile :

If the order of function definitions in the source file is main , foo and bar , thenthe final executable will contain functions in the order foo , bar and main .

text = LOAD ?RXO;text: .text%foo;text: .text%bar;text: .text%main;

Page 247: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Mapfile Option 233

7

For static functions with the same name the file names must also be used. The?O flag forces the ordering of sections as requested in the mapfile . Forexample, if a static function bar() exists in files a.o and b.o , and functionbar from file a.o is to be placed before function bar from file b.o , then themapfile entries should read:

Although the syntax allows for the entry:

this entry does not guarantee that function bar from file a.o will be placedbefore function bar from file b.o . The second format is not recommended asthe results are not reliable.

Note – If a virtual_address value is specified, the segment is placed at thatvirtual address. For the system kernel this creates a correct result. For files thatstart via exec(2) , this method creates an incorrect a.out file because thesegments do not have correct offsets relative to their page boundaries.

Mapping Directives

A mapping directive tells the link-editor how to map input sections to outputsegments. Basically, you name the segment that you are mapping to andindicate what the attributes of a section must be in order to map into thenamed segment. The set of section_attribute_values that a section must have tomap into a specific segment is called the “entrance criteria” for that segment.In order to be placed in a specified segment of the a.out , a section must meetthe entrance criteria for a segment exactly.

A mapping directive has the following syntax:

text: .text%bar: a.o;text: .text%bar: b.o;

text: .text%bar: a.o b.o;

segment_name : {section_attribute_value}* [: {file_name}+];

Page 248: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

234 Linker and Libraries Guide—November 1995

7

For a segment_name, you specify any number of section_attribute_values in anyorder, each separated by a space. (At most one section attribute value isallowed for each section attribute.) You can also specify that the section mustcome from a certain .o file(s) via the file_name substitutable. The sectionattributes and their valid values are as follows:

Note the following when entering mapping directives:

• You must choose at most one section_type from the section_types listed above.The section_types listed above are built-in types. For more information onsection_types, see “Sections” on page 148.

• The section_flags values are A for allocatable, W for writable, or X forexecutable. If an individual flag is preceded by an exclamation mark (! ), thelink-editor checks to make sure that the flag is not set. No spaces areallowed between the question mark, exclamation mark(s), and theindividual flags that make up the section_flags value.

• file_name may be any legal file name and can be of the formarchive_name(component_name), for example,/usr/lib/usr/libc.a(printf.o) . A file name may be of the form*filename (see next bullet item). Note that the link-editor does not checkthe syntax of file names.

• If a file_name is of the form *filename , the link-editor simulates abasename(1) on the file name from the command line and uses that tomatch against the specified filename . In other words, the filename fromthe mapfile only needs to match the last part of the file name from thecommand line. (See “Mapping Example” on page 236.)

Table 7-2 Section Attributes

Section Attribute Value

section_name: any valid section name

section_type: $PROGBITS$SYMTAB$STRTAB$REL$RELA$NOTE$NOBITS

section_flags: ? [[! ]A] [[! ]W] [[! ]X]

Page 249: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Mapfile Option 235

7

• If you use the -l option during a link-edit, and the library after the -loption is in the current directory, you must precede the library with ./ (orthe entire path name) in the mapfile in order to create a match.

• More than one directive line may appear for a particular output segment,for example, the following set of directives is legal:

Entering more than one mapping directive line for a segment is the only wayto specify multiple values of a section attribute.

• A section can match more than one entrance criteria. In this case, the firstsegment encountered in the mapfile with that entrance criteria is used, forexample, if a mapfile reads:

the $PROGBITS sections are mapped to segment S1.

Section-within-Segment Ordering

By using the following notation it is possible to specify the order that sectionswill be placed within a segment:

The sections that are named in the above form will be placed before anyunnamed sections, and in the order they are listed in the mapfile .

S1 : $PROGBITS;S1 : $NOBITS;

S1 : $PROGBITS;S2 : $PROGBITS;

segment_name | section_name1;segment_name | section_name2;segment_name | section_name3;

Page 250: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

236 Linker and Libraries Guide—November 1995

7

Size-Symbol Declarations

Size-symbol declarations let you define a new global-absolute symbol thatrepresents the size, in bytes, of the specified segment. This symbol can bereferenced in your object files. A size-symbol declaration has the followingsyntax:

symbol_name can be any legal C identifier, although the link-editor does notcheck the syntax of the symbol_name.

File Control Directives

File control directives allow users to specify which version definitions withinshared objects are to be made available during a link-edit. The file controldefinition has the following syntax:

version_name is a version definition name contained within the specifiedshared_object_name. For more information on version control see “Specifying aVersion Binding” on page 132.

Mapping ExampleFollowing is an example of a user-defined mapfile . The numbers on the leftare included in the example for tutorial purposes. Only the information to theright of the numbers actually appears in the mapfile .

segment_name @ symbol_name;

shared_object_name - version_name [ version_name ... ];

Page 251: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Mapfile Option 237

7

Code Example 7-1 User-Defined Mapfile

Four separate segments are manipulated in this example. The implicitlydeclared segment elephant (line 1) receives all of the .data sections from thefiles peanuts.o and popcorn.o . Note that *popcorn.o matches anypopcorn.o file that may be supplied to the link-edit; the file need not be in thecurrent directory. On the other hand, if /var/tmp/peanuts.o was suppliedto the link-edit, it will not match peanuts.o because it is not preceded by a * .

The implicitly declared segment monkey (line 2) receives all sections that areboth $PROGBITS and allocatable-executable (?AX), as well as all sections (notalready in the segment elephant ) with the name .data (line 3). The .datasections entering the monkey segment need not be $PROGBITS or allocatable-executable because the section_type and section_flags values are entered on aseparate line from the section_name value. (An “and” relationship existsbetween attributes on the same line as illustrated by $PROGBITS “and” ?AX online 2. An “or” relationship exists between attributes for the same segment thatspan more than one line as illustrated by $PROGBITS ?AX on line 2 “or” .dataon line 3.)

The monkey segment is implicitly declared in line 2 with segment_type valueLOAD, segment_flags value RWX, and no virtual_address, physical_address, length oralignment values specified (defaults are used). In line 4 the segment_type valueof monkey is set to LOAD (since the segment_type attribute value does notchange, no warning is issued), virtual_address value to 0x80000000 andmaximum length value to 0x4000.

Line 5 implicitly declares the donkey segment. The entrance criteria aredesigned to route all .data sections to this segment. Actually, no sections fallinto this segment because the entrance criteria for monkey in line 3 capture allof these sections. In line 6, the segment_flags value is set to ?RX and thealignment value is set to 0x1000 (since both of these attribute values changed, awarning is issued).

1. elephant : .data : peanuts.o *popcorn.o;2. monkey : $PROGBITS ?AX;3. monkey : .data;4. monkey = LOAD V0x80000000 L0x4000;5. donkey : .data;6. donkey = ?RX A0x1000;7. text = V0x80008000;

Page 252: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

238 Linker and Libraries Guide—November 1995

7

Line 7 sets the virtual_address value of the text segment to 0x80008000.

The example of a user-defined mapfile is designed to cause warnings forillustration purposes. If you want to change the order of the directives to avoidwarnings, use the following example:

The following mapfile example uses the segment within section ordering:

The text and data segments are manipulated in this example. Line 1 declaresthe text segment to have a virtual_address of 0xf0004000 and to not include theELF header or any program headers as part of this segments addresscalculations. Lines 2 and 3 turn on section-within-segment ordering andspecify that the .text and .rodata sections will be the first two sections in thissegment. The result is that the .text section will have a virtual address of0xf0004000, and the .rodata section will immediately follow that.

Any other $PROGBITS section that make up the text segment will follow the.rodata section. Line 5 declares the data segment and specifies that its virtualaddress must begin on a 0x1000 byte boundary. The first section thatconstitutes the data segment will also reside on a 0x1000 byte boundarywithin the file image.

1. elephant : .data : peanuts.o *popcorn.o;4. monkey = LOAD V0x80000000 L0x4000;2. monkey : $PROGBITS ?AX;3. monkey : .data;6. donkey = ?RX A0x1000;5. donkey : .data;7. text = V0x80008000;

1. text = LOAD ?RXN V0xf0004000;2. text | .text;3. text | .rodata;4. text : $PROGBITS ?A!W;5. data = LOAD ?RWX R0x1000;

Page 253: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Mapfile Option 239

7

Mapfile Option DefaultsThe link-editor defines three built-in segments (text , data , and note ) withdefault segment_attribute_values and corresponding default mapping directivesas described in “Segment Declarations” on page 229. Even though thelink-editor does not use an actual mapfile to provide the defaults, the modelof a default mapfile helps illustrate what happens when the link-editorencounters your mapfile .

The example below shows how a mapfile would appear for the link-editordefaults. The link-editor begins execution behaving as if the mapfile hasalready been read in. Then the link-editor reads your mapfile and eitheraugments or makes changes to the defaults.

As each segment declaration in your mapfile is read in, it is compared to theexisting list of segment declarations as follows:

1. If the segment does not already exist in the mapfile , but another with thesame segment-type value exists, the segment is added before all of theexisting segments of the same segment_type.

2. If none of the segments in the existing mapfile has the same segment_typevalue as the segment just read in, then the segment is added by segment_typevalue to maintain the following order:

INTERP

LOAD

DYNAMIC

NOTE

text = LOAD ?RX;text : ?A!W;data = LOAD ?RWX;data : ?AW;note = NOTE;note : $NOTE;

Page 254: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

240 Linker and Libraries Guide—November 1995

7

3. If the segment is of segment_type LOAD and you have defined avirtual_address value for this LOADable segment, the segment is placed beforeany LOADable segments without a defined virtual_address value or with ahigher virtual_address value, but after any segments with avirtual_address value that is lower.

As each mapping directive in a mapfile is read in, the directive is added afterany other mapping directives that you already specified for the same segmentbut before the default mapping directives for that segment.

Internal Map StructureOne of the most important data structures in the ELF-based link-editor is themap structure. A default map structure, corresponding to the model defaultmapfile mentioned above, is used by the link-editor when the command isexecuted. Then, if the mapfile option is used, the link-editor parses themapfile to augment and/or override certain values in the default mapstructure.

A typical (although somewhat simplified) map structure is illustratedin Figure6-1. The “Entrance Criteria” boxes correspond to the information inthe default mapping directives and the “Segment Attribute Descriptors” boxescorrespond to the information in the default segment declarations. The“Output Section Descriptors” boxes give the detailed attributes of the sectionsthat fall under each segment. The sections themselves are in circles.

Page 255: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Mapfile Option 241

7

Figure 7-1 Simple Map Structure

The link-editor performs the following steps when mapping sections tosegments:

1. When a section is read in, the link-editor checks the list of Entrance Criterialooking for a match. All specified criteria must be matched.

Entrancecriteria

$PROGBITS?A!W

$PROGBITS?AW

$NOGBITS?AW $NOTE

NO MATCH -appended toend of a.out

Segmentattributedescriptors

textLOAD?RX

dataLOAD?RWX

noteNOTE

Output sectiondescriptors

.data$PROGBITS

?AWX

.data1$PROBITS

?AWX

.data2$PROGBITS

?AWX

.bss$NOBITS

?AWX

.datafromfido.o

.data1fromfido.o

.data2fromfido.o

.bssfrom

rover.o

.data1from

rover.o

.data1from

sam.oSectionsplaced insegments

Page 256: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

242 Linker and Libraries Guide—November 1995

7

In Figure 6-1, for a section to fall into the text segment it must have asection_type value of $PROGBITS and have a section_flags value of ?A!W. Itneed not have the name .text since no name is specified in the EntranceCriteria. The section may be either X or !X (in the section_flags value) sincenothing was specified for the execute bit in the Entrance Criteria.

If no Entrance Criteria match is found, the section is placed at the end of thea.out file after all other segments. (No program header entry is created forthis information. See “Program Header” on page 189 for more information.)

2. When the section falls into a segment, the link-editor checks the list ofexisting Output Section Descriptors in that segment as follows:

If the section attribute values match those of an existing Output SectionDescriptor exactly, the section is placed at the end of the list of sectionsassociated with that Output Section Descriptor.

For instance, a section with a section_name value of .data1, a section_typevalue of $PROGBITS, and a section_flags value of ?AWX falls into the secondEntrance Criteria box in Figure 6-1, placing it in the data segment. Thesection matches the second Output Section Descriptor box exactly (.data1,$PROGBITS, ?AWX) and is added to the end of the list associated with thatbox. The .data1 sections from fido.o , rover.o , and sam.o illustrate thispoint.

If no matching Output Section Descriptor is found, but other Output SectionDescriptors of the same section_type exist, a new Output Section Descriptoris created with the same attribute values as the section and that section isassociated with the new Output Section Descriptor. The Output SectionDescriptor (and the section) are placed after the last Output SectionDescriptor of the same section_type. The .data2 section in Figure 6-1 wasplaced in this manner.

If no other Output Section Descriptors of the indicated section_type exist, anew Output Section Descriptor is created and the section is placed in thatsection.

Note – If the input section has a user-defined section_type value (that is,between SHT_LOUSER and SHT_HIUSER, as described in the “Sections” onpage 148) it is treated as a $PROGBITS section. Note that no method exists for

Page 257: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Mapfile Option 243

7

naming this section_type value in the mapfile , but these sections can beredirected using the other attribute value specifications (section_flags,section_name) in the entrance criteria.

3. If a segment contains no sections after all of the command line object filesand libraries are read in, no program header entry is produced for thatsegment.

Note – Input sections of type $SYMTAB, $STRTAB, $REL, and $RELA are usedinternally by the link-editor. Directives that refer to these section_types can onlymap output sections produced by the link-editor to segments.

Error Messages

Warnings

Errors within this category do not stop execution of the link-editor nor do theyprevent the link-editor from producing a viable a.out . The followingconditions produce warnings:

• A physical_address or a virtual_address value or a length value appears for anysegment other than a LOAD segment. (The directive is ignored.)

• A second declaration line exists for the same segment that changes anattribute value(s). (The second declaration overrides the original.)

• An attribute value(s) (segment_type and/or segment_flags for text and data ;segment_type for note ) was changed for one of the built-in segments

• An attribute value(s) (segment_type, segment_flags, length and/or alignment)was changed for a segment created by an implicit declaration. If only the ?Oflag has been added then the change of attribute value warning will not begenerated.

• An entrance criteria was not met. If the ?O flag has been turned on and ifnone of the input sections met an entrance criteria, the warning is generated.

Page 258: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

244 Linker and Libraries Guide—November 1995

7

Fatal Errors

Errors within this category stop execution of the link-editor at the point thefatal error occurred. The following conditions produce fatal errors:

• A mapfile cannot be opened or read.

• A syntax error is found in the mapfile .

Note – The link-editor does not return an error if a file_name, section_name,segment_name or symbol_name does not conform to the rules under the “MapfileStructure and Syntax” section unless this condition produces a syntax error.For instance, if a name begins with a special character and this name is at thebeginning of a directive line, the link-editor returns an error. If the name is asection_name (appearing within the directive), the link-editor does not return anerror.

• More than one segment_type, segment_flags, virtual_address, physical_address,length, or alignment value appears on a single declaration line.

• You attempt to manipulate either the interp segment or dynamic segmentin a mapfile .

Note – The interp and dynamic segments are special built-in segments thatyou cannot change in any way.

• A segment grows larger than the size specified by a your length attributevalue.

• A user-defined virtual_address value causes a segment to overlap theprevious segment.

• More than one section_name, section_type, or section_flags value appears on asingle directive line.

• A flag and its complement (for example, A and !A ) appear on a singledirective line.

Page 259: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

245

Link-Editor Quick Reference A

The following sections provide a simple overview, or cheat sheet, of the mostcommonly used link-editor scenarios (see “Link-Editing” on page 2 for anintroduction to the kinds of output modules generated by the link-editor).

The examples provided show the link-editor options as supplied to thecompiler driver cc(1) , this being the most common mechanism of invokingthe link-editor (see “Using a Compiler Driver” on page 9).

The link-editor places no meaning on the name of any input file. Each file isopened and inspected to determine the type of processing it requires (see“Input File Processing” on page 11).

Shared objects that follow a naming convention of lib x.so , and archivelibraries that follow a naming convention of lib x.a , can be input using the -loption (see “Library Naming Conventions” on page 14). This providesadditional flexibility in allowing search paths to be specified using the -Loption (see “Directories Searched by the Link-Editor” on page 16).

The link-editor basically operates in one of two modes, static or dynamic.

Static ModeThis mode is selected when the -dn option is used, and allows for the creationof relocatable objects and static executables. Under this mode only relocatableobjects and archive libraries are acceptable forms of input. Use of the -l optionwill result in a search for archive libraries.

Page 260: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

246 Linker and Libraries Guide—November 1995

A

Building a Relocatable Object• Use the -dn and -r options:

Building a Static Executable

The use of static executables is limited. Static executables usually containplatform specific implementation details which restricts the ability of theexecutable to be run on an alternative platform. Also, many implementationsof Solaris libraries depend on dynamic linking capabilities such asdlopen(3x) and dlsym(3x ). (see “Loading Additional Objects” on page 67).These capabilities are not available to static executables.

• Use the -dn option without the - r option:

Note – The -a option is available to indicate the creation of a static executable,however, the use of -dn without a -r implies -a .

Dynamic ModeThis is the default mode of operation for the link-editor. It can be enforced byspecifying the -dy option, but is implied when not using the -dn option.

Under this mode, relocatable objects, shared objects and archive libraries areacceptable forms of input. Use of the -l option will result in a directory search,where each directory is searched for a shared object, and if none is found thesame directory is then searched for an archive library. A search for archivelibraries only, can be enforced by using the -B static option (see “Linkingwith a Mix of Shared Objects and Archives” on page 15).

Building a Shared Object• Use the -G option (-dy is optional as it is implied by default).

$ cc -dn -r -o temp.o file1.o file2.o file3.o .....

$ cc -dn -o prog file1.o file2.o file3.o .....

Page 261: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Link-Editor Quick Reference 247

A

• Input relocatable objects should be built from position-independent code.Use the -z text option to enforce this requirement (see “Position-Independent Code” on page 100).

• Establish the shared objects public interface by defining the global symbolsthat should be visible from this shared object, and reducing any other globalsymbols to local scope. This definition is provided by the -M option togetherwith an associated mapfile , and is covered in more detail inAppendix B,“Versioning Quick Reference”.

• Use a versioned name for the shared object to allow for future upgrades (see“Coordination of Versioned Filenames” on page 136).

• If the shared object being generated has dependencies on any other sharedobjects, and these dependencies do not reside in /usr/lib , record theirpathname in the output file using the -R option (see “Shared Objects withDependencies” on page 89).

The following example combines the above points:

• If the shared object being generated will be used as input to anotherlink-edit, record within it the shared object’s runtime name using the -hoption (see “Recording a Shared Object Name” on page 86).

• Make the shared object available to the compilation environment by creatinga file system link to a non-versioned shared object name (see “Coordinationof Versioned Filenames” on page 136).

The following example combines the above points:

$ cc -c -o foo.o -Kpic foo.c$ cc -M mapfile -G -o libfoo.so.1 -z text -R /home/lib \foo.o -L. -lbar

$ cc -M mapfile -G -o libfoo.so.1 -z text -R /home/lib \-h libfoo.so.1 foo.o$ ln -s libfoo.so.1 libfoo.so

Page 262: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

248 Linker and Libraries Guide—November 1995

A

• Consider the performance implications of the shared object; maximizeshareability (see page 102) and minimize paging activity (see page 105),reduce relocation overhead, especially by minimizing symbolic relocations(see “Profiling Shared Objects” on page 111), and allow access to data viafunctional interfaces (see “Copy Relocations” on page 107).

Building a Dynamic Executable• Don’t use the -G , or -dn options.

• If the dynamic executable being generated has dependencies on any othershared objects, and these dependencies do not reside in /usr/lib , recordtheir pathname in the output file using the -R option (see “DirectoriesSearched by the Runtime Linker” on page 18).

The following example combines the above points:

$ cc -o prog -R /home/lib -L. -lfoo file1.o file2.o file3.o .....

Page 263: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

249

Versioning Quick Reference B

ELF objects make available global symbols to which other objects can bind.Some of these global symbols can be identified as providing the object’s publicinterface. Other symbols are part of the objects internal implementation and arenot intended for external use. An objects interface can evolve from onesoftware release to another, and thus the ability to identify this evolution isdesirable.

In addition, identifying the internal implementation changes of an object fromone software release to another might be desirable.

Both interface and implementation identifications can be recorded within anobject by establishing internal version definitions (see “Overview” on page 115for a more complete introduction to the concept of internal versioning).

Shared objects are prime candidates for internal versioning as this techniquedefines their evolution, provides for interface validation during runtimeprocessing (see “Binding to a Version Definition” on page 126), and providesfor the selective binding of applications (see “Specifying a Version Binding” onpage 132). Shared objects will be used as the examples throughout this chapter.

The following sections provide a simple overview, or cheat sheet, of the internalversioning mechanism provided by the link-editors as applied to sharedobjects. The examples recommend conventions and mechanisms for versioningshared objects, from their initial construction through several common updatescenarios.

Page 264: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

250 Linker and Libraries Guide—November 1995

B

Naming ConventionsA shared object follows a naming convention that includes a major number filesuffix (see “Naming Conventions” on page 84). Within this shared object, oneor more version definitions can be created. Each version definition correspondsto one of the following categories:

• It defines an industry standard interface (for example, the System VApplication Binary Interface).

• It defines a vendor specific public interface.

• It defines a vendor specific private interface.

• It defines a vendor specific change to the internal implementation of theobject.

The following version definition naming conventions help indicate which ofthese categories the definition represents.

The first three of these categories indicate interface definitions. Thesedefinitions consist of an association of the global symbol names that comprisethe interface, with a version definition name (see “Creating a VersionDefinition” on page 118). Interface changes within a shared object are oftenreferred to as minor revisions. Therefore, version definitions of this type, aresuffixed with a minor version number which is based off of the filenames majorversion number suffix.

The last category indicates a change having occurred within the object. Thisdefinition consists of a version definition acting as a label and has no symbolnames associated with it. This definition is referred to as being a weak versiondefinition (see “Creating a Weak Version Definition” on page 122).Implementation changes within a shared object are often referred to as microrevisions. Therefore, version definitions of this type are suffixed with a microversion number based off of the previous minor number to which the internalchanges have been applied.

Any industry standard interfaces should use a version definition name thatreflects the standard. Any vendor interfaces should use a version definitionname unique to that vendor (the company’s stock symbol is often appropriate).

Private version definitions indicate symbols that have restricted oruncommitted use, and should have the word private clearly visible.

Page 265: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning Quick Reference 251

B

All version definitions result in the creation of associated version symbolnames. Therefore, the use of unique names and the minor/micro suffixconvention reduce the chance of symbol collision within the object being built.

The following version definition examples show the use of these namingconventions:

• SVABI.1 - defines the System V Application Binary Interface standardsinterface.

• SUNW_1.1 - defines a SunSoft public interface.

• SUNWprivate_1.1 - defines a SunSoft private interface.

• SUNW_1.1.1 - defines a SunSoft internal implementation change.

Defining a Shared Object’s InterfaceWhen establishing a shared object’s interface the first task is to determinewhich global symbols provided by the shared object can be associated to one ofthe three interface version definition categories:

• Industry standard interface symbols conventionally are defined in publiclyavailable header files and associated manual pages supplied by the vendor,and are also documented in recognized standards literature.

• Vendor public interface symbols conventionally are defined in publiclyavailable header files and associated manual pages supplied by the vendor.

• Vendor private interface symbols can have little or no public definition.

By defining these interfaces, a vendor is indicating the commitment level ofeach interface of the shared object. Industry standard and vendor publicinterfaces remain stable from release to release. You are free to bind to theseinterfaces safe in the knowledge that your application will continue to functioncorrectly from release to release.

Industry standard interfaces might be available on systems provided by othervendors, and thus you can achieve a higher level of binary compatibility byrestricting your applications to use these interfaces.

Vendor public interfaces might not be available on systems provided by othervendors, however these interfaces will remain stable during the evolution ofthe system on which they are provided.

Page 266: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

252 Linker and Libraries Guide—November 1995

B

Vendor private interfaces are very unstable, and can change, of even bedeleted, from release to release. These interfaces provide for uncommitted orexperimental functionality, or are intended to provide access for vendorspecific applications only. If you who wish to achieve any level of binarycompatibility you should avoid using these interfaces.

Any global symbols that do not fall into one of the above categories should bereduced to local scope so that they are no longer visible for binding (see“Reducing Symbol Scope” on page 38).

Versioning a Shared ObjectHaving determined a shared object’s available interfaces, the associatedversion definitions are created using a mapfile and the link-editors -M option(see “Defining Additional Symbols” on page 32 for an introduction of thismapfile syntax).

The following example defines a vendor public interface in the shared objectlibfoo.so.1 :

Here the global symbols foo1 and foo2 are assigned to the shared objectspublic interface SUNW_1.1. Any other global symbols supplied from the inputfiles are reduced to local by the auto-reduction directive “*” (see “ReducingSymbol Scope” on page 38).

Note – Each version definition mapfile entry should be accompanied by acomment reflecting the release or date of the update. This information helpscoordinate multiple updates of a shared object, possibly by differentdevelopers, into one version definition suitable for delivery of the sharedobject as part of a software release.

$ cat mapfileSUNW_1.1 { # Release X. global: foo2; foo1; local: *;};$ cc -G -o libfoo.so.1 -h libfoo.so.1 -z text -M mapfile foo.c

Page 267: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning Quick Reference 253

B

Versioning an Existing (Non-versioned) Shared Object

Versioning an existing, non-versioned shared object requires extra care, as theshared object delivered in a previous software release has made available all itsglobal symbols for others to bind with. Although it can be possible todetermine the shared objects intended interfaces, it can be the case that othershave discovered and bound to other symbols. Therefore, the removal of anysymbols might result in an applications failure on delivery of the newversioned shared object.

The internal versioning of an existing, non-versioned shared object can beachieved if the interfaces can be determined, and applied, without breakingany existing applications. The runtime linker’s debugging capabilities can beuseful to help verify the binding requirements of various applications (see“Debugging Aids” on page 77). However, this determination of existingbinding requirements assumes that all users of the shared object are known.

If the binding requirements of an existing, non-versioned shared object can notbe determined then it is necessary to create a new shared object file using anew versioned name (see “Coordination of Versioned Filenames” on page 136).In addition to this new shared object, the original shared object must also bedelivered so as to satisfy the dependencies of any existing applications.

If the implementation of the original shared object is to be frozen thenmaintaining and delivering the shared object binary might be sufficient. Ifhowever, the original shared object might require updating - for example,through patches, or because its implementation must evolve to remaincompatible with new platforms - then an alternative source tree from which togenerate the shared object can be more applicable.

Updating a Versioned Shared ObjectThe only changes that can be made to a shared object that can be absorbed byinternal versioning are compatible changes (see “Interface Compatibility” onpage 116). Any incompatible changes require producing a new shared objectwith a new external versioned name (see “Coordination of VersionedFilenames” on page 136).

Compatible updates that can be accommodated by internal versioning fall intothree basic categories:

• adding new symbols.

Page 268: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

254 Linker and Libraries Guide—November 1995

B

• creating new interfaces from existing symbols.

• internal implementation changes.

The first two categories are achieved by associating an interface versiondefinition with the appropriate symbols. The latter is achieved by creating aweak version definition that has no associated symbols.

Adding New Symbols

Any compatible new release of a shared object that contains new globalsymbols should assign these symbols to a new version definition. This newversion definition should inherit the previous version definition.

The following mapfile example assigns the new symbol foo3 to the newinterface version definition SUNW_1.2. This new interface inherits the originalinterface SUNW_1.1:

The inheritance of version definitions reduces the amount of versioninformation that must be recorded in any user of the shared object.

$ cat mapfileSUNW_1.2 { # Release X+1. global: foo3;} SUNW_1.1;

SUNW_1.1 { # Release X. global: foo2; foo1; local: *;};

Page 269: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning Quick Reference 255

B

Internal Implementation Changes

Any compatible new release of the shared object that consists of an update tothe implementation of the object - for example, a bug fix or performanceimprovement - should be accompanied by a weak version definition. This newversion definition should inherit the latest version definition present at thetime the update occurred.

The following mapfile example generates a weak version definitionSUNW_1.1.1 . This new interface indicates that the internal changes were madeto the implementation offered by the previous interface SUNW_1.1:

New Symbols and Internal Implementation Changes

If both internal changes and the addition of a new interface has occurredduring the same release, both a weak version and a interface version definitionshould be created. The following example shows the addition of a version

$ cat mapfileSUNW_1.1.1 { } SUNW_1.1; # Release X+1.

SUNW_1.1 { # Release X. global: foo2; foo1; local: *;};

Page 270: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

256 Linker and Libraries Guide—November 1995

B

definition SUNW_1.2 and an interface change SUNW_1.1.1 which are addedduring the same release cycle. Both interfaces inherit the original interfaceSUNW_1.1:

Note – The comments for the SUNW_1.1 and SUNW_1.1.1 version definitionsindicate that they have both been applied to the same release.

Migrating Symbols to a Standard Interface

Occasionally, symbols offered by a vendors interface become absorbed into anew industry standard. When creating a new standard interface it is importantto maintain the original interface definitions provided by the shared object. Toaccomplish this it is necessary to create intermediate version definitions onwhich the new standard, and original interface definitions, can be built.

% cat mapfileSUNW_1.2 { # Release X+1. global: foo3;} SUNW_1.1;

SUNW_1.1.1 { } SUNW_1.1; # Release X+1.

SUNW_1.1 { # Release X. global: foo2; foo1; local: *;};

Page 271: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning Quick Reference 257

B

The following mapfile example shows the addition of a new industrystandard interface STAND.1. This interface contains the new symbol foo4 andthe existing symbols foo3 and foo1 which were originally offered through theinterfaces SUNW_1.2 and SUNW_1.1 respectively:

Here the symbols foo3 and foo1 are pulled into their own intermediateinterface definitions which are used to build the original and new interfacedefinitions.

$ cat mapfileSTAND.1 { # Release X+2. global: foo4;} STAND.0.1 STAND.0.2;

SUNW_1.2 { # Release X+1. global: SUNW_1.2;} STAND.0.1 SUNW_1.1;

SUNW_1.1.1 { } SUNW_1.1; # Release X+1.

SUNW_1.1 { # Release X. global: foo2; local: *;} STAND.0.2; # Subversion - providing forSTAND.0.1 { # SUNW_1.2 and STAND.1 interfaces. global: foo3;}; # Subversion - providing forSTAND.0.2 { # SUNW_1.1 and STAND.1 interfaces. global: foo1;};

Page 272: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

258 Linker and Libraries Guide—November 1995

B

Note – The new definition of the SUNW_1.2 interface has referenced its ownversion definition symbol. Without this reference the SUNW_1.2 interfacewould have contained no immediate symbol references and hence would becategorized as a weak version definition.

When migrating symbol definitions to a standards interface the requirement isthat any original interface definitions continue to represent the same symbollist. This requirement can be validated using pvs(1) . The following exampleshows the symbol list of the SUNW_1.2 interface as it existed in the softwarerelease X+1:

Although the introduction of the new standards interface in software releaseX+2 has changed the interface version definitions available, the list of symbolsprovided by each of the original interfaces remains constant. The followingexample shows that interface SUNW_1.2 still provides symbols foo1 , foo2and foo3 :

It is possible that an application might only reference one of the newsubversions, in which case any attempt to run the application on a previousrelease will result in a runtime versioning error (see “Binding to a VersionDefinition” on page 126).

$ pvs -ds -N SUNW_1.2 libfoo.so.1 SUNW_1.2: foo3; SUNW_1.1: foo2; foo1;

$ pvs -ds -N SUNW_1.2 libfoo.so.1 SUNW_1.2: STAND.0.1: foo3; SUNW_1.1: foo2; STAND.0.2: foo1;

Page 273: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Versioning Quick Reference 259

B

In this case an applications version binding can be promoted by directlyreferencing an existing version name (see “Binding to a Weak VersionDefinition” on page 130).

For example, if an application only references the symbol foo1 from theshared object libfoo.so.1 , then its version reference will be to STAND.0.2 .To allow this application to be run on previous releases, the version bindingcan be promoted to SUNW_1.1 using the link-editor’s -u option:

In practice it is rarely necessary to promote a version binding in this manner,as the introduction of new standards binary interfaces is rare, and mostapplications reference many symbols from an interface family.

% cat prog.cextern void foo1();

main(){ foo1();}% cc -o prog prog.c -L. -R. -lfoo% pvs -r prog libfoo.so.1 (STAND.0.2);

% cc -u SUNW_1.1 -o prog prog.c -L. -R. -lfoo% pvs -r prog libfoo.so.1 (SUNW_1.1);

Page 274: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

260 Linker and Libraries Guide—November 1995

B

Page 275: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

261

Index

Symbols/usr/lib , 18, 55, 56, 65, 67/usr/lib/ld.so.1 , 53

AABI (see Application Binary Interface and

System V Application BinaryInterface)

Application Binary Interface, 4, 5, 94, 115building a conforming

application, 15ar(1), 12archives, 14

inclusion of shared objects in, 88link-editor processing, 12multiple passes through, 12naming conventions, 14

as(1), 2

Bbase address, 193binding, 1

dependency ordering, 90lazy, 60to shared object dependencies, 86,

126

to version definitions, 126to weak version definitions, 130

Ccc(1), 1, 2, 9COMMON, 21, 34, 36, 150, 166compilation environment, 1, 4, 14, 84

Ddata representation, 141debugging aids

link-editing, 48runtime linking, 77

dependency ordering, 90dlclose(3X), 66dlerror(3X), 66dlfcn.h , 66dlopen(3X), 54, 66, 67 to 73, 131

effects of ordering, 72modes

RTLD_GLOBAL, 68, 73RTLD_LAZY, 69RTLD_NOW, 69

of a dynamic executable, 68, 73shared object naming conventions, 85

dlsym(3X), 54, 66, 73 to 76, 132

Page 276: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

262 Linker and Libraries Guide—November 1995

special handle (see RTLD_NEXT)dump(1), 5, 55, 58, 99, 101dynamic executables, 2, 3dynamic information tags

NEEDED, 55, 86RPATH, 56SONAME, 87TEXTREL, 101

dynamic linking, 4implementation, 167 to 176, 199

EELF, 2, 7, 97

(see also object files), 139elf(3E), 5environment variables

LD_BIND_NOT, 80LD_BIND_NOW, 60, 80, 206LD_DEBUG, 77LD_DEBUG_OUTPUT, 78LD_LIBRARY_PATH, 17, 56, 65, 67, 90LD_OPTIONS, 10, 49LD_PRELOAD, 62, 65LD_PROFILE, 112LD_PROFILE_OUTPUT, 112LD_RUN_PATH, 19SGS_SUPPORT, 43

error messageslink-editor

illegal argument to option, 10illegal option, 10incompatible options, 11multiple instances of an

option, 10multiply defined symbols, 27relocations against non-writable

sections, 101shared object name conflicts, 88soname conflicts, 89symbol not assigned to

version, 40symbol warnings, 25, 26undefined symbols, 28

undefined symbols from animplicit reference, 29

version unavailable, 134runtime linker

copy relocation sizedifferences, 110

relocation errors, 61, 129unable to find shared object, 57,

68unable to find version

definition, 128unable to locate symbol, 75

exec(2), 7, 53, 140executable and linking format (see ELF)

Ff77(1), 9filters

auxiliary, 91, 95standard, 91, 92

Ggenerating a shared object, 30generating an executable, 28generating the output file image, 42global offset table, 42, 58, 101, 175, 213 to

215global symbols, 21, 116, 163 to 165

Iinitialization and termination, 9, 19, 64input file processing, 11interface

private, 116public, 116, 249

interposition, 23, 24, 39, 59, 63, 76, 117interpreter (see also runtime linker)

Llazy binding, 60ld(1), 1, 2

Page 277: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Index 263

ld.so.1 (see also runtime linker), 1, 53LD_BIND_NOT, 80LD_BIND_NOW, 60, 80, 206LD_DEBUG, 77LD_DEBUG_OUTPUT, 78LD_LIBRARY_PATH, 17, 56, 65, 67, 90LD_OPTIONS, 10, 49LD_PRELOAD, 62, 65LD_PROFILE, 112LD_PROFILE_OUTPUT, 112LD_RUN_PATH, 19ldd(1), 5, 55, 57, 59, 61, 128, 129libld.so.1 , 66libraries

archives, 14naming conventions, 14shared, 167, 176, 199

link-editing, 2, 162 to 176, 199adding additional libraries, 14archive processing, 12binding to a version definition, 126,

132dynamic, 167 to 176, 199input file processing, 11library input processing, 11library linking options, 11mixing shared objects and

archives, 15multiply defined symbols, 164 to 165position of files on command line, 16search paths, 16, 17shared object processing, 13

link-editor, 1, 7debugging aids, 48error messages (see error messages)invoking directly, 8invoking using compiler driver, 9overview, 7sections, 7segments, 7specifying options, 10

link-editor options-a , 246

-B dynamic , 15-B reduce , 41-B static , 15, 246-D , 49-d , 245, 246-e , 43-F , 92-f , 92-G , 83-h , 86, 138, 247-i , 18-L , 17, 245-l , 11, 14, 56, 84, 136, 245-M, 8, 32, 33, 116, 118, 132, 227, 247,

252-m, 14, 24-R , 19, 90, 247, 248-r , 246-S , 43-s , 42-t , 25, 26-u , 32, 131-Y , 17-z defs , 30-z muldefs , 27-z nodefs , 28, 61-z noversion , 119, 128-z text , 101, 247

link-editor outputdynamic executables, 2relocatable objects, 2shared objects, 2static executables, 2

link-editor support interfaceld_atexit() , 44ld_file() , 45ld_section() , 45ld_start() , 44

local symbols, 21, 163 to 165lorder(1), 13, 50

Mmapfiles, 227 to 244

defaults, 239

Page 278: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

264 Linker and Libraries Guide—November 1995

error messages, 243example, 236map structure, 240mapping directives, 233segment declarations, 229size-symbol declarations, 236structure, 228syntax, 228usage, 228

mmap(2), 53multiply defined symbols, 42, 163 to 165

Nnaming conventions

archives, 14libraries, 14shared objects, 14, 84

NEEDED, 55, 86nm(1), 5, 98

Oobject files, 2

base address, 193data representation, 141global offset table (see global offset

table)note section, 187 to 188preloading at runtime, 62procedure linkage table (see

procedure linkage table)program header, 189 to 192program interpretor, 204program loading, 195relocation, 167 to 176, 213section alignment, 151section attributes, 155 to 160section header, 148 to 160section names, 160section types, 152 to 160segment contents, 194 to 195segment permissions, 193 to 194segment types, 190 to 193string table, 161 to 162

symbol table, 162 to 167

Ppaging, 195 to 199performance

allocating buffers dynamically, 105collapsing multiple definitions, 104improving locality of references, 106,

111maximizing shareability, 102minimizing data segment, 103position-independent code (see

position-dependent code)relocations, 106, 111the underlying system, 100using automatic variables, 104

position-independent code, 100, 203 to213

preloading objects (see LD_PRELOADalso), 62

procedure linkage table, 43, 60, 101, 175,215, 218

profil(2), 112program interpreter, 53, 204 to 205

(see also runtime linker)pvs(1), 5, 119, 122, 125, 127

Rrelocatable objects, 2relocation, 57 to 62, 106 to 111, 167 to 176

copy, 107data references, 60function references, 60non-symbolic, 58, 106runtime linker

symbol lookup, 59, 60symbolic, 58, 106

RPATH (see also runpath), 56RTLD_GLOBAL, 68, 73RTLD_LAZY, 69RTLD_NEXT (see also dependency

ordering), 73

Page 279: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Index 265

RTLD_NOW, 69runpath, 18, 56, 65, 67, 80, 90runtime environment, 4, 14, 84runtime linker, 1, 3, 53, 205

initialization and terminationroutines, 64

lazy binding, 60loading additional objects, 62programming interface (see also

dlopen(3X) family ofroutines), 65

relocation processing, 57search paths, 18, 55security, 64shared object processing, 54version definition verification, 128

runtime linking, 3

SSCD (see SPARC Compliance Definition)search paths

link-editing, 16runtime linker, 18, 55

section types.bss, 7, 104, 107.data, 7, 103.dynamic, 42, 53, 55.dynstr, 42.dynsym, 42.fini, 19, 64.got, 42, 58.init, 19, 64.interp, 53.plt, 43, 60, 112.rodata, 103.strtab, 7, 42.symtab, 7, 42.text, 7

sections, 7, 97(see also section types)

security, 64segments, 7, 97

data, 98, 100

text, 98, 100SGS_SUPPORT, 43shared libraries (see shared objects)shared objects, 2, 4, 54

as filters (see filters)building (see also performance), 83dependency ordering, 90explicit definition, 29implementation, 167 to 176, 199implicit definition, 29link-editor processing, 13naming conventions, 14, 84recording a runtime name, 86with dependencies, 89

size(1), 97SONAME, 87SPARC Compliance Definition, 5static executables, 2strings(1), 104strip(1), 42symbol reserved names, 42

_DYNAMIC, 42_edata , 42_end , 42_etext , 42_fini , 19_GLOBAL_OFFSET_TABLE_, 42, 215_init , 19_PROCEDURE_LINKAGE_TABLE_, 43_start , 43main , 43

symbol resolution, 21, 42complex, 25fatal, 26interposition (see interposition)multiple definitions, 13simple, 22

symbolsabsolute, 34, 149, 166archive extraction, 12auto-reduction, 34, 40, 118, 252COMMON, 21, 34, 36, 150, 166defined, 21definition, 12, 27

Page 280: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

266 Linker and Libraries Guide—November 1995

existance test, 30global, 21, 23, 116, 163 to 165local, 21, 163 to 165private interface, 116public interface, 116reference, 12, 27runtime lookup, 69 to 77

deferred, 60scope, 69 to 73tentative, 12, 21, 31, 34, 36, 150

ordering in the output file, 31realignment, 36

undefined, 12, 21, 27, 28, 30version definitions, 130weak, 12, 23, 30, 164

System V Application BinaryInterface, 250

Ttentative symbols, 12, 21, 34, 36TEXTREL, 101tsort(1), 13, 50

Uundefined symbols, 27

Vversioning, 115

base version definition, 119binding to a definition, 126, 132defining a public interface, 40, 118definitions, 116, 117, 126external filename, 117, 253generating definitions within an

image, 33, 40, 117internal definitions, 117normalization, 127overview, 115runtime verification, 128, 131sections, 160symbol definitions, 130

virtual addressing, 195

Wweak symbols, 23, 163 to 165

undefined, 30

Page 281: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Index 267

Page 282: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is

Copyright 1995 Sun Microsystems Inc., 2550 Garcia Avenue, Mountain View, Californie 94043-1100 U.S.A.

Tous droits réservés. Ce produit ou document est protégé par un copyright et distribué avec des licences qui en restreignentl’utilisation, la copie, et la décompliation. Aucune partie de ce produit ou de sa documentation associée ne peuvent Êtrereproduits sous aucune forme, par quelque moyen que ce soit sans l’autorisation préalable et écrite de Sun et de ses bailleursde licence, s’il en a.

Des parties de ce produit pourront etre derivees du système UNIX®, licencié par UNIX System Laboratories, Inc., filialeentierement detenue par Novell, Inc., ainsi que par le système 4.3. de Berkeley, licencié par l’Université de Californie. Lelogiciel détenu par des tiers, et qui comprend la technologie relative aux polices de caractères, est protégé par un copyrightet licencié par des fourmisseurs de Sun.

LEGENDE RELATIVE AUX DROITS RESTREINTS: l’utilisation, la duplication ou la divulgation par l’administrationamericaine sont soumises aux restrictions visées a l’alinéa (c)(1)(ii) de la clause relative aux droits des données techniques etaux logiciels informatiques du DFARS 252.227-7013 et FAR 52.227-19. Le produit décrit dans ce manuel peut Être protege parun ou plusieurs brevet(s) americain(s), etranger(s) ou par des demandes en cours d’enregistrement.

MARQUES

Sun, Sun Microsystems, le logo Sun, SunSoft, le logo SunSoft, Solaris, SunOS, OpenWindows, DeskSet, ONC, ONC+ et NFSsont des marques deposées ou enregistrées par Sun Microsystems, Inc. aux Etats-Unis et dans d’autres pays. UNIX est unemarque enregistrée aux Etats- Unis et dans d’autres pays, et exclusivement licenciée par X/Open Company Ltd. OPEN LOOKest une marque enregistrée de Novell, Inc. PostScript et Display PostScript sont des marques d’Adobe Systems, Inc. Le nomPowerPC est une marque depose d’International Business Machines Corporation.

Toutes les marques SPARC sont des marques deposées ou enregitrées de SPARC International, Inc. aux Etats-Unis et dansd’autres pays. SPARCcenter, SPARCcluster, SPARCompiler, SPARCdesign, SPARC811, SPARCengine, SPARCprinter,SPARCserver, SPARCstation, SPARCstorage, SPARCworks, microSPARC, microSPARC-II, et UltraSPARC sont exclusivementlicenciées a Sun Microsystems, Inc. Les produits portant les marques sont basés sur une architecture développée par SunMicrosystems, Inc.

Les utilisateurs d’interfaces graphiques OPEN LOOK® et Sun™ ont été développés par Sun Microsystems, Inc. pour sesutilisateurs et licenciés. Sun reconnait les efforts de pionniers de Xerox pour la recherche et le développement du concept desinterfaces d’utilisation visuelle ou graphique pour l’industrie de l’informatique. Sun détient une licence non exclusive deXerox sur l’interface d’utilisation graphique, cette licence couvrant aussi les licenciés de Sun qui mettent en place OPENLOOK GUIs et qui en outre se conforment aux licences écrites de Sun.

Le système X Window est un produit du X Consortium, Inc.

CETTE PUBLICATION EST FOURNIE “EN L’ETAT” SANS GARANTIE D’AUCUNE SORTE, NI EXPRESSE NI IMPLICITE,Y COMPRIS, ET SANS QUE CETTE LISTE NE SOIT LIMITATIVE, DES GARANTIES CONCERNANT LA VALEURMARCHANDE, L’APTITUDE DES PRODUITS A REPONDRE A UNE UTILISATION PARTICULIERE OU LE FAIT QU’ILSNE SOIENT PAS CONTREFAISANTS DE PRODUITS DE TIERS.

CETTE PUBLICATION PEUT CONTENIR DES MENTIONS TECHNIQUES ERRONEES OU DES ERREURSTYPOGRAPHIQUES. DES CHANGEMENTS SONT PERIODIQUEMENT APPORTES AUX INFORMATIONS CONTENUESAUX PRESENTES. CES CHANGEMENTS SERONT INCORPORES AUX NOUVELLES EDITIONS DE LA PUBLICATION.SUN MICROSYSTEMS INC. PEUT REALISER DES AMELIORATIONS ET/OU DES CHANGEMENTS DANS LE(S)PRODUIT(S) ET/OU LE(S) PROGRAMME(S) DECRITS DANS DETTE PUBLICATION A TOUS MOMENTS.

Page 283: Linker and Libraries Guide - Oracle · 2010-12-30 · Table 6-5 e_ident[ ] ... modes of linking (static anddynamic), scope and forms of input, and forms of output. This chapter is