122
7/27/2019 Linker GNU http://slidepdf.com/reader/full/linker-gnu 1/122 The GNU linker ld (Sourcery G ++ Lite 2010q1-188) Version 2.19.51 Steve Chamberlain Ian Lance Taylor

Linker GNU

Embed Size (px)

Citation preview

Page 1: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 1/122

The GNU linkerld

(Sourcery G ++ Lite 2010q1-188)Version 2.19.51

Steve ChamberlainIan Lance Taylor

Page 2: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 2/122

Red Hat [email protected], [email protected]

The GNU linker Edited by Jefrey Osier ([email protected])

Copyright c 1991, 92, 93, 94, 95, 96, 97, 98, 99, 2000, 2001, 2002, 2003, 2004, 2005, 2006,2007, 2008, 2009 Free So tware Foundation, Inc.Permission is granted to copy, distribute and/or modi y this document under the terms o the GNU Free Documentation License, Version 1.3 or any later version published by theFree So tware Foundation; with no Invariant Sections, with no Front-Cover Texts, and withno Back-Cover Texts. A copy o the license is included in the section entitled “GNU FreeDocumentation License”.

Page 3: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 3/122

i

Table o Contents

1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1

2 Invocation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .32.1 Command Line Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3

2.1.1 Options Speci c to i386 PE Targets . . . . . . . . . . . . . . . . . . . . . . 272.1.2 Options speci c to Motorola 68HC11 and 68HC12 targets

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .342.1.3 Options speci c to Motorola 68K target . . . . . . . . . . . . . . . . . . 35

2.2 Environment Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35

3 Linker Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .373.1 Basic Linker Script Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .373.2 Linker Script Format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .383.3 Simple Linker Script Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .383.4 Simple Linker Script Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39

3.4.1 Setting the Entry Point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .393.4.2 Commands Dealing with Files . . . . . . . . . . . . . . . . . . . . . . . . . . . .393.4.3 Commands Dealing with Object File Formats . . . . . . . . . . . . . 413.4.4 Assign alias names to memory regions . . . . . . . . . . . . . . . . . . . . 413.4.5 Other Linker Script Commands . . . . . . . . . . . . . . . . . . . . . . . . . . .44

3.5 Assigning Values to Symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .453.5.1 Simple Assignments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .453.5.2 PROVIDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .463.5.3 PROVIDE HIDDEN . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .463.5.4 Source Code Re erence . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .46

3.6 SECTIONS Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .483.6.1 Output Section Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .483.6.2 Output Section Name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .493.6.3 Output Section Address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .493.6.4 Input Section Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49

3.6.4.1 Input Section Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .503.6.4.2 Input Section Wildcard Patterns . . . . . . . . . . . . . . . . . . . . .513.6.4.3 Input Section or Common Symbols . . . . . . . . . . . . . . . . . .523.6.4.4 Input Section and Garbage Collection . . . . . . . . . . . . . . . . 53

3.6.4.5 Input Section Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .533.6.5 Output Section Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .533.6.6 Output Section Keywords . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .543.6.7 Output Section Discarding . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .553.6.8 Output Section Attributes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56

3.6.8.1 Output Section Type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .563.6.8.2 Output Section LMA . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .563.6.8.3 Forced Output Alignment . . . . . . . . . . . . . . . . . . . . . . . . . . .57

Page 4: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 4/122

ii The GNU linker

3.6.8.4 Forced Input Alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . .573.6.8.5 Output Section Constraint . . . . . . . . . . . . . . . . . . . . . . . . . . .583.6.8.6 Output Section Region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .583.6.8.7 Output Section Phdr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .583.6.8.8 Output Section Fill . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

3.6.9 Overlay Description . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .583.7 MEMORY Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .603.8 PHDRS Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .613.9 VERSION Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .633.10 Expressions in Linker Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66

3.10.1 Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .663.10.2 Symbolic Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .673.10.3 Symbol Names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .673.10.4 Orphan Sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .673.10.5 The Location Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .673.10.6 Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .693.10.7 Evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70

3.10.8 The Section o an Expression. . . . . . . . . . . . . . . . . . . . . . . . . . . .

703.10.9 Builtin Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .713.11 Implicit Linker Scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74

4 Machine Dependent Features . . . . . . . . . . . . . . . . .754.1 ld and the H8/300 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .754.2 ld and the Intel 960 Family . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .754.3 ld and the Motorola 68HC11 and 68HC12 amilies . . . . . . . . . . . . . 76

4.3.1 Linker Relaxation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .764.3.2 Trampoline Generation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76

4.4 ld and the ARM amily . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76

4.5 ld and HPPA 32-bit ELF Support. . . . . . . . . . . . . . . . . . . . . . . . . . . .

794.6 ld and the Motorola 68K amily . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .794.7 ld and MMIX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .794.8 ld and MSP430 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .804.9 ld and PowerPC 32-bit ELF Support . . . . . . . . . . . . . . . . . . . . . . . . . .804.10 ld and PowerPC64 64-bit ELF Support . . . . . . . . . . . . . . . . . . . . . .814.11 ld and SPU ELF Support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .834.12 ld ’s Support or Various TI COFF Versions . . . . . . . . . . . . . . . . . . 834.13 ld and WIN32 (cygwin/mingw) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .844.14 ld and Xtensa Processors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91

5 BFD . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .935.1 How It Works: An Outline o BFD . . . . . . . . . . . . . . . . . . . . . . . . . . . .93

5.1.1 In ormation Loss . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .935.1.2 The BFD canonical object- le ormat . . . . . . . . . . . . . . . . . . . . .94

6 Reporting Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .976.1 Have You Found a Bug? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .976.2 How to Report Bugs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97

Page 5: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 5/122

iii

Appendix A MRI Compatible Script Files . . 101

Appendix B GNU Free Documentation License. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .103

ADDENDUM: How to use this License or your documents . . . . . . . . 108

LD Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .109

Page 6: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 6/122

Page 7: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 7/122

Chapter 1: Overview 1

1 Overviewld combines a number o object and archive les, relocates their data and ties up symbolre erences. Usually the last step in compiling a program is to run ld .ld accepts Linker Command Language les written in a superset o AT&T’s Link EditorCommand Language syntax, to provide explicit and total control over the linking process.This version o ld uses the general purpose BFD libraries to operate on object les. Thisallows ld to read, combine, and write object les in many diferent ormats— or example,COFF or a.out . Diferent ormats may be linked together to produce any available kind o object le. See Chapter 5 [BFD], page 93 , or more in ormation.Aside rom its exibility, the gnu linker is more help ul than other linkers in providingdiagnostic in ormation. Many linkers abandon execution immediately upon encounteringan error; whenever possible, ld continues executing, allowing you to identi y other errors(or, in some cases, to get an output le in spite o the error).

Page 8: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 8/122

Page 9: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 9/122

Chapter 2: Invocation 3

2 InvocationThe gnu linker ld is meant to cover a broad range o situations, and to be as compatibleas possible with other linkers. As a result, you have many choices to control its behavior.

2.1 Command Line OptionsThe linker supports a plethora o command-line options, but in actual practice ew o themare used in any particular context. For instance, a requent use o ld is to link standardUnix object les on a standard, supported Unix system. On such a system, to link a lehello.o :

ld -o output /lib/crt0.o hello.o -lc

This tells ld to produce a le called output as the result o linking the le /lib/crt0.owith hello.o and the library libc.a , which will come rom the standard search directories.(See the discussion o the ‘ -l ’ option below.)

Some o the command-line options to ld may be speci ed at any point in the commandline. However, options which re er to les, such as ‘ -l ’ or ‘-T ’, cause the le to be read atthe point at which the option appears in the command line, relative to the object les andother le options. Repeating non- le options with a diferent argument will either have nourther efect, or override prior occurrences (those urther to the le t on the command line)o that option. Options which may be meaning ully speci ed more than once are noted inthe descriptions below.Non-option arguments are object les or archives which are to be linked together. Theymay ollow, precede, or be mixed in with command-line options, except that an object leargument may not be placed between an option and its argument.Usually the linker is invoked with at least one object le, but you can speci y other ormso binary input les using ‘ -l ’, ‘-R ’, and the script command language. I no binary inputles at all are speci ed, the linker does not produce any output, and issues the message ‘ No

input files ’.I the linker cannot recognize the ormat o an object le, it will assume that it is a linkerscript. A script speci ed in this way augments the main linker script used or the link(either the de ault linker script or the one speci ed by using ‘ -T ’). This eature permits thelinker to link against a le which appears to be an object or an archive, but actually merelyde nes some symbol values, or uses INPUT or GROUPto load other objects. Speci ying ascript in this way merely augments the main linker script, with the extra commands placeda ter the main script; use the ‘ -T ’ option to replace the de ault linker script entirely, butnote the efect o the INSERT command. See Chapter 3 [Scripts], page 37 .For options whose names are a single letter, option arguments must either ollow the op-tion letter without intervening whitespace, or be given as separate arguments immediatelyollowing the option that requires them.For options whose names are multiple letters, either one dash or two can precede the optionname; or example, ‘ -trace-symbol ’ and ‘--trace-symbol ’ are equivalent. Note—there isone exception to this rule. Multiple letter options that start with a lower case ’o’ can onlybe preceded by two dashes. This is to reduce con usion with the ‘ -o ’ option. So or example‘-omagic ’ sets the output le name to ‘ magic ’ whereas ‘--omagic ’ sets the NMAGIC agon the output.

Page 10: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 10/122

4 The GNU linker

Arguments to multiple-letter options must either be separated rom the option name byan equals sign, or be given as separate arguments immediately ollowing the option thatrequires them. For example, ‘ --trace-symbol foo ’ and ‘--trace-symbol=foo ’ are equiv-alent. Unique abbreviations o the names o multiple-letter options are accepted.Note—i the linker is being invoked indirectly, via a compiler driver (e.g. ‘ gcc ’) then all thelinker command line options should be pre xed by ‘ -Wl, ’ (or whatever is appropriate orthe particular compiler driver) like this:

gcc -Wl,--start-group foo.o bar.o -Wl,--end-group

This is important, because otherwise the compiler driver program may silently drop thelinker options, resulting in a bad link. Con usion may also arise when passing options thatrequire values through a driver, as the use o a space between option and argument acts asa separator, and causes the driver to pass only the option to the linker and the argumentto the compiler. In this case, it is simplest to use the joined orms o both single- andmultiple-letter options, such as:

gcc foo.o bar.o -Wl,-eENTRY -Wl,-Map=a.map

Here is a table o the generic command line switches accepted by the GNU linker:

@file Read command-line options rom le . The options read are inserted in placeo the original @le option. I le does not exist, or cannot be read, then theoption will be treated literally, and not removed.Options in le are separated by whitespace. A whitespace character may beincluded in an option by surrounding the entire option in either single or doublequotes. Any character (including a backslash) may be included by pre xing thecharacter to be included with a backslash. The le may itsel contain additional@le options; any such options will be processed recursively.

-a keyword

This option is supported or HP/UX compatibility. The keyword argumentmust be one o the strings ‘ archive ’, ‘shared ’, or ‘default ’. ‘-aarchive ’ isunctionally equivalent to ‘ -Bstatic ’, and the other two keywords are unc-tionally equivalent to ‘ -Bdynamic ’. This option may be used any number o times.

-A architecture--architecture= architecture

In the current release o ld , this option is use ul only or the Intel 960 amilyo architectures. In that ld con guration, the architecture argument identi esthe particular architecture in the 960 amily, enabling some sa eguards andmodi ying the archive-library search path. See Section 4.2 [ld and the Intel 960

amily], page 75 , or details.Future releases o ld may support similar unctionality or other architectureamilies.

-b input-format--format= input-format

ld may be con gured to support more than one kind o object le. I your ld iscon gured this way, you can use the ‘ -b ’ option to speci y the binary ormat orinput object les that ollow this option on the command line. Even when ld

Page 11: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 11/122

Chapter 2: Invocation 5

is con gured to support alternative object ormats, you don’t usually need tospeci y this, as ld should be con gured to expect as a de ault input ormat themost usual ormat on each machine. input- ormat is a text string, the name o a particular ormat supported by the BFD libraries. (You can list the availablebinary ormats with ‘ objdump -i ’.) See Chapter 5 [BFD], page 93 .You may want to use this option i you are linking les with an unusual binaryormat. You can also use ‘ -b ’ to switch ormats explicitly (when linking objectles o diferent ormats), by including ‘ -b input-format ’ be ore each group o object les in a particular ormat.The de ault ormat is taken rom the environment variable GNUTARGET. SeeSection 2.2 [Environment], page 35 . You can also de ne the input ormat roma script, using the command TARGET; see Section 3.4.3 [Format Commands],page 41.

-c MRI-commandfile

--mri-script= MRI-commandfileFor compatibility with linkers produced by MRI, ld accepts script les writtenin an alternate, restricted command language, described in Appendix A [MRICompatible Script Files], page 101 . Introduce MRI script les with the option‘-c ’; use the ‘-T ’ option to run linker scripts written in the general-purposeld scripting language. I MRI-cmd le does not exist, ld looks or it in thedirectories speci ed by any ‘ -L ’ options.

-d-dc-dp These three options are equivalent; multiple orms are supported or compati-

bility with other linkers. They assign space to common symbols even i a relo-

catable output le is speci ed (with ‘ -r ’). The script command FORCE_COMMON_ALLOCATIONhas the same efect. See Section 3.4.5 [Miscellaneous Commands],page 44.

-e entry --entry= entry

Use entry as the explicit symbol or beginning execution o your program, ratherthan the de ault entry point. I there is no symbol named entry , the linker willtry to parse entry as a number, and use that as the entry address (the numberwill be interpreted in base 10; you may use a leading ‘ 0x ’ or base 16, or aleading ‘0’ or base 8). See Section 3.4.1 [Entry Point], page 39 , or a discussiono de aults and other ways o speci ying the entry point.

--exclude-libs lib , lib ,...Speci es a list o archive libraries rom which symbols should not be automat-ically exported. The library names may be delimited by commas or colons.Speci ying --exclude-libs ALL excludes symbols in all archive libraries romautomatic export. This option is available only or the i386 PE targeted port o the linker and or ELF targeted ports. For i386 PE, symbols explicitly listed ina .de le are still exported, regardless o this option. For ELF targeted ports,symbols afected by this option will be treated as hidden.

Page 12: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 12/122

6 The GNU linker

--exclude-modules-for-implib module , module ,...Speci es a list o object les or archive members, rom which symbols shouldnot be automatically exported, but which should be copied wholesale into theimport library being generated during the link. The module names may bedelimited by commas or colons, and must match exactly the lenames used byld to open the les; or archive members, this is simply the member name, butor object les the name listed must include and match precisely any path usedto speci y the input le on the linker’s command-line. This option is availableonly or the i386 PE targeted port o the linker. Symbols explicitly listed in a.de le are still exported, regardless o this option.

-E--export-dynamic--no-export-dynamic

When creating a dynamically linked executable, using the ‘ -E ’ option or the‘--export-dynamic ’ option causes the linker to add all symbols to the dynamic

symbol table. The dynamic symbol table is the set o symbols which are visiblerom dynamic objects at run time.I you do not use either o these options (or use the ‘ --no-export-dynamic ’option to restore the de ault behavior), the dynamic symbol table will nor-mally contain only those symbols which are re erenced by some dynamic objectmentioned in the link.I you use dlopen to load a dynamic object which needs to re er back to thesymbols de ned by the program, rather than some other dynamic object, thenyou will probably need to use this option when linking the program itsel .You can also use the dynamic list to control what symbols should be added tothe dynamic symbol table i the output ormat supports it. See the description

o ‘--dynamic-list ’.Note that this option is speci c to ELF targeted ports. PE targets support asimilar unction to export all symbols rom a DLL or EXE; see the descriptiono ‘--export-all-symbols ’ below.

-EB Link big-endian objects. This afects the de ault output ormat.-EL Link little-endian objects. This afects the de ault output ormat.-f name--auxiliary= name

When creating an ELF shared object, set the internal DT AUXILIARY eldto the speci ed name. This tells the dynamic linker that the symbol table o the shared object should be used as an auxiliary lter on the symbol table o the shared object name .I you later link a program against this lter object, then, when you run theprogram, the dynamic linker will see the DT AUXILIARY eld. I the dynamiclinker resolves any symbols rom the lter object, it will rst check whether thereis a de nition in the shared object name . I there is one, it will be used instead o the de nition in the lter object. The shared object name need not exist. Thusthe shared object name may be used to provide an alternative implementationo certain unctions, perhaps or debugging or or machine speci c per ormance.

Page 13: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 13/122

Chapter 2: Invocation 7

This option may be speci ed more than once. The DT AUXILIARY entrieswill be created in the order in which they appear on the command line.

-F name

--filter= nameWhen creating an ELF shared object, set the internal DT FILTER eld tothe speci ed name. This tells the dynamic linker that the symbol table o theshared object which is being created should be used as a lter on the symboltable o the shared object name .I you later link a program against this lter object, then, when you run theprogram, the dynamic linker will see the DT FILTER eld. The dynamic linkerwill resolve symbols according to the symbol table o the lter object as usual,but it will actually link to the de nitions ound in the shared object name .Thus the lter object can be used to select a subset o the symbols provided bythe object name .

Some older linkers used the ‘ -F ’ option throughout a compilation toolchain orspeci ying object- le ormat or both input and output object les. The gnu

linker uses other mechanisms or this purpose: the ‘ -b ’, ‘--format ’, ‘--oformat ’options, the TARGETcommand in linker scripts, and the GNUTARGETenvironmentvariable. The gnu linker will ignore the ‘-F ’ option when not creating an ELFshared object.

-fini= nameWhen creating an ELF executable or shared object, call NAME when the exe-cutable or shared object is unloaded, by setting DT FINI to the address o theunction. By de ault, the linker uses _fini as the unction to call.

-g Ignored. Provided or compatibility with other tools.

-G value--gpsize= value

Set the maximum size o objects to be optimized using the GP register to size .This is only meaning ul or object le ormats such as MIPS ECOFF whichsupports putting large and small objects into diferent sections. This is ignoredor other object le ormats.

-h name-soname= name

When creating an ELF shared object, set the internal DT SONAME eld to thespeci ed name. When an executable is linked with a shared object which hasa DT SONAME eld, then when the executable is run the dynamic linker willattempt to load the shared object speci ed by the DT SONAME eld ratherthan the using the le name given to the linker.

-i Per orm an incremental link (same as option ‘ -r ’).

-init= nameWhen creating an ELF executable or shared object, call NAME when the ex-ecutable or shared object is loaded, by setting DT INIT to the address o theunction. By de ault, the linker uses _init as the unction to call.

Page 14: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 14/122

8 The GNU linker

-l namespec--library= namespec

Add the archive or object le speci ed by namespec to the list o les to link.This option may be used any number o times. I namespec is o the orm‘: filename ’, ld will search the library path or a le called lename , otherwiseit will search the library path or a le called ‘ lib namespec .a ’.On systems which support shared libraries, ld may also search or les otherthan ‘ lib namespec .a ’. Speci cally, on ELF and SunOS systems, ld will searcha directory or a library called ‘ lib namespec .so ’ be ore searching or one called‘lib namespec .a ’. (By convention, a .so extension indicates a shared library.)Note that this behavior does not apply to ‘ : filename ’, which always speci esa le called lename .The linker will search an archive only once, at the location where it is speci edon the command line. I the archive de nes a symbol which was unde ned insome object which appeared be ore the archive on the command line, the linker

will include the appropriate le(s) rom the archive. However, an unde nedsymbol in an object appearing later on the command line will not cause thelinker to search the archive again.See the ‘-( ’ option or a way to orce the linker to search archives multipletimes.You may list the same archive multiple times on the command line.This type o archive searching is standard or Unix linkers. However, i you areusing ld on AIX, note that it is diferent rom the behaviour o the AIX linker.

-L searchdir --library-path= searchdir

Add path searchdir to the list o paths that ld will search or archive librariesand ld control scripts. You may use this option any number o times. Thedirectories are searched in the order in which they are speci ed on the commandline. Directories speci ed on the command line are searched be ore the de aultdirectories. All ‘-L ’ options apply to all ‘ -l ’ options, regardless o the orderin which the options appear. ‘ -L ’ options do not afect how ld searches or alinker script unless ‘ -T ’ option is speci ed.I searchdir begins with =, then the = will be replaced by the sysroot pre x , apath speci ed when the linker is con gured.The de ault set o paths searched (without being speci ed with ‘ -L ’) dependson which emulation mode ld is using, and in some cases also on how it wascon gured. See Section 2.2 [Environment], page 35 .

The paths can also be speci ed in a link script with the SEARCH_DIRcommand.Directories speci ed this way are searched at the point in which the linker scriptappears in the command line.

-m emulationEmulate the emulation linker. You can list the available emulations with the‘--verbose ’ or ‘-V’ options.I the ‘ -m’ option is not used, the emulation is taken rom the LDEMULATIONenvironment variable, i that is de ned.

Page 15: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 15/122

Chapter 2: Invocation 9

Otherwise, the de ault emulation depends upon how the linker was con gured.

-M--print-map

Print a link map to the standard output. A link map provides in ormationabout the link, including the ollowing:• Where object les are mapped into memory.• How common symbols are allocated.• All archive members included in the link, with a mention o the symbol

which caused the archive member to be brought in.• The values assigned to symbols.

Note - symbols whose values are computed by an expression which involvesa re erence to a previous value o the same symbol may not have correctresult displayed in the link map. This is because the linker discards inter-

mediate results and only retains the nal value o an expression. Undersuch circumstances the linker will display the nal value enclosed by squarebrackets. Thus or example a linker script containing:

foo = 1foo = foo * 4foo = foo + 8

will produce the ollowing output in the link map i the ‘ -M’ option is used:0x00000001 foo = 0x1[0x0000000c] foo = (foo * 0x4)[0x0000000c] foo = (foo + 0x8)

See Section 3.10 [Expressions], page 66 or more in ormation about expres-sions in linker scripts.

-n--nmagic Turn of page alignment o sections, and mark the output as NMAGICi possible.

-N--omagic Set the text and data sections to be readable and writable. Also, do not page-

align the data segment, and disable linking against shared libraries. I theoutput ormat supports Unix style magic numbers, mark the output as OMAGIC.Note: Although a writable text section is allowed or PE-COFF targets, it doesnot con orm to the ormat speci cation published by Microso t.

--no-omagicThis option negates most o the efects o the ‘ -N’ option. It sets the text section

to be read-only, and orces the data segment to be page-aligned. Note - thisoption does not enable linking against shared libraries. Use ‘ -Bdynamic ’ orthis.

-o output--output= output

Use output as the name or the program produced by ld ; i this option is notspeci ed, the name ‘ a.out ’ is used by de ault. The script command OUTPUTcan also speci y the output le name.

Page 16: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 16/122

10 The GNU linker

-O level I level is a numeric values greater than zero ld optimizes the output. Thismight take signi cantly longer and there ore probably should only be enabledor the nal binary. At the moment this option only afects ELF shared librarygeneration. Future releases o the linker may make more use o this option. Alsocurrently there is no diference in the linker’s behaviour or diferent non-zerovalues o this option. Again this may change with uture releases.

-q --emit-relocs

Leave relocation sections and contents in ully linked executables. Post linkanalysis and optimization tools may need this in ormation in order to per ormcorrect modi cations o executables. This results in larger executables.This option is currently only supported on ELF plat orms.

--force-dynamicForce the output le to have dynamic sections. This option is speci c to Vx-

Works targets.-r--relocatable

Generate relocatable output—i.e., generate an output le that can in turn serveas input to ld . This is o ten called partial linking . As a side efect, in envi-ronments that support standard Unix magic numbers, this option also sets theoutput le’s magic number to OMAGIC. I this option is not speci ed, an abso-lute le is produced. When linking C ++ programs, this option will not resolvere erences to constructors; to do that, use ‘ -Ur ’.When an input le does not have the same ormat as the output le, partiallinking is only supported i that input le does not contain any relocations.Diferent output ormats can have urther restrictions; or example some a.out -based ormats do not support partial linking with input les in other ormatsat all.This option does the same thing as ‘ -i ’.

-R filename--just-symbols= filename

Read symbol names and their addresses rom lename , but do not relocate itor include it in the output. This allows your output le to re er symbolicallyto absolute locations o memory de ned in other programs. You may use thisoption more than once.For compatibility with other ELF linkers, i the ‘ -R ’ option is ollowed by adirectory name, rather than a le name, it is treated as the ‘ -rpath ’ option.

-s--strip-all

Omit all symbol in ormation rom the output le.

-S--strip-debug

Omit debugger symbol in ormation (but not all symbols) rom the output le.

Page 17: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 17/122

Chapter 2: Invocation 11

-t--trace Print the names o the input les as ld processes them.

-T scriptfile

--script= scriptfileUse script le as the linker script. This script replaces ld ’s de ault linker script(rather than adding to it), so command le must speci y everything necessaryto describe the output le. See Chapter 3 [Scripts], page 37 . I script le doesnot exist in the current directory, ld looks or it in the directories speci ed byany preceding ‘ -L ’ options. Multiple ‘ -T ’ options accumulate.

-dT scriptfile--default-script= scriptfile

Use script le as the de ault linker script. See Chapter 3 [Scripts], page 37 .

This option is similar to the ‘ --script ’ option except that processing o the

script is delayed until a ter the rest o the command line has been processed.This allows options placed a ter the ‘ --default-script ’ option on the com-mand line to afect the behaviour o the linker script, which can be importantwhen the linker command line cannot be directly controlled by the user. (egbecause the command line is being constructed by another tool, such as ‘ gcc ’).

-u symbol--undefined= symbol

Force symbol to be entered in the output le as an unde ned symbol. Do-ing this may, or example, trigger linking o additional modules rom standardlibraries. ‘ -u ’ may be repeated with diferent option arguments to enter addi-tional unde ned symbols. This option is equivalent to the EXTERNlinker script

command.-Ur For anything other than C ++ programs, this option is equivalent to ‘ -r ’: it gen-

erates relocatable output—i.e., an output le that can in turn serve as input told . When linking C ++ programs, ‘ -Ur ’ does resolve re erences to constructors,unlike ‘-r ’. It does not work to use ‘ -Ur ’ on les that were themselves linkedwith ‘-Ur ’; once the constructor table has been built, it cannot be added to.Use ‘-Ur ’ only or the last partial link, and ‘ -r ’ or the others.

--unique[= SECTION ]Creates a separate output section or every input section matching SECTION ,or i the optional wildcard SECTION argument is missing, or every orphan

input section. An orphan section is one not speci cally mentioned in a linkerscript. You may use this option multiple times on the command line; It preventsthe normal merging o input sections with the same name, overriding outputsection assignments in a linker script.

-v--version-V Display the version number or ld . The ‘-V’ option also lists the supported

emulations.

Page 18: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 18/122

12 The GNU linker

-x--discard-all

Delete all local symbols.

-X--discard-localsDelete all temporary local symbols. (These symbols start with system-speci clocal label pre xes, typically ‘ .L ’ or ELF systems or ‘ L’ or traditional a.outsystems.)

-y symbol--trace-symbol= symbol

Print the name o each linked le in which symbol appears. This option maybe given any number o times. On many systems it is necessary to prepend anunderscore.This option is use ul when you have an unde ned symbol in your link but don’t

know where the re erence is coming rom.-Y path Add path to the de ault library search path. This option exists or Solaris

compatibility.

-z keywordThe recognized keywords are:

‘combreloc ’Combines multiple reloc sections and sorts them to make dynamicsymbol lookup caching possible.

‘defs ’ Disallows unde ned symbols in object les. Unde ned symbols inshared libraries are still allowed.

‘execstack ’Marks the object as requiring executable stack.

‘initfirst ’This option is only meaning ul when building a shared object. Itmarks the object so that its runtime initialization will occur be orethe runtime initialization o any other objects brought into theprocess at the same time. Similarly the runtime nalization o theobject will occur a ter the runtime nalization o any other objects.

‘interpose ’Marks the object that its symbol table interposes be ore all symbols

but the primary executable.‘lazy ’ When generating an executable or shared library, mark it to tell the

dynamic linker to de er unction call resolution to the point whenthe unction is called (lazy binding), rather than at load time. Lazybinding is the de ault.

‘loadfltr ’Marks the object that its lters be processed immediately at run-time.

Page 19: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 19/122

Chapter 2: Invocation 13

‘ muldefs ’ Allows multiple de nitions.

‘nocombreloc ’Disables multiple reloc sections combining.

‘nocopyreloc ’Disables production o copy relocs.

‘nodefaultlib ’Marks the object that the search or dependencies o this objectwill ignore any de ault library search paths.

‘nodelete ’Marks the object shouldn’t be unloaded at runtime.

‘nodlopen ’Marks the object not available to dlopen .

‘nodump’ Marks the object can not be dumped by dldump .

‘noexecstack ’Marks the object as not requiring executable stack.

‘norelro ’ Don’t create an ELF PT_GNU_RELROsegment header in the object.

‘now’ When generating an executable or shared library, mark it to tell thedynamic linker to resolve all symbols when the program is started,or when the shared library is linked to using dlopen, instead o de erring unction call resolution to the point when the unction isrst called.

‘origin ’ Marks the object may contain $ORIGIN.

‘relro ’ Create an ELF PT_GNU_RELROsegment header in the object.

‘ max-page-size= value ’Set the emulation maximum page size to value .

‘common-page-size= value ’Set the emulation common page size to value .

Other keywords are ignored or Solaris compatibility.

-( archives -)--start-group archives --end-group

The archives should be a list o archive les. They may be either explicit lenames, or ‘-l ’ options.The speci ed archives are searched repeatedly until no new unde ned re erencesare created. Normally, an archive is searched only once in the order that it isspeci ed on the command line. I a symbol in that archive is needed to resolvean unde ned symbol re erred to by an object in an archive that appears lateron the command line, the linker would not be able to resolve that re erence.By grouping the archives, they all be searched repeatedly until all possiblere erences are resolved.Using this option has a signi cant per ormance cost. It is best to use it onlywhen there are unavoidable circular re erences between two or more archives.

Page 20: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 20/122

14 The GNU linker

--accept-unknown-input-arch--no-accept-unknown-input-arch

Tells the linker to accept input les whose architecture cannot be recognised.The assumption is that the user knows what they are doing and deliberatelywants to link in these unknown input les. This was the de ault behaviour o the linker, be ore release 2.14. The de ault behaviour rom release 2.14 onwardsis to reject such input les, and so the ‘ --accept-unknown-input-arch ’ optionhas been added to restore the old behaviour.

--as-needed--no-as-needed

This option afects ELF DT NEEDED tags or dynamic libraries mentionedon the command line a ter the ‘ --as-needed ’ option. Normally, the linker willadd a DT NEEDED tag or each dynamic library mentioned on the commandline, regardless o whether the library is actually needed. ‘ --as-needed ’ causes

a DT NEEDED tag to only be emitted or a library that satis es a symbolre erence rom regular objects which is unde ned at the point that the librarywas linked, or, i the library is not ound in the DT NEEDED lists o otherlibraries linked up to that point, a re erence rom another dynamic library.‘--no-as-needed ’ restores the de ault behaviour.

--add-needed--no-add-needed

This option afects the treatment o dynamic libraries rom ELF DT NEEDEDtags in dynamic libraries mentioned on the command line a ter the‘--no-add-needed ’ option. Normally, the linker will add a DT NEEDEDtag or each dynamic library rom DT NEEDED tags. ‘ --no-add-needed ’causes DT NEEDED tags will never be emitted or those libraries romDT NEEDED tags. ‘ --add-needed ’ restores the de ault behaviour.

-assert keywordThis option is ignored or SunOS compatibility.

-Bdynamic-dy-call_shared

Link against dynamic libraries. This is only meaning ul on plat orms or whichshared libraries are supported. This option is normally the de ault on suchplat orms. The diferent variants o this option are or compatibility with vari-ous systems. You may use this option multiple times on the command line: itafects library searching or ‘ -l ’ options which ollow it.

-Bgroup Set the DF_1_GROUPag in the DT_FLAGS_1entry in the dynamic section. Thiscauses the runtime linker to handle lookups in this object and its dependenciesto be per ormed only inside the group. ‘ --unresolved-symbols=report-all ’is implied. This option is only meaning ul on ELF plat orms which supportshared libraries.

Page 21: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 21/122

Chapter 2: Invocation 15

-Bstatic-dn-non_shared-static Do not link against shared libraries. This is only meaning ul on plat orms

or which shared libraries are supported. The diferent variants o this optionare or compatibility with various systems. You may use this option multipletimes on the command line: it afects library searching or ‘ -l ’ options whichollow it. This option also implies ‘ --unresolved-symbols=report-all ’. Thisoption can be used with ‘ -shared ’. Doing so means that a shared library isbeing created but that all o the library’s external re erences must be resolvedby pulling in entries rom static libraries.

-BsymbolicWhen creating a shared library, bind re erences to global symbols to the de -nition within the shared library, i any. Normally, it is possible or a programlinked against a shared library to override the de nition within the shared li-brary. This option is only meaning ul on ELF plat orms which support sharedlibraries.

-Bsymbolic-functionsWhen creating a shared library, bind re erences to global unction symbols tothe de nition within the shared library, i any. This option is only meaning ulon ELF plat orms which support shared libraries.

--dynamic-list= dynamic-list-fileSpeci y the name o a dynamic list le to the linker. This is typically used whencreating shared libraries to speci y a list o global symbols whose re erencesshouldn’t be bound to the de nition within the shared library, or creating dy-namically linked executables to speci y a list o symbols which should be addedto the symbol table in the executable. This option is only meaning ul on ELFplat orms which support shared libraries.The ormat o the dynamic list is the same as the version node without scopeand node name. See Section 3.9 [VERSION], page 63 or more in ormation.

--dynamic-list-dataInclude all global data symbols to the dynamic list.

--dynamic-list-cpp-newProvide the builtin dynamic list or C ++ operator new and delete. It is mainlyuse ul or building shared libstdc ++.

--dynamic-list-cpp-typeinfo

Provide the builtin dynamic list or C ++ runtime type identi cation.--check-sections--no-check-sections

Asks the linker not to check section addresses a ter they have been assigned tosee i there are any overlaps. Normally the linker will per orm this check, andi it nds any overlaps it will produce suitable error messages. The linker doesknow about, and does make allowances or sections in overlays. The de ault be-haviour can be restored by using the command line switch ‘ --check-sections ’.

Page 22: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 22/122

Page 23: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 23/122

Chapter 2: Invocation 17

-I file--dynamic-linker= file

Set the name o the dynamic linker. This is only meaning ul when generatingdynamically linked ELF executables. The de ault dynamic linker is normallycorrect; don’t use this unless you know what you are doing.

--fatal-warnings--no-fatal-warnings

Treat all warnings as errors. The de ault behaviour can be restored with theoption ‘--no-fatal-warnings ’.

--force-exe-suffixMake sure that an output le has a .exe su x.I a success ully built ully linked output le does not have a .exe or .dll su x,this option orces the linker to copy the output le to one o the same namewith a .exe su x. This option is use ul when using unmodi ed Unix make leson a Microso t Windows host, since some versions o Windows won’t run animage unless it ends in a .exe su x.

--gc-sections--no-gc-sections

Enable garbage collection o unused input sections. It is ignored on targetsthat do not support this option. The de ault behaviour (o not per orming thisgarbage collection) can be restored by speci ying ‘ --no-gc-sections ’ on thecommand line.‘--gc-sections ’ decides which input sections are used by examining symbolsand relocations. The section containing the entry symbol and all sections con-taining symbols unde ned on the command-line will be kept, as will sectionscontaining symbols re erenced by dynamic objects. Note that when buildingshared libraries, the linker must assume that any visible symbol is re erenced.Once this initial set o sections has been determined, the linker recursivelymarks as used any section re erenced by their relocations. See ‘ --entry ’ and‘--undefined ’.This option can be set when doing a partial link (enabled with option ‘ -r ’).In this case the root o symbols kept must be explicitely speci ed either by an‘--entry ’ or ‘--undefined ’ option or by a ENTRYcommand in the linker script.

--print-gc-sections--no-print-gc-sections

List all sections removed by garbage collection. The listing is printed on stderr.This option is only efective i garbage collection has been enabled via the‘--gc-sections ’) option. The de ault behaviour (o not listing the sectionsthat are removed) can be restored by speci ying ‘ --no-print-gc-sections ’ onthe command line.

--help Print a summary o the command-line options on the standard output and exit.

--target-helpPrint a summary o all target speci c options on the standard output and exit.

Page 24: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 24/122

Page 25: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 25/122

Chapter 2: Invocation 19

--default-imported-symverCreate and use a de ault symbol version (the soname) or unversioned importedsymbols.

--no-warn-mismatchNormally ld will give an error i you try to link together input les that aremismatched or some reason, perhaps because they have been compiled ordiferent processors or or diferent endiannesses. This option tells ld that itshould silently permit such possible errors. This option should only be usedwith care, in cases when you have taken some special action that ensures thatthe linker errors are inappropriate.

--no-warn-search-mismatchNormally ld will give a warning i it nds an incompatible library during alibrary search. This option silences the warning.

--no-whole-archive

Turn of the efect o the ‘ --whole-archive ’ option or subsequent archive les.--noinhibit-exec

Retain the executable output le whenever it is still usable. Normally, the linkerwill not produce an output le i it encounters errors during the link process;it exits without writing an output le when it issues any error whatsoever.

-nostdlibOnly search library directories explicitly speci ed on the command line. Librarydirectories speci ed in linker scripts (including linker scripts speci ed on thecommand line) are ignored.

--oformat= output-format

ld may be con gured to support more than one kind o object le. I yourld is con gured this way, you can use the ‘ --oformat ’ option to speci y thebinary ormat or the output object le. Even when ld is con gured to supportalternative object ormats, you don’t usually need to speci y this, as ld shouldbe con gured to produce as a de ault output ormat the most usual ormat oneach machine. output- ormat is a text string, the name o a particular ormatsupported by the BFD libraries. (You can list the available binary ormatswith ‘objdump -i ’.) The script command OUTPUT_FORMATcan also speci y theoutput ormat, but this option overrides it. See Chapter 5 [BFD], page 93 .

-pie--pic-executable

Create a position independent executable. This is currently only supportedon ELF plat orms. Position independent executables are similar to shared li-braries in that they are relocated by the dynamic linker to the virtual addressthe OS chooses or them (which can vary between invocations). Like normaldynamically linked executables they can be executed and symbols de ned inthe executable cannot be overridden by shared libraries.

-qmagic This option is ignored or Linux compatibility.

-Qy This option is ignored or SVR4 compatibility.

Page 26: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 26/122

20 The GNU linker

--relax An option with machine dependent efects. This option is only supported on aew targets. See Section 4.1 [ld and the H8/300], page 75 . See Section 4.2 [ldand the Intel 960 amily], page 75 . See Section 4.14 [ld and Xtensa Processors],page 91. See Section 4.3 [ld and the 68HC11 and 68HC12], page 76 . SeeSection 4.9 [ld and PowerPC 32-bit ELF Support], page 80 .On some plat orms, the ‘ --relax ’ option per orms global optimizations thatbecome possible when the linker resolves addressing in the program, such asrelaxing address modes and synthesizing new instructions in the output objectle.On some plat orms these link time global optimizations may make symbolicdebugging o the resulting executable impossible. This is known to be the caseor the Matsushita MN10200 and MN10300 amily o processors.On plat orms where this is not supported, ‘ --relax ’ is accepted, but ignored.

--retain-symbols-file= filenameRetain only the symbols listed in the le lename , discarding all others. le-name is simply a at le, with one symbol name per line. This option is espe-cially use ul in environments (such as VxWorks) where a large global symboltable is accumulated gradually, to conserve run-time memory.‘--retain-symbols-file ’ does not discard unde ned symbols, or symbolsneeded or relocations.You may only speci y ‘ --retain-symbols-file ’ once in the command line. Itoverrides ‘-s ’ and ‘-S ’.

-rpath= dir Add a directory to the runtime library search path. This is used when linking an

ELF executable with shared objects. All ‘ -rpath ’ arguments are concatenatedand passed to the runtime linker, which uses them to locate shared objects atruntime. The ‘ -rpath ’ option is also used when locating shared objects whichare needed by shared objects explicitly included in the link; see the descriptiono the ‘-rpath-link ’ option. I ‘-rpath ’ is not used when linking an ELFexecutable, the contents o the environment variable LD_RUN_PATHwill be usedi it is de ned.The ‘-rpath ’ option may also be used on SunOS. By de ault, on SunOS, thelinker will orm a runtime search patch out o all the ‘ -L ’ options it is given. I a ‘-rpath ’ option is used, the runtime search path will be ormed exclusivelyusing the ‘-rpath ’ options, ignoring the ‘ -L ’ options. This can be use ul when

using gcc, which adds many ‘-L

’ options which may be on NFS mounted lesystems.For compatibility with other ELF linkers, i the ‘ -R ’ option is ollowed by adirectory name, rather than a le name, it is treated as the ‘ -rpath ’ option.

-rpath-link= dir When using ELF or SunOS, one shared library may require another. Thishappens when an ld -shared link includes a shared library as one o the inputles.

Page 27: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 27/122

Chapter 2: Invocation 21

When the linker encounters such a dependency when doing a non-shared, non-relocatable link, it will automatically try to locate the required shared libraryand include it in the link, i it is not included explicitly. In such a case,the ‘-rpath-link ’ option speci es the rst set o directories to search. The‘-rpath-link ’ option may speci y a sequence o directory names either by spec-i ying a list o names separated by colons, or by appearing multiple times.This option should be used with caution as it overrides the search path thatmay have been hard compiled into a shared library. In such a case it is possibleto use unintentionally a diferent search path than the runtime linker would do.The linker uses the ollowing search paths to locate required shared libraries:

1. Any directories speci ed by ‘ -rpath-link ’ options.2. Any directories speci ed by ‘ -rpath ’ options. The diference between

‘-rpath ’ and ‘-rpath-link ’ is that directories speci ed by ‘ -rpath ’ op-tions are included in the executable and used at runtime, whereas the

‘-rpath-link ’ option is only efective at link time. Searching ‘ -rpath ’ inthis way is only supported by native linkers and cross linkers which havebeen con gured with the ‘ --with-sysroot ’ option.

3. On an ELF system, or native linkers, i the ‘ -rpath ’ and ‘-rpath-link ’options were not used, search the contents o the environment variableLD_RUN_PATH.

4. On SunOS, i the ‘ -rpath ’ option was not used, search any directoriesspeci ed using ‘ -L ’ options.

5. For a native linker, the search the contents o the environment variableLD_LIBRARY_PATH.

6. For a native ELF linker, the directories in DT_RUNPATHor DT_RPATHo ashared library are searched or shared libraries needed by it. The DT_RPATHentries are ignored i DT_RUNPATHentries exist.

7. The de ault directories, normally ‘ /lib ’ and ‘/usr/lib ’.8. For a native linker on an ELF system, i the le ‘ /etc/ld.so.conf ’ exists,

the list o directories ound in that le.

I the required shared library is not ound, the linker will issue a warning andcontinue with the link.

-shared-Bshareable

Create a shared library. This is currently only supported on ELF, XCOFF

and SunOS plat orms. On SunOS, the linker will automatically create a sharedlibrary i the ‘ -e ’ option is not used and there are unde ned symbols in thelink.

--sort-common--sort-common=ascending--sort-common=descending

This option tells ld to sort the common symbols by alignment in ascendingor descending order when it places them in the appropriate output sections.

Page 28: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 28/122

22 The GNU linker

The symbol alignments considered are sixteen-byte or larger, eight-byte, our-byte, two-byte, and one-byte. This is to prevent gaps between symbols due toalignment constraints. I no sorting order is speci ed, then descending order isassumed.

--sort-section=nameThis option will apply SORT_BY_NAMEto all wildcard section patterns in thelinker script.

--sort-section=alignmentThis option will apply SORT_BY_ALIGNMENTto all wildcard section patterns inthe linker script.

--split-by-file[= size ]Similar to ‘--split-by-reloc ’ but creates a new output section or each inputle when size is reached. size de aults to a size o 1 i not given.

--split-by-reloc[= count ]Tries to creates extra sections in the output le so that no single output sectionin the le contains more than count relocations. This is use ul when generat-ing huge relocatable les or downloading into certain real time kernels with theCOFF object le ormat; since COFF cannot represent more than 65535 reloca-tions in a single section. Note that this will ail to work with object le ormatswhich do not support arbitrary sections. The linker will not split up individualinput sections or redistribution, so i a single input section contains more thancount relocations one output section will contain that many relocations. countde aults to a value o 32768.

--stats Compute and display statistics about the operation o the linker, such as exe-cution time and memory usage.

--sysroot= directory Use directory as the location o the sysroot, overriding the con gure-time de-ault. This option is only supported by linkers that were con gured using‘--with-sysroot ’.

--traditional-formatFor some targets, the output o ld is diferent in some ways rom the outputo some existing linker. This switch requests ld to use the traditional ormatinstead.For example, on SunOS, ld combines duplicate entries in the symbol stringtable. This can reduce the size o an output le with ull debugging in ormation

by over 30 percent. Un ortunately, the SunOS dbx program can not read theresulting program ( gdb has no trouble). The ‘ --traditional-format ’ switchtells ld to not combine duplicate entries.

--section-start= sectionname =org Locate a section in the output le at the absolute address given by org . Youmay use this option as many times as necessary to locate multiple sections in thecommand line. org must be a single hexadecimal integer; or compatibility withother linkers, you may omit the leading ‘ 0x ’ usually associated with hexadecimal

Page 29: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 29/122

Chapter 2: Invocation 23

values. Note: there should be no white space between sectionname , the equalssign (“=”), and org .

-Tbss= org

-Tdata= org -Ttext= org Same as ‘--section-start ’, with .bss , .data or .text as the sectionname .

-Ttext-segment= org When creating an ELF executable or shared object, it will set the address o the rst byte o the text segment.

--unresolved-symbols= methodDetermine how to handle unresolved symbols. There are our possible valuesor ‘ method ’:

‘ignore-all ’Do not report any unresolved symbols.

‘report-all ’Report all unresolved symbols. This is the de ault.

‘ignore-in-object-files ’Report unresolved symbols that are contained in shared libraries,but ignore them i they come rom regular object les.

‘ignore-in-shared-libs ’Report unresolved symbols that come rom regular object les, butignore them i they come rom shared libraries. This can be use ulwhen creating a dynamic binary and it is known that all the sharedlibraries that it should be re erencing are included on the linker’s

command line.The behaviour or shared libraries on their own can also be controlled by the‘--[no-]allow-shlib-undefined ’ option.Normally the linker will generate an error message or each reported unresolvedsymbol but the option ‘ --warn-unresolved-symbols ’ can change this to awarning.

--dll-verbose--verbose

Display the version number or ld and list the linker emulations supported.Display which input les can and cannot be opened. Display the linker scriptbeing used by the linker.

--version-script= version-scriptfileSpeci y the name o a version script to the linker. This is typically used whencreating shared libraries to speci y additional in ormation about the versionhierarchy or the library being created. This option is only ully supportedon ELF plat orms which support shared libraries; see Section 3.9 [VERSION],page 63. It is partially supported on PE plat orms, which can use version scriptsto lter symbol visibility in auto-export mode: any symbols marked ‘ local ’ inthe version script will not be exported. See Section 4.13 [WIN32], page 84.

Page 30: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 30/122

24 The GNU linker

--warn-commonWarn when a common symbol is combined with another common symbol orwith a symbol de nition. Unix linkers allow this somewhat sloppy practise,but linkers on some other operating systems do not. This option allows you tond potential problems rom combining global symbols. Un ortunately, someC libraries use this practise, so you may get some warnings about symbols inthe libraries as well as in your programs.There are three kinds o global symbols, illustrated here by C examples:

‘int i = 1; ’A de nition, which goes in the initialized data section o the outputle.

‘extern int i; ’An unde ned re erence, which does not allocate space. There mustbe either a de nition or a common symbol or the variable some-where.

‘int i; ’ A common symbol. I there are only (one or more) common symbolsor a variable, it goes in the uninitialized data area o the output le.The linker merges multiple common symbols or the same variableinto a single symbol. I they are o diferent sizes, it picks the largestsize. The linker turns a common symbol into a declaration, i thereis a de nition o the same variable.

The ‘--warn-common ’ option can produce ve kinds o warnings. Each warningconsists o a pair o lines: the rst describes the symbol just encountered, andthe second describes the previous symbol encountered with the same name.

One or both o the two symbols will be a common symbol.1. Turning a common symbol into a re erence, because there is already a

de nition or the symbol.file ( section ): warning: common of ‘ symbol ’

overridden by definitionfile ( section ): warning: defined here

2. Turning a common symbol into a re erence, because a later de nition orthe symbol is encountered. This is the same as the previous case, exceptthat the symbols are encountered in a diferent order.

file ( section ): warning: definition of ‘ symbol ’overriding common

file ( section ): warning: common is here

3. Merging a common symbol with a previous same-sized common symbol.file ( section ): warning: multiple common

of ‘ symbol ’file ( section ): warning: previous common is here

4. Merging a common symbol with a previous larger common symbol.file ( section ): warning: common of ‘ symbol ’

overridden by larger commonfile ( section ): warning: larger common is here

Page 31: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 31/122

Chapter 2: Invocation 25

5. Merging a common symbol with a previous smaller common symbol. Thisis the same as the previous case, except that the symbols are encounteredin a diferent order.

file ( section ): warning: common of ‘ symbol ’overriding smaller common

file ( section ): warning: smaller common is here

--warn-constructorsWarn i any global constructors are used. This is only use ul or a ew objectle ormats. For ormats like COFF or ELF, the linker can not detect the useo global constructors.

--warn-multiple-gpWarn i multiple global pointer values are required in the output le. This isonly meaning ul or certain processors, such as the Alpha. Speci cally, someprocessors put large-valued constants in a special section. A special register(the global pointer) points into the middle o this section, so that constantscan be loaded e ciently via a base-register relative addressing mode. Since theofset in base-register relative mode is xed and relatively small (e.g., 16 bits),this limits the maximum size o the constant pool. Thus, in large programs,it is o ten necessary to use multiple global pointer values in order to be ableto address all possible constants. This option causes a warning to be issuedwhenever this case occurs.

--warn-onceOnly warn once or each unde ned symbol, rather than once per module whichre ers to it.

--warn-section-alignWarn i the address o an output section is changed because o alignment.Typically, the alignment will be set by an input section. The address will onlybe changed i it not explicitly speci ed; that is, i the SECTIONS commanddoes not speci y a start address or the section (see Section 3.6 [SECTIONS],page 48).

--warn-shared-textrelWarn i the linker adds a DT TEXTREL to a shared object.

--warn-alternate-emWarn i an object has alternate ELF machine code.

--warn-unresolved-symbolsI the linker is going to report an unresolved symbol (see the option

‘--unresolved-symbols ’) it will normally generate an error. This optionmakes it generate a warning instead.

--error-unresolved-symbolsThis restores the linker’s de ault behaviour o generating errors when it is re-porting unresolved symbols.

--whole-archiveFor each archive mentioned on the command line a ter the ‘ --whole-archive ’option, include every object le in the archive in the link, rather than searching

Page 32: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 32/122

26 The GNU linker

the archive or the required object les. This is normally used to turn an archivele into a shared library, orcing every object to be included in the resultingshared library. This option may be used more than once.Two notes when using this option rom gcc: First, gcc doesn’t know about thisoption, so you have to use ‘ -Wl,-whole-archive ’. Second, don’t orget to use‘-Wl,-no-whole-archive ’ a ter your list o archives, because gcc will add itsown list o archives to your link and you may not want this ag to afect thoseas well.

--wrap= symbolUse a wrapper unction or symbol . Any unde ned re erence to symbol will beresolved to __wrap_ symbol . Any unde ned re erence to __real_ symbol willbe resolved to symbol .This can be used to provide a wrapper or a system unction. The wrapper unc-tion should be called __wrap_ symbol . I it wishes to call the system unction,it should call __real_ symbol .Here is a trivial example:

void *__wrap_malloc (size_t c){

printf ("malloc called with %zu\n", c);return __real_malloc (c);

}

I you link other code with this le using ‘ --wrap malloc ’, then all calls to malloc will call the unction __wrap_malloc instead. The call to __real_ malloc in __wrap_malloc will call the real malloc unction.You may wish to provide a __real_malloc unction as well, so that links with-out the ‘ --wrap ’ option will succeed. I you do this, you should not put thede nition o __real_malloc in the same le as __wrap_malloc ; i you do, theassembler may resolve the call be ore the linker has a chance to wrap it to malloc .

--eh-frame-hdrRequest creation o .eh_frame_hdr section and ELF PT_GNU_EH_FRAMEseg-ment header.

--enable-new-dtags--disable-new-dtags

This linker can create the new dynamic tags in ELF. But the older ELF systemsmay not understand them. I you speci y ‘ --enable-new-dtags ’, the dynamictags will be created as needed. I you speci y ‘ --disable-new-dtags ’, no newdynamic tags will be created. By de ault, the new dynamic tags are not created.Note that those options are only available or ELF systems.

--hash-size= number Set the de ault size o the linker’s hash tables to a prime number close to num-ber . Increasing this value can reduce the length o time it takes the linkerto per orm its tasks, at the expense o increasing the linker’s memory require-ments. Similarly reducing this value can reduce the memory requirements atthe expense o speed.

Page 33: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 33/122

Chapter 2: Invocation 27

--hash-style= styleSet the type o linker’s hash table(s). style can be either sysv or classic ELF.hash section, gnu or new style GNU .gnu.hash section or both or both theclassic ELF .hash and new style GNU .gnu.hash hash tables. The de ault issysv .

--reduce-memory-overheadsThis option reduces memory requirements at ld runtime, at the expense o linking speed. This was introduced to select the old O(n ^2) algorithm or linkmap le generation, rather than the new O(n) algorithm which uses about 40%more memory or symbol storage.Another efect o the switch is to set the de ault hash table size to 1021, whichagain saves memory at the cost o lengthening the linker’s run time. This isnot done however i the ‘ --hash-size ’ switch has been used.The ‘--reduce-memory-overheads ’ switch may be also be used to enable other

tradeofs in uture versions o the linker.--build-id--build-id= style

Request creation o .note.gnu.build-id ELF note section. The contents o the note are unique bits identi ying this linked le. style can be uuid to use128 random bits, sha1 to use a 160-bit SHA1 hash on the normative parts o the output contents, md5 to use a 128-bit MD5 hash on the normative parts o the output contents, or 0x hexstring to use a chosen bit string speci ed as aneven number o hexadecimal digits ( - and : characters between digit pairs areignored). I style is omitted, sha1 is used.The md5 and sha1 styles produces an identi er that is always the same in an

identical output le, but will be unique among all nonidentical output les. Itis not intended to be compared as a checksum or the le’s contents. A linkedle may be changed later by other tools, but the build ID bit string identi yingthe original linked le does not change.Passing none or style disables the setting rom any --build-id options earlieron the command line.

--no-poison-system-directoriesDo not warn or ‘ -L ’ options using system directories such as ‘ /usr/lib ’ whencross linking. This option is intended or use in chroot environments when suchdirectories contain the correct libraries or the target system rather than thehost.

--error-poison-system-directoriesGive an error instead o a warning or ‘ -L ’ options using system directorieswhen cross linking.

2.1.1 Options Specifc to i386 PE TargetsThe i386 PE linker supports the ‘ -shared ’ option, which causes the output to be a dynam-ically linked library (DLL) instead o a normal executable. You should name the output*.dll when you use this option. In addition, the linker ully supports the standard *.def

Page 34: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 34/122

28 The GNU linker

les, which may be speci ed on the linker command line like an object le (in act, it shouldprecede archives it exports symbols rom, to ensure that they get linked in, just like a normalobject le).

In addition to the options common to all targets, the i386 PE linker support additionalcommand line options that are speci c to the i386 PE target. Options that take values maybe separated rom their values by either a space or an equals sign.

--add-stdcall-aliasI given, symbols with a stdcall su x ( @nn ) will be exported as-is and also withthe su x stripped. [This option is speci c to the i386 PE targeted port o thelinker]

--base-file fileUse le as the name o a le in which to save the base addresses o all therelocations needed or generating DLLs with ‘ dlltool ’. [This is an i386 PEspeci c option]

--dll Create a DLL instead o a regular executable. You may also use ‘ -shared ’ orspeci y a LIBRARYin a given .def le. [This option is speci c to the i386 PEtargeted port o the linker]

--enable-long-section-names--disable-long-section-names

The PE variants o the Cof object ormat add an extension that permits theuse o section names longer than eight characters, the normal limit or Cof. Byde ault, these names are only allowed in object les, as ully-linked executableimages do not carry the Cof string table required to support the longer names.As a GNU extension, it is possible to allow their use in executable images as

well, or to (probably pointlessly!) disallow it in object les, by using these twooptions. Executable images generated with these long section names are slightlynon-standard, carrying as they do a string table, and may generate con usingoutput when examined with non-GNU PE-aware tools, such as le viewers anddumpers. However, GDB relies on the use o PE long section names to ndDwar -2 debug in ormation sections in an executable image at runtime, and soi neither option is speci ed on the command-line, ld will enable long sectionnames, overriding the de ault and technically correct behaviour, when it ndsthe presence o debug in ormation while linking an executable image and notstripping symbols. [This option is valid or all PE targeted ports o the linker]

--enable-stdcall-fixup--disable-stdcall-fixup

I the link nds a symbol that it cannot resolve, it will attempt to do “ uzzylinking” by looking or another de ned symbol that difers only in the ormato the symbol name (cdecl vs stdcall) and will resolve that symbol by link-ing to the match. For example, the unde ned symbol _foo might be linkedto the unction _foo@12 , or the unde ned symbol _bar@16 might be linkedto the unction _bar . When the linker does this, it prints a warning, sinceit normally should have ailed to link, but sometimes import libraries gener-ated rom third-party dlls may need this eature to be usable. I you speci y

Page 35: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 35/122

Chapter 2: Invocation 29

‘--enable-stdcall-fixup ’, this eature is ully enabled and warnings are notprinted. I you speci y ‘ --disable-stdcall-fixup ’, this eature is disabledand such mismatches are considered to be errors. [This option is speci c to thei386 PE targeted port o the linker]

--export-all-symbolsI given, all global symbols in the objects used to build a DLL will be exportedby the DLL. Note that this is the de ault i there otherwise wouldn’t beany exported symbols. When symbols are explicitly exported via DEF lesor implicitly exported via unction attributes, the de ault is to not exportanything else unless this option is given. Note that the symbols DllMain@12 ,DllEntryPoint@0 , DllMainCRTStartup@12 , and impure_ptr will not beautomatically exported. Also, symbols imported rom other DLLs will notbe re-exported, nor will symbols speci ying the DLL’s internal layout such asthose beginning with _head_ or ending with _iname . In addition, no symbolsrom libgcc , libstd++ , libmingw32 , or crtX.o will be exported. Symbolswhose names begin with __rtti_ or __builtin_ will not be exported, tohelp with C ++ DLLs. Finally, there is an extensive list o cygwin-privatesymbols that are not exported (obviously, this applies on when building DLLsor cygwin targets). These cygwin-excludes are: _cygwin_dll_entry@12 ,

_cygwin_crt0_common@8 , _cygwin_noncygwin_dll_entry@12 , _fmode ,_impure_ptr , cygwin_attach_dll , cygwin_premain0 , cygwin_premain1 ,cygwin_premain2 , cygwin_premain3 , and environ . [This option is speci c tothe i386 PE targeted port o the linker]

--exclude-symbols symbol , symbol ,...Speci es a list o symbols which should not be automatically exported. The

symbol names may be delimited by commas or colons. [This option is speci cto the i386 PE targeted port o the linker]

--file-alignmentSpeci y the le alignment. Sections in the le will always begin at le ofsetswhich are multiples o this number. This de aults to 512. [This option is speci cto the i386 PE targeted port o the linker]

--heap reserve--heap reserve , commit

Speci y the number o bytes o memory to reserve (and optionally commit) tobe used as heap or this program. The de ault is 1Mb reserved, 4K committed.

[This option is speci c to the i386 PE targeted port o the linker]--image-base value

Use value as the base address o your program or dll. This is the lowest memorylocation that will be used when your program or dll is loaded. To reduce theneed to relocate and improve per ormance o your dlls, each should have aunique base address and not overlap any other dlls. The de ault is 0x400000or executables, and 0x10000000 or dlls. [This option is speci c to the i386 PEtargeted port o the linker]

Page 36: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 36/122

30 The GNU linker

--kill-atI given, the stdcall su xes ( @nn ) will be stripped rom symbols be ore they areexported. [This option is speci c to the i386 PE targeted port o the linker]

--large-address-awareI given, the appropriate bit in the “Characteristics” eld o the COFF header isset to indicate that this executable supports virtual addresses greater than 2 gi-gabytes. This should be used in conjunction with the /3GB or /USERVA= value megabytes switch in the “[operating systems]” section o the BOOT.INI. Oth-erwise, this bit has no efect. [This option is speci c to PE targeted ports o the linker]

--major-image-version valueSets the major number o the “image version”. De aults to 1. [This option isspeci c to the i386 PE targeted port o the linker]

--major-os-version value

Sets the major number o the “os version”. De aults to 4. [This option isspeci c to the i386 PE targeted port o the linker]

--major-subsystem-version valueSets the major number o the “subsystem version”. De aults to 4. [This optionis speci c to the i386 PE targeted port o the linker]

--minor-image-version valueSets the minor number o the “image version”. De aults to 0. [This option isspeci c to the i386 PE targeted port o the linker]

--minor-os-version valueSets the minor number o the “os version”. De aults to 0. [This option is speci cto the i386 PE targeted port o the linker]

--minor-subsystem-version valueSets the minor number o the “subsystem version”. De aults to 0. [This optionis speci c to the i386 PE targeted port o the linker]

--output-def fileThe linker will create the le le which will contain a DEF le correspondingto the DLL the linker is generating. This DEF le (which should be called*.def ) may be used to create an import library with dlltool or may be usedas a re erence to automatically or implicitly exported symbols. [This option isspeci c to the i386 PE targeted port o the linker]

--out-implib file

The linker will create the le le which will contain an import lib correspondingto the DLL the linker is generating. This import lib (which should be called*.dll.a or *.a may be used to link clients against the generated DLL; thisbehaviour makes it possible to skip a separate dlltool import library creationstep. [This option is speci c to the i386 PE targeted port o the linker]

--enable-auto-image-baseAutomatically choose the image base or DLLs, unless one is speci ed usingthe --image-base argument. By using a hash generated rom the dllname to

Page 37: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 37/122

Page 38: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 38/122

32 The GNU linker

extern type extern_array[];extern_array[1] -->

{ volatile type *t=extern_array; t[1] }

or extern type extern_array[];extern_array[1] -->

{ volatile int t=1; extern_array[t] }For structs (and most other multiword data types) the only option is to makethe struct itsel (or the long long, or the ...) variable:

extern struct s extern_struct;extern_struct.field -->

{ volatile struct s *t=&extern_struct; t->field }or

extern long long extern_ll;extern_ll -->

{ volatile long long * local_ll=&extern_ll; *local_ll }A third method o dealing with this di culty is to abandon ’auto-import’ orthe ofending symbol and mark it with __declspec(dllimport) . However,in practise that requires using compile-time #de nes to indicate whether youare building a DLL, building client code that will link to the DLL, or merelybuilding/linking to a static library. In making the choice between the variousmethods o resolving the ’direct address with constant ofset’ problem, youshould consider typical real-world usage:Original:

--foo.hextern int arr[];--foo.c#include "foo.h"void main(int argc, char **argv){

printf("%d\n",arr[1]);}

Solution 1:--foo.hextern int arr[];--foo.c#include "foo.h"

void main(int argc, char **argv){/* This workaround is for win32 and cygwin; do not "optimize" */volatile int *parr = arr;printf("%d\n",parr[1]);

}Solution 2:

--foo.h/* Note: auto-export is assumed (no __declspec(dllexport)) */

Page 39: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 39/122

Chapter 2: Invocation 33

#if (defined(_WIN32) || defined(__CYGWIN__)) && \!(defined(FOO_BUILD_DLL) || defined(FOO_STATIC))

#define FOO_IMPORT __declspec(dllimport)#else#define FOO_IMPORT#endifextern FOO_IMPORT int arr[];--foo.c#include "foo.h"void main(int argc, char **argv){

printf("%d\n",arr[1]);}

A ourth way to avoid this problem is to re-code your library to use a unc-tional inter ace rather than a data inter ace or the ofending variables (e.g.set oo() and get oo() accessor unctions). [This option is speci c to the i386PE targeted port o the linker]

--disable-auto-importDo not attempt to do sophisticated linking o _symbol to __imp__symbol orDATA imports rom DLLs. [This option is speci c to the i386 PE targeted porto the linker]

--enable-runtime-pseudo-relocI your code contains expressions described in –enable-auto-import section, thatis, DATA imports rom DLL with non-zero ofset, this switch will create a vectoro ’runtime pseudo relocations’ which can be used by runtime environment toadjust re erences to such data in your client code. [This option is speci c to

the i386 PE targeted port o the linker]

--disable-runtime-pseudo-relocDo not create pseudo relocations or non-zero ofset DATA imports rom DLLs.This is the de ault. [This option is speci c to the i386 PE targeted port o thelinker]

--enable-extra-pe-debugShow additional debug in o related to auto-import symbol thunking. [Thisoption is speci c to the i386 PE targeted port o the linker]

--section-alignment

Sets the section alignment. Sections in memory will always begin at addresseswhich are a multiple o this number. De aults to 0x1000. [This option is speci cto the i386 PE targeted port o the linker]

--stack reserve--stack reserve , commit

Speci y the number o bytes o memory to reserve (and optionally commit) tobe used as stack or this program. The de ault is 2Mb reserved, 4K committed.[This option is speci c to the i386 PE targeted port o the linker]

Page 40: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 40/122

34 The GNU linker

--subsystem which--subsystem which : major --subsystem which : major . minor

Speci es the subsystem under which your program will execute. The legalvalues or which are native , windows , console , posix , and xbox . You mayoptionally set the subsystem version also. Numeric values are also accepted orwhich . [This option is speci c to the i386 PE targeted port o the linker]The ollowing options set ags in the DllCharacteristics eld o the PE leheader: [These options are speci c to PE targeted ports o the linker]

--dynamicbaseThe image base address may be relocated using address space layout random-ization (ASLR). This eature was introduced with MS Windows Vista or i386PE targets.

--forceintegCode integrity checks are en orced.

--nxcompatThe image is compatible with the Data Execution Prevention. This eature wasintroduced with MS Windows XP SP2 or i386 PE targets.

--no-isolationAlthough the image understands isolation, do not isolate the image.

--no-seh The image does not use SEH. No SE handler may be called rom this image.

--no-bindDo not bind this image.

--wdmdriverThe driver uses the MS Windows Driver Model.

--tsawareThe image is Terminal Server aware.

2.1.2 Options specifc to Motorola 68HC11 and 68HC12 targetsThe 68HC11 and 68HC12 linkers support speci c options to control the memory bankswitching mapping and trampoline code generation.

--no-trampoline

This option disables the generation o trampoline. By de ault a trampoline isgenerated or each ar unction which is called using a jsr instruction (thishappens when a pointer to a ar unction is taken).

--bank-window nameThis option indicates to the linker the name o the memory region in the‘MEMORY’ speci cation that describes the memory bank window. The de ni-tion o such region is then used by the linker to compute paging and addresseswithin the memory window.

Page 41: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 41/122

Chapter 2: Invocation 35

2.1.3 Options specifc to Motorola 68K targetThe ollowing options are supported to control handling o GOT generation when linkingor 68K targets.

--got= typeThis option tells the linker which GOT generation scheme to use. type shouldbe one o ‘single ’, ‘negative ’, ‘ multigot ’ or ‘target ’. For more in ormationre er to the In o entry or ‘ ld ’.

2.2 Environment VariablesYou can change the behaviour o ld with the environment variables GNUTARGET,LDEMULATIONand COLLECT_NO_DEMANGLE.GNUTARGETdetermines the input- le object ormat i you don’t use ‘ -b ’ (or its synonym‘--format ’). Its value should be one o the BFD names or an input ormat (see Chapter 5[BFD], page 93). I there is no GNUTARGETin the environment, ld uses the natural ormato the target. I GNUTARGETis set to default then BFD attempts to discover the inputormat by examining binary input les; this method o ten succeeds, but there are potentialambiguities, since there is no method o ensuring that the magic number used to speci yobject- le ormats is unique. However, the con guration procedure or BFD on each systemplaces the conventional ormat or that system rst in the search-list, so ambiguities areresolved in avor o convention.LDEMULATIONdetermines the de ault emulation i you don’t use the ‘ -m’ option. The emula-tion can afect various aspects o linker behaviour, particularly the de ault linker script. Youcan list the available emulations with the ‘ --verbose ’ or ‘-V’ options. I the ‘ -m’ option isnot used, and the LDEMULATIONenvironment variable is not de ned, the de ault emulationdepends upon how the linker was con gured.

Normally, the linker will de ault to demangling symbols. However, i COLLECT_NO_DEMANGLEis set in the environment, then it will de ault to not demangling symbols. This environmentvariable is used in a similar ashion by the gcc linker wrapper program. The de ault maybe overridden by the ‘ --demangle ’ and ‘--no-demangle ’ options.

Page 42: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 42/122

Page 43: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 43/122

Chapter 3: Linker Scripts 37

3 Linker ScriptsEvery link is controlled by a linker script . This script is written in the linker commandlanguage.The main purpose o the linker script is to describe how the sections in the input les shouldbe mapped into the output le, and to control the memory layout o the output le. Mostlinker scripts do nothing more than this. However, when necessary, the linker script can alsodirect the linker to per orm many other operations, using the commands described below.The linker always uses a linker script. I you do not supply one yoursel , the linker will usea de ault script that is compiled into the linker executable. You can use the ‘ --verbose ’command line option to display the de ault linker script. Certain command line options,such as ‘-r ’ or ‘-N’, will afect the de ault linker script.You may supply your own linker script by using the ‘ -T ’ command line option. When youdo this, your linker script will replace the de ault linker script.

You may also use linker scripts implicitly by naming them as input les to the linker, asthough they were les to be linked. See Section 3.11 [Implicit Linker Scripts], page 74 .

3.1 Basic Linker Script ConceptsWe need to de ne some basic concepts and vocabulary in order to describe the linker scriptlanguage.The linker combines input les into a single output le. The output le and each input leare in a special data ormat known as an object le ormat . Each le is called an objectle . The output le is o ten called an executable , but or our purposes we will also call itan object le. Each object le has, among other things, a list o sections . We sometimesre er to a section in an input le as an input section ; similarly, a section in the output leis an output section .Each section in an object le has a name and a size. Most sections also have an associatedblock o data, known as the section contents . A section may be marked as loadable , whichmean that the contents should be loaded into memory when the output le is run. A sectionwith no contents may be allocatable , which means that an area in memory should be setaside, but nothing in particular should be loaded there (in some cases this memory mustbe zeroed out). A section which is neither loadable nor allocatable typically contains somesort o debugging in ormation.Every loadable or allocatable output section has two addresses. The rst is the VMA , orvirtual memory address. This is the address the section will have when the output le isrun. The second is the LMA , or load memory address. This is the address at which the

section will be loaded. In most cases the two addresses will be the same. An example o when they might be diferent is when a data section is loaded into ROM, and then copiedinto RAM when the program starts up (this technique is o ten used to initialize globalvariables in a ROM based system). In this case the ROM address would be the LMA, andthe RAM address would be the VMA.You can see the sections in an object le by using the objdump program with the ‘ -h ’ option.Every object le also has a list o symbols , known as the symbol table . A symbol may bede ned or unde ned. Each symbol has a name, and each de ned symbol has an address,

Page 44: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 44/122

Page 45: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 45/122

Chapter 3: Linker Scripts 39

The second line de nes an output section, ‘ .text ’. The colon is required syntax which maybe ignored or now. Within the curly braces a ter the output section name, you list thenames o the input sections which should be placed into this output section. The ‘ *’ is awildcard which matches any le name. The expression ‘ *(.text) ’ means all ‘.text ’ inputsections in all input les.Since the location counter is ‘ 0x10000 ’ when the output section ‘ .text ’ is de ned, the linkerwill set the address o the ‘ .text ’ section in the output le to be ‘ 0x10000 ’.

The remaining lines de ne the ‘ .data ’ and ‘.bss ’ sections in the output le. The linkerwill place the ‘.data ’ output section at address ‘ 0x8000000 ’. A ter the linker places the‘.data ’ output section, the value o the location counter will be ‘ 0x8000000 ’ plus the size o the ‘.data ’ output section. The efect is that the linker will place the ‘ .bss ’ output sectionimmediately a ter the ‘ .data ’ output section in memory.

The linker will ensure that each output section has the required alignment, by increasingthe location counter i necessary. In this example, the speci ed addresses or the ‘ .text ’

and ‘.data ’ sections will probably satis y any alignment constraints, but the linker mayhave to create a small gap between the ‘ .data ’ and ‘.bss ’ sections.

That’s it! That’s a simple and complete linker script.

3.4 Simple Linker Script CommandsIn this section we describe the simple linker script commands.

3.4.1 Setting the Entry PointThe rst instruction to execute in a program is called the entry point . You can use theENTRYlinker script command to set the entry point. The argument is a symbol name:

ENTRY(symbol )There are several ways to set the entry point. The linker will set the entry point by tryingeach o the ollowing methods in order, and stopping when one o them succeeds:

• the ‘-e ’ entry command-line option;• the ENTRY(symbol ) command in a linker script;• the value o the symbol start , i de ned;• the address o the rst byte o the ‘ .text ’ section, i present;• The address 0.

3.4.2 Commands Dealing with FilesSeveral linker script commands deal with les.

INCLUDEfilenameInclude the linker script lename at this point. The le will be searched or inthe current directory, and in any directory speci ed with the ‘ -L ’ option. Youcan nest calls to INCLUDEup to 10 levels deep.You can place INCLUDEdirectives at the top level, in MEMORYor SECTIONScom-mands, or in output section descriptions.

Page 46: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 46/122

40 The GNU linker

INPUT( file , file , ...)INPUT( file file ...)

The INPUT command directs the linker to include the named les in the link,as though they were named on the command line.For example, i you always want to include ‘ subr.o ’ any time you do a link,but you can’t be bothered to put it on every link command line, then you canput ‘INPUT (subr.o) ’ in your linker script.In act, i you like, you can list all o your input les in the linker script, andthen invoke the linker with nothing but a ‘ -T ’ option.In case a sysroot pre x is con gured, and the lename starts with the ‘ / ’character, and the script being processed was located inside the sysroot pre x ,the lename will be looked or in the sysroot pre x . Otherwise, the linker willtry to open the le in the current directory. I it is not ound, the linker willsearch through the archive library search path. See the description o ‘ -L ’ inSection 2.1 [Command Line Options], page 3 .I you use ‘INPUT (-l file ) ’, ld will trans orm the name to lib file .a , as withthe command line argument ‘ -l ’.When you use the INPUT command in an implicit linker script, the les will beincluded in the link at the point at which the linker script le is included. Thiscan afect archive searching.

GROUP(file , file , ...)GROUP(file file ...)

The GROUPcommand is like INPUT, except that the named les should all bearchives, and they are searched repeatedly until no new unde ned re erencesare created. See the description o ‘ -( ’ in Section 2.1 [Command Line Options],

page 3.AS_NEEDED(file , file , ...)AS_NEEDED(file file ...)

This construct can appear only inside o the INPUT or GROUPcommands, amongother lenames. The les listed will be handled as i they appear directly in theINPUT or GROUPcommands, with the exception o ELF shared libraries, thatwill be added only when they are actually needed. This construct essentiallyenables ‘--as-needed ’ option or all the les listed inside o it and restoresprevious ‘--as-needed ’ resp. ‘--no-as-needed ’ setting a terwards.

OUTPUT(filename )The OUTPUTcommand names the output le. Using OUTPUT(filename ) in

the linker script is exactly like using ‘ -o filename ’ on the command line (seeSection 2.1 [Command Line Options], page 3 ). I both are used, the commandline option takes precedence.You can use the OUTPUTcommand to de ne a de ault name or the output leother than the usual de ault o ‘ a.out ’.

SEARCH_DIR( path )The SEARCH_DIRcommand adds path to the list o paths where ld looks orarchive libraries. Using SEARCH_DIR( path ) is exactly like using ‘-L path ’ on

Page 47: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 47/122

Chapter 3: Linker Scripts 41

the command line (see Section 2.1 [Command Line Options], page 3 ). I bothare used, then the linker will search both paths. Paths speci ed using thecommand line option are searched rst.

STARTUP(filename )The STARTUPcommand is just like the INPUT command, except that lename will become the rst input le to be linked, as though it were speci ed rst onthe command line. This may be use ul when using a system in which the entrypoint is always the start o the rst le.

3.4.3 Commands Dealing with Object File FormatsA couple o linker script commands deal with object le ormats.

OUTPUT_FORMAT(bfdname )OUTPUT_FORMAT(default , big , little )

The OUTPUT_FORMATcommand names the BFD ormat to use or the output

le (see Chapter 5 [BFD], page 93 ). Using OUTPUT_FORMAT(bfdname ) is exactlylike using ‘--oformat bfdname ’ on the command line (see Section 2.1 [Com-mand Line Options], page 3 ). I both are used, the command line option takesprecedence.You can use OUTPUT_FORMATwith three arguments to use diferent ormats basedon the ‘-EB’ and ‘-EL ’ command line options. This permits the linker script toset the output ormat based on the desired endianness.I neither ‘ -EB’ nor ‘-EL ’ are used, then the output ormat will be the rst argu-ment, de ault . I ‘-EB’ is used, the output ormat will be the second argument,big . I ‘-EL ’ is used, the output ormat will be the third argument, little .For example, the de ault linker script or the MIPS ELF target uses this com-

mand:OUTPUT_FORMAT(elf32-bigmips, elf32-bigmips, elf32-littlemips)

This says that the de ault ormat or the output le is ‘ elf32-bigmips ’, but i the user uses the ‘ -EL ’ command line option, the output le will be created inthe ‘elf32-littlemips ’ ormat.

TARGET(bfdname )The TARGETcommand names the BFD ormat to use when reading input les.It afects subsequent INPUT and GROUPcommands. This command is like using‘-b bfdname ’ on the command line (see Section 2.1 [Command Line Options],page 3). I the TARGETcommand is used but OUTPUT_FORMATis not, then thelast TARGETcommand is also used to set the ormat or the output le. See

Chapter 5 [BFD], page 93 .

3.4.4 Assign alias names to memory regionsAlias names can be added to existing memory regions created with the Section 3.7 [MEM-ORY], page 60 command. Each name corresponds to at most one memory region.

REGION_ALIAS(alias , region )

The REGION_ALIASunction creates an alias name alias or the memory region region . Thisallows a exible mapping o output sections to memory regions. An example ollows.

Page 48: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 48/122

42 The GNU linker

Suppose we have an application or embedded systems which come with various memorystorage devices. All have a general purpose, volatile memory RAMthat allows code executionor data storage. Some may have a read-only, non-volatile memory ROMthat allows codeexecution and read-only data access. The last variant is a read-only, non-volatile memoryROM2with read-only data access and no code execution capability. We have our outputsections:

• .text program code;• .rodata read-only data;• .data read-write initialized data;• .bss read-write zero initialized data.

The goal is to provide a linker command le that contains a system independent partde ning the output sections and a system dependent part mapping the output sectionsto the memory regions available on the system. Our embedded systems come with threediferent memory setups A, B and C:Section Variant A Variant B Variant C.text RAM ROM ROM.rodata RAM ROM ROM2.data RAM RAM/ROM RAM/ROM2.bss RAM RAM RAMThe notation RAM/ROMor RAM/ROM2means that this section is loaded into region ROMorROM2respectively. Please note that the load address o the .data section starts in all threevariants at the end o the .rodata section.The base linker script that deals with the output sections ollows. It includes the systemdependent linkcmds.memory le that describes the memory layout:

INCLUDE linkcmds.memory

SECTIONS{

.text :{

*(.text)} > REGION_TEXT

.rodata :{

*(.rodata)rodata_end = .;

} > REGION_RODATA.data : AT (rodata_end)

{data_start = .;*(.data)

} > REGION_DATAdata_size = SIZEOF(.data);data_load_start = LOADADDR(.data);.bss :

{*(.bss)

} > REGION_BSS}

Page 49: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 49/122

Page 50: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 50/122

44 The GNU linker

}

3.4.5 Other Linker Script CommandsThere are a ew other linker scripts commands.

ASSERT(exp , message )Ensure that exp is non-zero. I it is zero, then exit the linker with an errorcode, and print message .

EXTERN(symbol symbol ...)Force symbol to be entered in the output le as an unde ned symbol. Doing thismay, or example, trigger linking o additional modules rom standard libraries.You may list several symbol s or each EXTERN, and you may use EXTERNmultipletimes. This command has the same efect as the ‘ -u ’ command-line option.

FORCE_COMMON_ALLOCATIONThis command has the same efect as the ‘ -d ’ command-line option: to make

ld assign space to common symbols even i a relocatable output le is speci ed(‘-r ’).

INHIBIT_COMMON_ALLOCATIONThis command has the same efect as the ‘ --no-define-common ’ command-lineoption: to make ld omit the assignment o addresses to common symbols evenor a non-relocatable output le.

INSERT [ AFTER | BEFORE ]output_sectionThis command is typically used in a script speci ed by ‘ -T ’ to augment thede ault SECTIONSwith, or example, overlays. It inserts all prior linker scriptstatements a ter (or be ore) output section , and also causes ‘-T ’ to not overridethe de ault linker script. The exact insertion point is as or orphan sections.See Section 3.10.5 [Location Counter], page 67 . The insertion happens a ter thelinker has mapped input sections to output sections. Prior to the insertion, since‘-T ’ scripts are parsed be ore the de ault linker script, statements in the ‘ -T ’script occur be ore the de ault linker script statements in the internal linkerrepresentation o the script. In particular, input section assignments will bemade to ‘ -T ’ output sections be ore those in the de ault script. Here is anexample o how a ‘-T ’ script using INSERT might look:

SECTIONS{

OVERLAY :{

.ov1 { ov1*(.text) }

.ov2 { ov2*(.text) }}

}INSERT AFTER .text;

NOCROSSREFS(section section ...)This command may be used to tell ld to issue an error about any re erencesamong certain output sections.In certain types o programs, particularly on embedded systems when usingoverlays, when one section is loaded into memory, another section will not be.

Page 51: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 51/122

Chapter 3: Linker Scripts 45

Any direct re erences between the two sections would be errors. For example,it would be an error i code in one section called a unction de ned in the othersection.

The NOCROSSREFScommand takes a list o output section names. I ld detectsany cross re erences between the sections, it reports an error and returns anon-zero exit status. Note that the NOCROSSREFScommand uses output sectionnames, not input section names.

OUTPUT_ARCH(bfdarch )Speci y a particular output machine architecture. The argument is one o thenames used by the BFD library (see Chapter 5 [BFD], page 93 ). You can seethe architecture o an object le by using the objdump program with the ‘ -f ’option.

3.5 Assigning Values to SymbolsYou may assign a value to a symbol in a linker script. This will de ne the symbol and placeit into the symbol table with a global scope.

3.5.1 Simple AssignmentsYou may assign to a symbol using any o the C assignment operators:

symbol = expression ;symbol += expression ;symbol -= expression ;symbol *= expression ;symbol /= expression ;symbol <<= expression ;symbol >>= expression ;symbol &= expression ;symbol |= expression ;

The rst case will de ne symbol to the value o expression . In the other cases, symbol mustalready be de ned, and the value will be adjusted accordingly.The special symbol name ‘ . ’ indicates the location counter. You may only use this withina SECTIONScommand. See Section 3.10.5 [Location Counter], page 67 .The semicolon a ter expression is required.Expressions are de ned below; see Section 3.10 [Expressions], page 66 .You may write symbol assignments as commands in their own right, or as statements within

a SECTIONScommand, or as part o an output section description in a SECTIONScommand.The section o the symbol will be set rom the section o the expression; or more in ormation,see Section 3.10.8 [Expression Section], page 70 .Here is an example showing the three diferent places that symbol assignments may be used:

floating_point = 0;SECTIONS{

.text :{

Page 52: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 52/122

Page 53: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 53/122

Chapter 3: Linker Scripts 47

extern int foo;

But in the linker script it might be de ned as:_foo = 1000;

In the remaining examples however it is assumed that no name trans ormation has takenplace.When a symbol is declared in a high level language such as C, two things happen. The rstis that the compiler reserves enough space in the program’s memory to hold the value o the symbol. The second is that the compiler creates an entry in the program’s symbol tablewhich holds the symbol’s address . ie the symbol table contains the address o the blocko memory holding the symbol’s value. So or example the ollowing C declaration, at lescope:

int foo = 1000;

creates a entry called ‘ foo ’ in the symbol table. This entry holds the address o an ‘ int ’sized block o memory where the number 1000 is initially stored.When a program re erences a symbol the compiler generates code that rst accesses thesymbol table to nd the address o the symbol’s memory block and then code to read thevalue rom that memory block. So:

foo = 1;

looks up the symbol ‘foo ’ in the symbol table, gets the address associated with this symboland then writes the value 1 into that address. Whereas:

int * a = & foo;

looks up the symbol ‘ foo ’ in the symbol table, gets it address and then copies this addressinto the block o memory associated with the variable ‘ a ’.Linker scripts symbol declarations, by contrast, create an entry in the symbol table but donot assign any memory to them. Thus they are an address without a value. So or examplethe linker script de nition:

foo = 1000;

creates an entry in the symbol table called ‘ foo ’ which holds the address o memory location1000, but nothing special is stored at address 1000. This means that you cannot access thevalue o a linker script de ned symbol - it has no value - all you can do is access the address o a linker script de ned symbol.Hence when you are using a linker script de ned symbol in source code you should alwaystake the address o the symbol, and never attempt to use its value. For example supposeyou want to copy the contents o a section o memory called .ROM into a section called.FLASH and the linker script contains these declarations:

start_of_ROM = .ROM;end_of_ROM = .ROM + sizeof (.ROM) - 1;start_of_FLASH = .FLASH;

Then the C source code to per orm the copy would be:extern char start_of_ROM, end_of_ROM, start_of_FLASH;

memcpy (& start_of_FLASH, & start_of_ROM, & end_of_ROM - & start_of_ROM);

Note the use o the ‘ &’ operators. These are correct.

Page 54: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 54/122

Page 55: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 55/122

Chapter 3: Linker Scripts 49

• a special output section keyword (see Section 3.6.6 [Output Section Keywords], page 54 )

3.6.2 Output Section Name

The name o the output section is section . section must meet the constraints o your outputormat. In ormats which only support a limited number o sections, such as a.out , thename must be one o the names supported by the ormat ( a.out , or example, allows only‘.text ’, ‘.data ’ or ‘.bss ’). I the output ormat supports any number o sections, but withnumbers and not names (as is the case or Oasys), the name should be supplied as a quotednumeric string. A section name may consist o any sequence o characters, but a namewhich contains any unusual characters such as commas must be quoted.The output section name ‘ /DISCARD/ ’ is special; Section 3.6.7 [Output Section Discarding],page 55.

3.6.3 Output Section AddressThe address is an expression or the VMA (the virtual memory address) o the outputsection. I you do not provide address , the linker will set it based on region i present, orotherwise based on the current value o the location counter.I you provide address , the address o the output section will be set to precisely that. I you provide neither address nor region , then the address o the output section will be setto the current value o the location counter aligned to the alignment requirements o theoutput section. The alignment requirement o the output section is the strictest alignmento any input section contained within the output section.For example,

.text . : { *(.text) }

and.text : { *(.text) }

are subtly diferent. The rst will set the address o the ‘ .text ’ output section to thecurrent value o the location counter. The second will set it to the current value o thelocation counter aligned to the strictest alignment o a ‘ .text ’ input section.The address may be an arbitrary expression; Section 3.10 [Expressions], page 66. Forexample, i you want to align the section on a 0x10 byte boundary, so that the lowest ourbits o the section address are zero, you could do something like this:

.text ALIGN(0x10) : { *(.text) }

This works because ALIGNreturns the current location counter aligned upward to the spec-i ed value.

Speci ying address or a section will change the value o the location counter, provided thatthe section is non-empty. (Empty sections are ignored).

3.6.4 Input Section DescriptionThe most common output section command is an input section description.The input section description is the most basic linker script operation. You use outputsections to tell the linker how to lay out your program in memory. You use input sectiondescriptions to tell the linker how to map the input les into your memory layout.

Page 56: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 56/122

50 The GNU linker

3.6.4.1 Input Section BasicsAn input section description consists o a le name optionally ollowed by a list o sectionnames in parentheses.

The le name and the section name may be wildcard patterns, which we describe urtherbelow (see Section 3.6.4.2 [Input Section Wildcards], page 51 ).The most common input section description is to include all input sections with a particularname in the output section. For example, to include all input ‘ .text ’ sections, you wouldwrite:

*(.text)

Here the ‘*’ is a wildcard which matches any le name. To exclude a list o les rommatching the le name wildcard, EXCLUDE FILE may be used to match all les exceptthe ones speci ed in the EXCLUDE FILE list. For example:

*(EXCLUDE_FILE (*crtend.o *otherfile.o) .ctors)

will cause all .ctors sections rom all les except ‘ crtend.o ’ and ‘otherfile.o ’ to be in-cluded.There are two ways to include more than one section:

*(.text .rdata)*(.text) *(.rdata)

The diference between these is the order in which the ‘ .text ’ and ‘.rdata ’ input sectionswill appear in the output section. In the rst example, they will be intermingled, appearingin the same order as they are ound in the linker input. In the second example, all ‘ .text ’input sections will appear rst, ollowed by all ‘ .rdata ’ input sections.You can speci y a le name to include sections rom a particular le. You would do this i one or more o your les contain special data that needs to be at a particular location inmemory. For example:

data.o(.data)

You can also speci y les within archives by writing a pattern matching the archive, a colon,then the pattern matching the le, with no whitespace around the colon.

‘archive:file ’matches le within archive

‘archive: ’matches the whole archive

‘:file ’ matches le but not one in an archive

Either one or both o ‘ archive ’ and ‘file ’ can contain shell wildcards. On DOS based lesystems, the linker will assume that a single letter ollowed by a colon is a drive speci er,so ‘c:myfile.o ’ is a simple le speci cation, not ‘ myfile.o ’ within an archive called ‘ c ’.‘archive:file ’ lespecs may also be used within an EXCLUDE_FILElist, but may not appearin other linker script contexts. For instance, you cannot extract a le rom an archive byusing ‘archive:file ’ in an INPUT command.I you use a le name without a list o sections, then all sections in the input le willbe included in the output section. This is not commonly done, but it may by use ul onoccasion. For example:

Page 57: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 57/122

Chapter 3: Linker Scripts 51

data.o

When you use a le name which is not an ‘ archive:file ’ speci er and does not containany wild card characters, the linker will rst see i you also speci ed the le name on the

linker command line or in an INPUT command. I you did not, the linker will attempt toopen the le as an input le, as though it appeared on the command line. Note that thisdifers rom an INPUT command, because the linker will not search or the le in the archivesearch path.

3.6.4.2 Input Section Wildcard PatternsIn an input section description, either the le name or the section name or both may bewildcard patterns.The le name o ‘ *’ seen in many examples is a simple wildcard pattern or the le name.The wildcard patterns are like those used by the Unix shell.

‘*’ matches any number o characters

‘? ’ matches any single character

‘[ chars ] ’ matches a single instance o any o the chars ; the ‘- ’ character may be used tospeci y a range o characters, as in ‘ [a-z] ’ to match any lower case letter

‘\ ’ quotes the ollowing character

When a le name is matched with a wildcard, the wildcard characters will not match a ‘ / ’character (used to separate directory names on Unix). A pattern consisting o a single ‘ *’character is an exception; it will always match any le name, whether it contains a ‘ / ’ ornot. In a section name, the wildcard characters will match a ‘ / ’ character.File name wildcard patterns only match les which are explicitly speci ed on the command

line or in an INPUT command. The linker does not search directories to expand wildcards.I a le name matches more than one wildcard pattern, or i a le name appears explicitlyand is also matched by a wildcard pattern, the linker will use the rst match in the linkerscript. For example, this sequence o input section descriptions is probably in error, becausethe ‘data.o ’ rule will not be used:

.data : { *(.data) }

.data1 : { data.o(.data) }

Normally, the linker will place les and sections matched by wildcards in the order in whichthey are seen during the link. You can change this by using the SORT_BY_NAMEkeyword,which appears be ore a wildcard pattern in parentheses (e.g., SORT_BY_NAME(.text*) ).When the SORT_BY_NAMEkeyword is used, the linker will sort the les or sections intoascending order by name be ore placing them in the output le.SORT_BY_ALIGNMENTis very similar to SORT_BY_NAME. The diference is SORT_BY_ALIGNMENTwill sort sections into ascending order by alignment be ore placing them in the output le.SORT is an alias or SORT_BY_NAME.When there are nested section sorting commands in linker script, there can be at most 1level o nesting or section sorting commands.

1. SORT_BY_NAME(SORT_BY_ALIGNMENT(wildcard section pattern)). It will sort the inputsections by name rst, then by alignment i 2 sections have the same name.

Page 58: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 58/122

52 The GNU linker

2. SORT_BY_ALIGNMENT(SORT_BY_NAME(wildcard section pattern)). It will sort the inputsections by alignment rst, then by name i 2 sections have the same alignment.

3. SORT_BY_NAME(SORT_BY_NAME(wildcard section pattern)) is treated the same as SORT_

BY_NAME(wildcard section pattern).4. SORT_BY_ALIGNMENT(SORT_BY_ALIGNMENT(wildcard section pattern)) is treated thesame as SORT_BY_ALIGNMENT(wildcard section pattern).

5. All other nested section sorting commands are invalid.

When both command line section sorting option and linker script section sorting commandare used, section sorting command always takes precedence over the command line option.I the section sorting command in linker script isn’t nested, the command line option willmake the section sorting command to be treated as nested sorting command.

1. SORT_BY_NAME(wildcard section pattern ) with ‘ --sort-sections alignment ’ is equiv-alent to SORT_BY_NAME(SORT_BY_ALIGNMENT(wildcard section pattern)).

2. SORT_BY_ALIGNMENT(wildcard section pattern) with ‘ --sort-section name ’ is equiv-alent to SORT_BY_ALIGNMENT(SORT_BY_NAME(wildcard section pattern)).

I the section sorting command in linker script is nested, the command line option will beignored.I you ever get con used about where input sections are going, use the ‘ -M’ linker option togenerate a map le. The map le shows precisely how input sections are mapped to outputsections.This example shows how wildcard patterns might be used to partition les. This linkerscript directs the linker to place all ‘ .text ’ sections in ‘.text ’ and all ‘.bss ’ sections in‘.bss ’. The linker will place the ‘ .data ’ section rom all les beginning with an upper casecharacter in ‘ .DATA’; or all other les, the linker will place the ‘ .data ’ section in ‘.data ’.

SECTIONS {.text : { *(.text) }.DATA : { [A-Z]*(.data) }.data : { *(.data) }.bss : { *(.bss) }

}

3.6.4.3 Input Section or Common SymbolsA special notation is needed or common symbols, because in many object le ormatscommon symbols do not have a particular input section. The linker treats common symbolsas though they are in an input section named ‘ COMMON’.You may use le names with the ‘ COMMON’ section just as with any other input sections.

You can use this to place common symbols rom a particular input le in one section whilecommon symbols rom other input les are placed in another section.In most cases, common symbols in input les will be placed in the ‘ .bss ’ section in theoutput le. For example:

.bss { *(.bss) *(COMMON) }

Some object le ormats have more than one type o common symbol. For example, theMIPS ELF object le ormat distinguishes standard common symbols and small commonsymbols. In this case, the linker will use a diferent special section name or other types o

Page 59: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 59/122

Page 60: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 60/122

54 The GNU linker

32 bits. In this case QUADstores a 32 bit value zero extended to 64 bits, and SQUADstoresa 32 bit value sign extended to 64 bits.I the object le ormat o the output le has an explicit endianness, which is the normal

case, the value will be stored in that endianness. When the object le ormat does not havean explicit endianness, as is true o , or example, S-records, the value will be stored in theendianness o the rst input object le.Note—these commands only work inside a section description and not between them, sothe ollowing will produce an error rom the linker:

SECTIONS { .text : { *(.text) } LONG(1) .data : { *(.data) } }

whereas this will work:SECTIONS { .text : { *(.text) ; LONG(1) } .data : { *(.data) } }

You may use the FILL command to set the ll pattern or the current section. It is ollowedby an expression in parentheses. Any otherwise unspeci ed regions o memory within thesection ( or example, gaps le t due to the required alignment o input sections) are lledwith the value o the expression, repeated as necessary. A FILL statement covers memorylocations a ter the point at which it occurs in the section de nition; by including morethan one FILL statement, you can have diferent ll patterns in diferent parts o an outputsection.This example shows how to ll unspeci ed regions o memory with the value ‘ 0x90 ’:

FILL(0x90909090)

The FILL command is similar to the ‘ =fillexp ’ output section attribute, but it only afectsthe part o the section ollowing the FILL command, rather than the entire section. I bothare used, the FILL command takes precedence. See Section 3.6.8.8 [Output Section Fill],page 58, or details on the ll expression.

3.6.6 Output Section KeywordsThere are a couple o keywords which can appear as output section commands.

CREATE_OBJECT_SYMBOLSThe command tells the linker to create a symbol or each input le. The nameo each symbol will be the name o the corresponding input le. The section o each symbol will be the output section in which the CREATE_OBJECT_SYMBOLScommand appears.This is conventional or the a.out object le ormat. It is not normally used orany other object le ormat.

CONSTRUCTORSWhen linking using the a.out object le ormat, the linker uses an unusual setconstruct to support C ++ global constructors and destructors. When linkingobject le ormats which do not support arbitrary sections, such as ECOFFand XCOFF, the linker will automatically recognize C ++ global constructorsand destructors by name. For these object le ormats, the CONSTRUCTORScommand tells the linker to place constructor in ormation in the output sectionwhere the CONSTRUCTORScommand appears. The CONSTRUCTORScommand isignored or other object le ormats.

Page 61: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 61/122

Chapter 3: Linker Scripts 55

The symbol __CTOR_LIST__ marks the start o the global constructors, andthe symbol __CTOR_END__marks the end. Similarly, __DTOR_LIST__ and__DTOR_END__mark the start and end o the global destructors. The rstword in the list is the number o entries, ollowed by the address o eachconstructor or destructor, ollowed by a zero word. The compiler must arrangeto actually run the code. For these object le ormats gnu C++ normallycalls constructors rom a subroutine __main ; a call to __main is automaticallyinserted into the startup code or main . gnu C++ normally runs destructorseither by using atexit , or directly rom the unction exit .For object le ormats such as COFF or ELF which support arbitrary sectionnames, gnu C++ will normally arrange to put the addresses o global construc-tors and destructors into the .ctors and .dtors sections. Placing the ollowingsequence into your linker script will build the sort o table which the gnu C++runtime code expects to see.

__CTOR_LIST__ = .;

LONG((__CTOR_END__ - __CTOR_LIST__) / 4 - 2)*(.ctors)LONG(0)__CTOR_END__ = .;__DTOR_LIST__ = .;LONG((__DTOR_END__ - __DTOR_LIST__) / 4 - 2)*(.dtors)LONG(0)__DTOR_END__ = .;

I you are using the gnu C++ support or initialization priority, whichprovides some control over the order in which global constructors arerun, you must sort the constructors at link time to ensure that they areexecuted in the correct order. When using the CONSTRUCTORScommand, use

‘SORT_BY_NAME(CONSTRUCTORS)’ instead. When using the .ctors and .dtorssections, use ‘*(SORT_BY_NAME(.ctors)) ’ and ‘*(SORT_BY_NAME(.dtors)) ’instead o just ‘ *(.ctors) ’ and ‘*(.dtors) ’.Normally the compiler and linker will handle these issues automatically, andyou will not need to concern yoursel with them. However, you may need toconsider this i you are using C ++ and writing your own linker scripts.

3.6.7 Output Section DiscardingThe linker will not create output sections with no contents. This is or convenience whenre erring to input sections that may or may not be present in any o the input les. Forexample:

.foo : { *(.foo) }will only create a ‘.foo ’ section in the output le i there is a ‘ .foo ’ section in at leastone input le, and i the input sections are not all empty. Other link script directives thatallocate space in an output section will also create the output section.The linker will ignore address assignments (see Section 3.6.3 [Output Section Address],page 49) on discarded output sections, except when the linker script de nes symbols in theoutput section. In that case the linker will obey the address assignments, possibly advancingdot even though the section is discarded.

Page 62: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 62/122

56 The GNU linker

The special output section name ‘ /DISCARD/ ’ may be used to discard input sections. Anyinput sections which are assigned to an output section named ‘ /DISCARD/ ’ are not includedin the output le.

3.6.8 Output Section AttributesWe showed above that the ull description o an output section looked like this:

section [ address ] [( type )] :[AT( lma )][ALIGN( section_align )][SUBALIGN(subsection_align )][ constraint ]{

output-section-commandoutput-section-command...

} [> region ] [AT> lma_region ] [: phdr : phdr ...] [= fillexp ]

We’ve already described section , address , and output-section-command . In this section wewill describe the remaining section attributes.

3.6.8.1 Output Section TypeEach output section may have a type. The type is a keyword in parentheses. The ollowingtypes are de ned:

NOLOAD The section should be marked as not loadable, so that it will not be loaded intomemory when the program is run.

DSECTCOPYINFOOVERLAY These type names are supported or backward compatibility, and are rarely

used. They all have the same efect: the section should be marked as notallocatable, so that no memory is allocated or the section when the programis run.

The linker normally sets the attributes o an output section based on the input sectionswhich map into it. You can override this by using the section type. For example, in thescript sample below, the ‘ ROM’ section is addressed at memory location ‘ 0’ and does notneed to be loaded when the program is run. The contents o the ‘ ROM’ section will appearin the linker output le as usual.

SECTIONS {ROM 0 (NOLOAD) : { ... }...

}

3.6.8.2 Output Section LMAEvery section has a virtual address (VMA) and a load address (LMA); see Section 3.1 [BasicScript Concepts], page 37 . The address expression which may appear in an output sectiondescription sets the VMA (see Section 3.6.3 [Output Section Address], page 49 ).The expression lma that ollows the AT keyword speci es the load address o the section.

Page 63: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 63/122

Chapter 3: Linker Scripts 57

Alternatively, with ‘ AT>lma_region ’ expression, you may speci y a memory region or thesection’s load address. See Section 3.7 [MEMORY], page 60 . Note that i the section hasnot had a VMA assigned to it then the linker will use the lma region as the VMA regionas well.

I neither AT nor AT> is speci ed or an allocatable section, the linker will set the LMA suchthat the diference between VMA and LMA or the section is the same as the precedingoutput section in the same region. I there is no preceding output section or the section isnot allocatable, the linker will set the LMA equal to the VMA. See Section 3.6.8.6 [OutputSection Region], page 58.

This eature is designed to make it easy to build a ROM image. For example, the ollowinglinker script creates three output sections: one called ‘ .text ’, which starts at 0x1000 , onecalled ‘.mdata ’, which is loaded at the end o the ‘ .text ’ section even though its VMA is0x2000 , and one called ‘.bss ’ to hold uninitialized data at address 0x3000 . The symbol_data is de ned with the value 0x2000 , which shows that the location counter holds the

VMA value, not the LMA value.SECTIONS

{.text 0x1000 : { *(.text) _etext = . ; }.mdata 0x2000 :

AT ( ADDR (.text) + SIZEOF (.text) ){ _data = . ; *(.data); _edata = . ; }

.bss 0x3000 :{ _bstart = . ; *(.bss) *(COMMON) ; _bend = . ;}

}

The run-time initialization code or use with a program generated with this linker scriptwould include something like the ollowing, to copy the initialized data rom the ROM image

to its runtime address. Notice how this code takes advantage o the symbols de ned by thelinker script.

extern char _etext, _data, _edata, _bstart, _bend;char *src = &_etext;char *dst = &_data;

/* ROM has data at end of text; copy it. */while (dst < &_edata) {

*dst++ = *src++;}

/* Zero bss */for (dst = &_bstart; dst< &_bend; dst++)

*dst = 0;

3.6.8.3 Forced Output AlignmentYou can increase an output section’s alignment by using ALIGN.

3.6.8.4 Forced Input AlignmentYou can orce input section alignment within an output section by using SUBALIGN. Thevalue speci ed overrides any alignment given by input sections, whether larger or smaller.

Page 64: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 64/122

58 The GNU linker

3.6.8.5 Output Section ConstraintYou can speci y that an output section should only be created i all o its input sections areread-only or all o its input sections are read-write by using the keyword ONLY_IF_ROand

ONLY_IF_RWrespectively.3.6.8.6 Output Section RegionYou can assign a section to a previously de ned region o memory by using ‘ >region ’. SeeSection 3.7 [MEMORY], page 60 .Here is a simple example:

MEMORY { rom : ORIGIN = 0x1000, LENGTH = 0x1000 }SECTIONS { ROM : { *(.text) } >rom }

3.6.8.7 Output Section PhdrYou can assign a section to a previously de ned program segment by using ‘ : phdr ’. SeeSection 3.8 [PHDRS], page 61 . I a section is assigned to one or more segments, then allsubsequent allocated sections will be assigned to those segments as well, unless they use anexplicitly : phdr modi er. You can use :NONE to tell the linker to not put the section inany segment at all.Here is a simple example:

PHDRS { text PT_LOAD ; }SECTIONS { .text : { *(.text) } :text }

3.6.8.8 Output Section FillYou can set the ll pattern or an entire section by using ‘ =fillexp ’. llexp is an expression(see Section 3.10 [Expressions], page 66 ). Any otherwise unspeci ed regions o memorywithin the output section ( or example, gaps le t due to the required alignment o inputsections) will be lled with the value, repeated as necessary. I the ll expression is a simplehex number, ie. a string o hex digit starting with ‘ 0x ’ and without a trailing ‘ k’ or ‘M’, thenan arbitrarily long sequence o hex digits can be used to speci y the ll pattern; Leadingzeros become part o the pattern too. For all other cases, including extra parentheses or aunary +, the ll pattern is the our least signi cant bytes o the value o the expression. Inall cases, the number is big-endian.You can also change the ll value with a FILL command in the output section commands;(see Section 3.6.5 [Output Section Data], page 53 ).Here is a simple example:

SECTIONS { .text : { *(.text) } =0x90909090 }

3.6.9 Overlay DescriptionAn overlay description provides an easy way to describe sections which are to be loadedas part o a single memory image but are to be run at the same memory address. Atrun time, some sort o overlay manager will copy the overlaid sections in and out o theruntime memory address as required, perhaps by simply manipulating addressing bits. Thisapproach can be use ul, or example, when a certain region o memory is aster than another.Overlays are described using the OVERLAYcommand. The OVERLAYcommand is used withina SECTIONScommand, like an output section description. The ull syntax o the OVERLAYcommand is as ollows:

Page 65: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 65/122

Chapter 3: Linker Scripts 59

OVERLAY [start ] : [NOCROSSREFS] [AT ( ldaddr )]{

secname1{

output-section-commandoutput-section-command...

} [: phdr ...] [= fill ]secname2

{output-section-commandoutput-section-command...

} [: phdr ...] [= fill ]...

} [> region ] [: phdr ...] [= fill ]

Everything is optional except OVERLAY(a keyword), and each section must have a name(secname1 and secname2 above). The section de nitions within the OVERLAYconstruct

are identical to those within the general SECTIONScontruct (see Section 3.6 [SECTIONS],page 48), except that no addresses and no memory regions may be de ned or sectionswithin an OVERLAY.The sections are all de ned with the same starting address. The load addresses o thesections are arranged such that they are consecutive in memory starting at the load addressused or the OVERLAYas a whole (as with normal section de nitions, the load address isoptional, and de aults to the start address; the start address is also optional, and de aultsto the current value o the location counter).I the NOCROSSREFSkeyword is used, and there any re erences among the sections, the linkerwill report an error. Since the sections all run at the same address, it normally does notmake sense or one section to re er directly to another. See Section 3.4.5 [MiscellaneousCommands], page 44 .For each section within the OVERLAY, the linker automatically provides two symbols. Thesymbol __load_start_ secname is de ned as the starting load address o the section. Thesymbol __load_stop_ secname is de ned as the nal load address o the section. Anycharacters within secname which are not legal within C identi ers are removed. C (orassembler) code may use these symbols to move the overlaid sections around as necessary.At the end o the overlay, the value o the location counter is set to the start address o theoverlay plus the size o the largest section.Here is an example. Remember that this would appear inside a SECTIONSconstruct.

OVERLAY 0x1000 : AT (0x4000){

.text0 { o1/*.o(.text) }

.text1 { o2/*.o(.text) }}

This will de ne both ‘ .text0 ’ and ‘.text1 ’ to start at address 0x1000. ‘ .text0 ’ willbe loaded at address 0x4000, and ‘ .text1 ’ will be loaded immediately a ter ‘ .text0 ’. Theollowing symbols will be de ned i re erenced: __load_start_text0 , __load_stop_text0 ,__load_start_text1 , __load_stop_text1 .C code to copy overlay .text1 into the overlay area might look like the ollowing.

Page 66: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 66/122

Page 67: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 67/122

Chapter 3: Linker Scripts 61

‘A’ Allocatable section

‘I ’ Initialized section

‘L’ Same as ‘I ’

‘! ’ Invert the sense o any o the preceding attributes

I a unmapped section matches any o the listed attributes other than ‘ ! ’, it will be placedin the memory region. The ‘ ! ’ attribute reverses this test, so that an unmapped sectionwill be placed in the memory region only i it does not match any o the listed attributes.The origin is an numerical expression or the start address o the memory region. Theexpression must evaluate to a constant and it cannot involve any symbols. The keywordORIGIN may be abbreviated to org or o (but not, or example, ORG).The len is an expression or the size in bytes o the memory region. As with the originexpression, the expression must be numerical only and must evaluate to a constant. Thekeyword LENGTHmay be abbreviated to len or l .In the ollowing example, we speci y that there are two memory regions available or allo-cation: one starting at ‘ 0’ or 256 kilobytes, and the other starting at ‘ 0x40000000 ’ or ourmegabytes. The linker will place into the ‘ rom’ memory region every section which is notexplicitly mapped into a memory region, and is either read-only or executable. The linkerwill place other sections which are not explicitly mapped into a memory region into the‘ram ’ memory region.

MEMORY{

rom (rx) : ORIGIN = 0, LENGTH = 256Kram (!rx) : org = 0x40000000, l = 4M

}

Once you de ne a memory region, you can direct the linker to place speci c output sectionsinto that memory region by using the ‘ >region ’ output section attribute. For example,i you have a memory region named ‘ mem’, you would use ‘>mem’ in the output sectionde nition. See Section 3.6.8.6 [Output Section Region], page 58 . I no address was speci edor the output section, the linker will set the address to the next available address withinthe memory region. I the combined output sections directed to a memory region are toolarge or the region, the linker will issue an error message.It is possible to access the origin and length o a memory in an expression via theORIGIN(memory ) and LENGTH(memory ) unctions:

_fstack = ORIGIN(ram) + LENGTH(ram) - 4;

3.8 PHDRS CommandThe ELF object le ormat uses program headers , also knows as segments . The programheaders describe how the program should be loaded into memory. You can print them outby using the objdump program with the ‘ -p ’ option.When you run an ELF program on a native ELF system, the system loader reads theprogram headers in order to gure out how to load the program. This will only work i theprogram headers are set correctly. This manual does not describe the details o how thesystem loader interprets program headers; or more in ormation, see the ELF ABI.

Page 68: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 68/122

62 The GNU linker

The linker will create reasonable program headers by de ault. However, in some cases, youmay need to speci y the program headers more precisely. You may use the PHDRScommandor this purpose. When the linker sees the PHDRScommand in the linker script, it will notcreate any program headers other than the ones speci ed.The linker only pays attention to the PHDRScommand when generating an ELF output le.In other cases, the linker will simply ignore PHDRS.This is the syntax o the PHDRScommand. The words PHDRS, FILEHDR, AT, and FLAGSarekeywords.

PHDRS{

name type [ FILEHDR ] [ PHDRS ] [ AT ( address ) ][ FLAGS ( flags ) ] ;

}

The name is used only or re erence in the SECTIONScommand o the linker script. It is notput into the output le. Program header names are stored in a separate name space, andwill not con ict with symbol names, le names, or section names. Each program headermust have a distinct name. The headers are processed in order and it is usual or them tomap to sections in ascending load address order.Certain program header types describe segments o memory which the system loader willload rom the le. In the linker script, you speci y the contents o these segments by placingallocatable output sections in the segments. You use the ‘ : phdr ’ output section attribute toplace a section in a particular segment. See Section 3.6.8.7 [Output Section Phdr], page 58 .It is normal to put certain sections in more than one segment. This merely implies thatone segment o memory contains another. You may repeat ‘ : phdr ’, using it once or eachsegment which should contain the section.I you place a section in one or more segments using ‘ : phdr ’, then the linker will place allsubsequent allocatable sections which do not speci y ‘ : phdr ’ in the same segments. This isor convenience, since generally a whole set o contiguous sections will be placed in a singlesegment. You can use :NONE to override the de ault segment and tell the linker to not putthe section in any segment at all.You may use the FILEHDR and PHDRSkeywords a ter the program header type to urtherdescribe the contents o the segment. The FILEHDRkeyword means that the segment shouldinclude the ELF le header. The PHDRSkeyword means that the segment should includethe ELF program headers themselves. I applied to a loadable segment ( PT_LOAD), it mustbe the rst loadable segment.The type may be one o the ollowing. The numbers indicate the value o the keyword.

PT_NULL(0)Indicates an unused program header.

PT_LOAD(1)Indicates that this program header describes a segment to be loaded rom thele.

PT_DYNAMIC(2)Indicates a segment where dynamic linking in ormation can be ound.

PT_INTERP (3)Indicates a segment where the name o the program interpreter may be ound.

Page 69: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 69/122

Chapter 3: Linker Scripts 63

PT_NOTE(4)Indicates a segment holding note in ormation.

PT_SHLIB (5)

A reserved program header type, de ned but not speci ed by the ELF ABI.PT_PHDR(6)

Indicates a segment where the program headers may be ound.

expression An expression giving the numeric type o the program header. This may beused or types not de ned above.

You can speci y that a segment should be loaded at a particular address in memory byusing an AT expression. This is identical to the AT command used as an output sectionattribute (see Section 3.6.8.2 [Output Section LMA], page 56 ). The AT command or aprogram header overrides the output section attribute.The linker will normally set the segment ags based on the sections which comprise the

segment. You may use the FLAGSkeyword to explicitly speci y the segment ags. The valueo ags must be an integer. It is used to set the p_flags eld o the program header.Here is an example o PHDRS. This shows a typical set o program headers used on a nativeELF system.

PHDRS{

headers PT_PHDR PHDRS ;interp PT_INTERP ;text PT_LOAD FILEHDR PHDRS ;data PT_LOAD ;dynamic PT_DYNAMIC ;

}

SECTIONS{

. = SIZEOF_HEADERS;

.interp : { *(.interp) } :text :interp

.text : { *(.text) } :text

.rodata : { *(.rodata) } /* defaults to :text */

...

. = . + 0x1000; /* move to a new page in memory */

.data : { *(.data) } :data

.dynamic : { *(.dynamic) } :data :dynamic

...}

3.9 VERSION CommandThe linker supports symbol versions when using ELF. Symbol versions are only use ulwhen using shared libraries. The dynamic linker can use symbol versions to select a speci cversion o a unction when it runs a program that may have been linked against an earlierversion o the shared library.

Page 70: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 70/122

64 The GNU linker

You can include a version script directly in the main linker script, or you can supply theversion script as an implicit linker script. You can also use the ‘ --version-script ’ linkeroption.

The syntax o the VERSIONcommand is simplyVERSION { version-script-commands }

The ormat o the version script commands is identical to that used by Sun’s linker in Solaris2.5. The version script de nes a tree o version nodes. You speci y the node names andinterdependencies in the version script. You can speci y which symbols are bound to whichversion nodes, and you can reduce a speci ed set o symbols to local scope so that they arenot globally visible outside o the shared library.

The easiest way to demonstrate the version script language is with a ew examples.VERS_1.1 {

global:foo1;local:old*;original*;new*;

};

VERS_1.2 {foo2;

} VERS_1.1;

VERS_2.0 {bar1; bar2;extern "C++" {ns::*;"int f(int, double)";

}} VERS_1.2;

This example version script de nes three version nodes. The rst version node de ned is‘VERS_1.1 ’; it has no other dependencies. The script binds the symbol ‘ foo1 ’ to ‘VERS_1.1 ’.It reduces a number o symbols to local scope so that they are not visible outside o theshared library; this is done using wildcard patterns, so that any symbol whose name beginswith ‘old ’, ‘original ’, or ‘new’ is matched. The wildcard patterns available are the sameas those used in the shell when matching lenames (also known as “globbing”). However,i you speci y the symbol name inside double quotes, then the name is treated as literal,rather than as a glob pattern.

Next, the version script de nes node ‘ VERS_1.2 ’. This node depends upon ‘ VERS_1.1 ’. The

script binds the symbol ‘ foo2 ’ to the version node ‘VERS_1.2 ’.Finally, the version script de nes node ‘ VERS_2.0 ’. This node depends upon ‘ VERS_1.2 ’.The scripts binds the symbols ‘ bar1 ’ and ‘bar2 ’ are bound to the version node ‘ VERS_2.0 ’.

When the linker nds a symbol de ned in a library which is not speci cally bound to aversion node, it will efectively bind it to an unspeci ed base version o the library. Youcan bind all otherwise unspeci ed symbols to a given version node by using ‘ global: *; ’somewhere in the version script. Note that it’s slightly crazy to use wildcards in a globalspec except on the last version node. Global wildcards elsewhere run the risk o accidentally

Page 71: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 71/122

Chapter 3: Linker Scripts 65

adding symbols to the set exported or an old version. That’s wrong since older versionsought to have a xed set o symbols.The names o the version nodes have no speci c meaning other than what they might

suggest to the person reading them. The ‘ 2.0 ’ version could just as well have appeared inbetween ‘1.1 ’ and ‘1.2 ’. However, this would be a con using way to write a version script.Node name can be omitted, provided it is the only version node in the version script. Suchversion script doesn’t assign any versions to symbols, only selects which symbols will beglobally visible out and which won’t.

{ global: foo; bar; local: *; };

When you link an application against a shared library that has versioned symbols, theapplication itsel knows which version o each symbol it requires, and it also knows whichversion nodes it needs rom each shared library it is linked against. Thus at runtime, thedynamic loader can make a quick check to make sure that the libraries you have linkedagainst do in act supply all o the version nodes that the application will need to resolve

all o the dynamic symbols. In this way it is possible or the dynamic linker to know withcertainty that all external symbols that it needs will be resolvable without having to searchor each symbol re erence.The symbol versioning is in efect a much more sophisticated way o doing minor versionchecking that SunOS does. The undamental problem that is being addressed here is thattypically re erences to external unctions are bound on an as-needed basis, and are notall bound when the application starts up. I a shared library is out o date, a requiredinter ace may be missing; when the application tries to use that inter ace, it may suddenlyand unexpectedly ail. With symbol versioning, the user will get a warning when they starttheir program i the libraries being used with the application are too old.There are several GNU extensions to Sun’s versioning approach. The rst o these is theability to bind a symbol to a version node in the source le where the symbol is de nedinstead o in the versioning script. This was done mainly to reduce the burden on the librarymaintainer. You can do this by putting something like:

__asm__(".symver original_foo,foo@VERS_1.1");

in the C source le. This renames the unction ‘ original_foo ’ to be an alias or ‘foo ’bound to the version node ‘ VERS_1.1 ’. The ‘local: ’ directive can be used to prevent thesymbol ‘original_foo ’ rom being exported. A ‘ .symver ’ directive takes precedence overa version script.The second GNU extension is to allow multiple versions o the same unction to appear ina given shared library. In this way you can make an incompatible change to an inter acewithout increasing the major version number o the shared library, while still allowingapplications linked against the old inter ace to continue to unction.To do this, you must use multiple ‘ .symver ’ directives in the source le. Here is an example:

__asm__(".symver original_foo,foo@");__asm__(".symver old_foo,foo@VERS_1.1");__asm__(".symver old_foo1,foo@VERS_1.2");__asm__(".symver new_foo,foo@@VERS_2.0");

In this example, ‘ foo@’ represents the symbol ‘ foo ’ bound to the unspeci ed base versiono the symbol. The source le that contains this example would de ne 4 C unctions:‘original_foo ’, ‘old_foo ’, ‘old_foo1 ’, and ‘new_foo ’.

Page 72: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 72/122

Page 73: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 73/122

Chapter 3: Linker Scripts 67

3.10.2 Symbolic ConstantsIt is possible to re er to target speci c constants via the use o the CONSTANT(name ) operator,where name is one o :

MAXPAGESIZEThe target’s maximum page size.

COMMONPAGESIZEThe target’s de ault page size.

So or example:.text ALIGN (CONSTANT (MAXPAGESIZE)) : { *(.text) }

will create a text section aligned to the largest page boundary supported by the target.

3.10.3 Symbol NamesUnless quoted, symbol names start with a letter, underscore, or period and may includeletters, digits, underscores, periods, and hyphens. Unquoted symbol names must not con ictwith any keywords. You can speci y a symbol which contains odd characters or has thesame name as a keyword by surrounding the symbol name in double quotes:

"SECTION" = 9;"with a space" = "also with a space" + 10;

Since symbols can contain many non-alphabetic characters, it is sa est to delimit symbolswith spaces. For example, ‘ A-B’ is one symbol, whereas ‘A - B’ is an expression involvingsubtraction.

3.10.4 Orphan SectionsOrphan sections are sections present in the input les which are not explicitly placed into theoutput le by the linker script. The linker will still copy these sections into the output le,

but it has to guess as to where they should be placed. The linker uses a simple heuristicto do this. It attempts to place orphan sections a ter non-orphan sections o the sameattribute, such as code vs data, loadable vs non-loadable, etc. I there is not enough roomto do this then it places at the end o the le.For ELF targets, the attribute o the section includes section type as well as section ag.I an orphaned section’s name is representable as a C identi er then the linker will au-tomatically see Section 3.5.2 [PROVIDE], page 46 two symbols: start SECNAME and

end SECNAME, where SECNAME is the name o the section. These indicate the startaddress and end address o the orphaned section respectively. Note: most section namesare not representable as C identi ers because they contain a ‘ . ’ character.

3.10.5 The Location CounterThe special linker variable dot ‘. ’ always contains the current output location counter. Sincethe . always re ers to a location in an output section, it may only appear in an expressionwithin a SECTIONScommand. The . symbol may appear anywhere that an ordinary symbolis allowed in an expression.Assigning a value to . will cause the location counter to be moved. This may be usedto create holes in the output section. The location counter may not be moved backwardsinside an output section, and may not be moved backwards outside o an output section i so doing creates areas with overlapping LMAs.

Page 74: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 74/122

68 The GNU linker

SECTIONS{

output :{

file1(.text). = . + 1000;file2(.text). += 1000;file3(.text)

} = 0x12345678;}

In the previous example, the ‘ .text ’ section rom ‘file1 ’ is located at the beginning o theoutput section ‘ output ’. It is ollowed by a 1000 byte gap. Then the ‘ .text ’ section rom‘file2 ’ appears, also with a 1000 byte gap ollowing be ore the ‘ .text ’ section rom ‘file3 ’.The notation ‘ = 0x12345678 ’ speci es what data to write in the gaps (see Section 3.6.8.8[Output Section Fill], page 58 ).Note: . actually re ers to the byte ofset rom the start o the current containing object.Normally this is the SECTIONSstatement, whose start address is 0, hence . can be used asan absolute address. I . is used inside a section description however, it re ers to the byteofset rom the start o that section, not an absolute address. Thus in a script like this:

SECTIONS{

. = 0x100

.text: {*(.text). = 0x200

}. = 0x500.data: {

*(.data)

. += 0x600}}

The ‘.text ’ section will be assigned a starting address o 0x100 and a size o exactly 0x200bytes, even i there is not enough data in the ‘ .text ’ input sections to ll this area. (I there is too much data, an error will be produced because this would be an attempt to move. backwards). The ‘ .data ’ section will start at 0x500 and it will have an extra 0x600 bytesworth o space a ter the end o the values rom the ‘ .data ’ input sections and be ore theend o the ‘ .data ’ output section itsel .Setting symbols to the value o the location counter outside o an output section statementcan result in unexpected values i the linker needs to place orphan sections. For example,given the ollowing:

SECTIONS{

start_of_text = . ;.text: { *(.text) }end_of_text = . ;

start_of_data = . ;.data: { *(.data) }end_of_data = . ;

}

Page 75: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 75/122

Chapter 3: Linker Scripts 69

I the linker needs to place some input section, e.g. .rodata , not mentioned in the script,it might choose to place that section between .text and .data . You might think thelinker should place .rodata on the blank line in the above script, but blank lines are o noparticular signi cance to the linker. As well, the linker doesn’t associate the above symbolnames with their sections. Instead, it assumes that all assignments or other statementsbelong to the previous output section, except or the special case o an assignment to . .I.e., the linker will place the orphan .rodata section as i the script was written as ollows:

SECTIONS{

start_of_text = . ;.text: { *(.text) }end_of_text = . ;

start_of_data = . ;

.rodata: { *(.rodata) }.data: { *(.data) }end_of_data = . ;

}

This may or may not be the script author’s intention or the value o start_of_data . Oneway to in uence the orphan section placement is to assign the location counter to itsel , asthe linker assumes that an assignment to . is setting the start address o a ollowing outputsection and thus should be grouped with that section. So you could write:

SECTIONS{

start_of_text = . ;.text: { *(.text) }end_of_text = . ;

. = . ;start_of_data = . ;.data: { *(.data) }end_of_data = . ;

}

Now, the orphan .rodata section will be placed between end_of_text and start_of_data .

3.10.6 OperatorsThe linker recognizes the standard C set o arithmetic operators, with the standard bindingsand precedence levels:

Page 76: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 76/122

70 The GNU linker

Precedence Associativity Operatorshighest

1 le t - ~ ! †2 le t * / %3 le t + -

4 le t >> <<5 le t == != > < <= >=6 le t &7 le t |8 le t &&9 le t ||

10 right ? :11 right &= += -= *= /= ‡

lowest

† Pre x operators.‡ See Section 3.5 [Assignments], page 45 .

3.10.7 EvaluationThe linker evaluates expressions lazily. It only computes the value o an expression whenabsolutely necessary.

The linker needs some in ormation, such as the value o the start address o the rst section,and the origins and lengths o memory regions, in order to do any linking at all. Thesevalues are computed as soon as possible when the linker reads in the linker script.

However, other values (such as symbol values) are not known or needed until a ter storageallocation. Such values are evaluated later, when other in ormation (such as the sizes o output sections) is available or use in the symbol assignment expression.

The sizes o sections cannot be known until a ter allocation, so assignments dependent uponthese are not per ormed until a ter allocation.

Some expressions, such as those depending upon the location counter ‘ . ’, must be evaluatedduring section allocation.

I the result o an expression is required, but the value is not available, then an error results.For example, a script like the ollowing

SECTIONS{

.text 9+this_isnt_constant :{ *(.text) }

}

will cause the error message ‘ non constant expression for initial address ’.

3.10.8 The Section o an ExpressionWhen the linker evaluates an expression, the result is either absolute or relative to somesection. A relative expression is expressed as a xed ofset rom the base o a section.

The position o the expression within the linker script determines whether it is absolute orrelative. An expression which appears within an output section de nition is relative to thebase o the output section. An expression which appears elsewhere will be absolute.

Page 77: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 77/122

Chapter 3: Linker Scripts 71

A symbol set to a relative expression will be relocatable i you request relocatable outputusing the ‘-r ’ option. That means that a urther link operation may change the value o the symbol. The symbol’s section will be the section o the relative expression.A symbol set to an absolute expression will retain the same value through any urther linkoperation. The symbol will be absolute, and will not have any particular associated section.You can use the builtin unction ABSOLUTEto orce an expression to be absolute when itwould otherwise be relative. For example, to create an absolute symbol set to the addresso the end o the output section ‘ .data ’:

SECTIONS{

.data : { *(.data) _edata = ABSOLUTE(.); }}

I ‘ABSOLUTE’ were not used, ‘_edata ’ would be relative to the ‘ .data ’ section.

3.10.9 Builtin Functions

The linker script language includes a number o builtin unctions or use in linker scriptexpressions.

ABSOLUTE(exp )Return the absolute (non-relocatable, as opposed to non-negative) value o theexpression exp . Primarily use ul to assign an absolute value to a symbol withina section de nition, where symbol values are normally section relative. SeeSection 3.10.8 [Expression Section], page 70 .

ADDR(section )Return the absolute address (the VMA) o the named section . Your script mustpreviously have de ned the location o that section. In the ollowing example,symbol_1 and symbol_2 are assigned identical values:

SECTIONS { ....output1 :{start_of_output_1 = ABSOLUTE(.);...}

.output :{symbol_1 = ADDR(.output1);symbol_2 = start_of_output_1;}

... }

ALIGN(align )ALIGN(exp , align )

Return the location counter ( . ) or arbitrary expression aligned to the nextalign boundary. The single operand ALIGN doesn’t change the value o thelocation counter—it just does arithmetic on it. The two operand ALIGNallowsan arbitrary expression to be aligned upwards ( ALIGN(align ) is equivalent toALIGN(., align ) ).Here is an example which aligns the output .data section to the next 0x2000byte boundary a ter the preceding section and sets a variable within the sectionto the next 0x8000 boundary a ter the input sections:

Page 78: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 78/122

72 The GNU linker

SECTIONS { ....data ALIGN(0x2000): {

*(.data)variable = ALIGN(0x8000);

}... }

The rst use o ALIGN in this example speci es the location o a section be-cause it is used as the optional address attribute o a section de nition (seeSection 3.6.3 [Output Section Address], page 49 ). The second use o ALIGN isused to de nes the value o a symbol.The builtin unction NEXTis closely related to ALIGN.

ALIGNOF(section )Return the alignment in bytes o the named section , i that section has beenallocated. I the section has not been allocated when this is evaluated, the linkerwill report an error. In the ollowing example, the alignment o the .output

section is stored as the rst value in that section.SECTIONS{ ....output {

LONG (ALIGNOF (.output))...}

... }

BLOCK(exp )This is a synonym or ALIGN, or compatibility with older linker scripts. It ismost o ten seen when setting the address o an output section.

DATA_SEGMENT_ALIGN(maxpagesize , commonpagesize )This is equivalent to either

(ALIGN(maxpagesize ) + ( . & ( maxpagesize - 1)))or

(ALIGN(maxpagesize ) + ( . & ( maxpagesize - commonpagesize )))

depending on whether the latter uses ewer commonpagesize sized pages or thedata segment (area between the result o this expression and DATA_SEGMENT_END) than the ormer or not. I the latter orm is used, it means commonpagesize bytes o runtime memory will be saved at the expense o up to commonpagesize wasted bytes in the on-disk le.This expression can only be used directly in SECTIONScommands, not in anyoutput section descriptions and only once in the linker script. commonpagesize should be less or equal to maxpagesize and should be the system page size the

object wants to be optimized or (while still working on system page sizes upto maxpagesize ).Example:

. = DATA_SEGMENT_ALIGN(0x10000, 0x2000);

DATA_SEGMENT_END(exp )This de nes the end o data segment or DATA_SEGMENT_ALIGNevaluation pur-poses.

. = DATA_SEGMENT_END(.);

Page 79: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 79/122

Chapter 3: Linker Scripts 73

DATA_SEGMENT_RELRO_END(offset , exp )This de nes the end o the PT_GNU_RELROsegment when ‘ -z relro ’ option isused. Second argument is returned. When ‘ -z relro ’ option is not present,DATA_SEGMENT_RELRO_ENDdoes nothing, otherwise DATA_SEGMENT_ALIGNis padded so that exp + ofset is aligned to the most commonly used pageboundary or particular target. I present in the linker script, it must alwayscome in between DATA_SEGMENT_ALIGNand DATA_SEGMENT_END.

. = DATA_SEGMENT_RELRO_END(24, .);

DEFINED(symbol )Return 1 i symbol is in the linker global symbol table and is de ned be orethe statement using DEFINED in the script, otherwise return 0. You can usethis unction to provide de ault values or symbols. For example, the ollowingscript ragment shows how to set a global symbol ‘ begin ’ to the rst locationin the ‘.text ’ section—but i a symbol called ‘ begin ’ already existed, its valueis preserved:

SECTIONS { ....text : {

begin = DEFINED(begin) ? begin : . ;...

}...

}

LENGTH(memory )Return the length o the memory region named memory .

LOADADDR(section )Return the absolute LMA o the named section . This is normally the same asADDR, but it may be diferent i the AT attribute is used in the output sectionde nition (see Section 3.6.8.2 [Output Section LMA], page 56 ).

MAX(exp1 , exp2 )Returns the maximum o exp1 and exp2 .

MIN(exp1 , exp2 )Returns the minimum o exp1 and exp2 .

NEXT(exp )Return the next unallocated address that is a multiple o exp . This unction isclosely related to ALIGN(exp ) ; unless you use the MEMORYcommand to de nediscontinuous memory or the output le, the two unctions are equivalent.

ORIGIN(memory )Return the origin o the memory region named memory .

SEGMENT_START(segment , default )Return the base address o the named segment . I an explicit value has beengiven or this segment (with a command-line ‘ -T ’ option) that value will bereturned; otherwise the value will be de ault . At present, the ‘ -T ’ command-line option can only be used to set the base address or the “text”, “data”, and“bss” sections, but you use SEGMENT_STARTwith any segment name.

Page 80: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 80/122

Page 81: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 81/122

Chapter 4: Machine Dependent Features 75

4 Machine Dependent Features

ld has additional eatures on some plat orms; the ollowing sections describe them. Ma-

chines where ld has no additional unctionality are not listed.

4.1 ld and the H8/300For the H8/300, ld can per orm these global optimizations when you speci y the ‘ --relax ’command-line option.

relaxing address modes ld nds all jsr and jmp instructions whose targets are within eight bits, andturns them into eight-bit program-counter relative bsr and bra instructions,respectively.

synthesizing instructions ld

nds allmov.b

instructions which use the sixteen-bit absolute address orm,but re er to the top page o memory, and changes them to use the eight-bitaddress orm. (That is: the linker turns ‘ mov.b @aa :16 ’ into ‘ mov.b @aa :8 ’whenever the address aa is in the top page o memory).

bit manipulation instructions ld nds all bit manipulation instructions like band, bclr, biand, bild,bior, bist, bixor, bld, bnot, bor, bset, bst, btst, bxor which use 32bit and 16 bit absolute address orm, but re er to the top page o memory, andchanges them to use the 8 bit address orm. (That is: the linker turns ‘ bset#xx:3,@ aa :32 ’ into ‘bset #xx:3,@ aa :8 ’ whenever the address aa is in thetop page o memory).

system control instructions ld nds all ldc.w, stc.w instructions which use the 32 bit absolute addressorm, but re er to the top page o memory, and changes them to use 16 bitaddress orm. (That is: the linker turns ‘ ldc.w @ aa :32,ccr ’ into ‘ldc.w@aa :16,ccr ’ whenever the address aa is in the top page o memory).

4.2 ld and the Intel 960 FamilyYou can use the ‘ -Aarchitecture ’ command line option to speci y one o the two-letternames identi ying members o the 960 amily; the option speci es the desired output target,and warns o any incompatible instructions in the input les. It also modi es the linker’ssearch strategy or archive libraries, to support the use o libraries speci c to each particular

architecture, by including in the search loop names su xed with the string identi ying thearchitecture.For example, i your ld command line included ‘ -ACA’ as well as ‘-ltry ’, the linker wouldlook (in its built-in search paths, and in any paths you speci y with ‘ -L ’) or a library withthe names

trylibtry.atrycalibtryca.a

Page 82: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 82/122

76 The GNU linker

The rst two possibilities would be considered in any event; the last two are due to the useo ‘-ACA’.You can meaning ully use ‘ -A’ more than once on a command line, since the 960 architectureamily allows combination o target architectures; each use will add another pair o namevariants to search or when ‘ -l ’ speci es a library.ld supports the ‘ --relax ’ option or the i960 amily. I you speci y ‘ --relax ’, ld ndsall balx and calx instructions whose targets are within 24 bits, and turns them into 24-bit program-counter relative bal and cal instructions, respectively. ld also turns calinstructions into bal instructions when it determines that the target subroutine is a lea routine (that is, the target subroutine does not itsel call any subroutines).The ‘--fix-cortex-a8 ’ switch enables a link-time workaround or an erratum in certainCortex-A8 processors. The workaround is enabled by de ault i you are targeting the ARMv7-A architecture pro le. It can be enabled otherwise by speci ying ‘ --fix-cortex-a8 ’, ordisabled unconditionally by speci ying ‘ --no-fix-cortex-a8 ’.

The erratum only afects Thumb-2 code. Please contact ARM or urther details.4.3 ld and the Motorola 68HC11 and 68HC12 amilies

4.3.1 Linker RelaxationFor the Motorola 68HC11, ld can per orm these global optimizations when you speci y the‘--relax ’ command-line option.

relaxing address modes ld nds all jsr and jmp instructions whose targets are within eight bits, andturns them into eight-bit program-counter relative bsr and bra instructions,respectively.

ld also looks at all 16-bit extended addressing modes and trans orms them ina direct addressing mode when the address is in page 0 (between 0 and 0x0f).

relaxing gcc instruction groupWhen gcc is called with ‘-mrelax ’, it can emit group o instructions that thelinker can optimize to use a 68HC11 direct addressing mode. These instructionsconsists o bclr or bset instructions.

4.3.2 Trampoline GenerationFor 68HC11 and 68HC12, ld can generate trampoline code to call a ar unction using anormal jsr instruction. The linker will also change the relocation to some ar unction touse the trampoline address instead o the unction address. This is typically the case when

a pointer to a unction is taken. The pointer will in act point to the unction trampoline.

4.4 ld and the ARM amilyFor the ARM, ld will generate code stubs to allow unctions calls between ARM and Thumbcode. These stubs only work with code that has been compiled and assembled with the‘-mthumb-interwork ’ command line option. I it is necessary to link with old ARM objectles or libraries, which have not been compiled with the -mthumb-interwork option thenthe ‘--support-old-code ’ command line switch should be given to the linker. This will

Page 83: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 83/122

Chapter 4: Machine Dependent Features 77

make it generate larger stub unctions which will work with non-interworking aware ARMcode. Note, however, the linker does not support generating stubs or unction calls tonon-interworking aware Thumb code.

The ‘--thumb-entry

’ switch is a duplicate o the generic ‘--entry

’ switch, in that it setsthe program’s starting address. But it also sets the bottom bit o the address, so that itcan be branched to using a BX instruction, and the program will start executing in Thumbmode straight away.The ‘--use-nul-prefixed-import-tables ’ switch is speci ying, that the import tablesidata4 and idata5 have to be generated with a zero elememt pre x or import libraries.This is the old style to generate import tables. By de ault this option is turned of.The ‘--be8 ’ switch instructs ld to generate BE8 ormat executables. This option is onlyvalid when linking big-endian objects. The resulting image will contain big-endian data andlittle-endian code.The ‘R_ARM_TARGET1’ relocation is typically used or entries in the ‘ .init_array ’ section.

It is interpreted as either ‘ R_ARM_REL32’ or ‘R_ARM_ABS32’, depending on the target. The‘--target1-rel ’ and ‘--target1-abs ’ switches override the de ault.The ‘--target2=type ’ switch overrides the de ault de nition o the ‘ R_ARM_TARGET2’ relo-cation. Valid values or ‘ type ’, their meanings, and target de aults are as ollows:

‘rel ’ ‘R_ARM_REL32’ (arm*-*-el , arm*-*-eabi)

‘abs ’ ‘R_ARM_ABS32’ (arm*-*-symbianel )

‘got-rel ’ ‘R_ARM_GOT_PREL’ (arm*-*-linux, arm*-*-*bsd)

The ‘R_ARM_V4BX’ relocation (de ned by the ARM AAELF speci cation) enables objectscompiled or the ARMv4 architecture to be interworking-sa e when linked with other objectscompiled or ARMv4t, but also allows pure ARMv4 binaries to be built rom the sameARMv4 objects.In the latter case, the switch ‘ --fix-v4bx ’ must be passed to the linker, which causesv4t BX rMinstructions to be rewritten as MOV PC,rM, since v4 processors do not have a BXinstruction.In the ormer case, the switch should not be used, and ‘ R_ARM_V4BX’ relocations are ignored.Replace BX rM instructions identi ed by ‘ R_ARM_V4BX’ relocations with a branch to theollowing veneer:

TST rM, #1MOVEQ PC, rMBX Rn

This allows generation o libraries/applications that work on ARMv4 cores and are still

interworking sa e. Note that the above veneer clobbers the condition ags, so may causeincorrect progrm behavior in rare cases.The ‘--use-blx ’ switch enables the linker to use ARM/Thumb BLX instructions (availableon ARMv5t and above) in various situations. Currently it is used to per orm calls via thePLT rom Thumb code using BLX rather than using BX and a mode-switching stub be oreeach PLT entry. This should lead to such calls executing slightly aster.This option is enabled implicitly or SymbianOS, so there is no need to speci y it i you areusing that target.

Page 84: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 84/122

78 The GNU linker

The ‘--vfp11-denorm-fix ’ switch enables a link-time workaround or a bug in certainVFP11 coprocessor hardware, which sometimes allows instructions with denorm operands(which must be handled by support code) to have those operands overwritten by subsequentinstructions be ore the support code can read the intended values.The bug may be avoided in scalar mode i you allow at least one intervening instructionbetween a VFP11 instruction which uses a register and another instruction which writes tothe same register, or at least two intervening instructions i vector mode is in use. The bugonly afects ull-compliance oating-point mode: you do not need this workaround i youare using " run ast " mode. Please contact ARM or urther details.This workaround is enabled or scalar code by de ault or pre-ARMv7 architectures,but disabled by de ault or later architectures. I you know you are not using buggyVFP11 hardware, you can disable the workaround by speci ying the linker option‘--vfp-denorm-fix=none ’. I you are using VFP vector mode, you should speci y‘--vfp-denorm-fix=vector ’.I the workaround is enabled, instructions are scanned or potentially-troublesomesequences, and a veneer is created or each such sequence which may trigger the erratum.The veneer consists o the rst instruction o the sequence and a branch back to thesubsequent instruction. The original instruction is then replaced with a branch to theveneer. The extra cycles required to call and return rom the veneer are su cient to avoidthe erratum in both the scalar and vector cases.The ‘--no-enum-size-warning ’ switch prevents the linker rom warning when linking ob- ject les that speci y incompatible EABI enumeration size attributes. For example, withthis switch enabled, linking o an object le using 32-bit enumeration values with anotherusing enumeration values tted into the smallest possible space will not be diagnosed.The ‘--no-wchar-size-warning ’ switch prevents the linker rom warning when linkingobject les that speci y incompatible EABI wchar_t size attributes. For example, with thisswitch enabled, linking o an object le using 32-bit wchar_t values with another using16-bit wchar_t values will not be diagnosed.The ‘--pic-veneer ’ switch makes the linker use PIC sequences or ARM/Thumb inter-working veneers, even i the rest o the binary is not PIC. This avoids problems on uClinuxtargets where ‘ --emit-relocs ’ is used to generate relocatable binaries.The linker will automatically generate and insert small sequences o code into a linked ARMELF executable whenever an attempt is made to per orm a unction call to a symbol that istoo ar away. The placement o these sequences o instructions - called stubs - is controlledby the command line option ‘ --stub-group-size=N ’. The placement is important becausea poor choice can create a need or duplicate stubs, increasing the code sizw. The linkerwill try to group stubs together in order to reduce interruptions to the ow o code, but itneeds guidance as to how big these groups should be and where they should be placed.The value o ‘ N’, the parameter to the ‘ --stub-group-size= ’ option controls where thestub groups are placed. I it is negative then all stubs are placed a ter the rst branch thatneeds them. I it is positive then the stubs can be placed either be ore or a ter the branchesthat need them. I the value o ‘ N’ is 1 (either +1 or -1) then the linker will choose exactlywhere to place groups o stubs, using its built in heuristics. A value o ‘ N’ greater than 1(or smaller than -1) tells the linker that a single group o stubs can service at most ‘ N’ bytesrom the input sections.

Page 85: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 85/122

Chapter 4: Machine Dependent Features 79

The de ault, i ‘ --stub-group-size= ’ is not speci ed, is ‘ N = +1’.Farcalls stubs insertion is ully supported or the ARM-EABI target only, because it relieson object les properties not present otherwise.

The ‘--fix-cortex-a8 ’ switch enables a link-time workaround or an erratum in certainCortex-A8 processors. The workaround is enabled by de ault i you are targeting the ARMv7-A architecture pro le. It can be enabled otherwise by speci ying ‘ --fix-cortex-a8 ’, ordisabled unconditionally by speci ying ‘ --no-fix-cortex-a8 ’.The erratum only afects Thumb-2 code. Please contact ARM or urther details.

4.5 ld and HPPA 32-bit ELF SupportWhen generating a shared library, ld will by de ault generate import stubs suitable or usewith a single sub-space application. The ‘ --multi-subspace ’ switch causes ld to generateexport stubs, and diferent (larger) import stubs suitable or use with multiple sub-spaces.Long branch stubs and import/export stubs are placed by ld in stub sections locatedbetween groups o input sections. ‘ --stub-group-size ’ speci es the maximum size o agroup o input sections handled by one stub section. Since branch ofsets are signed, a stubsection may serve two groups o input sections, one group be ore the stub section, and onegroup a ter it. However, when using conditional branches that require stubs, it may bebetter ( or branch prediction) that stub sections only serve one group o input sections. Anegative value or ‘ N’ chooses this scheme, ensuring that branches to stubs always use anegative ofset. Two special values o ‘ N’ are recognized, ‘1’ and ‘-1 ’. These both instructld to automatically size input section groups or the branch types detected, with the samebehaviour regarding stub placement as other positive or negative values o ‘ N’ respectively.Note that ‘ --stub-group-size ’ does not split input sections. A single input section largerthan the group size speci ed will o course create a larger group (o one section). I input

sections are too large, it may not be possible or a branch to reach its stub.

4.6 ld and the Motorola 68K amilyThe ‘--got= type ’ option lets you choose the GOT generation scheme. The choices are‘single ’, ‘negative ’, ‘ multigot ’ and ‘target ’. When ‘target ’ is selected the linker choosesthe de ault GOT generation scheme or the current target. ‘ single ’ tells the linker togenerate a single GOT with entries only at non-negative ofsets. ‘ negative ’ instructs thelinker to generate a single GOT with entries at both negative and positive ofsets. Not allenvironments support such GOTs. ‘ multigot ’ allows the linker to generate several GOTsin the output le. All GOT re erences rom a single input object le access the sameGOT, but re erences rom diferent input object les might access diferent GOTs. Not all

environments support such GOTs.

4.7 ld and MMIXFor MMIX, there is a choice o generating ELF object les or mmoobject les when linking.The simulator mmix understands the mmo ormat. The binutils objcopy utility can translatebetween the two ormats.There is one special section, the ‘ .MMIX.reg_contents ’ section. Contents in this sec-tion is assumed to correspond to that o global registers, and symbols re erring to it are

Page 86: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 86/122

80 The GNU linker

translated to special symbols, equal to registers. In a nal link, the start address o the‘.MMIX.reg_contents ’ section corresponds to the rst allocated global register multipliedby 8. Register $255 is not included in this section; it is always set to the program entry,which is at the symbol Main or mmo les.Global symbols with the pre x __.MMIX.start. , or example __.MMIX.start..text and__.MMIX.start..data are special. The de ault linker script uses these to set the de aultstart address o a section.Initial and trailing multiples o zero-valued 32-bit words in a section, are le t out rom anmmo le.

4.8 ld and MSP430For the MSP430 it is possible to select the MPU architecture. The ag ‘ -m [mpu type] ’ willselect an appropriate linker script or selected MPU type. (To get a list o known MPUs just pass ‘-m help ’ option to the linker).

The linker will recognize some extra sections which are MSP430 speci c:‘.vectors’

De nes a portion o ROM where interrupt vectors located.

‘.bootloader’De nes the bootloader portion o the ROM (i applicable). Any code in thissection will be uploaded to the MPU.

‘.infomem’De nes an in ormation memory section (i applicable). Any code in this sectionwill be uploaded to the MPU.

‘.infomemnobits’This is the same as the ‘ .infomem ’ section except that any code in this sectionwill not be uploaded to the MPU.

‘.noinit’Denotes a portion o RAM located above ‘ .bss ’ section.The last two sections are used by gcc.

4.9 ld and PowerPC 32-bit ELF SupportBranches on PowerPC processors are limited to a signed 26-bit displacement, which mayresult in ld giving ‘relocation truncated to fit ’ errors with very large programs.‘--relax ’ enables the generation o trampolines that can access the entire 32-bit address

space. These trampolines are inserted at section boundaries, so may not themselves bereachable i an input section exceeds 33M in size. You may combine ‘ -r ’ and ‘--relax ’to add trampolines in a partial link. In that case both branches to unde ned symbolsand inter-section branches are also considered potentially out o range, and trampolinesinserted.

‘--bss-plt ’Current PowerPC GCC accepts a ‘ -msecure-plt ’ option that generates codecapable o using a newer PLT and GOT layout that has the security advantage

Page 87: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 87/122

Chapter 4: Machine Dependent Features 81

o no executable section ever needing to be writable and no writable sectionever being executable. PowerPC ld will generate this layout, including stubsto access the PLT, i all input les (including startup and static libraries) werecompiled with ‘-msecure-plt ’. ‘--bss-plt ’ orces the old BSS PLT (and GOTlayout) which can give slightly better per ormance.

‘--secure-plt ’ld will use the new PLT and GOT layout i it is linking new ‘ -fpic ’ or ‘-fPIC ’code, but does not do so automatically when linking non-PIC code. This optionrequests the new PLT and GOT layout. A warning will be given i some objectle requires the old style BSS PLT.

‘--sdata-got ’The new secure PLT and GOT are placed diferently relative to other sectionscompared to older BSS PLT and GOT placement. The location o .plt mustchange because the new secure PLT is an initialized section while the old PLT

is uninitialized. The reason or the .got change is more subtle: The newplacement allows .got to be read-only in applications linked with ‘ -z relro -znow’. However, this placement means that .sdata cannot always be used inshared libraries, because the PowerPC ABI accesses .sdata in shared librariesrom the GOT pointer. ‘ --sdata-got ’ orces the old GOT placement. PowerPCGCC doesn’t use .sdata in shared libraries, so this option is really only use ulor other compilers that may do so.

‘--emit-stub-syms ’This option causes ld to label linker stubs with a local symbol that encodes thestub type and destination.

‘--no-tls-optimize ’

PowerPC ld normally per orms some optimization o code sequences used toaccess Thread-Local Storage. Use this option to disable the optimization.

4.10 ld and PowerPC64 64-bit ELF Support‘--stub-group-size ’

Long branch stubs, PLT call stubs and TOC adjusting stubs are placed by ld instub sections located between groups o input sections. ‘ --stub-group-size ’speci es the maximum size o a group o input sections handled by one stubsection. Since branch ofsets are signed, a stub section may serve two groupso input sections, one group be ore the stub section, and one group a ter it.However, when using conditional branches that require stubs, it may be better( or branch prediction) that stub sections only serve one group o input sections.A negative value or ‘ N’ chooses this scheme, ensuring that branches to stubsalways use a negative ofset. Two special values o ‘ N’ are recognized, ‘1’ and‘-1 ’. These both instruct ld to automatically size input section groups or thebranch types detected, with the same behaviour regarding stub placement asother positive or negative values o ‘ N’ respectively.Note that ‘ --stub-group-size ’ does not split input sections. A single inputsection larger than the group size speci ed will o course create a larger group

Page 88: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 88/122

82 The GNU linker

(o one section). I input sections are too large, it may not be possible or abranch to reach its stub.

‘--emit-stub-syms ’

This option causes ld to label linker stubs with a local symbol that encodes thestub type and destination.

‘--dotsyms, --no-dotsyms ’These two options control how ld interprets version patterns in a version script.Older PowerPC64 compilers emitted both a unction descriptor symbol with thesame name as the unction, and a code entry symbol with the name pre xedby a dot (‘ . ’). To properly version a unction ‘ foo ’, the version script thusneeds to control both ‘ foo ’ and ‘.foo ’. The option ‘--dotsyms ’, on by de ault,automatically adds the required dot-pre xed patterns. Use ‘ --no-dotsyms ’ todisable this eature.

‘--no-tls-optimize ’

PowerPC64 ld normally per orms some optimization o code sequences used toaccess Thread-Local Storage. Use this option to disable the optimization.

‘--no-opd-optimize ’PowerPC64 ld normally removes .opd section entries corresponding to deletedlink-once unctions, or unctions removed by the action o ‘ --gc-sections ’ orlinker script /DISCARD/ . Use this option to disable .opd optimization.

‘--non-overlapping-opd ’Some PowerPC64 compilers have an option to generate compressed .opd entriesspaced 16 bytes apart, overlapping the third word, the static chain pointer(unused in C) with the rst word o the next entry. This option expands suchentries to the ull 24 bytes.

‘--no-toc-optimize ’PowerPC64 ld normally removes unused .toc section entries. Such entries aredetected by examining relocations that re erence the TOC in code sections. Areloc in a deleted code section marks a TOC word as unneeded, while a reloc ina kept code section marks a TOC word as needed. Since the TOC may re erenceitsel , TOC relocs are also examined. TOC words marked as both needed andunneeded will o course be kept. TOC words without any re erencing reloc areassumed to be part o a multi-word entry, and are kept or discarded as perthe nearest marked preceding word. This works reliably or compiler generatedcode, but may be incorrect i assembly code is used to insert TOC entries. Usethis option to disable the optimization.

‘--no-multi-toc ’By de ault, PowerPC64 GCC generates code or a TOC model where TOCentries are accessed with a 16-bit ofset rom r2. This limits the total TOCsize to 64K. PowerPC64 ld extends this limit by grouping code sections suchthat each group uses less than 64K or its TOC entries, then inserts r2 adjustingstubs between inter-group calls. ld does not split apart input sections, so cannothelp i a single input le has a .toc section that exceeds 64K, most likely romlinking multiple les with ld -r . Use this option to turn of this eature.

Page 89: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 89/122

Chapter 4: Machine Dependent Features 83

4.11 ld and SPU ELF Support‘--plugin ’

This option marks an executable as a PIC plugin module.

‘--no-overlays ’Normally, ld recognizes calls to unctions within overlay regions, and redirectssuch calls to an overlay manager via a stub. ld also provides a built-in overlaymanager. This option turns of all this special overlay handling.

‘--emit-stub-syms ’This option causes ld to label overlay stubs with a local symbol that encodesthe stub type and destination.

‘--extra-overlay-stubs ’This option causes ld to add overlay call stubs on all unction calls out o overlay regions. Normally stubs are not added on calls to non-overlay regions.

‘--local-store=lo:hi ’ld usually checks that a nal executable or SPU ts in the address range 0 to256k. This option may be used to change the range. Disable the check entirelywith ‘--local-store=0:0 ’.

‘--stack-analysis ’SPU local store space is limited. Over-allocation o stack space unnecessarilylimits space available or code and data, while under-allocation results in run-time ailures. I given this option, ld will provide an estimate o maximumstack usage. ld does this by examining symbols in code sections to determinethe extents o unctions, and looking at unction prologues or stack adjust-ing instructions. A call-graph is created by looking or relocations on branchinstructions. The graph is then searched or the maximum stack usage path.Note that this analysis does not nd calls made via unction pointers, and doesnot handle recursion and other cycles in the call graph. Stack usage may beunder-estimated i your code makes such calls. Also, stack usage or dynamicallocation, e.g. alloca, will not be detected. I a link map is requested, detailedin ormation about each unction’s stack usage and calls will be given.

‘--emit-stack-syms ’This option, i given along with ‘ --stack-analysis ’ will result in ld emit-ting stack sizing symbols or each unction. These take the orm __stack_<function_name> or global unctions, and __stack_<number>_<function_name> or static unctions. <number> is the section id in hex. The value o such symbols is the stack requirement or the corresponding unction. Thesymbol size will be zero, type STT_NOTYPE, binding STB_LOCAL, and sectionSHN_ABS.

4.12 ld ’s Support or Various TI COFF VersionsThe ‘--format ’ switch allows selection o one o the various TI COFF versions. The latesto this writing is 2; versions 0 and 1 are also supported. The TI COFF versions also varyin header byte-order ormat; ld will read any version or byte order, but the output headerormat depends on the de ault speci ed by the speci c target.

Page 90: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 90/122

84 The GNU linker

4.13 ld and WIN32 (cygwin/mingw)This section describes some o the win32 speci c ld issues. See Section 2.1 [Command LineOptions], page 3 or detailed description o the command line options mentioned here.

import libraries The standard Windows linker creates and uses so-called import libraries, whichcontains in ormation or linking to dll’s. They are regular static archives andare handled as any other static archive. The cygwin and mingw ports o ld havespeci c support or creating such libraries provided with the ‘ --out-implib ’command line option.

exporting DLL symbols The cygwin/mingw ld has several ways to export symbols or dll’s.using auto-export unctionality

By de ault ld exports symbols with the auto-export unctionality,which is controlled by the ollowing command line options:

• –export-all-symbols [This is the de ault]• –exclude-symbols• –exclude-libs• –exclude-modules- or-implib• –version-script

When auto-export is in operation, ld will export all the non-local(global and common) symbols it nds in a DLL, with the excep-tion o a ew symbols known to belong to the system’s runtimeand libraries. As it will o ten not be desirable to export all o aDLL’s symbols, which may include private unctions that are not

part o any public inter ace, the command-line options listed abovemay be used to lter symbols out rom the list or exporting. The‘--output-def ’ option can be used in order to see the nal list o exported symbols with all exclusions taken into efect.I ‘--export-all-symbols ’ is not given explicitly on the commandline, then the de ault auto-export behavior will be disabled i eithero the ollowing are true:

• A DEF le is used.• Any symbol in any object le was marked with the

declspec(dllexport) attribute.using a DEF fle

Another way o exporting symbols is using a DEF le. A DEF le isan ASCII le containing de nitions o symbols which should be ex-ported when a dll is created. Usually it is named ‘ <dll name>.def ’and is added as any other object le to the linker’s command line.The le’s name must end in ‘ .def ’ or ‘.DEF ’.

gcc -o <output> <objectfiles> <dll name>.defUsing a DEF le turns of the normal auto-export behavior, unlessthe ‘--export-all-symbols ’ option is also used.

Page 91: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 91/122

Chapter 4: Machine Dependent Features 85

Here is an example o a DEF le or a shared library called‘xyz.dll ’:

LIBRARY "xyz.dll" BASE=0x20000000

EXPORTSfoobar_bar = baranother_foo = abc.dll.afoovar1 DATA

This example de nes a DLL with a non-de ault base address andve symbols in the export table. The third exported symbol _bar isan alias or the second. The ourth symbol, another_foo is resolvedby " orwarding " to another module and treating it as an alias orafoo exported rom the DLL ‘ abc.dll ’. The nal symbol var1 isdeclared to be a data object.The optional LIBRARY <name> command indicates the internal name o the output DLL. I ‘ <name>’ does not include a su x, thede ault library su x, ‘ .DLL’ is appended.When the .DEF le is used to build an application, rather thana library, the NAME <name>command should be used instead o LIBRARY. I ‘<name>’ does not include a su x, the de ault exe-cutable su x, ‘ .EXE’ is appended.With either LIBRARY <name>or NAME <name>the optional speci -cation BASE = <number> may be used to speci y a non-de ault baseaddress or the image.

I neither LIBRARY <name>nor NAME <name>is speci ed, or theyspeci y an empty string, the internal name is the same as the le-name speci ed on the command line.The complete speci cation o an export symbol is:

EXPORTS( ( ( <name1> [ = <name2> ] )

| ( <name1> = <module-name> . <external-name>))[ @ <integer> ] [NONAME] [DATA] [CONSTANT] [PRIVATE] ) *

Declares ‘<name1> ’ as an exported symbol rom the DLL, or de-clares ‘<name1> ’ as an exported alias or ‘ <name2> ’; or declares‘<name1> ’ as a " orward " alias or the symbol ‘ <external-name> ’in the DLL ‘<module-name> ’. Optionally, the symbol may be ex-ported by the speci ed ordinal ‘ <integer> ’ alias.The optional keywords that ollow the declaration indicate:NONAME: Do not put the symbol name in the DLL’s export table. Itwill still be exported by its ordinal alias (either the value speci edby the .de speci cation or, otherwise, the value assigned by thelinker). The symbol name, however, does remain visible in theimport library (i any), unless PRIVATE is also speci ed.

Page 92: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 92/122

Page 93: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 93/122

Chapter 4: Machine Dependent Features 87

automatic data imports The standard Windows dll ormat supports data imports rom dlls only byadding special decorations (dllimport/dllexport), which let the compiler pro-duce speci c assembler instructions to deal with this issue. This increases theefort necessary to port existing Un*x code to these plat orms, especially orlarge c++ libraries and applications. The auto-import eature, which was ini-tially provided by Paul Sokolovsky, allows one to omit the decorations to achievea behavior that con orms to that on POSIX/Un*x plat orms. This eature isenabled with the ‘ --enable-auto-import ’ command-line option, although itis enabled by de ault on cygwin/mingw. The ‘ --enable-auto-import ’ optionitsel now serves mainly to suppress any warnings that are ordinarily emittedwhen linked objects trigger the eature’s use.auto-import o variables does not always work awlessly without additionalassistance. Sometimes, you will see this message" variable ’<var>’ can’t be auto-imported. Please read the documentation orld’s --enable-auto-import or details. "The ‘--enable-auto-import ’ documentation explains why this error occurs,and several methods that can be used to overcome this di culty. One o thesemethods is the runtime pseudo-relocs eature, described below.For complex variables imported rom DLLs (such as structs or classes), ob- ject les typically contain a base address or the variable and an ofset ( ad-dend ) within the variable–to speci y a particular eld or public member, orinstance. Un ortunately, the runtime loader used in win32 environments is in-capable o xing these re erences at runtime without the additional in ormationsupplied by dllimport/dllexport decorations. The standard auto-import eaturedescribed above is unable to resolve these re erences.The ‘--enable-runtime-pseudo-relocs ’ switch allows these re erences to beresolved without error, while leaving the task o adjusting the re erences them-selves (with their non-zero addends) to specialized code provided by the run-time environment. Recent versions o the cygwin and mingw environments andcompilers provide this runtime support; older versions do not. However, thesupport is only necessary on the developer’s plat orm; the compiled result willrun without error on an older system.‘--enable-runtime-pseudo-relocs ’ is not the de ault; it must be explicitlyenabled as needed.

direct linking to a dll The cygwin/mingw ports o ld support the direct linking, including data sym-bols, to a dll without the usage o any import libraries. This is much asterand uses much less memory than does the traditional import library method,especially when linking large libraries or applications. When ld creates an im-port lib, each unction or variable exported rom the dll is stored in its own b d,even though a single b d could contain many exports. The overhead involvedin storing, loading, and processing so many b d’s is quite large, and explainsthe tremendous time, memory, and storage needed to link against particularlylarge or complex libraries when using import libs.

Page 94: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 94/122

88 The GNU linker

Linking directly to a dll uses no extra command-line switches other than ‘ -L ’and ‘-l ’, because ld already searches or a number o names to match eachlibrary. All that is needed rom the developer’s perspective is an understandingo this search, in order to orce ld to select the dll instead o an import library.For instance, when ld is called with the argument ‘ -lxxx ’ it will attempt tond, in the rst directory o its search path,

libxxx.dll.axxx.dll.alibxxx.axxx.libcygxxx.dll (*)libxxx.dllxxx.dll

be ore moving on to the next directory in the search path.

(*) Actually, this is not ‘ cygxxx.dll ’ but in act is ‘<prefix>xxx.dll ’, where‘<prefix> ’ is set by the ld option ‘--dll-search-prefix=<prefix> ’. In thecase o cygwin, the standard gcc spec le includes ‘ --dll-search-prefix=cyg ’,so in efect we actually search or ‘ cygxxx.dll ’.Other win32-based unix environments, such as mingw or pw32, may use other‘<prefix> ’es, although at present only cygwin makes use o this eature. Itwas originally intended to help avoid name con icts among dll’s built or thevarious win32/un*x environments, so that ( or example) two versions o a zlibdll could coexist on the same machine.The generic cygwin/mingw path layout uses a ‘ bin ’ directory or applicationsand dll’s and a ‘ lib ’ directory or the import libraries (using cygwin nomencla-

ture):bin/cygxxx.dlllib/libxxx.dll.a (in case of dll’s)libxxx.a (in case of static archive)

Linking directly to a dll without using the import library can be done two ways:1. Use the dll directly by adding the ‘ bin ’ path to the link line

gcc -Wl,-verbose -o a.exe -L../bin/ -lxxx

However, as the dll’s o ten have version numbers appended to their names

(‘cygncurses-5.dll ’) this will o ten ail, unless one speci es ‘ -L../bin-lncurses-5 ’ to include the version. Import libs are generally not versioned,and do not have this di culty.2. Create a symbolic link rom the dll to a le in the ‘ lib ’ directory accordingto the above mentioned search pattern. This should be used to avoid unwantedchanges in the tools needed or making the app/dll.

ln -s bin/cygxxx.dll lib/[cyg|lib|]xxx.dll[.a]

Then you can link without any make environment changes.

Page 95: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 95/122

Chapter 4: Machine Dependent Features 89

gcc -Wl,-verbose -o a.exe -L../lib/ -lxxx

This technique also avoids the version number problems, because the ollowingis per ectly legal

bin/cygxxx-5.dlllib/libxxx.dll.a -> ../bin/cygxxx-5.dll

Linking directly to a dll without using an import lib will workeven when auto-import eatures are exercised, and even when‘--enable-runtime-pseudo-relocs ’ is used.Given the improvements in speed and memory usage, one might justi ablywonder why import libraries are used at all. There are three reasons:1. Until recently, the link-directly-to-dll unctionality did not work with auto-imported data.2. Sometimes it is necessary to include pure static objects within the importlibrary (which otherwise contains only b d’s or indirection symbols that pointto the exports o a dll). Again, the import lib or the cygwin kernel makes useo this ability, and it is not possible to do this without an import lib.3. Symbol aliases can only be resolved using an import lib. This is criticalwhen linking against OS-supplied dll’s (eg, the win32 API) in which symbolsare usually exported as undecorated aliases o their stdcall-decorated assemblynames.So, import libs are not going away. But the ability to replace true import libswith a simple symbolic link to (or a copy o ) a dll, in many cases, is a use uladdition to the suite o tools binutils makes available to the win32 developer.Given the massive improvements in memory requirements during linking, stor-age requirements, and linking speed, we expect that many developers will soonbegin to use this eature whenever possible.

symbol aliasing

adding additional names Sometimes, it is use ul to export symbols with additional names. Asymbol ‘foo ’ will be exported as ‘foo ’, but it can also be exportedas ‘_foo ’ by using special directives in the DEF le when creatingthe dll. This will afect also the optional created import library.Consider the ollowing DEF le:

LIBRARY "xyz.dll" BASE=0x61000000

EXPORTSfoo_foo = foo

The line ‘_foo = foo ’ maps the symbol ‘ foo ’ to ‘_foo ’.Another method or creating a symbol alias is to create it in thesource code using the " weak" attribute:

Page 96: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 96/122

90 The GNU linker

void foo () { /* Do something. */; }void _foo () __attribute__ ((weak, alias ("foo")));

See the gcc manual or more in ormation about attributes and weak

symbols.renaming symbols

Sometimes it is use ul to rename exports. For instance, the cygwinkernel does this regularly. A symbol ‘ _foo ’ can be exported as ‘ foo ’but not as ‘ _foo ’ by using special directives in the DEF le. (Thiswill also afect the import library, i it is created). In the ollowingexample:

LIBRARY "xyz.dll" BASE=0x61000000

EXPORTS_foo = foo

The line ‘_foo = foo ’ maps the exported symbol ‘ foo ’ to ‘_foo ’.Note: using a DEF le disables the de ault auto-export behavior, unless the‘--export-all-symbols ’ command line option is used. I , however, you aretrying to rename symbols, then you should list all desired exports in the DEFle, including the symbols that are not being renamed, and do not use the‘--export-all-symbols ’ option. I you list only the renamed symbols in theDEF le, and use ‘ --export-all-symbols ’ to handle the other symbols, thenthe both the new names and the original names or the renamed symbols willbe exported. In efect, you’d be aliasing those symbols, not renaming them,which is probably not what you wanted.

weak externals The Windows object ormat, PE, speci es a orm o weak symbols called weakexternals. When a weak symbol is linked and the symbol is not de ned, theweak symbol becomes an alias or some other symbol. There are three variantso weak externals:

• De nition is searched or in objects and libraries, historically called lazyexternals.

• De nition is searched or only in other objects, not in libraries. This ormis not presently implemented.

• No search; the symbol is an alias. This orm is not presently implemented.

As a GNU extension, weak symbols that do not speci y an alternate symbol are

supported. I the symbol is unde ned when linking, the symbol uses a de aultvalue.

aligned common symbols As a GNU extension to the PE le ormat, it is possible to speci y the desiredalignment or a common symbol. This in ormation is conveyed rom the assem-bler or compiler to the linker by means o GNU-speci c commands carried inthe object le’s ‘ .drectve ’ section, which are recognized by ld and respectedwhen laying out the common symbols. Native tools will be able to process ob-

Page 97: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 97/122

Chapter 4: Machine Dependent Features 91

ject les employing this GNU extension, but will ail to respect the alignmentinstructions, and may issue noisy warnings about unknown linker directives.

4.14 ld and Xtensa ProcessorsThe de ault ld behavior or Xtensa processors is to interpret SECTIONScommands so thatlists o explicitly named sections in a speci cation with a wildcard le will be interleavedwhen necessary to keep literal pools within the range o PC-relative load ofsets. Forexample, with the command:

SECTIONS{

.text : {*(.literal .text)

}}

ld may interleave some o the .literal and .text sections rom diferent object lesto ensure that the literal pools are within the range o PC-relative load ofsets. A validinterleaving might place the .literal sections rom an initial group o les ollowed by the.text sections o that group o les. Then, the .literal sections rom the rest o the lesand the .text sections rom the rest o the les would ollow.Relaxation is enabled by de ault or the Xtensa version o ld and provides two impor-tant link-time optimizations. The rst optimization is to combine identical literal valuesto reduce code size. A redundant literal will be removed and all the L32R instructionsthat use it will be changed to re erence an identical literal, as long as the location o thereplacement literal is within the ofset range o all the L32R instructions. The second opti-mization is to remove unnecessary overhead rom assembler-generated “longcall” sequenceso L32R/ CALLXn when the target unctions are within range o direct CALLn instructions.For each o these cases where an indirect call sequence can be optimized to a direct call,the linker will change the CALLXn instruction to a CALLn instruction, remove the L32Rinstruction, and remove the literal re erenced by the L32R instruction i it is not used oranything else. Removing the L32R instruction always reduces code size but can potentiallyhurt per ormance by changing the alignment o subsequent branch targets. By de ault, thelinker will always preserve alignments, either by switching some instructions between 24-bitencodings and the equivalent density instructions or by inserting a no-op in place o theL32R instruction that was removed. I code size is more important than per ormance, the‘--size-opt ’ option can be used to prevent the linker rom widening density instructionsor inserting no-ops, except in a ew cases where no-ops are required or correctness.The ollowing Xtensa-speci c command-line options can be used to control the linker:

‘--no-relax ’Since the Xtensa version o ld enables the ‘ --relax ’ option by de ault, the‘--no-relax ’ option is provided to disable relaxation.

‘--size-opt ’When optimizing indirect calls to direct calls, optimize or code size more thanper ormance. With this option, the linker will not insert no-ops or widen densityinstructions to preserve branch target alignment. There may still be some caseswhere no-ops are required to preserve the correctness o the code.

Page 98: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 98/122

Page 99: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 99/122

Chapter 5: BFD 93

5 BFDThe linker accesses object and archive les using the BFD libraries. These libraries allowthe linker to use the same routines to operate on object les whatever the ob ject le ormat.A diferent object le ormat can be supported simply by creating a new BFD back end andadding it to the library. To conserve runtime memory, however, the linker and associatedtools are usually con gured to support only a subset o the object le ormats available.You can use objdump -i (see Section “objdump” in The GNU Binary Utilities ) to list allthe ormats available or your con guration.As with most implementations, BFD is a compromise between several con icting require-ments. The major actor in uencing BFD design was e ciency: any time used convertingbetween ormats is time which would not have been spent had BFD not been involved. Thisis partly ofset by abstraction payback; since BFD simpli es applications and back ends,more time and care may be spent optimizing algorithms or a greater speed.One minor arti act o the BFD solution which you should bear in mind is the potential or

in ormation loss. There are two places where use ul in ormation can be lost using the BFDmechanism: during conversion and during output. See Section 5.1.1 [BFD in ormation loss],page 93.

5.1 How It Works: An Outline o BFDWhen an object le is opened, BFD subroutines automatically determine the ormat o theinput object le. They then build a descriptor in memory with pointers to routines thatwill be used to access elements o the object le’s data structures.As diferent in ormation rom the object les is required, BFD reads rom diferent sectionso the le and processes them. For example, a very common operation or the linker isprocessing symbol tables. Each BFD back end provides a routine or converting between

the object le’s representation o symbols and an internal canonical ormat. When thelinker asks or the symbol table o an object le, it calls through a memory pointer to theroutine rom the relevant BFD back end which reads and converts the table into a canonicalorm. The linker then operates upon the canonical orm. When the link is nished and thelinker writes the output le’s symbol table, another BFD back end routine is called to takethe newly created symbol table and convert it into the chosen output ormat.

5.1.1 In ormation LossIn ormation can be lost during output. The output ormats supported by BFD do notprovide identical acilities, and in ormation which can be described in one orm has nowhereto go in another ormat. One example o this is alignment in ormation in b.out . There isnowhere in an a.out ormat le to store alignment in ormation on the contained data, sowhen a le is linked rom b.out and an a.out image is produced, alignment in ormationwill not propagate to the output le. (The linker will still use the alignment in ormationinternally, so the link is per ormed correctly).Another example is COFF section names. COFF les may contain an unlimited number o sections, each one with a textual section name. I the target o the link is a ormat whichdoes not have many sections (e.g., a.out ) or has sections without names (e.g., the Oasysormat), the link cannot be done simply. You can circumvent this problem by describingthe desired input-to-output section mapping with the linker command language.

Page 100: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 100/122

94 The GNU linker

In ormation can be lost during canonicalization. The BFD internal canonical orm o theexternal ormats is not exhaustive; there are structures in input ormats or which there isno direct representation internally. This means that the BFD back ends cannot maintainall possible data richness through the trans ormation between external to internal and backto external ormats.

This limitation is only a problem when an application reads one ormat and writes another.Each BFD back end is responsible or maintaining as much data as possible, and the internalBFD canonical orm has structures which are opaque to the BFD core, and exported onlyto the back ends. When a le is read in one ormat, the canonical orm is generated orBFD and the application. At the same time, the back end saves away any in ormationwhich may otherwise be lost. I the data is then written back in the same ormat, the backend routine will be able to use the canonical orm provided by the BFD core as well as thein ormation it prepared earlier. Since there is a great deal o commonality between backends, there is no in ormation lost when linking or copying big endian COFF to little endianCOFF, or a.out to b.out . When a mixture o ormats is linked, the in ormation is onlylost rom the les whose ormat difers rom the destination.

5.1.2 The BFD canonical object-fle ormatThe greatest potential or loss o in ormation occurs when there is the least overlap betweenthe in ormation provided by the source ormat, that stored by the canonical ormat, andthat needed by the destination ormat. A brie description o the canonical orm may helpyou understand which kinds o data you can count on preserving across conversions.

fles In ormation stored on a per- le basis includes target machine architecture, par-ticular implementation ormat type, a demand pageable bit, and a write pro-tected bit. In ormation like Unix magic numbers is not stored here—only themagic numbers’ meaning, so a ZMAGICle would have both the demand page-able bit and the write protected text bit set. The byte order o the target isstored on a per- le basis, so that big- and little-endian object les may be usedwith one another.

sections Each section in the input le contains the name o the section, the section’soriginal address in the object le, size and alignment in ormation, various ags,and pointers into other BFD data structures.

symbols Each symbol contains a pointer to the in ormation or the object le whichoriginally de ned it, its name, its value, and various ag bits. When a BFDback end reads in a symbol table, it relocates all symbols to make them relativeto the base o the section where they were de ned. Doing this ensures thateach symbol points to its containing section. Each symbol also has a varyingamount o hidden private data or the BFD back end. Since the symbol pointsto the original le, the private data ormat or that symbol is accessible. ld canoperate on a collection o symbols o wildly diferent ormats without problems.Normal global and simple local symbols are maintained on output, so an outputle (no matter its ormat) will retain symbols pointing to unctions and toglobal, static, and common variables. Some symbol in ormation is not worthretaining; in a.out , type in ormation is stored in the symbol table as long

Page 101: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 101/122

Page 102: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 102/122

Page 103: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 103/122

Chapter 6: Reporting Bugs 97

6 Reporting BugsYour bug reports play an essential role in making ld reliable.Reporting a bug may help you by bringing a solution to your problem, or it may not. Butin any case the principal unction o a bug report is to help the entire community by makingthe next version o ld work better. Bug reports are your contribution to the maintenanceo ld .In order or a bug report to serve its purpose, you must include the in ormation that enablesus to x the bug.

6.1 Have You Found a Bug?I you are not sure whether you have ound a bug, here are some guidelines:

• I the linker gets a atal signal, or any input whatever, that is a ld bug. Reliablelinkers never crash.

• I ld produces an error message or valid input, that is a bug.• I ld does not produce an error message or invalid input, that may be a bug. In the

general case, the linker can not veri y that object les are correct.• I you are an experienced user o linkers, your suggestions or improvement o ld are

welcome in any case.

6.2 How to Report BugsA number o companies and individuals ofer support or gnu products. I you obtained ldrom a support organization, we recommend you contact that organization rst.You can nd contact in ormation or many support companies and individuals in the le‘etc/SERVICE ’ in the gnu Emacs distribution.Otherwise, send bug reports or ld to https://support.codesourcery.com/GNUToolchain/ .The undamental principle o reporting bugs use ully is this: report all the facts . I you arenot sure whether to state a act or leave it out, state it!O ten people omit acts because they think they know what causes the problem and assumethat some details do not matter. Thus, you might assume that the name o a symbol youuse in an example does not matter. Well, probably it does not, but one cannot be sure.Perhaps the bug is a stray memory re erence which happens to etch rom the locationwhere that name is stored in memory; perhaps, i the name were diferent, the contents o that location would ool the linker into doing the right thing despite the bug. Play it sa eand give a speci c, complete example. That is the easiest thing or you to do, and the mosthelp ul.

Keep in mind that the purpose o a bug report is to enable us to x the bug i it is new tous. There ore, always write your bug reports on the assumption that the bug has not beenreported previously.Sometimes people give a ew sketchy acts and ask, “Does this ring a bell?” This cannothelp us x a bug, so it is basically useless. We respond by asking or enough details toenable us to investigate. You might as well expedite matters by sending them to beginwith.To enable us to x the bug, you should include all these things:

Page 104: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 104/122

Page 105: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 105/122

Chapter 6: Reporting Bugs 99

This is o ten time consuming and not very use ul, because the way we will nd thebug is by running a single example under the debugger with breakpoints, not by purededuction rom a series o examples. We recommend that you save your time orsomething else.O course, i you can nd a simpler example to report instead o the original one, thatis a convenience or us. Errors in the output will be easier to spot, running under thedebugger will take less time, and so on.However, simpli cation is not vital; i you do not want to do this, report the buganyway and send us the entire test case you used.

• A patch or the bug.A patch or the bug does help us i it is a good one. But do not omit the necessaryin ormation, such as the test case, on the assumption that a patch is all we need. Wemight see problems with your patch and decide to x the problem another way, or wemight not understand it at all.

Sometimes with a program as complicated as ld it is very hard to construct an examplethat will make the program ollow a certain path through the code. I you do not sendus the example, we will not be able to construct one, so we will not be able to veri ythat the bug is xed.And i we cannot understand what bug you are trying to x, or why your patch shouldbe an improvement, we will not install it. A test case will help us to understand.

• A guess about what the bug is or what it depends on.Such guesses are usually wrong. Even we cannot guess right about such things withoutrst using the debugger to nd the acts.

Page 106: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 106/122

Page 107: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 107/122

Appendix A: MRI Compatible Script Files 101

Appendix A MRI Compatible Script Files

To aid users making the transition to gnu ld rom the MRI linker, ld can use MRI com-

patible linker scripts as an alternative to the more general-purpose linker scripting languagedescribed in Chapter 3 [Scripts], page 37 . MRI compatible linker scripts have a much sim-pler command set than the scripting language otherwise used with ld . gnu ld supportsthe most commonly used MRI linker commands; these commands are described here.In general, MRI scripts aren’t o much use with the a.out object le ormat, since it onlyhas three sections and MRI scripts lack some eatures to make use o them.You can speci y a le containing an MRI-compatible script using the ‘ -c ’ command-lineoption.Each command in an MRI-compatible script occupies its own line; each command line startswith the keyword that identi es the command (though blank lines are also allowed orpunctuation). I a line o an MRI-compatible script begins with an unrecognized keyword,

ld issues a warning message, but continues processing the script.Lines beginning with ‘ *’ are comments.You can write these commands using all upper-case letters, or all lower case; or example,‘chip ’ is the same as ‘CHIP’. The ollowing list shows only the upper-case orm o eachcommand.

ABSOLUTEsecnameABSOLUTEsecname , secname , ... secname

Normally, ld includes in the output le all sections rom all the input les.However, in an MRI-compatible script, you can use the ABSOLUTEcommandto restrict the sections that will be present in your output program. I theABSOLUTEcommand is used at all in a script, then only the sections namedexplicitly in ABSOLUTEcommands will appear in the linker output. You canstill use other input sections (whatever you select on the command line, orusing LOAD) to resolve addresses in the output le.

ALIAS out-secname , in-secnameUse this command to place the data rom input section in-secname in a sectioncalled out-secname in the linker output le.in-secname may be an integer.

ALIGNsecname = expressionAlign the section called secname to expression . The expression should be apower o two.

BASEexpressionUse the value o expression as the lowest address (other than absolute addresses)in the output le.

CHIP expressionCHIP expression , expression

This command does nothing; it is accepted only or compatibility.

END This command does nothing whatever; it’s only accepted or compatibility.

Page 108: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 108/122

102 The GNU linker

FORMAToutput-formatSimilar to the OUTPUT_FORMATcommand in the more general linker language,but restricted to one o these output ormats:

1. S-records, i output- ormat

is ‘S

’2. IEEE, i output- ormat is ‘IEEE’3. COFF (the ‘ coff-m68k ’ variant in BFD), i output- ormat is ‘COFF’

LIST anything ...Print (to the standard output le) a link map, as produced by the ld command-line option ‘-M’.The keyword LIST may be ollowed by anything on the same line, with nochange in its efect.

LOADfilenameLOADfilename , filename , ... filename

Include one or more object le lename in the link; this has the same efect asspeci ying lename directly on the ld command line.

NAMEoutput-nameoutput-name is the name or the program produced by ld ; the MRI-compatiblecommand NAMEis equivalent to the command-line option ‘ -o ’ or the generalscript language command OUTPUT.

ORDERsecname , secname , ... secnameORDERsecname secname secname

Normally, ld orders the sections in its output le in the order in which theyrst appear in the input les. In an MRI-compatible script, you can overridethis ordering with the ORDERcommand. The sections you list with ORDERwill

appear rst in your output le, in the order speci ed.PUBLIC name =expressionPUBLIC name , expressionPUBLIC name expression

Supply a value ( expression ) or external symbol name used in the linker inputles.

SECT secname , expressionSECT secname =expressionSECT secname expression

You can use any o these three orms o the SECT command to speci y thestart address ( expression ) or section secname . I you have more than one SECT

statement or the same secname , only the frst sets the start address.

Page 109: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 109/122

Appendix B: GNU Free Documentation License 103

Appendix B GNU Free Documentation License

Version 1.1, March 2000

Copyright (C) 2000, 2003 Free So tware Foundation, Inc.51 Franklin Street, Fi th Floor, Boston, MA 02110-1301 USA

Everyone is permitted to copy and distribute verbatim copieso this license document, but changing it is not allowed.

0. PREAMBLEThe purpose o this License is to make a manual, textbook, or other written document“ ree” in the sense o reedom: to assure everyone the efective reedom to copy andredistribute it, with or without modi ying it, either commercially or noncommercially.Secondarily, this License preserves or the author and publisher a way to get credit or

their work, while not being considered responsible or modi cations made by others.This License is a kind o “copyle t”, which means that derivative works o the documentmust themselves be ree in the same sense. It complements the GNU General PublicLicense, which is a copyle t license designed or ree so tware.We have designed this License in order to use it or manuals or ree so tware, becauseree so tware needs ree documentation: a ree program should come with manualsproviding the same reedoms that the so tware does. But this License is not limited toso tware manuals; it can be used or any textual work, regardless o subject matter orwhether it is published as a printed book. We recommend this License principally orworks whose purpose is instruction or re erence.

1. APPLICABILITY AND DEFINITIONSThis License applies to any manual or other work that contains a notice placed bythe copyright holder saying it can be distributed under the terms o this License. The“Document”, below, re ers to any such manual or work. Any member o the public isa licensee, and is addressed as “you.”A “Modi ed Version” o the Document means any work containing the Document ora portion o it, either copied verbatim, or with modi cations and/or translated intoanother language.A “Secondary Section” is a named appendix or a ront-matter section o the Documentthat deals exclusively with the relationship o the publishers or authors o the Documentto the Document’s overall subject (or to related matters) and contains nothing thatcould all directly within that overall subject. (For example, i the Document is in part atextbook o mathematics, a Secondary Section may not explain any mathematics.) Therelationship could be a matter o historical connection with the subject or with relatedmatters, or o legal, commercial, philosophical, ethical or political position regardingthem.The “Invariant Sections” are certain Secondary Sections whose titles are designated, asbeing those o Invariant Sections, in the notice that says that the Document is releasedunder this License.

Page 110: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 110/122

104 The GNU linker

The “Cover Texts” are certain short passages o text that are listed, as Front-CoverTexts or Back-Cover Texts, in the notice that says that the Document is released underthis License.

A “Transparent” copy o the Document means a machine-readable copy, representedin a ormat whose speci cation is available to the general public, whose contents canbe viewed and edited directly and straight orwardly with generic text editors or ( orimages composed o pixels) generic paint programs or ( or drawings) some widely avail-able drawing editor, and that is suitable or input to text ormatters or or automatictranslation to a variety o ormats suitable or input to text ormatters. A copy madein an otherwise Transparent le ormat whose markup has been designed to thwart ordiscourage subsequent modi cation by readers is not Transparent. A copy that is not“Transparent” is called “Opaque.”Examples o suitable ormats or Transparent copies include plain ASCII withoutmarkup, Texin o input ormat, LaTeX input ormat, SGML or XML using a publiclyavailable DTD, and standard-con orming simple HTML designed or human modi ca-tion. Opaque ormats include PostScript, PDF, proprietary ormats that can be readand edited only by proprietary word processors, SGML or XML or which the DTDand/or processing tools are not generally available, and the machine-generated HTMLproduced by some word processors or output purposes only.The “Title Page” means, or a printed book, the title page itsel , plus such ollowingpages as are needed to hold, legibly, the material this License requires to appear in thetitle page. For works in ormats which do not have any title page as such, “Title Page”means the text near the most prominent appearance o the work’s title, preceding thebeginning o the body o the text.

2. VERBATIM COPYINGYou may copy and distribute the Document in any medium, either commercially ornoncommercially, provided that this License, the copyright notices, and the licensenotice saying this License applies to the Document are reproduced in all copies, andthat you add no other conditions whatsoever to those o this License. You may not usetechnical measures to obstruct or control the reading or urther copying o the copiesyou make or distribute. However, you may accept compensation in exchange or copies.I you distribute a large enough number o copies you must also ollow the conditionsin section 3.You may also lend copies, under the same conditions stated above, and you may publiclydisplay copies.

3. COPYING IN QUANTITYI you publish printed copies o the Document numbering more than 100, and theDocument’s license notice requires Cover Texts, you must enclose the copies in coversthat carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the rontcover, and Back-Cover Texts on the back cover. Both covers must also clearly andlegibly identi y you as the publisher o these copies. The ront cover must present theull title with all words o the title equally prominent and visible. You may add othermaterial on the covers in addition. Copying with changes limited to the covers, as long

Page 111: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 111/122

Appendix B: GNU Free Documentation License 105

as they preserve the title o the Document and satis y these conditions, can be treatedas verbatim copying in other respects.I the required texts or either cover are too voluminous to t legibly, you should putthe rst ones listed (as many as t reasonably) on the actual cover, and continue therest onto adjacent pages.I you publish or distribute Opaque copies o the Document numbering more than 100,you must either include a machine-readable Transparent copy along with each Opaquecopy, or state in or with each Opaque copy a publicly-accessible computer-networklocation containing a complete Transparent copy o the Document, ree o added ma-terial, which the general network-using public has access to download anonymously atno charge using public-standard network protocols. I you use the latter option, youmust take reasonably prudent steps, when you begin distribution o Opaque copiesin quantity, to ensure that this Transparent copy will remain thus accessible at thestated location until at least one year a ter the last time you distribute an Opaquecopy (directly or through your agents or retailers) o that edition to the public.It is requested, but not required, that you contact the authors o the Document wellbe ore redistributing any large number o copies, to give them a chance to provide youwith an updated version o the Document.

4. MODIFICATIONSYou may copy and distribute a Modi ed Version o the Document under the conditionso sections 2 and 3 above, provided that you release the Modi ed Version under preciselythis License, with the Modi ed Version lling the role o the Document, thus licensingdistribution and modi cation o the Modi ed Version to whoever possesses a copy o it. In addition, you must do these things in the Modi ed Version:A. Use in the Title Page (and on the covers, i any) a title distinct rom that o theDocument, and rom those o previous versions (which should, i there were any, belisted in the History section o the Document). You may use the same title as a previousversion i the original publisher o that version gives permission.B. List on the Title Page, as authors, one or more persons or entities responsible orauthorship o the modi cations in the Modi ed Version, together with at least ve o the principal authors o the Document (all o its principal authors, i it has less thanve).C. State on the Title page the name o the publisher o the Modi ed Version, as thepublisher.D. Preserve all the copyright notices o the Document.E. Add an appropriate copyright notice or your modi cations adjacent to the othercopyright notices.F. Include, immediately a ter the copyright notices, a license notice giving the publicpermission to use the Modi ed Version under the terms o this License, in the ormshown in the Addendum below.G. Preserve in that license notice the ull lists o Invariant Sections and required CoverTexts given in the Document’s license notice.H. Include an unaltered copy o this License.I. Preserve the section entitled “History”, and its title, and add to it an item stating atleast the title, year, new authors, and publisher o the Modi ed Version as given on the

Page 112: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 112/122

106 The GNU linker

Title Page. I there is no section entitled “History” in the Document, create one statingthe title, year, authors, and publisher o the Document as given on its Title Page, thenadd an item describing the Modi ed Version as stated in the previous sentence.J. Preserve the network location, i any, given in the Document or public access toa Transparent copy o the Document, and likewise the network locations given in theDocument or previous versions it was based on. These may be placed in the “History”section. You may omit a network location or a work that was published at least ouryears be ore the Document itsel , or i the original publisher o the version it re ers togives permission.K. In any section entitled “Acknowledgements” or “Dedications”, preserve the section’stitle, and preserve in the section all the substance and tone o each o the contributoracknowledgements and/or dedications given therein.L. Preserve all the Invariant Sections o the Document, unaltered in their text and intheir titles. Section numbers or the equivalent are not considered part o the sectiontitles.

M. Delete any section entitled “Endorsements.” Such a section may not be included inthe Modi ed Version.N. Do not retitle any existing section as “Endorsements” or to con ict in title with anyInvariant Section.

I the Modi ed Version includes new ront-matter sections or appendices that quali yas Secondary Sections and contain no material copied rom the Document, you may atyour option designate some or all o these sections as invariant. To do this, add theirtitles to the list o Invariant Sections in the Modi ed Version’s license notice. Thesetitles must be distinct rom any other section titles.You may add a section entitled “Endorsements”, provided it contains nothing butendorsements o your Modi ed Version by various parties– or example, statements o peer review or that the text has been approved by an organization as the authoritativede nition o a standard.You may add a passage o up to ve words as a Front-Cover Text, and a passage o upto 25 words as a Back-Cover Text, to the end o the list o Cover Texts in the Modi edVersion. Only one passage o Front-Cover Text and one o Back-Cover Text may beadded by (or through arrangements made by) any one entity. I the Document alreadyincludes a cover text or the same cover, previously added by you or by arrangementmade by the same entity you are acting on behal o , you may not add another; butyou may replace the old one, on explicit permission rom the previous publisher thatadded the old one.The author(s) and publisher(s) o the Document do not by this License give permissionto use their names or publicity or or to assert or imply endorsement o any Modi edVersion.

5. COMBINING DOCUMENTSYou may combine the Document with other documents released under this License,under the terms de ned in section 4 above or modi ed versions, provided that youinclude in the combination all o the Invariant Sections o all o the original documents,

Page 113: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 113/122

Page 114: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 114/122

108 The GNU linker

between the translation and the original English version o this License, the originalEnglish version will prevail.

9. TERMINATIONYou may not copy, modi y, sublicense, or distribute the Document except as expresslyprovided or under this License. Any other attempt to copy, modi y, sublicense ordistribute the Document is void, and will automatically terminate your rights underthis License. However, parties who have received copies, or rights, rom you under thisLicense will not have their licenses terminated so long as such parties remain in ullcompliance.

10. FUTURE REVISIONS OF THIS LICENSEThe Free So tware Foundation may publish new, revised versions o the GNU FreeDocumentation License rom time to time. Such new versions will be similar in spiritto the present version, but may difer in detail to address new problems or concerns.See http://www.gnu.org/copyle t/.Each version o the License is given a distinguishing version number. I the Documentspeci es that a particular numbered version o this License “or any later version”applies to it, you have the option o ollowing the terms and conditions either o thatspeci ed version or o any later version that has been published (not as a dra t) bythe Free So tware Foundation. I the Document does not speci y a version number o this License, you may choose any version ever published (not as a dra t) by the FreeSo tware Foundation.

ADDENDUM: How to use this License or your documentsTo use this License in a document you have written, include a copy o the License in thedocument and put the ollowing copyright and license notices just a ter the title page:

Copyright (C) year your name .Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.1or any later version published by the Free Software Foundation;with the Invariant Sections being list their titles , with theFront-Cover Texts being list , and with the Back-Cover Texts being list .A copy of the license is included in the section entitled "GNUFree Documentation License."

I you have no Invariant Sections, write “with no Invariant Sections” instead o saying whichones are invariant. I you have no Front-Cover Texts, write “no Front-Cover Texts” insteado “Front-Cover Texts being list ”; likewise or Back-Cover Texts.

I your document contains nontrivial examples o program code, we recommend releasingthese examples in parallel under your choice o ree so tware license, such as the GNUGeneral Public License, to permit their use in ree so tware.

Page 115: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 115/122

LD Index 109

LD Index

"

" . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67

--( . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13--accept-unknown-input-arch . . . . . . . . . . . . . . . . 13--add-needed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14--add-stdcall-alias . . . . . . . . . . . . . . . . . . . . . . . . .28--allow-multiple-definition . . . . . . . . . . . . . . . . 18--allow-shlib-undefined . . . . . . . . . . . . . . . . . . . . .18--architecture= arch . . . . . . . . . . . . . . . . . . . . . . . . . .4--as-needed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14--auxiliary= name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6--bank-window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34--base-file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28--be8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77--bss-plt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .80--build-id . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .27--build-id= style . . . . . . . . . . . . . . . . . . . . . . . . . . . .27--check-sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15--cref . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16--default-imported-symver . . . . . . . . . . . . . . . . . . 18--default-script= script . . . . . . . . . . . . . . . . . . . . 11--default-symver . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18--defsym= symbol =exp . . . . . . . . . . . . . . . . . . . . . . . . .16--demangle[= style ] . . . . . . . . . . . . . . . . . . . . . . . . . .16--disable-auto-image-base . . . . . . . . . . . . . . . . . . 31--disable-auto-import . . . . . . . . . . . . . . . . . . . . . . .33

--disable-long-section-names. . . . . . . . . . . . . . .

28--disable-new-dtags . . . . . . . . . . . . . . . . . . . . . . . . .26--disable-runtime-pseudo-reloc . . . . . . . . . . . . . 33--disable-stdcall-fixup . . . . . . . . . . . . . . . . . . . . .28--discard-all . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11--discard-locals . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12--dll . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .28--dll-search-prefix . . . . . . . . . . . . . . . . . . . . . . . . .31--dotsyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .82--dynamic-linker= file . . . . . . . . . . . . . . . . . . . . . . .16--dynamic-list-cpp-new . . . . . . . . . . . . . . . . . . . . . .15--dynamic-list-cpp-typeinfo . . . . . . . . . . . . . . . . 15--dynamic-list-data . . . . . . . . . . . . . . . . . . . . . . . . .15--dynamic-list= dynamic-list-file . . . . . . . . . . 15--dynamicbase . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34--eh-frame-hdr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .26--emit-relocs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10--emit-stack-syms . . . . . . . . . . . . . . . . . . . . . . . . . . . .83--emit-stub-syms . . . . . . . . . . . . . . . . . . . . . 81, 82, 83--enable-auto-image-base . . . . . . . . . . . . . . . . . . . 30--enable-auto-import . . . . . . . . . . . . . . . . . . . . . . . .31--enable-extra-pe-debug . . . . . . . . . . . . . . . . . . . . .33--enable-long-section-names . . . . . . . . . . . . . . . . 28--enable-new-dtags . . . . . . . . . . . . . . . . . . . . . . . . . .26--enable-runtime-pseudo-reloc . . . . . . . . . . . . . . 33

--enable-stdcall-fixup . . . . . . . . . . . . . . . . . . . . . .28--entry= entry . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5--error-poison-system-directories . . . . . . . . . 27--error-unresolved-symbols . . . . . . . . . . . . . . . . . 25--exclude-libs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5--exclude-modules-for-implib . . . . . . . . . . . . . . . . 5--exclude-symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . .29--export-all-symbols . . . . . . . . . . . . . . . . . . . . . . . .29--export-dynamic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6--extra-overlay-stubs . . . . . . . . . . . . . . . . . . . . . . .83--fatal-warnings . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17--file-alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29--filter= name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7--fix-cortex-a8 . . . . . . . . . . . . . . . . . . . . . . . . . .76, 79--fix-v4bx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77--fix-v4bx-interworking . . . . . . . . . . . . . . . . . . . . .77--force-dynamic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10--force-exe-suffix . . . . . . . . . . . . . . . . . . . . . . . . . .17--forceinteg . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34--format= format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4--format= version . . . . . . . . . . . . . . . . . . . . . . . . . . . .83--gc-sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17--got . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35--got= type . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79--gpsize= value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7--hash-size= number . . . . . . . . . . . . . . . . . . . . . . . . . .26--hash-style= style . . . . . . . . . . . . . . . . . . . . . . . . . .26--heap . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29--help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17--image-base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29

--just-symbols= file . . . . . . . . . . . . . . . . . . . . . . . . .10--kill-at . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29--large-address-aware . . . . . . . . . . . . . . . . . . . . . . .30--library-path= dir . . . . . . . . . . . . . . . . . . . . . . . . . . .8--library= namespec . . . . . . . . . . . . . . . . . . . . . . . . . . .7--local-store=lo:hi . . . . . . . . . . . . . . . . . . . . . . . . .83--major-image-version . . . . . . . . . . . . . . . . . . . . . . .30--major-os-version . . . . . . . . . . . . . . . . . . . . . . . . . .30--major-subsystem-version . . . . . . . . . . . . . . . . . . 30--minor-image-version . . . . . . . . . . . . . . . . . . . . . . .30--minor-os-version . . . . . . . . . . . . . . . . . . . . . . . . . .30--minor-subsystem-version . . . . . . . . . . . . . . . . . . 30--mri-script= MRI-cmdfile . . . . . . . . . . . . . . . . . . . . 5--multi-subspace . . . . . . . . . . . . . . . . . . . . . . . . . . . . .79--nmagic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9--no-accept-unknown-input-arch . . . . . . . . . . . . . 13--no-add-needed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14--no-allow-shlib-undefined . . . . . . . . . . . . . . . . . 18--no-as-needed . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14--no-bind . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .34--no-check-sections . . . . . . . . . . . . . . . . . . . . . . . . .15--no-define-common . . . . . . . . . . . . . . . . . . . . . . . . . .16--no-demangle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16--no-dotsyms . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .82--no-enum-size-warning . . . . . . . . . . . . . . . . . . . . . .78

Page 116: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 116/122

Page 117: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 117/122

LD Index 111

-fini= name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-g . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-G value . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-h name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7

-i. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

7-I file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16-init= name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-L dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-l namespec . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-M. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-m emulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8-Map=mapfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17-n . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-N . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-non_shared . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-nostdlib . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-O level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-o output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9-pie . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-q . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-qmagic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-Qy . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .19-r . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-R file . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-rpath-link= dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-rpath= dir . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .20-s . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-S . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-shared . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21-soname= name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7-static . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .14-t . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10-T script . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-Tbss= org . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-Tdata= org . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-Ttext-segment= org . . . . . . . . . . . . . . . . . . . . . . . . . .23-Ttext= org . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23-u symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-Ur . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-v . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-V . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-x . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11-X . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-Y path . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-y symbol . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12-z defs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18-z keyword . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .12

-z muldefs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18

.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67

//DISCARD/ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55

:: phdr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

==fillexp . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

>

>region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

[[COMMON] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53

AABSOLUTE(MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101absolute and relocatable symbols . . . . . . . . . . . . . . .70absolute expressions . . . . . . . . . . . . . . . . . . . . . . . . . . .70ABSOLUTE(exp ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71ADDR(section ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71address, section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49ALIAS (MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101ALIGN(MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101align expression . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71align location counter . . . . . . . . . . . . . . . . . . . . . . . . . .71ALIGN(align ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .71ALIGN(exp , align ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .71ALIGN(section_align ) . . . . . . . . . . . . . . . . . . . . . . . .57aligned common symbols . . . . . . . . . . . . . . . . . . . . . .90ALIGNOF(section ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .72

allocating memory. . . . . . . . . . . . . . . . . . . . . . . . . . . . .

60architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .45architectures . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4archive fles, rom cmd line . . . . . . . . . . . . . . . . . . . . . .7archive search path in linker script . . . . . . . . . . . . . 40arithmetic . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66arithmetic operators . . . . . . . . . . . . . . . . . . . . . . . . . . .69ARM interworking support . . . . . . . . . . . . . . . . . . . .76AS_NEEDED(files ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .40ASSERT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44assertion in linker script . . . . . . . . . . . . . . . . . . . . . . .44assignment in scripts . . . . . . . . . . . . . . . . . . . . . . . . . .45AT( lma ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56AT>lma_region . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56automatic data imports . . . . . . . . . . . . . . . . . . . . . . . .87

Bback end . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93BASE(MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101BE8 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77BFD canonical ormat . . . . . . . . . . . . . . . . . . . . . . . . .94BFD requirements . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93big-endian objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6binary input ormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4

Page 118: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 118/122

112 The GNU linker

BLOCK(exp ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72bug criteria . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97bug reports . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97bugs in ld . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97BYTE(expression ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .53

CC++ constructors, arranging in link . . . . . . . . . . . . . 54CHIP (MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101COLLECT_NO_DEMANGLE. . . . . . . . . . . . . . . . . . . . . . . . .35combining symbols, warnings on . . . . . . . . . . . . . . . 23command fles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37command line . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3common allocation . . . . . . . . . . . . . . . . . . . . . . . . . .5, 16common allocation in linker script . . . . . . . . . . . . . 44common symbol placement . . . . . . . . . . . . . . . . . . . . 52COMMONPAGESIZE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67compatibility, MRI . . . . . . . . . . . . . . . . . . . . . . . . . . . . .5CONSTANT. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67constants in linker scripts . . . . . . . . . . . . . . . . . . . . . .66constraints on output sections . . . . . . . . . . . . . . . . . 58constructors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11CONSTRUCTORS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54constructors, arranging in link . . . . . . . . . . . . . . . . . 54Cortex-A8 erratum workaround . . . . . . . . . . . . 76, 79crash o linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97CREATE_OBJECT_SYMBOLS. . . . . . . . . . . . . . . . . . . . . . .54creating a DEF fle . . . . . . . . . . . . . . . . . . . . . . . . . . . .86cross re erence table . . . . . . . . . . . . . . . . . . . . . . . . . . .16cross re erences . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44current output location . . . . . . . . . . . . . . . . . . . . . . . .67

Ddata . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53DATA_SEGMENT_ALIGN(maxpagesize ,

commonpagesize ) . . . . . . . . . . . . . . . . . . . . . . . . .72DATA_SEGMENT_END(exp ) . . . . . . . . . . . . . . . . . . . . . . .72DATA_SEGMENT_RELRO_END(offset , exp ) . . . . . . . 73dbx . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .22DEF fles, creating . . . . . . . . . . . . . . . . . . . . . . . . . . . . .30de ault emulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35de ault input ormat . . . . . . . . . . . . . . . . . . . . . . . . . . .35DEFINED(symbol ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73deleting local symbols . . . . . . . . . . . . . . . . . . . . . . . . .11demangling, de ault . . . . . . . . . . . . . . . . . . . . . . . . . . . .35demangling, rom command line . . . . . . . . . . . . . . . 16direct linking to a dll . . . . . . . . . . . . . . . . . . . . . . . . . .87discarding sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55discontinuous memory . . . . . . . . . . . . . . . . . . . . . . . . .60DLLs, creating . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29, 30DLLs, linking to . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .31dot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67dot inside sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . .68dot outside sections . . . . . . . . . . . . . . . . . . . . . . . . . . . .68dynamic linker, rom command line . . . . . . . . . . . . 16dynamic symbol table . . . . . . . . . . . . . . . . . . . . . . . . . . .6

EELF program headers . . . . . . . . . . . . . . . . . . . . . . . . .61emulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .8emulation, de ault . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35

END(MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101endianness . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6entry point . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39entry point, rom command line . . . . . . . . . . . . . . . . .5entry point, thumb . . . . . . . . . . . . . . . . . . . . . . . . . . . .77ENTRY(symbol ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39error on valid input . . . . . . . . . . . . . . . . . . . . . . . . . . . .97example o linker script . . . . . . . . . . . . . . . . . . . . . . . .38exporting DLL symbols . . . . . . . . . . . . . . . . . . . . . . . .84expression evaluation order . . . . . . . . . . . . . . . . . . . .70expression sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70expression, absolute . . . . . . . . . . . . . . . . . . . . . . . . . . .71expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66EXTERN. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44

Fatal signal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97fle name wildcard patterns . . . . . . . . . . . . . . . . . . . .51FILEHDR. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .62flename symbols . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54fll pattern, entire section . . . . . . . . . . . . . . . . . . . . . .58FILL( expression ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .54fnalization unction . . . . . . . . . . . . . . . . . . . . . . . . . . . .7frst input fle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41frst instruction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39FIX V4BX . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .77FIX V4BX INTERWORKING . . . . . . . . . . . . . . . . 77FORCE_COMMON_ALLOCATION. . . . . . . . . . . . . . . . . . . . .44

orcing input section alignment. . . . . . . . . . . . . . . .

57orcing output section alignment . . . . . . . . . . . . . . . 57orcing the creation o dynamic sections . . . . . . . . 10FORMAT(MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .101unctions in expressions . . . . . . . . . . . . . . . . . . . . . . . .71

Ggarbage collection . . . . . . . . . . . . . . . . . . . . . . . . . .17, 53generating optimized output . . . . . . . . . . . . . . . . . . . .9gnu linker . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .1GNUTARGET. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35GROUP(files ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40grouping input fles . . . . . . . . . . . . . . . . . . . . . . . . . . . .40groups o archives . . . . . . . . . . . . . . . . . . . . . . . . . . . . .13

HH8/300 support . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75header size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74heap size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29help . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17holes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67holes, flling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .54HPPA multiple sub-space stubs . . . . . . . . . . . . . . . . 79

Page 119: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 119/122

LD Index 113

HPPA stub grouping . . . . . . . . . . . . . . . . . . . . . . . . . .79

Ii960 support

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .75image base . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .29

implicit linker scripts . . . . . . . . . . . . . . . . . . . . . . . . . .74import libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .84INCLUDEfilename . . . . . . . . . . . . . . . . . . . . . . . . . . . . .39including a linker script . . . . . . . . . . . . . . . . . . . . . . . .39including an entire archive . . . . . . . . . . . . . . . . . . . . .25incremental link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7INHIBIT_COMMON_ALLOCATION. . . . . . . . . . . . . . . . . . 44initialization unction . . . . . . . . . . . . . . . . . . . . . . . . . . .7initialized data in ROM . . . . . . . . . . . . . . . . . . . . . . . .57input fle ormat in linker script . . . . . . . . . . . . . . . .41input flename symbols . . . . . . . . . . . . . . . . . . . . . . . .54input fles in linker scripts . . . . . . . . . . . . . . . . . . . . .40input fles, displaying . . . . . . . . . . . . . . . . . . . . . . . . . .10input ormat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .4input object fles in linker scripts . . . . . . . . . . . . . . 40input section alignment . . . . . . . . . . . . . . . . . . . . . . . .57input section basics . . . . . . . . . . . . . . . . . . . . . . . . . . . .50input section wildcards . . . . . . . . . . . . . . . . . . . . . . . .51input sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49INPUT(files ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .40INSERT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .44insert user script into de ault script . . . . . . . . . . . . 44integer notation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66integer su xes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66internal object-fle ormat . . . . . . . . . . . . . . . . . . . . . .94invalid input . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97

KK and M integer su xes . . . . . . . . . . . . . . . . . . . . . . .66KEEP . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53

Ll = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61lazy evaluation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .70ld bugs, reporting . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97LDEMULATION. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .35len = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61LENGTH =. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61LENGTH(memory ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73library search path in linker script . . . . . . . . . . . . . 40link map . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9link-time runtime library search path . . . . . . . . . . 20linker crash . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .97linker script concepts . . . . . . . . . . . . . . . . . . . . . . . . . .37linker script example . . . . . . . . . . . . . . . . . . . . . . . . . .38linker script fle commands . . . . . . . . . . . . . . . . . . . . .39linker script ormat . . . . . . . . . . . . . . . . . . . . . . . . . . . .38linker script input object fles . . . . . . . . . . . . . . . . . .40linker script simple commands . . . . . . . . . . . . . . . . . 39linker scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37

LIST (MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102little-endian objects . . . . . . . . . . . . . . . . . . . . . . . . . . . . .6LOAD(MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102load address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56LOADADDR(section ) . . . . . . . . . . . . . . . . . . . . . . . . . . .73loading, preventing . . . . . . . . . . . . . . . . . . . . . . . . . . . .56local symbols, deleting . . . . . . . . . . . . . . . . . . . . . . . . .12location counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67LONG(expression ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .53

MM and K integer su xes . . . . . . . . . . . . . . . . . . . . . . .66M68HC11 and 68HC12 support . . . . . . . . . . . . . . . . 76machine architecture . . . . . . . . . . . . . . . . . . . . . . . . . . .45machine dependencies . . . . . . . . . . . . . . . . . . . . . . . . .75mapping input sections to output sections . . . . . . 49MAX. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73MAXPAGESIZE. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67MEMORY. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60memory region attributes . . . . . . . . . . . . . . . . . . . . . .60memory regions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60memory regions and sections . . . . . . . . . . . . . . . . . . .58memory usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .18MIN. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73Motorola 68K GOT generation . . . . . . . . . . . . . . . . 79MRI compatibility . . . . . . . . . . . . . . . . . . . . . . . . . . . .101MSP430 extra sections . . . . . . . . . . . . . . . . . . . . . . . . .80

NNAME(MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102name, section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49

names. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

67naming the output fle . . . . . . . . . . . . . . . . . . . . . . . . . .9NEXT(exp ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73NMAGIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9NO ENUM SIZE WARNING . . . . . . . . . . . . . . . . . 78NO WCHAR SIZE WARNING . . . . . . . . . . . . . . . 78NOCROSSREFS(sections ) . . . . . . . . . . . . . . . . . . . . . . .44NOLOAD. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .56not enough room or program headers . . . . . . . . . . 74

Oo = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61objdump -i . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .93object fle management . . . . . . . . . . . . . . . . . . . . . . . .93object fles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3object ormats available . . . . . . . . . . . . . . . . . . . . . . . .93object size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .7OMAGIC . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9ONLY_IF_RO. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58ONLY_IF_RW. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58opening object fles . . . . . . . . . . . . . . . . . . . . . . . . . . . .93operators or arithmetic . . . . . . . . . . . . . . . . . . . . . . . .69options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .3ORDER(MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102

Page 120: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 120/122

114 The GNU linker

org = . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61ORIGIN =. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61ORIGIN(memory ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .73orphan . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .67output fle a ter errors . . . . . . . . . . . . . . . . . . . . . . . . .19output fle ormat in linker script . . . . . . . . . . . . . . 41output fle name in linker script . . . . . . . . . . . . . . . .40output section alignment . . . . . . . . . . . . . . . . . . . . . .57output section attributes . . . . . . . . . . . . . . . . . . . . . . .56output section data . . . . . . . . . . . . . . . . . . . . . . . . . . . .53OUTPUT(filename ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .40OUTPUT_ARCH(bfdarch ) . . . . . . . . . . . . . . . . . . . . . . . .45OUTPUT_FORMAT(bfdname ) . . . . . . . . . . . . . . . . . . . . . .41OVERLAY. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58overlays . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58

Ppartial link . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10PE import table prefxing . . . . . . . . . . . . . . . . . . . . . .77PHDRS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61, 62PIC VENEER . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .78position independent executables . . . . . . . . . . . . . . .19PowerPC ELF32 options . . . . . . . . . . . . . . . . . . . . . . .80PowerPC GOT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .81PowerPC long branches . . . . . . . . . . . . . . . . . . . . . . . .80PowerPC PLT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .80PowerPC stub symbols . . . . . . . . . . . . . . . . . . . . . . . .81PowerPC TLS optimization . . . . . . . . . . . . . . . . . . . .81PowerPC64 dot symbols . . . . . . . . . . . . . . . . . . . . . . .82PowerPC64 ELF64 options . . . . . . . . . . . . . . . . . . . . 81PowerPC64 multi-TOC . . . . . . . . . . . . . . . . . . . . . . . .82PowerPC64 OPD optimization . . . . . . . . . . . . . . . . .82

PowerPC64 OPD spacing. . . . . . . . . . . . . . . . . . . . . .

82PowerPC64 stub grouping . . . . . . . . . . . . . . . . . . . . .81PowerPC64 stub symbols . . . . . . . . . . . . . . . . . . . . . .82PowerPC64 TLS optimization . . . . . . . . . . . . . . . . . .82PowerPC64 TOC optimization . . . . . . . . . . . . . . . . .82precedence in expressions . . . . . . . . . . . . . . . . . . . . . .69prevent unnecessary loading . . . . . . . . . . . . . . . . . . . 56program headers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61program headers and sections . . . . . . . . . . . . . . . . . .58program headers, not enough room . . . . . . . . . . . . 74program segments . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61PROVIDE . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .46PROVIDE HIDDEN . . . . . . . . . . . . . . . . . . . . . . . . . .46PUBLIC (MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102

QQUAD(expression ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .53quoted symbol names . . . . . . . . . . . . . . . . . . . . . . . . . .67

Rread-only text . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .9read/write rom cmd line . . . . . . . . . . . . . . . . . . . . . . .9region alias . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41

region names . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .41REGION_ALIAS(alias , region ) . . . . . . . . . . . . . . . . 41regions o memory . . . . . . . . . . . . . . . . . . . . . . . . . . . . .60relative expressions . . . . . . . . . . . . . . . . . . . . . . . . . . . .70relaxing addressing modes . . . . . . . . . . . . . . . . . . . . .19relaxing on H8/300 . . . . . . . . . . . . . . . . . . . . . . . . . . . .75relaxing on i960 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .76relaxing on M68HC11 . . . . . . . . . . . . . . . . . . . . . . . . .76relaxing on Xtensa . . . . . . . . . . . . . . . . . . . . . . . . . . . . .91relocatable and absolute symbols . . . . . . . . . . . . . . .70relocatable output . . . . . . . . . . . . . . . . . . . . . . . . . . . . .10removing sections . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55reporting bugs in ld . . . . . . . . . . . . . . . . . . . . . . . . . . .97requirements or BFD . . . . . . . . . . . . . . . . . . . . . . . . .93retain relocations in fnal executable . . . . . . . . . . . 10retaining specifed symbols . . . . . . . . . . . . . . . . . . . . .20ROM initialized data . . . . . . . . . . . . . . . . . . . . . . . . . .57round up expression . . . . . . . . . . . . . . . . . . . . . . . . . . .71round up location counter . . . . . . . . . . . . . . . . . . . . .71runtime library name . . . . . . . . . . . . . . . . . . . . . . . . . . .7runtime library search path . . . . . . . . . . . . . . . . . . . .20runtime pseudo-relocation . . . . . . . . . . . . . . . . . . . . .87

Sscaled integers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .66scommon section . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .52script fles . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .11scripts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .37search directory, rom cmd line . . . . . . . . . . . . . . . . . .8search path in linker script . . . . . . . . . . . . . . . . . . . . .40SEARCH_DIR( path ) . . . . . . . . . . . . . . . . . . . . . . . . . . . .40SECT (MRI) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .102

section address . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49section address in expression . . . . . . . . . . . . . . . . . . .71section alignment . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .72section alignment, warnings on . . . . . . . . . . . . . . . . .25section data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .53section fll pattern . . . . . . . . . . . . . . . . . . . . . . . . . . . . .58section load address . . . . . . . . . . . . . . . . . . . . . . . . . . .56section load address in expression . . . . . . . . . . . . . . 73section name . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .49section name wildcard patterns . . . . . . . . . . . . . . . . 51section size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74section, assigning to memory region . . . . . . . . . . . . 58section, assigning to program header . . . . . . . . . . . 58SECTIONS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .48sections, discarding . . . . . . . . . . . . . . . . . . . . . . . . . . . .55segment origins, cmd line . . . . . . . . . . . . . . . . . . . . . .23SEGMENT_START(segment , default ) . . . . . . . . . . . 73segments, ELF . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .61shared libraries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .21SHORT(expression ) . . . . . . . . . . . . . . . . . . . . . . . . . . .53SIZEOF( section ) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74SIZEOF_HEADERS. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .74small common symbols . . . . . . . . . . . . . . . . . . . . . . . .52SORT . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .51SORT BY ALIGNMENT . . . . . . . . . . . . . . . . . . . . .51

Page 121: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 121/122

Page 122: Linker GNU

7/27/2019 Linker GNU

http://slidepdf.com/reader/full/linker-gnu 122/122