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