Skip to main content

rucc_sysroot/
argv.rs

1//! The linker command line, as a function of the target and the sysroot and nothing else.
2//!
3//! Design: `spec/cross-compile/11-linking.md` section 11.3, which is a list of eight things a
4//! system linker gets right by default on the machine it came with and gets wrong when it is asked
5//! to link for another one.
6//!
7//! # Why this is a pure function
8//!
9//! Section 11.3 ends with the shape: `(tuple, sysroot, options) -> argv`, no environment reads, no
10//! filesystem probing. That is not tidiness, it is what makes the highest consequence code in the
11//! driver testable. A link line is the last thing that touches a binary and the first thing that
12//! can quietly ruin it, and a function that reads the machine it runs on can only be tested on the
13//! machine it runs on. This one is tested for every target in the table from any host, and
14//! `tests/link-lines` is what it produced for each of them when it was last changed.
15//!
16//! The mirror of that rule is the one [`crate::search`] enforces for headers: nothing from the host
17//! reaches the line. No `/usr/lib`, no `/lib64`, no `LIBRARY_PATH`, and no start file found by
18//! looking around. Every path here is either under the sysroot or something the user wrote on the
19//! command line themselves, and `nothing_on_the_line_comes_from_the_host` is that as a test.
20//!
21//! # What is not decided here
22//!
23//! Which linker runs. `spec/cross-compile/11-linking.md` section 11.2 picks one per format and the
24//! driver spawns it, and the arguments below are the ones `ld`, `ld.lld` and `mold` all read the
25//! same way. That is a real constraint rather than an aspiration: `-static-pie` is a compiler driver
26//! flag that none of the three linkers has, so the mode that means it is spelled out here as the
27//! three flags a linker does understand.
28//!
29//! # The two formats that have a line
30//!
31//! ELF, and PE in mingw-w64's environment. Both are written in the GNU style, which is the same
32//! syntax for the inputs and a different set of flags, so they share everything below that is about
33//! what has to be linked and differ in what is about the image. The PE line is GNU ld's PE port and
34//! `ld.lld` in its MinGW mode, which read each other's arguments for exactly this reason.
35//!
36//! Mach-O and the MSVC ABI are refused rather than approximated. `ld64` wants a platform version
37//! load command and a `-syslibroot`, `lld-link` wants `/MACHINE:` and a `/DEFAULTLIB:` set out of an
38//! SDK that cannot be redistributed, and neither is a different spelling of what is below.
39//! [`Unsupported`] says which by name, which is a better answer than a line that looks plausible and
40//! produces nothing that runs.
41
42use std::fmt;
43use std::path::{Path, PathBuf};
44
45use rucc_tuple::{Arch, DataModel, Endian, Env, ObjectFormat, TargetTuple};
46
47use crate::layout::Sysroot;
48use crate::link::{BUILTINS, Libc, LinkLine, LinkMode, libc, loader};
49
50/// One input to the link, in the position the user wrote it.
51///
52/// Link order is semantic: an archive is searched for what is undefined at the moment the linker
53/// reaches it, so a library named before the object that needs it contributes nothing. That is why
54/// this is one ordered list rather than a list of objects and a list of libraries, which is a shape
55/// that cannot represent what the user typed.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub enum Item {
58    /// A file, which is an object this compilation produced or one named on the command line.
59    File(PathBuf),
60    /// `-l<name>`, which the linker resolves against the search path.
61    Library(String),
62}
63
64/// What the driver knows that the line needs, beyond the target and the sysroot.
65///
66/// A struct because most of it is empty in the common case, and because a function with nine
67/// positional parameters of which seven are usually a default is a function somebody calls wrong.
68#[derive(Debug, Clone, Default)]
69pub struct Invocation<'a> {
70    /// The objects and libraries, in the order they were written.
71    pub inputs: &'a [Item],
72    /// `-o`. Empty means the linker's own default, which is what a caller testing a line wants.
73    pub output: Option<&'a Path>,
74    /// How the program is linked, which decides the start file and four of the flags.
75    pub mode: LinkMode,
76    /// `-L`, in the order given. The user's own, and they come before ours, because somebody who
77    /// passed `-L` meant it to win.
78    pub search: &'a [PathBuf],
79    /// `-Wl,` and `-Xlinker`, passed through untouched and last, so that anything the user said
80    /// wins over anything decided here.
81    pub passthrough: &'a [String],
82    /// `-nostartfiles`, which leaves `crt1.o`, `crti.o` and `crtn.o` off.
83    pub no_startfiles: bool,
84    /// `-nodefaultlibs`, which leaves the libc and our runtime off.
85    pub no_defaultlibs: bool,
86    /// `-fno-builtins-lib`, which leaves our own runtime off and keeps the libc.
87    ///
88    /// It means something narrower here than it does on a native link. There it leaves ours off so
89    /// that the machine's `libgcc` answers for the wide arithmetic instead, and there is no `libgcc`
90    /// in a generated sysroot, so here it leaves those names undefined. Which is what somebody
91    /// passing it with a `-l` of their own is asking for, and the link says so by name if they are
92    /// not.
93    pub no_builtins_lib: bool,
94    /// `-rdynamic`, which puts every symbol in the dynamic table so a program can look itself up.
95    pub export_dynamic: bool,
96    /// `-s`, which drops the symbol table.
97    pub strip: bool,
98}
99
100/// A target, or a combination of a target and a mode, that has no line here.
101///
102/// Four variants and they are different kinds of answer. A format is not supported yet and will be.
103/// The MSVC ABI is waiting on something that is not code. A static glibc link is not a thing this
104/// scheme can produce at all. The distinction matters to somebody reading the message, because only
105/// some of them are worth waiting for.
106#[derive(Debug, Clone, PartialEq, Eq)]
107pub enum Unsupported {
108    /// The target's object format is neither ELF nor PE, and the linker for it wants a different
109    /// line rather than a different spelling of this one.
110    Format {
111        /// The target that was asked for.
112        target: String,
113        /// Its object format, in the spelling `--print-config` uses.
114        format: &'static str,
115    },
116    /// A Windows target in Microsoft's ABI rather than mingw-w64's.
117    ///
118    /// Refused for two reasons and the second one is the one that matters. `lld-link` takes a
119    /// different command line rather than a different set of flags: `/MACHINE:`, `/SUBSYSTEM:`,
120    /// `/DEFAULTLIB:` and a response file, which is its own work. And the import libraries a program
121    /// in that ABI links against come from the Windows SDK and the universal CRT, which
122    /// `spec/cross-compile/08-sysroots.md` section 8.6 says cannot be redistributed, so there is
123    /// nothing to produce on this side and a user has to point at an installed one themselves.
124    MsvcAbi {
125        /// The target that was asked for.
126        target: String,
127    },
128    /// A PE target whose architecture has no machine type among the ones a PE linker writes.
129    ///
130    /// Unreachable through the target table, which has three mingw-w64 rows and an ARM64EC one that
131    /// the MSVC ABI refuses first. It is a variant rather than a panic because the table is data and
132    /// a row added to it should produce a sentence rather than a crash.
133    Machine {
134        /// The target that was asked for.
135        target: String,
136    },
137    /// A static link against a libc that is a stub.
138    ///
139    /// `spec/cross-compile/09-libc-stubs.md` section 9.1 is the reason: a stub carries the names a
140    /// library exports and none of the code behind them, which is everything a dynamic link needs
141    /// and nothing a static one does. glibc's own `libc.a` is several megabytes of objects that
142    /// cannot be synthesized from a description of an interface, so this combination is refused
143    /// here rather than failing later with several thousand undefined symbols.
144    ///
145    /// Every [`crate::link::Libc::Stub`] target, which is glibc and also bionic, the BSDs and
146    /// illumos. musl is the exception rather than the rule here, because musl is the one whose libc
147    /// we build from source.
148    StaticStub {
149        /// The target that was asked for.
150        target: String,
151    },
152}
153
154impl fmt::Display for Unsupported {
155    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
156        match self {
157            Unsupported::Format { target, format } => write!(
158                f,
159                "there is no cross link line for {target} yet, because its object format is \
160                 {format} and that linker takes a different line rather than a different spelling \
161                 of this one"
162            ),
163            Unsupported::MsvcAbi { target } => write!(
164                f,
165                "there is no cross link line for {target}, because it is Microsoft's ABI: the \
166                 linker for it takes a different command line and the import libraries a program \
167                 there links against come from the Windows SDK, which cannot be redistributed. \
168                 Build for the mingw-w64 environment instead, which needs nothing installed, or \
169                 pass --sysroot=<dir> naming an SDK you have"
170            ),
171            Unsupported::Machine { target } => write!(
172                f,
173                "there is no PE machine type for {target}, so there is nothing to write after -m \
174                 and a linker would guess the machine from the first object it read"
175            ),
176            Unsupported::StaticStub { target } => write!(
177                f,
178                "{target} cannot be linked statically against a generated sysroot, because its \
179                 libc there is a stub: it carries the names the platform's libc exports and none of \
180                 the code behind them, which is what a dynamic link reads and not what a static one \
181                 needs. Link it dynamically, or use a musl target, which ships a real libc.a"
182            ),
183        }
184    }
185}
186
187impl std::error::Error for Unsupported {}
188
189/// The whole linker command line for this target, not counting the linker itself.
190///
191/// Section 11.3's eight items, in the order a linker wants them:
192///
193/// 1. `-m`, the output format, because a linker built for more than one machine guesses from its
194///    first input otherwise and a link of no objects has nothing to guess from.
195/// 2. `--sysroot`, and every `-L` rooted inside it.
196/// 3. `-dynamic-linker`, the one string on the line that describes the target's filesystem rather
197///    than ours.
198/// 4. The start files, by absolute path, in the order the two nested pairs need.
199/// 5. The default libraries, which are ours rather than the host's.
200/// 6. `librucc_builtins.a` for the target, which [`LinkLine`] puts after the libc.
201/// 7. No host paths at all.
202/// 8. The format's own extras, which on ELF is the hardening and reproducibility set below and on
203///    PE is the subsystem, the address space layout flags and the header timestamp.
204///
205/// Two formats reach a line here and the difference between them is the flags rather than the shape.
206/// Both are written in the GNU style, which is what `ld`, `ld.lld` and `ld.lld` in its MinGW mode all
207/// read, so the inputs, the `-L` directories and the passthrough are assembled once for both rather
208/// than twice.
209///
210/// # Errors
211///
212/// [`Unsupported::Format`] for a target whose object format is neither ELF nor PE,
213/// [`Unsupported::MsvcAbi`] for a Windows target in Microsoft's ABI,
214/// [`Unsupported::Machine`] for a PE target with no machine type, and
215/// [`Unsupported::StaticStub`] for a static link against a libc that is a stub.
216pub fn argv(
217    target: TargetTuple,
218    sysroot: &Sysroot,
219    options: &Invocation<'_>,
220) -> Result<Vec<String>, Unsupported> {
221    let format = target.object_format();
222    match format {
223        ObjectFormat::Elf => elf(target, sysroot, options),
224        // mingw-w64 rather than every COFF target, because the MSVC ABI is a different linker with a
225        // different argument syntax and an import library set we are not allowed to ship.
226        ObjectFormat::Coff if target.env() == Env::Gnu => coff(target, sysroot, options),
227        ObjectFormat::Coff => Err(Unsupported::MsvcAbi { target: target.to_canonical_string() }),
228        _ => Err(Unsupported::Format {
229            target: target.to_canonical_string(),
230            format: format.as_str(),
231        }),
232    }
233}
234
235/// The line for an ELF target.
236fn elf(
237    target: TargetTuple,
238    sysroot: &Sysroot,
239    options: &Invocation<'_>,
240) -> Result<Vec<String>, Unsupported> {
241    let statically = matches!(options.mode, LinkMode::Static | LinkMode::StaticPie);
242    if statically && libc(target) == Libc::Stub {
243        return Err(Unsupported::StaticStub { target: target.to_canonical_string() });
244    }
245
246    let mut args = output(options);
247    if let Some(name) = emulation(target) {
248        args.push("-m".to_owned());
249        args.push(name.to_owned());
250    }
251    args.push(sysroot_flag(sysroot));
252
253    args.extend(mode_flags(target, options.mode));
254    args.extend(hardening());
255    if options.export_dynamic {
256        args.push("--export-dynamic".to_owned());
257    }
258    if options.strip {
259        args.push("-s".to_owned());
260    }
261
262    args.extend(body(sysroot, options));
263    Ok(args)
264}
265
266/// The line for a mingw-w64 target.
267///
268/// The same eight items as the ELF line and four of them answered differently. The emulation is a PE
269/// one. There is no dynamic linker, because a PE image names no interpreter: the loader is part of
270/// the operating system and finds a DLL by name at load time rather than by a path written into the
271/// program. There is no `-pie` and no `-no-pie`, because every PE image carries a relocation table
272/// and may be placed anywhere, so the question the two flags answer does not exist here and what is
273/// left of it is whether the loader is asked to use that freedom, which is `--dynamicbase`. And
274/// `-static` says something narrower than it does on ELF, which is the note on
275/// [`crate::link::Libc::Import`].
276///
277/// So the five modes are three lines here, and the recorded file shows two pairs of identical
278/// blocks. That is the answer rather than a gap: a position independent executable and one that is
279/// not are the same image on this format, so a build system that passes `-static-pie` or `-no-pie`
280/// gets what it asked for and loses nothing by the flag having nowhere to go.
281///
282/// The subsystem is named rather than left to the linker. Both linkers default it from the entry
283/// point they find, which means a program with a `WinMain` in it silently becomes a GUI program, and
284/// a cross link deciding anything from what it happens to find in the inputs is the failure mode
285/// section 11.3 is about. A user who wants the other one passes `-Wl,--subsystem,windows`, which
286/// goes on last and wins.
287fn coff(
288    target: TargetTuple,
289    sysroot: &Sysroot,
290    options: &Invocation<'_>,
291) -> Result<Vec<String>, Unsupported> {
292    let Some(machine) = pe_machine(target) else {
293        return Err(Unsupported::Machine { target: target.to_canonical_string() });
294    };
295
296    let mut args = output(options);
297    args.push("-m".to_owned());
298    args.push(machine.to_owned());
299    args.push(sysroot_flag(sysroot));
300
301    if options.mode == LinkMode::Shared {
302        args.push("-shared".to_owned());
303    } else {
304        args.push("--subsystem".to_owned());
305        args.push("console".to_owned());
306    }
307    if matches!(options.mode, LinkMode::Static | LinkMode::StaticPie) {
308        args.push("-static".to_owned());
309    }
310    args.extend(pe_hardening(target));
311    // The PE counterpart of `--export-dynamic`, and a different word rather than a different
312    // default: a Windows image exports what its own export table names, and `-rdynamic` asks for
313    // every symbol to be in there so that a program can look itself up.
314    if options.export_dynamic {
315        args.push("--export-all-symbols".to_owned());
316    }
317    if options.strip {
318        args.push("-s".to_owned());
319    }
320
321    args.extend(body(sysroot, options));
322    Ok(args)
323}
324
325/// `-o`, or nothing, which is what a caller testing a line wants.
326fn output(options: &Invocation<'_>) -> Vec<String> {
327    match options.output {
328        Some(path) => vec!["-o".to_owned(), path.display().to_string()],
329        None => Vec::new(),
330    }
331}
332
333/// `--sysroot`.
334///
335/// Not because anything below needs it, since every path this function writes is absolute and
336/// complete, but because a linker script inside the sysroot resolves the names in it against this.
337/// On a real distribution `libc.so` is such a script, and without this the names in one found under
338/// a sysroot are looked for on the host.
339fn sysroot_flag(sysroot: &Sysroot) -> String {
340    format!("--sysroot={}", sysroot.root().display())
341}
342
343/// Everything after the flags: the start files, the search directories, the inputs, the libraries
344/// and whatever the user told the linker directly.
345///
346/// One function for both formats, because none of this differs between them. What has to be linked
347/// is [`LinkLine`]'s answer and it is already a per target one, `-L` and `-l` are spelled the same
348/// by every linker that reads a GNU command line, and the passthrough is last in both so that
349/// anything the user said wins over anything decided here.
350fn body(sysroot: &Sysroot, options: &Invocation<'_>) -> Vec<String> {
351    let mut args = Vec::new();
352    let line = LinkLine::for_target(sysroot, options.mode);
353    if !options.no_startfiles {
354        args.extend(shown(&line.start));
355    }
356
357    // The user's search directories first and ours second, which is the order they are written in a
358    // native link too, so that `-L` in front of a sysroot behaves the way somebody passing it
359    // expects. And then nothing else: step 7 is that there is no host directory here at all.
360    for dir in options.search {
361        args.push(format!("-L{}", dir.display()));
362    }
363    args.push(format!("-L{}", sysroot.lib().display()));
364
365    for input in options.inputs {
366        match input {
367            Item::File(path) => args.push(path.display().to_string()),
368            Item::Library(name) => args.push(format!("-l{name}")),
369        }
370    }
371
372    if !options.no_defaultlibs {
373        args.extend(shown(&libraries(&line, options)));
374    }
375    if !options.no_startfiles {
376        args.extend(shown(&line.end));
377    }
378
379    args.extend(options.passthrough.iter().cloned());
380    args
381}
382
383/// The libraries, with ours left off if that is what was asked for.
384///
385/// By the one name in [`BUILTINS`] rather than by position, because the position is
386/// [`LinkLine`]'s business and a caller that knew it would be a second place to fix the day the
387/// order changes.
388fn libraries(line: &LinkLine, options: &Invocation<'_>) -> Vec<PathBuf> {
389    let mut libraries = line.libraries.clone();
390    if options.no_builtins_lib {
391        libraries.retain(|path| path.file_name().is_none_or(|name| name != BUILTINS));
392    }
393    libraries
394}
395
396/// The flags that say how the result is linked, and the loader when there is one.
397///
398/// `-static-pie` is not among them and that is the point of this function being separate. It is a
399/// compiler driver flag, and the three linkers this line has to suit take three flags instead: the
400/// link is static, the result is position independent, and there is explicitly no interpreter,
401/// because a static binary that names one gets one mapped and then relocates itself twice.
402fn mode_flags(target: TargetTuple, mode: LinkMode) -> Vec<String> {
403    let mut args = Vec::new();
404    match mode {
405        LinkMode::Static => args.push("-static".to_owned()),
406        LinkMode::StaticPie => {
407            args.push("-static".to_owned());
408            args.push("-pie".to_owned());
409            args.push("--no-dynamic-linker".to_owned());
410        }
411        LinkMode::Dynamic => args.push("-pie".to_owned()),
412        LinkMode::DynamicNoPie => args.push("-no-pie".to_owned()),
413        LinkMode::Shared => args.push("-shared".to_owned()),
414    }
415    // A shared object is started by whatever loads it, so it names no interpreter even though it is
416    // linked dynamically. That is the one place `is_dynamic` is not the condition.
417    if matches!(mode, LinkMode::Dynamic | LinkMode::DynamicNoPie) {
418        if let Some(path) = loader(target) {
419            args.push("-dynamic-linker".to_owned());
420            args.push(path.to_owned());
421        }
422    }
423    args
424}
425
426/// The flags that are on every ELF line, whatever the target and whatever the mode.
427///
428/// Five answers to defaults nobody wants. An executable stack is a target default several linkers
429/// still assume when no input object says otherwise. `relro` and `now` make the relocation tables
430/// read only before `main` runs, which is the cheapest hardening there is. The unwind table header
431/// is needed by every crash handler and by `backtrace`, in a C program with no exceptions in it.
432/// The GNU hash table is the one a loader from this century reads.
433///
434/// `--build-id=none` is the reproducibility one and it is the interesting one.
435/// `spec/cross-compile/11-linking.md` section 11.4 wants byte identical output from two hosts, and a
436/// build id computed over the inputs carries their absolute paths into the binary. A deterministic
437/// one would also do, and it is a linker's own idea of deterministic rather than ours, so the
438/// absence of one is the answer that holds on all three linkers.
439fn hardening() -> Vec<String> {
440    [
441        "--eh-frame-hdr",
442        "--hash-style=gnu",
443        "-z",
444        "relro",
445        "-z",
446        "now",
447        "-z",
448        "noexecstack",
449        "--build-id=none",
450    ]
451    .iter()
452    .map(|flag| (*flag).to_owned())
453    .collect()
454}
455
456/// The flags that are on every PE line, whatever the target and whatever the mode.
457///
458/// The same job as [`hardening`] above and a different list, because the two formats protect
459/// themselves with different mechanisms. `--dynamicbase` is the PE counterpart of a position
460/// independent executable: the image carries a relocation table either way, and this is the bit in
461/// the header that tells the loader it may use it rather than placing the image where it asks. It is
462/// not a default in GNU ld's PE port, which is the reason it is written here.
463/// `--high-entropy-va` goes with it on a 64-bit target, where it widens the address space the loader
464/// picks from, and means nothing on a 32-bit one. `--nxcompat` is the `noexecstack` of this format.
465///
466/// `--no-insert-timestamp` is the reproducibility one and it is this format's version of
467/// `--build-id=none`. A PE header carries the time it was linked, `spec/cross-compile/11-linking.md`
468/// section 11.4 names it as one of the four ways byte identical output is lost, and a link that
469/// stamps the current second produces a different file every time it runs on one machine, let alone
470/// on two.
471fn pe_hardening(target: TargetTuple) -> Vec<String> {
472    let mut args = vec!["--dynamicbase".to_owned(), "--nxcompat".to_owned()];
473    if target.pointer_width() == 64 {
474        args.push("--high-entropy-va".to_owned());
475    }
476    args.push("--no-insert-timestamp".to_owned());
477    args
478}
479
480/// Which machine a PE linker is to write for, in the name `-m` knows it by.
481///
482/// A different table from [`emulation`] and a much shorter one, because PE has four machine types
483/// that matter against ELF's dozen formats: there is no byte order to spell, since every Windows port
484/// is little endian, and no data model to spell either, since each machine type fixes one.
485///
486/// The names are GNU ld's PE emulations, which `ld.lld` accepts in its MinGW mode for exactly this
487/// reason. `i386pep` is the 64-bit x86 one and `i386pe` the 32-bit one, and the `p` that tells them
488/// apart is PE32+ rather than anything about the architecture, which is a piece of 1990s naming that
489/// nothing can be done about now.
490///
491/// [`None`] for a Windows target in Microsoft's ABI, which is not a gap. These names are GNU ld's
492/// and `lld-link` has never read one: it takes `/MACHINE:X64`, in an argument syntax where the rest
493/// of the line is different too, so there is nothing for a shared table to hold. ARM64EC is
494/// [`None`] for that reason first and for a second one:
495/// `spec/cross-compile/09-libc-stubs.md` refuses its import libraries as well, because an export in
496/// that ABI is a mangled name and a library written the way the others are written links and then
497/// fails to load.
498#[must_use]
499pub fn pe_machine(target: TargetTuple) -> Option<&'static str> {
500    if target.object_format() != ObjectFormat::Coff || target.env() != Env::Gnu {
501        return None;
502    }
503    Some(match target.arch() {
504        Arch::X86_64 => "i386pep",
505        Arch::X86 => "i386pe",
506        Arch::Aarch64 => "arm64pe",
507        Arch::Arm => "thumb2pe",
508        _ => return None,
509    })
510}
511
512/// Paths as the line carries them.
513fn shown(paths: &[PathBuf]) -> Vec<String> {
514    paths.iter().map(|path| path.display().to_string()).collect()
515}
516
517/// Which of the formats one linker can write is meant, in the name `-m` knows it by.
518///
519/// The same names in `ld`, `ld.lld` and `mold`, which is why this is one table rather than one per
520/// linker. They are not derivable from the architecture: three of them spell the byte order into
521/// the name, two spell the data model, and the narrow modes of a 64-bit architecture are a different
522/// format rather than a flag on one.
523///
524/// [`None`] for a target whose format is not ELF, which is every one of them rather than wasm alone.
525/// An emulation is an ELF idea: `ld64` takes an architecture and a platform version, and the COFF
526/// linkers take a machine, so a Mach-O target that answered `aarch64linux` here would be answering a
527/// question nobody asked it in a word its linker does not know. Nothing reaches this through
528/// [`argv`], which refuses a non-ELF target before asking, and the answer still has to be right for
529/// the recorded files and for anybody calling it directly.
530#[must_use]
531pub fn emulation(target: TargetTuple) -> Option<&'static str> {
532    if target.object_format() != ObjectFormat::Elf {
533        return None;
534    }
535    let narrow = target.data_model() == DataModel::Ilp32On64;
536    let little = target.endian() == Endian::Little;
537    Some(match target.arch() {
538        Arch::X86_64 if narrow => "elf32_x86_64",
539        Arch::X86_64 => "elf_x86_64",
540        Arch::X86 => "elf_i386",
541        Arch::Aarch64 | Arch::Arm64Ec => match (little, narrow) {
542            (true, false) => "aarch64linux",
543            (true, true) => "aarch64linux32",
544            (false, false) => "aarch64linuxb",
545            (false, true) => "aarch64linux32b",
546        },
547        Arch::Arm if little => "armelf_linux_eabi",
548        Arch::Arm => "armelfb_linux_eabi",
549        Arch::Riscv64 if little => "elf64lriscv",
550        Arch::Riscv64 => "elf64briscv",
551        Arch::Riscv32 if little => "elf32lriscv",
552        Arch::Riscv32 => "elf32briscv",
553        // 32-bit z/Architecture is `elf32_s390` and is not a target here, so there is one row.
554        Arch::S390x => "elf64_s390",
555        Arch::PowerPc64 if little => "elf64lppc",
556        Arch::PowerPc64 => "elf64ppc",
557        Arch::LoongArch64 => "elf64loongarch",
558        // Unreachable, because a wasm target's format is wasm and the check above has already
559        // returned. It is here because the match is exhaustive and a wasm emulation name does not
560        // exist to write in it.
561        Arch::Wasm32 => return None,
562    })
563}
564
565#[cfg(test)]
566mod tests {
567    use std::path::Path;
568
569    use rucc_tuple::TargetTuple;
570
571    use super::{Invocation, Item, Unsupported, argv, emulation, pe_machine};
572    use crate::layout::Sysroot;
573    use crate::link::LinkMode;
574
575    fn target(spelling: &str) -> TargetTuple {
576        spelling.parse().expect("a tuple the table knows")
577    }
578
579    fn sysroot(spelling: &str) -> Sysroot {
580        Sysroot::in_cache(Path::new("/cache"), target(spelling))
581    }
582
583    fn line(spelling: &str, mode: LinkMode) -> Vec<String> {
584        let one = [Item::File(Path::new("main.o").to_path_buf())];
585        let options = Invocation {
586            inputs: &one,
587            output: Some(Path::new("main")),
588            mode,
589            ..Invocation::default()
590        };
591        argv(target(spelling), &sysroot(spelling), &options).expect("a line")
592    }
593
594    #[test]
595    fn nothing_on_the_line_comes_from_the_host() {
596        // The mirror of the header search rule, and the property `spec/cross-compile/02-the-goal.md`
597        // claim 5 rests on. Every path is under the sysroot or is what the caller wrote.
598        for spelling in ["aarch64-linux-musl", "x86_64-linux-gnu", "riscv64-linux-musl"] {
599            for mode in [LinkMode::Dynamic, LinkMode::DynamicNoPie, LinkMode::Shared] {
600                for arg in line(spelling, mode) {
601                    let host = ["/usr/lib", "/usr/local", "/lib64/", "/lib/x86_64"]
602                        .iter()
603                        .any(|bad| arg.starts_with(bad));
604                    // The loader is the one absolute path that is not a path on this machine. It is
605                    // read by the kernel on the target, which is why it is written in full.
606                    let is_loader = arg.contains("ld-musl") || arg.contains("ld-linux");
607                    assert!(!host || is_loader, "{spelling} {mode:?} {arg}");
608                }
609            }
610        }
611    }
612
613    #[test]
614    fn every_file_of_ours_is_under_the_sysroot() {
615        let spelling = "aarch64-linux-musl";
616        // The prefix as this host spells it rather than as a literal, because the question is which
617        // directory these files are in and a Windows separator is a backslash.
618        let root = sysroot(spelling).root().display().to_string();
619        for arg in line(spelling, LinkMode::Static) {
620            // The caller's own `main.o` is relative and is theirs. Everything this function named
621            // is absolute, and every absolute file on the line is under the sysroot.
622            let ours = arg.starts_with('/') && (arg.ends_with(".o") || arg.ends_with(".a"));
623            assert!(!ours || arg.starts_with(&root), "{arg}");
624        }
625    }
626
627    #[test]
628    fn the_static_line_names_no_loader_because_nothing_will_start_it() {
629        let args = line("aarch64-linux-musl", LinkMode::Static);
630        assert!(args.contains(&"-static".to_owned()), "{args:?}");
631        assert!(!args.contains(&"-dynamic-linker".to_owned()), "{args:?}");
632    }
633
634    #[test]
635    fn a_static_position_independent_link_is_three_flags_and_not_the_driver_one() {
636        // `-static-pie` is a gcc flag and none of the three linkers has it, which is the whole
637        // reason the mode is spelled out rather than passed through.
638        let args = line("x86_64-linux-musl", LinkMode::StaticPie);
639        assert!(!args.iter().any(|arg| arg == "-static-pie"), "{args:?}");
640        for flag in ["-static", "-pie", "--no-dynamic-linker"] {
641            assert!(args.contains(&flag.to_owned()), "{flag} missing from {args:?}");
642        }
643    }
644
645    #[test]
646    fn a_dynamic_program_names_the_loader_that_will_start_it_and_a_shared_object_does_not() {
647        let program = line("x86_64-linux-gnu", LinkMode::Dynamic);
648        let at = program.iter().position(|arg| arg == "-dynamic-linker").expect("the flag");
649        assert_eq!(program[at + 1], "/lib64/ld-linux-x86-64.so.2");
650        let library = line("x86_64-linux-gnu", LinkMode::Shared);
651        assert!(!library.contains(&"-dynamic-linker".to_owned()), "{library:?}");
652        assert!(library.contains(&"-shared".to_owned()), "{library:?}");
653    }
654
655    #[test]
656    fn the_start_file_of_a_program_that_moves_is_not_the_one_of_a_program_that_does_not() {
657        let named = |mode| {
658            line("x86_64-linux-gnu", mode)
659                .iter()
660                .filter_map(|arg| {
661                    Path::new(arg).file_name().map(|n| n.to_string_lossy().into_owned())
662                })
663                .find(|name| name.ends_with("crt1.o"))
664        };
665        assert_eq!(named(LinkMode::Dynamic).as_deref(), Some("Scrt1.o"));
666        assert_eq!(named(LinkMode::DynamicNoPie).as_deref(), Some("crt1.o"));
667        assert_eq!(named(LinkMode::Shared), None);
668    }
669
670    #[test]
671    fn the_library_comes_after_the_objects_that_need_it() {
672        let inputs = [Item::File(Path::new("main.o").to_path_buf()), Item::Library("m".to_owned())];
673        let options =
674            Invocation { inputs: &inputs, mode: LinkMode::Static, ..Invocation::default() };
675        let args = argv(target("x86_64-linux-musl"), &sysroot("x86_64-linux-musl"), &options)
676            .expect("a line");
677        let object = args.iter().position(|arg| arg == "main.o").expect("the object");
678        let asked = args.iter().position(|arg| arg == "-lm").expect("the library");
679        let libc = args.iter().position(|arg| arg.ends_with("libc.a")).expect("the libc");
680        let end = args.iter().position(|arg| arg.ends_with("crtn.o")).expect("the end file");
681        assert!(object < asked && asked < libc && libc < end, "{args:?}");
682    }
683
684    #[test]
685    fn a_static_glibc_link_is_refused_by_name_rather_than_attempted() {
686        // A stub has no code in it, so there is nothing for a static link to take. Saying that is
687        // the whole value here: the alternative is a line that produces several thousand undefined
688        // symbols and a user reading the first forty of them.
689        let options = Invocation { mode: LinkMode::Static, ..Invocation::default() };
690        let error = argv(target("x86_64-linux-gnu"), &sysroot("x86_64-linux-gnu"), &options)
691            .expect_err("refused");
692        assert!(matches!(error, Unsupported::StaticStub { .. }), "{error:?}");
693        assert!(error.to_string().contains("musl"), "the way out is not in the message");
694        // And a musl target links statically, which is the exit criterion of #618.
695        assert!(argv(target("x86_64-linux-musl"), &sysroot("x86_64-linux-musl"), &options).is_ok());
696    }
697
698    #[test]
699    fn a_format_with_no_line_of_its_own_is_refused_by_name_rather_than_approximated() {
700        for spelling in ["aarch64-macos", "wasm32-wasi"] {
701            let options = Invocation { mode: LinkMode::Dynamic, ..Invocation::default() };
702            let error =
703                argv(target(spelling), &sysroot(spelling), &options).expect_err("no line for it");
704            assert!(matches!(error, Unsupported::Format { .. }), "{spelling} {error:?}");
705        }
706    }
707
708    #[test]
709    fn the_msvc_abi_is_refused_on_its_own_grounds_and_the_way_out_is_in_the_message() {
710        // Not the format, because mingw-w64 has a line and is the same format. What is missing is an
711        // SDK nobody may redistribute and a linker with a different command line, and the two are
712        // different kinds of missing, so the message names the environment that needs neither.
713        for spelling in ["x86_64-windows-msvc", "aarch64-windows-msvc", "arm64ec-windows-msvc"] {
714            let options = Invocation { mode: LinkMode::Dynamic, ..Invocation::default() };
715            let error = argv(target(spelling), &sysroot(spelling), &options).expect_err("refused");
716            assert!(matches!(error, Unsupported::MsvcAbi { .. }), "{spelling} {error:?}");
717            assert!(error.to_string().contains("mingw-w64"), "{spelling} {error}");
718        }
719    }
720
721    #[test]
722    fn what_the_user_told_the_linker_comes_after_what_this_told_it() {
723        let passthrough = ["--no-eh-frame-hdr".to_owned()];
724        let options = Invocation {
725            mode: LinkMode::Dynamic,
726            passthrough: &passthrough,
727            ..Invocation::default()
728        };
729        let args = argv(target("x86_64-linux-gnu"), &sysroot("x86_64-linux-gnu"), &options)
730            .expect("a line");
731        assert_eq!(args.last().map(String::as_str), Some("--no-eh-frame-hdr"));
732    }
733
734    #[test]
735    fn asking_for_no_start_files_leaves_out_both_ends_of_them() {
736        let options =
737            Invocation { mode: LinkMode::Dynamic, no_startfiles: true, ..Invocation::default() };
738        let args = argv(target("x86_64-linux-gnu"), &sysroot("x86_64-linux-gnu"), &options)
739            .expect("a line");
740        assert!(!args.iter().any(|arg| arg.ends_with("crt1.o")), "{args:?}");
741        assert!(!args.iter().any(|arg| arg.ends_with("crtn.o")), "{args:?}");
742        // And still links against the libc, because that is the other flag.
743        assert!(args.iter().any(|arg| arg.ends_with("libc.so")), "{args:?}");
744    }
745
746    #[test]
747    fn a_narrow_mode_of_a_wide_architecture_is_a_different_output_format() {
748        // The row that proves the data model belongs in the tuple. Linking x32 as `elf_x86_64`
749        // produces 64-bit pointers for a target whose pointers are 32 bits.
750        assert_eq!(emulation(target("x86_64-linux-gnux32")), Some("elf32_x86_64"));
751        assert_eq!(emulation(target("x86_64-linux-gnu")), Some("elf_x86_64"));
752    }
753
754    #[test]
755    fn byte_order_is_in_the_output_format_name() {
756        assert_eq!(emulation(target("s390x-linux-gnu")), Some("elf64_s390"));
757        assert_eq!(emulation(target("powerpc64le-linux-gnu")), Some("elf64lppc"));
758        assert_eq!(emulation(target("riscv64-linux-musl")), Some("elf64lriscv"));
759    }
760
761    /// The two flags that are about the line rather than about the target.
762    ///
763    /// `-rdynamic` is a flag the linker has and `-fno-builtins-lib` is one it does not, so one of
764    /// them appears and the other one takes a path away, and both are here because a flag the cross
765    /// line ignored would be a flag that works natively and stops working the moment the target is
766    /// somebody else's.
767    #[test]
768    fn rdynamic_reaches_the_linker_and_no_builtins_lib_takes_our_runtime_off() {
769        let one = [Item::File(Path::new("main.o").to_path_buf())];
770        let both = Invocation {
771            inputs: &one,
772            output: Some(Path::new("main")),
773            mode: LinkMode::Dynamic,
774            export_dynamic: true,
775            no_builtins_lib: true,
776            ..Invocation::default()
777        };
778        let spelling = "x86_64-linux-musl";
779        let args = argv(target(spelling), &sysroot(spelling), &both).expect("a line");
780        assert!(args.contains(&"--export-dynamic".to_owned()), "{args:?}");
781        assert!(!args.iter().any(|arg| arg.ends_with("librucc_builtins.a")), "{args:?}");
782        // And the libc it was asked to keep is still there, because that is the other flag.
783        assert!(args.iter().any(|arg| arg.ends_with("libc.a")), "{args:?}");
784    }
785
786    #[test]
787    fn a_mingw_line_names_the_pe_machine_and_the_subsystem_and_no_loader() {
788        let args = line("x86_64-windows-gnu", LinkMode::Dynamic);
789        let at = args.iter().position(|arg| arg == "-m").expect("the machine flag");
790        assert_eq!(args[at + 1], "i386pep");
791        let at = args.iter().position(|arg| arg == "--subsystem").expect("the subsystem flag");
792        assert_eq!(args[at + 1], "console");
793        // A PE image names no interpreter and carries a relocation table whatever it is linked as,
794        // so the two flags that answer those questions on ELF have nothing to say here.
795        for absent in ["-dynamic-linker", "-pie", "-no-pie", "--eh-frame-hdr"] {
796            assert!(!args.contains(&absent.to_owned()), "{absent} in {args:?}");
797        }
798    }
799
800    #[test]
801    fn a_mingw_line_carries_the_crt_and_the_win32_libraries_in_single_pass_order() {
802        let args = line("x86_64-windows-gnu", LinkMode::Dynamic);
803        let at = |name: &str| {
804            args.iter().position(|arg| arg.ends_with(name)).unwrap_or_else(|| panic!("{name}"))
805        };
806        // One start file and no end file, because PE has no `.init` and `.fini` for a pair of them
807        // to open and close.
808        assert!(at("crt2.o") < at("main.o"), "{args:?}");
809        assert!(!args.iter().any(|arg| arg.ends_with("crtn.o")), "{args:?}");
810        // Then a library after everything that calls into it, which is what GNU ld's PE port needs
811        // and what lld's COFF linker does not care about.
812        assert!(at("main.o") < at("libmingw32.a"), "{args:?}");
813        assert!(at("libmingwex.a") < at("libmsvcrt.a"), "{args:?}");
814        assert!(at("libmsvcrt.a") < at("libkernel32.a"), "{args:?}");
815        assert!(at("libkernel32.a") < at("librucc_builtins.a"), "{args:?}");
816    }
817
818    #[test]
819    fn a_dll_takes_the_other_start_file_and_no_subsystem() {
820        let args = line("x86_64-windows-gnu", LinkMode::Shared);
821        assert!(args.contains(&"-shared".to_owned()), "{args:?}");
822        // By file name rather than by suffix, since `dllcrt2.o` ends with the other one's name.
823        let named = |name: &str| {
824            args.iter().any(|arg| Path::new(arg).file_name().is_some_and(|file| file == name))
825        };
826        assert!(named("dllcrt2.o"), "{args:?}");
827        assert!(!named("crt2.o"), "{args:?}");
828        assert!(!args.contains(&"--subsystem".to_owned()), "{args:?}");
829    }
830
831    #[test]
832    fn a_static_windows_link_is_not_refused_because_the_crt_there_is_a_dll_on_every_machine() {
833        // The difference between an import library and a stub shared object that shows up on the
834        // line. `-static` on Windows is a statement about our libraries rather than about the CRT,
835        // and the program it produces runs, which is why the refusal is about `Libc::Stub` by name.
836        let args = line("x86_64-windows-gnu", LinkMode::Static);
837        assert!(args.contains(&"-static".to_owned()), "{args:?}");
838        assert!(args.iter().any(|arg| arg.ends_with("libmsvcrt.a")), "{args:?}");
839    }
840
841    #[test]
842    fn the_pe_header_carries_no_timestamp_so_that_two_links_produce_one_file() {
843        // Section 11.4's second cause of a host reaching a binary, and the PE counterpart of
844        // `--build-id=none`. A stamped header differs between two runs on one machine.
845        for spelling in ["x86_64-windows-gnu", "i686-windows-gnu", "aarch64-windows-gnu"] {
846            let args = line(spelling, LinkMode::Dynamic);
847            assert!(args.contains(&"--no-insert-timestamp".to_owned()), "{spelling} {args:?}");
848            assert!(args.contains(&"--dynamicbase".to_owned()), "{spelling} {args:?}");
849            // The wide address space is a 64-bit idea and i686 has no room for it.
850            let wide = args.contains(&"--high-entropy-va".to_owned());
851            assert_eq!(wide, spelling != "i686-windows-gnu", "{spelling} {args:?}");
852        }
853    }
854
855    #[test]
856    fn the_pe_machine_is_the_one_the_linker_knows_and_not_the_one_the_architecture_is_called() {
857        assert_eq!(pe_machine(target("x86_64-windows-gnu")), Some("i386pep"));
858        assert_eq!(pe_machine(target("i686-windows-gnu")), Some("i386pe"));
859        assert_eq!(pe_machine(target("aarch64-windows-gnu")), Some("arm64pe"));
860        // An ELF target has no PE machine, the same way a PE target has no ELF emulation. And
861        // neither has the MSVC ABI, whose linker takes `/MACHINE:X64` and reads none of these names.
862        assert_eq!(pe_machine(target("x86_64-linux-gnu")), None);
863        assert_eq!(pe_machine(target("x86_64-windows-msvc")), None);
864        assert_eq!(emulation(target("x86_64-windows-gnu")), None);
865    }
866
867    #[test]
868    fn a_format_with_no_emulation_names_none_rather_than_its_architecture_s() {
869        // An emulation is an ELF idea. A Mach-O target whose architecture is also an ELF one would
870        // otherwise answer `aarch64linux` here, which is a word `ld64` has never heard and exactly
871        // the almost-right answer `spec/cross-compile/06-abis.md` opens by warning about.
872        for spelling in
873            ["aarch64-macos", "x86_64-windows-gnu", "x86_64-windows-msvc", "wasm32-wasi"]
874        {
875            assert_eq!(emulation(target(spelling)), None, "{spelling}");
876        }
877    }
878
879    #[test]
880    fn a_freestanding_link_has_no_libc_and_no_start_files_and_still_has_our_runtime() {
881        // Section 8.2's first row is nine headers and no link inputs, so there is no `crt1.o` to
882        // name and no `libc.a` either. The builtins stay, because a 32-bit target doing 64-bit
883        // arithmetic reaches them whether a libc exists or not.
884        let args = line("armv7m-none-eabi", LinkMode::Static);
885        assert!(!args.iter().any(|arg| arg.ends_with("crt1.o")), "{args:?}");
886        assert!(!args.iter().any(|arg| arg.ends_with("crti.o")), "{args:?}");
887        assert!(!args.iter().any(|arg| arg.ends_with("crtn.o")), "{args:?}");
888        assert!(!args.iter().any(|arg| arg.ends_with("libc.a")), "{args:?}");
889        assert!(args.iter().any(|arg| arg.ends_with("librucc_builtins.a")), "{args:?}");
890        // And it is a static link with nothing to interpret it, which is what a bare metal target is.
891        assert!(args.contains(&"-static".to_owned()), "{args:?}");
892        assert!(!args.contains(&"-dynamic-linker".to_owned()), "{args:?}");
893    }
894
895    #[test]
896    fn the_platforms_whose_libc_we_stub_refuse_a_static_link_too_and_not_only_glibc() {
897        // The refusal follows from the sysroot holding a stub rather than from the target being a
898        // glibc one. bionic and the BSDs are in the same position for the same reason, and a line
899        // that pretended otherwise would fail in the linker instead of here.
900        for spelling in ["aarch64-linux-android", "x86_64-freebsd", "x86_64-illumos"] {
901            let options = Invocation { mode: LinkMode::Static, ..Invocation::default() };
902            let error = argv(target(spelling), &sysroot(spelling), &options).expect_err("refused");
903            assert!(matches!(error, Unsupported::StaticStub { .. }), "{spelling} {error:?}");
904        }
905    }
906
907    #[test]
908    fn the_same_line_comes_out_every_time_it_is_asked_for() {
909        // Claim 5 in the smallest form it has: the function reads nothing but its arguments, so
910        // two calls agree and so do two hosts.
911        for mode in [LinkMode::Dynamic, LinkMode::Shared] {
912            assert_eq!(line("aarch64-linux-gnu", mode), line("aarch64-linux-gnu", mode));
913        }
914    }
915}