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