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