Skip to main content

rucc_driver/
link.rs

1//! Finding a linker and telling it what to link.
2//!
3//! Design: `spec/04-driver-and-cli.md` section 4.9. There is no linker of our own before 1.0, so
4//! this finds one on the machine and builds the command line it wants.
5//!
6//! The linker is invoked directly rather than through the system compiler driver. Going through
7//! `cc` would be shorter to write and would borrow that compiler's idea of where everything is,
8//! and it would also mean this compiler cannot link on a machine that has no other compiler on
9//! it, which is most of the machines a compiler ends up on. It would also make `-###` output a
10//! line that does not say what happens, since the interesting half would be inside the program
11//! being spawned.
12//!
13//! # What is not decided here
14//!
15//! The startup files and the library directories are looked for rather than configured, for the
16//! same reason `library` looks for the headers: gcc settles this when it is built because a gcc
17//! is built for the machine it will run on, and this is one binary that runs wherever it is
18//! copied. So the shape of the answer is a list of candidates per platform of which the ones
19//! that exist are taken, and a cross build says where the rest is with `--sysroot`.
20//!
21//! # The compiler's own runtime
22//!
23//! `crtbegin`, `crtend` and the runtime libraries are found the same way, on the machine rather
24//! than by configuration. Ours is `librucc_builtins.a`, looked for beside the compiler, and the
25//! machine's `libgcc` goes on after it for the parts we have not written, which today is the
26//! unwinder and its personality routine. The C library goes in front of both, so that on a target
27//! that has one its `memcpy` is the one that answers rather than ours. `-fno-builtins-lib` leaves
28//! ours off, for somebody who wants libgcc to answer for everything.
29//!
30//! On a static link the three archives go inside `--start-group`, because `libc.a` refers to the
31//! unwinder and the unwinder refers back to `libc.a`, and a linker walking a list once resolves
32//! whichever of the two it reaches first and leaves the other undefined. That circularity is the
33//! whole reason `-static` failed before this, and it is issue #277.
34//!
35//! # Linking for a machine that is not this one
36//!
37//! Everything above describes a link against the machine running the compiler, and it is what runs
38//! when the target is that machine. A target that is not is a different problem: there is no
39//! `crt1.o` for it in `/usr/lib`, the `libc.so` there is the wrong architecture, and a line built
40//! out of what is lying around either fails at the first input or, worse, links. So a cross link
41//! does not look at this machine at all. It is built by [`rucc_sysroot::argv`] out of the target
42//! and a sysroot under the cache directory, and `spec/cross-compile/11-linking.md` section 11.3 is
43//! the design. [`cross_sysroot`] is the one place that decides which of the two it is.
44//!
45//! Two conditions keep that out of the way of everything that works today. The target has to differ
46//! from the host, and `--sysroot` must not have been given: somebody who assembled a tree and named
47//! it is asking for the line above with their own root in front of every path, which is what a
48//! cross compile with a real distribution tree in it has always been.
49//!
50//! That second condition is also the escape hatch for a machine which has a distribution's own cross
51//! files installed, where `/usr/lib/aarch64-linux-gnu` really does hold an AArch64 `crt1.o`.
52//! `--sysroot=/` takes the line above, and then every directory it decides is that machine's again.
53//!
54//! # What is not here yet
55//!
56//! Windows in Microsoft's ABI. `lld-link` wants a `/`-style command line and an import library set
57//! out of an SDK nobody may redistribute, and a link to it is refused by name rather than
58//! approximated. A mingw-w64 target does have a line, because PE in that environment is written in
59//! the GNU style and the import libraries for it are ours to produce.
60//!
61//! Darwin has a line of its own, [`darwin_line`], and it is the same line on a Mac and anywhere
62//! else. Everything it links against is in the SDK, which is found the way the header search finds
63//! it, so a machine that is not a Mac links for one exactly when somebody has named an SDK with
64//! `-isysroot` or `SDKROOT` and there is an `ld64.lld` to hand it to.
65//!
66//! The headers are the other half of a cross compile and [`crate::library::header_dirs`] is where
67//! they are decided. It asks [`cross_sysroot`] the same question this file asks it, which is the
68//! point: a compile that took its libc from the sysroot and its declarations from this machine would
69//! be wrong in the quietest way available, and one function answering for both is what stops that
70//! being possible.
71
72use std::ffi::OsString;
73use std::fs;
74use std::path::{Path, PathBuf};
75use std::process::Command;
76
77use rucc_sysroot::layout::{Kernel, Sysroot};
78use rucc_sysroot::{LinkMode, argv};
79use rucc_target::{Arch, Env, Os, Triple};
80use rucc_tuple::TargetTuple;
81
82/// What the command line said about linking.
83///
84/// Kept apart from `Options` because none of it reaches the compilation. A flag here changes what
85/// the linker is told and changes nothing about the object files handed to it, which is why `-lm`
86/// on a `-c` line is a note rather than an error.
87#[derive(Debug, Default, Clone, PartialEq, Eq)]
88pub struct LinkOptions {
89    /// `-fuse-ld=<name>`, which names a linker rather than a path to one.
90    pub use_ld: Option<String>,
91    /// `-L<dir>`, in order, because the linker takes the first library it finds.
92    pub search: Vec<PathBuf>,
93    /// `-B<prefix>`, which is where to look for the linker before looking on the path.
94    pub prefixes: Vec<PathBuf>,
95    /// `--sysroot=<dir>`, which prefixes the directories this looks in.
96    pub sysroot: Option<PathBuf>,
97    /// Where the generated sysroots are, which is [`crate::cache::dir`] on a real command line.
98    ///
99    /// [`None`] is a caller that was not given one, which outside a test is nothing, and then there
100    /// is no cross link line and a foreign target is refused the way it was before there was one.
101    /// It is a field rather than a call inside this module because a link line that read the
102    /// environment could only be tested on a machine whose environment said the right thing.
103    pub cache: Option<PathBuf>,
104    /// Where a distribution's cross packages put the tree for another architecture, which is
105    /// `/usr` on a real command line.
106    ///
107    /// Debian and Ubuntu install `libc6-dev-arm64-cross` and its friends as `/usr/<multiarch>/include`
108    /// and `/usr/<multiarch>/lib`, and gcc's own files for that target under
109    /// `/usr/lib/gcc-cross/<multiarch>`. [`distro_cross`] reads it. A field for the reason
110    /// [`LinkOptions::cache`] is one, and [`None`] in a test is a machine with no such packages.
111    pub usr: Option<PathBuf>,
112    /// `-static`.
113    pub is_static: bool,
114    /// `-shared`.
115    pub shared: bool,
116    /// `-pie` or `-no-pie`, and the platform's default when neither was written.
117    pub pie: Option<bool>,
118    /// `-nostdlib`, which is `-nostartfiles` and `-nodefaultlibs` together.
119    pub no_stdlib: bool,
120    /// `-nostartfiles`.
121    pub no_startfiles: bool,
122    /// `-nodefaultlibs`.
123    pub no_defaultlibs: bool,
124    /// `-rdynamic`, which puts every symbol in the dynamic table so a program can look itself up.
125    pub export_dynamic: bool,
126    /// `-s`, which drops the symbol table.
127    pub strip: bool,
128    /// `-mwindows` rather than `-mconsole`, whichever came last. Only a Windows line reads it.
129    pub gui: bool,
130    /// `-municode`, which only a Windows line reads.
131    pub unicode: bool,
132    /// `-fno-builtins-lib`, which leaves our own runtime off the line so that the machine's
133    /// libgcc answers for everything instead.
134    pub no_builtins_lib: bool,
135    /// The whole ten field target when `--target=` spelled one, which is where a pinned libc
136    /// release is.
137    ///
138    /// [`None`] is a command line that named no target at all, and then there is nothing pinned and
139    /// this machine is the target. A `Triple` has room for an architecture, an OS and an
140    /// environment and nowhere to put a release, so the release arrives here instead of there, and
141    /// [`cross_sysroot`] reads it for both of the things it decides: whether this is a cross link
142    /// and which directory under the cache it is against.
143    pub pinned: Option<TargetTuple>,
144    /// `-pg`, which changes the link as well as the code.
145    ///
146    /// The counts a profiled program keeps have to be started before `main` runs and written out
147    /// after it returns, and what does both is a start file of its own. So a build that compiles
148    /// with the flag and links without it produces a program that calls the hook on every function
149    /// and never writes a profile.
150    pub profile: bool,
151    /// Whether `-Ofast`, `-ffast-math` or `-funsafe-math-optimizations` was in force at the end
152    /// of the command line, which links `crtfastmath.o` into anything that is not a shared object.
153    ///
154    /// That file is a constructor which sets flush to zero and denormals are zero before `main`,
155    /// so the mode is the process's rather than the unit's, and it is the half of fast math the
156    /// compiler cannot give from inside a function.
157    pub fast_math: bool,
158    /// `-mdaz-ftz` or `-mno-daz-ftz`, which decides the same file outright and for a shared
159    /// object as well.
160    pub daz_ftz: Option<bool>,
161    /// `-r`, which joins objects into one bigger object rather than into something that runs.
162    ///
163    /// Kbuild builds every directory into a `built-in.o` this way. The result is still an input to a
164    /// later link, so it takes no startup files, no libraries and nothing about how it will be
165    /// loaded, which is what gcc leaves off the line when it sees the flag.
166    pub relocatable: bool,
167    /// The deployment target on an Apple platform, from `-mmacosx-version-min=` and its friends or
168    /// from the tuple, which `ld64` is told in `-platform_version` and checks every object against.
169    ///
170    /// [`None`] is the platform's default, the same one the object writer puts in
171    /// `LC_BUILD_VERSION`, so that the two agree when neither was told anything.
172    pub os_version: Option<rucc_tuple::Version>,
173}
174
175impl LinkOptions {
176    /// Whether gcc's `crtfastmath.o` goes on the line, which is its end file spec on x86-64.
177    fn wants_fastmath(&self) -> bool {
178        self.daz_ftz.unwrap_or(self.fast_math && !self.shared)
179    }
180
181    /// Whether the startup files go on the line.
182    fn wants_startfiles(&self) -> bool {
183        !self.no_stdlib && !self.no_startfiles && !self.relocatable
184    }
185
186    /// Whether the library the program was written against goes on the line.
187    fn wants_defaultlibs(&self) -> bool {
188        !self.no_stdlib && !self.no_defaultlibs && !self.relocatable
189    }
190
191    /// Whether the compiler's own runtime goes on the line.
192    ///
193    /// The same switch as the C library, because `-nodefaultlibs` in GCC means the compiler's
194    /// runtime too, and a link that keeps `libgcc` while dropping `libc` is not a thing anyone
195    /// asks for on purpose.
196    fn wants_runtime(&self) -> bool {
197        !self.no_stdlib && !self.no_defaultlibs && !self.relocatable
198    }
199}
200
201/// One item on the link line, in the order it was written, because link order is semantic.
202///
203/// A library named before the object that needs it is not found on a static link, which is the
204/// oldest surprise in the toolchain and the reason this is one ordered list rather than a list of
205/// files and a list of libraries.
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub enum Item {
208    /// A file: an object this compilation produced, or one named on the command line.
209    File(String),
210    /// `-l<name>`, which the linker resolves against its search path.
211    Library(String),
212    /// One word from `-Wl,` or `-Xlinker`, handed to the linker where the user wrote it.
213    ///
214    /// Here rather than in a list of its own because a great many of the linker's options are a
215    /// bracket around the files after them, and an option moved away from what it brackets means
216    /// something else or nothing at all. `--whole-archive` says that every member of every archive
217    /// named after it goes in whether anything referenced it or not, `--start-group` says that the
218    /// archives after it are searched again until nothing more comes out, and `-Bstatic` says which
219    /// half of a library that ships both is wanted. Collecting them and appending them to the end
220    /// leaves each of those pointing at nothing.
221    Linker(String),
222}
223
224impl std::fmt::Display for Item {
225    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226        match self {
227            Item::File(path) => f.write_str(path),
228            Item::Library(name) => write!(f, "-l{name}"),
229            Item::Linker(arg) => write!(f, "-Wl,{arg}"),
230        }
231    }
232}
233
234/// Why a link could not be run.
235#[derive(Debug, Clone, PartialEq, Eq)]
236pub enum Error {
237    /// No linker was found, after looking everywhere there was to look.
238    NoLinker {
239        /// The names that were tried, in the order they were tried.
240        tried: Vec<String>,
241    },
242    /// `-fuse-ld=` named one that is not on this machine.
243    Named {
244        /// What it named.
245        name: String,
246    },
247    /// A target this does not know how to build a link line for.
248    Target {
249        /// The triple that was asked for.
250        triple: String,
251    },
252    /// A cross link this scheme cannot produce, which [`rucc_sysroot::argv`] has explained.
253    ///
254    /// The reason is carried as a sentence rather than as a variant per cause, because the causes
255    /// live in `rucc-sysroot` and a second enumeration here would be a second thing to keep in step
256    /// with them. What this adds is that the sentence came from a link rather than from a
257    /// compilation.
258    Cross {
259        /// Why, in full, ready to print.
260        why: String,
261    },
262    /// The sysroot a cross link needs is not on this machine.
263    Sysroot {
264        /// The target that was asked for.
265        target: String,
266        /// Where its sysroot would be.
267        dir: String,
268        /// Whether this release pins an artifact for that target, which decides whether the message
269        /// can name a command that would fix it.
270        pinned: bool,
271    },
272    /// The linker was found and cannot do this target's link.
273    ///
274    /// Separate from [`Error::NoLinker`] because the linker is there and runs, and separate from
275    /// [`Error::Refused`] because the refusal is ours rather than its own: this is the case the
276    /// linker would not complain about at all.
277    TooOld {
278        /// What it was found as, which is what to look for when replacing it.
279        name: String,
280        /// The major version it reported.
281        found: u32,
282        /// The target whose link it cannot do.
283        target: String,
284    },
285    /// The linker was found and could not be started.
286    Spawn {
287        /// Where it was.
288        path: String,
289        /// What the operating system said.
290        why: String,
291    },
292    /// The linker ran and said no.
293    Refused {
294        /// What it exited with, or a description when it was killed instead.
295        status: String,
296    },
297}
298
299impl std::fmt::Display for Error {
300    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
301        match self {
302            Error::NoLinker { tried } => {
303                write!(f, "no linker was found; tried {}", tried.join(", "))?;
304                // Only when lld was one of the names, because that is the linker every cross
305                // target here is linked with and the one there is a single answer for.
306                if tried.iter().any(|name| is_lld(name)) {
307                    write!(
308                        f,
309                        ". lld {LLD_EXPORTAS} or newer links for every target, and {}",
310                        lld_advice()
311                    )?;
312                }
313                Ok(())
314            }
315            Error::Named { name } => {
316                write!(f, "-fuse-ld={name} asks for a linker that is not on this machine")
317            }
318            Error::Target { triple } => {
319                write!(f, "there is no link line for {triple} in this compiler yet")
320            }
321            Error::Cross { why } => f.write_str(why),
322            // Two sentences and the second one changes, because a person whose link just failed
323            // wants the command that fixes it and there is only a command to name when this release
324            // pins an artifact for that target. Section 13.8's rule is that a compile which is
325            // missing a sysroot says what to run rather than running it, and this is where it says
326            // it.
327            Error::Sysroot { target, dir, pinned: true } => write!(
328                f,
329                "there is no sysroot for {target} at {dir}, so there is nothing to link it \
330                 against. `rucc --fetch {target}` gets the one this release pins, or pass \
331                 --sysroot=<dir> to name a tree you have already"
332            ),
333            Error::Sysroot { target, dir, pinned: false } => write!(
334                f,
335                "there is no sysroot for {target} at {dir}, so there is nothing to link it \
336                 against, and this release pins none for it to fetch. Pass --sysroot=<dir> to name \
337                 a tree you have already, or see spec/cross-compile/13-distribution.md section \
338                 13.2 for the cache that will hold one"
339            ),
340            // The whole message, because the person reading it has a linker that works, a link that
341            // succeeded on their last try, and no reason to suspect the thing that is wrong.
342            Error::TooOld { name, found, target } => write!(
343                f,
344                "{name} is lld {found} and cannot link for {target}. mingw-w64 writes a few hundred \
345                 of its aliases, `_crt_atexit == atexit` among them, as IMPORT_NAME_EXPORTAS \
346                 records in its import libraries, which lld learned to read in {LLD_EXPORTAS}. An \
347                 older one neither reads them nor says so: it writes an import by ordinal zero, the \
348                 link succeeds, and the program dies at startup. No newer lld was found either. \
349                 For lld {LLD_EXPORTAS} or newer, {}, or name one with -fuse-ld=",
350                lld_advice()
351            ),
352            Error::Spawn { path, why } => write!(f, "could not run the linker at {path}: {why}"),
353            Error::Refused { status } => write!(f, "the linker {status}"),
354        }
355    }
356}
357
358impl std::error::Error for Error {}
359
360/// A linker, found.
361#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct Linker {
363    /// The name it is known by, which is what `--print-config` reports.
364    pub name: String,
365    /// Where it is, which is what gets spawned.
366    pub path: PathBuf,
367}
368
369/// The names to look for, in the order section 4.9 gives.
370///
371/// `mold` first because it is dramatically faster, and a compiler that is twice the speed of
372/// another one while the link takes twelve seconds has not helped anybody. Then `lld`, then the
373/// platform's own. Each is looked for under both the bare name and the `ld.` prefix, because a
374/// distribution installs `mold` under its own name and `ld.mold` for exactly this lookup.
375#[must_use]
376pub fn order(target: Triple, opts: &LinkOptions) -> Vec<String> {
377    if let Some(named) = &opts.use_ld {
378        // A name rather than a path, so `-fuse-ld=mold` finds a `mold` that is not `ld.mold`.
379        return vec![format!("ld.{named}"), named.clone()];
380    }
381    // Apple's `ld` and lld's Mach-O flavour, and nothing from the list below. mold and `ld.lld` write
382    // ELF, and a Mac with Homebrew's llvm on its `PATH` has an `ld.lld` that would take the line and
383    // fail on its first flag.
384    if target.os == Os::Darwin {
385        return vec!["ld".to_owned(), "ld64.lld".to_owned()];
386    }
387    if cross_sysroot(target, opts).is_some() {
388        let mut names = cross_order(target);
389        // The mingw-w64 sysroot this release fetches has import libraries that GNU ld cannot link
390        // against: the `==` aliases are IMPORT_NAME_EXPORTAS records, and binutils reports every
391        // one of them as an undefined reference to a symbol like `__imp__fmode`. So on this path
392        // lld is the only linker worth finding, and a machine without one is told how to get it
393        // instead of being handed a page of undefined references.
394        if (target.os, target.env) == (Os::Windows, Env::Gnu) {
395            names.retain(|name| is_lld(name));
396        }
397        return names;
398    }
399    if distro_cross(target, opts).is_some() {
400        return cross_order(target);
401    }
402    match target.os {
403        Os::Windows => vec!["lld-link".to_owned(), "link.exe".to_owned()],
404        _ => vec![
405            "ld.mold".to_owned(),
406            "mold".to_owned(),
407            "ld.lld".to_owned(),
408            "lld".to_owned(),
409            "ld".to_owned(),
410        ],
411    }
412}
413
414/// The names to look for when the target is not this machine.
415///
416/// A shorter list than the one above and a different one, because most of that list cannot do this.
417/// `spec/cross-compile/11-linking.md` section 11.2 settles it: `ld.lld` is the ELF cross linker,
418/// since one binary of it links for every architecture it was built with and that is all of them.
419/// mold is off the list because it links for the host and `wild` likewise, which is why section 11.2
420/// has them as `-fuse-ld=` choices for a native link rather than as defaults. The platform's own
421/// `ld` is off it for the same reason: a distribution's `/usr/bin/ld` is built for one architecture,
422/// and `-fuse-ld=` is still there for somebody whose is not.
423///
424/// A cross binutils under its prefixed name is last, because a machine that has
425/// `aarch64-linux-gnu-ld` installed has it on purpose. The prefix is a distribution convention and
426/// there are two of them: a Linux target is filed under its multiarch name and a mingw-w64 one under
427/// `<arch>-w64-mingw32`, which is what every distribution's mingw packages install. `ld.lld` is the
428/// same binary for both, because its MinGW mode is a mode of the one linker rather than a second one.
429fn cross_order(target: Triple) -> Vec<String> {
430    let mut names = vec!["ld.lld".to_owned(), "lld".to_owned()];
431    match (target.os, target.env) {
432        (Os::Linux, _) => names.push(format!("{}-ld", multiarch(target))),
433        (Os::Windows, Env::Gnu) => names.push(format!("{}-w64-mingw32-ld", target.arch.as_str())),
434        _ => {}
435    }
436    names
437}
438
439/// The sysroot a cross link would use, or [`None`] for a link against this machine.
440///
441/// The one place the two paths are told apart, so that the linker that is looked for and the line it
442/// is handed cannot disagree about which kind of link this is.
443///
444/// Three conditions, and two of them are about leaving working configurations alone. A target that
445/// is this machine is linked against this machine, which is what every native compile has always
446/// done and what the directories under `/usr/lib` are for. A `--sysroot` the user wrote is taken as
447/// the root of a tree they assembled, and the line above prefixes every path it decides with it,
448/// which is what cross compiling against a real distribution tree has always meant here. The third
449/// is that there has to be a cache directory to look in, which on a real command line there always
450/// is.
451///
452/// An unknown host counts as different from every target. A machine this compiler cannot name is a
453/// machine whose `/usr/lib` it should not be guessing at.
454///
455/// # A pinned release is a cross compile
456///
457/// The first of those three conditions is about the machine and not about the triple, and a target
458/// that names a libc release is not this machine even when it is this architecture. Somebody on a
459/// 2.44 box writing `--target=x86_64-linux-gnu.2.28` is asking for a binary that runs on a 2.28
460/// machine, and handing them their own headers and their own libc gives them a binary that does not.
461/// So the condition is the triple being the host *and* no release named, and what it costs is that a
462/// pin equal to this machine's own release also stops using this machine's libc. That is not a loss:
463/// the two should be the same text, and if they are not then this machine's copy is patched and the
464/// bundled tree is the one the pin asked for. tamnd/rucc#956.
465#[must_use]
466pub fn cross_sysroot(target: Triple, opts: &LinkOptions) -> Option<Sysroot> {
467    cross_for(target, opts, Triple::host())
468}
469
470/// The same answer with the host as a parameter, so that both branches are testable on one machine.
471fn cross_for(target: Triple, opts: &LinkOptions, host: Option<Triple>) -> Option<Sysroot> {
472    if opts.sysroot.is_some() {
473        return None;
474    }
475    let tuple = target_tuple(target, opts);
476    if host == Some(target) && tuple.env_version().is_none() {
477        return None;
478    }
479    if distro_for(target, opts, host).is_some() {
480        return None;
481    }
482    let cache = opts.cache.as_deref()?;
483    Some(Sysroot::in_cache(cache, tuple))
484}
485
486/// A tree a distribution's cross packages installed for a Linux target that is not this machine.
487///
488/// What `apt install gcc-aarch64-linux-gnu` leaves behind: the C library's headers and files under
489/// `/usr/aarch64-linux-gnu`, and gcc's `crtbegin.o` and `libgcc.a` for that target under
490/// `/usr/lib/gcc-cross/aarch64-linux-gnu/<version>`. The library's `libc.so` script names its files
491/// by their full path, so the tree is linked where it is and not under a `--sysroot`.
492#[derive(Debug, Clone, PartialEq, Eq)]
493pub struct Distro {
494    /// `/usr/<multiarch>`, which has `include` and `lib` under it.
495    pub root: PathBuf,
496    /// gcc's directories for the target, newest version first, and empty when only the library
497    /// was installed.
498    pub gcc: Vec<PathBuf>,
499}
500
501impl Distro {
502    /// The C library's headers, and the kernel's, which the same packages put in the same place.
503    #[must_use]
504    pub fn include(&self) -> PathBuf {
505        self.root.join("include")
506    }
507
508    /// The C library's startup files and libraries.
509    #[must_use]
510    pub fn lib(&self) -> PathBuf {
511        self.root.join("lib")
512    }
513}
514
515/// The distribution's tree for this target, when a cross compile should use it.
516///
517/// Only when nothing better was asked for or is there. A `--sysroot` is a tree somebody named, a
518/// pinned release is a request for our tree cut at that release, and a sysroot already fetched into
519/// the cache is the one this release pins, so each of those wins. What is left is a machine that
520/// has the distribution's cross packages and nothing of ours, and there the packages are what a
521/// prefixed gcc on the same machine would use, so they are what this uses too.
522#[must_use]
523pub fn distro_cross(target: Triple, opts: &LinkOptions) -> Option<Distro> {
524    distro_for(target, opts, Triple::host())
525}
526
527/// The same answer with the host as a parameter, for the same reason as [`cross_for`].
528fn distro_for(target: Triple, opts: &LinkOptions, host: Option<Triple>) -> Option<Distro> {
529    if opts.sysroot.is_some() || target.os != Os::Linux || host == Some(target) {
530        return None;
531    }
532    let tuple = target_tuple(target, opts);
533    if tuple.env_version().is_some() {
534        return None;
535    }
536    if opts.cache.as_deref().is_some_and(|cache| Sysroot::in_cache(cache, tuple).lib().is_dir()) {
537        return None;
538    }
539    let usr = opts.usr.as_deref()?;
540    let name = multiarch(target);
541    let root = usr.join(&name);
542    if !root.join("include").is_dir() || !root.join("lib").is_dir() {
543        return None;
544    }
545    let gcc = newest_first(&usr.join("lib/gcc-cross").join(&name));
546    Some(Distro { root, gcc })
547}
548
549/// The target as the model that has room for a release, which is what names the cache directory.
550///
551/// The pinned spelling when there is one, because `x86_64-linux-gnu` and `x86_64-linux-gnu.2.28` are
552/// two sysroots and not one: the release is in the tuple for the reason
553/// `spec/cross-compile/03-target-model.md` section 3.2 admits a field at all, which is that it
554/// changes what is compiled. A command line that named no target, or one whose spelling the ten
555/// field parser did not take, falls back to what the three field one did.
556fn target_tuple(target: Triple, opts: &LinkOptions) -> TargetTuple {
557    opts.pinned.unwrap_or_else(|| target.tuple())
558}
559
560/// The kernel headers that go with [`cross_sysroot`], for the targets that have any.
561///
562/// The same three conditions, asked through the same function, because the two halves of one
563/// target's system headers have to be decided together or a compile could read glibc's `sys/stat.h`
564/// against this machine's `asm/stat.h`. A `None` here on a Linux target where the sysroot is `Some`
565/// means only one thing, which is that the cache has no kernel tree for that architecture, and the
566/// directory is still named for the reason [`crate::library::header_dirs`] gives.
567///
568/// Not under the sysroot, because `linux/` and `asm-generic/` are the same nine megabytes for every
569/// target that shares an architecture, and a copy per target is eight copies of one thing.
570#[must_use]
571pub fn cross_kernel(target: Triple, opts: &LinkOptions) -> Option<Kernel> {
572    kernel_for(target, opts, Triple::host())
573}
574
575/// The same answer with the host as a parameter, for the same reason as [`cross_for`].
576fn kernel_for(target: Triple, opts: &LinkOptions, host: Option<Triple>) -> Option<Kernel> {
577    cross_for(target, opts, host)?;
578    Kernel::for_target(opts.cache.as_deref()?, target.tuple())
579}
580
581/// How the result is linked, as the five cases a sysroot link line is written over.
582///
583/// Four booleans reach here and five cases leave, because static and position independent are not
584/// independent of each other and the start file differs in four of the five. The default for `pie`
585/// is the one the native line above uses, so that a command line that says neither gets the same
586/// answer whichever path it takes.
587fn mode(opts: &LinkOptions) -> LinkMode {
588    let pie = opts.pie.unwrap_or(!opts.is_static && !opts.shared);
589    if opts.shared {
590        LinkMode::Shared
591    } else if opts.is_static {
592        if pie { LinkMode::StaticPie } else { LinkMode::Static }
593    } else if pie {
594        LinkMode::Dynamic
595    } else {
596        LinkMode::DynamicNoPie
597    }
598}
599
600/// The line for a machine that is not this one, from the target and the sysroot and nothing else.
601///
602/// Everything this knows is already in `opts`, and all it does is say it in the shape
603/// [`rucc_sysroot::argv`] is written over. There is deliberately no decision here: a second place
604/// that decided what goes on a cross link line would be a second place to get it wrong, and the
605/// recorded lines under `tests/link-lines` would stop describing what this compiler does.
606fn cross_line(
607    target: Triple,
608    opts: &LinkOptions,
609    items: &[Item],
610    output: &str,
611    sysroot: &Sysroot,
612) -> Result<Vec<String>, Error> {
613    if opts.profile {
614        // `gcrt1.o` is a compiled object out of the C library's own sources, and a generated sysroot
615        // has the names a libc exports rather than the bodies behind them. Said here rather than
616        // left to the linker, because what the linker would say is that `main` is undefined.
617        return Err(Error::Cross {
618            why: format!(
619                "-pg needs gcrt1.o, or gcrt2.o on Windows, the startup file that starts and stops \
620                 the counting, and a generated sysroot for {target} does not have one. Profile on \
621                 the host, or pass --sysroot=<dir> naming a tree that has it"
622            ),
623        });
624    }
625    let inputs: Vec<argv::Item> = items
626        .iter()
627        .map(|item| match item {
628            Item::File(path) => argv::Item::File(PathBuf::from(path)),
629            Item::Library(name) => argv::Item::Library(name.clone()),
630            Item::Linker(arg) => argv::Item::Linker(arg.clone()),
631        })
632        .collect();
633    let output = PathBuf::from(output);
634    // Ours, from beside the compiler, because that is where `cargo xtask builtins` writes it and a
635    // fetched sysroot will never hold it. The cross line used to name it inside the sysroot, which
636    // is a file nothing puts there, so every cross link either failed at the linker or quietly ran
637    // against somebody else's `libgcc` copied in under the name. tamnd/rucc#1514.
638    let ours = builtins_archive(target, &opts.prefixes);
639    if ours.is_none() && opts.wants_runtime() && !opts.no_builtins_lib {
640        // Said here rather than left to the linker, which on a Windows target says `___chkstk_ms`
641        // is undefined and names mingw-w64's objects as the callers, and on a musl one says
642        // `__udivti3` is. Neither of those is a person's first guess at a missing archive.
643        let tuple = target.tuple().to_canonical_string();
644        return Err(Error::Cross {
645            why: format!(
646                "a cross link ends with librucc_builtins.a, this compiler's own runtime for \
647                 {tuple}, and there is none beside the compiler or under a -B prefix. A sysroot \
648                 does not carry it, because it is our output rather than the platform's. Build it \
649                 with `cargo xtask builtins --target={tuple}`, or pass -fno-builtins-lib to link \
650                 without it"
651            ),
652        });
653    }
654    let invocation = argv::Invocation {
655        inputs: &inputs,
656        output: Some(&output),
657        mode: mode(opts),
658        search: &opts.search,
659        no_startfiles: !opts.wants_startfiles(),
660        no_defaultlibs: !opts.wants_defaultlibs(),
661        no_builtins_lib: opts.no_builtins_lib,
662        builtins: ours.as_deref(),
663        export_dynamic: opts.export_dynamic,
664        strip: opts.strip,
665        gui: opts.gui,
666        unicode: opts.unicode,
667    };
668    argv::argv(target.tuple(), sysroot, &invocation)
669        .map_err(|why| Error::Cross { why: why.to_string() })
670}
671
672/// Whether this link can be run at all, asked before anything is compiled.
673///
674/// Two questions that have answers before the first object exists: whether there is a line for this
675/// target and mode at all, and whether the sysroot it would read is on the machine. Both are worth a
676/// second at the start rather than a message after a minute of compiling, which is the same reason
677/// the linker itself is looked for first.
678///
679/// The line is built rather than inspected, with no inputs and a name nothing will be written to,
680/// because the refusals belong to the one function that builds it. A link against this machine has
681/// nothing to answer here: its directories are looked for as the line is built and a missing one is
682/// simply a directory that is not offered.
683///
684/// # Errors
685///
686/// [`Error::Cross`] for a target or a mode that has no line, and [`Error::Sysroot`] when the sysroot
687/// it would be linked against is not there.
688pub fn preflight(target: Triple, opts: &LinkOptions) -> Result<(), Error> {
689    if opts.relocatable {
690        return relocatable_line(target, opts, &[], "a.out").map(drop);
691    }
692    // Whether there is an SDK, which is the one thing a Darwin link can be missing that is worth
693    // saying before everything has been compiled.
694    if target.os == Os::Darwin {
695        return darwin_line(target, opts, &[], "a.out").map(drop);
696    }
697    let Some(sysroot) = cross_sysroot(target, opts) else { return Ok(()) };
698    // Whether there is a line for this target and mode at all, asked with our own runtime left off
699    // it. Otherwise a target nothing here can link and a machine where nobody built the runtime
700    // report the same thing, and the archive is the smaller of the two problems by a long way.
701    let shape = LinkOptions { no_builtins_lib: true, ..opts.clone() };
702    cross_line(target, &shape, &[], "a.out", &sysroot)?;
703    // The library directory rather than the root, because the root of a cache directory that has
704    // been created and never populated is there and holds nothing. Section 11.6's rule is that
705    // suitable is checked and not assumed, and this is the cheapest form of that.
706    if !sysroot.lib().is_dir() {
707        let tuple = target_tuple(target, opts).to_canonical_string();
708        return Err(Error::Sysroot {
709            dir: sysroot.root().display().to_string(),
710            pinned: rucc_sysroot::pinned_for_target(target_tuple(target, opts)).is_some(),
711            target: tuple,
712        });
713    }
714    // And now the whole line, which is the sysroot's files plus ours, so that a missing runtime is
715    // said here rather than by the linker after everything has been compiled.
716    cross_line(target, opts, &[], "a.out", &sysroot)?;
717    Ok(())
718}
719
720/// Writes the stub libraries a glibc cross link reads, into [`Sysroot::stubs`].
721///
722/// `spec/cross-compile/09-libc-stubs.md` section 9.1: the stubs are generated on demand rather than
723/// shipped, out of the description `rucc-stub` carries, cut at the release the tuple names or at
724/// the bundled one when it names none. So there is nothing to fetch for them and nothing to go
725/// stale, and a pin is a different directory rather than a different download.
726///
727/// A file is written only when its bytes differ from what is there, and then through a temporary
728/// name and a rename, because two builds for one target run side by side all the time and a
729/// linker must never read a half written `libc.so`. The bytes are the same on every host, so two
730/// processes racing to write them race to write the same thing.
731///
732/// Nothing for a link against this machine, a `--sysroot` the user named, or a target that is not
733/// glibc. A glibc release newer than the bundled tree was already refused when the headers were
734/// chosen, so it is quietly nothing here too.
735///
736/// # Errors
737///
738/// [`Error::Cross`] when the stubs cannot be generated for this target or cannot be written.
739pub fn write_stubs(target: Triple, opts: &LinkOptions) -> Result<(), Error> {
740    let Some(sysroot) = cross_sysroot(target, opts) else { return Ok(()) };
741    let tuple = sysroot.target();
742    if rucc_stub::glibc::architecture(tuple).is_none() {
743        return Ok(());
744    }
745    let Ok(Some(minor)) = rucc_sysroot::bundled_glibc_minor(tuple) else { return Ok(()) };
746    let files = rucc_stub::glibc::stubs(tuple, minor).map_err(|why| Error::Cross {
747        why: format!("the glibc stubs for {}: {why}", tuple.to_canonical_string()),
748    })?;
749    let dir = sysroot.stubs();
750    let failed = |path: &Path, why: std::io::Error| Error::Cross {
751        why: format!("{} cannot be written: {why}", path.display()),
752    };
753    fs::create_dir_all(dir).map_err(|why| failed(dir, why))?;
754    for file in files {
755        let path = dir.join(&file.name);
756        if fs::read(&path).is_ok_and(|there| there == file.bytes) {
757            continue;
758        }
759        let temporary = dir.join(format!(".{}.{}", file.name, std::process::id()));
760        fs::write(&temporary, &file.bytes).map_err(|why| failed(&temporary, why))?;
761        fs::rename(&temporary, &path).map_err(|why| {
762            let _ = fs::remove_file(&temporary);
763            failed(&path, why)
764        })?;
765    }
766    Ok(())
767}
768
769/// The linker to use, looked for where a linker is.
770///
771/// `-B` prefixes first, since the point of one is to put a toolchain in front of the machine's,
772/// then the path. A name that contains a separator is a path and is taken as one, which is what
773/// gcc does with `-fuse-ld=/usr/bin/ld.gold` and what a build system relying on that expects.
774///
775/// # Errors
776///
777/// [`Error::Named`] when `-fuse-ld=` asked for one that is not here, and [`Error::NoLinker`] when
778/// nothing was, which name the candidates so that the message says what was looked for.
779pub fn find(target: Triple, opts: &LinkOptions) -> Result<Linker, Error> {
780    let tried = order(target, opts);
781    let places = lld_dirs(Path::new("/"), std::env::var_os("ProgramFiles").map(PathBuf::from));
782    // The first linker [`suitable`] turned down, which is the answer when nothing after it is any
783    // better. Ubuntu 24.04 has lld 18 on PATH and lld 19 under /usr/lib/llvm-19/bin once somebody
784    // installs `lld-19`, and the second is the one to use without asking them to change PATH.
785    let mut refused = None;
786    for name in &tried {
787        for path in linker_candidates(name, opts, &places) {
788            let linker = Linker { name: name.clone(), path };
789            match suitable(target, &linker) {
790                Ok(()) => return Ok(linker),
791                Err(why) => {
792                    refused.get_or_insert(why);
793                }
794            }
795        }
796    }
797    if let Some(why) = refused {
798        return Err(why);
799    }
800    match &opts.use_ld {
801        Some(name) => Err(Error::Named { name: name.clone() }),
802        None => Err(Error::NoLinker { tried }),
803    }
804}
805
806/// Every file a linker of this name could be, in the order they are asked.
807///
808/// A name with a separator in it is a path and is the only answer. Otherwise the `-B` prefixes,
809/// then every directory on `PATH` rather than the first hit, then the places an lld is installed
810/// without being put on `PATH`. All of them rather than the first, because the first may be an lld
811/// that [`suitable`] turns down and a later one may not be.
812fn linker_candidates(name: &str, opts: &LinkOptions, places: &[PathBuf]) -> Vec<PathBuf> {
813    if name.contains(std::path::MAIN_SEPARATOR) || name.contains('/') {
814        let path = PathBuf::from(name);
815        return if path.is_file() { vec![path] } else { Vec::new() };
816    }
817    let pathext = pathext();
818    let mut found: Vec<PathBuf> = opts
819        .prefixes
820        .iter()
821        .flat_map(|dir| spellings(&dir.join(name), &pathext))
822        .filter(|path| path.is_file())
823        .collect();
824    if let Some(path) = std::env::var_os("PATH") {
825        found.extend(
826            std::env::split_paths(&path)
827                .flat_map(|dir| spellings(&dir.join(name), &pathext))
828                .filter(|p| executable(p)),
829        );
830    }
831    // The same spellings as on PATH, so `ld.lld` here and `ld.lld.exe` on Windows. Only `.exe`
832    // was tried at first, which found nothing in /usr/lib/llvm-19/bin on the Linux machines this
833    // search was written for.
834    if is_lld(name) {
835        for dir in places {
836            for file in spellings(&dir.join(name), &pathext) {
837                if executable(&file) && !found.contains(&file) {
838                    found.push(file);
839                }
840            }
841        }
842    }
843    found
844}
845
846/// The extensions a program name is tried with, from `PATHEXT` on Windows and none elsewhere.
847///
848/// `ld.lld` on Windows is `ld.lld.exe`, and looking for the bare name finds nothing, which is how
849/// a Windows host with LLVM installed and on `PATH` used to be told there was no linker. `PATHEXT`
850/// is what `cmd.exe` uses for the same question, and when it is unset the list is the one
851/// Windows ships with.
852fn pathext() -> Vec<String> {
853    if !cfg!(windows) {
854        return Vec::new();
855    }
856    let list = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_owned());
857    list.split(';').filter(|ext| ext.starts_with('.')).map(str::to_ascii_lowercase).collect()
858}
859
860/// A path with each extension added, or as given when there are none or it already ends in one.
861///
862/// `ld.lld` ends in `.lld`, which is not an extension anybody runs, so the check is against the
863/// list rather than against whether there is a dot in the name at all. The bare name is left out
864/// when there is a list, because a file called `ld.lld` in a Git Bash directory on Windows is a
865/// shell script that `CreateProcess` cannot start.
866fn spellings(path: &Path, exts: &[String]) -> Vec<PathBuf> {
867    let has = path
868        .extension()
869        .and_then(|ext| ext.to_str())
870        .is_some_and(|ext| exts.iter().any(|e| e[1..].eq_ignore_ascii_case(ext)));
871    if exts.is_empty() || has {
872        return vec![path.to_path_buf()];
873    }
874    exts.iter()
875        .map(|ext| {
876            let mut name = path.as_os_str().to_owned();
877            name.push(ext);
878            PathBuf::from(name)
879        })
880        .collect()
881}
882
883/// Whether a name is one of the spellings lld is installed under.
884fn is_lld(name: &str) -> bool {
885    matches!(name, "ld.lld" | "ld64.lld" | "lld" | "lld-link")
886}
887
888/// Where lld is installed without being on `PATH`, newest first where a version is in the name.
889///
890/// Homebrew's `lld` and `llvm` formulae, whose `llvm` is keg-only and so never on `PATH` unless
891/// somebody put it there. Debian and Ubuntu's `lld-<N>` packages, which put the real program in
892/// `/usr/lib/llvm-<N>/bin` and only a versioned name in `/usr/bin`. Fedora's compatibility packages,
893/// which do the same under `/usr/lib64/llvm<N>/bin`. And the LLVM installer for Windows, which puts
894/// everything in `%ProgramFiles%\LLVM\bin` and leaves adding it to `PATH` as a checkbox that is off.
895///
896/// `root` is `/` except in the tests, which build the same tree somewhere they are allowed to.
897fn lld_dirs(root: &Path, program_files: Option<PathBuf>) -> Vec<PathBuf> {
898    let mut dirs: Vec<PathBuf> = [
899        "opt/homebrew/opt/lld/bin",
900        "opt/homebrew/opt/llvm/bin",
901        "usr/local/opt/lld/bin",
902        "usr/local/opt/llvm/bin",
903        "home/linuxbrew/.linuxbrew/opt/lld/bin",
904        "home/linuxbrew/.linuxbrew/opt/llvm/bin",
905    ]
906    .iter()
907    .map(|dir| root.join(dir))
908    .collect();
909    for (parent, prefix) in [("usr/lib", "llvm-"), ("usr/lib64", "llvm")] {
910        let mut versions: Vec<(u32, PathBuf)> = fs::read_dir(root.join(parent))
911            .into_iter()
912            .flatten()
913            .flatten()
914            .filter_map(|entry| {
915                let name = entry.file_name();
916                let version = name.to_str()?.strip_prefix(prefix)?.parse().ok()?;
917                Some((version, entry.path().join("bin")))
918            })
919            .collect();
920        versions.sort_by_key(|(version, _)| std::cmp::Reverse(*version));
921        dirs.extend(versions.into_iter().map(|(_, dir)| dir));
922    }
923    if let Some(dir) = program_files {
924        dirs.push(dir.join("LLVM").join("bin"));
925    }
926    dirs
927}
928
929/// Where to get an lld on the machine this compiler is running on, as the end of a sentence.
930///
931/// One per host rather than a list of every package manager, because the person reading it has one
932/// machine and wants the one command for it. Each names a place [`lld_dirs`] looks, so that doing
933/// what it says is enough and nobody has to edit `PATH` afterwards.
934fn lld_advice() -> &'static str {
935    if cfg!(target_os = "macos") {
936        "`brew install lld` installs one, and rucc finds it in Homebrew's directory without a \
937         change to PATH"
938    } else if cfg!(windows) {
939        "the LLVM installer from https://github.com/llvm/llvm-project/releases, or `winget install \
940         LLVM.LLVM`, installs one in %ProgramFiles%\\LLVM\\bin, where rucc finds it without a \
941         change to PATH"
942    } else {
943        "on Debian and Ubuntu `apt install lld-19` installs one in /usr/lib/llvm-19/bin and on \
944         Fedora `dnf install lld` installs one on PATH, and rucc finds either without a change to \
945         PATH"
946    }
947}
948
949/// The first lld that reads `IMPORT_NAME_EXPORTAS`, which is what a windows-gnu link needs.
950///
951/// 18 does not read it and does not say so, so the number is not a convenience: below it the
952/// answer is wrong rather than absent. tamnd/rucc#1515.
953pub const LLD_EXPORTAS: u32 = 19;
954
955/// Whether a found linker can do this target's link, asked before it is handed anything.
956///
957/// Section 11.6's rule is that suitable is checked and not assumed, and this is the one check that
958/// cannot be made by looking at a file. A windows-gnu link reads import libraries that mingw-w64's
959/// `==` aliases compiled into `IMPORT_NAME_EXPORTAS` records, which lld reads from
960/// [`LLD_EXPORTAS`] on. An older lld writes an import by ordinal zero instead, without a warning
961/// and with a successful exit, so nothing later in the toolchain has anything to notice: the
962/// program is wrong at startup and the link that made it said nothing. Ubuntu 24.04 is the current
963/// LTS and ships 18, so the machine this happens on is an ordinary one.
964///
965/// Every other target is left alone, and so is anything that is not an lld, because this is the one
966/// version of the one linker that is known to answer wrongly rather than not at all.
967///
968/// A linker that will not run or whose version cannot be read is allowed through. What the check
969/// can establish is that a specific old lld is here, and it should not turn every unusual linker
970/// into a refusal on the strength of failing to recognise it.
971///
972/// # Errors
973///
974/// [`Error::TooOld`] when the linker is an lld older than [`LLD_EXPORTAS`] and the target is
975/// windows-gnu.
976pub fn suitable(target: Triple, linker: &Linker) -> Result<(), Error> {
977    if (target.os, target.env) != (Os::Windows, Env::Gnu) {
978        return Ok(());
979    }
980    let Some(found) = lld_major(&reported_version(&linker.path)) else { return Ok(()) };
981    if found >= LLD_EXPORTAS {
982        return Ok(());
983    }
984    Err(Error::TooOld {
985        name: linker.name.clone(),
986        found,
987        target: target.tuple().to_canonical_string(),
988    })
989}
990
991/// What `<linker> --version` prints, or an empty string when it will not say.
992///
993/// A linker that cannot be started is not this function's problem to report, because the link is
994/// about to start it again and say so properly. What this returns for such a one is nothing to
995/// read, which is the same as a linker that ran and said something unrecognisable.
996fn reported_version(path: &Path) -> String {
997    let Ok(out) = Command::new(path).arg("--version").output() else { return String::new() };
998    String::from_utf8_lossy(&out.stdout).into_owned()
999}
1000
1001/// The major version in an lld's `--version`, when the program that printed it was an lld.
1002///
1003/// What lld prints is `LLD 18.1.8 (compatible with GNU linkers)`, with a distribution's own prefix
1004/// in front of it often enough that the word is looked for rather than the line starting with it:
1005/// Ubuntu's says `Ubuntu LLD 18.1.3`. Binutils prints `GNU ld (GNU Binutils for Ubuntu) 2.42` and
1006/// mold prints its own name, and neither has the word, so both come back as [`None`] and are left
1007/// alone.
1008fn lld_major(text: &str) -> Option<u32> {
1009    let mut words = text.split_whitespace();
1010    words.find(|word| *word == "LLD")?;
1011    words.next()?.split('.').next()?.parse().ok()
1012}
1013
1014/// Whether a path is a file this process could run.
1015#[cfg(unix)]
1016fn executable(path: &Path) -> bool {
1017    use std::os::unix::fs::PermissionsExt as _;
1018    path.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
1019}
1020
1021/// Whether a path is a file this process could run.
1022///
1023/// Windows has no executable bit and decides by extension, and the names looked for above carry
1024/// theirs, so being a file is the whole of the question here.
1025#[cfg(not(unix))]
1026fn executable(path: &Path) -> bool {
1027    path.is_file()
1028}
1029
1030/// What the linker is told, in order, not counting the linker itself.
1031///
1032/// Two lines and [`cross_sysroot`] picks which: the one above for this machine, and
1033/// [`rucc_sysroot::argv`]'s for any other. Nothing about the machine is read on the second path, so
1034/// `-###` prints the same line on every host and prints it whether the sysroot has been built or
1035/// not, which is what makes it worth printing.
1036///
1037/// # Errors
1038///
1039/// [`Error::Target`] for a platform there is no native line for yet, which is every one but Linux,
1040/// and [`Error::Cross`] for a cross link that cannot be produced at all.
1041pub fn line(
1042    target: Triple,
1043    opts: &LinkOptions,
1044    items: &[Item],
1045    output: &str,
1046) -> Result<Vec<String>, Error> {
1047    if opts.relocatable {
1048        return relocatable_line(target, opts, items, output);
1049    }
1050    if target.os == Os::Darwin {
1051        return darwin_line(target, opts, items, output);
1052    }
1053    if let Some(sysroot) = cross_sysroot(target, opts) {
1054        return cross_line(target, opts, items, output, &sysroot);
1055    }
1056    if target.os != Os::Linux {
1057        return Err(Error::Target { triple: target.to_string() });
1058    }
1059    let machine = emulation(target);
1060    let root = opts.sysroot.as_deref();
1061    // A distribution's cross tree is linked by the same line, with its two directories in place of
1062    // this machine's, because it is laid out the way this machine's own library is.
1063    let distro = distro_cross(target, opts);
1064    let dirs = match &distro {
1065        Some(distro) => vec![distro.lib()],
1066        None => library_dirs(target, root),
1067    };
1068    // Where a gcc on this machine keeps its own runtime, which is a different place from where
1069    // the C library keeps its own, and where our runtime is if it was built for this target.
1070    let runtime = match distro {
1071        Some(distro) => distro.gcc,
1072        None => runtime_dirs(target, root),
1073    };
1074    let ours = if opts.no_builtins_lib { None } else { builtins_archive(target, &opts.prefixes) };
1075    let mut args = vec![
1076        "-o".to_owned(),
1077        output.to_owned(),
1078        // Which of the several formats one `ld` can write is meant. A linker built for more than
1079        // one machine guesses from its first input otherwise, and a link of no objects at all has
1080        // nothing to guess from.
1081        "-m".to_owned(),
1082        machine.to_owned(),
1083        // The table a program unwinds through, which a C program with no exceptions in it still
1084        // needs because `backtrace` and every crash handler read it.
1085        "--eh-frame-hdr".to_owned(),
1086        // The symbol hash a dynamic loader from this century reads. The old one is still written
1087        // alongside by default on some distributions, and asking for this one is what stops a link
1088        // from carrying a table nothing has needed since 2006.
1089        "--hash-style=gnu".to_owned(),
1090    ];
1091
1092    let pie = opts.pie.unwrap_or(!opts.is_static && !opts.shared);
1093    if opts.shared {
1094        args.push("-shared".to_owned());
1095    } else if opts.is_static {
1096        args.push("-static".to_owned());
1097    } else if pie {
1098        args.push("-pie".to_owned());
1099    } else {
1100        args.push("-no-pie".to_owned());
1101    }
1102    if !opts.is_static && !opts.shared {
1103        args.push("-dynamic-linker".to_owned());
1104        args.push(target_path(root, loader(target)));
1105    }
1106    if opts.export_dynamic {
1107        args.push("--export-dynamic".to_owned());
1108    }
1109    if opts.strip {
1110        args.push("-s".to_owned());
1111    }
1112
1113    if opts.wants_startfiles() {
1114        for name in startfile(opts, pie).into_iter().chain(["crti.o"]) {
1115            if let Some(path) = find_file(&dirs, name) {
1116                args.push(path.display().to_string());
1117            }
1118        }
1119        // The compiler's own startup file, which runs the static constructors. Three spellings
1120        // of the same thing, and which one is right is about how the code in it refers to
1121        // itself: `S` for a position independent result, `T` for a static one, plain for the
1122        // rest. Skipped when there is no gcc on the machine to take it from, because a program
1123        // with no constructor in it does not miss it.
1124        let begin = if opts.shared || pie {
1125            "crtbeginS.o"
1126        } else if opts.is_static {
1127            "crtbeginT.o"
1128        } else {
1129            "crtbegin.o"
1130        };
1131        if let Some(path) = find_file(&runtime, begin).or_else(|| find_file(&runtime, "crtbegin.o"))
1132        {
1133            args.push(path.display().to_string());
1134        }
1135    }
1136
1137    for dir in &opts.search {
1138        args.push(format!("-L{}", dir.display()));
1139    }
1140    for dir in &dirs {
1141        args.push(format!("-L{}", dir.display()));
1142    }
1143    // Where `libgcc.a` and `libgcc_eh.a` are, which is not where the C library is. Nothing is
1144    // added when there is no gcc on the machine, and then the `-l` names below are left off too.
1145    for dir in &runtime {
1146        args.push(format!("-L{}", dir.display()));
1147    }
1148
1149    for item in items {
1150        match item {
1151            Item::File(path) => args.push(path.clone()),
1152            Item::Library(name) => args.push(format!("-l{name}")),
1153            Item::Linker(arg) => args.push(arg.clone()),
1154        }
1155    }
1156    // After the objects, because a static archive is searched for what is undefined at the point
1157    // it is reached and a library named before the object that needs it contributes nothing.
1158    args.extend(runtime_items(opts, &runtime, ours.as_deref()));
1159
1160    if opts.wants_startfiles() {
1161        // The other end of `crtbegin`, and it goes before `crtn.o` for the same reason `crti.o`
1162        // goes before `crtbegin`: the four are two nested pairs and not four separate files.
1163        // The fast math constructor, ahead of `crtend` where gcc puts it. Skipped when there is
1164        // no gcc to take it from, as `crtbegin` is.
1165        if opts.wants_fastmath() {
1166            if let Some(path) = find_file(&runtime, "crtfastmath.o") {
1167                args.push(path.display().to_string());
1168            }
1169        }
1170        let end = if opts.shared || pie { "crtendS.o" } else { "crtend.o" };
1171        if let Some(path) = find_file(&runtime, end).or_else(|| find_file(&runtime, "crtend.o")) {
1172            args.push(path.display().to_string());
1173        }
1174        if let Some(path) = find_file(&dirs, "crtn.o") {
1175            args.push(path.display().to_string());
1176        }
1177    }
1178
1179    Ok(args)
1180}
1181
1182/// The line for `-r`, which is the objects and the machine and nothing else.
1183///
1184/// No sysroot is read, because a relocatable link takes nothing from the C library, so this is the
1185/// same line for this machine and for any other Linux target. The `-L` directories the command
1186/// line gave are kept for a `-l` written on it, which the linker still resolves against archives.
1187fn relocatable_line(
1188    target: Triple,
1189    opts: &LinkOptions,
1190    items: &[Item],
1191    output: &str,
1192) -> Result<Vec<String>, Error> {
1193    if target.os == Os::Darwin {
1194        // `ld64` joins objects with `-r` too, and needs only to be told the architecture, since
1195        // nothing from the SDK goes into an object that is still going to be linked.
1196        let mut args = vec![
1197            "-r".to_owned(),
1198            "-arch".to_owned(),
1199            darwin_arch(target)?.to_owned(),
1200            "-o".to_owned(),
1201            output.to_owned(),
1202        ];
1203        for dir in &opts.search {
1204            args.push(format!("-L{}", dir.display()));
1205        }
1206        push_items(&mut args, items);
1207        return Ok(args);
1208    }
1209    if target.os != Os::Linux {
1210        return Err(Error::Target { triple: target.to_string() });
1211    }
1212    let mut args = vec![
1213        "-o".to_owned(),
1214        output.to_owned(),
1215        "-m".to_owned(),
1216        emulation(target).to_owned(),
1217        "-r".to_owned(),
1218    ];
1219    if opts.strip {
1220        args.push("-s".to_owned());
1221    }
1222    for dir in &opts.search {
1223        args.push(format!("-L{}", dir.display()));
1224    }
1225    for item in items {
1226        match item {
1227            Item::File(path) => args.push(path.clone()),
1228            Item::Library(name) => args.push(format!("-l{name}")),
1229            Item::Linker(arg) => args.push(arg.clone()),
1230        }
1231    }
1232    Ok(args)
1233}
1234
1235/// The line `ld64` takes, which is Apple's `ld` or lld's Mach-O flavour.
1236///
1237/// Shorter than the ELF one, because the SDK carries everything a program starts with. There are no
1238/// start files to find: `libSystem` has the C library, the startup code and the runtime in it, and
1239/// `dyld` calls `main` itself. What the linker has to be told is the architecture, the platform with
1240/// the oldest release the program runs on and the SDK it was built against, and where the SDK is,
1241/// which `-syslibroot` puts in front of every library it looks for.
1242///
1243/// `-pie` and `-no-pie` are not passed on. Every arm64 program on a Mac is position independent and
1244/// `ld64` rejects `-no_pie` there, so the flag has nothing to change. `-static` is refused, because
1245/// Apple ships no static C library and a static executable is a kernel's business.
1246///
1247/// # Errors
1248///
1249/// [`Error::Cross`] when there is no SDK to link against, or for a static link, or an architecture
1250/// that has no Mach-O name.
1251pub fn darwin_line(
1252    target: Triple,
1253    opts: &LinkOptions,
1254    items: &[Item],
1255    output: &str,
1256) -> Result<Vec<String>, Error> {
1257    let arch = darwin_arch(target)?;
1258    if opts.is_static && !opts.shared {
1259        return Err(Error::Cross {
1260            why: "there is no static C library for Apple platforms, so -static cannot make a \
1261                  program for one"
1262                .to_owned(),
1263        });
1264    }
1265    let Some(sdk) = crate::library::sdk(opts.sysroot.as_deref()) else {
1266        return Err(Error::Cross {
1267            why: format!(
1268                "no SDK was found to link {} against. Install the command line tools with \
1269                 `xcode-select --install`, or name one with -isysroot <dir> or SDKROOT",
1270                target_tuple(target, opts).to_canonical_string()
1271            ),
1272        });
1273    };
1274    let tuple = target_tuple(target, opts);
1275    let (platform, default) = match (tuple.os(), tuple.env()) {
1276        (rucc_tuple::Os::IOs, rucc_tuple::Env::Simulator) => ("ios-simulator", "14.0"),
1277        (rucc_tuple::Os::IOs, rucc_tuple::Env::MacAbi) => ("mac-catalyst", "14.0"),
1278        (rucc_tuple::Os::IOs, _) => ("ios", "14.0"),
1279        _ => ("macos", "11.0"),
1280    };
1281    let minimum = opts
1282        .os_version
1283        .or_else(|| tuple.os_version())
1284        .map_or_else(|| default.to_owned(), |version| version.to_string());
1285    // What the SDK says it is, which `ld64` records so the loader can tell which behaviours the
1286    // program was built to expect. The deployment target when the SDK does not say, which is the
1287    // answer that asks for no behaviour newer than the program claims to run on.
1288    let version = sdk_version(&sdk).unwrap_or_else(|| minimum.clone());
1289
1290    let mut args = vec![
1291        "-arch".to_owned(),
1292        arch.to_owned(),
1293        "-platform_version".to_owned(),
1294        platform.to_owned(),
1295        minimum,
1296        version,
1297        "-syslibroot".to_owned(),
1298        sdk.display().to_string(),
1299        "-o".to_owned(),
1300        output.to_owned(),
1301    ];
1302    if opts.shared {
1303        args.push("-dylib".to_owned());
1304    }
1305    if opts.export_dynamic {
1306        args.push("-export_dynamic".to_owned());
1307    }
1308    if opts.strip {
1309        // The debug map and the local symbols, which between them are what `-s` leaves out of an
1310        // ELF program. `ld64` has no one flag for it.
1311        args.push("-S".to_owned());
1312        args.push("-x".to_owned());
1313    }
1314    for dir in &opts.search {
1315        args.push(format!("-L{}", dir.display()));
1316    }
1317    push_items(&mut args, items);
1318    if opts.wants_runtime() && !opts.no_builtins_lib {
1319        if let Some(ours) = builtins_archive(target, &opts.prefixes) {
1320            args.push(ours.display().to_string());
1321        }
1322    }
1323    if opts.wants_defaultlibs() {
1324        args.push("-lSystem".to_owned());
1325    }
1326    Ok(args)
1327}
1328
1329/// What `ld64` calls the architecture, which is not what the triple does.
1330fn darwin_arch(target: Triple) -> Result<&'static str, Error> {
1331    match target.arch {
1332        Arch::Aarch64 => Ok("arm64"),
1333        Arch::X86_64 => Ok("x86_64"),
1334        _ => Err(Error::Target { triple: target.to_string() }),
1335    }
1336}
1337
1338/// The version an SDK says it is, from the `SDKSettings.json` every SDK since Xcode 7 has at its
1339/// root, or from its directory name, which is `MacOSX15.2.sdk` when it is not the unversioned link.
1340///
1341/// Read by hand rather than parsed, because the one field wanted is a quoted string at the top
1342/// level and a JSON parser would be a dependency for one line.
1343fn sdk_version(sdk: &Path) -> Option<String> {
1344    let valid = |text: &str| {
1345        !text.is_empty()
1346            && text
1347                .split('.')
1348                .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
1349    };
1350    if let Ok(text) = fs::read_to_string(sdk.join("SDKSettings.json")) {
1351        if let Some(at) = text.find("\"Version\"") {
1352            let rest = &text[at + "\"Version\"".len()..];
1353            let rest = rest.trim_start().strip_prefix(':')?.trim_start().strip_prefix('"')?;
1354            let version = &rest[..rest.find('"')?];
1355            if valid(version) {
1356                return Some(version.to_owned());
1357            }
1358        }
1359    }
1360    let name = sdk.file_name()?.to_str()?.strip_suffix(".sdk")?;
1361    let version = name.trim_start_matches(|c: char| c.is_ascii_alphabetic());
1362    valid(version).then(|| version.to_owned())
1363}
1364
1365/// The objects, libraries and linker words, in the order they were written.
1366fn push_items(args: &mut Vec<String>, items: &[Item]) {
1367    for item in items {
1368        match item {
1369            Item::File(path) => args.push(path.clone()),
1370            Item::Library(name) => args.push(format!("-l{name}")),
1371            Item::Linker(arg) => args.push(arg.clone()),
1372        }
1373    }
1374}
1375
1376/// The startup file the C library brings, or `None` for a link that calls nothing.
1377///
1378/// This is what calls `main` and what passes it the arguments, so a shared object takes none of
1379/// them: nothing starts one and it has no `main` to be started at. `Scrt1.o` rather than `crt1.o`
1380/// when the result moves, because the two differ in whether the reference to `main` in them is one
1381/// a loader may relocate.
1382///
1383/// A profiled program gets a different one again, which does all of that and starts and stops the
1384/// counting around it. There are two of those rather than three: the one that relocates itself is
1385/// only needed by a static position independent link, and every other link takes the plain one,
1386/// which is what gcc does with the same flag.
1387fn startfile(opts: &LinkOptions, pie: bool) -> Option<&'static str> {
1388    if opts.shared {
1389        None
1390    } else if opts.profile {
1391        Some(if pie && opts.is_static { "grcrt1.o" } else { "gcrt1.o" })
1392    } else if pie {
1393        Some("Scrt1.o")
1394    } else {
1395        Some("crt1.o")
1396    }
1397}
1398
1399/// The libraries the compiler's own runtime contributes, in the order the linker wants them.
1400///
1401/// The C library first, then ours, then the machine's `libgcc`. Order inside this list is not
1402/// about whether a symbol resolves, it is about which archive supplies one that more than one of
1403/// them defines, and the two places that happens both have a right answer.
1404///
1405/// `memcpy` and its three neighbours are in the C library on a hosted target and in ours only for
1406/// a freestanding one, which is what `spec/12-abi-and-runtime.md` section 12.8 says they are for.
1407/// glibc's are written in assembly per microarchitecture and ours is a word at a time loop, so a
1408/// link that took ours over glibc's would be slower at the one routine every program reaches.
1409///
1410/// The wide arithmetic is in ours and in `libgcc` both, and the two are ABI-identical on purpose,
1411/// so which one answers is not a correctness question. Ours comes first because it is ours, and
1412/// `-fno-builtins-lib` leaves it off for somebody who would rather it were not.
1413///
1414/// A static link puts the whole list inside `--start-group`. `libc.a` refers to `_Unwind_Resume`,
1415/// and the unwinder refers back into `libc.a`, so a linker walking the list once resolves
1416/// whichever it reaches first and reports the other as undefined. That is exactly the failure
1417/// issue #277 describes and the group is the fix for it.
1418///
1419/// A dynamic link needs no group, because the shared `libc` resolves its own references inside
1420/// itself. `libgcc_s` is asked for `--as-needed` there, the way gcc asks for it, so a program that
1421/// never unwinds does not acquire a dependency on it.
1422fn runtime_items(opts: &LinkOptions, runtime: &[PathBuf], ours: Option<&Path>) -> Vec<String> {
1423    let mut args = Vec::new();
1424    if !opts.wants_defaultlibs() && !opts.wants_runtime() {
1425        return args;
1426    }
1427    // Only when there is a gcc to take them from. On a machine without one the names would be an
1428    // error about a library that was never going to be there, and a program that needs neither
1429    // the unwinder nor a wide divide links and runs without them.
1430    let has_gcc = find_file(runtime, "libgcc.a").is_some();
1431
1432    if opts.is_static {
1433        args.push("--start-group".to_owned());
1434    }
1435    if opts.wants_defaultlibs() {
1436        args.push("-lc".to_owned());
1437    }
1438    if opts.wants_runtime() {
1439        if let Some(path) = ours {
1440            args.push(path.display().to_string());
1441        }
1442        if has_gcc {
1443            args.push("-lgcc".to_owned());
1444            if opts.is_static {
1445                args.push("-lgcc_eh".to_owned());
1446            }
1447        }
1448    }
1449    if opts.is_static {
1450        args.push("--end-group".to_owned());
1451    } else if opts.wants_runtime() && has_gcc {
1452        // The shared half, and only if something still wants it after everything above.
1453        args.push("--as-needed".to_owned());
1454        args.push("-lgcc_s".to_owned());
1455        args.push("--no-as-needed".to_owned());
1456    }
1457    args
1458}
1459
1460/// Where a gcc on this machine keeps `crtbegin.o`, `crtend.o` and `libgcc.a`, newest first.
1461///
1462/// This is not where the C library's files are. A distribution puts them under a directory named
1463/// for the gcc version, and there may be several, so the answer is every one that exists with the
1464/// highest version in front. Newest first because a newer `libgcc` is a superset of an older one
1465/// and because that is the one the C library on the same machine was built against.
1466#[must_use]
1467pub fn runtime_dirs(target: Triple, sysroot: Option<&Path>) -> Vec<PathBuf> {
1468    let libc = match target.env {
1469        Env::Musl => "musl",
1470        Env::None | Env::Gnu | Env::Msvc => "gnu",
1471    };
1472    let arch = target.arch.as_str();
1473    // The spellings the distributions use for the same triple. Debian and Ubuntu drop the vendor
1474    // field, the source builds and Arch keep `pc`, and Red Hat and SUSE write their own name in
1475    // it, so all of them are looked for and the ones that are there are taken.
1476    let names = [
1477        format!("{arch}-linux-{libc}"),
1478        format!("{arch}-pc-linux-{libc}"),
1479        format!("{arch}-redhat-linux"),
1480        format!("{arch}-suse-linux"),
1481        format!("{arch}-alpine-linux-{libc}"),
1482    ];
1483    let mut found = Vec::new();
1484    for base in ["/usr/lib/gcc", "/usr/lib64/gcc", "/usr/local/lib/gcc"] {
1485        for name in &names {
1486            found.extend(newest_first(&under(sysroot, &format!("{base}/{name}"))));
1487        }
1488    }
1489    found
1490}
1491
1492/// The version directories under one of gcc's, highest version first.
1493fn newest_first(dir: &Path) -> Vec<PathBuf> {
1494    let Ok(entries) = fs::read_dir(dir) else { return Vec::new() };
1495    let mut versions: Vec<(Vec<u64>, PathBuf)> = entries
1496        .flatten()
1497        .map(|e| e.path())
1498        .filter(|p| p.is_dir())
1499        .map(|p| (version_key(&p), p))
1500        .collect();
1501    // Descending, so the highest version is the first place `find_file` looks. Ties keep the order
1502    // the directory gave, which is arbitrary and does not matter because two directories that sort
1503    // the same hold the same version.
1504    versions.sort_by(|a, b| b.0.cmp(&a.0));
1505    versions.into_iter().map(|(_, path)| path).collect()
1506}
1507
1508/// A directory name read as a version, so that `13` sorts above `9` and `10.2` above `10`.
1509///
1510/// A name that is not a version at all sorts below every name that is, rather than being left
1511/// out, because a directory holding a `libgcc.a` is worth looking in whatever it is called.
1512fn version_key(dir: &Path) -> Vec<u64> {
1513    let name = dir.file_name().unwrap_or_default().to_string_lossy();
1514    name.split('.').map(|part| part.parse::<u64>().unwrap_or(0)).collect()
1515}
1516
1517/// Our own runtime library for this target, if it was built.
1518///
1519/// Looked for beside the compiler rather than at a path decided when the compiler was built, for
1520/// the same reason everything else here is looked for: one binary runs wherever it is copied. A
1521/// `-B` prefix is asked first, because that is what a `-B` prefix is for.
1522#[must_use]
1523pub fn builtins_archive(target: Triple, prefixes: &[PathBuf]) -> Option<PathBuf> {
1524    // The name from the crate that puts it on a line, rather than a second spelling of it here,
1525    // which is what that constant asks of anybody who needs the name.
1526    const NAME: &str = rucc_sysroot::link::BUILTINS;
1527    // The four field triple first and then the tuple the sysroots are named by, because `cargo
1528    // xtask builtins --target=aarch64-linux-musl` names its directory after what it was given, and
1529    // that shorter spelling is the one people type.
1530    let spellings = [target.to_string(), target.tuple().to_string()];
1531    let mut places: Vec<PathBuf> = Vec::new();
1532    for prefix in prefixes {
1533        for triple in &spellings {
1534            places.push(prefix.join(triple).join(NAME));
1535        }
1536        places.push(prefix.join(NAME));
1537    }
1538    if let Some(dir) =
1539        std::env::current_exe().ok().and_then(|exe| exe.parent().map(Path::to_path_buf))
1540    {
1541        // A release archive: the compiler at the top of the unpacked directory and the runtime
1542        // beside it in `lib/rucc/<triple>`, which is how `.github/package.sh` lays one out.
1543        for triple in &spellings {
1544            places.push(dir.join("lib").join("rucc").join(triple).join(NAME));
1545        }
1546        if let Some(up) = dir.parent() {
1547            for triple in &spellings {
1548                // An install: the compiler in `bin` and its runtime in `lib/rucc/<triple>`.
1549                places.push(up.join("lib").join("rucc").join(triple).join(NAME));
1550                // A build tree: the compiler in `target/release` and the runtime, which is built
1551                // for the target and not the host, in `target/<triple>/release`.
1552                for profile in ["release", "debug"] {
1553                    places.push(up.join(triple).join(profile).join(NAME));
1554                }
1555            }
1556        }
1557        places.push(dir.join(NAME));
1558    }
1559    places.into_iter().find(|path| path.is_file())
1560}
1561
1562/// Which output format this `ld` should write, in the name `ld` knows it by.
1563fn emulation(target: Triple) -> &'static str {
1564    match target.arch {
1565        Arch::X86_64 => "elf_x86_64",
1566        Arch::Aarch64 => "aarch64linux",
1567        Arch::Riscv64 => "elf64lriscv",
1568    }
1569}
1570
1571/// The program that starts a dynamically linked program, whose path is part of the file.
1572///
1573/// It is a per-target constant rather than something to look for, because the name is fixed by
1574/// the platform's ABI and a program naming a different one does not start.
1575fn loader(target: Triple) -> &'static str {
1576    match (target.arch, target.env) {
1577        (Arch::X86_64, Env::Musl) => "/lib/ld-musl-x86_64.so.1",
1578        (Arch::X86_64, _) => "/lib64/ld-linux-x86-64.so.2",
1579        (Arch::Aarch64, Env::Musl) => "/lib/ld-musl-aarch64.so.1",
1580        (Arch::Aarch64, _) => "/lib/ld-linux-aarch64.so.1",
1581        (Arch::Riscv64, Env::Musl) => "/lib/ld-musl-riscv64.so.1",
1582        (Arch::Riscv64, _) => "/lib/ld-linux-riscv64-lp64d.so.1",
1583    }
1584}
1585
1586/// Where the library's own files might be, in search order.
1587///
1588/// The multiarch directory first for the reason it comes first in the header search: it is where
1589/// a distribution that can hold two architectures at once puts the one being asked for, and a
1590/// distribution that cannot simply does not have it. `lib64` after it, which is what the
1591/// distributions that split by word size use instead, and `lib` last, which is every other one.
1592#[must_use]
1593pub fn candidates(target: Triple, sysroot: Option<&Path>) -> Vec<PathBuf> {
1594    let multiarch = multiarch(target);
1595    [
1596        format!("/usr/lib/{multiarch}"),
1597        format!("/lib/{multiarch}"),
1598        "/usr/lib64".to_owned(),
1599        "/lib64".to_owned(),
1600        "/usr/lib".to_owned(),
1601        "/lib".to_owned(),
1602    ]
1603    .into_iter()
1604    .map(|dir| under(sysroot, &dir))
1605    .collect()
1606}
1607
1608/// The name a distribution that holds two architectures at once files this target under.
1609///
1610/// `x86_64-linux-gnu` and its friends, which is what `gcc -print-multiarch` prints and what a
1611/// build system pastes into a path when it is looking for a library itself.
1612#[must_use]
1613pub fn multiarch(target: Triple) -> String {
1614    let libc = match target.env {
1615        Env::Musl => "musl",
1616        Env::None | Env::Gnu | Env::Msvc => "gnu",
1617    };
1618    format!("{}-linux-{libc}", target.arch.as_str())
1619}
1620
1621/// The candidates that are there.
1622fn library_dirs(target: Triple, sysroot: Option<&Path>) -> Vec<PathBuf> {
1623    candidates(target, sysroot).into_iter().filter(|dir| dir.is_dir()).collect()
1624}
1625
1626/// Where a library is looked for, in the order it is looked for in.
1627///
1628/// The command line first and the target's own after it, which is the order the linker is handed
1629/// and therefore the order `-print-search-dirs` has to print.
1630#[must_use]
1631pub fn search_dirs(link: &LinkOptions, target: Triple) -> Vec<PathBuf> {
1632    let mut dirs = link.search.clone();
1633    // A cross link searches the sysroot's directory and, for a libc that is a stub, the one its
1634    // stubs are written to, so this is those and not the machine's. What `-print-search-dirs` says is what a build
1635    // system pastes into a link line of its own, and an answer that named `/usr/lib` for a target
1636    // whose link line never goes near it would be worse than no answer at all.
1637    if let Some(sysroot) = cross_sysroot(target, link) {
1638        dirs.push(sysroot.lib());
1639        if rucc_sysroot::link::libc(sysroot.target()) == rucc_sysroot::link::Libc::Stub {
1640            dirs.push(sysroot.stubs().to_path_buf());
1641        }
1642        return dirs;
1643    }
1644    if let Some(distro) = distro_cross(target, link) {
1645        dirs.push(distro.lib());
1646        return dirs;
1647    }
1648    dirs.extend(candidates(target, link.sysroot.as_deref()));
1649    dirs
1650}
1651
1652/// The full path of a file with that name, when one of the search directories holds it.
1653///
1654/// What `-print-file-name=` answers. GCC prints the name back unchanged when it finds nothing,
1655/// which is what makes the flag safe to paste into a link line either way.
1656#[must_use]
1657pub fn find_in_search(link: &LinkOptions, target: Triple, name: &str) -> Option<PathBuf> {
1658    find_file(&search_dirs(link, target), name)
1659}
1660
1661/// The first of those directories holding a file of that name.
1662fn find_file(dirs: &[PathBuf], name: &str) -> Option<PathBuf> {
1663    dirs.iter().map(|dir| dir.join(name)).find(|path| path.is_file())
1664}
1665
1666/// A path under the sysroot, when there is one.
1667fn under(sysroot: Option<&Path>, path: &str) -> PathBuf {
1668    match sysroot {
1669        // `strip_prefix` because joining an absolute path replaces the root rather than extending
1670        // it, which would make every entry the unprefixed one.
1671        Some(root) => root.join(path.strip_prefix('/').unwrap_or(path)),
1672        None => PathBuf::from(path),
1673    }
1674}
1675
1676/// A path on the machine that will run the program, rather than on the one compiling it.
1677///
1678/// Written with the separator of the target and not of the host, which matters for the one path
1679/// that is not looked at here but stored in the file and read by something else later: the loader
1680/// a dynamic program names. A Windows host joining it would put a backslash in the middle of a
1681/// name that a Linux loader has to find, and the program would not start.
1682fn target_path(sysroot: Option<&Path>, path: &str) -> String {
1683    match sysroot {
1684        Some(root) => {
1685            let root = root.display().to_string();
1686            format!("{}/{}", root.trim_end_matches(['/', '\\']), path.trim_start_matches('/'))
1687        }
1688        None => path.to_owned(),
1689    }
1690}
1691
1692/// The whole invocation as one line, quoted the way `-###` prints it.
1693#[must_use]
1694pub fn render(linker: &Linker, args: &[String]) -> String {
1695    let mut out = linker.path.display().to_string();
1696    for arg in args {
1697        out.push(' ');
1698        if arg.is_empty() || arg.contains(char::is_whitespace) {
1699            out.push('"');
1700            out.push_str(arg);
1701            out.push('"');
1702        } else {
1703            out.push_str(arg);
1704        }
1705    }
1706    out
1707}
1708
1709/// How long a command line may be on Windows before the arguments go in a file instead.
1710///
1711/// `CreateProcess` takes 32767 characters, the program's own path and the quoting included, and
1712/// what is left for the arguments is not worth computing to the character.
1713const WINDOWS_LINE: usize = 30_000;
1714
1715/// The same for every other host, where the limit is a megabyte or more shared with the
1716/// environment, and a link this long is Kbuild's `-r` of a whole subsystem.
1717const UNIX_LINE: usize = 256 * 1024;
1718
1719/// Whether these arguments, joined with a space and a pair of quotes each, are over `limit`.
1720fn too_long(args: &[String], limit: usize) -> bool {
1721    args.iter().map(|arg| arg.len() + 3).sum::<usize>() > limit
1722}
1723
1724/// The arguments that stay on the command line and the ones that go in the file.
1725///
1726/// `-m` and its value stay, because they are what makes `ld.lld` pick its MinGW driver over its
1727/// ELF one, and it is better not to depend on that choice looking inside the file.
1728fn split_for_file(args: &[String]) -> (Vec<String>, Vec<String>) {
1729    let mut front = Vec::new();
1730    let mut rest = Vec::with_capacity(args.len());
1731    let mut words = args.iter();
1732    while let Some(arg) = words.next() {
1733        if arg == "-m" {
1734            front.push(arg.clone());
1735            front.extend(words.next().cloned());
1736        } else {
1737            rest.push(arg.clone());
1738        }
1739    }
1740    (front, rest)
1741}
1742
1743/// Whether this linker reads a response file with Windows quoting, where a backslash is an
1744/// ordinary character unless it comes before a quote.
1745///
1746/// lld does on a Windows host, both its ELF driver and its MinGW one, and the MinGW one has no
1747/// option to say otherwise. GNU ld reads the GNU way on every host, MSYS2's included.
1748fn windows_quoting(linker: &Linker) -> bool {
1749    let file = linker.path.file_stem().and_then(|stem| stem.to_str()).unwrap_or_default();
1750    cfg!(windows) && (is_lld(&linker.name) || file.starts_with("ld.lld") || file.starts_with("lld"))
1751}
1752
1753/// The words of a response file, one to a line, quoted so that the linker reads them back as
1754/// they were.
1755///
1756/// The GNU way is a backslash before every quote and every backslash. The Windows way leaves a
1757/// backslash alone unless a run of them ends at a quote, and then doubles the run and escapes the
1758/// quote, which is the rule `CommandLineToArgvW` reads with and so the rule LLVM reads with too.
1759fn response_text(args: &[String], windows: bool) -> String {
1760    let mut text = String::new();
1761    for arg in args {
1762        text.push('"');
1763        let mut slashes = 0;
1764        for c in arg.chars() {
1765            match c {
1766                '\\' if windows => slashes += 1,
1767                '"' if windows => {
1768                    text.extend(std::iter::repeat_n('\\', slashes * 2 + 1));
1769                    text.push('"');
1770                    slashes = 0;
1771                }
1772                _ if windows => {
1773                    text.extend(std::iter::repeat_n('\\', slashes));
1774                    text.push(c);
1775                    slashes = 0;
1776                }
1777                '"' | '\\' => {
1778                    text.push('\\');
1779                    text.push(c);
1780                }
1781                _ => text.push(c),
1782            }
1783        }
1784        text.extend(std::iter::repeat_n('\\', slashes * 2));
1785        text.push_str("\"\n");
1786    }
1787    text
1788}
1789
1790/// Runs the linker and waits for it.
1791///
1792/// A line too long for the host goes to the linker as a response file, which is what a Windows
1793/// build of a large program needs: a few hundred objects in a deep directory are past what
1794/// `CreateProcess` takes.
1795///
1796/// # Errors
1797///
1798/// [`Error::Spawn`] when it could not be started, which is a machine problem, and
1799/// [`Error::Refused`] when it ran and said no, which is a program problem and one the linker has
1800/// already explained on its own error output.
1801pub fn run(linker: &Linker, args: &[String]) -> Result<(), Error> {
1802    let spawn = |why: std::io::Error| Error::Spawn {
1803        path: linker.path.display().to_string(),
1804        why: why.to_string(),
1805    };
1806    let mut command = Command::new(&linker.path);
1807    let mut written = None;
1808    if too_long(args, if cfg!(windows) { WINDOWS_LINE } else { UNIX_LINE }) {
1809        let (front, rest) = split_for_file(args);
1810        let path = std::env::temp_dir().join(format!("rucc-link-{}.rsp", std::process::id()));
1811        fs::write(&path, response_text(&rest, windows_quoting(linker))).map_err(spawn)?;
1812        let mut at = OsString::from("@");
1813        at.push(&path);
1814        command.args(front).arg(at);
1815        written = Some(path);
1816    } else {
1817        command.args(args.iter().map(OsString::from));
1818    }
1819    let status = command.status();
1820    if let Some(path) = written {
1821        let _ = fs::remove_file(path);
1822    }
1823    let status = status.map_err(spawn)?;
1824    if status.success() {
1825        return Ok(());
1826    }
1827    // Nothing is added to what the linker printed. It has already named the symbol or the file,
1828    // and a second message from here saying that linking failed would only push the first one
1829    // further up the screen.
1830    Err(Error::Refused {
1831        status: match status.code() {
1832            Some(code) => format!("exited with status {code}"),
1833            None => "was killed before it finished".to_owned(),
1834        },
1835    })
1836}
1837
1838#[cfg(test)]
1839mod tests {
1840    use super::*;
1841
1842    fn linux() -> Triple {
1843        Triple::new(Arch::X86_64, Os::Linux, Env::Gnu)
1844    }
1845
1846    fn one(name: &str) -> Vec<Item> {
1847        vec![Item::File(name.to_owned())]
1848    }
1849
1850    #[test]
1851    fn the_fast_one_is_looked_for_first_and_the_platforms_own_last() {
1852        let names = order(linux(), &LinkOptions::default());
1853        assert_eq!(names.first().map(String::as_str), Some("ld.mold"));
1854        assert_eq!(names.last().map(String::as_str), Some("ld"));
1855    }
1856
1857    #[test]
1858    fn naming_one_is_the_whole_of_the_order() {
1859        let opts = LinkOptions { use_ld: Some("gold".to_owned()), ..LinkOptions::default() };
1860        assert_eq!(order(linux(), &opts), ["ld.gold", "gold"]);
1861    }
1862
1863    #[test]
1864    fn a_dynamic_program_names_the_loader_that_will_start_it() {
1865        let args = line(linux(), &LinkOptions::default(), &one("a.o"), "a.out").expect("a line");
1866        let at = args.iter().position(|a| a == "-dynamic-linker").expect("the flag");
1867        assert!(args[at + 1].ends_with("/lib64/ld-linux-x86-64.so.2"), "{args:?}");
1868    }
1869
1870    /// Kbuild's `built-in.o`, which is objects joined into an object and is linked again later.
1871    #[test]
1872    fn a_relocatable_link_is_the_objects_and_nothing_a_program_needs() {
1873        let opts = LinkOptions { relocatable: true, ..LinkOptions::default() };
1874        let args = line(linux(), &opts, &one("a.o"), "built-in.o").expect("a line");
1875        assert_eq!(args, ["-o", "built-in.o", "-m", "elf_x86_64", "-r", "a.o"]);
1876    }
1877
1878    #[test]
1879    fn a_static_program_names_no_loader_because_nothing_will_start_it() {
1880        let opts = LinkOptions { is_static: true, ..LinkOptions::default() };
1881        let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
1882        assert!(args.contains(&"-static".to_owned()), "{args:?}");
1883        assert!(!args.contains(&"-dynamic-linker".to_owned()), "{args:?}");
1884    }
1885
1886    #[test]
1887    fn the_startup_file_of_a_program_that_moves_is_not_the_one_of_a_program_that_does_not() {
1888        let moving = LinkOptions { pie: Some(true), ..LinkOptions::default() };
1889        let fixed = LinkOptions { pie: Some(false), ..LinkOptions::default() };
1890        let named = |opts: &LinkOptions| {
1891            line(linux(), opts, &one("a.o"), "a.out")
1892                .expect("a line")
1893                .iter()
1894                .filter_map(|a| Path::new(a).file_name().map(|n| n.to_string_lossy().into_owned()))
1895                .find(|n| n.ends_with("crt1.o"))
1896        };
1897        // Only when the machine running this has them, which is what makes this two assertions
1898        // rather than one: a machine with no glibc development files has neither to find.
1899        if let Some(name) = named(&moving) {
1900            assert_eq!(name, "Scrt1.o");
1901            assert_eq!(named(&fixed).as_deref(), Some("crt1.o"));
1902        }
1903    }
1904
1905    /// A profiled program is started by a startup file of its own.
1906    ///
1907    /// The counts it keeps have to be started before `main` runs and written out after it returns,
1908    /// and what does both is this file rather than anything the compiler wrote. So a build that
1909    /// compiles with the flag and links without it produces a program that calls the hook on every
1910    /// function and never writes a profile, which is the failure this is here to keep out.
1911    ///
1912    /// A shared object takes none of them either way, since nothing starts one.
1913    #[test]
1914    fn a_profiled_program_is_started_by_the_startup_file_that_counts() {
1915        let profile = LinkOptions { profile: true, ..LinkOptions::default() };
1916        assert_eq!(startfile(&profile, false), Some("gcrt1.o"));
1917        assert_eq!(startfile(&profile, true), Some("gcrt1.o"));
1918        let still = LinkOptions { is_static: true, ..profile.clone() };
1919        assert_eq!(startfile(&still, true), Some("grcrt1.o"));
1920        assert_eq!(startfile(&still, false), Some("gcrt1.o"));
1921        let shared = LinkOptions { shared: true, ..profile };
1922        assert_eq!(startfile(&shared, false), None);
1923    }
1924
1925    /// And a program that is not profiled is started by the one it always was.
1926    #[test]
1927    fn a_program_that_is_not_profiled_is_started_by_the_usual_one() {
1928        let plain = LinkOptions::default();
1929        assert_eq!(startfile(&plain, false), Some("crt1.o"));
1930        assert_eq!(startfile(&plain, true), Some("Scrt1.o"));
1931    }
1932
1933    #[test]
1934    fn asking_for_no_startup_files_leaves_out_both_ends_of_them() {
1935        let opts = LinkOptions { no_startfiles: true, ..LinkOptions::default() };
1936        let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
1937        assert!(!args.iter().any(|a| a.ends_with("crt1.o")), "{args:?}");
1938        assert!(!args.iter().any(|a| a.ends_with("crtn.o")), "{args:?}");
1939        // And still links against the library, because that is the other flag.
1940        assert!(args.contains(&"-lc".to_owned()), "{args:?}");
1941    }
1942
1943    #[test]
1944    fn asking_for_no_library_at_all_leaves_out_the_startup_files_too() {
1945        let opts = LinkOptions { no_stdlib: true, ..LinkOptions::default() };
1946        let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
1947        assert!(!args.contains(&"-lc".to_owned()), "{args:?}");
1948        assert!(!args.iter().any(|a| a.ends_with("crt1.o")), "{args:?}");
1949    }
1950
1951    #[test]
1952    fn the_library_comes_after_the_objects_that_need_it() {
1953        let items = vec![Item::File("a.o".to_owned()), Item::Library("m".to_owned())];
1954        let args = line(linux(), &LinkOptions::default(), &items, "a.out").expect("a line");
1955        let obj = args.iter().position(|a| a == "a.o").expect("the object");
1956        let m = args.iter().position(|a| a == "-lm").expect("the library");
1957        let c = args.iter().position(|a| a == "-lc").expect("the library");
1958        assert!(obj < m && m < c, "{args:?}");
1959    }
1960
1961    #[test]
1962    fn what_the_user_told_the_linker_stays_where_the_user_wrote_it() {
1963        // The pair libtool writes around a set of convenience archives, which is what found this.
1964        // Both words are about the files between them, so a line that collects them and puts them
1965        // at the end has two options that do nothing and an archive whose members were all dropped.
1966        let items = vec![
1967            Item::File("a.o".to_owned()),
1968            Item::Linker("--whole-archive".to_owned()),
1969            Item::File("libaesni.a".to_owned()),
1970            Item::Linker("--no-whole-archive".to_owned()),
1971            Item::Library("m".to_owned()),
1972        ];
1973        let args = line(linux(), &LinkOptions::default(), &items, "a.out").expect("a line");
1974        let at = |what: &str| args.iter().position(|a| a == what).expect(what);
1975        assert!(at("a.o") < at("--whole-archive"), "{args:?}");
1976        assert!(at("--whole-archive") < at("libaesni.a"), "{args:?}");
1977        assert!(at("libaesni.a") < at("--no-whole-archive"), "{args:?}");
1978        assert!(at("--no-whole-archive") < at("-lm"), "{args:?}");
1979        assert!(at("-lm") < at("-lc"), "{args:?}");
1980    }
1981
1982    #[test]
1983    fn a_sysroot_moves_every_path_this_decided_and_none_the_user_wrote() {
1984        let opts = LinkOptions {
1985            sysroot: Some(PathBuf::from("/nowhere-at-all")),
1986            search: vec![PathBuf::from("/opt/mine")],
1987            ..LinkOptions::default()
1988        };
1989        let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
1990        let at = args.iter().position(|a| a == "-dynamic-linker").expect("the flag");
1991        assert_eq!(args[at + 1], "/nowhere-at-all/lib64/ld-linux-x86-64.so.2");
1992        assert!(args.contains(&"-L/opt/mine".to_owned()), "{args:?}");
1993    }
1994
1995    #[test]
1996    fn a_platform_with_no_link_line_is_said_so_rather_than_linked_wrongly() {
1997        let triple = Triple::new(Arch::X86_64, Os::Windows, Env::Msvc);
1998        let error = line(triple, &LinkOptions::default(), &one("a.o"), "a.out")
1999            .expect_err("no line for it");
2000        assert!(matches!(error, Error::Target { .. }), "{error:?}");
2001    }
2002
2003    /// A made up SDK with the one file the line reads out of it, so that nothing about this machine
2004    /// decides what the line says.
2005    fn an_sdk(name: &str, settings: Option<&str>) -> PathBuf {
2006        let dir = std::env::temp_dir()
2007            .join(format!("rucc-sdk-{}-{}", std::process::id(), name.replace('.', "-")))
2008            .join(name);
2009        fs::create_dir_all(&dir).expect("a temporary directory");
2010        if let Some(settings) = settings {
2011            fs::write(dir.join("SDKSettings.json"), settings).expect("a settings file");
2012        }
2013        dir
2014    }
2015
2016    fn mac() -> Triple {
2017        Triple::new(Arch::Aarch64, Os::Darwin, Env::None)
2018    }
2019
2020    #[test]
2021    fn a_mac_link_names_the_platform_the_sdk_and_libsystem() {
2022        let sdk = an_sdk(
2023            "MacOSX.sdk",
2024            Some(
2025                "{\"CanonicalName\": \"macosx15.2\", \"Version\" : \"15.2\", \"MaximumDeploymentTarget\": \"15.2.99\"}",
2026            ),
2027        );
2028        let opts = LinkOptions {
2029            sysroot: Some(sdk.clone()),
2030            search: vec![PathBuf::from("/opt/mine")],
2031            no_builtins_lib: true,
2032            ..LinkOptions::default()
2033        };
2034        let items = vec![Item::File("a.o".to_owned()), Item::Library("m".to_owned())];
2035        let args = line(mac(), &opts, &items, "a.out").expect("a line");
2036        let sdk = sdk.display().to_string();
2037        let want: Vec<&str> = vec![
2038            "-arch",
2039            "arm64",
2040            "-platform_version",
2041            "macos",
2042            "11.0",
2043            "15.2",
2044            "-syslibroot",
2045            &sdk,
2046            "-o",
2047            "a.out",
2048            "-L/opt/mine",
2049            "a.o",
2050            "-lm",
2051            "-lSystem",
2052        ];
2053        assert_eq!(args, want);
2054
2055        // The deployment target from the command line, and a shared library.
2056        let opts =
2057            LinkOptions { os_version: Some(rucc_tuple::Version::new(13, 4)), shared: true, ..opts };
2058        let args = line(mac(), &opts, &one("a.o"), "liba.dylib").expect("a line");
2059        assert_eq!(args[3..6], ["macos", "13.4", "15.2"]);
2060        assert!(args.contains(&"-dylib".to_owned()), "{args:?}");
2061        assert!(!args.iter().any(|arg| arg.contains("pie")), "{args:?}");
2062    }
2063
2064    #[test]
2065    fn the_sdk_version_comes_from_its_name_when_it_has_no_settings() {
2066        let sdk = an_sdk("MacOSX14.5.sdk", None);
2067        let opts =
2068            LinkOptions { sysroot: Some(sdk), no_builtins_lib: true, ..LinkOptions::default() };
2069        let args = line(mac(), &opts, &one("a.o"), "a.out").expect("a line");
2070        assert_eq!(args[3..6], ["macos", "11.0", "14.5"]);
2071        // And the deployment target when neither says anything.
2072        let sdk = an_sdk("Somewhere", None);
2073        let opts = LinkOptions {
2074            sysroot: Some(sdk),
2075            os_version: Some(rucc_tuple::Version::major(12)),
2076            ..opts
2077        };
2078        let args = line(mac(), &opts, &one("a.o"), "a.out").expect("a line");
2079        assert_eq!(args[3..6], ["macos", "12", "12"]);
2080    }
2081
2082    #[test]
2083    fn a_mac_link_looks_for_a_mach_o_linker_and_nothing_else() {
2084        assert_eq!(order(mac(), &LinkOptions::default()), ["ld", "ld64.lld"]);
2085    }
2086
2087    #[test]
2088    fn a_static_mac_program_is_refused_and_a_relocatable_one_is_not() {
2089        let sdk = an_sdk("MacOSX.sdk", None);
2090        let opts = LinkOptions { sysroot: Some(sdk), is_static: true, ..LinkOptions::default() };
2091        let error = line(mac(), &opts, &one("a.o"), "a.out").expect_err("no static line");
2092        let Error::Cross { why } = &error else { panic!("{error:?}") };
2093        assert!(why.contains("-static"), "{why}");
2094        let args = relocatable_line(mac(), &LinkOptions::default(), &one("a.o"), "b.o")
2095            .expect("ld64 takes -r");
2096        assert_eq!(args, ["-r", "-arch", "arm64", "-o", "b.o", "a.o"]);
2097    }
2098
2099    #[test]
2100    fn the_line_is_printed_the_way_it_would_be_typed() {
2101        let linker = Linker { name: "ld".to_owned(), path: PathBuf::from("/usr/bin/ld") };
2102        let args = ["-o".to_owned(), "a b".to_owned()];
2103        assert_eq!(render(&linker, &args), "/usr/bin/ld -o \"a b\"");
2104    }
2105
2106    #[test]
2107    fn a_linker_that_is_not_there_is_said_by_name() {
2108        let opts = LinkOptions {
2109            use_ld: Some("a-linker-nobody-has".to_owned()),
2110            ..LinkOptions::default()
2111        };
2112        let error = find(linux(), &opts).expect_err("not on this machine");
2113        assert_eq!(error, Error::Named { name: "a-linker-nobody-has".to_owned() });
2114    }
2115    /// A directory with a `libgcc.a` in it, so a test can say what a machine with a gcc on it
2116    /// looks like without needing one.
2117    fn a_gcc_dir(name: &str) -> PathBuf {
2118        let dir = std::env::temp_dir().join(format!("rucc-link-{name}-{}", std::process::id()));
2119        fs::create_dir_all(&dir).expect("a temporary directory");
2120        fs::write(dir.join("libgcc.a"), b"not really an archive").expect("a file in it");
2121        dir
2122    }
2123
2124    #[test]
2125    fn the_c_library_supplies_the_block_routines_and_our_runtime_does_not_displace_them() {
2126        let gcc = a_gcc_dir("order");
2127        let ours = PathBuf::from("/somewhere/librucc_builtins.a");
2128        let args = runtime_items(&LinkOptions::default(), &[gcc], Some(&ours));
2129        let at_libc = args.iter().position(|a| a == "-lc").expect("libc");
2130        let at_ours = args.iter().position(|a| a.ends_with("librucc_builtins.a")).expect("ours");
2131        // glibc's `memcpy` is assembly per microarchitecture and ours is a word at a time loop,
2132        // so on a target that has one, its is the one that should answer.
2133        assert!(at_libc < at_ours, "{args:?}");
2134    }
2135
2136    #[test]
2137    fn a_static_link_puts_them_in_a_group_because_two_of_them_refer_to_each_other() {
2138        let gcc = a_gcc_dir("group");
2139        let opts = LinkOptions { is_static: true, ..LinkOptions::default() };
2140        let args = runtime_items(&opts, &[gcc], None);
2141        assert_eq!(args.first().map(String::as_str), Some("--start-group"), "{args:?}");
2142        assert_eq!(args.last().map(String::as_str), Some("--end-group"), "{args:?}");
2143        // The unwinder, which is what `libc.a` refers to and what a static link fails on without
2144        // it. Issue #277.
2145        assert!(args.contains(&"-lgcc_eh".to_owned()), "{args:?}");
2146    }
2147
2148    #[test]
2149    fn a_dynamic_link_needs_no_group_and_asks_for_the_shared_half_only_if_something_wants_it() {
2150        let gcc = a_gcc_dir("dynamic");
2151        let args = runtime_items(&LinkOptions::default(), &[gcc], None);
2152        assert!(!args.contains(&"--start-group".to_owned()), "{args:?}");
2153        assert!(!args.contains(&"-lgcc_eh".to_owned()), "{args:?}");
2154        let at = args.iter().position(|a| a == "-lgcc_s").expect("the shared half");
2155        assert_eq!(args[at - 1], "--as-needed", "{args:?}");
2156        assert_eq!(args[at + 1], "--no-as-needed", "{args:?}");
2157    }
2158
2159    #[test]
2160    fn our_own_runtime_comes_before_the_machines_because_the_two_are_interchangeable() {
2161        let gcc = a_gcc_dir("ours");
2162        let ours = PathBuf::from("/somewhere/librucc_builtins.a");
2163        let args = runtime_items(&LinkOptions::default(), &[gcc], Some(&ours));
2164        let at_ours = args.iter().position(|a| a.ends_with("librucc_builtins.a")).expect("ours");
2165        let at_gcc = args.iter().position(|a| a == "-lgcc").expect("libgcc");
2166        assert!(at_ours < at_gcc, "{args:?}");
2167    }
2168
2169    #[test]
2170    fn no_builtins_lib_leaves_ours_off_and_keeps_the_machines() {
2171        let gcc = a_gcc_dir("theirs");
2172        let opts = LinkOptions { no_builtins_lib: true, ..LinkOptions::default() };
2173        let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
2174        assert!(!args.iter().any(|a| a.ends_with("librucc_builtins.a")), "{args:?}");
2175        // And the machine's half is still decided the same way it was, from the directories
2176        // that are there, which on the machine running this test may be none.
2177        assert!(runtime_items(&opts, &[gcc], None).contains(&"-lgcc".to_owned()));
2178    }
2179
2180    #[test]
2181    fn nodefaultlibs_leaves_the_whole_runtime_off_and_not_only_the_c_library() {
2182        let gcc = a_gcc_dir("none");
2183        let opts = LinkOptions { no_defaultlibs: true, ..LinkOptions::default() };
2184        assert!(runtime_items(&opts, &[gcc], None).is_empty());
2185    }
2186
2187    #[test]
2188    fn a_machine_with_no_gcc_on_it_gets_no_names_for_libraries_that_are_not_there() {
2189        let empty = std::env::temp_dir().join("rucc-link-empty-not-a-gcc");
2190        let args = runtime_items(&LinkOptions::default(), &[empty], None);
2191        assert_eq!(args, ["-lc"], "{args:?}");
2192    }
2193
2194    #[test]
2195    fn a_gcc_version_directory_is_read_as_a_version_and_not_as_a_word() {
2196        assert!(version_key(Path::new("/usr/lib/gcc/x/13")) > version_key(Path::new("/x/9")));
2197        assert!(version_key(Path::new("/x/10.2")) > version_key(Path::new("/x/10")));
2198        // Something that is not a version at all still sorts, and sorts below one that is.
2199        assert!(version_key(Path::new("/x/snapshot")) < version_key(Path::new("/x/1")));
2200    }
2201
2202    /// A command line that has a cache to find generated sysroots in, which a real one always has.
2203    ///
2204    /// And a `-B` prefix with our runtime in it, because a cross link refuses without one and
2205    /// every machine that does this for real has the archive `cargo xtask builtins` wrote. What
2206    /// happens when it is missing is its own test below.
2207    /// The fast math startup file follows gcc's end file spec: the family puts it in anything
2208    /// that is not a shared object, and `-mdaz-ftz` decides it outright either way.
2209    #[test]
2210    fn the_fast_math_startup_file_is_wanted_where_gccs_spec_wants_it() {
2211        let fast = LinkOptions { fast_math: true, ..LinkOptions::default() };
2212        assert!(!LinkOptions::default().wants_fastmath());
2213        assert!(fast.wants_fastmath());
2214        assert!(!LinkOptions { shared: true, ..fast.clone() }.wants_fastmath());
2215        assert!(!LinkOptions { daz_ftz: Some(false), ..fast.clone() }.wants_fastmath());
2216        let forced = LinkOptions { shared: true, daz_ftz: Some(true), ..LinkOptions::default() };
2217        assert!(forced.wants_fastmath());
2218    }
2219
2220    fn cached() -> LinkOptions {
2221        LinkOptions {
2222            cache: Some(PathBuf::from("/cache")),
2223            prefixes: vec![a_builtins_dir()],
2224            ..LinkOptions::default()
2225        }
2226    }
2227
2228    /// A directory with our runtime archive in it, so that a test can say what a machine where the
2229    /// runtime was built looks like without building one.
2230    ///
2231    /// One directory for every test rather than one each, since none of them writes to it and the
2232    /// name of the file is the whole of what they read.
2233    fn a_builtins_dir() -> PathBuf {
2234        let dir = std::env::temp_dir().join(format!("rucc-link-ours-{}", std::process::id()));
2235        fs::create_dir_all(&dir).expect("a temporary directory");
2236        fs::write(dir.join("librucc_builtins.a"), b"not really an archive").expect("a file in it");
2237        dir
2238    }
2239
2240    /// An archive in a directory named by the short tuple is found, which is where `cargo xtask
2241    /// builtins --target=aarch64-linux-musl` puts it.
2242    #[test]
2243    fn the_runtime_is_found_under_the_tuple_as_well_as_the_triple() {
2244        let dir = std::env::temp_dir().join(format!("rucc-link-tuple-{}", std::process::id()));
2245        let target: Triple = "aarch64-linux-musl".parse().expect("a triple");
2246        let under = dir.join(target.tuple().to_string());
2247        fs::create_dir_all(&under).expect("a temporary directory");
2248        fs::write(under.join("librucc_builtins.a"), b"not really an archive")
2249            .expect("a file in it");
2250        let found = builtins_archive(target, std::slice::from_ref(&dir));
2251        assert_eq!(found, Some(under.join("librucc_builtins.a")));
2252        let _ = fs::remove_dir_all(&dir);
2253    }
2254
2255    /// Where that cache would keep this target's sysroot.
2256    fn a_sysroot(target: Triple) -> Sysroot {
2257        Sysroot::in_cache(Path::new("/cache"), target.tuple())
2258    }
2259
2260    /// A target that is not the machine running this test, whatever machine that is.
2261    ///
2262    /// A freestanding one, because [`Triple::host`] answers Linux, Darwin or Windows and never
2263    /// `Os::None`. Every other triple is somebody's host, so a test that wants the cross path out of
2264    /// [`line`] itself has to use this one and the rest go through [`cross_line`].
2265    fn foreign() -> Triple {
2266        Triple::new(Arch::X86_64, Os::None, Env::None)
2267    }
2268
2269    #[test]
2270    fn a_cross_link_reads_the_targets_own_sysroot_and_nothing_of_this_machine() {
2271        let target = Triple::new(Arch::Aarch64, Os::Linux, Env::Musl);
2272        let sysroot = a_sysroot(target);
2273        // The paths as this host spells them, because what is being checked is which directory the
2274        // files are in and a Windows separator is a backslash.
2275        let root = sysroot.root().display().to_string();
2276        let lib = sysroot.lib();
2277        let args = cross_line(target, &cached(), &one("a.o"), "a.out", &sysroot).expect("a line");
2278        assert!(args.contains(&format!("--sysroot={root}")), "{args:?}");
2279        assert!(args.contains(&format!("-L{}", lib.display())), "{args:?}");
2280        assert!(args.contains(&lib.join("libc.a").display().to_string()), "{args:?}");
2281        let at = args.iter().position(|a| a == "-dynamic-linker").expect("the loader");
2282        assert_eq!(args[at + 1], "/lib/ld-musl-aarch64.so.1", "{args:?}");
2283        // The whole point of the other path not being taken: not one directory of this machine is
2284        // on the line, so the line is the same on every host and the recorded ones describe it.
2285        for arg in &args {
2286            assert!(!arg.contains("/usr/lib"), "{arg} in {args:?}");
2287            assert!(!arg.contains("/lib64"), "{arg} in {args:?}");
2288        }
2289    }
2290
2291    #[test]
2292    fn a_freestanding_target_links_against_our_runtime_instead_of_being_refused() {
2293        let args = line(foreign(), &cached(), &one("a.o"), "a.out").expect("a line");
2294        assert!(args.iter().any(|a| a.ends_with("librucc_builtins.a")), "{args:?}");
2295        // No libc, because there is not one, and no start file either: what runs before `main` on a
2296        // freestanding target comes from whatever is being built.
2297        assert!(!args.iter().any(|a| a.ends_with("libc.a")), "{args:?}");
2298        assert!(!args.contains(&"-lc".to_owned()), "{args:?}");
2299        assert!(!args.iter().any(|a| a.ends_with("crt1.o")), "{args:?}");
2300    }
2301
2302    /// And with nothing to find sysroots in it is refused, which is what it was before this.
2303    #[test]
2304    fn a_driver_with_no_cache_to_look_in_says_so_rather_than_guessing() {
2305        let error = line(foreign(), &LinkOptions::default(), &one("a.o"), "a.out")
2306            .expect_err("no line for it");
2307        assert!(matches!(error, Error::Target { .. }), "{error:?}");
2308    }
2309
2310    #[test]
2311    fn a_static_link_against_a_libc_that_is_a_stub_is_refused_rather_than_attempted() {
2312        let target = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2313        let opts = LinkOptions { is_static: true, ..cached() };
2314        let error = cross_line(target, &opts, &one("a.o"), "a.out", &a_sysroot(target))
2315            .expect_err("there is no libc.a in a stub sysroot");
2316        let Error::Cross { why } = &error else { panic!("{error:?}") };
2317        // Because a stub carries the names a library exports and none of the bodies, which is
2318        // everything a dynamic link reads and nothing a static one does.
2319        assert!(why.contains("stub"), "{why}");
2320    }
2321
2322    #[test]
2323    fn a_target_whose_linker_wants_a_different_line_is_refused_by_name() {
2324        for target in [
2325            Triple::new(Arch::Aarch64, Os::Darwin, Env::None),
2326            Triple::new(Arch::X86_64, Os::Windows, Env::Msvc),
2327        ] {
2328            let error = cross_line(target, &cached(), &one("a.o"), "a.out", &a_sysroot(target))
2329                .expect_err("no line for that format");
2330            let Error::Cross { why } = &error else { panic!("{error:?}") };
2331            assert!(why.contains(&target.tuple().to_canonical_string()), "{why}");
2332        }
2333    }
2334
2335    #[test]
2336    fn a_mingw_target_links_and_looks_for_a_linker_that_can_write_a_pe_image() {
2337        let target = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2338        let args = cross_line(target, &cached(), &one("a.o"), "a.exe", &a_sysroot(target))
2339            .expect("a line for mingw-w64");
2340        let at = |flag: &str| args.iter().position(|arg| arg == flag).expect(flag);
2341        assert_eq!(args[at("-m") + 1], "i386pep");
2342        assert_eq!(args[at("--subsystem") + 1], "console");
2343        assert!(args.iter().any(|arg| arg.ends_with("libmsvcrt.a")), "{args:?}");
2344        // And the prefixed name a distribution files its mingw binutils under, which is not the
2345        // multiarch one.
2346        let names = cross_order(target);
2347        assert_eq!(names.first().map(String::as_str), Some("ld.lld"));
2348        assert!(names.contains(&"x86_64-w64-mingw32-ld".to_owned()), "{names:?}");
2349    }
2350
2351    #[test]
2352    fn our_runtime_comes_from_beside_the_compiler_rather_than_from_inside_the_sysroot() {
2353        // The two halves of tamnd/rucc#1514. The line used to name it under the sysroot's `lib`,
2354        // where nothing ever put it: it is this compiler's output for the target and a sysroot
2355        // fetched from a release holds the platform's files and not ours. So the path on the line
2356        // is the one the driver found, and the only `librucc_builtins.a` on the line is that one.
2357        let target = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2358        let sysroot = a_sysroot(target);
2359        let opts = cached();
2360        let args = cross_line(target, &opts, &one("a.o"), "a.exe", &sysroot).expect("a line");
2361        let ours: Vec<&String> =
2362            args.iter().filter(|arg| arg.ends_with("librucc_builtins.a")).collect();
2363        assert_eq!(ours.len(), 1, "{args:?}");
2364        assert_eq!(ours[0], &opts.prefixes[0].join("librucc_builtins.a").display().to_string());
2365        assert!(!ours[0].starts_with(&sysroot.lib().display().to_string()), "{args:?}");
2366        // And it is still last, after everything that calls into it.
2367        assert_eq!(args.last(), Some(ours[0]), "{args:?}");
2368    }
2369
2370    #[test]
2371    fn a_cross_link_with_no_runtime_to_find_says_which_command_writes_one() {
2372        // What the linker would say instead is that `___chkstk_ms` is undefined, referenced from
2373        // mingw-w64's own objects, which is tamnd/rucc#1513 and is nobody's first guess at a
2374        // missing archive.
2375        let target = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2376        let opts = LinkOptions { prefixes: Vec::new(), ..cached() };
2377        let error = cross_line(target, &opts, &one("a.o"), "a.exe", &a_sysroot(target))
2378            .expect_err("there is no runtime for it to find");
2379        let Error::Cross { why } = &error else { panic!("{error:?}") };
2380        assert!(why.contains("cargo xtask builtins"), "{why}");
2381        assert!(why.contains("-fno-builtins-lib"), "{why}");
2382
2383        // And that flag is the way through it, for somebody who meant to link without ours.
2384        let without = LinkOptions { no_builtins_lib: true, ..opts };
2385        let args = cross_line(target, &without, &one("a.o"), "a.exe", &a_sysroot(target))
2386            .expect("a line without ours on it");
2387        assert!(!args.iter().any(|arg| arg.ends_with("librucc_builtins.a")), "{args:?}");
2388    }
2389
2390    #[test]
2391    fn the_version_an_lld_prints_is_read_and_nothing_elses_is() {
2392        // What each of these programs actually prints, because the word being in the line is the
2393        // whole of how one is told from another.
2394        assert_eq!(lld_major("LLD 18.1.8 (compatible with GNU linkers)\n"), Some(18));
2395        assert_eq!(lld_major("Ubuntu LLD 18.1.3 (compatible with GNU linkers)\n"), Some(18));
2396        assert_eq!(lld_major("LLD 20.1.2 (compatible with GNU linkers)\n"), Some(20));
2397
2398        // Binutils and mold do not have it, and neither of them has this problem, so the answer
2399        // for both is that this check has nothing to say about them.
2400        assert_eq!(lld_major("GNU ld (GNU Binutils for Ubuntu) 2.42\n"), None);
2401        assert_eq!(lld_major("mold 2.4.1 (compatible with GNU ld)\n"), None);
2402        assert_eq!(lld_major(""), None);
2403    }
2404
2405    /// A program that prints `text` and exits, which is as much of a linker as this check reads.
2406    ///
2407    /// Named after what it says, so that two of them in one test are two files.
2408    #[cfg(unix)]
2409    fn a_linker_that_says(tag: &str, text: &str) -> Linker {
2410        use std::os::unix::fs::PermissionsExt as _;
2411        let dir = std::env::temp_dir().join(format!("rucc-link-ld-{}", std::process::id()));
2412        fs::create_dir_all(&dir).expect("a temporary directory");
2413        let path = dir.join(format!("ld.lld-{tag}"));
2414        fs::write(&path, format!("#!/bin/sh\necho '{text}'\n")).expect("a script");
2415        fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("an executable one");
2416        Linker { name: "ld.lld".to_owned(), path }
2417    }
2418
2419    #[test]
2420    #[cfg(unix)]
2421    fn an_lld_too_old_to_read_exportas_is_refused_for_windows_gnu_and_nowhere_else() {
2422        // The failure this replaces has no diagnostic at all: 18 writes an import by ordinal zero,
2423        // exits successfully, and the program dies at startup under wine. tamnd/rucc#1515.
2424        let windows = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2425        let old = a_linker_that_says("18", "LLD 18.1.8 (compatible with GNU linkers)");
2426        let error = suitable(windows, &old).expect_err("18 cannot link this");
2427        let Error::TooOld { name, found, target } = &error else { panic!("{error:?}") };
2428        assert_eq!((name.as_str(), *found, target.as_str()), ("ld.lld", 18, "x86_64-windows-gnu"));
2429        assert!(error.to_string().contains("IMPORT_NAME_EXPORTAS"), "{error}");
2430
2431        // The same linker for a target whose import libraries have no such records in them, which
2432        // is every other target, since this is one encoding in one format.
2433        let linux = Triple::new(Arch::X86_64, Os::Linux, Env::Musl);
2434        assert_eq!(suitable(linux, &old), Ok(()));
2435
2436        // And the first one that reads them.
2437        let new = a_linker_that_says("19", "LLD 19.1.0 (compatible with GNU linkers)");
2438        assert_eq!(suitable(windows, &new), Ok(()));
2439    }
2440
2441    #[test]
2442    #[cfg(unix)]
2443    fn an_old_lld_first_in_line_is_passed_over_for_a_newer_one_behind_it() {
2444        // Ubuntu 24.04 after `apt install lld-19`: 18 is the one on PATH and 19 is somewhere else.
2445        // Two -B prefixes stand in for the two places, since the search asks them in order too. The
2446        // name is one nothing on this machine is called, so a real lld on PATH does not answer.
2447        use std::os::unix::fs::PermissionsExt as _;
2448        let root = std::env::temp_dir().join(format!("rucc-link-two-lld-{}", std::process::id()));
2449        let mut prefixes = Vec::new();
2450        for (dir, version) in [("old", "18.1.3"), ("new", "19.1.7")] {
2451            let dir = root.join(dir);
2452            fs::create_dir_all(&dir).expect("a temporary directory");
2453            let path = dir.join("ld.rucc-test-lld");
2454            fs::write(&path, format!("#!/bin/sh\necho 'Ubuntu LLD {version}'\n"))
2455                .expect("a script");
2456            fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("executable");
2457            prefixes.push(dir);
2458        }
2459        let windows = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2460        let opts = LinkOptions {
2461            use_ld: Some("rucc-test-lld".to_owned()),
2462            prefixes,
2463            ..LinkOptions::default()
2464        };
2465        let found = find(windows, &opts).expect("the newer one");
2466        assert_eq!(found.path, root.join("new").join("ld.rucc-test-lld"));
2467
2468        // With only the old one there, the answer is the refusal that names it.
2469        let opts = LinkOptions { prefixes: vec![root.join("old")], ..opts };
2470        let error = find(windows, &opts).expect_err("only 18 is here");
2471        assert!(matches!(error, Error::TooOld { found: 18, .. }), "{error:?}");
2472        let _ = fs::remove_dir_all(&root);
2473    }
2474
2475    #[test]
2476    fn a_long_line_goes_in_a_response_file_that_reads_back_as_it_was() {
2477        let args: Vec<String> =
2478            ["-o", r"C:\Users\a b\out.exe", "-m", "i386pep", r#"say "hi""#, "", "plain.o"]
2479                .map(str::to_owned)
2480                .to_vec();
2481        let (front, rest) = split_for_file(&args);
2482        assert_eq!(front, ["-m", "i386pep"]);
2483        assert_eq!(
2484            crate::response_words(&response_text(&rest, false)),
2485            [&args[..2], &args[4..]].concat()
2486        );
2487        // And the Windows way, which leaves the backslashes in a path alone.
2488        assert_eq!(
2489            response_text(&rest, true),
2490            "\"-o\"\n\"C:\\Users\\a b\\out.exe\"\n\"say \\\"hi\\\"\"\n\"\"\n\"plain.o\"\n"
2491        );
2492        assert_eq!(response_text(&[r"C:\dir\".to_owned()], true), "\"C:\\dir\\\\\"\n");
2493        assert!(!too_long(&args, 1000));
2494        assert!(too_long(&vec!["x".repeat(100); 400], WINDOWS_LINE));
2495    }
2496
2497    #[test]
2498    fn a_program_name_is_tried_with_each_pathext_extension_it_does_not_already_have() {
2499        let exts = vec![".com".to_owned(), ".exe".to_owned()];
2500        let dir = Path::new("bin");
2501        assert_eq!(
2502            spellings(&dir.join("ld.lld"), &exts),
2503            [dir.join("ld.lld.com"), dir.join("ld.lld.exe")]
2504        );
2505        assert_eq!(spellings(&dir.join("lld-link.EXE"), &exts), [dir.join("lld-link.EXE")]);
2506        assert_eq!(spellings(&dir.join("ld.lld"), &[]), [dir.join("ld.lld")]);
2507    }
2508
2509    #[test]
2510    #[cfg(unix)]
2511    fn an_lld_off_path_is_found_under_its_own_name() {
2512        use std::os::unix::fs::PermissionsExt as _;
2513        let dir = std::env::temp_dir().join(format!("rucc-link-off-path-{}", std::process::id()));
2514        fs::create_dir_all(&dir).expect("a temporary directory");
2515        let lld = dir.join("ld.lld");
2516        fs::write(&lld, "#!/bin/sh\n").expect("a file");
2517        fs::set_permissions(&lld, fs::Permissions::from_mode(0o755)).expect("permissions");
2518        let found =
2519            linker_candidates("ld.lld", &LinkOptions::default(), std::slice::from_ref(&dir));
2520        let _ = fs::remove_dir_all(&dir);
2521        assert!(found.contains(&lld), "{found:?}");
2522    }
2523
2524    #[test]
2525    fn lld_is_looked_for_where_package_managers_put_it_newest_version_first() {
2526        let root = std::env::temp_dir().join(format!("rucc-link-lld-dirs-{}", std::process::id()));
2527        for dir in ["usr/lib/llvm-18/bin", "usr/lib/llvm-19/bin", "usr/lib/llvm-9/bin", "usr/lib/x"]
2528        {
2529            fs::create_dir_all(root.join(dir)).expect("a temporary directory");
2530        }
2531        let dirs = lld_dirs(&root, Some(PathBuf::from("C:/Program Files")));
2532        let under_lib: Vec<_> =
2533            dirs.iter().filter(|dir| dir.starts_with(root.join("usr/lib"))).collect();
2534        assert_eq!(
2535            under_lib,
2536            [
2537                &root.join("usr/lib/llvm-19/bin"),
2538                &root.join("usr/lib/llvm-18/bin"),
2539                &root.join("usr/lib/llvm-9/bin")
2540            ]
2541        );
2542        assert!(dirs.contains(&root.join("opt/homebrew/opt/lld/bin")), "{dirs:?}");
2543        assert_eq!(dirs.last(), Some(&PathBuf::from("C:/Program Files").join("LLVM").join("bin")));
2544        let _ = fs::remove_dir_all(&root);
2545    }
2546
2547    #[test]
2548    fn no_linker_says_where_to_get_lld_only_when_lld_was_looked_for() {
2549        let cross = Error::NoLinker { tried: vec!["ld.lld".to_owned(), "lld".to_owned()] };
2550        assert!(cross.to_string().contains("lld 19 or newer"), "{cross}");
2551        let native = Error::NoLinker { tried: vec!["ld".to_owned()] };
2552        assert_eq!(native.to_string(), "no linker was found; tried ld");
2553    }
2554
2555    #[test]
2556    #[cfg(unix)]
2557    fn a_linker_that_will_not_say_what_it_is_is_left_alone() {
2558        // Every linker that is not an lld reaches this check too, and what it can establish is
2559        // that a specific old lld is here rather than that anything else is fit. Turning "I did
2560        // not recognise this" into a refusal would break machines this problem never touched.
2561        let windows = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2562        let quiet = a_linker_that_says("gnu", "GNU ld (GNU Binutils for Ubuntu) 2.42");
2563        assert_eq!(suitable(windows, &quiet), Ok(()));
2564
2565        let missing = Linker { name: "ld.lld".to_owned(), path: PathBuf::from("/no/such/linker") };
2566        assert_eq!(suitable(windows, &missing), Ok(()));
2567    }
2568
2569    #[test]
2570    fn profiling_a_cross_link_is_refused_because_the_startup_file_is_compiled_code() {
2571        let target = Triple::new(Arch::X86_64, Os::Linux, Env::Musl);
2572        let opts = LinkOptions { profile: true, ..cached() };
2573        let error = cross_line(target, &opts, &one("a.o"), "a.out", &a_sysroot(target))
2574            .expect_err("there is no gcrt1.o in a generated sysroot");
2575        let Error::Cross { why } = &error else { panic!("{error:?}") };
2576        assert!(why.contains("gcrt1.o"), "{why}");
2577    }
2578
2579    #[test]
2580    fn a_distributions_cross_tree_is_used_when_there_is_no_sysroot_of_ours() {
2581        let usr = std::env::temp_dir().join(format!("rucc-link-usr-{}", std::process::id()));
2582        let root = usr.join("aarch64-linux-gnu");
2583        for dir in ["include", "lib"] {
2584            fs::create_dir_all(root.join(dir)).expect("a scratch tree");
2585        }
2586        for version in ["9", "13"] {
2587            fs::create_dir_all(usr.join("lib/gcc-cross/aarch64-linux-gnu").join(version))
2588                .expect("a scratch gcc");
2589        }
2590        let host = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2591        let arm = Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu);
2592        let opts = LinkOptions { usr: Some(usr.clone()), ..cached() };
2593        let distro = distro_for(arm, &opts, Some(host)).expect("the packages are there");
2594        assert_eq!(distro.include(), root.join("include"));
2595        assert_eq!(distro.lib(), root.join("lib"));
2596        assert_eq!(
2597            distro.gcc,
2598            [13, 9].map(|v| usr.join("lib/gcc-cross/aarch64-linux-gnu").join(v.to_string()))
2599        );
2600        // And then it is not a link against a sysroot of ours, which is what decides the line.
2601        assert!(cross_for(arm, &opts, Some(host)).is_none());
2602        // The host itself, a target with no tree, a named tree and a pinned release all leave it.
2603        assert!(distro_for(host, &opts, Some(host)).is_none());
2604        let riscv = Triple::new(Arch::Riscv64, Os::Linux, Env::Gnu);
2605        assert!(distro_for(riscv, &opts, Some(host)).is_none());
2606        let named = LinkOptions { sysroot: Some(PathBuf::from("/opt/root")), ..opts.clone() };
2607        assert!(distro_for(arm, &named, Some(host)).is_none());
2608        let pinned = LinkOptions {
2609            pinned: Some("aarch64-linux-gnu.2.28".parse::<TargetTuple>().expect("a release")),
2610            ..opts.clone()
2611        };
2612        assert!(distro_for(arm, &pinned, Some(host)).is_none());
2613        // A sysroot of ours in the cache wins over the packages, because it is the one pinned.
2614        let cache = usr.join("cache");
2615        fs::create_dir_all(Sysroot::in_cache(&cache, arm.tuple()).lib()).expect("a sysroot");
2616        let fetched = LinkOptions { cache: Some(cache), ..opts };
2617        assert!(distro_for(arm, &fetched, Some(host)).is_none());
2618        let _ = fs::remove_dir_all(&usr);
2619    }
2620
2621    #[test]
2622    fn the_host_takes_the_host_line_and_a_tree_the_user_named_takes_it_too() {
2623        let host = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2624        let other = Triple::new(Arch::Riscv64, Os::Linux, Env::Musl);
2625        assert!(cross_for(host, &cached(), Some(host)).is_none());
2626        assert!(cross_for(other, &cached(), Some(host)).is_some());
2627        // A tree somebody assembled and named is what `--sysroot` has always meant here, and the
2628        // native line prefixes every path it decides with it.
2629        let named = LinkOptions { sysroot: Some(PathBuf::from("/opt/root")), ..cached() };
2630        assert!(cross_for(other, &named, Some(host)).is_none());
2631        // A host this compiler cannot name is a host whose directories it should not be guessing at.
2632        assert!(cross_for(other, &cached(), None).is_some());
2633    }
2634
2635    #[test]
2636    fn a_pinned_release_on_this_machines_own_target_is_a_cross_compile() {
2637        // The case that used to be dropped on the floor. `--target=x86_64-linux-gnu.2.28` on an
2638        // x86-64 glibc machine read that machine's headers and linked that machine's libc, and the
2639        // release reached nothing, so what came out was a binary for whatever release the build
2640        // machine happened to have. A pin is the one thing a person writes to say otherwise.
2641        let host = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2642        let pinned = LinkOptions {
2643            pinned: Some(
2644                "x86_64-linux-gnu.2.28".parse::<TargetTuple>().expect("a spelling with a release"),
2645            ),
2646            ..cached()
2647        };
2648        let at = cross_for(host, &pinned, Some(host)).expect("a pin is a cross compile");
2649        // And against the release's own directory, because the release is in the cache key: a tree
2650        // produced for 2.28 and a tree produced for 2.44 are two trees and the path has to say which.
2651        assert!(at.root().ends_with("x86_64-linux-gnu.2.28"), "{:?}", at.root());
2652        // The release is the whole of the difference. The same command line without it is this
2653        // machine, which is what every native compile has always been.
2654        let bare = LinkOptions { pinned: None, ..cached() };
2655        assert!(cross_for(host, &bare, Some(host)).is_none());
2656    }
2657
2658    #[test]
2659    fn a_glibc_cross_link_writes_its_stubs_beside_the_sysroot_once() {
2660        let cache = std::env::temp_dir().join(format!("rucc-link-stubs-{}", std::process::id()));
2661        let _ = fs::remove_dir_all(&cache);
2662        let target = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2663        let pinned = LinkOptions {
2664            cache: Some(cache.clone()),
2665            pinned: Some("x86_64-linux-gnu.2.28".parse().expect("a spelling with a release")),
2666            ..LinkOptions::default()
2667        };
2668        write_stubs(target, &pinned).expect("x86_64 glibc has a description");
2669        let dir = cache.join("stubs").join("x86_64-linux-gnu.2.28");
2670        let libc = dir.join("libc.so");
2671        let bytes = fs::read(&libc).expect("libc.so was written");
2672        assert!(bytes.starts_with(b"\x7fELF"));
2673        assert!(dir.join("libm.so").is_file());
2674        // 2.28 is before the release that emptied libpthread, so there is no empty one to write.
2675        assert!(!dir.join("libpthread.so").exists());
2676        // The second time finds the same bytes and leaves the file alone, which is what keeps a
2677        // linker in another build from ever reading one that is being replaced.
2678        let before = fs::metadata(&libc).and_then(|m| m.modified()).expect("a time");
2679        write_stubs(target, &pinned).expect("again");
2680        let after = fs::metadata(&libc).and_then(|m| m.modified()).expect("a time");
2681        assert_eq!(before, after);
2682        // And nothing for a libc that is not glibc, whose sysroot has a real one in it.
2683        let musl = LinkOptions {
2684            cache: Some(cache.clone()),
2685            pinned: Some("x86_64-linux-musl".parse().expect("musl")),
2686            ..LinkOptions::default()
2687        };
2688        write_stubs(Triple::new(Arch::X86_64, Os::Linux, Env::Musl), &musl).expect("nothing");
2689        assert!(!cache.join("stubs").join("x86_64-linux-musl").exists());
2690        let _ = fs::remove_dir_all(&cache);
2691    }
2692
2693    #[test]
2694    fn what_a_cross_link_searches_is_the_sysroot_and_not_this_machine() {
2695        let dirs = search_dirs(&cached(), foreign());
2696        // One directory, because that is what the line has, and the same one the line has, because
2697        // `-print-search-dirs` is what a build system reads to write a link line of its own.
2698        assert_eq!(dirs.len(), 1, "{dirs:?}");
2699        assert!(dirs[0].starts_with("/cache"), "{dirs:?}");
2700        assert!(dirs[0].ends_with("lib"), "{dirs:?}");
2701        // And what the user wrote still comes first, the way it does on the line itself.
2702        let mine = LinkOptions { search: vec![PathBuf::from("/opt/mine")], ..cached() };
2703        assert_eq!(search_dirs(&mine, foreign())[0], PathBuf::from("/opt/mine"));
2704    }
2705
2706    #[test]
2707    fn gnu_ld_is_not_looked_for_against_the_fetched_mingw_sysroot() {
2708        let windows = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2709        assert_eq!(order(windows, &cached()), ["ld.lld", "lld"]);
2710    }
2711
2712    #[test]
2713    fn the_linker_looked_for_on_a_cross_link_is_one_that_can_cross() {
2714        let names = cross_order(Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu));
2715        assert_eq!(names.first().map(String::as_str), Some("ld.lld"));
2716        assert!(names.contains(&"aarch64-linux-gnu-ld".to_owned()), "{names:?}");
2717        // mold links for the machine it is running on, and so does a distribution's own `ld`, so
2718        // neither is a default here. `-fuse-ld=` is still there for somebody whose is different.
2719        assert!(!names.iter().any(|name| name.contains("mold")), "{names:?}");
2720        assert!(!names.contains(&"ld".to_owned()), "{names:?}");
2721        // And the lookup the driver really does for a target that is not this machine.
2722        assert_eq!(order(foreign(), &cached()), ["ld.lld", "lld"]);
2723    }
2724
2725    #[test]
2726    fn the_four_flags_become_the_five_modes_they_describe() {
2727        let plain = LinkOptions::default();
2728        assert_eq!(mode(&plain), LinkMode::Dynamic);
2729        assert_eq!(
2730            mode(&LinkOptions { pie: Some(false), ..plain.clone() }),
2731            LinkMode::DynamicNoPie
2732        );
2733        assert_eq!(mode(&LinkOptions { is_static: true, ..plain.clone() }), LinkMode::Static);
2734        let both = LinkOptions { is_static: true, pie: Some(true), ..plain.clone() };
2735        assert_eq!(mode(&both), LinkMode::StaticPie);
2736        assert_eq!(mode(&LinkOptions { shared: true, ..plain }), LinkMode::Shared);
2737    }
2738
2739    #[test]
2740    fn a_sysroot_that_has_not_been_built_is_named_before_anything_is_compiled() {
2741        let opts = LinkOptions {
2742            cache: Some(std::env::temp_dir().join("rucc-a-cache-nobody-filled")),
2743            ..LinkOptions::default()
2744        };
2745        let error = preflight(foreign(), &opts).expect_err("nothing has built one");
2746        let Error::Sysroot { dir, pinned, .. } = &error else { panic!("{error:?}") };
2747        assert!(dir.ends_with("x86_64-none"), "{dir}");
2748        // Nothing is pinned for that target, or for any target yet, so the message says that rather
2749        // than naming a command that would not work.
2750        assert!(!pinned, "nothing should be pinned for a bare metal target");
2751        let said = error.to_string();
2752        assert!(said.contains("pins none for it to fetch"), "{said}");
2753    }
2754
2755    /// The other half of the same message, which is what a target this release does pin an artifact
2756    /// for is told. Built by hand rather than through `preflight`, because what is being checked is
2757    /// the message and not which targets `rucc_sysroot::artifact` happens to pin this release.
2758    #[test]
2759    fn a_sysroot_that_could_be_fetched_is_told_what_to_run() {
2760        let said = Error::Sysroot {
2761            target: "x86_64-linux-musl".to_owned(),
2762            dir: "/somewhere/sysroots/x86_64-linux-musl".to_owned(),
2763            pinned: true,
2764        }
2765        .to_string();
2766        assert!(said.contains("`rucc --fetch x86_64-linux-musl`"), "{said}");
2767        // And the other way out of it, because a person who has a tree already does not want a
2768        // download.
2769        assert!(said.contains("--sysroot=<dir>"), "{said}");
2770    }
2771
2772    #[test]
2773    fn a_link_against_this_machine_has_nothing_to_check_before_it_starts() {
2774        // Its directories are looked for as the line is built, and one that is not there is simply
2775        // one that is not offered, so there is no question to answer early.
2776        assert!(preflight(linux(), &LinkOptions::default()).is_ok());
2777    }
2778
2779    #[test]
2780    fn a_runtime_directory_that_is_not_on_this_machine_is_not_offered() {
2781        let dirs = runtime_dirs(linux(), Some(Path::new("/definitely/not/a/sysroot")));
2782        assert!(dirs.is_empty(), "{dirs:?}");
2783    }
2784}