binutils is the assembler, the linker, and the tools that read what they write
gcc runs two binutils programs on every build. as turns assembly text into an object file. ld joins object files into a program or a shared library. objdump, nm, readelf, objcopy and the other tools read or change those files.
Each chapter covers one part of the source tree. It opens with what that part looks like from the command line, then shows the code behind it. A dotted underline marks a term from the glossary at the end of this chapter. Hover it for the definition, or click it to open the entry.
| Command | What runs | Libraries | Chapter |
|---|---|---|---|
gcc -c foo.c | gcc runs cc1, then as on the assembly that cc1 wrote. The source calls this assembler gas. | BFD, opcodes | gas |
gcc foo.o -o foo | gcc runs collect2, and collect2 runs ld. | BFD and its ELF backend | ld |
ld --verbose | ld prints its version, its emulations and the linker script it uses when no -T option is given. | BFD | ld emulations |
ar rcs libfoo.a a.o b.o | ar packs the objects into one file and writes an index of their symbols. | BFD | The tools |
nm foo.o | nm opens the file through BFD and lists its symbols. size and addr2line work the same way. | BFD | The tools |
objdump -d foo | objdump reads the sections through BFD and decodes the instructions through opcodes. | BFD, opcodes | opcodes |
objcopy -O binary foo foo.bin | objcopy writes a changed copy of a file. strip is built from the same source, objcopy.c. | BFD | The tools |
readelf -a foo | readelf decodes the ELF structures with its own parser. | neither | The tools |
gcc -v prints each command that gcc runs, and gcc -### prints them without running them. The as and collect2 lines in that output are the first two rows of this table.| Name | x86-64 GNU/Linux | AArch64 bare metal | Where the name is used |
|---|---|---|---|
| target triplet | x86_64-pc-linux-gnu | aarch64-elf | configure --target=, and the prefix of installed cross tools: aarch64-elf-ld. |
| BFD target name | elf64-x86-64 | elf64-littleaarch64 | objdump -b, objcopy -O, OUTPUT_FORMAT in a linker script. objdump -i lists them. |
| BFD architecture | i386:x86-64 | aarch64 | objdump -m, OUTPUT_ARCH in a linker script. |
| ld emulation | elf_x86_64 | aarch64elf | ld -m. ld -V lists them. |
| BFD vector | x86_64_elf64_vec | aarch64_elf64_le_vec | Only the source: bfd/config.bfd and bfd/targets.c. |
ld -m takes an emulation, and objdump -m takes a BFD architecture. The -m options of as and gcc, such as -march=, are CPU options that each port defines.Glossary · files
object file
The output of the assembler, usually a .o file. It holds machine code and data in sections, a symbol table, and relocations for the values that are not known yet.
Chapter: from .s to a running binary →section
A named block of bytes in an object file, such as .text for code or .data for initialised variables. The linker merges the input sections into output sections.
Chapter: ld →segment
A range of a linked file that the loader maps into memory with one set of permissions. A segment holds one or more sections. The program headers describe the segments.
Chapter: background →symbol
A name with a value, usually the address of a function or a variable. One file can define a symbol and another file can refer to it.
Chapter: the ELF backend →relocation
An instruction to the linker or the loader: when the address of a symbol is known, write it into these bytes in this encoding. gas creates relocations. ld or ld.so applies them.
Chapter: from .s to a running binary →archive
A .a file that ar makes: a set of object files plus an index of the symbols they define, called the armap. ld extracts only the members that define a symbol it still needs.
Chapter: the tools →GOT and PLT
Two tables that ld builds when code uses symbols from a shared library. The GOT holds addresses. The PLT holds small stubs that jump through the GOT. At run time, ld.so writes the addresses of shared-library symbols into the GOT.
Chapter: the ELF backend →ld.so, the dynamic loader
The program that starts a dynamically linked executable. It maps the shared libraries and applies the dynamic relocations. It is part of the C library, not of binutils.
Chapter: from .s to a running binary →Glossary · libraries
BFD
The Binary File Descriptor library in bfd/. It reads and writes object files of many formats through one API, so the tools do not parse the formats themselves.
Chapter: BFD →target vector
A bfd_target structure: the table of functions for one format in one byte order, such as x86_64_elf64_vec. BFD identifies a file by trying its vectors in turn.
backend
The code for one format or one CPU inside BFD, for example bfd/elfnn-aarch64.c. Generic code calls it through hooks.
Chapter: the ELF backend →hook
A function pointer in a table that a port fills. Generic code calls the hook and does not know which port answers. A port that leaves a hook empty gets the default.
Chapter: the ELF backend →canonical form
BFD's format-neutral view of a file: asymbol for a symbol, arelent for a relocation. A tool that works only with this view sees what all formats have in common.
howto
A reloc_howto_type: the description of one relocation type. It gives the size, the bit position, the mask and the overflow check that BFD needs to apply it.
opcodes
The library in opcodes/ that holds the instruction tables and the disassemblers. objdump and GDB use it to print instructions. gas uses the same tables on some targets.
Chapter: opcodes →libiberty
A library of portability functions that binutils, GCC and GDB share. It also holds the C++ demangler that c++filt and nm -C use.
Chapter: the tools →Glossary · configuration
target triplet
The cpu-vendor-system name of a machine, such as x86_64-pc-linux-gnu or aarch64-elf. The system part can have two words, as in linux-gnu. config.sub expands a short name to the full form.
Chapter: configuration →build, host, target
Three machines in a configure command. The tools are compiled on the build machine and run on the host. The target is the machine they produce code for. A cross toolchain has a host different from its target.
Chapter: configuration →generated file
A file in the tree that a program writes from another file. A change goes into the input, then the output is regenerated. Some outputs are committed and some are written at build time.
Chapter: generated files →CGEN
A generator that writes the assembler and disassembler tables of some older ports from a CPU description in cpu/*.cpu. It is a separate project.
Chapter: opcodes →Glossary · assembler
directive
An assembler command that starts with a dot, such as .section, .globl or .word. It controls the assembler. It is not an instruction for the CPU.
Chapter: gas →frag
A fragment of a section inside gas: bytes with a known size, then an optional variable part. A branch that can be short or long is a variable part.
Chapter: gas →fixup
A note inside gas that a field needs a value that gas does not know yet. At the end of the input, gas writes the value or turns the fixup into a relocation.
Chapter: gas →relaxation
Adjusting instruction sequences or section contents after distances become known. gas can expand a branch to reach its target. On targets such as RISC-V, ld can shorten a sequence and delete bytes. Changed sizes require another layout pass.
Chapter: gas →tc-, obj- and te- files
The three layers of a gas port in gas/config/: tc-<cpu> for the instruction set, obj-<format> for the object format, te-<environment> for the target environment. configure picks one of each.
Chapter: gas →Glossary · linker and project
linker script
A file in ld's command language. It maps input sections to output sections and assigns addresses. -T path/to/script.ld selects an explicit script. The filename is user-chosen. Without an explicit script, ld uses its emulation's default script.
emulation
ld's settings for one kind of output: the default output format and architecture, the default linker scripts, the library search path, and C hooks for the target. ld -m selects one.
input BFD
A bfd structure through which the linker reads one input file. It identifies the file's format and gives access to its sections and symbols.
symbol resolution
Matching references to definitions under the rules for strong, weak and common symbols. This chooses which definition supplies a name before its final address is known.
Chapter: ld →garbage collection
With --gc-sections, the linker keeps sections reachable from required roots and removes the others. Relocations describe references between sections. The script's KEEP() protects matched sections from removal.
allocation
The linker calculates output section sizes, alignment padding, input section offsets and output addresses. It does not allocate physical RAM or create threads. Relaxation can require these calculations to repeat.
Chapter: ld →orphan section
An input section that no rule of the linker script matches. The emulation decides where it goes, usually after an output section with similar attributes, such as code after code.
Chapter: ld →LTO plugin
A shared library from GCC that ld, ar and nm load. It reads the compiler's intermediate code in -flto objects, so link-time optimisation can run inside the link.
Chapter: ld →script statement tree
The parsed representation of a linker script and related command-line inputs. Later passes traverse its input-file statements, section rules and expressions.
Chapter: ld →wildcard matching
Script patterns select input files and sections by name. For example, *(.text .text.*) selects code sections. ld prepares matches before collection and refreshes them when new sections appear.
Chapter: ld →KEEP()
A linker-script directive that protects matching input sections from garbage collection. ld marks the matched section descriptors before BFD collects unreachable sections.
Chapter: ld →thread-local storage (TLS)
Storage with a separate instance for each thread. ELF TLS sections and relocations describe the initial contents and how code accesses each thread’s instance.
Chapter: elf →DejaGnu
The Tcl test framework of the GNU toolchain. make check runs it, and the .exp files are its test drivers.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Separate two parsers
Read the linked introduction to readelf.c. Why does readelf avoid BFD for ELF decoding?
Show answer
An independent parser can expose an ELF interpretation error that BFD clients otherwise share.
-
Question 2: Classify a failure
Assembly succeeds, but the final link reports an undefined reference. Which stage lacks a definition?
Show answer
The linker lacks a usable definition among its selected inputs. Successful assembly does not prove that all references can resolve.
-
Question 3: Explain the tool chain
State the difference between an instruction, an object file, and an executable.
Show answer
An instruction encodes a machine operation. An object file contains sections, symbols, and relocations. An executable has the layout needed for loading.
-
Problem 1: Reconstruct a link from two sources
Write caller.s with an exported entry that calls an undefined helper. Define helper in helper.s. Write a shell script that assembles both and links them without a C runtime. Read the assembler's object-writing path and ld's input-loading path.
Test requirements: Save symbol tables and relocations before and after linking. Assert that omitting helper.o fails and adding it succeeds. Do not execute the result.
Show solution
Use
.globl entry,call helper, andretin caller.s. Link with an explicit entry symbol. The caller object has an undefined helper and a call relocation. The complete static link resolves helper. The omitted-definition case must fail at linking, not assembly. -
Problem 2: Make pipeline failures distinguishable
Implement a Python runner for assembly, relocatable linking, and final static linking. Read how as and ld choose their exit statuses. Preserve each command's arguments, exit code, stdout, and stderr separately.
Test requirements: Test an invalid mnemonic, a missing object, an unresolved symbol, and a valid two-object link. Assert which stage runs last for each input.
Show solution
Stop after the first nonzero exit status. An invalid mnemonic fails assembly. A nonexistent input and an unresolved definition fail in ld through different paths. Treat diagnostic text as evidence, not a stable machine-readable API.
-
Problem 3: Audit the tools actually invoked
Write a command-line tool that accepts a directory containing a built as, ld, nm, objdump, and readelf. Resolve absolute executable paths before running them. Read the version-reporting paths in two programs.
Test requirements: Test a complete directory, a missing executable, and a directory containing spaces. Record every tool version and prove that a PATH entry cannot silently substitute another program.
Show solution
Invoke explicit paths using an argument array. Check each executable before starting. A shared version number does not prove a shared configuration. The report must retain paths as well as version output.
-
Problem 4: Predict and test a symbol rename
Create two assembly files that call and define one global function. Write a script that renames that symbol in both sources. Read how gas emits unresolved symbols and how ld loads their definitions.
Test requirements: Compare original and renamed links. Assert equal text-section bytes after equivalent layout. Rename only one side as a negative test.
Show solution
Consistent renaming preserves the call relationship and can preserve identical text bytes. One-sided renaming creates an unresolved reference. Compare section bytes rather than whole ELF files because symbol strings and metadata intentionally differ.
-
Problem 5: Reduce a failing input
Construct five assembly objects with one unresolved call hidden among unrelated data and functions. Implement a reducer that removes unnecessary inputs while preserving the final-link failure. Read the undefined-symbol diagnostic path.
Test requirements: The reducer must preserve the specific missing-symbol failure. Test that replacing it with an unreadable input is rejected as a different failure. Submit the reduced sources and reproduction command.
Show solution
Match the failing stage and missing symbol as well as the nonzero status. Retain the object containing the live reference and any inputs required to reach that diagnosis. A generic failure predicate can reduce to an unrelated broken command.
-
Problem 6: Test partial-link equivalence
Write three objects with direct calls and global data. Compare a direct final link against one that first combines two inputs with a relocatable link. Read ld's handling of relocatable output.
Test requirements: Automate checks of symbol addresses, decoded calls, and allocated section contents. Use a fixed script and explicit input order. Explain differences outside the compared data.
Show solution
Use
ld --relocatablefor the intermediate object. Under a simple fixed layout without special grouping or relaxation, the selected definitions and call targets should agree. Whole-file equality is too strong because intermediate symbol and section metadata can differ. -
Problem 7: Trace one fact through three representations
Write assembly containing a call to an external function and a pointer to it in data. Build a Python report that joins nm symbols, readelf relocations, and objdump disassembly by name and section offset. Read each tool's display path.
Test requirements: Check the report before linking, after a relocatable link, and after a complete static link. Detect an intentionally renamed definition without confusing instruction offsets with file offsets.
Show solution
The call and data pointer create different relocation fields but refer to the same symbol. Normalize addresses within each section. Final static linking can consume both relocations while preserving the symbol's resulting address and encoded uses.
Every binutils program is a thin front end over two libraries
BFD reads and writes every object format. opcodes encodes and decodes every instruction set. Only readelf stays outside both, by design.
From the command line
objdump -i prints the object formats and architectures that this build of BFD supports. nm, objdump, objcopy and ld accept the same list, because they call the same library.
- Nine programs. None of them knows what an ELF section header looks like, except one.
- Eight of them call libbfd through one generic API: open, check the format, read sections, symbols and relocations, write.
- BFD hides each format behind a target vector. The same nm binary lists an ELF .o, a PE .dll or an S-record file.
- gas and objdump also need instruction knowledge. libopcodes holds the assembler tables and the disassemblers.
- readelf links neither. It reads the bytes with its own parser, so it can check what BFD tells everyone else.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Route a bug report
Several BFD clients misread one section, but readelf decodes it correctly. Which shared layer needs investigation?
Show answer
BFD is a plausible shared cause. Compare the file bytes and the separate parsing paths before assigning the fault.
-
Question 2: Distinguish source and build
Does a source directory for a target guarantee support in an installed objdump?
Show answer
No. Configuration selects the target code and vectors included in the build.
-
Question 3: Explain the abstraction
Why can one BFD fix affect several command-line tools?
Show answer
Multiple clients call the same library operations. A correction in a shared backend can change each client's results.
-
Problem 1: Recover the real dependency graph
Write a script that extracts program dependencies from binutils/Makefile.am and follows the BFD and opcodes libraries. Resolve make variables rather than searching for library-name substrings only.
Test requirements: Produce a graph for objdump, objcopy, nm, and readelf. Test variable indirection and conditional dependencies. Cite the rules that establish each library edge.
Show solution
Treat the Makefile as structured input with assignments, continuations, and conditionals. objdump needs BFD and opcodes. readelf's independent ELF reader must not acquire a fabricated libbfd edge merely because another rule mentions BFD.
-
Problem 2: Trace two section readers
Add temporary trace output to the BFD section-reading path and readelf's independent section reader in a disposable source checkout. Build both tools. Write a driver that runs them on the same object.
Test requirements: Submit traces that identify the first shared file fact and the point where implementations diverge. Assert that trace output changes neither normal stdout nor success status.
Show solution
Put tracing on stderr behind a local debug control. BFD dispatches through its selected backend. readelf reads ELF headers through its own Filedata path. The file's section offset and size are comparable even when internal representations differ.
-
Problem 3: Build a minimal independent ELF reader
Implement a Python program that reads a little-endian ELF64 section table and prints section names, file offsets, sizes, and types. Read both BFD's and readelf's bounds checks before choosing yours.
Test requirements: Compare with readelf on an object containing text, data, and NOBITS sections. Test a truncated header, an out-of-range name offset, and a section table beyond end of file.
Show solution
Decode declared entry sizes and validate table extents before reading entries. Read names through the designated string table. NOBITS contributes memory size without corresponding file payload. Explicitly reject unsupported extended numbering instead of misdecoding it.
-
Problem 4: Measure the blast radius of a BFD change
In a disposable build, instrument BFD format recognition with a counter. Run objdump, nm, objcopy, and readelf over one valid object and one invalid file. Write a driver that records call counts.
Test requirements: Predict which tools reach the instrumented operation before running them. Explain mismatches through caller source paths, including repeated probes and failed recognition.
Show solution
BFD clients can reach the common recognition path, sometimes more than once. readelf's ELF parser does not use it. Counts describe actual calls for these invocations, not a permanent one-call-per-file interface guarantee.
-
Problem 5: Separate file errors from decode errors
Write an assembly fixture with a known text section. Produce one copy with a damaged ELF header and another with one changed instruction byte. Follow objdump from file recognition to disassembly.
Test requirements: Automate a report of exit status, section visibility, and decoded instruction output. Demonstrate that the two mutations cross different boundaries without assuming either diagnostic spelling.
Show solution
A damaged header can prevent object recognition before decoding. A changed code byte can leave ELF recognition intact while changing the decoded instruction or producing undecodable bytes. Capture both layers' observations instead of treating any changed output as a parser failure.
-
Problem 6: Explain a copy through library calls
Write a small tracing patch that logs the BFD operations used when objcopy copies an object with a symbol and relocation. Reduce the trace to a dependency graph and a repeatable driver.
Test requirements: Verify section bytes, symbol relationships, and relocation targets in the output. Repeat with a symbol-free object. Identify which calls disappear and which remain required.
Show solution
Copying needs output-section creation before symbol and relocation references can be remapped. Raw byte copying does not preserve those relationships by itself. The symbol-free case can remove symbol processing without removing section or format handling.
-
Problem 7: Test independent diagnostic value
Build a fixture generator that mutates one ELF section-header field at a time. Compare readelf and objdump behavior for each generated file. Read their corresponding validation branches.
Test requirements: Cover an invalid string-table index, truncated section table, and out-of-file section contents. Require bounded execution and retain each mutation's offset, bytes, status, and diagnostic.
Show solution
Independence permits different diagnostics or acceptance decisions, but disagreement alone does not establish which parser is correct. Check each mutation against header bounds and the relevant source guard. A crash or hang requires a minimized reproducer, not an expected-success assertion.
Pipeline
Each tool owns one stage in the life of a relocation
The compiler is not part of binutils, and neither is the dynamic loader. Everything between them is.
From the command line
gcc -save-temps -c foo.c keeps foo.s beside foo.o. objdump -dr foo.o prints each relocation under the instruction it patches. readelf -r foo prints the dynamic relocations that ld left for ld.so.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Recognize a relocation
Why can an object contain a relocation even when its instruction bytes already exist?
Show answer
The bytes can contain a placeholder or partial value. The relocation records the adjustment that a later stage must apply.
-
Question 2: Explain allocation
Why must output section addresses exist before a final address-dependent relocation can be calculated?
Show answer
Relocation formulas can depend on the symbol address and the address of the field being patched. Allocation supplies those addresses.
-
Question 3: Diagnose the stage
A call assembles but its relocation overflows during linking. Why is successful assembly insufficient?
Show answer
The assembler did not know the final distance. The linker discovers that the allocated addresses exceed the relocation field's range.
-
Problem 1: Follow an unresolved call into final bytes
Create caller.s and helper.s with one external call. Write a Python script that reads the call displacement from the object and final executable. Trace the assembler fixup and linker relocation paths.
Test requirements: Use an explicit linker script. Assert the final call destination equals helper's address. Repeat after inserting 32 bytes before helper. Preserve relocation and disassembly evidence.
Show solution
On x86-64 a direct call has an opcode followed by a signed 32-bit displacement relative to the next instruction. Follow the emitted relocation's actual type and addend rather than guessing them. Moving helper changes the displacement consistently.
-
Problem 2: Distinguish resolved fixups from relocations
Write assembly variants for a local same-section label, a global external label, and a label in another section. Instrument fixup processing and write a checker for emitted relocation records.
Test requirements: Predict each variant's fixup and relocation behavior before assembling. Repeat with a relocatable link. Explain any target-specific conversion through the source branch that performs it.
Show solution
A fixup is an internal adjustment request. Some same-section differences can resolve during assembly. External or section-dependent values can need output relocations. Use actual symbol binding and expression form when predicting what survives.
-
Problem 3: Create an independent relocation oracle
Generate two objects containing a PC-relative reference. Implement the relocation arithmetic in Python using the emitted symbol, addend, and place. Compare your calculated field bytes with the final output.
Test requirements: Test forward and backward references, nonzero addends, and two section placements. Include a deliberately wrong place address that your checker detects.
Show solution
For the relevant x86-64 PC-relative relocation, compute
S + A - P, range-check it, and encode the low four bytes in little-endian order. P is the relocation field's address. The emitted addend accounts for instruction-relative semantics. -
Problem 4: Measure who consumes relocations
Construct an object containing a direct call, an absolute data pointer, and a section-relative expression. Write a script that records relocation tables after assembly, relocatable linking, and static final linking.
Test requirements: Match surviving records by section and target. Do not assert that record counts always decrease. Explain each change using the assembler and linker source paths.
Show solution
A relocatable link can preserve, adjust, or transform records for a later link. A final static link consumes references it resolves. Count changes alone do not establish correctness because records can be rewritten with different symbol associations.
-
Problem 5: Expose layout dependence
Write a linker script that places a caller and target at independently configurable addresses. Generate several layouts and decode the final call in each. Read the relocation overflow check.
Test requirements: Include nearby, backward, and out-of-range placements. Your test must distinguish a missing symbol from a range failure and verify successful instruction destinations numerically.
Show solution
Successful cases must land at the selected symbol address. The signed displacement must fit the relocation field. An overflow with a resolved symbol is a layout or encoding constraint, not an unresolved-definition error.
-
Problem 6: Observe a dynamic relocation boundary
Build a small shared library with an exported function and a data pointer to it, using assembly and ld. Write a report joining dynamic symbols, relocation targets, and output sections.
Test requirements: Compare with a static link of equivalent definitions. Read the backend decisions that preserve a dynamic relocation. Do not require a dynamic loader to execute the library.
Show solution
A shared object can retain a dynamic relocation for an interposable address. A static final link can write the known address directly. Exact relocation choices depend on symbol visibility and the reference form, so explain the emitted records rather than imposing one universal type.
-
Problem 7: Write a stage-aware regression test
Select one earlier relocation fixture and write a test harness that independently checks assembly, intermediate records, link status, and final bytes. Read an existing dump test before designing expectations.
Test requirements: Introduce one wrong expected relocation type and one wrong expected instruction byte. Prove that each fails at the intended assertion without masking other failures.
Show solution
Keep stage results separate. Check semantic relocation fields and exact bytes where encoding is the subject. A test that checks only successful command construction or link status can miss a wrong relocation record or patched field.
libbfd · bfd/
BFD finds a file's format by asking every vector it was built with
There is no magic-number table. bfd_check_format_matches sets abfd->xvec to each candidate in turn and lets that vector's own _bfd_check_format decide.
From the command line
objdump -b binary -m i386:x86-64 -D blob.bin names the target vector and the architecture, so BFD does not try to identify the bytes. The messages file format not recognized and file format is ambiguous come from the identification loop below.
- A tool opens a file with bfd_openr and asks for bfd_object. Nothing is known yet.
- The loop at format.c:579 sets xvec to each vector in _bfd_target_vector and calls BFD_SEND_FMT (abfd, _bfd_check_format, (abfd)).
- binary_vec would accept any bytes, so the loop skips it. plugin_vec drops out as soon as a real format matches.
- Lower match_priority wins (format.c:655). The generic elf64-little vector matches too, at priority 2. Two winners at the same priority give "file format is ambiguous".
targ_selvecs from config.bfd, the generic ELF vectors, and the raw formats that targets.c:1374 always adds. --enable-targets=all carries all 270 in the table.#define that fills it in the target's template.elf_symbol_type (elf-bfd.h:74) glues the top two layers: an asymbol followed by its Elf_Internal_Sym. Tools that copy through the canonical layer lose ELF-only details unless a bfd_copy_private_* hook carries them across.Drill down
Call trees for the eight things every BFD client does. Indentation is the call depth. Each name opens the definition at the binutils-2_46 tag.
Open a file and decide its format10
- bfd_openr()bfd/opncls.c:330Allocate a bfd for the file name and target name; nothing is read yet.
- _bfd_new_bfd()bfd/opncls.c:67Zero a struct bfd, give it an objalloc arena, and set the default target.
- bfd_find_target()bfd/targets.c:1551Map a target name, a triplet, or "default" to a bfd_target vector.
- bfd_check_format()bfd/format.c:101Wrapper that asks for one format with no match list.
- bfd_check_format_matches()bfd/format.c:446Try every vector in bfd_target_vector, rank matches by match_priority, report ambiguity.
- elf_object_p()bfd/elfcode.h:519ELF probe: check e_ident, class and machine, then read every section header.
- bfd_section_from_shdr()bfd/elf.c:2498Turn one Elf_Internal_Shdr into a BFD section, recursing for linked sections.
- _bfd_elf_make_section_from_shdr()bfd/elf.c:891Create the asection and translate sh_flags into SEC_* flags.
- bfd_generic_archive_p()bfd/archive.c:887Archive probe: check the !<arch> magic and slurp the armap.
- coff_object_p()bfd/coffgen.c:387COFF probe: check the file header magic and read the section table.
Read section contents5
- bfd_get_section_contents()bfd/section.c:1564Read a byte range of one section through the vector's _bfd_get_section_contents.
- bfd_get_full_section_contents()bfd/compress.c:727Read a whole section and decompress it when SHF_COMPRESSED or .zdebug applies.
- bfd_init_section_decompress_status()bfd/compress.c:986Read the compression header and record the uncompressed size.
- decompress_contents()bfd/compress.c:525Run zlib or zstd over the compressed bytes.
- bfd_cache_init()bfd/cache.c:584Put a bfd in the open-file cache, which closes the least recently used file past the descriptor limit.
Read symbols7
- bfd_canonicalize_symtabbfd/bfd-in2.h:1249Public macro: BFD_SEND to the vector's _bfd_canonicalize_symtab slot.
- _bfd_elf_canonicalize_symtab()bfd/elf.c:9223ELF slot: call the size-specific slurp_symbol_table through elf_backend_data.
- elf_slurp_symbol_table()bfd/elfcode.h:1238Build elf_symbol_type entries, each an asymbol plus its Elf_Internal_Sym.
- bfd_elf_get_elf_syms()bfd/elf.c:441Read and swap a run of symbols, including SHT_SYMTAB_SHNDX extended indices.
- elf_swap_symbol_in()bfd/elfcode.h:174Convert one on-disk Elf_External_Sym to host order.
- bfd_decode_symclass()bfd/syms.c:678Give the one-letter nm class (T, D, U, W…) for a canonical symbol.
- _bfd_elf_get_symbol_version_string()bfd/elf.c:2339Find the @VERSION or @@VERSION text for a dynamic symbol.
Read relocations6
- bfd_canonicalize_reloc()bfd/bfd.c:2185Fill an arelent array for one section through the vector.
- _bfd_elf_canonicalize_reloc()bfd/elf.c:9201ELF slot: forward to the size-specific reloc reader.
- elf_slurp_reloc_table()bfd/elfcode.h:1639Read the SHT_REL or SHT_RELA section that targets this section.
- elf_slurp_reloc_table_from_section()bfd/elfcode.h:1538Swap each entry, attach the symbol, and call info_to_howto.
- bfd_reloc_type_lookup()bfd/reloc.c:8067Map a generic BFD_RELOC_* code to this target's reloc_howto_type.
- bfd_get_reloc_size()bfd/bfd-in2.h:3236Size in bytes of the field a howto patches.
Write an object file12
- bfd_openw()bfd/opncls.c:729Create a bfd for writing with a named target.
- bfd_make_section_with_flags()bfd/section.c:1253Add an output section with SEC_* flags.
- bfd_set_section_contents()bfd/section.c:1497Copy bytes into a section of an output bfd, computing file positions first if needed.
- bfd_close()bfd/opncls.c:860Flush the object: BFD_SEND_FMT to _bfd_write_contents, then close.
- _bfd_elf_write_object_contents()bfd/elf.c:7221ELF writer: lay out the file, write section bodies, relocations and headers.
- _bfd_elf_compute_section_file_positions()bfd/elf.c:4695Build the section header table and assign file offsets.
- elf_fake_sections()bfd/elf.c:3615Fill an Elf_Internal_Shdr from each asection.
- assign_file_positions_except_relocs()bfd/elf.c:6863Lay out segments and sections, leaving relocation sections for last.
- bfd_elf_map_sections_to_segments()bfd/elf.c:5088Group allocated sections into PT_LOAD and the other program headers.
- assign_file_positions_for_load_sections()bfd/elf.c:5893Give each PT_LOAD an offset congruent to its address modulo the page size.
- elf_write_relocs()bfd/elfcode.h:930Swap arelent entries out to SHT_REL or SHT_RELA bytes.
- elf_write_shdrs_and_ehdr()bfd/elfcode.h:1101Write the section header table and the ELF header.
Read and write archives7
- bfd_slurp_armap()bfd/archive.c:1184Read the "/" or "/SYM64/" symbol index into memory.
- bfd_openr_next_archived_file()bfd/archive.c:835Iterate over members, returning each as its own bfd.
- _bfd_get_elt_at_filepos()bfd/archive.c:671Open the member at a file offset, following the path for a thin archive.
- _bfd_write_archive_contents()bfd/archive.c:2141Write the magic, the armap, the long-name table and every member.
- _bfd_compute_and_write_armap()bfd/archive.c:2309Collect global symbols per member and call the vector's armap writer.
- _bfd_coff_write_armap()bfd/archive.c:2707Write the GNU/SVR4 armap: big-endian count, offsets, names.
- _bfd_archive_64_bit_write_armap()bfd/archive64.c:160Write the /SYM64/ armap with 64-bit offsets.
Generic link hash table3
- bfd_link_hash_lookup()bfd/linker.c:520Find or create the global symbol entry shared by all inputs.
- _bfd_generic_link_add_archive_symbols()bfd/linker.c:930Loop over the armap until no member defines a still-undefined symbol.
- _bfd_generic_link_add_one_symbol()bfd/linker.c:1420Apply one definition or reference with the link_action state table: strong, weak, common, indirect.
Relocation arithmetic6
- struct reloc_howto_structbfd/bfd-in2.h:3137One relocation type: size, right shift, bit position, overflow rule, masks, pc-relative flag.
- bfd_perform_relocation()bfd/reloc.c:658Generic application of one arelent for non-ELF-linker paths such as objdump --reloc.
- bfd_install_relocation()bfd/reloc.c:998Store an addend into section bytes for gas when the target uses REL.
- _bfd_final_link_relocate()bfd/reloc.c:1151Compute S + A (− P) for a howto and patch the field.
- _bfd_relocate_contents()bfd/reloc.c:1198Read the field, add the value under the masks, check overflow, write it back.
- bfd_check_overflow()bfd/reloc.c:445Decide signed, unsigned or bitfield overflow for a value in a field.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Rank matches
Inspect the comparisons with
best_matchin the linked source. Does a largermatch_priorityalways win?Show answer
No. Lower numeric priorities rank ahead of larger ones. The probe also has rules for preferred targets and duplicate matches.
-
Question 2: Handle ambiguity
Why should an inspector report matching targets instead of silently selecting an arbitrary one?
Show answer
An arbitrary choice can interpret the same bytes through the wrong backend. Reporting candidates lets the caller make an explicit choice.
-
Question 3: Recognize abstraction loss
Can canonical symbols preserve every ELF-specific field automatically?
Show answer
No. Format-specific data can require private backend state and copy hooks. A common representation does not promise lossless format conversion.
-
Problem 1: Build a format-probe inspector
Implement a C program that initializes BFD, opens a file, checks object format, and reports the selected target or matching alternatives. Read format recognition and error ownership before implementing cleanup.
Test requirements: Test an ELF object, plain text, a truncated ELF header, and a missing path. Assert useful nonzero failures and release any returned candidate list.
Show solution
Opening succeeds for some files that are not objects. Recognition is a separate check. Report BFD error state before cleanup can replace it. The matches array has its own documented ownership and must not outlive careless cleanup.
-
Problem 2: Trace target selection rather than guessing
Add a diagnostic-only trace around candidate probes in a disposable BFD build. Write a driver that records vector names, match priorities, and the selected result for each file.
Test requirements: Compare default recognition with an explicitly supplied target name. Use a valid object and invalid bytes. Explain skipped or repeated probes from the actual control flow.
Show solution
Explicit target selection changes the recognition path and is not equivalent to blindly trying every vector. Lower numeric match priorities can rank ahead of larger ones. Preserve the original return value and error state when tracing.
-
Problem 3: Implement a bounded section dumper
Extend the probe inspector to dump a selected section slice through BFD. Read bfd_get_section_contents and the public section-size interface. Validate numeric arguments before making the library call.
Test requirements: Test the first byte, the final byte, an empty slice, an offset beyond the section, and an offset-plus-length overflow. Include a NOBITS section.
Show solution
Check offset and length without overflowing their sum. A zero-size request and a section with no stored file bytes require deliberate handling. BFD's section representation differs from a raw file slice, so document the semantics your dumper exposes.
-
Problem 4: Walk an archive safely
Extend the inspector to recognize an archive and iterate its members. Read the member-handle lifetime rules. Write a runner that compares your member list with ar's listing.
Test requirements: Cover an empty archive, two object members, one non-object member, and two members with the same basename. Ensure each handle is closed in a valid order.
Show solution
Archive recognition does not establish that every member is an object. Probe each member separately. Preserve duplicate member identities rather than using basename as a unique key. Closing the parent affects its child handles.
-
Problem 5: Compare canonical and ELF-specific symbols
Write a BFD symbol dumper and an independent Python decoder for a narrow ELF64 symbol-table subset. Generate local, weak, global, and undefined symbols. Read how BFD canonicalizes ELF symbols.
Test requirements: Compare binding, section association, value, size, and visibility. Mark fields unavailable through your chosen canonical interface rather than fabricating values.
Show solution
The canonical representation supports common operations but is not the entire Elf_Internal_Sym. Some information requires ELF-private state or a separate decoder. An unavailable canonical field is not automatically zero.
-
Problem 6: Test conversion invariants
Write a driver that copies a generated ELF object through objcopy to ELF and then to a raw binary. Read which BFD operations preserve private data. Define a different correctness relation for each output format.
Test requirements: For ELF, compare symbols, relocations, flags, and section contents. For binary, compare only the intended loadable bytes. Include an input with an unresolved reference.
Show solution
ELF copying can preserve relationships beyond bytes. Raw binary has no ELF symbol or relocation tables, so it cannot promise the same linkable semantics. Treat unsupported conversions or unresolved output semantics explicitly rather than calling every output equivalent.
-
Problem 7: Create a failure-path ownership audit
Annotate one complete inspector path with allocation owners and lifetimes, then implement fault injection at each allocation in your own program. Read BFD allocation and close behavior.
Test requirements: Every injected failure must produce a nonzero exit without using a closed handle or freeing BFD-owned symbols. Run a memory checker when available and record its limitations.
Show solution
Separate caller-owned pointer arrays from symbols owned by the BFD. Centralize cleanup and preserve the first failure reason. Do not apply free to every pointer merely because it came back from a library call.
libbfd · client API
The BFD API: build an object-file inspector
A BFD client works with a file handle, sections, symbols and relocations. The library selects the backend and converts format-specific records into canonical structures.
For library users
The BFD chapter follows calls into the backend. This chapter covers the caller's responsibilities: initialization, call order, return values and memory ownership.
One input file, five steps
bfd_openr therefore does not prove that the file contains a supported object.A complete C client
This program prints section names, sizes and virtual memory addresses (VMAs), then regular symbols with their nm class letters. It accepts one object or executable. Archives need a separate member loop.
#include <bfd.h>
#include <inttypes.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
static void
show_section (bfd *abfd, asection *sec, void *data)
{
(void) abfd;
(void) data;
printf ("section %-16s size=%" PRIuMAX " vma=0x%" PRIxMAX "\n",
bfd_section_name (sec), (uintmax_t) bfd_section_size (sec),
(uintmax_t) bfd_section_vma (sec));
}
int
main (int argc, char **argv)
{
bfd *abfd;
asymbol **symbols = NULL;
char **matching = NULL;
long needed, count;
int status = EXIT_FAILURE;
if (argc != 2)
{
fprintf (stderr, "Usage: %s OBJECT\n", argv[0]);
return EXIT_FAILURE;
}
if (bfd_init () != BFD_INIT_MAGIC)
{
fputs ("BFD header/library configuration mismatch\n", stderr);
return EXIT_FAILURE;
}
abfd = bfd_openr (argv[1], NULL);
if (abfd == NULL)
{
bfd_perror (argv[1]);
return EXIT_FAILURE;
}
if (!bfd_check_format_matches (abfd, bfd_object, &matching))
{
bfd_perror (argv[1]);
if (matching != NULL)
for (char **target = matching; *target != NULL; ++target)
fprintf (stderr, "Matching target: %s\n", *target);
goto done;
}
bfd_map_over_sections (abfd, show_section, NULL);
needed = bfd_get_symtab_upper_bound (abfd);
if (needed < 0)
goto bfd_error;
if (needed > 0)
{
if ((uintmax_t) needed > SIZE_MAX)
{
fputs ("Symbol pointer array is too large\n", stderr);
goto done;
}
symbols = malloc ((size_t) needed);
if (symbols == NULL)
{
perror ("malloc");
goto done;
}
count = bfd_canonicalize_symtab (abfd, symbols);
if (count < 0)
goto bfd_error;
for (long i = 0; i < count; ++i)
printf ("symbol %c %s\n", bfd_decode_symclass (symbols[i]),
bfd_asymbol_name (symbols[i]));
}
else
puts ("No regular symbol table");
status = EXIT_SUCCESS;
goto done;
bfd_error:
bfd_perror (argv[1]);
done:
free (matching);
free (symbols);
if (!bfd_close (abfd))
{
bfd_perror ("bfd_close");
status = EXIT_FAILURE;
}
return status;
}
bfd_get_symtab_upper_bound returns a capacity in bytes. bfd_canonicalize_symtab returns a symbol count. The program allocates with the first value and iterates with the second.Build and run
Save the program as bfd-inspect.c. The commands below assume a C compiler, matching BFD development headers, and a shared libbfd on the library search path.
cc -std=c11 -Wall -Wextra bfd-inspect.c -o bfd-inspect -lbfd
printf 'extern int other(int); int entry(int n) { return other(n) + 1; }\n' > sample.c
cc -c sample.c -o sample.o
./bfd-inspect sample.o
entry symbol and an undefined other symbol. Section names and class letters depend on the target format. Static libbfd builds can require additional libraries from that build's configuration. The BFD_INIT_MAGIC check detects a configuration mismatch, but does not guarantee API or ABI compatibility across releases.Ownership determines the cleanup order
| Value | Owner | Client responsibility |
|---|---|---|
bfd * | Client owns the open handle. | Call bfd_close once. Closing releases the handle even when it reports failure. |
asection * | BFD owns the section. | Use it before closing its BFD. Do not call free on it. |
asymbol **symbols | Client owns the pointer array. | Allocate the reported byte capacity. Free the array after its last use. |
symbols[i] and names | BFD owns input symbols and their names. | Do not free individual symbols or names. Copy any data that must survive bfd_close. |
char **matching | Client owns the returned match list. | After an ambiguous recognition, report candidates and free the list once. Do not free each name. |
| Section read buffer | Client supplies the storage. | Pass a buffer large enough for the requested byte range. Release heap storage after use. |
Errors and addresses have different meanings
Check each return contract
Open calls return NULL on failure. Boolean calls return false. Symbol and relocation readers use negative counts for errors. Zero can mean an empty table.
bfd_perror prints the current BFD error. Report it before cleanup calls can replace it. Allocation failures use the C library's error reporting.
A VMA is not a file offset
bfd_section_vma reports the section's virtual address. A relocatable object's sections usually have no final addresses. bfd_get_section_contents takes an offset within a section, not a VMA.
bfd_asymbol_value adds a symbol's section VMA to its section-relative value. It does not resolve an undefined symbol or perform a link.
An empty regular table is valid
A stripped executable can lack a regular symbol table while retaining dynamic symbols. Reading the regular table does not automatically read the dynamic table.
The library recognizes only targets included in its build. Passing a target name cannot add a missing backend.
Extend the client by task
| Task | Public API sequence | Required condition |
|---|---|---|
| Read section bytes | bfd_get_section_by_name → bfd_get_section_contents | Check that the section exists. Supply a buffer and a bounded section-relative range. A section without SEC_HAS_CONTENTS, such as .bss, returns zero-filled data rather than stored file bytes. |
| Read regular symbols | bfd_get_symtab_upper_bound → bfd_canonicalize_symtab | Allocate an asymbol ** array with the byte capacity. Check the returned count before iterating. |
| Read dynamic symbols | bfd_get_dynamic_symtab_upper_bound → bfd_canonicalize_dynamic_symtab | Use a separate pointer array and the same capacity/count pattern. The backend must support dynamic symbols. |
| Read section relocations | bfd_get_reloc_upper_bound → bfd_canonicalize_reloc | Allocate an arelent ** array and pass the canonical regular symbol array. Keep that symbol array alive while using relocation symbol pointers. Reading relocations does not apply them. |
| Read dynamic relocations | bfd_get_dynamic_reloc_upper_bound → bfd_canonicalize_dynamic_reloc | Pass the canonical dynamic symbol array. This table is distinct from the relocations attached to individual input sections. |
| Inspect an archive | bfd_check_format(archive, bfd_archive) → bfd_openr_next_archived_file | Start with NULL, then pass the previous member to obtain the next. Obtain the next member before closing the previous one. Recognize each member separately. At NULL, bfd_error_no_more_archived_files marks normal completion. Close members before the archive. |
| Create an object | bfd_openw → bfd_set_format → bfd_set_arch_mach → bfd_make_section_with_flags → bfd_set_section_size → bfd_set_section_contents → bfd_close | Select an output target and bfd_object. Set architecture, section flags, alignment and sizes before writing contents. Check every result, including close, which completes output. Copying an existing file also needs symbols, relocations and format-specific metadata. |
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Size the symbol buffer
Read the linked contract for
bfd_get_symtab_upper_bound. Is its result a symbol count?Show answer
No. It is a byte bound for the symbol-pointer storage. Negative results indicate an error.
-
Question 2: Retain the owner
Can canonical symbol pointers remain usable after the owning BFD is closed?
Show answer
No lifetime guarantee permits that use. Keep the owning handle open while reading its symbols and sections.
-
Question 3: Design cleanup
Which resources does an inspector need to release after reading a symbol table?
Show answer
Release its allocated pointer buffer and close the BFD handle. Check relevant operation results before cleanup can replace error state.
-
Problem 1: Implement a relocation inspector
Extend the chapter's C inspector to read the regular symbol table and canonical relocations for every section. Follow the upper-bound and canonicalization contracts in the source. Print section-relative offsets, addends, target symbols, and relocation names.
Test requirements: Cover an object with no symbols, no relocations, and both call and data relocations. Compare semantic records with objdump, including negative addends.
Show solution
Relocation storage and symbol storage have separate bounds and counts. Pass the required canonical symbol array into relocation canonicalization. Each relocation offset belongs to its section, not directly to the whole file. Keep the owning BFD open during printing.
-
Problem 2: Make error handling testable
Refactor your inspector so each BFD operation has one checked result and one cleanup route. Implement injectable failures in the application's own allocation and output functions. Read the different BFD return contracts.
Test requirements: Test missing files, non-objects, zero symbols, allocation failure, and a failed output write. Assert the first error survives cleanup and that every resource has one owner.
Show solution
Do not interpret every zero as failure. Symbol bounds can be zero, counts can be negative, and handles can be NULL. Capture the diagnostic before cleanup. A failed stdout write should affect the program's status even after successful parsing.
-
Problem 3: Build a lifetime-safe symbol cache
Implement a C API that returns an owned snapshot of symbol names and section associations after closing the input BFD. Read canonical symbol allocation and handle cleanup.
Test requirements: Read two different objects sequentially. Verify the first snapshot remains valid after the second file closes. Test repeated names, undefined symbols, and allocation failure halfway through copying.
Show solution
Copy every string and value needed after close. Retaining an asymbol pointer is not an owned snapshot. Use a partial-construction cleanup path for copied names and entries. Duplicate symbol names require separate records or an explicit selection policy.
-
Problem 4: Create a deterministic object report
Change the inspector to emit structured JSON with stable ordering for sections, symbols, and relocations. Read which identifiers are input-local and which survive a relocatable link.
Test requirements: Compare two assemblies of the same source and one source with reordered local labels. Escape quotes and control characters in names. Do not serialize process pointer values as identifiers.
Show solution
Sort using documented keys and retain section identity when names repeat. Preserve meaningful duplicates. Stable reports should ignore allocator addresses and incidental traversal order without hiding changes to symbol binding, section placement, or relocation relationships.
-
Problem 5: Implement an archive-wide reference graph
Write a C program that reads every object member of an archive and builds a graph from undefined global references to candidate defining members. Read archive and symbol APIs.
Test requirements: Generate a two-member cycle, a weak definition, and two strong definitions of one name. Emit ambiguity explicitly. Compare your graph with an actual link without claiming to simulate all ld rules.
Show solution
Archive members are candidates, not automatically selected inputs. Multiple candidates and weak definitions need representation before resolution. A reference graph can explain dependencies but does not by itself reproduce ordered extraction, visibility, or platform-specific linker policy.
-
Problem 6: Check sizes without truncation
Implement a section-range validator using BFD's declared integer types. Read the section-content API and its bounds checks before writing conversions from command-line numbers.
Test requirements: Unit-test zero, the maximum representable value, one-past-end, a negative string, and an addition that would overflow. Prove rejected requests never call the read operation.
Show solution
Parse first, validate representability second, and use subtraction-based bounds checks after establishing offset is within size. Narrowing before validation loses evidence. Do not convert a negative signed value into a huge unsigned read request.
-
Problem 7: Design a hostile-input regression corpus
Create a generator for truncated ELF headers, malformed symbol-table extents, and relocation records with invalid symbol indices. Run the C inspector over each case in a separate process with a timeout.
Test requirements: Preserve the original bytes and a mutation manifest. Assert bounded failure and nonzero status for rejected inputs. Identify the exact BFD validation branch for two cases.
Show solution
Treat diagnostics and supported rejection behavior as part of the evidence. A program crash is not equivalent to a clean parse error. Minimize failures by preserving the malformed relationship, not merely the exit status.
bfd/elf*.c
An ELF port is a list of #defines and one #include
Generic ELF code lives in elf.c, elflink.c and elfcode.h. A backend overrides the hooks it needs and includes a template that builds the vector.
From the command line
A link error that names a relocation type, such as relocation truncated to fit: R_X86_64_PC32, starts in a backend's relocate_section. The backend detects the problem and a callback in ld/ldmain.c prints the message. multiple definition of and undefined reference to reach the user the same way.
elfxx-target.h applies, often a generic function or NULL. Read that file first when a backend "does nothing".| Hook in elf_backend_data | Called from | What a backend does there |
|---|---|---|
elf_info_to_howto | reading relocs | Map an r_type number to its reloc_howto_type: size, shift, mask, overflow check. |
check_relocs | elflink.c:4335, after symbols load | Count GOT entries, PLT entries and dynamic relocs that each input will need. |
adjust_dynamic_symbol | sizing | Decide copy reloc or PLT for each symbol a shared library defines. |
early_size_sections / late_size_sections | ldelf.c:1839 via bfd_elf_size_dynamic_sections | Give .got, .plt and .rela.* their final sizes. Before 2.43 these were always_size_sections and size_dynamic_sections. |
relocate_section | elflink.c:11411, once per input section | Apply every relocation: compute S + A − P, check range, write bytes, emit dynamic relocs. |
finish_dynamic_symbol | elflink.c:11030 | Fill this symbol's PLT stub and GOT slot. |
finish_dynamic_sections | end of final link | Write .dynamic entries and PLT0. |
gc_mark_hook | --gc-sections | Say which section a relocation keeps alive. |
relocate_section or in a disagreement between check_relocs (the count) and relocate_section (the use).strong + strong
weak + strong
.o + .so
.so + .so
common + common
undefined weak
_bfd_elf_merge_symbol (bfd/elflink.c:1140) and the generic link_action table (bfd/linker.c:1324) decide when a second definition of a name arrives. The link lab runs these rules on a configurable link.- Local symbols are read once per input and written to the output .symtab unless they are stripped.
- For each section with contents, the bytes come from a cache filled by an earlier pass, an mmap, or a read.
- The relocations are read into Elf_Internal_Rela form. The ELF linker never builds arelents.
- The backend relocate_section patches the bytes in place: one switch case per relocation type.
- For ld -r and --emit-relocs, the relocations are copied out with symbol indices renumbered for the output.
- .eh_frame, SEC_MERGE and .stab sections go through their own writers. Everything else goes to bfd_set_section_contents at output_offset.
elf_link_input_bfd (bfd/elflink.c:11386) per input file. A crash in a link is usually inside one iteration of this loop, so break on relocate_section with a condition on the section name.Drill down
The generic ELF linker in elflink.c and two backends. The backend functions are the ones a target port writes.
Add one input's symbols7
- bfd_elf_link_add_symbols()bfd/elflink.c:6449Entry point from ld: dispatch on object or archive.
- elf_link_add_archive_symbols()bfd/elflink.c:6251Archive loop for ELF, aware of dynamic and versioned definitions.
- elf_link_add_object_symbols()bfd/elflink.c:4409Read the symbol table, merge each symbol into the hash table, record DT_NEEDED.
- _bfd_elf_merge_symbol()bfd/elflink.c:1140Decide what a new definition does to an existing one: override, ignore, warn, or make it indirect.
- _bfd_elf_add_default_symbol()bfd/elflink.c:1949For foo@@VER, also enter foo as an indirect symbol.
- bfd_elf_add_dt_needed_tag()bfd/elflink.c:3933Add a DT_NEEDED entry once per shared library that stays in the link.
- _bfd_elf_link_check_relocs()bfd/elflink.c:4335After symbols load, run the backend check_relocs over every input section.
Size the dynamic sections3
- bfd_elf_size_dynamic_sections()bfd/elflink.c:6929Called from ldelf_before_allocation: decide dynamic symbols, versions, DT_* entries.
- _bfd_elf_adjust_dynamic_symbol()bfd/elflink.c:3270Visit each symbol and call the backend adjust_dynamic_symbol.
- bfd_elf_size_dynsym_hash_dynstr()bfd/elflink.c:7880Size .dynsym, .hash, .gnu.hash and .dynstr.
Garbage-collect sections4
- bfd_elf_gc_sections()bfd/elflink.c:14667Mark from roots (entry, KEEP, exported symbols), then sweep.
- _bfd_elf_gc_mark()bfd/elflink.c:14151Mark one section and every section its relocations reach.
- _bfd_elf_gc_mark_reloc()bfd/elflink.c:14120Follow one relocation through gc_mark_hook to its target section.
- elf_gc_sweep()bfd/elflink.c:14405Drop every unmarked section; --print-gc-sections reports them.
Final link4
- _bfd_elf_final_link()bfd/elflink.c:12635Allocate output buffers, then process every input bfd and write the result.
- elf_link_input_bfd()bfd/elflink.c:11386Read one input's sections, symbols and relocations, and call relocate_section.
- elf_link_output_extsym()bfd/elflink.c:10740Write one global symbol and call finish_dynamic_symbol for it.
- elf_link_sort_relocs()bfd/elflink.c:10026Sort .rela.dyn so RELATIVE entries come first (-z combreloc).
.eh_frame, merged strings and .eh_frame_hdr7
- _bfd_elf_parse_eh_frame()bfd/elf-eh-frame.c:579Parse CIEs and FDEs of one input .eh_frame.
- _bfd_elf_discard_section_eh_frame()bfd/elf-eh-frame.c:1502Drop FDEs of discarded code and merge duplicate CIEs.
- _bfd_elf_write_section_eh_frame()bfd/elf-eh-frame.c:1951Write the edited .eh_frame with adjusted offsets and encodings.
- _bfd_elf_write_section_eh_frame_hdr()bfd/elf-eh-frame.c:2582Write the sorted table of initial locations that .eh_frame_hdr holds.
- _bfd_add_merge_section()bfd/merge.c:612Register a SEC_MERGE input section for deduplication.
- bfd_merge_sections()bfd/merge.c:1061Deduplicate entries across inputs and set the merged sizes; ld calls it after mapping.
- _bfd_merged_section_offset()bfd/merge.c:1133Translate an offset into an input SEC_MERGE section to its merged position.
One backend: x86-645
- elf_x86_64_scan_relocs()bfd/elf64-x86-64.c:2500Scan one section's relocations and count GOT, PLT and dynamic relocation needs per symbol.
- _bfd_x86_elf_late_size_sections()bfd/elfxx-x86.c:2275Size .got, .plt, .plt.sec and .rela.* for every x86 target.
- elf_x86_64_relocate_section()bfd/elf64-x86-64.c:3165The switch over R_X86_64_* types that writes the bytes.
- elf_x86_64_finish_dynamic_symbol()bfd/elf64-x86-64.c:5142Fill one symbol's PLT entry and GOT slot.
- elf_x86_64_convert_load_reloc()bfd/elf64-x86-64.c:1792Rewrite mov foo@GOTPCREL into lea when the symbol is local (GOTPCRELX relaxation).
One backend: AArch644
- elfNN_aarch64_check_relocs()bfd/elfnn-aarch64.c:7897Count GOT, PLT and TLS needs, per NN = 32 or 64.
- elfNN_aarch64_relocate_section()bfd/elfnn-aarch64.c:7022Apply R_AARCH64_* types, including TLS relaxation.
- elfNN_aarch64_finish_dynamic_symbol()bfd/elfnn-aarch64.c:10043Fill PLT and GOT entries.
- elfNN_aarch64_size_stubs()bfd/elfnn-aarch64.c:4740Create long-branch veneers for calls out of range.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Explain dynamic sizing
Why can the linker need a sizing pass before writing GOT and PLT contents?
Show answer
It must determine which entries are needed and reserve their space before their final addresses and contents can be fixed.
-
Question 2: Trace diagnostics
Why can a relocation error originate in BFD but appear as an ld diagnostic?
Show answer
BFD detects a backend problem and invokes the linker's callbacks. ld supplies the user-facing diagnostic context.
-
Question 3: Choose a repair location
A single target encodes one relocation incorrectly while other targets link correctly. Where should investigation begin?
Show answer
Begin with that target's relocation handler and relocation definitions. Use generic ELF code only when evidence points to shared behavior.
-
Problem 1: Derive relocation overflow boundaries
Generate an x86-64 object with a PC-relative 32-bit relocation and an explicit addend. Write linker scripts that place its target at the two signed boundaries and one step outside each. Read the backend's actual field check.
Test requirements: Build an independent Python oracle for the field value. Assert success or failure at all four boundaries. Derive placements from the relocation place and addend rather than approximate section distance.
Show solution
The signed range is -2147483648 through 2147483647 for the computed value. Include S, A, and P in the calculation. Choose a relocation form that is not transformed by another optimization, or account for that transformation from source.
-
Problem 2: Explain a GOT decision experimentally
Write assembly using both a direct symbol reference and a GOT-based reference. Link variants with global-default, hidden, and local definitions. Instrument the backend's relocation scan or inspect its decisions in a debugger.
Test requirements: Report GOT allocation, remaining dynamic relocations, and final instructions for each case. Predict which references may bind locally before reading the output.
Show solution
Binding and visibility influence whether a reference can resolve locally. A GOT-based input can sometimes relax into a direct access. Separate the input relocation from the final instruction and explain actual decisions with the backend condition that permits them.
-
Problem 3: Build a section-liveness oracle
Generate one entry section that references helper, one unreferenced function section, and one data section referenced only by the dead function. Implement reachability in Python and compare it with a garbage-collected link.
Test requirements: Test a live cycle, a dead cycle, and two functions deliberately placed in one section. Cite both mark and sweep paths in the ELF linker.
Show solution
Reachability roots and relocation edges retain complete sections. A dead cycle does not become live merely by referencing itself. Functions in one retained section remain together. Model the actual roots of the selected link, including its entry.
-
Problem 4: Test COMDAT selection and consistency
Create two assembly objects defining the same COMDAT group signature with distinguishable data and a relocation within each group. Read ELF group selection and symbol resolution.
Test requirements: Link in both input orders. Verify that the selected group's symbol and relocation refer to the same surviving contents. Add a non-COMDAT duplicate as a negative test.
Show solution
COMDAT permits the linker to discard redundant group instances as a unit. Do not combine a retained section from one instance with a relocation target from a discarded instance. An ordinary duplicate strong definition does not gain COMDAT semantics.
-
Problem 5: Trace dynamic-section sizing
Build a shared library with multiple references to the same imported function and data symbol. Add local diagnostic counters to allocation and finalization hooks in a disposable backend build.
Test requirements: Vary reference counts while keeping the symbol set fixed. Compare GOT and PLT sizes and relocation counts. Explain any duplicate elimination and reserved entries through source.
Show solution
Several references can share one per-symbol entry, so entry counts need not equal reference counts. Reserved entries and relocation kinds affect total sizes. Sizing establishes addresses before finalization fills entries. Confirm actual backend rules instead of imposing a one-entry-per-reference model.
-
Problem 6: Audit private ELF information during copying
Generate ELF objects with nondefault visibility, a COMDAT group, and a note section. Copy them through objcopy and write a Python checker for semantic preservation. Read the private copy hooks.
Test requirements: Remove one private-copy call only in a disposable build. Determine which fixture detects the change, or explain why these fixtures do not exercise that hook.
Show solution
Canonical section bytes alone do not prove preservation of ELF relationships. Check visibility, group membership, and note contents separately. A mutation that no fixture detects exposes a coverage gap rather than proving the removed hook is unnecessary.
-
Problem 7: Write an ABI-preserving backend regression
Select one earlier relocation or visibility fixture and locate the existing target tests that cover its code path. Add a focused test and apply a temporary one-line fault to that path.
Test requirements: Demonstrate a pass on the unmodified backend and a failure on the faulty backend. Check output bytes or relationships, not only diagnostic text or successful linking.
Show solution
Change the test fixture or expectation enough to expose the selected backend decision. A useful test fails when that decision is wrong and passes after restoration. Do not invent a new relocation encoding to accommodate an incorrect result.
configure
One target triplet is read by four separate tables
bfd, gas, ld and opcodes each translate the triplet themselves. A new target, or a new OS on an old CPU, touches all four.
From the command line
ld -V and objdump -i show what one build supports. A cross build installs its programs with the triplet as a prefix, such as aarch64-elf-objdump. gcc -dumpmachine prints the triplet that gcc was configured for.
--enable-targets=all widens bfd, ld emulations and opcodes. gas still assembles for one CPU per build: gas/configure.ac:216–240 adds emulations only.Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Explain a cross prefix
Does the name
aarch64-elf-objdumpprove that a tool executes on an AArch64 host?Show answer
No. The prefix describes its intended target. A cross tool can execute on another host architecture.
-
Question 2: Distinguish two targets
Why does recognizing an object format not prove that gas can assemble instructions for its architecture?
Show answer
BFD format support and the selected gas CPU backend are separate configuration decisions.
-
Question 3: Diagnose missing support
A backend exists in the tree, but objdump rejects its format. What evidence should be collected first?
Show answer
Collect the installed version,
objdump --info, and the build configuration. Determine whether that backend was included before changing its parser. -
Problem 1: Write a target-selection report
Implement a Python report for one native x86-64 target and aarch64-unknown-elf. Trace selection through BFD, gas, ld, and opcodes rather than treating one table as authoritative.
Test requirements: Emit the matching cases, default vector, additional vectors, assembler backend, and default linker emulation. Test a triplet with no supported match and report uncertainty instead of guessing.
Show solution
Each component selects its own configuration. Record file and case evidence for every value. Pattern order and shell assignments matter, so substring search alone is insufficient to determine the effective selection.
-
Problem 2: Measure an additional-target build
Configure two disposable native builds that differ only in adding one supported additional BFD target through the documented target-selection option. Read how configure propagates that choice.
Test requirements: Compare objdump's supported formats, linked object lists, binary sizes, and ability to inspect a fixture for the additional target. Prove gas did not become a universal assembler.
Show solution
Follow
--enable-targetshandling through BFD and opcodes configuration. Additional object and disassembler support is distinct from gas CPU selection. Size growth measures this build only and can vary with linking and optimization. -
Problem 3: Resolve a triplet alias end to end
Write a driver that canonicalizes several target spellings with config.sub, then records each component's selected target case. Include aarch64-elf and its canonical spelling.
Test requirements: Assert equivalent effective selections for aliases that canonicalize identically. Include an unsupported spelling and preserve config.sub's diagnostic and status.
Show solution
Canonicalization precedes component matching. Do not infer support from the raw shorthand alone. Equivalent canonical triplets should enter equivalent target-selection logic under the same configuration inputs.
-
Problem 4: Prove a missing vector is configuration
Build or select a default-only objdump and one configured with an additional target. Use the same foreign object with both. Write a reproducible diagnostic report.
Test requirements: Record version, supported formats, configuration inputs, and file identity. Trace the rejected path and show that the fixture bytes remain identical across runs.
Show solution
A file can be valid while unsupported by one installed BFD build. Recognition failure without a compiled target vector is not evidence that the ELF file needs repair. Confirm the available vectors and selected backend objects.
-
Problem 5: Audit a proposed new target mapping
In a disposable source copy, add a test-only target spelling that maps to an existing architecture and platform behavior. Trace all component decisions it would require without inventing instruction semantics.
Test requirements: Submit the mapping patch, a case-selection checker, and native-tool build smoke tests where applicable. Identify any inherited emulation or environment choice that is wrong for the proposed platform.
Show solution
Reusing a backend is not a complete platform port. BFD vector, gas environment, linker emulation, and opcodes selection must agree. Explicitly leave unsupported platform behavior unresolved rather than making a new name appear fully supported.
-
Problem 6: Detect mixed installations
Write a runner that accepts explicit tool paths and checks whether the assembler's output can be read and relocatably linked by the supplied tools. Read the output-format defaults selected for each component.
Test requirements: Test a consistent set, one intentionally wrong target tool, and two versions with otherwise compatible target support. Distinguish version mismatch from demonstrated incompatibility.
Show solution
Assemble a target-specific fixture and check its machine and class before linking. Different version strings alone do not prove incompatibility. Matching version strings alone do not prove matching architectures or supported formats.
-
Problem 7: Turn configuration assumptions into tests
Pick one case in each target table used for aarch64 ELF. Write table-driven tests for nearby target patterns, including a big-endian spelling and an unsupported OS spelling.
Test requirements: Show the selected vector, gas endianness, and ld emulation or explicit rejection for each case. Mutate one case in a disposable copy and demonstrate a failing assertion.
Show solution
Test effective branch behavior rather than just the presence of a pattern string. Endianness can affect default vector and emulation. A test that only checks that four files contain aarch64 will miss incompatible selections.
libopcodes · opcodes/
The disassembler calls back into objdump for every byte and every word it prints
libopcodes never opens a file. objdump fills a disassemble_info (include/dis-asm.h:137) with callbacks, and the per-arch printer drives them.
From the command line
objdump -d -M intel passes a disassembler option to the x86 printer. objdump --help lists the -M options of each architecture. The x/i command of GDB calls the same printers.
- disassembler() (disassemble.c:112) is a switch on the BFD architecture. It returns a function pointer.
- Per-arch setup: options, private data, the instruction length unit.
- disassemble_bytes (objdump.c:3265) calls the printer once per instruction.
- The printer reads bytes through a callback. GDB passes its own callback that reads target memory.
- Text goes out in styled pieces, so objdump and GDB can colour mnemonics, registers and addresses.
- Symbolic addresses come from the caller, which owns the symbol table.
- The return value is the instruction length. A negative value means a read error.
riscv, mips, sparc
riscv-opc.c is a table of match and mask words. riscv-dis.c walks it. gas uses the same table to assemble.
i386, aarch64
i386-gen.c reads i386-opc.tbl and writes i386-tbl.h (52k lines). aarch64-gen.c writes aarch64-{asm,dis,opc}-2.c. The outputs are committed.
fr30, m32r, or1k, mep…
cpu/*.cpu descriptions run through Guile to make *-desc.c, *-asm.c, *-dis.c. Regeneration needs the separate CGEN tree.
Drill down
From the dispatch switch to the generated decoder, for three instruction sets.
Disassemble one AArch64 instruction6
- disassembler()opcodes/disassemble.c:112Switch on bfd_architecture and return the printer.
- print_insn_aarch64()opcodes/aarch64-dis.c:4405Read 4 bytes, handle mapping symbols ($x, $d), and print.
- print_insn_aarch64_word()opcodes/aarch64-dis.c:4224Decode one word and print it, or print .inst for an undefined encoding.
- aarch64_decode_insn()opcodes/aarch64-dis.c:3837Find the opcode entry for a word and extract its operands.
- aarch64_opcode_lookup()opcodes/aarch64-dis-2.c:35510Generated decision tree from aarch64-gen.
- print_aarch64_insn()opcodes/aarch64-dis.c:4187Print mnemonic and operands through fprintf_styled_func.
Disassemble one x86 instruction3
- print_insn_i386()opcodes/i386-dis.c:10388Entry point for AT&T and Intel syntax.
- print_insn()opcodes/i386-dis.c:9720Read prefixes, then walk dis386 and the extension tables to the entry.
- ckprefix()opcodes/i386-dis.c:8792Collect legacy, REX and REX2 prefixes.
Disassemble one RISC-V instruction2
- print_insn_riscv()opcodes/riscv-dis.c:1505Pick the instruction length from the low bits and read the word.
- riscv_disassemble_insn()opcodes/riscv-dis.c:942Search riscv_opcodes by match and mask, honouring the enabled extensions.
Assemble with the same tables2
- aarch64_opcode_encode()opcodes/aarch64-asm.c:2612Insert operand fields into an opcode entry's base value for gas.
- riscv_opcodes()opcodes/riscv-opc.c:451The RISC-V table: name, extension, operand string, match, mask.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Explain context
Can the same byte sequence have different interpretations under different instruction modes?
Show answer
Yes. Instruction mode and target features can change decoding. Bytes without the correct context are insufficient.
-
Question 2: Choose a bug location
Section bytes are correct, but one instruction prints the wrong operand. Which layer is the first candidate?
Show answer
Inspect the target disassembler and operand decoding in opcodes before changing the object-file reader.
-
Question 3: Avoid false equivalence
Must gas and objdump share every instruction parser function?
Show answer
No. Assembly parses text into encodings. Disassembly decodes encodings into text. Some tables can be shared without identical algorithms.
-
Problem 1: Implement a bounded disassembly client
Write a C program that disassembles an x86-64 byte buffer through libopcodes using disassemble_info callbacks. Read the client setup in objdump and the callback contracts before coding.
Test requirements: Test an empty buffer, a nop, a multi-byte instruction, and a truncated instruction. Assert that your read callback rejects every request outside the supplied buffer.
Show solution
Translate requested virtual addresses into buffer offsets with checked subtraction. Return a read error without copying bytes when the range is invalid. Advance according to the decoder's documented result and prevent a zero-length loop.
-
Problem 2: Find instruction boundaries systematically
Write a generator for x86 instructions whose encodings use prefixes, ModRM, SIB, and displacements. Assemble them, extract text bytes, and compare libopcodes' decoded lengths with symbol differences marking each instruction.
Test requirements: Include displacement boundaries, register-only operands, and truncated copies. Report length errors separately from mnemonic-format differences.
Show solution
Label both ends of each source instruction to obtain assembler-derived lengths. A decoding mismatch in length shifts every following instruction. Textual aliases can differ without a boundary error, so do not compare strings as the sole oracle.
-
Problem 3: Build a mode-confusion experiment
Generate one raw byte sequence valid under more than one x86 mode. Write a libopcodes driver that selects 32-bit and 64-bit contexts explicitly. Read the machine-selection and prefix logic.
Test requirements: Preserve identical bytes across both runs. Compare decoded lengths and register names. Add a test that proves your driver actually changes the selected mode.
Show solution
The architecture and machine context are inputs to decoding. Some prefixes and operand sizes change meaning between modes. Explain a concrete difference through the branch that selects it rather than assuming different printed register names prove every setting is correct.
-
Problem 4: Trace one AArch64 decode decision
Choose an instruction-table entry with variable register operands. Write a Python encoder for that one form from its fixed opcode and operand fields. Trace the decoder's candidate and operand checks.
Test requirements: Compare several register combinations against GNU assembly and disassembly for an AArch64 build. Flip one fixed bit and explain whether it becomes another instruction or fails this form's match.
Show solution
A mask comparison identifies candidates, not necessarily every validity condition. Operand constraints can reject a matched pattern. The independent encoder must preserve fixed bits and insert only the documented fields for the chosen form.
-
Problem 5: Test memory callback failure paths
Instrument the bounded disassembler from problem 1 with a callback log and an injectable failure at a selected byte address. Read the decoder's fetch and error paths.
Test requirements: Fail the first byte and a later byte of a multi-byte instruction. Verify bounded termination, recorded read requests, and the behavior of the error callback.
Show solution
A decoder may request bytes incrementally and can have fallback behavior after a partial fetch. Assert the contract your wrapper promises, including no out-of-range read and no infinite loop. Do not require one memory-error callback per attempted byte.
-
Problem 6: Design an assembly-disassembly round trip
Write a driver that assembles a restricted set of instructions, disassembles them, normalizes supported aliases, and reassembles the normalized output. Read the printer logic for one alias.
Test requirements: Compare bytes for register arithmetic and memory operands. Include one unsupported printed form and reject it clearly instead of silently dropping text.
Show solution
Restrict the accepted syntax and distinguish semantic aliases from encoding changes. Round-trip byte equality is useful within the selected subset. It does not prove every decoder output is valid assembly for every option and target.
-
Problem 7: Create a decoder regression with a real oracle
Select one instruction form and add a boundary-focused disassembly test in the target testsuite. Apply a temporary wrong mask or operand-width change in a disposable decoder build.
Test requirements: Prove your test fails with the fault and passes after restoration. Include a neighboring valid encoding that must retain its original interpretation.
Show solution
Check both the intended instruction and a nearby encoding. A test that merely recognizes one mnemonic can miss an overly broad mask. Use expected instruction lengths and operands to detect the chosen fault precisely.
gas/
gas defers every address it cannot know yet, then settles them in one pass at the end
While gas reads, the code goes into frags and each unresolved value becomes a fixup. write_object_file (write.c:2115) relaxes the frags, resolves what it can, and hands the rest to BFD as relocations.
From the command line
gcc -Wa,-alh=foo.lst -c foo.c writes an assembler listing with the encoded bytes beside each source line. as --help lists the options of this port after the generic ones.
- read.c reads one statement at a time. A directive goes to the pseudo-op hash, everything else to the target.
- md_assemble encodes the instruction. Known bits go into the current frag. A value that needs a symbol becomes a fixup at that frag offset.
- At end of input, relax_segment loops until no variable frag changes size. Only now are addresses final.
- fixup_segment folds in a symbol from the same section unless the target forces a relocation. md_apply_fix writes the bytes and sets fx_done.
- Fixups without fx_done become relocations: tc_gen_reloc picks the BFD_RELOC_* code, and bfd_install_relocation (reloc.c:998) stores the addend.
Directive lookup: the first table to claim a name wins
md_pseudo_tableoverobj_pseudo_tableoverpotable[]overcfi tablesThe tables are hashed in that order by pobegin (read.c:588). A target that defines .word overrides the ELF and generic meanings. The three layers are chosen at configure time by three generated one-line headers: targ-cpu.h (tc-*), obj-format.h (obj-*) and targ-env.h (te-*).
md_estimate_size_before_relax and the relax table grow it when the target is out of range, and every later address moves. A .org or .align after it can then change size too, so the loop runs again.call to a static in the same section
The distance is fixed inside one section. gas writes it.
call to a global function
The symbol can be preempted or lives elsewhere. ld decides.
load of a static in .rodata
tc_fix_adjustable rewrites it against the section symbol, so local labels can be dropped.
RISC-V call, same section
ld relaxation can delete bytes between the two, so gas must not fix the distance. See relaxation.
TC_FORCE_RELOCATION* macros.Drill down
A statement from text to bytes, and an object from frags to a file.
Read one statement9
- read_a_source_file()gas/read.c:894Loop over lines: labels, directives, instructions.
- pobegin()gas/read.c:588Fill po_hash: target table first, then object format, then generic.
- colon()gas/symbols.c:504Define a label at the current frag and offset.
- cons_worker()gas/read.c:4302Implement .byte, .word, .quad and friends.
- emit_expr()gas/read.c:4541Emit a value, or a fixup when it is not yet known.
- md_assemble()gas/config/tc-aarch64.c:8821Parse one AArch64 instruction and its operands.
- md_assemble()gas/config/tc-riscv.c:4398Parse one RISC-V instruction or macro.
- riscv_ip()gas/config/tc-riscv.c:2844Match the text against riscv_opcodes and build the instruction.
- append_insn()gas/config/tc-riscv.c:1971Emit the bytes and any fixup, with R_RISCV_RELAX when relaxing.
Expressions and symbols4
- expr()gas/expr.c:1826Parse an expression with precedence; the result is an expressionS.
- operand()gas/expr.c:793Parse one operand: number, symbol, unary operator, parenthesis.
- symbol_new()gas/symbols.c:331Create a symbol attached to a frag and offset.
- resolve_symbol_value()gas/symbols.c:1251Compute a symbol's value once its frag address is known.
Frags4
- frag_more()gas/frags.c:211Reserve fixed bytes in the current frag.
- frag_var()gas/frags.c:257Close the current frag with a variable part of a given relax state.
- frag_align()gas/frags.c:313Emit an rs_align frag.
- subseg_set()gas/subsegs.c:224Switch to a section and subsection; each has its own frag chain.
Write the object9
- write_object_file()gas/write.c:2115Finish every section and write the object through BFD.
- relax_segment()gas/write.c:2681Iterate frag sizes to a fixed point.
- relax_frag()gas/write.c:2544Generic relaxation with the target's md_relax_table.
- cvt_frag_to_fill()gas/write.c:413Turn a relaxed frag into fixed bytes, calling md_convert_frag.
- adjust_reloc_syms()gas/write.c:794Rewrite relocations against local symbols to section symbol + offset.
- fixup_segment()gas/write.c:955Resolve what is local, call md_apply_fix, keep the rest.
- write_relocs()gas/write.c:1259Turn surviving fixups into arelents with tc_gen_reloc.
- md_apply_fix()gas/config/tc-aarch64.c:9785Patch an AArch64 field, or leave it to a relocation.
- tc_gen_reloc()gas/config/tc-aarch64.c:10189Build the arelent and choose the BFD_RELOC_* code.
Debug and unwind output5
- dwarf2_directive_loc()gas/dwarf2dbg.c:1257Handle .loc: record file, line and column for the next instruction.
- dwarf2_emit_insn()gas/dwarf2dbg.c:1071Attach the current location to the instruction just emitted.
- out_debug_line()gas/dwarf2dbg.c:2447Write the .debug_line program.
- cfi_finish()gas/dw2gencfi.c:2385Write .eh_frame or .debug_frame from the .cfi_* directives.
- output_sframe()gas/gen-sframe.c:2509Write .sframe from the same CFI data.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Locate relaxation
Find
relax_segmentcalls in the linked source. Why can layout require repeated passes?Show answer
A size change can move later fragments and change other distances. Further passes let those dependent sizes settle.
-
Question 2: Compare section switching
What changes when assembly switches from
.textto.data?Show answer
Subsequent bytes and labels belong to a different section. Their input-section offsets do not establish final executable addresses.
-
Question 3: Diagnose a rejected mnemonic
Does an unknown mnemonic prove that BFD cannot write the target object format?
Show answer
No. Instruction parsing belongs to the assembler backend and selected instruction features. Object-format support is a separate concern.
-
Problem 1: Derive both short-branch boundaries
Write a Python generator for x86 forward and backward jumps with configurable padding. Read the gas relaxation table and derive the exact padding values at which a short jump becomes a near jump.
Test requirements: Test the two signed 8-bit displacement limits and one byte beyond each. Check emitted bytes, instruction lengths, and target addresses independently.
Show solution
The displacement is relative to the end of the selected instruction. Forward padding and backward padding therefore need different equations. A longer encoding also moves later labels. Derive each case instead of treating source padding as the displacement itself.
-
Problem 2: Make relaxation cascades visible
Construct at least three jumps so that growing one changes another jump's required encoding. Add a diagnostic-only trace to relaxation passes in a disposable assembler build.
Test requirements: Submit the source, pass trace, and a checker that verifies every final jump target. Show why a single left-to-right size calculation gives a wrong prediction.
Show solution
Fragment-size changes alter later addresses and can move other branch distances across their boundaries. Trace the actual passes and final convergence. A correct test checks final destinations as well as the number of iterations, which is not a stable interface.
-
Problem 3: Separate alignment from branch growth
Generate an x86 branch followed by alignment and a labelled instruction. Vary the preceding padding around an alignment boundary. Write a checker for label positions and branch displacements.
Test requirements: Find a pair of inputs where one size change is absorbed by alignment padding. Explain the result using fragment types and the alignment path.
Show solution
Increasing one fragment does not necessarily increase the final section size by the same amount. Alignment can shrink its own padding. Compute each label from the complete layout rather than adding the branch growth to every later address blindly.
-
Problem 4: Instrument fixup resolution
Add a local trace to fixup_segment that records expression symbols, section, offset, and whether an output relocation remains. Generate same-section differences, cross-section differences, and unresolved external references.
Test requirements: Predict each case before running it. Compare the trace with the output relocation table. Include one invalid expression and show where gas rejects it.
Show solution
Some expressions are fully known after layout. Others require relocation support that the target format may or may not provide. A surviving fixup needs a representable output relocation. Do not assume every arithmetic expression can be deferred to ld.
-
Problem 5: Test failed assembly as a transaction
Write a runner that assembles valid and invalid variants of one input into fresh output paths. Read how gas handles diagnostics and output-file removal.
Test requirements: Test a bad mnemonic, an out-of-range constant for a selected directive, and an undefined external call. Record exit status and output existence without assuming every warning is fatal.
Show solution
Distinguish errors from warnings using actual target behavior. An external reference can legitimately remain unresolved. Inspect gas's cleanup and force-output settings before specifying whether an output file should survive a failed invocation.
-
Problem 6: Build a directive-level byte oracle
Implement a Python oracle for a restricted assembly data language containing byte constants, fixed-width integers, labels, and alignment. Generate fixtures for gas and compare section contents and label offsets.
Test requirements: Cover negative values, exact-width boundaries, empty alignment padding, and a value outside your supported grammar. Reject unsupported syntax explicitly.
Show solution
Define integer truncation or rejection according to the selected directive's actual gas behavior. Encode little-endian values at declared widths and compute alignment from current offset. Keep the oracle independent of objdump's textual formatting.
-
Problem 7: Add a relaxation regression test
Turn the cascading-branch fixture into a gas dump test. Read the target's existing test driver and place the fixture where the intended assembler configuration runs it.
Test requirements: Show the test passes normally and fails with a temporary relaxation-boundary fault in a disposable build. Verify a neighboring non-boundary case still passes.
Show solution
A useful expectation constrains the opcode, displacement, and label relationship that the faulty decision changes. Broad disassembly patterns can accept the wrong branch size. Restore the backend before retaining the regression test.
ld/
ld is a script interpreter: BFD does the reading, the backend does the patching
lang_process (ldlang.c:8351) coordinates input processing, section mapping and allocation. The linker script describes the layout. Emulation hooks and BFD backends supply target-specific work. Some passes repeat before main calls ldwrite to produce the output.
Source map
ldmain.c starts the linker and calls the major operations. lexsup.c parses options, and ldgram.y defines the linker-script grammar. ldlang.c holds the script statements and coordinates the passes. ldemul.c dispatches emulation hooks, with shared ELF work in ldelf.c. ldwrite.c prepares the final link through BFD. The BFD backend reads object formats and applies target relocations.
The GNU ld steps page explains each phase and links to the resolution, layout and relocation labs.
GNU ld: passes and the inputs each pass reads
Time runs downward through the central blocks. Each incoming arrow names the files or state that the pass reads. Script statements appear again wherever a pass uses them. Step titles open the explanation below. Function names open source definitions. Hover or focus a linked term for details.
-
Reads
Command-line options, the selected emulation, and an explicit linker script, or the default script supplied by the emulation.
1. Read options and the script
main·parse_args· script parserProduces
Target settings and a statement tree: input names, section rules,
KEEP(), memory regions and expressions. -
Reads
Object and archive names from the command line and script statements. Archive indexes and unresolved symbols guide extraction.
2. Open inputs and resolve symbols
open_input_bfds·load_symbols·bfd_link_add_symbolsProduces
Input BFDs with section lists, plus symbol definitions. Extracted archive members supply additional input sections. LTO can add objects and require another scan.
-
Reads
Input BFD section lists from step 2, their relocation references and symbol definitions, plus entry settings and script
KEEP()matches.3. Collect unused sections
resolve_wilds·lang_gc_sections·bfd_gc_sectionsProduces
With
--gc-sections, BFD marks reachable sections and excludes unreachable ones. Input section lists exist before output-section mapping. -
Reads
Retained input sections, relocation records, symbol definitions and the selected backend's rules.
4. Check relocation requirements
lang_check_relocs· backend checksProduces
Requirements for GOT entries and other linker-created structures. New sections can appear, so ld refreshes wildcard matches.
-
Reads
Script section rules and wildcard matches, retained input sections, linker-created sections, and their attributes.
5. Map sections and place orphans
map_input_to_output_sections·lang_place_orphans·bfd_merge_sectionsProduces
Output-section membership and order, orphan placement, and merged contents where eligible. Final input offsets remain pending.
-
Reads
Mapped output sections, TLS sections, dynamic-link requirements and target emulation settings.
6. Prepare allocation
ldemul_before_allocation→ ELF hooksProduces
TLS alignment and dynamic section sizes. The default hook removes excluded output sections and can require preliminary sizing.
-
Reads
Section membership, sizes and alignment, plus script address expressions, memory regions and symbol values available in this phase.
7. Calculate sizes and addresses
lang_size_sectionsProduces
Input offsets, padding, output sizes and addresses for the current layout pass.
-
Reads
The current layout, relocation records, instruction contents and backend relaxation rules. Repeated passes also evaluate script assignments.
8. Relax and repeat where needed
ldemul_after_allocation·lang_relax_sectionswhere requiredProduces
Changed encodings or contents can require more assignment and sizing passes. Layout settles when the target needs no further changes.
-
Reads
Script expressions and symbol definitions, together with the settled section sizes and addresses.
9. Finish script assignments
lang_do_assignmentsin the final phaseProduces
Final script values such as
_end = .;, plus remaining expression diagnostics. -
Reads
The final layout and symbol values, input contents and relocation records, plus script statements that emit data.
10. Relocate and write output
ldwrite→bfd_final_link→ backendrelocate_sectionProduces
Relocated contents and link tables in the output file. Closing the output BFD completes its headers. Dynamic outputs can retain loader relocations.
main calls lang_process for steps 2–9, then calls ldwrite. Emulation hooks can add work. Relaxation can repeat assignments and sizing.1. Read options and the linker script
main selects the emulation, parses options and reads the linker script before calling lang_process. The emulation supplies target defaults and a default script. An explicit script can replace or extend that script.
The linker script is an input, supplied explicitly or through the emulation's default script. Parsing converts its text into statements, rather than a BFD list of input sections. Script commands such as INPUT and GROUP can also name object files or libraries. The statement tree records input files, output sections, matching rules and expressions. These statements describe the requested link. Later passes use them to select contents and calculate addresses. The sequence below follows the main ELF final-link path in GNU ld 2.46. Hooks can add work, and some passes repeat.
2. Open inputs and resolve symbols
open_input_bfds walks the input statements from the command line and linker scripts. An input BFD is the linker's handle for reading one file through the BFD library. load_symbols checks its format and calls bfd_link_add_symbols to add its symbols to the link's hash table.
When BFD recognises an object, it reads the section headers and creates section descriptors. Each input BFD's sections list records those descriptors, including names, sizes, alignment and flags. These input sections exist before ld maps them into output sections. For an archive, extracted members supply the sections that participate in the link.
Symbol resolution matches references to definitions and applies the rules for strong, weak and common symbols. BFD updates the hash table as inputs arrive. An archive's symbol index identifies members that can satisfy unresolved references. Resolution therefore starts while inputs open, before their sections have final addresses. LTO can supply more objects and cause another archive scan.
gcc -Wl,--trace foo.o -o foo prints each file as ld opens it.
3. Collect unused input sections
The section lists come from the input-opening phase. The ELF collector walks link_info.input_bfds, then each input BFD's sections list. Before collection, resolve_wilds prepares script matches. lang_gc_sections_1 uses those matches to mark sections protected by KEEP(). This matching does not yet assign input sections to output sections.
lang_gc_sections performs garbage collection when --gc-sections is active. Required sections, including the entry section and sections matched by KEEP(), form roots. BFD follows references from these roots and excludes unreachable sections. The references identify which sections are needed before their final addresses exist.
Collection acts on input sections before ld combines their contents into output sections. If several functions share one input section, a reference to one can retain them all. -ffunction-sections gives each function a separate input section. With --gc-sections active, -Wl,--print-gc-sections reports the sections removed.
4. Check relocation requirements
A relocation describes a value that an instruction field or data location needs. lang_check_relocs asks BFD to inspect these requirements before section mapping. A reference can require a Global Offset Table (GOT) entry or another linker-created structure.
This pass identifies required structures before allocation determines their addresses. It does not apply the final relocation values. Because checks can create sections, ld refreshes the script's wildcard matches afterwards.
5. Map sections, place orphans and merge contents
map_input_to_output_sections maps input sections to output sections under the script's rules. For example, .text : { *(.text .text.*) } collects matching code sections into the output section named .text. Mapping establishes membership and order. Allocation later calculates their offsets and addresses.
An orphan is an input section that no script rule places. lang_place_orphans handles these sections. With the normal placement policy, the ELF hook ldelf_place_orphan chooses an existing output section or creates one near sections with compatible attributes. For a final link, bfd_merge_sections then combines eligible mergeable contents, such as duplicate strings.
6. Prepare allocation through the emulation
The before_allocation hook runs after section mapping and orphan placement, before the main section-sizing pass. For ELF, ldelf_before_allocation calls bfd_elf_tls_setup to identify thread-local storage sections and establish their required starting alignment. It also calls bfd_elf_size_dynamic_sections to size structures needed for dynamic linking. Later, before_allocation_default calls strip_excluded_output_sections for a final link. That function can perform a preliminary sizing pass before it removes excluded output sections.
7. Calculate sizes and addresses
Allocation calculates section sizes and addresses. lang_size_sections enters lang_allocating_phase_enum and calculates input section offsets, alignment padding and output section sizes and addresses. For example, a 24-byte input at offset zero leaves offset 24 next. A following input with 16-byte alignment starts at offset 32, after 8 padding bytes. The linker records a layout in the output file. It does not allocate physical RAM or create threads.
gcc -Wl,-Map=foo.map foo.o -o foo records section placement and the reasons for archive-member extraction in foo.map.
8. Relax and repeat layout where necessary
Relaxation changes instruction sequences or section contents when the target permits a different encoding. A RISC-V call sequence can become a shorter instruction once its destination is within range. lang_relax_sections repeats assignments and sizing while the backend requests another relaxation pass. ELF emulation code can call it through ldelf_map_segments, which also reconciles section layout with segment layout. Target-specific hooks can require additional passes.
9. Finish script assignments
lang_do_assignments evaluates script expressions, including symbols such as _end = .;. Assignments run at several stages with the information then available. The final call in lang_process uses lang_final_phase_enum and reports remaining expression errors.
10. Apply relocations and write output
Relocation applies a calculated value to an instruction field or data location according to a relocation type. For example, a PC-relative call needs the displacement from the call site to the selected symbol. Earlier relocation checks identify requirements such as GOT entries. Relaxation can also inspect relocations before final layout.
After lang_process returns, main calls ldwrite. Its build_link_order traversal describes which input contents and script-generated data belong in each output section. bfd_final_link dispatches to the output backend. For ELF, _bfd_elf_final_link processes inputs through elf_link_input_bfd, which invokes the backend's relocate_section hook. The final link writes section contents and link tables.
Closing the output BFD completes the file's headers. A dynamic output can retain relocations for the loader to apply at run time.
Drill down
ldmain.c to ldwrite.c. The ELF emulation hooks are where ld calls back into BFD.
Startup4
- main()ld/ldmain.c:654Choose the emulation, parse options, load plugins, read the script, run the link.
- parse_args()ld/lexsup.c:651Turn the command line into script statements and settings.
- ldemul_choose_target()ld/ldemul.c:204Pick the emulation from -m, the target name or the default.
- ldfile_open_default_command_file()ld/ldfile.c:965Open the default script compiled into the emulation, or found on disk.
Main phases of lang_process (intermediate work omitted)14
- lang_process()ld/ldlang.c:8351Coordinate input processing, section mapping and allocation before main calls ldwrite.
- open_input_bfds()ld/ldlang.c:3620Open input BFDs and start symbol resolution by adding their symbols to the link hash table.
- load_symbols()ld/ldlang.c:3071Check the input format and add symbols for resolution. Also recognise linker scripts given as inputs.
- ldfile_open_file()ld/ldfile.c:604Search -L directories and the sysroot for -lfoo.
- ldfile_try_open_bfd()ld/ldfile.c:346Open a candidate and reject an incompatible format.
- lang_gc_sections()ld/ldlang.c:7931Garbage collection: ask BFD to exclude unreachable sections when --gc-sections is active.
- map_input_to_output_sections()ld/ldlang.c:4290Section mapping: attach input sections to output sections under the script rules, before allocation.
- walk_wild()ld/ldlang.c:1076Apply one wildcard statement to every input file.
- lang_place_orphans()ld/ldlang.c:7640Orphan placement: handle input sections that no script rule places.
- ldelf_place_orphan()ld/ldelf.c:2104ELF heuristics: find a similar output section, or make a new one.
- ldemul_before_allocation()ld/ldemul.c:102Invoke the emulation hook after section mapping, before the main allocation pass.
- lang_size_sections()ld/ldlang.c:6666Allocation: calculate section sizes, padding, input offsets and output addresses.
- ldemul_after_allocation()ld/ldemul.c:96Invoke target-specific work after initial sizing, including relaxation where required.
- lang_do_assignments()ld/ldlang.c:6875Evaluate script expressions again in the final phase and report remaining errors.
The linker script5
- script_file()ld/ldgram.y:298Start of the Bison grammar for linker scripts; ldlex.l start states switch between script, expression and version-script tokens.
- exp_fold_tree()ld/ldexp.c:1292Evaluate an expression tree in the current phase.
- fold_name()ld/ldexp.c:714Evaluate ADDR, SIZEOF, LOADADDR, DEFINED and symbol names.
- lang_memory_region_lookup()ld/ldlang.c:1457Find or create a MEMORY region.
- lang_map()ld/ldlang.c:2388Write the -Map file.
ELF emulation hooks8
- ldelf_after_open()ld/ldelf.c:1239Load DT_NEEDED libraries and check their compatibility.
- ldelf_before_allocation()ld/ldelf.c:1752Prepare TLS alignment and dynamic section sizes before allocation.
- bfd_elf_tls_setup()bfd/elflink.c:3630Identify TLS output sections and raise the first section's alignment to their maximum requirement.
- bfd_elf_size_dynamic_sections()bfd/elflink.c:6929Size structures needed for dynamic linking, including backend-created sections.
- before_allocation_default()ld/ldemul.c:301For a final link, call strip_excluded_output_sections to remove excluded output sections.
- strip_excluded_output_sections()ld/ldlang.c:4687Perform preliminary sizing if needed and remove excluded output sections from the output BFD's section list.
- ldelf_map_segments()ld/ldelfgen.c:259Reconcile section and segment layout, repeating when required.
- lang_relax_sections()ld/ldlang.c:8035Repeat assignments and section sizing while the backend requests another relaxation pass.
LTO plugin3
- plugin_load_plugins()ld/plugin.c:1104dlopen each plugin and call its onload with the transfer vector.
- plugin_call_claim_file()ld/plugin.c:1169Offer an input file to the plugins before BFD sees it.
- plugin_call_all_symbols_read()ld/plugin.c:1367After resolution, let the plugin compile and add objects.
Write the output4
- ldwrite()ld/ldwrite.c:537After lang_process returns, build link orders and dispatch the final link through bfd_final_link.
- build_link_order()ld/ldwrite.c:40Describe input contents and script-generated data for each output section in BFD link_order lists.
- _bfd_elf_final_link()bfd/elflink.c:12635ELF final link: process input contents, apply relocations and write link tables and sections.
- elf_link_input_bfd()bfd/elflink.c:11386Process one input BFD and invoke the backend relocate_section hook.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Test input ordering
An object introduces a reference after an earlier archive was scanned. Why can moving the archive later fix the link?
Show answer
A normal archive scan responds to unresolved references known at that point. A later scan can see the newly introduced reference.
-
Question 2: Recognize liveness granularity
Why can an unused function remain despite
--gc-sections?Show answer
If it shares a retained section, section garbage collection retains it with the rest of that section. Separate function sections enable finer removal.
-
Question 3: Diagnose an overflow
Should a relocation overflow always be fixed by enlarging the relocation field in BFD?
Show answer
No. The ABI defines the field. The program may need a different layout, instruction sequence, or code model.
-
Problem 1: Force an archive rescan to matter
Create main.o, liba.a, and libb.a so main needs a1, a1 needs b1, and b1 needs a2 in a different member of liba.a. Write a test matrix for ordinary order, repeated archives, and an archive group.
Test requirements: Check which members are extracted and which variants resolve every reference. Trace ld's group iteration and BFD's archive symbol loading. Avoid a fixture that succeeds through only one archive pass.
Show solution
Put a1 and a2 in separate archive members. A normal scan of liba before libb can miss the later a2 need. Repeating liba or placing both archives in a rescan group can reach the extraction fixed point.
-
Problem 2: Build a symbol-resolution state trace
Generate object combinations containing strong, weak, undefined, and COMMON symbols. Add diagnostic snapshots around input symbol loading in a disposable linker build.
Test requirements: Automate a table of the chosen definition or diagnostic under both input orders. Cover two strong definitions and a strong definition competing with a weak definition.
Show solution
A defined strong symbol ordinarily supersedes a weak definition. Two ordinary strong definitions are a conflict. COMMON introduces allocation and size rules, so trace its distinct state instead of treating it as another weak symbol.
-
Problem 3: Predict section garbage collection
Generate live and dead function sections, a data reference, and an unreferenced section protected by a linker-script KEEP rule. Implement an expected section-reachability graph.
Test requirements: Compare links with and without garbage collection and with and without KEEP. Include two functions sharing one section. Explain every retained section using a root or edge.
Show solution
Entry selection and KEEP can supply roots. Relocations from live sections supply edges. Garbage collection removes sections rather than individual instructions or functions. Shared-section functions remain together even if only one is called.
-
Problem 4: Write a section-allocation oracle
Create three input sections with different alignments. Write a linker script that places them in a declared order and a Python oracle that computes output offsets and symbol addresses.
Test requirements: Test reordered inputs, a zero-size section, and a large alignment gap. Compare the map, ELF section headers, and symbol addresses. Keep file offsets separate from VMAs.
Show solution
Align the current allocation address before placing each contribution and account for output-section rules. Empty sections and explicit address assignments can affect interpretation. ELF file layout has additional constraints, so virtual-address agreement alone does not predict every file offset.
-
Problem 5: Create and diagnose an orphan section
Add a custom allocated section not named by an explicit linker script. Instrument or trace ld's orphan placement logic and write a driver that compares the resulting map with an explicitly placed variant.
Test requirements: Vary the section's write and execute flags. Explain the actual placement decisions without assuming declaration order alone determines the result.
Show solution
An unmentioned section is an orphan, not automatically discarded. Placement considers section properties and emulation behavior. Naming it explicitly in the script removes that placement uncertainty and gives the test a controlled comparison.
-
Problem 6: Test a constrained memory layout
Write a script with a small executable memory region and a separate data region. Generate text and data fixtures just below, at, and above their limits. Read allocation and region-overflow diagnostics.
Test requirements: Automate success and failure checks. Verify the region receiving each section and distinguish region overflow from relocation overflow. Include alignment that consumes the final available bytes.
Show solution
Region capacity includes placement and alignment effects, not just summed payload sizes. A region overflow is independent of a relocation field's numeric range. Inspect addresses in successful cases and the specific allocation failure in unsuccessful cases.
-
Problem 7: Prove a linker test detects the bug
Select one earlier allocation or resolution problem and add a focused ld regression. Apply a temporary one-line fault to the relevant decision in a disposable source tree.
Test requirements: Record unmodified pass, faulty failure, and restored pass. Include a control case that exercises a neighboring rule without needing the changed decision.
Show solution
The regression must observe the semantic consequence, such as selected definition, retained section, or allocated address. A test that only checks ld exited zero cannot detect many wrong-success results. Keep the intentional fault separate from the test patch.
ld/emulparams · ld/emultempl · ld/scripttempl
How ld builds and selects emulations
An emulation is a profile that GNU ld uses to link for a platform. It supplies the default output format, architecture, linker scripts and library search paths. A hook is a C function that can change what ld does at a specific point in the link. The build creates a table of these functions for each emulation. See the hook API reference for declarations, call sites and defaults.
From the command line
ld -V lists the emulations of this ld. On x86-64 GNU/Linux, gcc passes -m elf_x86_64 to ld, or -m elf_i386 with gcc -m32, through the LINK_SPEC in GCC's config/i386/gnu-user64.h. ld --verbose prints the default script for the options given. ld --help ends with the options that each emulation adds, such as -z ibt.
Which emulation runs: the first source that names one wins
-m NAMEoverLDEMULATIONovertarg_emul from ld/configure.tgtget_emulation (ldmain.c:1174) reads the environment, then scans the arguments for -m. main calls it before parse_args (ldmain.c:792–799), because parse_args asks the emulation for its extra options. The MIPS options -mips1 to -mips32r2 look like -m but are skipped (:1198).
--enable-targets=all builds every emulation.Building the aarch64elf emulation
configureselectsaarch64elfas the default foraarch64-none-elf. The Makefile includes its object inEMULATION_OFILES. ld/configure.tgt- The Makefile calls
genscripts.shforeaarch64elf.c. The generator reads the emulation parameters and runself.scwith different shell variables for each script variant. ld/Makefile.am · ld/emulparams/aarch64elf.sh elf.emreads the AArch64 C template. The override below selects the function forbefore_allocation. Thenemulation.ememits the table initializer. ld/emultempl/elf.em · ld/emultempl/emulation.em
LDEMUL_BEFORE_ALLOCATION=aarch64_elf_before_allocation
Generator output
The script header shows the chosen BFD formats, architecture and entry symbol. The C initializers show which functions the two ELF emulations use.
OUTPUT_FORMAT("elf64-littleaarch64", "elf64-bigaarch64", "elf64-littleaarch64")
OUTPUT_ARCH(aarch64)
ENTRY(_start)
Generated hook table · eaarch64elf.c
struct ld_emulation_xfer_struct ld_aarch64elf_emulation =
{
gldaarch64elf_before_parse,
syslib_default,
hll_default,
ldelf_after_parse,
gldaarch64elf_before_plugin_all_symbols_read,
gldaarch64elf_after_open,
after_check_relocs_default,
ldelf_before_place_orphans,
gldaarch64elf_after_allocation,
ldelf_set_output_arch,
ldemul_default_target,
aarch64_elf_before_allocation,
gldaarch64elf_get_script,
"aarch64elf",
"elf64-littleaarch64",
gldaarch64elf_finish,
aarch64_elf_create_output_section_statements,
ldelf_open_dynamic_archive,
ldelf_place_orphan,
NULL,
NULL,
gldaarch64elf_add_options,
gldaarch64elf_handle_option,
NULL,
gldaarch64elf_list_options,
ldelf_load_symbols,
NULL,
NULL,
NULL,
ldelf_emit_ctf_early,
ldelf_acquire_strings_for_ctf,
ldelf_new_dynsym_for_ctf,
NULL,
NULL
};
Generated hook table · eelf_x86_64.c
struct ld_emulation_xfer_struct ld_elf_x86_64_emulation =
{
elf_x86_64_glibc_before_parse,
syslib_default,
hll_default,
ldelf_after_parse,
gldelf_x86_64_before_plugin_all_symbols_read,
gldelf_x86_64_after_open,
after_check_relocs_default,
ldelf_before_place_orphans,
gldelf_x86_64_after_allocation,
ldelf_set_output_arch,
ldemul_default_target,
elf_x86_64_before_allocation,
gldelf_x86_64_get_script,
"elf_x86_64",
"elf64-x86-64",
ldelf_finish,
elf_x86_create_output_section_statements,
ldelf_open_dynamic_archive,
ldelf_place_orphan,
NULL,
NULL,
gldelf_x86_64_add_options,
gldelf_x86_64_handle_option,
NULL,
gldelf_x86_64_list_options,
ldelf_load_symbols,
NULL,
NULL,
NULL,
ldelf_emit_ctf_early,
ldelf_acquire_strings_for_ctf,
ldelf_new_dynsym_for_ctf,
NULL,
NULL
};
The build compiles each generated C file and links its object into ld. The Makefile also creates ldemul-list.h from EMULATION_OFILES. At runtime, ldemul_choose_mode searches the resulting table by name. ld/Makefile.am · ld/ldemul.c
| Variable in emulparams/elf_x86_64.sh | Value | Effect |
|---|---|---|
OUTPUT_FORMAT | "elf64-x86-64" | The BFD target name of the output. It becomes the OUTPUT_FORMAT line of every default script. |
ARCH | "i386:x86-64" | The BFD architecture. It becomes OUTPUT_ARCH. |
TEXT_START_ADDR | 0x400000 | The start of a non-PIE executable. A PIE and a shared library use SHLIB_TEXT_START_ADDR, which defaults to 0 (elf.sc:356). |
MAXPAGESIZE | "CONSTANT (MAXPAGESIZE)" | Segment alignment, read from the BFD backend when the script runs. -z max-page-size= changes it. |
SCRIPT_NAME | elf | The script template: scripttempl/elf.sc. |
TEMPLATE_NAME | elf | The C template that fills the hooks: emultempl/elf.em. |
EXTRA_EM_FILE | "elf-x86-64-glibc" | More C code for this emulation only: emultempl/elf-x86-64-glibc.em. |
GENERATE_SHLIB_SCRIPT · GENERATE_PIE_SCRIPT | yes | Also write the -shared and -pie variants of the script. |
source_sh …/cet.sh and others | Shared fragments that add options and their help text, such as -z ibt, -z shstk and -z pack-relative-relocs. |
| Script file | Link mode |
|---|---|
ldscripts/elf_x86_64.x | an executable, no special options |
.xr · .xu | -r · -Ur: a relocatable output, another .o file |
.xn · .xbn | -n: sections not page-aligned · -N: text writable, data not page-aligned |
.xc · .xce | -z combreloc, and with -z separate-code |
.xw | -z combreloc -z relro -z now |
.xs* · .xd* | the same set again for -shared and for -pie |
get_script hook picks one file from the link options. The first line of the script that ld --verbose prints names the variant, for example /* Script for -z combreloc -z separate-code */. For the default emulation, and for the emulations that the configure stanza lists in targ_extra_libpath, the scripts are compiled into ld as strings. The other emulations read them from the installed ldscripts directory (genscripts.sh:760).| Hook | ELF function | When ld calls it | What it does |
|---|---|---|---|
add_options · handle_option | gld*_add_options · gld*_handle_option | while ld parses its options | Register and handle ELF options, such as the -z keywords. |
get_script | gld*_get_script | after the options, if ld still needs a default script | Returns the default script for this link mode. |
open_dynamic_archive | ldelf_open_dynamic_archive | for each -lNAME in each search directory, unless -Bstatic is in effect | Tries libNAME.so before ld tries libNAME.a (ldfile.c:573). |
after_open | gld*_after_open | after all inputs are open | Calls ldelf_after_open to find the libraries that DT_NEEDED entries name. |
place_orphan | ldelf_place_orphan | when an input section matches no script rule | Chooses an output section by name and flags. |
before_allocation | gld*_before_allocation or a target override | after section mapping and orphan placement, before the main allocation pass | Prepares TLS alignment and dynamic section sizes, then calls the default hook to remove excluded output sections. |
an emulation
A target profile chosen at run time with -m, as above.
em= in gas/configure.tgt
The comment calls it "emulation", but it selects a target-environment header, te-*.h, when gas is configured (configure.tgt:30).
as --em=NAME
A run-time choice that only MIPS and CRIS builds of gas offer, for example between big-endian and little-endian ELF (configure.ac:715). AS_EMULATION sets the default.
none
BFD has no emulations. It has target vectors, and objdump -b or objcopy -O names one.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Separate format and policy
Why is an ELF BFD vector insufficient to define a platform's entire linker behavior?
Show answer
The vector supplies format operations. Emulation code and scripts supply additional platform and layout conventions.
-
Question 2: Explain installed variants
Why should a command example check supported emulations before assuming an emulation name exists?
Show answer
Configuration controls which emulations the installed linker includes. A name present in the source tree can be absent from that build.
-
Question 3: Diagnose a default mismatch
A linker recognizes an object but chooses the wrong default layout. Which areas need comparison?
Show answer
Compare the selected emulation, its parameter files, and its default script. Format recognition alone does not select every platform policy.
-
Problem 1: Reproduce a generated default script
Trace one native ELF emulation from configure.tgt through its parameter file, script template, and genscripts.sh. Write a driver that saves the generated default script and the script printed by the built linker.
Test requirements: Compare their semantic section rules under the same link mode. Explain embedded-script wrappers or comments that prevent naive whole-output equality.
Show solution
genscripts combines parameters and templates into variants. The linker can embed selected scripts in generated C. Separate the script text from ld's version and support output before comparing it with generated files.
-
Problem 2: Explain mode-specific script differences
Generate relocatable, executable, and shared outputs from one compatible assembly fixture. Write a report that pairs each link mode with the selected generated script and output ELF type.
Test requirements: Identify three concrete rule differences using source conditions. Verify the output types and section addresses rather than merely comparing script filenames.
Show solution
Modes change available address assumptions, section organization, and metadata requirements. Follow the conditions setting the script variant. A REL, EXEC, or DYN header checks the result more directly than an inferred name alone.
-
Problem 3: Replace defaults with a minimal script
Write an explicit script that defines entry, text, data, and a custom section. Link a two-object program both with that script and with the emulation default. Build a Python layout comparator.
Test requirements: Check every allocated input section's destination, entry address, and alignment. Include an unmentioned section to reveal orphan behavior in the minimal script.
Show solution
A short custom script replaces many default placement rules but does not make unspecified sections disappear. State the intended layout precisely and compare actual headers and symbols. Explain orphan sections through ld and emulation behavior.
-
Problem 4: Follow an emulation hook across phases
Choose one hook used by the native ELF emulation. Add temporary tracing that records when it runs relative to input loading, allocation, and final writing. Write a fixture that exercises its purpose.
Test requirements: Record the callback's caller, relevant state before and after, and an output property it controls. Demonstrate that the trace itself does not alter that property.
Show solution
Use generated emulation code and its template together to identify the hook implementation and installation. A function's name does not establish timing. The caller establishes which state is valid when the hook runs.
-
Problem 5: Change a default without changing the script
In a disposable source tree, alter one native emulation parameter that changes a default layout address. Regenerate and rebuild. Write a checker for the affected output addresses and unaffected symbol relationships.
Test requirements: Compare an ordinary link, the modified-default link, and an explicitly scripted link. Show which invocation bypasses the modified default.
Show solution
The parameter feeds generated defaults. An explicit script can supply its own addresses and avoid that changed default. Verify the actual generated script before attributing an output difference to the parameter.
-
Problem 6: Detect a stale generated emulation
Make a controlled parameter change and write a dependency audit that determines which generated script and C files need updating. Compare a fresh build with an intentionally stale build in separate directories.
Test requirements: Produce a test that fails when source parameters and reported default behavior disagree. Restore the generated dependency before accepting the change.
Show solution
A source edit alone does not prove the running ld contains it. Trace the Makefile rule, inspect generated contents, and run the rebuilt executable by explicit path. A stale binary can otherwise make a correct parameter patch look ineffective.
-
Problem 7: Make script selection observable in a regression
Select two link modes that choose distinct script variants. Write a target-appropriate ld test whose section addresses or flags distinguish those variants. Read the selection hook before choosing expectations.
Test requirements: Show that forcing the wrong variant in a disposable build makes the test fail. Retain one default-mode control and avoid matching comments as the only assertion.
Show solution
Tests should constrain the layout consequence of selection. A filename or printed banner can be right while the selected rules are wrong. Use a small fixture that makes the variants' relevant difference unavoidable.
GNU ld 2.46 · internal API
Linker emulation hook API
Each row gives the C declaration, a call site, and the dispatch function. The LDEMUL_* shell variable selects the function that emulation.em writes into the generated table.
The default column shows what the base template emits when the variable is unset. A template such as elf.em can supply its own functions. The dispatch functions handle absent optional hooks.
Compare the generated AArch64 and x86-64 tables for actual bindings. See the ld chapter for the link phases.
Setup, options and scripts
| Hook | Contract | Template override and default |
|---|---|---|
choose_targetld/ldemul.h:156 |
char * (*choose_target) (int, char**);Return the initial BFD target name before parsing options. The default reads GNUTARGET, then uses the emulation’s target_name. ldmain.c · Dispatch |
LDEMUL_CHOOSE_TARGETldemul_default_target |
before_parseld/ldemul.h:126 |
void (*before_parse) (void);Set emulation defaults before ld parses the command line or a linker script. ldmain.c · Dispatch |
LDEMUL_BEFORE_PARSEgld${EMULATION_NAME}_before_parse |
add_optionsld/ldemul.h:199 |
void (*add_options) (int, char **, int, struct option **, int, struct option **);Extend the three getopt option lists through the pointer arguments. Each count gives the current length of its list. lexsup.c · Dispatch |
LDEMUL_ADD_OPTIONSNULL · skip |
parse_argsld/ldemul.h:195 |
bool (*parse_args) (int, char **);Try to consume the next argument before the common parser. Advance the argument index and return true if the hook consumes it. lexsup.c · Dispatch |
LDEMUL_PARSE_ARGSNULL · return false |
handle_optionld/ldemul.h:204 |
bool (*handle_option) (int);Receive the option code from getopt. Return true to skip the common option handler. lexsup.c · Dispatch |
LDEMUL_HANDLE_OPTIONNULL · return false |
list_optionsld/ldemul.h:212 |
void (*list_options) (FILE *);Print this emulation’s options to the supplied stream. The help dispatcher visits every built-in emulation. lexsup.c · Dispatch |
LDEMUL_LIST_OPTIONSNULL · skip this emulation |
hllld/ldemul.h:132 |
void (*hll) (char *);Handle an HLL script directive. The parser can pass NULL. The default reports that ld ignores the directive. ldgram.y · Dispatch |
LDEMUL_HLLhll_default |
syslibld/ldemul.h:129 |
void (*syslib) (char *);Handle the library name in a SYSLIB script directive. The default reports that ld ignores the directive. ldgram.y · Dispatch |
LDEMUL_SYSLIBsyslib_default |
new_vers_patternld/ldemul.h:228 |
struct bfd_elf_version_expr * (*new_vers_pattern) (struct bfd_elf_version_expr *);Return the version pattern to register. PowerPC64 ELF uses this hook to add dotted names. ldlang.c · Dispatch |
LDEMUL_NEW_VERS_PATTERNNULL · return the input pattern |
set_symbolsld/ldemul.h:191 |
void (*set_symbols) (void);Initialize symbols after command-line parsing and before ld reads a default script. An explicit script can already be parsed. ldmain.c · Dispatch |
LDEMUL_SET_SYMBOLSNULL · skip |
get_scriptld/ldemul.h:162 |
char * (*get_script) (int *isfile);Return the default script for the current link mode. Set *isfile to 1 for a filename or 0 for script text. ldmain.c · Dispatch |
LDEMUL_GET_SCRIPTgld${EMULATION_NAME}_get_script |
after_parseld/ldemul.h:135 |
void (*after_parse) (void);Adjust link settings after ld parses the command line and scripts. The default sets page sizes and can add an undefined entry symbol. ldmain.c · Dispatch |
LDEMUL_AFTER_PARSEafter_parse_default |
Output setup and input files
| Hook | Contract | Template override and default |
|---|---|---|
set_output_archld/ldemul.h:153 |
void (*set_output_arch) (void);Set the BFD architecture and machine on the output file. ldlang.c · Dispatch |
LDEMUL_SET_OUTPUT_ARCHset_output_arch_default |
create_output_section_statementsld/ldemul.h:174 |
void (*create_output_section_statements) (void);Create target-specific output sections after ld opens the output BFD and before it opens inputs. ldlang.c · Dispatch |
LDEMUL_CREATE_OUTPUT_SECTION_STATEMENTSNULL · skip |
open_dynamic_archiveld/ldemul.h:179 |
bool (*open_dynamic_archive) (const char *arch, struct search_dirs *, struct lang_input_statement_struct *entry);Try a shared-library candidate in this search directory. Return true if the hook opens it. ELF tries libNAME.so before the archive. ldfile.c · Dispatch |
LDEMUL_OPEN_DYNAMIC_ARCHIVENULL · return false |
find_potential_librariesld/ldemul.h:223 |
int (*find_potential_libraries) (char *, struct lang_input_statement_struct *);Try another library naming rule after the regular search fails for this architecture suffix. Return nonzero if the hook finds a library. ldfile.c · Dispatch |
LDEMUL_FIND_POTENTIAL_LIBRARIESNULL · return 0 |
unrecognized_fileld/ldemul.h:208 |
bool (*unrecognized_file) (struct lang_input_statement_struct *);Try to handle an input that BFD did not recognize as an object or archive. Return true if the hook handles it. ldlang.c · Dispatch |
LDEMUL_UNRECOGNIZED_FILENULL · return false |
recognized_fileld/ldemul.h:216 |
bool (*recognized_file) (struct lang_input_statement_struct *);Handle a recognized input specially. Return true if the hook takes over the normal symbol-loading path. ldlang.c · Dispatch |
LDEMUL_RECOGNIZED_FILENULL · return false |
before_plugin_all_symbols_readld/ldemul.h:138 |
void (*before_plugin_all_symbols_read) (void);Run before the plugin receives its all-symbols-read notification. ldlang.c · Dispatch |
LDEMUL_BEFORE_PLUGIN_ALL_SYMBOLS_READNULL · skip |
after_openld/ldemul.h:141 |
void (*after_open) (void);Run after ld opens the inputs and loads their symbols. The ELF hook can locate libraries named by DT_NEEDED. ldlang.c · Dispatch |
LDEMUL_AFTER_OPENafter_open_default |
Relocations, layout and entry point
| Hook | Contract | Template override and default |
|---|---|---|
after_check_relocsld/ldemul.h:144 |
void (*after_check_relocs) (void);Run after ld checks relocations and before it maps input sections to output sections. ldlang.c · Dispatch |
LDEMUL_AFTER_CHECK_RELOCSafter_check_relocs_default |
before_place_orphansld/ldemul.h:147 |
void (*before_place_orphans) (void);Prepare to place input sections that no script rule assigned. Script-based section mapping already ran. ldlang.c · Dispatch |
LDEMUL_BEFORE_PLACE_ORPHANSbefore_place_orphans_default |
place_orphanld/ldemul.h:186 |
lang_output_section_statement_type *(*place_orphan) (asection *, const char *, int);Place an orphan and return its output section statement. Return NULL to request common placement. ldlang.c · Dispatch |
LDEMUL_PLACE_ORPHANNULL · return NULL |
before_allocationld/ldemul.h:159 |
void (*before_allocation) (void);Prepare output sections before ld sizes them. ELF uses this stage to size dynamic sections. ldlang.c · Dispatch |
LDEMUL_BEFORE_ALLOCATIONbefore_allocation_default |
after_allocationld/ldemul.h:150 |
void (*after_allocation) (void);Adjust output sections after the first sizing pass. The default runs section relaxation. ldlang.c · Dispatch |
LDEMUL_AFTER_ALLOCATIONafter_allocation_default |
finishld/ldemul.h:171 |
void (*finish) (void);Run after final script assignments. The default frees per-section data and fixes symbols in excluded sections for non-relocatable links. ldlang.c · Dispatch |
LDEMUL_FINISHfinish_default |
find_alt_start_symbolld/ldemul.h:265 |
struct bfd_link_hash_entry * (*find_alt_start_symbol) (struct bfd_sym_chain *entry);Try another spelling of the entry symbol after a direct lookup fails. Return a hash entry or NULL. ldlang.c · Dispatch |
LDEMUL_FIND_START_SYMBOLNULL · return NULL |
Map output and CTF debug information
| Hook | Contract | Template override and default |
|---|---|---|
extra_map_file_textld/ldemul.h:233 |
void (*extra_map_file_text) (bfd *, struct bfd_link_info *, FILE *);Write emulation-specific text to the link map stream. ldlang.c · Dispatch |
LDEMUL_EXTRA_MAP_FILE_TEXTNULL · skip |
print_symbolld/ldemul.h:260 |
bool (*print_symbol) (struct bfd_link_hash_entry *hash_entry, void *ptr);Print a symbol in the link map. The caller ignores the return value. The default calls print_one_symbol. ldlang.c · Dispatch |
LDEMUL_PRINT_SYMBOLNULL · call print_one_symbol |
emit_ctf_earlyld/ldemul.h:238 |
int (*emit_ctf_early) (void);Return nonzero for early CTF output. Return 0 to defer until the target supplies late symbol and string-table data. ldlang.c · Dispatch |
LDEMUL_EMIT_CTF_EARLYNULL · return 1 |
acquire_strings_for_ctfld/ldemul.h:247 |
void (*acquire_strings_for_ctf) (struct ctf_dict *, struct elf_strtab_hash *);Pass the final dynamic string table to the CTF dictionary when the target provides it. ldlang.c · Dispatch |
LDEMUL_ACQUIRE_STRINGS_FOR_CTFNULL · skip |
new_dynsym_for_ctfld/ldemul.h:256 |
void (*new_dynsym_for_ctf) (struct ctf_dict *, int, struct elf_internal_sym *);Pass a dynamic symbol and its index to the CTF dictionary. A NULL symbol ends the sequence. ldlang.c · Dispatch |
LDEMUL_NEW_DYNSYM_FOR_CTFNULL · skip |
Regenerating this reference
Run the generator from the Systems Reference repository. Give it the path to a local Binutils checkout that contains the binutils-2_46 tag.
python3 scripts/binutils-emulations.py /path/to/binutils
python3 scripts/binutils-emulations.py --check /path/to/binutils
binutils/
Most tools are a few thousand lines of option parsing over BFD
Link lines from binutils/Makefile.am. The default is LDADD = $(BFDLIB) $(LIBIBERTY) $(LIBINTL) (line 254).
From the command line
objdump -h and readelf -S print the same section table through two different parsers. When the two disagree, compare with readelf, which reads the bytes directly.
| Tool | BFD | opcodes | What to know |
|---|---|---|---|
ar · ranlib | ● yes | — | Archive code is in bfd/archive.c. --enable-deterministic-archives makes D the default. Also parses MRI scripts (arparse.y). |
nm | ● yes | — | Symbol letters come from bfd_decode_symclass. Loads the LTO plugin to list IR symbols. |
objdump | ● yes | ● yes | Also links libctf and libsframe. Shares dwarf.c with readelf for -W output. |
objcopy · strip | ● yes | — | One program, two names. Copies through the canonical view plus bfd_copy_private_* hooks. Sets the PE header timestamp: the input's with --preserve-dates, the current time otherwise (objcopy.c:2858–2861).
|
readelf | ▲ no | — | Own ELF parser. Links libctf-nobfd, libsframe, zlib, zstd and debuginfod. The reference when BFD output looks wrong. |
addr2line | ● yes | — | Calls bfd_find_nearest_line, which reads .debug_line in bfd/dwarf2.c. |
size · strings | ● yes | — | strings scans the whole file by default. It opens a BFD only for -d, to read data sections. |
c++filt | links only | — | The demangler is libiberty's cp-demangle.c, shared with gcc and gdb. |
elfedit | ▲ no | — | Rewrites e_machine, e_type, OSABI and x86 feature bits in place. |
dlltool · windres | ● yes | — | PE only: import libraries from .def files, and resource compilation. |
gprof · gprofng | ● yes | gprofng | Profilers. gprofng has its own collector library and depends on bfd, opcodes and gas. |
Drill down
Each tool is a short path from main to a BFD or dwarf.c call.
objdump10
- main()binutils/objdump.c:6006Parse options and call display_file for each input.
- display_any_bfd()binutils/objdump.c:5930Recurse into archive members.
- dump_bfd()binutils/objdump.c:5690Run each requested dump in a fixed order.
- dump_headers()binutils/objdump.c:979-h: the section table.
- dump_symbols()binutils/objdump.c:5218-t and -T.
- disassemble_data()binutils/objdump.c:4140-d: sort symbols and disassemble each code section.
- disassemble_bytes()binutils/objdump.c:3265The per-instruction loop, with relocations and line numbers inline.
- show_line()binutils/objdump.c:2187-l and -S: line information through bfd_find_nearest_line.
- dump_relocs()binutils/objdump.c:5561-r and -R.
- dump_dwarf()binutils/objdump.c:4522-W: hand the sections to dwarf.c.
objcopy and strip8
- copy_main()binutils/objcopy.c:5352Parse objcopy options.
- strip_main()binutils/objcopy.c:4906Parse strip options; the same copy path follows.
- copy_file()binutils/objcopy.c:3868Open the input, handle archives, create the output.
- copy_object()binutils/objcopy.c:2673Copy one object: headers, sections, symbols, relocations.
- setup_section()binutils/objcopy.c:4186Create the output section and copy its private data.
- filter_symbols()binutils/objcopy.c:1557Apply --strip-*, --keep-*, --localize-* and renames.
- copy_relocations_in_section()binutils/objcopy.c:4515Copy relocations, dropping those against stripped symbols.
- copy_section()binutils/objcopy.c:4608Copy section bytes.
readelf10
- process_file()binutils/readelf.c:25318Open the file and dispatch for objects and archives.
- process_object()binutils/readelf.c:24879Run each requested display in order.
- get_file_header()binutils/readelf.c:24652Read and validate the ELF header without BFD.
- process_section_headers()binutils/readelf.c:8573-S.
- process_program_headers()binutils/readelf.c:7475-l.
- process_dynamic_section()binutils/readelf.c:12883-d.
- process_relocs()binutils/readelf.c:10001-r.
- process_symbol_table()binutils/readelf.c:15300-s.
- process_version_sections()binutils/readelf.c:13690-V.
- process_notes()binutils/readelf.c:24528-n.
nm, ar, addr2line6
- display_rel_file()binutils/nm.c:1409Read, filter, sort and print the symbols of one object.
- replace_members()binutils/ar.c:1472ar r: insert or replace members, then write the archive.
- write_archive()binutils/ar.c:1245Write the new archive through BFD and rename it into place.
- translate_addresses()binutils/addr2line.c:287For each address, find the section and the source line.
- _bfd_dwarf2_find_nearest_line()bfd/dwarf2.c:5745Search .debug_info and .debug_line for an address.
- decode_line_info()bfd/dwarf2.c:2710Run the line-number program into a sorted table.
dwarf.c, shared by objdump and readelf4
- display_debug_info()binutils/dwarf.c:7756Dump .debug_info.
- process_debug_info()binutils/dwarf.c:3836Walk compilation units and their DIEs.
- read_and_display_attr()binutils/dwarf.c:3553Decode one attribute in its form.
- display_debug_lines()binutils/dwarf.c:6003Dump .debug_line, raw or decoded.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Trace copying
Find
copy_objectin the linked source. Why does copying need more than duplicating section bytes?Show answer
Symbols, relocations, section relationships, and format-specific metadata can refer to those sections and require consistent updates.
-
Question 2: Interpret stripping
Why should stripping operate on a disposable copy during an exercise?
Show answer
Stripping can remove information needed for debugging or later linking. A separate output keeps the original available for comparison.
-
Question 3: Route address lookup
Does addr2line recover a source line from raw machine instructions alone?
Show answer
No. It needs applicable debug information and the correct address context. Instruction bytes do not contain source filenames and line tables by themselves.
-
Problem 1: Build a semantic copy checker
Generate an ELF object with local and global symbols, a relocation, and two allocated sections. Write a Python report that compares the input with an objcopy copy. Read section, symbol, and relocation remapping.
Test requirements: Compare section contents, symbol-to-section associations, addends, and relocation targets. Reorder section definitions in a second fixture so raw index equality cannot serve as the oracle.
Show solution
Compare relationships through normalized section and symbol identities. A correct copy can use different numeric indices while preserving meaning. Bytes alone cannot detect a relocation that points to the wrong copied symbol.
-
Problem 2: Prove a symbol rewrite stays consistent
Assemble a caller and a definition in separate objects. Use objcopy's documented symbol-redefinition facility to rename the reference and definition. Write tests for both-sided and one-sided rewriting.
Test requirements: Inspect relocation symbol names before linking. Verify both-sided rewriting links and reaches the intended target, while one-sided rewriting preserves an unresolved reference.
Show solution
A consistent rewrite must update the symbol identity used by relocations, not merely a displayed name string. Check actual link behavior and encoded target. One-sided rewriting is a negative control for missing propagation.
-
Problem 3: Implement an archive index verifier
Create an archive containing duplicate symbol names in different members and one member with no globals. Write a Python reader for the archive index variant your GNU ar emits. Read BFD's matching archive parser.
Test requirements: Compare index names and member offsets with nm and ar output. Test truncation and an index offset that points outside the archive. Explicitly reject index formats you do not support.
Show solution
Archive indexes associate names with member file offsets, not ELF symbol values. Preserve duplicate names rather than collapsing them into one map entry. Validate each offset against archive member boundaries and the file size.
-
Problem 4: Create a separate-debug-file workflow
Compile a tiny program with debug information. Write a driver that creates a separate debug file, strips the runtime copy, and adds a debuglink using documented objcopy operations. Trace the implementation.
Test requirements: Verify runtime allocated-section bytes remain equivalent. Check the debuglink filename and CRC independently. Change one debug-file byte and prove the CRC check detects it.
Show solution
Debug separation moves debugging data without promising byte-identical ELF containers. The debuglink stores a filename and checksum, not the debug content. Compare appropriate sections and validate the checksum over the separate file bytes.
-
Problem 5: Audit stripping against later linking
Generate a relocatable object with local symbols needed by relocations and extra debugging symbols. Compare debug-only stripping with full stripping on disposable copies. Read symbol-retention decisions in objcopy.
Test requirements: Attempt a later relocatable and final link where meaningful. Record rejected operations as well as successful outputs. Explain why one stripping operation can be unsafe for linkable input.
Show solution
Relocations can require symbol-table entries. Removing debug information is different from discarding the whole symbol table. A tool may preserve required symbols or reject the request. Do not claim that an output file's existence establishes later-link equivalence.
-
Problem 6: Test deterministic archive production
Write a driver that builds the same archive from unchanged object contents after varying member timestamps and filesystem ownership where permitted. Read ar's deterministic-mode handling and the archive writer.
Test requirements: Compare deterministic and timestamp-preserving modes using documented ar modifiers. Record configuration defaults. Separate archive-header differences from member payload differences.
Show solution
Deterministic mode normalizes selected archive metadata. The result still depends on member order and contents. A default deterministic build needs an explicit contrasting mode before the experiment can show timestamp sensitivity.
-
Problem 7: Cross-check source-line lookup
Compile a small two-function program with debug information and a fixed optimization setting. Write a driver that chooses instruction addresses and compares addr2line output with decoded line-table ranges. Read the lookup path.
Test requirements: Include an address inside a function, a boundary address, an address with no line entry, and the stripped copy. Distinguish unknown information from a command failure.
Show solution
Line-table rows describe address ranges, not a guaranteed distinct line for every instruction. End-sequence boundaries and absent debug data affect lookup. Use the selected debug representation as evidence and preserve unknown results explicitly.
Data structures
Twenty structures carry almost all of the state
Read these definitions before the functions that fill them. bfd-in2.h is generated from the doc comments in bfd/*.c, so a change goes into the .c file and make headers.
From the command line
No option prints these structures. A debugger does: gdb --args ld … with a breakpoint on bfd_check_format_matches stops each time ld asks BFD to identify a file.
BFD7
- struct bfdbfd/bfd-in2.h:1947One open file: name, target vector, format, sections, tdata.
- struct bfd_targetbfd/bfd-in2.h:7418The vector: flavour, byte orders, and the jump tables.
- struct bfd_sectionbfd/bfd-in2.h:435asection: name, flags, vma, lma, size, output_section, output_offset.
- struct bfd_symbolbfd/bfd-in2.h:1060asymbol: name, value, flags, section.
- struct reloc_cache_entrybfd/bfd-in2.h:3102arelent: symbol pointer, address, addend, howto.
- struct bfd_link_hash_entryinclude/bfdlink.h:101A global symbol during a link: type, value, section.
- struct bfd_link_infoinclude/bfdlink.h:340Every linker setting BFD sees: output type, options, hash table.
ELF4
- struct elf_backend_databfd/elf-bfd.h:1008The ELF backend vector of hooks and constants.
- struct elf_link_hash_entrybfd/elf-bfd.h:132The ELF form of a link symbol: dynindx, GOT and PLT refcounts, version.
- struct elf_obj_tdatabfd/elf-bfd.h:2128Per-file ELF data: headers, symbol tables, segment map.
- struct elf_internal_shdrinclude/elf/internal.h:102A section header in host form.
gas, ld, opcodes6
- struct fraggas/frags.h:38Fixed bytes plus an optional variable part.
- struct fixgas/write.h:47One fixup: frag, offset, symbols, addend, reloc type.
- struct lang_input_statement_structld/ldlang.h:303One input file in the statement tree.
- struct lang_output_section_statement_structld/ldlang.h:141One output section and its children.
- struct disassemble_infoinclude/dis-asm.h:137The callback table opcodes uses to read bytes and print text.
- struct aarch64_opcodeinclude/opcode/aarch64.h:1381One AArch64 table entry: opcode, mask, class, operands.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Separate input and global symbols
Why does the linker need
bfd_link_hash_entryas well asasymbol?Show answer
It needs a shared resolution state across inputs, beyond the representation of an individual file's symbol.
-
Question 2: Locate linker statements
Why does ld need input and output-section statement structures in addition to BFD sections?
Show answer
ld represents linker-script and input-order decisions. Those statements organize how BFD input sections contribute to output sections.
-
Question 3: Choose a debugger object
At a format-recognition breakpoint, which object is the best starting point for inspecting the current target vector?
Show answer
Inspect the current BFD handle and its xvec. A global link hash entry describes symbol resolution, not format selection.
-
Problem 1: Capture a file's state transitions
Add a diagnostic snapshot helper for a BFD handle in a disposable build. Record selected fields before recognition, after recognition, after symbol loading, and before close. Read initialization and cleanup.
Test requirements: Run the helper on an object, an archive, and an invalid file. Mark fields as unavailable when the handle's current state does not justify reading them.
Show solution
Format-specific state is not valid merely because memory exists for the handle. Recognition installs relevant target and private data. Snapshot only established state and avoid accessing a handle after close. Archive and object paths do not share every valid field.
-
Problem 2: Track one symbol across representations
Create a global symbol referenced from a second object. Instrument its input asymbol, global link hash entry, and ELF-specific link entry during linking. Write a script that joins the snapshots by semantic identity.
Test requirements: Repeat with a weak definition superseded by a strong definition. Record the chosen input, section, value, and output address without using pointer equality across runs.
Show solution
One input symbol and the link-wide resolution entry serve different purposes. The selected definition can change while the logical global name persists. ELF-specific state extends the common link entry instead of replacing its resolution role.
-
Problem 3: Implement a relocation-relationship validator
Write a C inspector that checks each canonical relocation's owning section, offset range, referenced symbol, and howto. Read reloc_cache_entry and the target howto definitions.
Test requirements: Generate valid call and data relocations, an empty section, and a malformed relocation offset. Report unsupported field checks rather than assuming every relocation has one contiguous writable field.
Show solution
The howto describes relocation semantics and encoding details, but not every relocation is a simple byte slice. Check structural ownership first. Perform field-size checks only for supported shapes and explain markers or special handlers separately.
-
Problem 4: Distinguish VMA, LMA, and file position
Write a linker script with code in one region and initialized data whose runtime and load addresses differ. Implement a report using BFD fields and ELF headers. Read the section structures.
Test requirements: Check symbol addresses, section VMA and LMA, segment mapping, and file offsets. Add a NOBITS section and prove it does not consume its declared size as file payload.
Show solution
VMA describes runtime addressing, LMA describes the load image, and file position locates stored bytes. They are different coordinate systems. Derive load mapping from the selected ELF segment rules rather than equating an ELF section header with every BFD field.
-
Problem 5: Observe fragment and fixup ownership
Instrument gas so each fixup report includes its fragment, section, fragment-relative offset, and final section offset. Write a fixture containing alignment, a relaxable jump, and an external reference.
Test requirements: Verify the reference's final relocation offset independently from section bytes. Record snapshots before and after relaxation and account for every offset change.
Show solution
A fixup's location is relative to its fragment until layout supplies the fragment address. Adding the settled fragment address gives the section-relative location. Relaxation can move the location without changing the fixup's fragment-relative offset.
-
Problem 6: Check linker statement invariants
Add a diagnostic traversal of input and output-section statements in a disposable ld build. Generate a script that merges several input sections and leaves one orphan.
Test requirements: Emit parent-child relationships and final output assignments. Assert each retained ordinary input section has a consistent output owner and that discarded sections are represented distinctly.
Show solution
Script statements encode placement intent while BFD sections hold section data and output associations. Traversal must distinguish statement kinds. Do not cast every node to an input-section statement or assume discarded sections have usable output addresses.
-
Problem 7: Turn a structure invariant into a regression
Choose a relationship observed above, such as a relocation's symbol owner or an input section's output assignment. Implement a diagnostic assertion in a local debug build and a fixture that exercises it.
Test requirements: Introduce one controlled relationship error only in the disposable build. Show the assertion detects it before an unrelated later crash. Keep the normal fixture valid and identify the owning writer.
Show solution
Place the check after the relationship becomes valid and before consumers rely on it. An assertion before initialization produces false failures. The useful invariant connects the writer's guarantee with the consumer's assumption, not merely a non-NULL pointer.
maintainer mode
Many checked-in files are outputs: edit the input and regenerate
A patch that edits a generated file without its source fails review, and the next regeneration reverts it.
From the command line
configure --enable-maintainer-mode adds the make rules that regenerate these files. Without it, make keeps the committed copies of files such as bfd/bfd-in2.h, even after their inputs change.
| Generated | Edit instead | How |
|---|---|---|
bfd/bfd-in2.h | bfd-in.h and doc comments in archive.c, reloc.c, section.c, syms.c, targets.c… | make headers in bfd/, which runs doc/chew |
bfd/libbfd.h · libcoff.h | libbfd-in.h, libcoff-in.h, coffcode.h | make headers |
enum bfd_reloc_code_real | ENUM / ENUMX / ENUMDOC stanzas in reloc.c | make headers (also refreshes libbfd.h names) |
elf32-*.c · elf64-*.c | elfnn-*.c | sed at build time, nothing committed |
targmatch.h | config.bfd | targmatch.sed at build time |
opcodes/i386-tbl.h · aarch64-*-2.c | i386-opc.tbl, aarch64-tbl.h | i386-gen, aarch64-gen, then commit the output |
CGEN *-desc.c … | cpu/*.cpu, cpu/*.opc | --enable-cgen-maint with a CGEN checkout |
configure · Makefile.in | configure.ac, Makefile.am, Makefile.def | The exact autoconf and automake versions the tree pins, and autogen Makefile.def at top level |
*/po/*.pot | source strings | Release managers regenerate them. Leave them out of a patch. |
move-if-change, so an unchanged regeneration does not rebuild the whole tree.Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Inspect maintainer rules
Search the linked Makefile for maintainer-related conditions. Why can changing an input leave a generated file unchanged in an ordinary build?
Show answer
Some regeneration rules depend on maintainer mode or explicit generation targets. An ordinary build can use the distributed generated copies.
-
Question 2: Plan a reproducible patch
What should a generated-file patch contain when project policy requires regenerated outputs?
Show answer
Include the authoritative input change and the corresponding generated outputs. Use the tool versions and generation procedure required by that project.
-
Question 3: Check a regeneration diff
Why should an unexpected large generated diff stop a small intended change?
Show answer
It can indicate mismatched generator versions or unrelated inputs. Check the cause before including unrelated output churn.
-
Problem 1: Trace one public declaration to its input
Select a public BFD declaration in bfd-in2.h. Write a script that identifies its authoritative input and regeneration rule. Make a parameter-name-only change in its generated declaration input in a disposable checkout.
Test requirements: Regenerate the header and prove the expected declaration region changes while unrelated regions remain stable under the same generator environment. Restore the input and verify reproducibility.
Show solution
Follow BFD_H_FILES and the header extraction recipe. The generated header can combine template material with extracted source declarations. Changing only the distributed header does not update those authoritative inputs.
-
Problem 2: Test relocation enum and name consistency
Write a checker that parses the relocation enum generation inputs and the resulting generated declarations or name table. Read ENUM, ENUMX, and ENUMDOC handling before defining the supported grammar.
Test requirements: Cover explicit enum values, aliases where present, and documentation-only stanzas. Demonstrate a deliberately deleted generated name is detected without confusing a comment with an entry.
Show solution
Enum order alone is not a safe numeric model when explicit values or special stanzas exist. Follow the generator's actual expansion rules. Compare only constructs your parser supports and reject unknown syntax explicitly.
-
Problem 3: Verify x86 table regeneration
Trace i386-opc.tbl through preprocessing and i386-gen to its generated headers. Write a driver that regenerates twice in an isolated build environment and hashes each output.
Test requirements: Verify identical inputs and tools produce identical outputs. Change one controlled table entry and identify all affected generated headers and one affected assembler or disassembler test.
Show solution
The recipe can generate multiple related headers in one invocation. Comparing only i386-tbl.h can miss a stale companion. Record preprocessing definitions and generator version because they are part of the effective input.
-
Problem 4: Detect a missing generation dependency
In a disposable tree, remove one dependency from a selected generation rule. Write a test that changes only that input and checks whether the output rebuilds. Read the complete rule before selecting the mutation.
Test requirements: Compare incremental and fresh builds. Restore the dependency and prove both builds agree. Keep generator invocations and output hashes as evidence.
Show solution
A fresh build can hide a missing dependency because it generates everything. The incremental test is essential. Timestamp and content evidence must show the omitted input changed and the stale output survived for the intended reason.
-
Problem 5: Audit maintainer-mode behavior
Create separate build directories with and without documented maintainer-mode regeneration. Write a driver that changes one header-generation input and records which generation targets run.
Test requirements: Compare ordinary builds with an explicit header-generation target. Explain observed rule behavior from the MAINT substitutions rather than assuming all generated files follow one policy.
Show solution
Some automatic regeneration dependencies are conditional while explicit targets remain available. Distributed generated files support ordinary builds without every maintainer tool. Inspect the expanded Makefile to establish the selected rule behavior.
-
Problem 6: Review a generated-only patch mechanically
Implement a checker that flags changes to selected generated files when none of their authoritative inputs changed. Use a small explicit dependency map derived from actual generation rules.
Test requirements: Test an input-and-output patch, an output-only patch, an unrelated edit, and a legitimate regeneration after a generator change. Emit an explanation rather than silently rejecting every output-only diff.
Show solution
A dependency-aware warning identifies likely omissions but is not a universal proof of an invalid patch. Generator updates and reproducibility repairs can legitimately change outputs. Include the relevant dependency evidence and support an explicit reviewed exception.
-
Problem 7: Create a clean-regeneration experiment
Choose one generation family and record the exact tools, input revisions, output hashes, and rebuild commands. Implement a driver that reproduces the outputs in a second isolated directory.
Test requirements: Deliberately vary one tool or preprocessing setting and explain any output difference. Separate environment effects from the intended source edit.
Show solution
Reproducibility requires the generator and effective inputs, not just a source commit. Compare normalized paths only where path differences are irrelevant to output semantics. Do not hide a changed opcode table by normalizing away its substantive content.
DejaGnu
A test is a source file and a .d file of expected output
run_dump_test (binutils/testsuite/lib/binutils-common.exp:1021) reads the header, runs the tools, and compares output line by line against regular expressions.
From the command line
make check-gas, make check-ld and make check-binutils run the three suites from the build directory. Each writes a .sum file with one PASS or FAIL line per test, and a .log file with the commands.
#source: emit-relocs-257.s ① #ld: -T relocs.ld --defsym tempy=0x11012 … -e0 --emit-relocs ② #notarget: aarch64_be-*-* ③ #objdump: -dr ④ #... ⑤ +10000: 00011012 \.word 0x00011012 +10000: R_AARCH64_ABS32 tempy +10004: 00045034 \.word 0x00045034 +10004: R_AARCH64_ABS64 tempy2
- ①The source to assemble. Default: the .d name with .s.
- ②Link options. Without
#ld:the test stops after gas. - ③Targets that skip the test.
#target:,#xfail:and#error:work the same way. - ④The program whose output is compared. Also
#readelf:,#nm:,#objcopy:. - ⑤Expected lines are regular expressions.
#...skips any number of lines.
make check-ld RUNTESTFLAGS="aarch64-elf.exp=emit-relocs-257". The three suites hold 11,747 .d files and 369 .exp drivers.Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Design a regression case
A relocation writes one wrong instruction bit. What should the test observe?
Show answer
Check the affected encoded bytes or disassembly and relevant relocation behavior. Merely checking that the command succeeds can miss the error.
-
Question 2: Avoid broad expectations
Why is matching every output line with
.*a weak repair for a failing test?Show answer
It can hide the regression the test should detect. Keep expectations specific to the behavior under test.
-
Question 3: Distinguish harness and feature
Does a test that prints a constructed command prove that the external tool accepts its options?
Show answer
No. It proves command construction only. Tool execution or inspection of the relevant implementation is needed to establish option support.
-
Problem 1: Write a failing-first relocation regression
Choose a relocation boundary in the x86-64 backend. Write a small assembly input and a dump-test expectation that detects a one-byte error in the patched field. Read the harness and a neighboring target test.
Test requirements: Run it on the normal backend and on a disposable one-line faulty variant. Preserve logs proving the intended assertion, rather than assembly setup, causes the faulty failure.
Show solution
Calculate the expected field independently from the backend. Match the exact relevant bytes or decoded operand. The fixture must reach the faulty path and retain a nearby control that would catch an overly broad repair.
-
Problem 2: Build a regular-expression test adversary
Select an existing .d expectation. Write a script that mutates captured tool output in one semantic field at a time and runs the harness comparison logic on each variant.
Test requirements: Mutate a relocation name, addend, address, and irrelevant whitespace separately. Report which mutations the expectation detects and justify tolerated differences.
Show solution
A broad pattern can accept a wrong relocation while still rejecting harmless formatting changes. Use the harness's actual matching semantics. Tighten meaningful fields and relax only documented presentation differences.
-
Problem 3: Test the intended failure stage
Create one assembler rejection, one undefined-symbol link failure, and one relocation overflow. Write harness tests that distinguish these cases using the relevant directives and result checks.
Test requirements: Prove each test fails if the fixture instead encounters a missing input file. Retain commands and diagnostics showing the intended operation actually ran.
Show solution
A nonzero status is insufficient evidence. The expected failure must come from the intended stage and semantic condition. Check both the harness directives and logs so a setup failure cannot masquerade as a passing negative test.
-
Problem 4: Design a target-selection regression
Write one target-specific instruction or relocation test and the selector needed to run it only where supported. Read how the containing .exp driver schedules .d files.
Test requirements: Show the selected target runs the test and an unrelated target skips it for the intended reason. Distinguish UNSUPPORTED or skipped results from a passing test.
Show solution
Instruction availability depends on target configuration. A skip prevents irrelevant failures but supplies no positive evidence of correct encoding. Preserve the target selection and executed command in the validation report.
-
Problem 5: Implement a fixture minimizer for a test failure
Write a reducer for assembly lines or independent input sections that preserves one specific dump-test failure. Use a synthetic wrong expectation or controlled backend fault as the starting case.
Test requirements: Reject reductions that fail assembly, select another target, or stop exercising the intended relocation. Verify the reduced fixture still fails for the same semantic reason.
Show solution
Keep stage success and the target observation inside the reduction predicate. Minimizing only a FAIL result can remove the actual behavior and leave a malformed test. Validate the minimized fixture again after restoring the normal backend.
-
Problem 6: Add a metamorphic test
Generate a family of equivalent relocation fixtures by consistently renaming symbols or shifting both source and target addresses. Write a driver that checks the invariant and include one intentionally non-equivalent transformation.
Test requirements: Predict which absolute fields change and which PC-relative values remain unchanged. Run the family through the actual tools and compare structured results.
Show solution
A common address shift preserves S minus P when the relocation type and addend are unchanged. Absolute references change by that shift. Consistent renaming preserves relationships. The negative control proves the checker is not simply accepting every result.
-
Problem 7: Prove the regression suite can fail
For three tests written above, apply a different local source fault that each should detect. Write a summary mapping faults to failed assertions and restore the source after every run.
Test requirements: Require at least one normal pass and one intended faulty failure per test. Identify surviving mutations as coverage gaps and add a fixture only when the missing behavior belongs to the test's scope.
Show solution
Mutation testing measures sensitivity to selected faults, not complete correctness. A test that passes after its relevant decision is broken needs a stronger oracle or a fixture that actually reaches the changed path. Keep intentional faults out of the final patch.
Scale
opcodes is the largest directory, and most of it is generated tables
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Define an honest comparison
What must remain consistent when comparing line counts between releases?
Show answer
Use the same file extensions, directory scope, generated-file treatment, and test exclusions. Otherwise the totals measure different things.
-
Question 2: Explain BFD's size
Why is it misleading to treat ld's own C count as the whole static linker?
Show answer
BFD implements substantial object handling and linking work that ld calls. The executable's behavior crosses directory boundaries.
-
Question 3: Interpret the metric
Which conclusion can line counts support without additional measurements?
Show answer
They describe source volume under the stated counting rules. They do not establish runtime cost, defect rate, or implementation quality.
-
Problem 1: Reproduce the chapter's measurement
Write a Python counter for C and header lines by directory at the referenced source revision. Define treatment of generated files, testsuites, symlinks, empty files, and final lines without a newline.
Test requirements: Compare your results with the displayed categories. Explain differences caused by branch changes or counting rules rather than editing totals to force agreement. Unit-test the counter on small synthetic files.
Show solution
Counting newline characters and counting logical final lines can differ. Scope and exclusion rules must remain explicit. The chapter's numbers are a snapshot, so a different branch revision need not reproduce every displayed total.
-
Problem 2: Separate authored inputs from generated volume
Implement a source inventory that classifies a selected set of generated headers through their actual Makefile rules. Produce both a physical-line total and a source-input-oriented report.
Test requirements: Include i386-tbl.h and BFD's generated public header. Test a large manual table so the classifier cannot use size as its only criterion.
Show solution
Generation evidence comes from dependency and recipe relationships, not filename or volume alone. Avoid adding generated output and its authoritative input together when estimating authored input volume. State where classification remains uncertain.
-
Problem 3: Compare two revisions fairly
Write a script that applies identical counting and classification rules to binutils-2_46 and the referenced binutils-2.46 branch. Produce per-directory deltas and the largest contributing files.
Test requirements: Retain the two resolved commit IDs. Test added, deleted, renamed, and binary files. Explain one large delta by reading the relevant source or generation rule.
Show solution
A reported increase can come from checked-in generated material or a scope change rather than new algorithms. Compare content under fixed rules and separate renames from unrelated additions when interpreting the result.
-
Problem 4: Measure one backend's build cost
Make two otherwise equivalent builds with different supported target sets. Write a collector for selected objects, executable sizes, and build duration. Read the target-selection and Makefile rules that explain the difference.
Test requirements: Repeat timing measurements and report their spread. Separate code-size differences from elapsed-time claims. Record compiler, linker, configuration, and whether caches were warm.
Show solution
Source line counts do not predict linked size or build time directly. Only compiled and retained objects contribute to a given executable. Timing needs repeated comparable runs and explicit environmental limits.
-
Problem 5: Recover ld's hidden implementation footprint
Write a source-call inventory starting from ld's final write path and following calls into BFD for one tiny static link. Use a diagnostic trace to validate selected cross-directory edges.
Test requirements: Report the functions actually reached separately from all functions statically reachable. Include one backend-specific relocation function and explain why summing ld directory lines misses it.
Show solution
ld delegates substantial work to BFD. A static call graph overestimates one execution's footprint, while a trace underestimates all possible behavior. Present both as different measurements and connect the selected relocation path explicitly.
-
Problem 6: Test the cost of a generated table change
Select one small input-table change in a disposable x86 opcode build. Write a report of generated-line delta, object-size delta, and one observable encoding or decoding effect.
Test requirements: Restore the input and reproduce the original outputs. Check that the behavioral test detects the change even when a size metric barely moves.
Show solution
A compact source edit can expand into many generated lines without a comparable semantic expansion. Conversely, a small binary-size change can still alter an important decode decision. Correctness needs a behavioral oracle independent of volume.
-
Problem 7: Design an honest comparison report
Implement a report generator that combines source counts, generated-input relationships, and selected build measurements. Include machine-readable data and a short explanation of unsupported conclusions.
Test requirements: Test a case where generated lines grow but linked size stays constant, and one where a small source change adds a selected object. Ensure the report does not label either result as a quality score.
Show solution
Keep measurement units and scopes separate. A directory's volume, an executable's size, and runtime behavior answer different questions. The report should expose evidence and uncertainty rather than deriving maintenance quality from a single line count.
Background
The formats and mechanisms behind each part are on the main site
This page explains the code. These pages explain what the code reads and writes.
Header, program headers, section headers, the two views. BFD's elfcode.h and readelf both parse this.
What ar writes and what ld reads to pull members.
Why objcopy must keep groups whole.
.symver in gas, version scripts in ld, readelf -V.
ld --build-id and the feature-bit AND across inputs.
The Elf_Chdr that bfd/compress.c reads.
What dwarf.c dumps and dwarf2.c reads for addr2line.
The objcopy and strip recipe.
The other container BFD writes, timestamp included.
Archive order, --start-group, --as-needed, weak and COMMON.
Every psABI type applied, with formula and range check.
What finish_dynamic_symbol writes.
What gas emits from .cfi_* and ld turns into .eh_frame_hdr.
Why gas emits .sframe beside .eh_frame.
The compiler that writes the .s files gas reads, and the LTO side of the plugin API.
Sources
binutils-2.46 tree: bfd/bfd-in2.h · bfd/format.c · bfd/targets.c · bfd/config.bfd · bfd/configure.ac · bfd/elfxx-target.h · bfd/elf-bfd.h · bfd/elfcode.h · bfd/elf.c · bfd/elflink.c · bfd/reloc.c · bfd/archive.c · bfd/compress.c · bfd/peXXigen.c · bfd/Makefile.am · opcodes/disassemble.c · include/dis-asm.h · binutils/objdump.c · binutils/objcopy.c · binutils/readelf.c · binutils/Makefile.am · gas/as.c · gas/read.c · gas/write.c · gas/frags.h · gas/write.h · gas/configure.ac · gas/configure.tgt · gas/config/tc-aarch64.c · ld/ldmain.c · ld/ldlang.c · ld/ldelf.c · ld/ldwrite.c · ld/emultempl/elf.em · ld/genscripts.sh · ld/configure.tgt · binutils/testsuite/lib/binutils-common.exp · ld/testsuite/ld-aarch64/emit-relocs-257.d · src-release.sh. Line counts: wc -l over *.c and *.h, testsuites excluded.
Exercises: 3 questions and 7 problems
The questions require reasoning about the chapter. Each problem requires code, source investigation, and tests. Record a prediction before running the experiment.
Use disposable source and build directories. Keep the reference checkout unchanged. Unless a problem specifies another target, use x86-64 GNU/Linux.
Build the required tools from the referenced branch. C API problems also need BFD or libopcodes development libraries. Debug-data problems need a C compiler. Read the linked starting points, then follow callers and callees to justify the result.
-
Question 1: Connect a source entry
Find
bfd_elf_link_add_symbolsin the linked source. Which background should precede investigation of an archive-resolution problem there?Show answer
Read symbol resolution and archives first. Those mechanisms explain why a member's symbols enter the link at a particular point.
-
Question 2: Build an investigation route
A copied object loses debug information. Which two areas should be connected first?
Show answer
Connect the objcopy path with the DWARF and separate-debug-file background. Compare the requested transformation with the input and output sections.
-
Question 3: Explain one full path
Connect an unresolved call, its relocation, the chosen definition, and the patched instruction in one account.
Show answer
Assembly records the reference. Resolution chooses its definition. Allocation assigns addresses. Relocation calculates and encodes the required instruction-field value.
-
Problem 1: Connect an archive file to member extraction
Implement a small archive-index reader and use it to predict candidate members for a two-library dependency cycle. Then trace the actual member selections in a grouped and an ungrouped link.
Test requirements: Compare your index-derived candidates with selected members. Explain why the format index alone cannot decide the entire ordered link. Cite both the archive parser and resolution path.
Show solution
The index identifies candidate definitions by member offset. Current unresolved symbols and scan order determine extraction. Group rescanning can discover later needs. Keep candidate lookup distinct from the linker's changing resolution state.
-
Problem 2: Trace COMDAT from bytes to selection
Write a Python decoder for the section-group metadata of a narrowly defined ELF64 fixture with duplicate COMDAT signatures. Link both input orders and compare retained groups.
Test requirements: Verify member section indices, signature symbol, and relocation consistency. Test an invalid group member index in a disposable file and identify the rejecting source guard.
Show solution
Group metadata connects a signature with member sections. Selection discards redundant instances as groups, not arbitrary matching bytes. The decoder must validate indices before following them, and retained relocations must refer to surviving relationships.
-
Problem 3: Follow one call through GOT and PLT
Build a shared library with an imported call and an imported data address. Implement a report joining disassembly, dynamic symbols, GOT or PLT entries, and dynamic relocations.
Test requirements: Trace the backend decision for each reference and compare with hidden or locally defined variants. Check addresses numerically without relying on executing a dynamic loader.
Show solution
The input reference form and binding determine whether the linker can resolve locally or needs dynamic structures. A PLT relocation and a data relocation serve different targets and timing. Explain actual output records rather than treating every dynamic relocation as a call patch.
-
Problem 4: Decode unwind data emitted by gas
Write a small assembly function with
.cfi_*directives for a stack adjustment and saved return context. Implement a decoder for the limited CFI operations it emits. Follow gas emission and linker handling of .eh_frame.Test requirements: Compare your interpreted rows with a tool dump before and after linking. Verify at least two instruction addresses and reject an unsupported opcode explicitly.
Show solution
The directives describe recovery rules indexed by instruction location. They are not the machine instructions that adjust the stack. CIE defaults and FDE updates combine to form each row. Linking can merge or relocate records while preserving the applicable recovery semantics.
-
Problem 5: Validate a separate-debug relationship
Compile a small program with debug data and produce a runtime image plus a separate debug file. Write an independent debuglink parser and checksum verifier. Read generation and lookup paths.
Test requirements: Cover a valid pair, a renamed debug file, a changed debug byte, and a missing debug file. Distinguish locating a candidate from accepting its checksum.
Show solution
The link contains a filename and CRC with alignment requirements. The checksum covers the debug file, not the runtime executable. Finding a matching basename is insufficient when its contents do not match.
-
Problem 6: Investigate a wrong address end to end
Create a deliberately faulty Python relocation oracle by using the section's file offset as P. Generate two valid layouts that separate file offsets from VMAs. Compare its prediction with linked bytes and symbol addresses.
Test requirements: Minimize the discrepancy to one relocation. Submit a corrected oracle and a source-backed explanation of the coordinate-system error. Check both a direct and a relocatable intermediate link.
Show solution
P is the relocation place in the relevant address space, not automatically its file offset. ELF section storage and runtime placement differ. The independent oracle must obtain the allocated address and then apply the actual relocation formula and addend.
-
Problem 7: Write a complete source-backed bug report
Choose one controlled fault from the preceding problems. Produce a minimal source fixture, a driver, expected and actual structured results, and a call path from the user command to the faulty implementation.
Test requirements: Prove the report reproduces on the faulty build and does not reproduce on the restored build. State tool paths, source revision, target configuration, and the exact failing invariant.
Show solution
A useful report connects valid input, an independently justified expectation, observed behavior, and the responsible decision. Include only evidence needed to reproduce the fault. A long source listing or a nonzero status without a semantic expectation is insufficient.