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