MOLD(1)
mold(1) โ yes, the MOLD(1) page โ is from the General Commands Manual, and ngl bestie, she's lowkey iconic. ๐
โจ The way this linker shows up, slays, and makes the whole build feel main character? Obsessed. ๐ซถ
โจ NAME โจ
moldโ a modern linker, periodt. ๐
๐ ๏ธ SYNOPSIS ๐ ๏ธ
mold [option...] file...
๐ DESCRIPTION ๐
mold is a faster drop-in replacement for the default GNU ld(1). No cap. ๐ฅ
๐ง How to use ๐ง
See https://github.com/rui314/mold#how-to-use. That's the how-to, bestie. ๐
๐ธ Compatibility ๐ธ
mold is designed as a drop-in replacement for the GNU linkers for linking user-land programs. If your user-land program cannot be built due to missing command-line options, please file a bug at https://github.com/rui314/mold/issues. fr fr. ๐
mold supports a very limited set of linker script features, which is just sufficient to read /usr/lib/x86_64-linux-gnu/libc.so on Linux systems (on Linux, that file is contrary to its name not a shared library but an ASCII linker script that loads a real libc.so file.) ๐
Beyond that, we have no plan to support any additional linker script features. The linker script is an ad-hoc, over-designed, complex language which we believe needs to be replaced by a simpler mechanism. We have a plan to add a replacement for the linker script to mold instead. ๐
๐๏ธ Archive symbol resolution ๐๏ธ
Traditionally, Unix linkers are sensitive to the order in which input files appear on the command line. They process input files from the first (leftmost) file to the last (rightmost) file one-by-one. While reading input files, they maintain sets of defined and undefined symbols. When visiting an archive file (.a files), they pull out object files to resolve as many undefined symbols as possible and move on to the next input file. Object files that weren't pulled out will never have a chance for a second look. ๐ Not me crying over missed object files.
Due to this behavior, you usually have to add archive files at the end of a command line, so that when a linker reaches archive files, it knows what symbols remain as undefined. ๐ง
If you put archive files at the beginning of a command line, a linker doesn't have any undefined symbols, and thus no object files will be pulled out from archives. You can change the processing order by using the --start-group and --end-group options, though they make a linker slower. ๐
mold, as well as the LLVM lld(1) linker, takes a different approach. They remember which symbols can be resolved from archive files instead of forgetting them after processing each archive. Therefore, mold and lld(1) can "go back" in a command line to pull out object files from archives if they are needed to resolve remaining undefined symbols. They are not sensitive to the input file order. โจ
--start-group and --end-group are still accepted by mold and lld(1) for compatibility with traditional linkers, but they are silently ignored. ๐
๐ Dynamic symbol resolution ๐
Some Unix linker features are difficult to understand without comprehending the semantics of dynamic symbol resolution. Therefore, even though it's not specific to mold, we'll explain it here. ๐
We use "ELF module" or just "module" as a collective term to refer to an executable or a shared library file in the ELF format. ๐ฆ
An ELF module may have lists of imported symbols and exported symbols, as well as a list of shared library names from which imported symbols should be imported. The point is that imported symbols are not bound to any specific shared library until runtime. โณ
Here is how the Unix dynamic linker resolves dynamic symbols. Upon the start of an ELF program, the dynamic linker constructs a list of ELF modules which, as a whole, consist of a complete program. The executable file is always at the beginning of the list followed by its dependent shared libraries. An imported symbol is searched from the beginning of the list to the end. If two or more modules define the same symbol, the one that appears first in the list takes precedence over the others. ๐ฏ
This Unix semantics are contrary to systems such as Windows that have a two-level namespace for dynamic symbols. On Windows, for example, dynamic symbols are represented as a tuple of (symbol-name, shared-library-name), so that each dynamic symbol is guaranteed to be resolved from some specific library. ๐ช
Typically, an ELF module that exports a symbol also imports the same symbol. Such a symbol is usually resolved to itself, but that's not the case if a module that appears before it in the symbol search list provides another definition of the same symbol. ๐
Let's take malloc as an example. Assume that you define your version of malloc in your main executable file. Then, all malloc calls from any module are resolved to your function instead of the one in libc, because the executable is always at the beginning of the dynamic symbol search list. Note that even malloc calls within libc are resolved to your definition since libc exports and imports malloc. Therefore, by defining malloc yourself, you can overwrite a library function, and the malloc in libc becomes dead code. ๐
These Unix semantics are tricky and sometimes considered harmful. For example, assume that you accidentally define atoi as a global function in your executable that behaves completely differently from the one in the C standard. Then, all atoi function calls from any modules (even function calls within libc) are redirected to your function instead of the one in libc, which will very likely cause a problem. That is a somewhat surprising consequence for an accidental name conflict. On the other hand, this semantic is sometimes useful because it allows users to override library functions without rebuilding modules containing them. ๐ญ
Whether good or bad, you should keep these semantics in mind to understand Unix linkers' behaviors. ๐ง
๐ Build reproducibility ๐
mold's output is deterministic. That is, if you pass the same object files and the same command-line options to the same version of mold, it is guaranteed that mold produces the bit-for-bit identical output. The linker's internal randomness, such as the timing of thread scheduling or iteration orders of hash tables, doesn't affect the output. ๐
mold does not have any host-specific default settings. This is contrary to the GNU linkers, for which some configurable values, such as system-dependent library search paths, are hard-coded. mold depends only on its command-line arguments. ๐ง
๐ OPTION NOTATIONS ๐
Long options are spelled with two dashes. Some also accept a single dash, but which ones do is somewhat arbitrary for historical reasons. mold follows the conventions of other linkers for compatibility. For example, --export-dynamic can be spelled -export-dynamic, while --execute-only requires two dashes. ๐
This can cause unexpected behavior when constructing command-line options in a script. For example, you might use "-e$foo" to set the entry point symbol to the value of $foo. However, if $foo is xport-dynamic, the argument becomes -export-dynamic and is interpreted as --export-dynamic. ๐ฑ
To avoid such ambiguities, we recommend always using two dashes for long options and separating a single-letter option from its argument with a space. For example, use -e $foo or --entry=$foo to specify the entry point symbol in a script. ๐ซถ
๐ MOLD-SPECIFIC OPTIONS ๐
--chroot=dirโ Setsdiras the root directory. That's it, that's the whole vibe. ๐ธ--color-diagnostics=[ auto | always | never ]โ Shows diagnostic messages in color using ANSI escape sequences.automeans mold only prints the pretty colors when standard output is connected to a TTY. The default isauto. โจ--color-diagnosticsโ Synonym for--color-diagnostics=auto. Same thing, shorter to type, we love a shortcut. ๐--no-color-diagnosticsโ Synonym for--color-diagnostics=never. For when you want your terminal to be boring on purpose.--detach,--no-detachโ Permit โ or don't permit โ mold to create a debug info file in the background. That's the whole toggle. ๐ฆ--fork,--no-forkโ Spawns a child process and lets it do the actual linking. When you're linking a big program, the OS kernel can take a few hundred milliseconds to terminate a mold process, and--forkhides that latency. By default, it does fork.
Heads up though, bestie:--forkalso hides the resource usage statistics reported bytime(2), because it doesn't callwaitpid(2)on the child process. If you actually need those stats, pass--no-fork. ๐
--perfโ Prints performance statistics. Numbers! For looking at! ๐ฅ--print-dependenciesโ Prints out dependency information for input files.
Each line of the output for this option shows which file depends on which file in order to use a specific symbol. This one is genuinely a lifesaver for debugging why some object file in a static archive got linked, or why some shared library is still chillin' in an output file's dependency list even when you passed --as-needed. Detective mode activated. ๐
--relocatable-merge-sectionsโ So by default, mold doesn't merge input sections by name when it's merging input object files into a single output object file for-r. Like,.text.fooand.text.bararen't merged for-r, even though they do get merged into.textbased on the default section merging rules.
This option flips the behavior so that mold merges input sections by name using the default section merging rules. ๐
--reproโ Archives your input files, plus a text file containing the command line options, all into a tar file, so you can run mold again with the exact same inputs. Iconic for reporting a bug with a reproducer, honestly. The output filename ispath/to/output.tar, wherepath/to/outputis the output filename you specified with-o. ๐--reverse-sectionsโ Reverses the order of input sections before assigning them their offsets in the output file.
This one is useful for finding bugs that depend on the initialization order of global objects. In C++, constructors of global objects in a single source file are guaranteed to be executed in source order, but there is no such guarantee across compilation units. Usually constructors get executed in the order given to the linker โ but depending on that is a mistake, fr fr.
By reversing the order of input sections using --reverse-sections, you can easily test that your program still works in the reversed initialization order. ๐งช
--run command arg...โ Runscommandwith mold as/usr/bin/ld. Specifically, mold runs the given command with theLD_PRELOADenvironment set to interceptexec(3)family functions, and replacesargv[0]with itself if it isld,ld.gold, orld.lld. Sneaky? No. Iconic. ๐--separate-debug-file,--separate-debug-file=fileโ Bundles debug info sections into a separate file instead of embedding them in an output executable or a shared library. mold creates that debug info file in the background by default, so you can start running your executable ASAP. ๐โโ๏ธ
By default the debug info file is created in the same directory as the output file, with the .dbg file extension. That filename gets embedded into the output file so that gdb can automatically find the debug info file for the output file. For more info about gdb features related to separate debug files, see https://sourceware.org/gdb/current/onlinedocs/gdb.html/Separate-Debug-Files.html.
mold holds a file lock with flock(2) while creating a debug info file in the background. ๐
If you don't want a debug info file created in the background, pass the --no-detach option.
--shuffle-sections,--shuffle-sections=numberโ Randomizes the output by shuffling the order of input sections before assigning them their offsets in the output file. If a number is given, it's used as the seed for the random number generator, so that the linker produces the same output for the same seed. If no seed is given, a random number is used as the seed. ๐ฒ
This option is useful for benchmarking. Modern CPUs are super sensitive to a program's memory layout. A seemingly benign change in program layout โ like a tiny size increase of a function in the middle of a program โ can affect the program's performance. So even if you write new code and get a good benchmark result, it's genuinely hard to say whether the new code improves performance, because maybe the new memory layout just happens to perform better. ๐
By running a benchmark multiple times with randomized memory layouts using --shuffle-sections, you can isolate your program's real performance number from the randomness caused by memory layout changes. Science, bestie. ๐ฌ
--spare-program-headers=numberโ Appends the givennumberofPT_NULLentries to the end of the program header, so that post-link processing tools can easily add new segments by overwriting those null entries.
Note that ELF requires allPT_LOADsegments to be sorted byp_vaddr. So if you add a newLOADsegment, you may need to sort the entire program header. Don't forget! ๐
--statsโ Prints input statistics.--thread-count=countโ Usescountnumber of threads. Exactly that many. โก--threads,--no-threadsโ Uses multiple threads. By default, mold uses as many threads as the number of cores, or 32 โ whichever is smaller. The reason it's capped at 32 is because mold doesn't scale well beyond that point. To use only one thread, pass--no-threadsor--thread-count=1. ๐--quick-exit,--no-quick-exitโ Use โ or do not use โquick_exitto exit. Simple as that.--zero-to-bssโ Converts all-zero data sections into BSS.
When this option is enabled, mold scans input data sections that are not of type SHT_NOBITS and checks whether their contents consist solely of zero bytes. Those sections then get converted into BSS (SHT_NOBITS) sections. This reduces the size of the output file, since BSS sections occupy no space in the file image. โจ
This behavior is especially useful for user-defined sections created with __attribute__((section(".sectname"))) that contain uninitialized global variables. GCC and Clang don't automatically mark such sections as BSS even if their contents are entirely zero โ instead they emit them as regular data sections. Rude, but okay. ๐ญ
For example, consider __attribute__((section(".sectname"))) int vec[256];.
By default, this results in a .sectname section of type SHT_PROGBITS filled with zeros. With --zero-to-bss, the linker will recognize it as empty data and convert it to a SHT_NOBITS section, reducing the output file size without changing runtime semantics. Free real estate. ๐
-z rewrite-endbr,-z norewrite-endbrโ Okay so gather round, this one's a whole story. ๐
As a security measure, some CPU instruction sets have recently gained a feature to protect control flow integrity by disallowing indirect branches by default. If that feature is enabled, the instruction executed immediately after an indirect branch must be a branch target marker instruction, or the CPU raises a fault. That marker instruction is also known as a "landing pad" instruction, and it's where indirect branches are allowed to land. This feature makes ROP attacks harder to conduct. ๐ก๏ธ
To use the feature, a function whose pointer is taken needs to begin with a landing pad, because a function call via a function pointer is compiled to an indirect branch. On the other hand, if a function is called only directly (i.e. referred to only by direct branch instructions), it doesn't have to begin with one.
By default, the compiler always emits a landing pad at the beginning of each global function, because it doesn't know whether or not the function's pointer is taken in another translation unit. As a result, the resulting binary has more attack surface than necessary. ๐ฌ
If --rewrite-endbr is given, mold conducts a whole program analysis to identify functions whose addresses are actually taken, and rewrites landing pads with no-ops for non-address-taken functions, reducing the attack surface. โจ
This feature is currently available only on x86-64 and arm64.
On arm64, the landing pad is bti c. Note that code compiled with -mbranch-protection=standard (BTI + pointer authentication) starts functions with paciasp, which doubles as a landing pad โ so there's no separate bti c to rewrite, and this option has no effect on such code. ๐
โโ๏ธ
๐ GNU-COMPATIBLE OPTIONS ๐
--helpโ Reports usage information to stdout and exits. The classic.-v,--versionโ Reports version information to stdout.-Vโ Reports version and target information to stdout. Extra info, extra slay. โญ-E,--export-dynamic,--no-export-dynamicโ When creating an executable, using the-Eoption causes all global symbols to be put into the dynamic symbol table, so that those symbols are visible from other ELF modules at runtime.
By default โ or if --no-export-dynamic is given โ only symbols that are referenced by DSOs at link-time are exported from an executable.
-F libname,--filter=libnameโ Sets theDT_FILTERdynamic section field tolibname. ๐-I file,--dynamic-linker=file,--no-dynamic-linkerโ Sets the dynamic linker path tofile. If no-Ioption is given, or if--no-dynamic-linkeris given, no dynamic linker path is set to an output file. This is contrary to the GNU linkers, which do set a default dynamic linker path in that case. This difference doesn't usually make any difference though, because the compiler driver always passes-Ito the linker. So it's giving... theoretical. ๐ฆ-L dir,--library-path=dirโ Addsdirto the list of library search paths from which mold searches libraries for the-loption. ๐
โจ okay also, real quick before we keep going: unlike the GNU linkers, mold does not have default search paths. And honestly? That rarely changes anything, because the compiler driver always passes all the necessary search paths to the linker anyway. ๐ซถ
-M,--print-mapโ writes a map file to stdout. dump it right into your terminal, queen ๐-N,--omagic,--no-omagicโ forces mold to emit an output file with an old-fashioned memory layout. Two things happen: first, the first data segment is not aligned to a page boundary, and second, text segments get marked as writable if the option is given. vintage vibes, no cap โจ-S,--strip-debugโ omits.debug_*sections from the output file. bye bye debug info ๐ฆ-Tfile,--script=fileโ read a linker script from file.-X,--discard-localsโ discards temporary local symbols to shrink the symbol table and the string table. What counts as "temporary"? Local symbols starting with.Lโ compilers generate those for unnamed program elements like string literals or floating-point literals. This is the default; use--discard-noneif you want to keep them.--discard-noneโ keeps all local symbols in the symbol table, including the temporary ones starting with.L, except ones in mergeable sections. This restores the default behavior of GNU ld. Just so you know: mold andld.llddiscard temporary local symbols by default. ๐-esymbol,--entry=symbolโ and that's it, that's the whole entry in the page. No description, she just showed up with a colon and left ๐ (the original really is just this.)-fshlib,--auxiliary=shlibโ sets theDT_AUXILIARYdynamic section field to shlib.-hlibname,--soname=libnameโ sets theDT_SONAMEdynamic section field to libname. This one's for when you're creating a shared object file. Like, typically when you createlibfoo.so, you want to pass--soname=footo the linker. iconic ๐-llibname โ searches forliblibname.soorliblibname.afrom the library search paths.-mtarget โ choose a target.-ofile,--output=fileโ use file as the output file name instead of the default namea.out. (yes,a.out, the main character of 1971 ๐)-r,--relocatableโ instead of generating an executable or a shared object file, combine the input object files into another object file that can be used as an input to a linker. object files all the way down ๐-s,--strip-allโ omits the.symtabsection from the output file.-usymbol,--undefined=symbolโ if symbol is still undefined after reading all object files, and if there's a static archive containing an object file that defines symbol, pull that object file out and link it so the output file contains a definition of symbol. rescue mission activated ๐ซก-ysymbol,--trace-symbol=symbolโ trace references to symbol. internet sleuth mode ๐--Bdynamicโ link against shared libraries.--Bstaticโ do not link against shared libraries.--Bsymbolicโ when creating a shared library, makes global symbols export-only (i.e. it does not import the same symbol). The consequence is genuinely important: references within a shared library are always resolved locally, which negates symbol override at runtime. See "Dynamic symbol resolution" for more on symbol imports and exports. โจ--Bsymbolic-functionsโ same effect as--Bsymbolicbut only for function symbols. Data symbols stay both imported and exported.--Bsymbolic-non-weakโ same effect as--Bsymbolicbut only for non-weak symbols. Weak symbols stay both imported and exported.--Bsymbolic-non-weak-functionsโ same effect as--Bsymbolicbut only for non-weak function symbols. Data symbols and weak function symbols stay both imported and exported.--Bno-symbolicโ cancels--Bsymbolic,--Bsymbolic-functions,--Bsymbolic-non-weakand--Bsymbolic-non-weak-functions. the uninvite button ๐ซ--Map=fileโ write the map file to file.--Tbss=addressโ alias for--section-start=.bss=address.--Tdata=addressโ alias for--section-start=.data=address.--Ttext=addressโ alias for--section-start=.text=address.--Ttext-segment=addressโ sets the address of the first byte of the text segment.--allow-multiple-definitionโ normally the linker errors out if a symbol has more than one definition. This option flips the default so it doesn't report an error for duplicate definitions, and instead uses the first definition. first come, first served ๐--allow-shlib-undefined,--no-allow-shlib-undefinedโ okay this one's important, listen up:
Even if mold successfully links a main executable with no undefined symbol errors, you can still run into symbol lookup errors at runtime, because the dynamic linker can't find some symbols in shared libraries in any ELF module. Why does that happen? Because mold ignores undefined symbols in shared libraries by default.
If you pass --no-allow-shlib-undefined, mold verifies that the undefined symbols in the shared libraries you gave the linker can actually be resolved at link-time. In other words โ it converts that runtime error into a link-time error. glow up of the century โญ
Heads up bestie: you need to pass all the shared libraries, including the indirectly dependent ones, to the linker as arguments for -l. If a shared library depends on a library that isn't passed to the linker, the verification gets skipped for that file. ๐ญ
--as-needed,--no-as-neededโ by default, shared libraries given to the linker are unconditionally added to the list of required libraries in the output file. But libraries after--as-neededare added to that list only when at least one symbol is actually used by the output file. Translation: shared libraries after--as-neededdon't get added to the list of needed libraries if the program doesn't need them. minimalism, we love her ๐ฆ
The --no-as-needed option restores the default behavior for subsequent files.
--build-id=[ md5 | sha1 | sha256 | fast | uuid | 0xhexstring | none ]โ creates a.note.gnu.build-idsection containing a byte string that uniquely identifies an output file. Here's the tea:sha256computes a 256-bit cryptographic hash of the output file and sets it to the build-id.md5andsha1compute the same hash but truncate it to 128 and 160 bits respectively, before setting it to the build-id.uuidsets a random 128-bit UUID.0xhexstringsets hexstring.fastis a synonym forsha256.
--build-idโ synonym for--build-id=sha256.--no-build-idโ synonym for--build-id=none.--compress-debug-sections=[ zlib | zlib-gabi | zlib:N | zstd | zstd:N | none ]โ compresses DWARF debug info (.debug_*sections) using thezliborzstdcompression algorithm. Details, because numbers matter:zlib-gabiis an alias forzlib.zlib:Npicks the zlib compression level, where N is between 0 and 9 (0 means no compression).zstd:Npicks the zstd compression level, where N is between 1 and 22.- Higher levels get you better compression ratios but are slower. ๐
zlibis equivalent tozlib:1andzstdis equivalent tozstd:3.
--defsym=symbol=valueโ defines symbol as an alias for value.
value is either an integer (in decimal, or hexadecimal with a 0x prefix) or a symbol name. If you give an integer as the value, symbol is defined as an absolute symbol with that given value. ๐ฅ
--default-symverโ uses the soname as a symbol version and appends that version to all symbols.--demangle,--no-demangleโ demangles C++ and Rust symbols in log messages. readable logs, we stan ๐--dependency-file=fileโ writes a dependency file to file. The contents of the written file are readable bymake(1), which defines exactly one rule with the linker's output file as a target and all input files as its prerequisites. The expectation is that you include the generated dependency file into aMakefileto automate dependency management. This option is analogous to the compiler's-MM -MFoptions. ๐--dynamic-list=fileโ reads a list of dynamic symbols from file. Same as--export-dynamic-symbol-list, except that it implies--Bsymbolic. If file doesn't exist in the current directory, it gets searched from the library search paths, for the sake of compatibility with GNU ld.--eh-frame-hdr,--no-eh-frame-hdrโ creates the.eh_frame_hdrsection.--emit-relocsโ the linker usually "consumes" relocation sections. Like, it applies the relocations to other sections, and the relocation sections themselves are discarded.--emit-relocstells the linker to leave relocation sections in the output file. Some post-link binary analysis or optimization tools such as LLVM Bolt need them. ๐--enable-new-dtags,--disable-new-dtagsโ by default mold emitsDT_RUNPATHfor--rpath. If you pass--disable-new-dtags, mold emitsDT_RPATHfor--rpathinstead. choose your tag, bestie ๐--execute-onlyโ again, that's the whole entry. no description, just the flag, standing there looking pretty โจ- *
--exclude-libs=libraries* ... โ marks all symbols in the given libraries hidden. ๐คซ --export-dynamic-symbol=symbolโ puts symbols matching symbol in the dynamic symbol table. symbol may be a glob pattern in the same syntax as for the--export-dynamic-symbol-listor--version-scriptoptions.--export-dynamic-symbol-list=fileโ reads a list of dynamic symbols from file.--fatal-warnings,--no-fatal-warningsโ treats warnings as errors. no warnings, only consequences ๐ญ--fini=symbolโ calls symbol at unload-time.--gc-sections,--no-gc-sectionsโ removes unreferenced sections. garbage collection era ๐๏ธโจ--gdb-indexโ creates a.gdb_indexsection to speed up the GNU debugger. To actually use this, you need to compile your source files with the-ggnu-pubnamescompiler flag.--hash-style=[ sysv | gnu | both | none ]โ set the hash style.--icf=[ safe | all | none ],--no-icfโ okay so it is genuinely not uncommon for a program to contain a ton of identical functions that differ only in name. Classic example: a C++ templatestd::vectoris very likely to be instantiated to the exact same code forstd::vector<int>andstd::vector<unsigned>, because the container only cares about the size of the parameter type. Identical Code Folding (ICF) is a size optimization that identifies and merges these identical functions. twin magic ๐ฎ
So, continuing the --icf tea โ โ okay so if you pass --icf=all, mold goes full send and tries to merge, like, every single identical function it can find ๐ซถ. It shrinks your output the most, bestie, but it is not a "safe" optimization โ and this is the part where you gotta listen ๐. In C and C++ it's literally guaranteed that two pointers pointing at two different functions will never, ever be equal. But --icf=all breaks that assumption, because two identical functions end up with the same address after merging ๐ญ. So you gotta be careful when you use this flag โ make sure your program doesn't depend on function pointer uniqueness, fr fr. No cap.
--icf=safe is the cautious queen ๐ โ it only merges functions when it's actually safe to do so. The logic is kinda iconic: if a program never takes the address of a function, then merging that function with another one is fine, because you literally cannot compare a function pointer with anything else without taking an address of a function first ๐
.
--icf=safeneeds a compiler that supports the.llvm_addrsigsection, which carries the info about which symbols are address-taken. LLVM/Clang supports that section by default. GCC does not support it yet, so you can't use--icf=safewith GCC โ it doesn't do any harm, but it can't optimize at all ๐.
--icf=none and --no-icf disable ICF entirely. Periodt. โจ
--ignore-data-address-equalityโ tells ICF to merge not just functions but data too ๐. Only use this in combination with--icf=all, okay?--image-base=addrโ sets the base address to addr. Simple as that ๐.--init=symbolโ calls symbol at load-time ๐ธ.--no-undefinedโ reports undefined symbols, even when you're doing--shared๐.--noinhibit-execโ creates an output file even if errors occur ๐ญ. Chaotic but valid.--package-metadata=percent-encoded-stringโ embeds a specified string into the.note.packagesection ๐. This one's designed for build scripts that generate binary packages โ think.rpmor.debโ so they can include package metadata in each executable. It seriously simplifies the whole "which package does this executable or core file even belong to" detective work ๐.
The argument gets treated as percent-encoded and decoded before being inserted into the section, which lets you dodge using the comma (,) character in the argument. Why does that matter? Because the compiler replaces all occurrences of commas in -Wl, with spaces before forwarding them to the linker โ so commas are a whole mess ๐. Note that mold always interprets the argument as percent-encoded, so you also need to escape every occurrence of % as %25. Iykyk.
--pack-dyn-relocs=[ relr | android | android+relr | none ]โ compresses dynamic relocations in the output file ๐ฆ.
If relr is specified, all R_*_RELATIVE relocations get put into the .relr.dyn section instead of .rel.dyn or .rela.dyn. Since .relr.dyn uses a space-efficient encoding scheme, this flag can literally shrink your output. It's typically most effective for position-independent executables โจ.
If android is specified, all dynamic relocations are encoded in Android's packed relocation format (APS2) and stored in the .rel.dyn or .rela.dyn section โ whose section type changes to SHT_ANDROID_REL or SHT_ANDROID_RELA. The dynamic table gets updated to use DT_ANDROID_REL / DT_ANDROID_RELA and their SZ variants instead of the standard tags ๐
android+relr combines both: R_*_RELATIVE relocations go to .relr.dyn and the rest are APS2-encoded. This is the configuration used by most Android system binaries ๐ฅ.
Heads up, bestie โ a runtime loader has to support.relr.dynto run executables or shared libraries linked with--pack-dyn-relocs=relr๐ญ. As of 2026, glibc (since 2.36), musl (since 1.2.4), Android, ChromeOS, and Fuchsia all support it. The APS2 format, on the other hand, is only handled by Android's bionic loader โ the encoder itself is target-agnostic, but the produced binary can only be loaded on platforms where bionic (or a compatible loader) handlesDT_ANDROID_REL(A). So don't just vibe-check it and assume ๐.
--pie,--pic-executable,--no-pie,--no-pic-executableโ creates a position-independent executable ๐.--print-gc-sections,--no-print-gc-sectionsโ prints the removed unreferenced sections ๐.--print-icf-sections,--no-print-icf-sectionsโ prints folded identical sections ๐.--push-state,--pop-stateโ--push-statesaves the current values of--as-needed,--whole-archive,--static, and--start-lib. Those saved values can be restored by--pop-state๐ .
--push-state / --pop-state pairs can nest, bestie โ they're stack girlies ๐.
These are so useful when you want to construct linker command line options programmatically. Example: if you wanna link libfoo.so on an as-needed basis but don't wanna change the global state of --as-needed, you can just append --push-state --as-needed -lfoo --pop-state to the linker command line options โจ.
--relax,--no-relaxโ rewrites machine instructions with more efficient ones for some relocations. Enabled by default ๐ซถ.--require-defined=symbolโ like--undefined, except the new symbol must be defined by the end of the link ๐.--retain-symbols-file=fileโ keeps only the symbols listed in file. The file is a text file containing a symbol name on each line. mold discards all local symbols as well as global symbols that aren't in file. Note that this option removes symbols only from the.symtabsection and does not affect the.dynsymsection, which is the one used for dynamic linking ๐.--rpath=dirโ adds dir to the runtime search paths ๐ธ.--section-start=section=addressโ sets address to section. The address is a hexadecimal number that may start with an optional0x๐.--shared,--Bshareableโ creates a share library โจ.--spare-dynamic-tags=numberโ appends the given number ofDT_NULLentries to the end of the.dynamicsection, so post-link processing tools can easily add new dynamic tags by overwriting the null entries ๐.--start-lib,--end-libโ handles object files between--start-liband--end-libas if they were in an archive file. That means object files between them are linked only when they're needed to resolve undefined symbols ๐ฆ. These are useful when you wanna link object files only when needed but also wanna avoid the overhead of runningar(3)โ efficiency queen ๐ .--staticโ do not link against shared libraries. Simple.--sysroot=dirโ sets the target system root directory to dir ๐.--traceโ prints the name of each input file ๐.--undefined-glob=patternโ synonym for--undefined, except--undefined-globtakes a glob pattern instead of just a single symbol name โจ.--undefined-version,--no-undefined-versionโ by default, mold warns on a symbol specified by a version script or by--export-dynamic-symbolif it's not defined. You can silence the warning with--undefined-version๐ซถ.--unique=patternโ don't merge input sections that match the given glob pattern pattern ๐.--unresolved-symbols=[ report-all | ignore-all | ignore-in-object-files | ignore-in-shared-libs ]โ how to handle undefined symbols. That's the whole vibe check ๐.--version-script=fileโ reads a version script from file. If file doesn't exist in the current directory, it's searched from the library search paths for the sake of compatibility with GNU ld ๐.-w,--no-warningsโ suppresses warnings and cancels--fatal-warnings๐คซ.--warn-common,--no-warn-commonโ warns about common symbols ๐.--warn-onceโ only warns once for each undefined symbol, instead of warning for each relocation referring to an undefined symbol. Life saver ๐ญ.--warn-unresolved-symbols,--error-unresolved-symbolsโ normally the linker reports an error for unresolved symbols.--warn-unresolved-symbolsturns that into a warning, and--error-unresolved-symbolsrestores the default behavior ๐.--whole-archive,--no-whole-archiveโ when archive files (.afiles) are given to the linker, only object files needed to resolve undefined symbols are extracted from them and linked to an output file.--whole-archivechanges that behavior for subsequent archives, so the linker extracts all object files and links them to the output ๐ . For example, if you're creating a shared object file and you want all archive members included in the output, you should pass--whole-archive. And--no-whole-archiverestores the default behavior for subsequent archives โจ.--wrap=symbolโ makes symbol resolve to__wrap_symbol. The original symbol can be resolved as__real_symbol๐ฆ. Typically used for wrapping an existing function.-z cet-report=[ warning | error | none ]โ Intel Control-flow Enforcement Technology (CET) is a new x86 feature available since Tiger Lake (released in 2020) ๐. It defines new instructions to harden security and protect programs from control hijacking attacks. You can tell the compiler to use the feature by specifying the-fcf-protectionflag ๐ฅ.
The -z cet-report flag makes sure all object files were compiled with a correct -fcf-protection flag. If warning or error is given, mold prints out a warning or an error message if an object file was not compiled with the compiler flag ๐ค.
mold looks for the GNU_PROPERTY_X86_FEATURE_1_IBT bit and the GNU_PROPERTY_X86_FEATURE_1_SHSTK bit in the .note.gnu.property section to determine whether an object file was compiled with -fcf-protection ๐.
-z now,-z lazyโ by default, functions referring to other ELF modules are resolved by the dynamic linker when they're called for the first time.-z nowmarks an executable or shared library file so that all dynamic symbols are resolved when the file is loaded into memory โจ.-z lazyrestores the default behavior ๐ .-z originโ marks the object as requiring immediate$ORIGINprocessing at runtime ๐ธ.-z ibtโ turns on theGNU_PROPERTY_X86_FEATURE_1_IBTbit in the.note.gnu.propertysection to indicate that the output uses IBT-enabled PLT ๐. This option implies-z ibtplt.-z ibtpltโ generates an Intel Branch Tracking (IBT)-enabled PLT, which is the default on x86-64. Yeah, this is the default ๐.
okay continuing our -z era, bestie, we're so back ๐
-z execstack,-z noexecstackโ real talk, by default the pages for the stack area (aka the pages where your local variables live) are not executable, and that's for security reasons, periodt.-z execstackmakes them executable.-z noexecstackputs the default behavior back. ๐ซถ-z keep-text-section-prefix,-z nokeep-text-section-prefixโ keeps.text.hot,.text.unknown,.text.unlikely,.text.startup, and.text.exitas separate sections in the final binary instead of merging them all into.text. like let them have their own identity bestie โจ-z rodynamicโ makes the.dynamicsection read-only. ๐-z relro,-z norelroโ okay so some sections like.dynamiconly have to be writable while a module is being loaded into memory. Once the dynamic linker finishes its job, nobody's gonna mutate those sections ever again. As a security mitigation, it's preferred to make those segments read-only while the program runs.
-z relro puts those sections into a special segment called relro. The dynamic linker makes a relro segment read-only after it finishes its job.
By default, mold generates a relro segment. -z norelro disables the feature. ๐
-z sectionheader,-z nosectionheaderโ-z nosectionheadertells the linker to omit the section header. By default, the linker does not omit the section header. that's the whole vibe ๐-z separate-loadable-segments,-z separate-code,-z noseparate-codeโ if one memory page contains multiple segments, the page protection bits get set so that the needed attributes (writable or executable) are satisfied for all the segments. This usually happens at a boundary of two segments with two different attributes.
separate-loadable-segments adds paddings between segments with different attributes so they don't share the same page.
separate-code adds paddings only between executable and non-executable segments.
noseparate-code adds no paddings between segments at all. This is the default. ๐
-z defs,-z undefsโ reports undefined symbols (even with--shared). no cap, it will tell you ๐-z shstkโ enforces shadow stack by turning theGNU_PROPERTY_X86_FEATURE_1_SHSTKbit in the.note.gnu.propertyoutput section. Shadow stack is part of Intel Control-flow Enforcement Technology (CET), which is available since Tiger Lake (2020). iconic hardware era โญ-z start-stop-visibility=[ hidden | protected ]โ if a section name is valid as a C identifier (i.e. it matches/^[_a-zA-Z][_a-zA-Z0-9]*$/), mold creates__start_SECNAMEand__stop_SECNAMEsymbols to mark the beginning and end of the section, where SECNAME is the section name.
You can make these marker symbols visible from other ELF modules by passing -z start-stop-visibility=protected. Default is hidden. ๐ฆ
-z text,-z notext,-z textoffโ mold by default reports an error if dynamic relocations are created in read-only sections. If-z notextor-z textoffare given, mold creates such dynamic relocations without reporting an error.-z textrestores the default behavior. choose your fighter ๐ญ-z max-page-size=numberโ some CPU ISAs support multiple memory page sizes. This option specifies the maximum page size that an output binary can run on. In general, binaries built for a larger page size can run on a system with a smaller page size, but not vice versa. The default value is4 KiBfor i386, x86-64, and RISC-V, and64 KiBfor ARM64. math girlie behavior ๐ง-z nodefaultlibโ makes the dynamic loader ignore default search paths.-z nodeleteโ marks the DSO non-deletable at runtime.-z nodlopenโ marks the DSO not available todlopen(3). This option makes it possible for the linker to optimize thread-local variable accesses by rewriting instructions for some targets. โจ-z nodumpโ marks the DSO not available todldump(3).-z nocopyrelocโ do not create copy relocations.-z initfirstโ marks the DSO to be initialized first at runtime. main character energy fr fr ๐-z interposeโ marks the object to interpose all DSOs but the executable.-(,-),-EL,-Onumber,--dc,--dp,--end-group,--no-add-needed,--no-copy-dt-needed-entries,--nostdlib,--rpath-link=Ar dir,--sort-common,--sort-section,--start-group,--warn-constructors,--warn-once,--fix-cortex-a53-835769,--fix-cortex-a53-843419,-z combreloc,-z common-page-size,-z nocombrelocโ Ignored. ๐ that's it, that's the whole entry, they're just there vibing.
๐ธ ENVIRONMENT VARIABLES ๐ธ
MOLD_JOBSโ if this variable is set to1, only one mold process will run at a time. If a new mold process is initiated while another is already active, the new process will wait until the active one completes before starting. ๐ซถ
The primary reason for this environment variable is to minimize peak memory usage. Since mold is designed to operate with high parallelism, running multiple mold instances simultaneously may not be beneficial. If you execute N instances of mold concurrently, it could require N times the time and N times the memory. On the other hand, running them one after the other might still take N times longer, but the peak memory usage would be the same as running just a single instance.
If your build system invokes multiple linker processes simultaneously and some of them often get killed due to out-of-memory errors, you might consider setting this environment variable to 1 to see if it addresses the OOM issue. ๐ง
Currently, any value other than 1 is silently ignored. (yes, silently, it's not gonna tell you ๐)
MOLD_DEBUGโ if this variable is set to a non-empty string, mold embeds its command-line options in the output file's.commentsection. little diary entry, love that for us ๐MOLD_REPROโ setting this variable to a non-empty string has the same effect as passing the--reprooption. โจ
๐ฆ SEE ALSO ๐ฆ
gold(1), ld(1), elf(5), ld.so(8)
the whole friend group honestly ๐
๐ AUTHOR ๐
Rui Ueyama ruiu@cs.stanford.edu
๐ BUGS ๐
Report bugs to https://github.com/rui314/mold/issues.
like actually report them, don't just suffer in silence bestie ๐ญ
aaand that's the whole page, we ate, no crumbs ๐ this icon of a manpage is from October 2026, section MOLD(1) โ go forth and link things, ily, bye ๐ โจ
๐ฆ where this page comes from
- arch rolling: mold 3.0.0-4 ยท MIT
- nixpkgs unstable: mold-unwrapped 3.0.0
- ๐ girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms