rucc_sysroot/link.rs
1//! The start files, the libraries and the loader for one target's link.
2//!
3//! Design: `spec/cross-compile/08-sysroots.md` section 8.2 and `spec/cross-compile/11-linking.md`.
4//!
5//! What is here is what has to be linked, in what order, and which loader will start the result.
6//! How that is spelled for a particular linker is [`crate::argv`], which is the division
7//! `spec/cross-compile/11-linking.md` draws: the files are a fact about the target and the flags are
8//! a fact about the linker.
9//!
10//! # Why musl is first
11//!
12//! `spec/cross-compile/09-libc-stubs.md` section 9.3 is the argument. musl exercises the header
13//! tree, the search paths, the start files, the compiler runtime and the link line, and it does
14//! that without symbol versioning and without stub generation, which are the two hardest pieces of
15//! the glibc path. If a musl cross link works end to end then the pipeline is right and what is
16//! left for M9.5 is the glibc specific parts rather than the shape of the thing.
17//!
18//! # Why the line has three parts and not one
19//!
20//! `crtn.o` goes after the libraries and `crti.o` goes before them, because between them they open
21//! and close the `.init` and `.fini` sections and anything contributing to those has to land in the
22//! middle. A link line that is one list gets this wrong in a way that produces a binary which links,
23//! runs, and does not run its static constructors, so the three parts are three fields here rather
24//! than a comment on an ordering somebody has to preserve.
25
26use std::path::{Path, PathBuf};
27
28use rucc_tuple::{Abi, Arch, DataModel, Endian, Env, ObjectFormat, Os, TargetTuple, Version};
29
30use crate::layout::Sysroot;
31
32/// How the program is linked, which decides the first start file and the flags.
33///
34/// The glibc release that moved the `stat` family out of `libc_nonshared.a` and into `libc.so.6`.
35const STAT_IN_LIBC: Version = Version::new(2, 33);
36
37/// Five cases rather than two booleans for static and position independent, because the two are not
38/// independent and the start file is a different file in four of the five. A pair of flags would
39/// admit a sixth combination, a shared object that is not position independent, which is not a thing
40/// any of these linkers will produce.
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
42pub enum LinkMode {
43 /// Everything in the binary, no interpreter, no relocation at load. The default for musl, and
44 /// the mode `spec/cross-compile/02-the-goal.md`'s exit criterion names.
45 #[default]
46 Static,
47 /// Static, and position independent, so the loader may place it anywhere. A different first
48 /// start file, because the program has to relocate itself before `main` and `rcrt1.o` is what
49 /// does that.
50 StaticPie,
51 /// Against the shared libc, position independent, with the libc's loader named in the program
52 /// header. What every distribution builds today and what `-pie` asks for.
53 Dynamic,
54 /// Against the shared libc, at a fixed address, which is `-no-pie`.
55 ///
56 /// The same link as [`LinkMode::Dynamic`] with a different start file, because the reference to
57 /// `main` in `crt1.o` is an absolute one and the reference in `Scrt1.o` is not. Build systems
58 /// that pass `-no-pie` are usually doing it because something in them takes the address of a
59 /// function and compares it, and they get the file that matches.
60 DynamicNoPie,
61 /// A shared object rather than a program, which is `-shared`.
62 ///
63 /// No start file at all, since nothing starts a shared object and it has no `main` to be
64 /// started at, and no loader named either: the program that loads this one carries that.
65 Shared,
66}
67
68impl LinkMode {
69 /// Whether the result is linked against a shared libc, which decides whether a loader is named.
70 #[must_use]
71 pub const fn is_dynamic(self) -> bool {
72 matches!(self, LinkMode::Dynamic | LinkMode::DynamicNoPie | LinkMode::Shared)
73 }
74
75 /// Whether the result may be placed anywhere in memory.
76 #[must_use]
77 pub const fn is_pie(self) -> bool {
78 matches!(self, LinkMode::StaticPie | LinkMode::Dynamic | LinkMode::Shared)
79 }
80}
81
82/// What a produced sysroot holds for a target's C library.
83///
84/// Four cases, from `spec/cross-compile/08-sysroots.md` section 8.2's table, and the line differs
85/// between them in what goes on it rather than in how it is spelled. The table has seven rows and two
86/// of those are legal walls rather than technical ones, so what is left is these four.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum Libc {
89 /// Nothing, which is the freestanding row: the nine compiler headers and no link inputs at all.
90 /// Our runtime is still there, because an architecture without a division instruction needs it
91 /// whether there is a libc or not.
92 None,
93 /// A real static archive, which today means musl built from source. The only row where the code
94 /// behind the names is present, so the only row a static link can use.
95 Archive,
96 /// A generated stub shared object: the names the platform's libc exports and none of the code.
97 /// glibc is the row this was written for, and bionic, the BSDs and illumos take the same shape
98 /// for the same reason, which is that their libc is a shared object on the target machine and a
99 /// list of names is enough to link against one.
100 Stub,
101 /// A set of import libraries, which is what the same idea is called in COFF.
102 ///
103 /// Windows is the row this is, and it is a separate case from [`Libc::Stub`] rather than a
104 /// spelling of it, for two reasons that both show up on the line. The container is different: a
105 /// Windows program links against an archive of tiny objects per DLL rather than against one
106 /// shared object, which is `spec/cross-compile/09-libc-stubs.md` section 9.4 and what
107 /// `rucc_stub::coff` writes. And the C library is not one file: the msvcrt import library,
108 /// mingw-w64's own `libmingwex.a` and `libmoldname.a`, and the Win32 libraries a CRT calls into
109 /// are all on the line, where a glibc line has one `libc.so` on it.
110 ///
111 /// A static link against this is not refused, which is the other difference. On Windows the C
112 /// library is a DLL on every machine and always has been, so `-static` there is a statement
113 /// about our libraries and mingw-w64's rather than about the CRT, and a program linked that way
114 /// runs. That is why the refusal in [`crate::argv::argv`] is about [`Libc::Stub`] by name.
115 Import,
116}
117
118/// Which of the four cases this target is.
119///
120/// Asked in two places, which is why it is a function rather than a `match` in each: [`LinkLine`]
121/// uses it to pick the files and [`crate::argv::argv`] uses it to refuse a static link against a
122/// stub. Two copies of this rule would be two rules.
123///
124/// The format is asked before the environment, because what holds a libc's names is a property of
125/// the object format and `Env::Gnu` means mingw-w64 on a Windows target and glibc on a Linux one.
126#[must_use]
127pub fn libc(target: TargetTuple) -> Libc {
128 match (target.os(), target.env()) {
129 (Os::None, _) => Libc::None,
130 _ if target.object_format() == ObjectFormat::Coff => Libc::Import,
131 (_, Env::Musl) => Libc::Archive,
132 _ => Libc::Stub,
133 }
134}
135
136/// Which of Microsoft's two C runtimes a program in the MSVC environment is linked against.
137///
138/// `cl.exe` spells the choice `/MT` and `/MD`, and here it is `-fms-runtime-lib=static` and
139/// `-fms-runtime-lib=dll`, which is clang's spelling. Two sets of libraries and two macros: the
140/// headers read `_MT` for both and `_DLL` only for the second, and that is how a header knows its
141/// functions are imported from a DLL rather than linked into the program.
142///
143/// The static one is the default, which is the opposite of `cl.exe`, and the reason is the machine
144/// the program is copied to. The universal CRT is part of Windows 10 and later, but the Visual C++
145/// runtime is not: `vcruntime140.dll` arrives with the redistributable, and a program linked `/MD`
146/// on a machine that never installed it does not start. A program linked `/MT` carries both and
147/// starts anywhere, which is what the mingw-w64 rows give without being asked.
148#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
149pub enum Crt {
150 /// `/MT`: `libcmt.lib`, `libucrt.lib` and `libvcruntime.lib`, all three linked into the
151 /// program.
152 #[default]
153 Static,
154 /// `/MD`: `msvcrt.lib`, `ucrt.lib` and `vcruntime.lib`, which are import libraries for
155 /// `ucrtbase.dll` and `vcruntime140.dll` with the startup code in the first of them.
156 Dll,
157}
158
159/// Our own runtime library, which every one of the three lines below carries.
160///
161/// Named once because three callers ask about it by name: the line that puts it on,
162/// [`crate::argv::argv`] when `-fno-builtins-lib` asks for it to be left off, and the driver that
163/// goes looking for the file. A second spelling of the name anywhere is a flag that stops working
164/// the day the first one is renamed.
165///
166/// Where the file is, is not this crate's answer and used to be. Every line below named it inside
167/// the sysroot, as `sysroot.lib().join(BUILTINS)`, and nothing ever put it there: it is this
168/// compiler's own output for the target rather than anything the platform ships, `cargo xtask
169/// builtins` writes it beside the compiler, and a sysroot fetched from a release will never hold
170/// it. So the lines take the path from whoever built them, which is the driver, and this constant
171/// is the name alone. tamnd/rucc#1514.
172pub const BUILTINS: &str = "librucc_builtins.a";
173
174/// Our runtime as a list, which is what every line below puts at the end of its libraries.
175///
176/// One function rather than the same `into_iter` at four call sites, and it takes the whole answer
177/// rather than a path so that a line reads the same whether the file was found or not.
178fn ours(builtins: Option<&Path>) -> Vec<PathBuf> {
179 builtins.map(Path::to_path_buf).into_iter().collect()
180}
181
182/// The inputs to a link, in the three groups a linker needs them in.
183///
184/// Paths rather than strings, and no flags at all, because
185/// `spec/cross-compile/11-linking.md` owns which linker is invoked and how its arguments are
186/// spelled and [`crate::argv`] is where that happens. What is here is what has to be linked and in
187/// what order, which is a target fact and the same fact whichever linker reads it.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct LinkLine {
190 /// The start files, before the user's objects.
191 pub start: Vec<PathBuf>,
192 /// The libraries, after the user's objects.
193 pub libraries: Vec<PathBuf>,
194 /// The end files, after the libraries.
195 pub end: Vec<PathBuf>,
196}
197
198impl LinkLine {
199 /// The line for a link against this sysroot, whichever libc the target names.
200 ///
201 /// The dispatch rather than the line, and it is [`libc`] that decides: a real archive, a stub
202 /// shared object, or nothing. The three methods below are the three answers. A target whose
203 /// sysroot we do not produce yet still gets the right shape, because the shape follows from
204 /// whether the libc on the target machine is an archive or a shared object and that is known
205 /// before any of it is built.
206 ///
207 /// The runtime is a path from the caller rather than a name joined onto the sysroot, and
208 /// [`None`] means it is not on this machine and the line goes without it. Whether that is worth
209 /// refusing over is the driver's question, since the driver is what knows whether it looked.
210 #[must_use]
211 pub fn for_target(sysroot: &Sysroot, mode: LinkMode, builtins: Option<&Path>) -> Self {
212 match libc(sysroot.target()) {
213 Libc::None => LinkLine::freestanding(builtins),
214 Libc::Archive => LinkLine::musl(sysroot, mode, builtins),
215 Libc::Stub => LinkLine::glibc(sysroot, mode, builtins),
216 Libc::Import if sysroot.target().env() == Env::Msvc => {
217 LinkLine::msvc(Crt::Static, builtins)
218 }
219 Libc::Import => LinkLine::mingw(sysroot, mode, builtins),
220 }
221 }
222
223 /// The line for a freestanding link against this sysroot, which is our runtime and nothing else.
224 ///
225 /// Section 8.2's first row: nine compiler headers and no link inputs. There is no `crt1.o`,
226 /// because nothing here decides what runs before `main` or whether there is a `main` at all, and
227 /// no `crti.o` or `crtn.o`, because those come from a libc too. A kernel or a bootloader brings
228 /// its own start file and says so with `-nostartfiles`, which it would have to pass anyway.
229 ///
230 /// `librucc_builtins.a` stays, because it is ours rather than the platform's.
231 /// `spec/cross-compile/10-runtime.md` is the argument: an architecture with no division
232 /// instruction needs `__divti3` whether there is a libc in the picture or not, and freestanding
233 /// code that does 64-bit arithmetic on a 32-bit target reaches it without asking.
234 ///
235 /// The mode is not a parameter because it changes nothing here. Every difference between the
236 /// modes is a start file and there are none. Neither is the sysroot, now that the one file on
237 /// this line is not in it: a freestanding link reads headers out of a sysroot and links nothing
238 /// out of one.
239 #[must_use]
240 pub fn freestanding(builtins: Option<&Path>) -> Self {
241 LinkLine { start: Vec::new(), libraries: ours(builtins), end: Vec::new() }
242 }
243
244 /// The line for a musl link against this sysroot.
245 ///
246 /// `crt1.o` runs before `main` and calls it. `crti.o` and `crtn.o` are the prologue and the
247 /// epilogue of the `.init` and `.fini` sections, which is why one is at the front and the other
248 /// is at the very back. `libc.a` carries musl's whole C library, and `librucc_builtins.a`
249 /// carries the operations the architecture does not have an instruction for, which
250 /// `spec/cross-compile/10-runtime.md` says has to be ours rather than the platform's.
251 ///
252 /// The builtins go after `libc.a` because musl calls some of them, and an archive that is
253 /// searched before the thing that needs it contributes nothing.
254 ///
255 /// `libc.a` on every mode including the dynamic ones, because what a musl sysroot here holds is
256 /// musl built static: section 9.3 takes musl first precisely because one tarball built one way
257 /// exercises the whole pipeline, and a shared musl is a second build of it that buys nothing
258 /// until somebody asks for a dynamically linked musl program.
259 #[must_use]
260 pub fn musl(sysroot: &Sysroot, mode: LinkMode, builtins: Option<&Path>) -> Self {
261 let lib = sysroot.lib();
262 let mut libraries = vec![lib.join("libc.a")];
263 libraries.extend(ours(builtins));
264 LinkLine { start: start_files(&lib, mode), libraries, end: vec![lib.join("crtn.o")] }
265 }
266
267 /// The line for a link against a generated stub, which is glibc and every other hosted libc that
268 /// is not musl.
269 ///
270 /// Named for glibc because glibc is the case `spec/cross-compile/09-libc-stubs.md` is written
271 /// about and the hard one. bionic, the BSDs and illumos reach the same line for the same reason:
272 /// their libc is a shared object on the target machine, so a list of the names it exports is
273 /// enough to link against it, and that is what `rucc-stub` produces. The paragraphs below about
274 /// `libc_nonshared.a` and `libm` are glibc's own.
275 ///
276 /// The same start files as musl's and different libraries. A stub libc is linked against
277 /// dynamically, so what goes on the line is the `libc.so` `rucc-stub` wrote into
278 /// [`Sysroot::stubs`] rather than an archive, and the version nodes in it are what make a
279 /// program built here run on an older machine. The driver writes it before the link, cut at
280 /// the release the tuple names, and the directory is on the line as a `-L` too so that `-lm`
281 /// and `-lpthread` find their stubs there.
282 ///
283 /// `libc_nonshared.a` comes next and out of the sysroot. glibc's own `libc.so` is a linker
284 /// script naming `libc.so.6`, `libc_nonshared.a` and the loader as a group, and that archive
285 /// holds real compiled objects: `atexit`, `__stack_chk_fail_local` on i386, and the `stat`
286 /// family on releases before 2.33. None of it can be written from a description, because a
287 /// stub is a list of names and these are bodies, so it is built from glibc's sources and
288 /// fetched with the start files. It goes after the stub because what is in it calls into
289 /// libc, which is the order glibc's script gives them. It is glibc's alone, so bionic and the
290 /// BSDs get the stub and nothing between it and our runtime.
291 ///
292 /// The archive in the sysroot is 2.44's, and 2.44's has no `stat` in it, because 2.33 moved the
293 /// family into `libc.so.6`. A target pinned before 2.33 gets `libc_nonshared_stat.a` after it,
294 /// which rucc-cross builds the way 2.32 built those ten functions, each a call to `__xstat` or
295 /// one of its siblings. Without it a program that calls `stat` links at -O2, where the old
296 /// headers inline the call, and not at -O0. A target with no pin is the newest release and
297 /// does not get it.
298 ///
299 /// `libm.so` is not on the line, and that is a decision. glibc's `libm` is real code and a
300 /// program that wants it passes `-lm`, which every build system that does arithmetic already
301 /// does, so putting it on every line would record a dependency the program does not have.
302 ///
303 /// A static glibc link is not one of these: there is no `libc.a` in a sysroot whose libc is a
304 /// stub, because a stub is a list of names and a static link needs bodies.
305 /// [`crate::argv::argv`] refuses that combination by name rather than producing this line with
306 /// `-static` in front of it.
307 #[must_use]
308 pub fn glibc(sysroot: &Sysroot, mode: LinkMode, builtins: Option<&Path>) -> Self {
309 let lib = sysroot.lib();
310 let mut libraries = vec![sysroot.stubs().join("libc.so")];
311 if sysroot.target().env() == Env::Gnu {
312 libraries.push(lib.join("libc_nonshared.a"));
313 let version = sysroot.target().env_version();
314 if version.is_some_and(|version| !version.at_least(STAT_IN_LIBC)) {
315 libraries.push(lib.join("libc_nonshared_stat.a"));
316 }
317 }
318 libraries.extend(ours(builtins));
319 LinkLine { start: start_files(&lib, mode), libraries, end: vec![lib.join("crtn.o")] }
320 }
321
322 /// The line for a mingw-w64 link against this sysroot.
323 ///
324 /// One start file and no end file, which is the first thing that is different from every ELF
325 /// line above. `crt2.o` runs before `main` and calls it, `dllcrt2.o` is its counterpart for a
326 /// DLL, and there is no `crti.o` and no `crtn.o` because PE has no `.init` and `.fini` sections
327 /// for a pair of files to open and close. What those two bracket on ELF is done on Windows by a
328 /// table of pointers in the `.CRT$XC` sections, which the linker sorts by section name, so the
329 /// ordering problem the three groups exist for does not arise here.
330 ///
331 /// `crtbegin.o` and `crtend.o` are deliberately absent. They are GCC's files rather than
332 /// mingw-w64's, they bracket GCC's own list of constructors, and a toolchain that is not GCC
333 /// writes that list the way the platform writes it instead. Ours is not written yet: a mingw
334 /// link runs `main` and does not run a file scope constructor, which is a known gap that belongs
335 /// with the sysroot build rather than with the line, and the gap is in the codegen for the
336 /// format rather than here.
337 ///
338 /// The libraries are a set rather than one file, because the C library on Windows is several
339 /// DLLs and the CRT calls into the system ones. `libmingw32.a` holds the start code `crt2.o`
340 /// calls, `libmoldname.a` is the layer that gives the old unprefixed spellings of the names
341 /// Microsoft deprecated, `libmingwex.a` is everything C requires that the CRT does not have, and
342 /// `libmsvcrt.a` is the import library for the CRT itself. Then the four Win32 libraries that
343 /// mingw-w64's own code calls into, which are on the line for the same reason they are on gcc's:
344 /// a program that uses none of them directly still reaches `kernel32` through `malloc`.
345 ///
346 /// `libmsvcrt.a` is the right name for either CRT, which is why nothing here asks the sysroot
347 /// which one it has. mingw-w64 installs it as a copy of the default runtime's import library, so
348 /// in the UCRT sysroot this compiler fetches it is `libucrt.a` and names the `api-ms-win-crt-*`
349 /// API sets, and in a `-msvcrt` sysroot it names `msvcrt.dll`. gcc's spec says `-lmsvcrt` on a
350 /// UCRT toolchain for the same reason, so the line follows the sysroot without being told.
351 ///
352 /// `-pthread` adds `-lpthread` after the objects, as on every other target, and the sysroot's
353 /// `libpthread.a` is winpthreads, built static so the program needs no `libwinpthread-1.dll`.
354 /// It is not on this line otherwise. A gcc built with the posix thread model lists it for every
355 /// program, and a program that asked for no threads has nothing to take from it.
356 ///
357 /// The order is the one a single pass linker needs, which is GNU ld's PE port: a library after
358 /// everything that calls into it. `librucc_builtins.a` is last for the reason it is last on the
359 /// musl line, which is that the things before it call it and it calls none of them. lld's COFF
360 /// linker resolves archives to a fixed point and does not care about any of this, and writing
361 /// the line for the stricter of the two is what makes one line serve both.
362 #[must_use]
363 pub fn mingw(sysroot: &Sysroot, mode: LinkMode, builtins: Option<&Path>) -> Self {
364 let lib = sysroot.lib();
365 let start = match mode {
366 LinkMode::Shared => "dllcrt2.o",
367 _ => "crt2.o",
368 };
369 let theirs = [
370 "libmingw32.a",
371 "libmoldname.a",
372 "libmingwex.a",
373 "libmsvcrt.a",
374 "libadvapi32.a",
375 "libshell32.a",
376 "libuser32.a",
377 "libkernel32.a",
378 ];
379 let mut libraries: Vec<PathBuf> = theirs.iter().map(|name| lib.join(name)).collect();
380 libraries.extend(ours(builtins));
381 LinkLine { start: vec![lib.join(start)], libraries, end: Vec::new() }
382 }
383
384 /// The line for a program in Microsoft's environment, linked against the CRT `crt` names.
385 ///
386 /// No start file, because the one Microsoft ships is not a file of its own. `mainCRTStartup` is
387 /// a member of `libcmt.lib`, or of `msvcrt.lib` for the other runtime, and the linker picks it
388 /// as the entry point because the program defines `main`, so the start of the program is left
389 /// to the CRT the way `cl.exe` leaves it. The mode is not a parameter for the same reason: a
390 /// DLL is started by `_DllMainCRTStartup`, which is in the same libraries.
391 ///
392 /// Names rather than paths, which is where this differs from every other line here. The tree
393 /// keeps the CRT in `crt/lib` and the SDK's libraries in two directories of `sdk/lib`, and
394 /// [`crate::argv`] names those directories to the linker, which is how `lld-link` and
395 /// `link.exe` both look for a library and how a `-L` of the user's own gets in front of ours.
396 ///
397 /// `kernel32.lib` because the CRT calls into it and says so only in a directive, and
398 /// `oldnames.lib` because it is what makes `open` and `strdup` mean `_open` and `_strdup`,
399 /// which a C program written for anything but Windows calls by the old names. Ours goes last,
400 /// the same as on the mingw-w64 line, so that the CRT answers for everything it has.
401 #[must_use]
402 pub fn msvc(crt: Crt, builtins: Option<&Path>) -> Self {
403 let theirs = match crt {
404 Crt::Static => ["libcmt.lib", "libucrt.lib", "libvcruntime.lib"],
405 Crt::Dll => ["msvcrt.lib", "ucrt.lib", "vcruntime.lib"],
406 };
407 let mut libraries: Vec<PathBuf> = theirs.iter().map(PathBuf::from).collect();
408 libraries.push(PathBuf::from("kernel32.lib"));
409 libraries.push(PathBuf::from("oldnames.lib"));
410 libraries.extend(ours(builtins));
411 LinkLine { start: Vec::new(), libraries, end: Vec::new() }
412 }
413
414 /// Every input, in the order they reach the linker, with the caller's objects in the middle.
415 ///
416 /// The one function that knows the whole order, so that a caller cannot assemble the three
417 /// groups in the wrong sequence.
418 #[must_use]
419 pub fn with_objects(&self, objects: &[PathBuf]) -> Vec<PathBuf> {
420 let mut all = self.start.clone();
421 all.extend_from_slice(objects);
422 all.extend(self.libraries.iter().cloned());
423 all.extend(self.end.iter().cloned());
424 all
425 }
426}
427
428/// The start files for one mode, in the order they go on the line.
429///
430/// Two files, and which the first one is says how the reference to `main` inside it is written.
431/// `crt1.o` refers to it absolutely, `Scrt1.o` through the global offset table so that a loader may
432/// place the program anywhere, and `rcrt1.o` does that and relocates the program itself before
433/// `main` runs, which is what a static position independent executable needs because there is no
434/// loader to do it. A shared object has none of them.
435///
436/// `crti.o` is always second and `crtn.o` is always last, which is [`LinkLine`]'s three groups
437/// rather than anything here.
438fn start_files(lib: &Path, mode: LinkMode) -> Vec<PathBuf> {
439 let first = match mode {
440 LinkMode::Static | LinkMode::DynamicNoPie => Some("crt1.o"),
441 LinkMode::StaticPie => Some("rcrt1.o"),
442 LinkMode::Dynamic => Some("Scrt1.o"),
443 LinkMode::Shared => None,
444 };
445 first.map(|name| lib.join(name)).into_iter().chain([lib.join("crti.o")]).collect()
446}
447
448/// The absolute path the target's loader is installed at, or [`None`] for a target that has none.
449///
450/// The libc picks the table and the architecture picks the row. [`None`] is the right answer for
451/// three different reasons: a freestanding target has no libc, WASI has no loader of this kind at
452/// all, and Darwin and Windows have one whose path is not written on the link line.
453#[must_use]
454pub fn loader(target: TargetTuple) -> Option<&'static str> {
455 match (target.os(), target.env()) {
456 (Os::Linux, Env::Musl) => Some(musl_loader(target)),
457 (Os::Linux, Env::Gnu) => Some(glibc_loader(target)),
458 // Bionic's is one path per word size and not one per architecture, because Android fixes
459 // the filesystem layout rather than leaving it to the port.
460 (Os::Linux, Env::Android) => Some(match target.pointer_width() {
461 64 => "/system/bin/linker64",
462 _ => "/system/bin/linker",
463 }),
464 _ => None,
465 }
466}
467
468/// The absolute path musl's loader is installed at on the target.
469///
470/// It goes in the program header of a dynamically linked binary, so it is a string about the target
471/// machine's filesystem and not about ours, and it has to be right without anything to check it
472/// against at link time. A wrong one produces a binary that the kernel refuses to start with a
473/// message about a missing file that is on nobody's disk.
474///
475/// 32-bit ARM is the row with two answers, because musl names the hard float and soft float builds
476/// differently and they are not interchangeable. PowerPC is the other row with two, and there the
477/// endianness picks, because musl treats the two byte orders as separate ports.
478#[must_use]
479pub fn musl_loader(target: TargetTuple) -> &'static str {
480 match target.arch() {
481 Arch::X86_64 => match target.data_model() {
482 DataModel::Ilp32On64 => "/lib/ld-musl-x32.so.1",
483 _ => "/lib/ld-musl-x86_64.so.1",
484 },
485 Arch::X86 => "/lib/ld-musl-i386.so.1",
486 Arch::Aarch64 | Arch::Arm64Ec => "/lib/ld-musl-aarch64.so.1",
487 Arch::Arm => match target.resolved_abi() {
488 Abi::DoubleFloat => "/lib/ld-musl-armhf.so.1",
489 _ => "/lib/ld-musl-arm.so.1",
490 },
491 Arch::Riscv64 => "/lib/ld-musl-riscv64.so.1",
492 Arch::Riscv32 => "/lib/ld-musl-riscv32.so.1",
493 Arch::S390x => "/lib/ld-musl-s390x.so.1",
494 Arch::PowerPc64 => match target.endian() {
495 Endian::Little => "/lib/ld-musl-powerpc64le.so.1",
496 Endian::Big => "/lib/ld-musl-powerpc64.so.1",
497 },
498 Arch::LoongArch64 => "/lib/ld-musl-loongarch64.so.1",
499 // musl has no wasm port and wasm has no loader. The caller that gets here asked for a
500 // dynamic musl link on a target with neither, which is a driver bug rather than a user
501 // one, and a path that cannot exist is a better report than a plausible wrong one.
502 Arch::Wasm32 => "/lib/ld-musl-none.so.1",
503 }
504}
505
506/// The absolute path glibc's loader is installed at on the target.
507///
508/// A different table from musl's and not a different spelling of it. musl names every loader after
509/// the architecture in one directory; glibc's names come from each port's history, so three of them
510/// are called `ld64.so` with a number that means something different per architecture, two are in
511/// `/lib64` rather than `/lib`, and i386's carries no architecture in its name at all because it was
512/// the only one when it was named.
513///
514/// The rows with more than one answer are the ones where the loader and the program have to agree
515/// about register usage. 32-bit ARM has the hard float and soft float split, RISC-V and LoongArch
516/// spell the float ABI and the data model into the name, and AArch64 has a byte order in it.
517/// Getting one wrong produces a binary the kernel will not start, with a message about a missing
518/// file, and it is a string nothing at link time can check.
519#[must_use]
520pub fn glibc_loader(target: TargetTuple) -> &'static str {
521 let narrow = target.data_model() == DataModel::Ilp32On64;
522 let hard = matches!(target.resolved_abi(), Abi::DoubleFloat);
523 match target.arch() {
524 Arch::X86_64 if narrow => "/libx32/ld-linux-x32.so.2",
525 Arch::X86_64 => "/lib64/ld-linux-x86-64.so.2",
526 Arch::X86 => "/lib/ld-linux.so.2",
527 Arch::Aarch64 | Arch::Arm64Ec => match (target.endian(), narrow) {
528 (Endian::Little, false) => "/lib/ld-linux-aarch64.so.1",
529 (Endian::Little, true) => "/lib/ld-linux-aarch64_ilp32.so.1",
530 (Endian::Big, false) => "/lib/ld-linux-aarch64_be.so.1",
531 (Endian::Big, true) => "/lib/ld-linux-aarch64_be_ilp32.so.1",
532 },
533 // The one row where the number differs rather than the name. ARM's loader went to 3 when
534 // EABI replaced OABI, and the hard float build is a separate file because passing a double
535 // in a float register is not compatible with passing it in a pair of integer ones.
536 Arch::Arm if hard => "/lib/ld-linux-armhf.so.3",
537 Arch::Arm => "/lib/ld-linux.so.3",
538 Arch::Riscv64 if hard => "/lib/ld-linux-riscv64-lp64d.so.1",
539 Arch::Riscv64 => "/lib/ld-linux-riscv64-lp64.so.1",
540 Arch::Riscv32 if hard => "/lib/ld-linux-riscv32-ilp32d.so.1",
541 Arch::Riscv32 => "/lib/ld-linux-riscv32-ilp32.so.1",
542 // `ld64` here means 64-bit z/Architecture and the 1 is glibc's ABI version for the port,
543 // which is not the 2 on PowerPC's file of the same name. It is in `/lib` and PowerPC's is in
544 // `/lib64`, so the two rows have nothing in common but the stem.
545 Arch::S390x => "/lib/ld64.so.1",
546 // ELFv2, both byte orders, which is the only PowerPC ABI
547 // `spec/cross-compile/06-abis.md` admits. The ELFv1 big-endian world uses `ld64.so.1` and
548 // is out of scope, so a wrong answer here is impossible rather than merely unlikely.
549 Arch::PowerPc64 => "/lib64/ld64.so.2",
550 Arch::LoongArch64 if hard => "/lib64/ld-linux-loongarch-lp64d.so.1",
551 Arch::LoongArch64 => "/lib64/ld-linux-loongarch-lp64s.so.1",
552 // There is no glibc for wasm and no loader for it either. Same reasoning as the musl table
553 // above: a path nothing will ever open beats a plausible one.
554 Arch::Wasm32 => "/lib/ld-linux-wasm32.so.1",
555 }
556}