1use std::ffi::OsString;
73use std::fs;
74use std::path::{Path, PathBuf};
75use std::process::Command;
76
77use rucc_sysroot::layout::{Kernel, Sysroot};
78use rucc_sysroot::{LinkMode, argv};
79use rucc_target::{Arch, Env, Os, Triple};
80use rucc_tuple::TargetTuple;
81
82#[derive(Debug, Default, Clone, PartialEq, Eq)]
88pub struct LinkOptions {
89 pub use_ld: Option<String>,
91 pub search: Vec<PathBuf>,
93 pub prefixes: Vec<PathBuf>,
95 pub sysroot: Option<PathBuf>,
97 pub cache: Option<PathBuf>,
104 pub usr: Option<PathBuf>,
112 pub is_static: bool,
114 pub shared: bool,
116 pub pie: Option<bool>,
118 pub no_stdlib: bool,
120 pub no_startfiles: bool,
122 pub no_defaultlibs: bool,
124 pub export_dynamic: bool,
126 pub strip: bool,
128 pub gui: bool,
130 pub unicode: bool,
132 pub no_builtins_lib: bool,
135 pub pinned: Option<TargetTuple>,
144 pub profile: bool,
151 pub fast_math: bool,
158 pub daz_ftz: Option<bool>,
161 pub relocatable: bool,
167 pub os_version: Option<rucc_tuple::Version>,
173}
174
175impl LinkOptions {
176 fn wants_fastmath(&self) -> bool {
178 self.daz_ftz.unwrap_or(self.fast_math && !self.shared)
179 }
180
181 fn wants_startfiles(&self) -> bool {
183 !self.no_stdlib && !self.no_startfiles && !self.relocatable
184 }
185
186 fn wants_defaultlibs(&self) -> bool {
188 !self.no_stdlib && !self.no_defaultlibs && !self.relocatable
189 }
190
191 fn wants_runtime(&self) -> bool {
197 !self.no_stdlib && !self.no_defaultlibs && !self.relocatable
198 }
199}
200
201#[derive(Debug, Clone, PartialEq, Eq)]
207pub enum Item {
208 File(String),
210 Library(String),
212 Linker(String),
222}
223
224impl std::fmt::Display for Item {
225 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
226 match self {
227 Item::File(path) => f.write_str(path),
228 Item::Library(name) => write!(f, "-l{name}"),
229 Item::Linker(arg) => write!(f, "-Wl,{arg}"),
230 }
231 }
232}
233
234#[derive(Debug, Clone, PartialEq, Eq)]
236pub enum Error {
237 NoLinker {
239 tried: Vec<String>,
241 },
242 Named {
244 name: String,
246 },
247 Target {
249 triple: String,
251 },
252 Cross {
259 why: String,
261 },
262 Sysroot {
264 target: String,
266 dir: String,
268 pinned: bool,
271 },
272 TooOld {
278 name: String,
280 found: u32,
282 target: String,
284 },
285 Spawn {
287 path: String,
289 why: String,
291 },
292 Refused {
294 status: String,
296 },
297}
298
299impl std::fmt::Display for Error {
300 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
301 match self {
302 Error::NoLinker { tried } => {
303 write!(f, "no linker was found; tried {}", tried.join(", "))?;
304 if tried.iter().any(|name| is_lld(name)) {
307 write!(
308 f,
309 ". lld {LLD_EXPORTAS} or newer links for every target, and {}",
310 lld_advice()
311 )?;
312 }
313 Ok(())
314 }
315 Error::Named { name } => {
316 write!(f, "-fuse-ld={name} asks for a linker that is not on this machine")
317 }
318 Error::Target { triple } => {
319 write!(f, "there is no link line for {triple} in this compiler yet")
320 }
321 Error::Cross { why } => f.write_str(why),
322 Error::Sysroot { target, dir, pinned: true } => write!(
328 f,
329 "there is no sysroot for {target} at {dir}, so there is nothing to link it \
330 against. `rucc --fetch {target}` gets the one this release pins, or pass \
331 --sysroot=<dir> to name a tree you have already"
332 ),
333 Error::Sysroot { target, dir, pinned: false } => write!(
334 f,
335 "there is no sysroot for {target} at {dir}, so there is nothing to link it \
336 against, and this release pins none for it to fetch. Pass --sysroot=<dir> to name \
337 a tree you have already, or see spec/cross-compile/13-distribution.md section \
338 13.2 for the cache that will hold one"
339 ),
340 Error::TooOld { name, found, target } => write!(
343 f,
344 "{name} is lld {found} and cannot link for {target}. mingw-w64 writes a few hundred \
345 of its aliases, `_crt_atexit == atexit` among them, as IMPORT_NAME_EXPORTAS \
346 records in its import libraries, which lld learned to read in {LLD_EXPORTAS}. An \
347 older one neither reads them nor says so: it writes an import by ordinal zero, the \
348 link succeeds, and the program dies at startup. No newer lld was found either. \
349 For lld {LLD_EXPORTAS} or newer, {}, or name one with -fuse-ld=",
350 lld_advice()
351 ),
352 Error::Spawn { path, why } => write!(f, "could not run the linker at {path}: {why}"),
353 Error::Refused { status } => write!(f, "the linker {status}"),
354 }
355 }
356}
357
358impl std::error::Error for Error {}
359
360#[derive(Debug, Clone, PartialEq, Eq)]
362pub struct Linker {
363 pub name: String,
365 pub path: PathBuf,
367}
368
369#[must_use]
376pub fn order(target: Triple, opts: &LinkOptions) -> Vec<String> {
377 if let Some(named) = &opts.use_ld {
378 return vec![format!("ld.{named}"), named.clone()];
380 }
381 if target.os == Os::Darwin {
385 return vec!["ld".to_owned(), "ld64.lld".to_owned()];
386 }
387 if cross_sysroot(target, opts).is_some() {
388 let mut names = cross_order(target);
389 if (target.os, target.env) == (Os::Windows, Env::Gnu) {
395 names.retain(|name| is_lld(name));
396 }
397 return names;
398 }
399 if distro_cross(target, opts).is_some() {
400 return cross_order(target);
401 }
402 match target.os {
403 Os::Windows => vec!["lld-link".to_owned(), "link.exe".to_owned()],
404 _ => vec![
405 "ld.mold".to_owned(),
406 "mold".to_owned(),
407 "ld.lld".to_owned(),
408 "lld".to_owned(),
409 "ld".to_owned(),
410 ],
411 }
412}
413
414fn cross_order(target: Triple) -> Vec<String> {
430 let mut names = vec!["ld.lld".to_owned(), "lld".to_owned()];
431 match (target.os, target.env) {
432 (Os::Linux, _) => names.push(format!("{}-ld", multiarch(target))),
433 (Os::Windows, Env::Gnu) => names.push(format!("{}-w64-mingw32-ld", target.arch.as_str())),
434 _ => {}
435 }
436 names
437}
438
439#[must_use]
466pub fn cross_sysroot(target: Triple, opts: &LinkOptions) -> Option<Sysroot> {
467 cross_for(target, opts, Triple::host())
468}
469
470fn cross_for(target: Triple, opts: &LinkOptions, host: Option<Triple>) -> Option<Sysroot> {
472 if opts.sysroot.is_some() {
473 return None;
474 }
475 let tuple = target_tuple(target, opts);
476 if host == Some(target) && tuple.env_version().is_none() {
477 return None;
478 }
479 if distro_for(target, opts, host).is_some() {
480 return None;
481 }
482 let cache = opts.cache.as_deref()?;
483 Some(Sysroot::in_cache(cache, tuple))
484}
485
486#[derive(Debug, Clone, PartialEq, Eq)]
493pub struct Distro {
494 pub root: PathBuf,
496 pub gcc: Vec<PathBuf>,
499}
500
501impl Distro {
502 #[must_use]
504 pub fn include(&self) -> PathBuf {
505 self.root.join("include")
506 }
507
508 #[must_use]
510 pub fn lib(&self) -> PathBuf {
511 self.root.join("lib")
512 }
513}
514
515#[must_use]
523pub fn distro_cross(target: Triple, opts: &LinkOptions) -> Option<Distro> {
524 distro_for(target, opts, Triple::host())
525}
526
527fn distro_for(target: Triple, opts: &LinkOptions, host: Option<Triple>) -> Option<Distro> {
529 if opts.sysroot.is_some() || target.os != Os::Linux || host == Some(target) {
530 return None;
531 }
532 let tuple = target_tuple(target, opts);
533 if tuple.env_version().is_some() {
534 return None;
535 }
536 if opts.cache.as_deref().is_some_and(|cache| Sysroot::in_cache(cache, tuple).lib().is_dir()) {
537 return None;
538 }
539 let usr = opts.usr.as_deref()?;
540 let name = multiarch(target);
541 let root = usr.join(&name);
542 if !root.join("include").is_dir() || !root.join("lib").is_dir() {
543 return None;
544 }
545 let gcc = newest_first(&usr.join("lib/gcc-cross").join(&name));
546 Some(Distro { root, gcc })
547}
548
549fn target_tuple(target: Triple, opts: &LinkOptions) -> TargetTuple {
557 opts.pinned.unwrap_or_else(|| target.tuple())
558}
559
560#[must_use]
571pub fn cross_kernel(target: Triple, opts: &LinkOptions) -> Option<Kernel> {
572 kernel_for(target, opts, Triple::host())
573}
574
575fn kernel_for(target: Triple, opts: &LinkOptions, host: Option<Triple>) -> Option<Kernel> {
577 cross_for(target, opts, host)?;
578 Kernel::for_target(opts.cache.as_deref()?, target.tuple())
579}
580
581fn mode(opts: &LinkOptions) -> LinkMode {
588 let pie = opts.pie.unwrap_or(!opts.is_static && !opts.shared);
589 if opts.shared {
590 LinkMode::Shared
591 } else if opts.is_static {
592 if pie { LinkMode::StaticPie } else { LinkMode::Static }
593 } else if pie {
594 LinkMode::Dynamic
595 } else {
596 LinkMode::DynamicNoPie
597 }
598}
599
600fn cross_line(
607 target: Triple,
608 opts: &LinkOptions,
609 items: &[Item],
610 output: &str,
611 sysroot: &Sysroot,
612) -> Result<Vec<String>, Error> {
613 if opts.profile {
614 return Err(Error::Cross {
618 why: format!(
619 "-pg needs gcrt1.o, or gcrt2.o on Windows, the startup file that starts and stops \
620 the counting, and a generated sysroot for {target} does not have one. Profile on \
621 the host, or pass --sysroot=<dir> naming a tree that has it"
622 ),
623 });
624 }
625 let inputs: Vec<argv::Item> = items
626 .iter()
627 .map(|item| match item {
628 Item::File(path) => argv::Item::File(PathBuf::from(path)),
629 Item::Library(name) => argv::Item::Library(name.clone()),
630 Item::Linker(arg) => argv::Item::Linker(arg.clone()),
631 })
632 .collect();
633 let output = PathBuf::from(output);
634 let ours = builtins_archive(target, &opts.prefixes);
639 if ours.is_none() && opts.wants_runtime() && !opts.no_builtins_lib {
640 let tuple = target.tuple().to_canonical_string();
644 return Err(Error::Cross {
645 why: format!(
646 "a cross link ends with librucc_builtins.a, this compiler's own runtime for \
647 {tuple}, and there is none beside the compiler or under a -B prefix. A sysroot \
648 does not carry it, because it is our output rather than the platform's. Build it \
649 with `cargo xtask builtins --target={tuple}`, or pass -fno-builtins-lib to link \
650 without it"
651 ),
652 });
653 }
654 let invocation = argv::Invocation {
655 inputs: &inputs,
656 output: Some(&output),
657 mode: mode(opts),
658 search: &opts.search,
659 no_startfiles: !opts.wants_startfiles(),
660 no_defaultlibs: !opts.wants_defaultlibs(),
661 no_builtins_lib: opts.no_builtins_lib,
662 builtins: ours.as_deref(),
663 export_dynamic: opts.export_dynamic,
664 strip: opts.strip,
665 gui: opts.gui,
666 unicode: opts.unicode,
667 };
668 argv::argv(target.tuple(), sysroot, &invocation)
669 .map_err(|why| Error::Cross { why: why.to_string() })
670}
671
672pub fn preflight(target: Triple, opts: &LinkOptions) -> Result<(), Error> {
689 if opts.relocatable {
690 return relocatable_line(target, opts, &[], "a.out").map(drop);
691 }
692 if target.os == Os::Darwin {
695 return darwin_line(target, opts, &[], "a.out").map(drop);
696 }
697 let Some(sysroot) = cross_sysroot(target, opts) else { return Ok(()) };
698 let shape = LinkOptions { no_builtins_lib: true, ..opts.clone() };
702 cross_line(target, &shape, &[], "a.out", &sysroot)?;
703 if !sysroot.lib().is_dir() {
707 let tuple = target_tuple(target, opts).to_canonical_string();
708 return Err(Error::Sysroot {
709 dir: sysroot.root().display().to_string(),
710 pinned: rucc_sysroot::pinned_for_target(target_tuple(target, opts)).is_some(),
711 target: tuple,
712 });
713 }
714 cross_line(target, opts, &[], "a.out", &sysroot)?;
717 Ok(())
718}
719
720pub fn write_stubs(target: Triple, opts: &LinkOptions) -> Result<(), Error> {
740 let Some(sysroot) = cross_sysroot(target, opts) else { return Ok(()) };
741 let tuple = sysroot.target();
742 if rucc_stub::glibc::architecture(tuple).is_none() {
743 return Ok(());
744 }
745 let Ok(Some(minor)) = rucc_sysroot::bundled_glibc_minor(tuple) else { return Ok(()) };
746 let files = rucc_stub::glibc::stubs(tuple, minor).map_err(|why| Error::Cross {
747 why: format!("the glibc stubs for {}: {why}", tuple.to_canonical_string()),
748 })?;
749 let dir = sysroot.stubs();
750 let failed = |path: &Path, why: std::io::Error| Error::Cross {
751 why: format!("{} cannot be written: {why}", path.display()),
752 };
753 fs::create_dir_all(dir).map_err(|why| failed(dir, why))?;
754 for file in files {
755 let path = dir.join(&file.name);
756 if fs::read(&path).is_ok_and(|there| there == file.bytes) {
757 continue;
758 }
759 let temporary = dir.join(format!(".{}.{}", file.name, std::process::id()));
760 fs::write(&temporary, &file.bytes).map_err(|why| failed(&temporary, why))?;
761 fs::rename(&temporary, &path).map_err(|why| {
762 let _ = fs::remove_file(&temporary);
763 failed(&path, why)
764 })?;
765 }
766 Ok(())
767}
768
769pub fn find(target: Triple, opts: &LinkOptions) -> Result<Linker, Error> {
780 let tried = order(target, opts);
781 let places = lld_dirs(Path::new("/"), std::env::var_os("ProgramFiles").map(PathBuf::from));
782 let mut refused = None;
786 for name in &tried {
787 for path in linker_candidates(name, opts, &places) {
788 let linker = Linker { name: name.clone(), path };
789 match suitable(target, &linker) {
790 Ok(()) => return Ok(linker),
791 Err(why) => {
792 refused.get_or_insert(why);
793 }
794 }
795 }
796 }
797 if let Some(why) = refused {
798 return Err(why);
799 }
800 match &opts.use_ld {
801 Some(name) => Err(Error::Named { name: name.clone() }),
802 None => Err(Error::NoLinker { tried }),
803 }
804}
805
806fn linker_candidates(name: &str, opts: &LinkOptions, places: &[PathBuf]) -> Vec<PathBuf> {
813 if name.contains(std::path::MAIN_SEPARATOR) || name.contains('/') {
814 let path = PathBuf::from(name);
815 return if path.is_file() { vec![path] } else { Vec::new() };
816 }
817 let pathext = pathext();
818 let mut found: Vec<PathBuf> = opts
819 .prefixes
820 .iter()
821 .flat_map(|dir| spellings(&dir.join(name), &pathext))
822 .filter(|path| path.is_file())
823 .collect();
824 if let Some(path) = std::env::var_os("PATH") {
825 found.extend(
826 std::env::split_paths(&path)
827 .flat_map(|dir| spellings(&dir.join(name), &pathext))
828 .filter(|p| executable(p)),
829 );
830 }
831 if is_lld(name) {
835 for dir in places {
836 for file in spellings(&dir.join(name), &pathext) {
837 if executable(&file) && !found.contains(&file) {
838 found.push(file);
839 }
840 }
841 }
842 }
843 found
844}
845
846fn pathext() -> Vec<String> {
853 if !cfg!(windows) {
854 return Vec::new();
855 }
856 let list = std::env::var("PATHEXT").unwrap_or_else(|_| ".COM;.EXE;.BAT;.CMD".to_owned());
857 list.split(';').filter(|ext| ext.starts_with('.')).map(str::to_ascii_lowercase).collect()
858}
859
860fn spellings(path: &Path, exts: &[String]) -> Vec<PathBuf> {
867 let has = path
868 .extension()
869 .and_then(|ext| ext.to_str())
870 .is_some_and(|ext| exts.iter().any(|e| e[1..].eq_ignore_ascii_case(ext)));
871 if exts.is_empty() || has {
872 return vec![path.to_path_buf()];
873 }
874 exts.iter()
875 .map(|ext| {
876 let mut name = path.as_os_str().to_owned();
877 name.push(ext);
878 PathBuf::from(name)
879 })
880 .collect()
881}
882
883fn is_lld(name: &str) -> bool {
885 matches!(name, "ld.lld" | "ld64.lld" | "lld" | "lld-link")
886}
887
888fn lld_dirs(root: &Path, program_files: Option<PathBuf>) -> Vec<PathBuf> {
898 let mut dirs: Vec<PathBuf> = [
899 "opt/homebrew/opt/lld/bin",
900 "opt/homebrew/opt/llvm/bin",
901 "usr/local/opt/lld/bin",
902 "usr/local/opt/llvm/bin",
903 "home/linuxbrew/.linuxbrew/opt/lld/bin",
904 "home/linuxbrew/.linuxbrew/opt/llvm/bin",
905 ]
906 .iter()
907 .map(|dir| root.join(dir))
908 .collect();
909 for (parent, prefix) in [("usr/lib", "llvm-"), ("usr/lib64", "llvm")] {
910 let mut versions: Vec<(u32, PathBuf)> = fs::read_dir(root.join(parent))
911 .into_iter()
912 .flatten()
913 .flatten()
914 .filter_map(|entry| {
915 let name = entry.file_name();
916 let version = name.to_str()?.strip_prefix(prefix)?.parse().ok()?;
917 Some((version, entry.path().join("bin")))
918 })
919 .collect();
920 versions.sort_by_key(|(version, _)| std::cmp::Reverse(*version));
921 dirs.extend(versions.into_iter().map(|(_, dir)| dir));
922 }
923 if let Some(dir) = program_files {
924 dirs.push(dir.join("LLVM").join("bin"));
925 }
926 dirs
927}
928
929fn lld_advice() -> &'static str {
935 if cfg!(target_os = "macos") {
936 "`brew install lld` installs one, and rucc finds it in Homebrew's directory without a \
937 change to PATH"
938 } else if cfg!(windows) {
939 "the LLVM installer from https://github.com/llvm/llvm-project/releases, or `winget install \
940 LLVM.LLVM`, installs one in %ProgramFiles%\\LLVM\\bin, where rucc finds it without a \
941 change to PATH"
942 } else {
943 "on Debian and Ubuntu `apt install lld-19` installs one in /usr/lib/llvm-19/bin and on \
944 Fedora `dnf install lld` installs one on PATH, and rucc finds either without a change to \
945 PATH"
946 }
947}
948
949pub const LLD_EXPORTAS: u32 = 19;
954
955pub fn suitable(target: Triple, linker: &Linker) -> Result<(), Error> {
977 if (target.os, target.env) != (Os::Windows, Env::Gnu) {
978 return Ok(());
979 }
980 let Some(found) = lld_major(&reported_version(&linker.path)) else { return Ok(()) };
981 if found >= LLD_EXPORTAS {
982 return Ok(());
983 }
984 Err(Error::TooOld {
985 name: linker.name.clone(),
986 found,
987 target: target.tuple().to_canonical_string(),
988 })
989}
990
991fn reported_version(path: &Path) -> String {
997 let Ok(out) = Command::new(path).arg("--version").output() else { return String::new() };
998 String::from_utf8_lossy(&out.stdout).into_owned()
999}
1000
1001fn lld_major(text: &str) -> Option<u32> {
1009 let mut words = text.split_whitespace();
1010 words.find(|word| *word == "LLD")?;
1011 words.next()?.split('.').next()?.parse().ok()
1012}
1013
1014#[cfg(unix)]
1016fn executable(path: &Path) -> bool {
1017 use std::os::unix::fs::PermissionsExt as _;
1018 path.metadata().is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0)
1019}
1020
1021#[cfg(not(unix))]
1026fn executable(path: &Path) -> bool {
1027 path.is_file()
1028}
1029
1030pub fn line(
1042 target: Triple,
1043 opts: &LinkOptions,
1044 items: &[Item],
1045 output: &str,
1046) -> Result<Vec<String>, Error> {
1047 if opts.relocatable {
1048 return relocatable_line(target, opts, items, output);
1049 }
1050 if target.os == Os::Darwin {
1051 return darwin_line(target, opts, items, output);
1052 }
1053 if let Some(sysroot) = cross_sysroot(target, opts) {
1054 return cross_line(target, opts, items, output, &sysroot);
1055 }
1056 if target.os != Os::Linux {
1057 return Err(Error::Target { triple: target.to_string() });
1058 }
1059 let machine = emulation(target);
1060 let root = opts.sysroot.as_deref();
1061 let distro = distro_cross(target, opts);
1064 let dirs = match &distro {
1065 Some(distro) => vec![distro.lib()],
1066 None => library_dirs(target, root),
1067 };
1068 let runtime = match distro {
1071 Some(distro) => distro.gcc,
1072 None => runtime_dirs(target, root),
1073 };
1074 let ours = if opts.no_builtins_lib { None } else { builtins_archive(target, &opts.prefixes) };
1075 let mut args = vec![
1076 "-o".to_owned(),
1077 output.to_owned(),
1078 "-m".to_owned(),
1082 machine.to_owned(),
1083 "--eh-frame-hdr".to_owned(),
1086 "--hash-style=gnu".to_owned(),
1090 ];
1091
1092 let pie = opts.pie.unwrap_or(!opts.is_static && !opts.shared);
1093 if opts.shared {
1094 args.push("-shared".to_owned());
1095 } else if opts.is_static {
1096 args.push("-static".to_owned());
1097 } else if pie {
1098 args.push("-pie".to_owned());
1099 } else {
1100 args.push("-no-pie".to_owned());
1101 }
1102 if !opts.is_static && !opts.shared {
1103 args.push("-dynamic-linker".to_owned());
1104 args.push(target_path(root, loader(target)));
1105 }
1106 if opts.export_dynamic {
1107 args.push("--export-dynamic".to_owned());
1108 }
1109 if opts.strip {
1110 args.push("-s".to_owned());
1111 }
1112
1113 if opts.wants_startfiles() {
1114 for name in startfile(opts, pie).into_iter().chain(["crti.o"]) {
1115 if let Some(path) = find_file(&dirs, name) {
1116 args.push(path.display().to_string());
1117 }
1118 }
1119 let begin = if opts.shared || pie {
1125 "crtbeginS.o"
1126 } else if opts.is_static {
1127 "crtbeginT.o"
1128 } else {
1129 "crtbegin.o"
1130 };
1131 if let Some(path) = find_file(&runtime, begin).or_else(|| find_file(&runtime, "crtbegin.o"))
1132 {
1133 args.push(path.display().to_string());
1134 }
1135 }
1136
1137 for dir in &opts.search {
1138 args.push(format!("-L{}", dir.display()));
1139 }
1140 for dir in &dirs {
1141 args.push(format!("-L{}", dir.display()));
1142 }
1143 for dir in &runtime {
1146 args.push(format!("-L{}", dir.display()));
1147 }
1148
1149 for item in items {
1150 match item {
1151 Item::File(path) => args.push(path.clone()),
1152 Item::Library(name) => args.push(format!("-l{name}")),
1153 Item::Linker(arg) => args.push(arg.clone()),
1154 }
1155 }
1156 args.extend(runtime_items(opts, &runtime, ours.as_deref()));
1159
1160 if opts.wants_startfiles() {
1161 if opts.wants_fastmath() {
1166 if let Some(path) = find_file(&runtime, "crtfastmath.o") {
1167 args.push(path.display().to_string());
1168 }
1169 }
1170 let end = if opts.shared || pie { "crtendS.o" } else { "crtend.o" };
1171 if let Some(path) = find_file(&runtime, end).or_else(|| find_file(&runtime, "crtend.o")) {
1172 args.push(path.display().to_string());
1173 }
1174 if let Some(path) = find_file(&dirs, "crtn.o") {
1175 args.push(path.display().to_string());
1176 }
1177 }
1178
1179 Ok(args)
1180}
1181
1182fn relocatable_line(
1188 target: Triple,
1189 opts: &LinkOptions,
1190 items: &[Item],
1191 output: &str,
1192) -> Result<Vec<String>, Error> {
1193 if target.os == Os::Darwin {
1194 let mut args = vec![
1197 "-r".to_owned(),
1198 "-arch".to_owned(),
1199 darwin_arch(target)?.to_owned(),
1200 "-o".to_owned(),
1201 output.to_owned(),
1202 ];
1203 for dir in &opts.search {
1204 args.push(format!("-L{}", dir.display()));
1205 }
1206 push_items(&mut args, items);
1207 return Ok(args);
1208 }
1209 if target.os != Os::Linux {
1210 return Err(Error::Target { triple: target.to_string() });
1211 }
1212 let mut args = vec![
1213 "-o".to_owned(),
1214 output.to_owned(),
1215 "-m".to_owned(),
1216 emulation(target).to_owned(),
1217 "-r".to_owned(),
1218 ];
1219 if opts.strip {
1220 args.push("-s".to_owned());
1221 }
1222 for dir in &opts.search {
1223 args.push(format!("-L{}", dir.display()));
1224 }
1225 for item in items {
1226 match item {
1227 Item::File(path) => args.push(path.clone()),
1228 Item::Library(name) => args.push(format!("-l{name}")),
1229 Item::Linker(arg) => args.push(arg.clone()),
1230 }
1231 }
1232 Ok(args)
1233}
1234
1235pub fn darwin_line(
1252 target: Triple,
1253 opts: &LinkOptions,
1254 items: &[Item],
1255 output: &str,
1256) -> Result<Vec<String>, Error> {
1257 let arch = darwin_arch(target)?;
1258 if opts.is_static && !opts.shared {
1259 return Err(Error::Cross {
1260 why: "there is no static C library for Apple platforms, so -static cannot make a \
1261 program for one"
1262 .to_owned(),
1263 });
1264 }
1265 let Some(sdk) = crate::library::sdk(opts.sysroot.as_deref()) else {
1266 return Err(Error::Cross {
1267 why: format!(
1268 "no SDK was found to link {} against. Install the command line tools with \
1269 `xcode-select --install`, or name one with -isysroot <dir> or SDKROOT",
1270 target_tuple(target, opts).to_canonical_string()
1271 ),
1272 });
1273 };
1274 let tuple = target_tuple(target, opts);
1275 let (platform, default) = match (tuple.os(), tuple.env()) {
1276 (rucc_tuple::Os::IOs, rucc_tuple::Env::Simulator) => ("ios-simulator", "14.0"),
1277 (rucc_tuple::Os::IOs, rucc_tuple::Env::MacAbi) => ("mac-catalyst", "14.0"),
1278 (rucc_tuple::Os::IOs, _) => ("ios", "14.0"),
1279 _ => ("macos", "11.0"),
1280 };
1281 let minimum = opts
1282 .os_version
1283 .or_else(|| tuple.os_version())
1284 .map_or_else(|| default.to_owned(), |version| version.to_string());
1285 let version = sdk_version(&sdk).unwrap_or_else(|| minimum.clone());
1289
1290 let mut args = vec![
1291 "-arch".to_owned(),
1292 arch.to_owned(),
1293 "-platform_version".to_owned(),
1294 platform.to_owned(),
1295 minimum,
1296 version,
1297 "-syslibroot".to_owned(),
1298 sdk.display().to_string(),
1299 "-o".to_owned(),
1300 output.to_owned(),
1301 ];
1302 if opts.shared {
1303 args.push("-dylib".to_owned());
1304 }
1305 if opts.export_dynamic {
1306 args.push("-export_dynamic".to_owned());
1307 }
1308 if opts.strip {
1309 args.push("-S".to_owned());
1312 args.push("-x".to_owned());
1313 }
1314 for dir in &opts.search {
1315 args.push(format!("-L{}", dir.display()));
1316 }
1317 push_items(&mut args, items);
1318 if opts.wants_runtime() && !opts.no_builtins_lib {
1319 if let Some(ours) = builtins_archive(target, &opts.prefixes) {
1320 args.push(ours.display().to_string());
1321 }
1322 }
1323 if opts.wants_defaultlibs() {
1324 args.push("-lSystem".to_owned());
1325 }
1326 Ok(args)
1327}
1328
1329fn darwin_arch(target: Triple) -> Result<&'static str, Error> {
1331 match target.arch {
1332 Arch::Aarch64 => Ok("arm64"),
1333 Arch::X86_64 => Ok("x86_64"),
1334 _ => Err(Error::Target { triple: target.to_string() }),
1335 }
1336}
1337
1338fn sdk_version(sdk: &Path) -> Option<String> {
1344 let valid = |text: &str| {
1345 !text.is_empty()
1346 && text
1347 .split('.')
1348 .all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit()))
1349 };
1350 if let Ok(text) = fs::read_to_string(sdk.join("SDKSettings.json")) {
1351 if let Some(at) = text.find("\"Version\"") {
1352 let rest = &text[at + "\"Version\"".len()..];
1353 let rest = rest.trim_start().strip_prefix(':')?.trim_start().strip_prefix('"')?;
1354 let version = &rest[..rest.find('"')?];
1355 if valid(version) {
1356 return Some(version.to_owned());
1357 }
1358 }
1359 }
1360 let name = sdk.file_name()?.to_str()?.strip_suffix(".sdk")?;
1361 let version = name.trim_start_matches(|c: char| c.is_ascii_alphabetic());
1362 valid(version).then(|| version.to_owned())
1363}
1364
1365fn push_items(args: &mut Vec<String>, items: &[Item]) {
1367 for item in items {
1368 match item {
1369 Item::File(path) => args.push(path.clone()),
1370 Item::Library(name) => args.push(format!("-l{name}")),
1371 Item::Linker(arg) => args.push(arg.clone()),
1372 }
1373 }
1374}
1375
1376fn startfile(opts: &LinkOptions, pie: bool) -> Option<&'static str> {
1388 if opts.shared {
1389 None
1390 } else if opts.profile {
1391 Some(if pie && opts.is_static { "grcrt1.o" } else { "gcrt1.o" })
1392 } else if pie {
1393 Some("Scrt1.o")
1394 } else {
1395 Some("crt1.o")
1396 }
1397}
1398
1399fn runtime_items(opts: &LinkOptions, runtime: &[PathBuf], ours: Option<&Path>) -> Vec<String> {
1423 let mut args = Vec::new();
1424 if !opts.wants_defaultlibs() && !opts.wants_runtime() {
1425 return args;
1426 }
1427 let has_gcc = find_file(runtime, "libgcc.a").is_some();
1431
1432 if opts.is_static {
1433 args.push("--start-group".to_owned());
1434 }
1435 if opts.wants_defaultlibs() {
1436 args.push("-lc".to_owned());
1437 }
1438 if opts.wants_runtime() {
1439 if let Some(path) = ours {
1440 args.push(path.display().to_string());
1441 }
1442 if has_gcc {
1443 args.push("-lgcc".to_owned());
1444 if opts.is_static {
1445 args.push("-lgcc_eh".to_owned());
1446 }
1447 }
1448 }
1449 if opts.is_static {
1450 args.push("--end-group".to_owned());
1451 } else if opts.wants_runtime() && has_gcc {
1452 args.push("--as-needed".to_owned());
1454 args.push("-lgcc_s".to_owned());
1455 args.push("--no-as-needed".to_owned());
1456 }
1457 args
1458}
1459
1460#[must_use]
1467pub fn runtime_dirs(target: Triple, sysroot: Option<&Path>) -> Vec<PathBuf> {
1468 let libc = match target.env {
1469 Env::Musl => "musl",
1470 Env::None | Env::Gnu | Env::Msvc => "gnu",
1471 };
1472 let arch = target.arch.as_str();
1473 let names = [
1477 format!("{arch}-linux-{libc}"),
1478 format!("{arch}-pc-linux-{libc}"),
1479 format!("{arch}-redhat-linux"),
1480 format!("{arch}-suse-linux"),
1481 format!("{arch}-alpine-linux-{libc}"),
1482 ];
1483 let mut found = Vec::new();
1484 for base in ["/usr/lib/gcc", "/usr/lib64/gcc", "/usr/local/lib/gcc"] {
1485 for name in &names {
1486 found.extend(newest_first(&under(sysroot, &format!("{base}/{name}"))));
1487 }
1488 }
1489 found
1490}
1491
1492fn newest_first(dir: &Path) -> Vec<PathBuf> {
1494 let Ok(entries) = fs::read_dir(dir) else { return Vec::new() };
1495 let mut versions: Vec<(Vec<u64>, PathBuf)> = entries
1496 .flatten()
1497 .map(|e| e.path())
1498 .filter(|p| p.is_dir())
1499 .map(|p| (version_key(&p), p))
1500 .collect();
1501 versions.sort_by(|a, b| b.0.cmp(&a.0));
1505 versions.into_iter().map(|(_, path)| path).collect()
1506}
1507
1508fn version_key(dir: &Path) -> Vec<u64> {
1513 let name = dir.file_name().unwrap_or_default().to_string_lossy();
1514 name.split('.').map(|part| part.parse::<u64>().unwrap_or(0)).collect()
1515}
1516
1517#[must_use]
1523pub fn builtins_archive(target: Triple, prefixes: &[PathBuf]) -> Option<PathBuf> {
1524 const NAME: &str = rucc_sysroot::link::BUILTINS;
1527 let spellings = [target.to_string(), target.tuple().to_string()];
1531 let mut places: Vec<PathBuf> = Vec::new();
1532 for prefix in prefixes {
1533 for triple in &spellings {
1534 places.push(prefix.join(triple).join(NAME));
1535 }
1536 places.push(prefix.join(NAME));
1537 }
1538 if let Some(dir) =
1539 std::env::current_exe().ok().and_then(|exe| exe.parent().map(Path::to_path_buf))
1540 {
1541 for triple in &spellings {
1544 places.push(dir.join("lib").join("rucc").join(triple).join(NAME));
1545 }
1546 if let Some(up) = dir.parent() {
1547 for triple in &spellings {
1548 places.push(up.join("lib").join("rucc").join(triple).join(NAME));
1550 for profile in ["release", "debug"] {
1553 places.push(up.join(triple).join(profile).join(NAME));
1554 }
1555 }
1556 }
1557 places.push(dir.join(NAME));
1558 }
1559 places.into_iter().find(|path| path.is_file())
1560}
1561
1562fn emulation(target: Triple) -> &'static str {
1564 match target.arch {
1565 Arch::X86_64 => "elf_x86_64",
1566 Arch::Aarch64 => "aarch64linux",
1567 Arch::Riscv64 => "elf64lriscv",
1568 }
1569}
1570
1571fn loader(target: Triple) -> &'static str {
1576 match (target.arch, target.env) {
1577 (Arch::X86_64, Env::Musl) => "/lib/ld-musl-x86_64.so.1",
1578 (Arch::X86_64, _) => "/lib64/ld-linux-x86-64.so.2",
1579 (Arch::Aarch64, Env::Musl) => "/lib/ld-musl-aarch64.so.1",
1580 (Arch::Aarch64, _) => "/lib/ld-linux-aarch64.so.1",
1581 (Arch::Riscv64, Env::Musl) => "/lib/ld-musl-riscv64.so.1",
1582 (Arch::Riscv64, _) => "/lib/ld-linux-riscv64-lp64d.so.1",
1583 }
1584}
1585
1586#[must_use]
1593pub fn candidates(target: Triple, sysroot: Option<&Path>) -> Vec<PathBuf> {
1594 let multiarch = multiarch(target);
1595 [
1596 format!("/usr/lib/{multiarch}"),
1597 format!("/lib/{multiarch}"),
1598 "/usr/lib64".to_owned(),
1599 "/lib64".to_owned(),
1600 "/usr/lib".to_owned(),
1601 "/lib".to_owned(),
1602 ]
1603 .into_iter()
1604 .map(|dir| under(sysroot, &dir))
1605 .collect()
1606}
1607
1608#[must_use]
1613pub fn multiarch(target: Triple) -> String {
1614 let libc = match target.env {
1615 Env::Musl => "musl",
1616 Env::None | Env::Gnu | Env::Msvc => "gnu",
1617 };
1618 format!("{}-linux-{libc}", target.arch.as_str())
1619}
1620
1621fn library_dirs(target: Triple, sysroot: Option<&Path>) -> Vec<PathBuf> {
1623 candidates(target, sysroot).into_iter().filter(|dir| dir.is_dir()).collect()
1624}
1625
1626#[must_use]
1631pub fn search_dirs(link: &LinkOptions, target: Triple) -> Vec<PathBuf> {
1632 let mut dirs = link.search.clone();
1633 if let Some(sysroot) = cross_sysroot(target, link) {
1638 dirs.push(sysroot.lib());
1639 if rucc_sysroot::link::libc(sysroot.target()) == rucc_sysroot::link::Libc::Stub {
1640 dirs.push(sysroot.stubs().to_path_buf());
1641 }
1642 return dirs;
1643 }
1644 if let Some(distro) = distro_cross(target, link) {
1645 dirs.push(distro.lib());
1646 return dirs;
1647 }
1648 dirs.extend(candidates(target, link.sysroot.as_deref()));
1649 dirs
1650}
1651
1652#[must_use]
1657pub fn find_in_search(link: &LinkOptions, target: Triple, name: &str) -> Option<PathBuf> {
1658 find_file(&search_dirs(link, target), name)
1659}
1660
1661fn find_file(dirs: &[PathBuf], name: &str) -> Option<PathBuf> {
1663 dirs.iter().map(|dir| dir.join(name)).find(|path| path.is_file())
1664}
1665
1666fn under(sysroot: Option<&Path>, path: &str) -> PathBuf {
1668 match sysroot {
1669 Some(root) => root.join(path.strip_prefix('/').unwrap_or(path)),
1672 None => PathBuf::from(path),
1673 }
1674}
1675
1676fn target_path(sysroot: Option<&Path>, path: &str) -> String {
1683 match sysroot {
1684 Some(root) => {
1685 let root = root.display().to_string();
1686 format!("{}/{}", root.trim_end_matches(['/', '\\']), path.trim_start_matches('/'))
1687 }
1688 None => path.to_owned(),
1689 }
1690}
1691
1692#[must_use]
1694pub fn render(linker: &Linker, args: &[String]) -> String {
1695 let mut out = linker.path.display().to_string();
1696 for arg in args {
1697 out.push(' ');
1698 if arg.is_empty() || arg.contains(char::is_whitespace) {
1699 out.push('"');
1700 out.push_str(arg);
1701 out.push('"');
1702 } else {
1703 out.push_str(arg);
1704 }
1705 }
1706 out
1707}
1708
1709const WINDOWS_LINE: usize = 30_000;
1714
1715const UNIX_LINE: usize = 256 * 1024;
1718
1719fn too_long(args: &[String], limit: usize) -> bool {
1721 args.iter().map(|arg| arg.len() + 3).sum::<usize>() > limit
1722}
1723
1724fn split_for_file(args: &[String]) -> (Vec<String>, Vec<String>) {
1729 let mut front = Vec::new();
1730 let mut rest = Vec::with_capacity(args.len());
1731 let mut words = args.iter();
1732 while let Some(arg) = words.next() {
1733 if arg == "-m" {
1734 front.push(arg.clone());
1735 front.extend(words.next().cloned());
1736 } else {
1737 rest.push(arg.clone());
1738 }
1739 }
1740 (front, rest)
1741}
1742
1743fn windows_quoting(linker: &Linker) -> bool {
1749 let file = linker.path.file_stem().and_then(|stem| stem.to_str()).unwrap_or_default();
1750 cfg!(windows) && (is_lld(&linker.name) || file.starts_with("ld.lld") || file.starts_with("lld"))
1751}
1752
1753fn response_text(args: &[String], windows: bool) -> String {
1760 let mut text = String::new();
1761 for arg in args {
1762 text.push('"');
1763 let mut slashes = 0;
1764 for c in arg.chars() {
1765 match c {
1766 '\\' if windows => slashes += 1,
1767 '"' if windows => {
1768 text.extend(std::iter::repeat_n('\\', slashes * 2 + 1));
1769 text.push('"');
1770 slashes = 0;
1771 }
1772 _ if windows => {
1773 text.extend(std::iter::repeat_n('\\', slashes));
1774 text.push(c);
1775 slashes = 0;
1776 }
1777 '"' | '\\' => {
1778 text.push('\\');
1779 text.push(c);
1780 }
1781 _ => text.push(c),
1782 }
1783 }
1784 text.extend(std::iter::repeat_n('\\', slashes * 2));
1785 text.push_str("\"\n");
1786 }
1787 text
1788}
1789
1790pub fn run(linker: &Linker, args: &[String]) -> Result<(), Error> {
1802 let spawn = |why: std::io::Error| Error::Spawn {
1803 path: linker.path.display().to_string(),
1804 why: why.to_string(),
1805 };
1806 let mut command = Command::new(&linker.path);
1807 let mut written = None;
1808 if too_long(args, if cfg!(windows) { WINDOWS_LINE } else { UNIX_LINE }) {
1809 let (front, rest) = split_for_file(args);
1810 let path = std::env::temp_dir().join(format!("rucc-link-{}.rsp", std::process::id()));
1811 fs::write(&path, response_text(&rest, windows_quoting(linker))).map_err(spawn)?;
1812 let mut at = OsString::from("@");
1813 at.push(&path);
1814 command.args(front).arg(at);
1815 written = Some(path);
1816 } else {
1817 command.args(args.iter().map(OsString::from));
1818 }
1819 let status = command.status();
1820 if let Some(path) = written {
1821 let _ = fs::remove_file(path);
1822 }
1823 let status = status.map_err(spawn)?;
1824 if status.success() {
1825 return Ok(());
1826 }
1827 Err(Error::Refused {
1831 status: match status.code() {
1832 Some(code) => format!("exited with status {code}"),
1833 None => "was killed before it finished".to_owned(),
1834 },
1835 })
1836}
1837
1838#[cfg(test)]
1839mod tests {
1840 use super::*;
1841
1842 fn linux() -> Triple {
1843 Triple::new(Arch::X86_64, Os::Linux, Env::Gnu)
1844 }
1845
1846 fn one(name: &str) -> Vec<Item> {
1847 vec![Item::File(name.to_owned())]
1848 }
1849
1850 #[test]
1851 fn the_fast_one_is_looked_for_first_and_the_platforms_own_last() {
1852 let names = order(linux(), &LinkOptions::default());
1853 assert_eq!(names.first().map(String::as_str), Some("ld.mold"));
1854 assert_eq!(names.last().map(String::as_str), Some("ld"));
1855 }
1856
1857 #[test]
1858 fn naming_one_is_the_whole_of_the_order() {
1859 let opts = LinkOptions { use_ld: Some("gold".to_owned()), ..LinkOptions::default() };
1860 assert_eq!(order(linux(), &opts), ["ld.gold", "gold"]);
1861 }
1862
1863 #[test]
1864 fn a_dynamic_program_names_the_loader_that_will_start_it() {
1865 let args = line(linux(), &LinkOptions::default(), &one("a.o"), "a.out").expect("a line");
1866 let at = args.iter().position(|a| a == "-dynamic-linker").expect("the flag");
1867 assert!(args[at + 1].ends_with("/lib64/ld-linux-x86-64.so.2"), "{args:?}");
1868 }
1869
1870 #[test]
1872 fn a_relocatable_link_is_the_objects_and_nothing_a_program_needs() {
1873 let opts = LinkOptions { relocatable: true, ..LinkOptions::default() };
1874 let args = line(linux(), &opts, &one("a.o"), "built-in.o").expect("a line");
1875 assert_eq!(args, ["-o", "built-in.o", "-m", "elf_x86_64", "-r", "a.o"]);
1876 }
1877
1878 #[test]
1879 fn a_static_program_names_no_loader_because_nothing_will_start_it() {
1880 let opts = LinkOptions { is_static: true, ..LinkOptions::default() };
1881 let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
1882 assert!(args.contains(&"-static".to_owned()), "{args:?}");
1883 assert!(!args.contains(&"-dynamic-linker".to_owned()), "{args:?}");
1884 }
1885
1886 #[test]
1887 fn the_startup_file_of_a_program_that_moves_is_not_the_one_of_a_program_that_does_not() {
1888 let moving = LinkOptions { pie: Some(true), ..LinkOptions::default() };
1889 let fixed = LinkOptions { pie: Some(false), ..LinkOptions::default() };
1890 let named = |opts: &LinkOptions| {
1891 line(linux(), opts, &one("a.o"), "a.out")
1892 .expect("a line")
1893 .iter()
1894 .filter_map(|a| Path::new(a).file_name().map(|n| n.to_string_lossy().into_owned()))
1895 .find(|n| n.ends_with("crt1.o"))
1896 };
1897 if let Some(name) = named(&moving) {
1900 assert_eq!(name, "Scrt1.o");
1901 assert_eq!(named(&fixed).as_deref(), Some("crt1.o"));
1902 }
1903 }
1904
1905 #[test]
1914 fn a_profiled_program_is_started_by_the_startup_file_that_counts() {
1915 let profile = LinkOptions { profile: true, ..LinkOptions::default() };
1916 assert_eq!(startfile(&profile, false), Some("gcrt1.o"));
1917 assert_eq!(startfile(&profile, true), Some("gcrt1.o"));
1918 let still = LinkOptions { is_static: true, ..profile.clone() };
1919 assert_eq!(startfile(&still, true), Some("grcrt1.o"));
1920 assert_eq!(startfile(&still, false), Some("gcrt1.o"));
1921 let shared = LinkOptions { shared: true, ..profile };
1922 assert_eq!(startfile(&shared, false), None);
1923 }
1924
1925 #[test]
1927 fn a_program_that_is_not_profiled_is_started_by_the_usual_one() {
1928 let plain = LinkOptions::default();
1929 assert_eq!(startfile(&plain, false), Some("crt1.o"));
1930 assert_eq!(startfile(&plain, true), Some("Scrt1.o"));
1931 }
1932
1933 #[test]
1934 fn asking_for_no_startup_files_leaves_out_both_ends_of_them() {
1935 let opts = LinkOptions { no_startfiles: true, ..LinkOptions::default() };
1936 let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
1937 assert!(!args.iter().any(|a| a.ends_with("crt1.o")), "{args:?}");
1938 assert!(!args.iter().any(|a| a.ends_with("crtn.o")), "{args:?}");
1939 assert!(args.contains(&"-lc".to_owned()), "{args:?}");
1941 }
1942
1943 #[test]
1944 fn asking_for_no_library_at_all_leaves_out_the_startup_files_too() {
1945 let opts = LinkOptions { no_stdlib: true, ..LinkOptions::default() };
1946 let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
1947 assert!(!args.contains(&"-lc".to_owned()), "{args:?}");
1948 assert!(!args.iter().any(|a| a.ends_with("crt1.o")), "{args:?}");
1949 }
1950
1951 #[test]
1952 fn the_library_comes_after_the_objects_that_need_it() {
1953 let items = vec![Item::File("a.o".to_owned()), Item::Library("m".to_owned())];
1954 let args = line(linux(), &LinkOptions::default(), &items, "a.out").expect("a line");
1955 let obj = args.iter().position(|a| a == "a.o").expect("the object");
1956 let m = args.iter().position(|a| a == "-lm").expect("the library");
1957 let c = args.iter().position(|a| a == "-lc").expect("the library");
1958 assert!(obj < m && m < c, "{args:?}");
1959 }
1960
1961 #[test]
1962 fn what_the_user_told_the_linker_stays_where_the_user_wrote_it() {
1963 let items = vec![
1967 Item::File("a.o".to_owned()),
1968 Item::Linker("--whole-archive".to_owned()),
1969 Item::File("libaesni.a".to_owned()),
1970 Item::Linker("--no-whole-archive".to_owned()),
1971 Item::Library("m".to_owned()),
1972 ];
1973 let args = line(linux(), &LinkOptions::default(), &items, "a.out").expect("a line");
1974 let at = |what: &str| args.iter().position(|a| a == what).expect(what);
1975 assert!(at("a.o") < at("--whole-archive"), "{args:?}");
1976 assert!(at("--whole-archive") < at("libaesni.a"), "{args:?}");
1977 assert!(at("libaesni.a") < at("--no-whole-archive"), "{args:?}");
1978 assert!(at("--no-whole-archive") < at("-lm"), "{args:?}");
1979 assert!(at("-lm") < at("-lc"), "{args:?}");
1980 }
1981
1982 #[test]
1983 fn a_sysroot_moves_every_path_this_decided_and_none_the_user_wrote() {
1984 let opts = LinkOptions {
1985 sysroot: Some(PathBuf::from("/nowhere-at-all")),
1986 search: vec![PathBuf::from("/opt/mine")],
1987 ..LinkOptions::default()
1988 };
1989 let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
1990 let at = args.iter().position(|a| a == "-dynamic-linker").expect("the flag");
1991 assert_eq!(args[at + 1], "/nowhere-at-all/lib64/ld-linux-x86-64.so.2");
1992 assert!(args.contains(&"-L/opt/mine".to_owned()), "{args:?}");
1993 }
1994
1995 #[test]
1996 fn a_platform_with_no_link_line_is_said_so_rather_than_linked_wrongly() {
1997 let triple = Triple::new(Arch::X86_64, Os::Windows, Env::Msvc);
1998 let error = line(triple, &LinkOptions::default(), &one("a.o"), "a.out")
1999 .expect_err("no line for it");
2000 assert!(matches!(error, Error::Target { .. }), "{error:?}");
2001 }
2002
2003 fn an_sdk(name: &str, settings: Option<&str>) -> PathBuf {
2006 let dir = std::env::temp_dir()
2007 .join(format!("rucc-sdk-{}-{}", std::process::id(), name.replace('.', "-")))
2008 .join(name);
2009 fs::create_dir_all(&dir).expect("a temporary directory");
2010 if let Some(settings) = settings {
2011 fs::write(dir.join("SDKSettings.json"), settings).expect("a settings file");
2012 }
2013 dir
2014 }
2015
2016 fn mac() -> Triple {
2017 Triple::new(Arch::Aarch64, Os::Darwin, Env::None)
2018 }
2019
2020 #[test]
2021 fn a_mac_link_names_the_platform_the_sdk_and_libsystem() {
2022 let sdk = an_sdk(
2023 "MacOSX.sdk",
2024 Some(
2025 "{\"CanonicalName\": \"macosx15.2\", \"Version\" : \"15.2\", \"MaximumDeploymentTarget\": \"15.2.99\"}",
2026 ),
2027 );
2028 let opts = LinkOptions {
2029 sysroot: Some(sdk.clone()),
2030 search: vec![PathBuf::from("/opt/mine")],
2031 no_builtins_lib: true,
2032 ..LinkOptions::default()
2033 };
2034 let items = vec![Item::File("a.o".to_owned()), Item::Library("m".to_owned())];
2035 let args = line(mac(), &opts, &items, "a.out").expect("a line");
2036 let sdk = sdk.display().to_string();
2037 let want: Vec<&str> = vec![
2038 "-arch",
2039 "arm64",
2040 "-platform_version",
2041 "macos",
2042 "11.0",
2043 "15.2",
2044 "-syslibroot",
2045 &sdk,
2046 "-o",
2047 "a.out",
2048 "-L/opt/mine",
2049 "a.o",
2050 "-lm",
2051 "-lSystem",
2052 ];
2053 assert_eq!(args, want);
2054
2055 let opts =
2057 LinkOptions { os_version: Some(rucc_tuple::Version::new(13, 4)), shared: true, ..opts };
2058 let args = line(mac(), &opts, &one("a.o"), "liba.dylib").expect("a line");
2059 assert_eq!(args[3..6], ["macos", "13.4", "15.2"]);
2060 assert!(args.contains(&"-dylib".to_owned()), "{args:?}");
2061 assert!(!args.iter().any(|arg| arg.contains("pie")), "{args:?}");
2062 }
2063
2064 #[test]
2065 fn the_sdk_version_comes_from_its_name_when_it_has_no_settings() {
2066 let sdk = an_sdk("MacOSX14.5.sdk", None);
2067 let opts =
2068 LinkOptions { sysroot: Some(sdk), no_builtins_lib: true, ..LinkOptions::default() };
2069 let args = line(mac(), &opts, &one("a.o"), "a.out").expect("a line");
2070 assert_eq!(args[3..6], ["macos", "11.0", "14.5"]);
2071 let sdk = an_sdk("Somewhere", None);
2073 let opts = LinkOptions {
2074 sysroot: Some(sdk),
2075 os_version: Some(rucc_tuple::Version::major(12)),
2076 ..opts
2077 };
2078 let args = line(mac(), &opts, &one("a.o"), "a.out").expect("a line");
2079 assert_eq!(args[3..6], ["macos", "12", "12"]);
2080 }
2081
2082 #[test]
2083 fn a_mac_link_looks_for_a_mach_o_linker_and_nothing_else() {
2084 assert_eq!(order(mac(), &LinkOptions::default()), ["ld", "ld64.lld"]);
2085 }
2086
2087 #[test]
2088 fn a_static_mac_program_is_refused_and_a_relocatable_one_is_not() {
2089 let sdk = an_sdk("MacOSX.sdk", None);
2090 let opts = LinkOptions { sysroot: Some(sdk), is_static: true, ..LinkOptions::default() };
2091 let error = line(mac(), &opts, &one("a.o"), "a.out").expect_err("no static line");
2092 let Error::Cross { why } = &error else { panic!("{error:?}") };
2093 assert!(why.contains("-static"), "{why}");
2094 let args = relocatable_line(mac(), &LinkOptions::default(), &one("a.o"), "b.o")
2095 .expect("ld64 takes -r");
2096 assert_eq!(args, ["-r", "-arch", "arm64", "-o", "b.o", "a.o"]);
2097 }
2098
2099 #[test]
2100 fn the_line_is_printed_the_way_it_would_be_typed() {
2101 let linker = Linker { name: "ld".to_owned(), path: PathBuf::from("/usr/bin/ld") };
2102 let args = ["-o".to_owned(), "a b".to_owned()];
2103 assert_eq!(render(&linker, &args), "/usr/bin/ld -o \"a b\"");
2104 }
2105
2106 #[test]
2107 fn a_linker_that_is_not_there_is_said_by_name() {
2108 let opts = LinkOptions {
2109 use_ld: Some("a-linker-nobody-has".to_owned()),
2110 ..LinkOptions::default()
2111 };
2112 let error = find(linux(), &opts).expect_err("not on this machine");
2113 assert_eq!(error, Error::Named { name: "a-linker-nobody-has".to_owned() });
2114 }
2115 fn a_gcc_dir(name: &str) -> PathBuf {
2118 let dir = std::env::temp_dir().join(format!("rucc-link-{name}-{}", std::process::id()));
2119 fs::create_dir_all(&dir).expect("a temporary directory");
2120 fs::write(dir.join("libgcc.a"), b"not really an archive").expect("a file in it");
2121 dir
2122 }
2123
2124 #[test]
2125 fn the_c_library_supplies_the_block_routines_and_our_runtime_does_not_displace_them() {
2126 let gcc = a_gcc_dir("order");
2127 let ours = PathBuf::from("/somewhere/librucc_builtins.a");
2128 let args = runtime_items(&LinkOptions::default(), &[gcc], Some(&ours));
2129 let at_libc = args.iter().position(|a| a == "-lc").expect("libc");
2130 let at_ours = args.iter().position(|a| a.ends_with("librucc_builtins.a")).expect("ours");
2131 assert!(at_libc < at_ours, "{args:?}");
2134 }
2135
2136 #[test]
2137 fn a_static_link_puts_them_in_a_group_because_two_of_them_refer_to_each_other() {
2138 let gcc = a_gcc_dir("group");
2139 let opts = LinkOptions { is_static: true, ..LinkOptions::default() };
2140 let args = runtime_items(&opts, &[gcc], None);
2141 assert_eq!(args.first().map(String::as_str), Some("--start-group"), "{args:?}");
2142 assert_eq!(args.last().map(String::as_str), Some("--end-group"), "{args:?}");
2143 assert!(args.contains(&"-lgcc_eh".to_owned()), "{args:?}");
2146 }
2147
2148 #[test]
2149 fn a_dynamic_link_needs_no_group_and_asks_for_the_shared_half_only_if_something_wants_it() {
2150 let gcc = a_gcc_dir("dynamic");
2151 let args = runtime_items(&LinkOptions::default(), &[gcc], None);
2152 assert!(!args.contains(&"--start-group".to_owned()), "{args:?}");
2153 assert!(!args.contains(&"-lgcc_eh".to_owned()), "{args:?}");
2154 let at = args.iter().position(|a| a == "-lgcc_s").expect("the shared half");
2155 assert_eq!(args[at - 1], "--as-needed", "{args:?}");
2156 assert_eq!(args[at + 1], "--no-as-needed", "{args:?}");
2157 }
2158
2159 #[test]
2160 fn our_own_runtime_comes_before_the_machines_because_the_two_are_interchangeable() {
2161 let gcc = a_gcc_dir("ours");
2162 let ours = PathBuf::from("/somewhere/librucc_builtins.a");
2163 let args = runtime_items(&LinkOptions::default(), &[gcc], Some(&ours));
2164 let at_ours = args.iter().position(|a| a.ends_with("librucc_builtins.a")).expect("ours");
2165 let at_gcc = args.iter().position(|a| a == "-lgcc").expect("libgcc");
2166 assert!(at_ours < at_gcc, "{args:?}");
2167 }
2168
2169 #[test]
2170 fn no_builtins_lib_leaves_ours_off_and_keeps_the_machines() {
2171 let gcc = a_gcc_dir("theirs");
2172 let opts = LinkOptions { no_builtins_lib: true, ..LinkOptions::default() };
2173 let args = line(linux(), &opts, &one("a.o"), "a.out").expect("a line");
2174 assert!(!args.iter().any(|a| a.ends_with("librucc_builtins.a")), "{args:?}");
2175 assert!(runtime_items(&opts, &[gcc], None).contains(&"-lgcc".to_owned()));
2178 }
2179
2180 #[test]
2181 fn nodefaultlibs_leaves_the_whole_runtime_off_and_not_only_the_c_library() {
2182 let gcc = a_gcc_dir("none");
2183 let opts = LinkOptions { no_defaultlibs: true, ..LinkOptions::default() };
2184 assert!(runtime_items(&opts, &[gcc], None).is_empty());
2185 }
2186
2187 #[test]
2188 fn a_machine_with_no_gcc_on_it_gets_no_names_for_libraries_that_are_not_there() {
2189 let empty = std::env::temp_dir().join("rucc-link-empty-not-a-gcc");
2190 let args = runtime_items(&LinkOptions::default(), &[empty], None);
2191 assert_eq!(args, ["-lc"], "{args:?}");
2192 }
2193
2194 #[test]
2195 fn a_gcc_version_directory_is_read_as_a_version_and_not_as_a_word() {
2196 assert!(version_key(Path::new("/usr/lib/gcc/x/13")) > version_key(Path::new("/x/9")));
2197 assert!(version_key(Path::new("/x/10.2")) > version_key(Path::new("/x/10")));
2198 assert!(version_key(Path::new("/x/snapshot")) < version_key(Path::new("/x/1")));
2200 }
2201
2202 #[test]
2210 fn the_fast_math_startup_file_is_wanted_where_gccs_spec_wants_it() {
2211 let fast = LinkOptions { fast_math: true, ..LinkOptions::default() };
2212 assert!(!LinkOptions::default().wants_fastmath());
2213 assert!(fast.wants_fastmath());
2214 assert!(!LinkOptions { shared: true, ..fast.clone() }.wants_fastmath());
2215 assert!(!LinkOptions { daz_ftz: Some(false), ..fast.clone() }.wants_fastmath());
2216 let forced = LinkOptions { shared: true, daz_ftz: Some(true), ..LinkOptions::default() };
2217 assert!(forced.wants_fastmath());
2218 }
2219
2220 fn cached() -> LinkOptions {
2221 LinkOptions {
2222 cache: Some(PathBuf::from("/cache")),
2223 prefixes: vec![a_builtins_dir()],
2224 ..LinkOptions::default()
2225 }
2226 }
2227
2228 fn a_builtins_dir() -> PathBuf {
2234 let dir = std::env::temp_dir().join(format!("rucc-link-ours-{}", std::process::id()));
2235 fs::create_dir_all(&dir).expect("a temporary directory");
2236 fs::write(dir.join("librucc_builtins.a"), b"not really an archive").expect("a file in it");
2237 dir
2238 }
2239
2240 #[test]
2243 fn the_runtime_is_found_under_the_tuple_as_well_as_the_triple() {
2244 let dir = std::env::temp_dir().join(format!("rucc-link-tuple-{}", std::process::id()));
2245 let target: Triple = "aarch64-linux-musl".parse().expect("a triple");
2246 let under = dir.join(target.tuple().to_string());
2247 fs::create_dir_all(&under).expect("a temporary directory");
2248 fs::write(under.join("librucc_builtins.a"), b"not really an archive")
2249 .expect("a file in it");
2250 let found = builtins_archive(target, std::slice::from_ref(&dir));
2251 assert_eq!(found, Some(under.join("librucc_builtins.a")));
2252 let _ = fs::remove_dir_all(&dir);
2253 }
2254
2255 fn a_sysroot(target: Triple) -> Sysroot {
2257 Sysroot::in_cache(Path::new("/cache"), target.tuple())
2258 }
2259
2260 fn foreign() -> Triple {
2266 Triple::new(Arch::X86_64, Os::None, Env::None)
2267 }
2268
2269 #[test]
2270 fn a_cross_link_reads_the_targets_own_sysroot_and_nothing_of_this_machine() {
2271 let target = Triple::new(Arch::Aarch64, Os::Linux, Env::Musl);
2272 let sysroot = a_sysroot(target);
2273 let root = sysroot.root().display().to_string();
2276 let lib = sysroot.lib();
2277 let args = cross_line(target, &cached(), &one("a.o"), "a.out", &sysroot).expect("a line");
2278 assert!(args.contains(&format!("--sysroot={root}")), "{args:?}");
2279 assert!(args.contains(&format!("-L{}", lib.display())), "{args:?}");
2280 assert!(args.contains(&lib.join("libc.a").display().to_string()), "{args:?}");
2281 let at = args.iter().position(|a| a == "-dynamic-linker").expect("the loader");
2282 assert_eq!(args[at + 1], "/lib/ld-musl-aarch64.so.1", "{args:?}");
2283 for arg in &args {
2286 assert!(!arg.contains("/usr/lib"), "{arg} in {args:?}");
2287 assert!(!arg.contains("/lib64"), "{arg} in {args:?}");
2288 }
2289 }
2290
2291 #[test]
2292 fn a_freestanding_target_links_against_our_runtime_instead_of_being_refused() {
2293 let args = line(foreign(), &cached(), &one("a.o"), "a.out").expect("a line");
2294 assert!(args.iter().any(|a| a.ends_with("librucc_builtins.a")), "{args:?}");
2295 assert!(!args.iter().any(|a| a.ends_with("libc.a")), "{args:?}");
2298 assert!(!args.contains(&"-lc".to_owned()), "{args:?}");
2299 assert!(!args.iter().any(|a| a.ends_with("crt1.o")), "{args:?}");
2300 }
2301
2302 #[test]
2304 fn a_driver_with_no_cache_to_look_in_says_so_rather_than_guessing() {
2305 let error = line(foreign(), &LinkOptions::default(), &one("a.o"), "a.out")
2306 .expect_err("no line for it");
2307 assert!(matches!(error, Error::Target { .. }), "{error:?}");
2308 }
2309
2310 #[test]
2311 fn a_static_link_against_a_libc_that_is_a_stub_is_refused_rather_than_attempted() {
2312 let target = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2313 let opts = LinkOptions { is_static: true, ..cached() };
2314 let error = cross_line(target, &opts, &one("a.o"), "a.out", &a_sysroot(target))
2315 .expect_err("there is no libc.a in a stub sysroot");
2316 let Error::Cross { why } = &error else { panic!("{error:?}") };
2317 assert!(why.contains("stub"), "{why}");
2320 }
2321
2322 #[test]
2323 fn a_target_whose_linker_wants_a_different_line_is_refused_by_name() {
2324 for target in [
2325 Triple::new(Arch::Aarch64, Os::Darwin, Env::None),
2326 Triple::new(Arch::X86_64, Os::Windows, Env::Msvc),
2327 ] {
2328 let error = cross_line(target, &cached(), &one("a.o"), "a.out", &a_sysroot(target))
2329 .expect_err("no line for that format");
2330 let Error::Cross { why } = &error else { panic!("{error:?}") };
2331 assert!(why.contains(&target.tuple().to_canonical_string()), "{why}");
2332 }
2333 }
2334
2335 #[test]
2336 fn a_mingw_target_links_and_looks_for_a_linker_that_can_write_a_pe_image() {
2337 let target = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2338 let args = cross_line(target, &cached(), &one("a.o"), "a.exe", &a_sysroot(target))
2339 .expect("a line for mingw-w64");
2340 let at = |flag: &str| args.iter().position(|arg| arg == flag).expect(flag);
2341 assert_eq!(args[at("-m") + 1], "i386pep");
2342 assert_eq!(args[at("--subsystem") + 1], "console");
2343 assert!(args.iter().any(|arg| arg.ends_with("libmsvcrt.a")), "{args:?}");
2344 let names = cross_order(target);
2347 assert_eq!(names.first().map(String::as_str), Some("ld.lld"));
2348 assert!(names.contains(&"x86_64-w64-mingw32-ld".to_owned()), "{names:?}");
2349 }
2350
2351 #[test]
2352 fn our_runtime_comes_from_beside_the_compiler_rather_than_from_inside_the_sysroot() {
2353 let target = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2358 let sysroot = a_sysroot(target);
2359 let opts = cached();
2360 let args = cross_line(target, &opts, &one("a.o"), "a.exe", &sysroot).expect("a line");
2361 let ours: Vec<&String> =
2362 args.iter().filter(|arg| arg.ends_with("librucc_builtins.a")).collect();
2363 assert_eq!(ours.len(), 1, "{args:?}");
2364 assert_eq!(ours[0], &opts.prefixes[0].join("librucc_builtins.a").display().to_string());
2365 assert!(!ours[0].starts_with(&sysroot.lib().display().to_string()), "{args:?}");
2366 assert_eq!(args.last(), Some(ours[0]), "{args:?}");
2368 }
2369
2370 #[test]
2371 fn a_cross_link_with_no_runtime_to_find_says_which_command_writes_one() {
2372 let target = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2376 let opts = LinkOptions { prefixes: Vec::new(), ..cached() };
2377 let error = cross_line(target, &opts, &one("a.o"), "a.exe", &a_sysroot(target))
2378 .expect_err("there is no runtime for it to find");
2379 let Error::Cross { why } = &error else { panic!("{error:?}") };
2380 assert!(why.contains("cargo xtask builtins"), "{why}");
2381 assert!(why.contains("-fno-builtins-lib"), "{why}");
2382
2383 let without = LinkOptions { no_builtins_lib: true, ..opts };
2385 let args = cross_line(target, &without, &one("a.o"), "a.exe", &a_sysroot(target))
2386 .expect("a line without ours on it");
2387 assert!(!args.iter().any(|arg| arg.ends_with("librucc_builtins.a")), "{args:?}");
2388 }
2389
2390 #[test]
2391 fn the_version_an_lld_prints_is_read_and_nothing_elses_is() {
2392 assert_eq!(lld_major("LLD 18.1.8 (compatible with GNU linkers)\n"), Some(18));
2395 assert_eq!(lld_major("Ubuntu LLD 18.1.3 (compatible with GNU linkers)\n"), Some(18));
2396 assert_eq!(lld_major("LLD 20.1.2 (compatible with GNU linkers)\n"), Some(20));
2397
2398 assert_eq!(lld_major("GNU ld (GNU Binutils for Ubuntu) 2.42\n"), None);
2401 assert_eq!(lld_major("mold 2.4.1 (compatible with GNU ld)\n"), None);
2402 assert_eq!(lld_major(""), None);
2403 }
2404
2405 #[cfg(unix)]
2409 fn a_linker_that_says(tag: &str, text: &str) -> Linker {
2410 use std::os::unix::fs::PermissionsExt as _;
2411 let dir = std::env::temp_dir().join(format!("rucc-link-ld-{}", std::process::id()));
2412 fs::create_dir_all(&dir).expect("a temporary directory");
2413 let path = dir.join(format!("ld.lld-{tag}"));
2414 fs::write(&path, format!("#!/bin/sh\necho '{text}'\n")).expect("a script");
2415 fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("an executable one");
2416 Linker { name: "ld.lld".to_owned(), path }
2417 }
2418
2419 #[test]
2420 #[cfg(unix)]
2421 fn an_lld_too_old_to_read_exportas_is_refused_for_windows_gnu_and_nowhere_else() {
2422 let windows = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2425 let old = a_linker_that_says("18", "LLD 18.1.8 (compatible with GNU linkers)");
2426 let error = suitable(windows, &old).expect_err("18 cannot link this");
2427 let Error::TooOld { name, found, target } = &error else { panic!("{error:?}") };
2428 assert_eq!((name.as_str(), *found, target.as_str()), ("ld.lld", 18, "x86_64-windows-gnu"));
2429 assert!(error.to_string().contains("IMPORT_NAME_EXPORTAS"), "{error}");
2430
2431 let linux = Triple::new(Arch::X86_64, Os::Linux, Env::Musl);
2434 assert_eq!(suitable(linux, &old), Ok(()));
2435
2436 let new = a_linker_that_says("19", "LLD 19.1.0 (compatible with GNU linkers)");
2438 assert_eq!(suitable(windows, &new), Ok(()));
2439 }
2440
2441 #[test]
2442 #[cfg(unix)]
2443 fn an_old_lld_first_in_line_is_passed_over_for_a_newer_one_behind_it() {
2444 use std::os::unix::fs::PermissionsExt as _;
2448 let root = std::env::temp_dir().join(format!("rucc-link-two-lld-{}", std::process::id()));
2449 let mut prefixes = Vec::new();
2450 for (dir, version) in [("old", "18.1.3"), ("new", "19.1.7")] {
2451 let dir = root.join(dir);
2452 fs::create_dir_all(&dir).expect("a temporary directory");
2453 let path = dir.join("ld.rucc-test-lld");
2454 fs::write(&path, format!("#!/bin/sh\necho 'Ubuntu LLD {version}'\n"))
2455 .expect("a script");
2456 fs::set_permissions(&path, fs::Permissions::from_mode(0o755)).expect("executable");
2457 prefixes.push(dir);
2458 }
2459 let windows = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2460 let opts = LinkOptions {
2461 use_ld: Some("rucc-test-lld".to_owned()),
2462 prefixes,
2463 ..LinkOptions::default()
2464 };
2465 let found = find(windows, &opts).expect("the newer one");
2466 assert_eq!(found.path, root.join("new").join("ld.rucc-test-lld"));
2467
2468 let opts = LinkOptions { prefixes: vec![root.join("old")], ..opts };
2470 let error = find(windows, &opts).expect_err("only 18 is here");
2471 assert!(matches!(error, Error::TooOld { found: 18, .. }), "{error:?}");
2472 let _ = fs::remove_dir_all(&root);
2473 }
2474
2475 #[test]
2476 fn a_long_line_goes_in_a_response_file_that_reads_back_as_it_was() {
2477 let args: Vec<String> =
2478 ["-o", r"C:\Users\a b\out.exe", "-m", "i386pep", r#"say "hi""#, "", "plain.o"]
2479 .map(str::to_owned)
2480 .to_vec();
2481 let (front, rest) = split_for_file(&args);
2482 assert_eq!(front, ["-m", "i386pep"]);
2483 assert_eq!(
2484 crate::response_words(&response_text(&rest, false)),
2485 [&args[..2], &args[4..]].concat()
2486 );
2487 assert_eq!(
2489 response_text(&rest, true),
2490 "\"-o\"\n\"C:\\Users\\a b\\out.exe\"\n\"say \\\"hi\\\"\"\n\"\"\n\"plain.o\"\n"
2491 );
2492 assert_eq!(response_text(&[r"C:\dir\".to_owned()], true), "\"C:\\dir\\\\\"\n");
2493 assert!(!too_long(&args, 1000));
2494 assert!(too_long(&vec!["x".repeat(100); 400], WINDOWS_LINE));
2495 }
2496
2497 #[test]
2498 fn a_program_name_is_tried_with_each_pathext_extension_it_does_not_already_have() {
2499 let exts = vec![".com".to_owned(), ".exe".to_owned()];
2500 let dir = Path::new("bin");
2501 assert_eq!(
2502 spellings(&dir.join("ld.lld"), &exts),
2503 [dir.join("ld.lld.com"), dir.join("ld.lld.exe")]
2504 );
2505 assert_eq!(spellings(&dir.join("lld-link.EXE"), &exts), [dir.join("lld-link.EXE")]);
2506 assert_eq!(spellings(&dir.join("ld.lld"), &[]), [dir.join("ld.lld")]);
2507 }
2508
2509 #[test]
2510 #[cfg(unix)]
2511 fn an_lld_off_path_is_found_under_its_own_name() {
2512 use std::os::unix::fs::PermissionsExt as _;
2513 let dir = std::env::temp_dir().join(format!("rucc-link-off-path-{}", std::process::id()));
2514 fs::create_dir_all(&dir).expect("a temporary directory");
2515 let lld = dir.join("ld.lld");
2516 fs::write(&lld, "#!/bin/sh\n").expect("a file");
2517 fs::set_permissions(&lld, fs::Permissions::from_mode(0o755)).expect("permissions");
2518 let found =
2519 linker_candidates("ld.lld", &LinkOptions::default(), std::slice::from_ref(&dir));
2520 let _ = fs::remove_dir_all(&dir);
2521 assert!(found.contains(&lld), "{found:?}");
2522 }
2523
2524 #[test]
2525 fn lld_is_looked_for_where_package_managers_put_it_newest_version_first() {
2526 let root = std::env::temp_dir().join(format!("rucc-link-lld-dirs-{}", std::process::id()));
2527 for dir in ["usr/lib/llvm-18/bin", "usr/lib/llvm-19/bin", "usr/lib/llvm-9/bin", "usr/lib/x"]
2528 {
2529 fs::create_dir_all(root.join(dir)).expect("a temporary directory");
2530 }
2531 let dirs = lld_dirs(&root, Some(PathBuf::from("C:/Program Files")));
2532 let under_lib: Vec<_> =
2533 dirs.iter().filter(|dir| dir.starts_with(root.join("usr/lib"))).collect();
2534 assert_eq!(
2535 under_lib,
2536 [
2537 &root.join("usr/lib/llvm-19/bin"),
2538 &root.join("usr/lib/llvm-18/bin"),
2539 &root.join("usr/lib/llvm-9/bin")
2540 ]
2541 );
2542 assert!(dirs.contains(&root.join("opt/homebrew/opt/lld/bin")), "{dirs:?}");
2543 assert_eq!(dirs.last(), Some(&PathBuf::from("C:/Program Files").join("LLVM").join("bin")));
2544 let _ = fs::remove_dir_all(&root);
2545 }
2546
2547 #[test]
2548 fn no_linker_says_where_to_get_lld_only_when_lld_was_looked_for() {
2549 let cross = Error::NoLinker { tried: vec!["ld.lld".to_owned(), "lld".to_owned()] };
2550 assert!(cross.to_string().contains("lld 19 or newer"), "{cross}");
2551 let native = Error::NoLinker { tried: vec!["ld".to_owned()] };
2552 assert_eq!(native.to_string(), "no linker was found; tried ld");
2553 }
2554
2555 #[test]
2556 #[cfg(unix)]
2557 fn a_linker_that_will_not_say_what_it_is_is_left_alone() {
2558 let windows = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2562 let quiet = a_linker_that_says("gnu", "GNU ld (GNU Binutils for Ubuntu) 2.42");
2563 assert_eq!(suitable(windows, &quiet), Ok(()));
2564
2565 let missing = Linker { name: "ld.lld".to_owned(), path: PathBuf::from("/no/such/linker") };
2566 assert_eq!(suitable(windows, &missing), Ok(()));
2567 }
2568
2569 #[test]
2570 fn profiling_a_cross_link_is_refused_because_the_startup_file_is_compiled_code() {
2571 let target = Triple::new(Arch::X86_64, Os::Linux, Env::Musl);
2572 let opts = LinkOptions { profile: true, ..cached() };
2573 let error = cross_line(target, &opts, &one("a.o"), "a.out", &a_sysroot(target))
2574 .expect_err("there is no gcrt1.o in a generated sysroot");
2575 let Error::Cross { why } = &error else { panic!("{error:?}") };
2576 assert!(why.contains("gcrt1.o"), "{why}");
2577 }
2578
2579 #[test]
2580 fn a_distributions_cross_tree_is_used_when_there_is_no_sysroot_of_ours() {
2581 let usr = std::env::temp_dir().join(format!("rucc-link-usr-{}", std::process::id()));
2582 let root = usr.join("aarch64-linux-gnu");
2583 for dir in ["include", "lib"] {
2584 fs::create_dir_all(root.join(dir)).expect("a scratch tree");
2585 }
2586 for version in ["9", "13"] {
2587 fs::create_dir_all(usr.join("lib/gcc-cross/aarch64-linux-gnu").join(version))
2588 .expect("a scratch gcc");
2589 }
2590 let host = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2591 let arm = Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu);
2592 let opts = LinkOptions { usr: Some(usr.clone()), ..cached() };
2593 let distro = distro_for(arm, &opts, Some(host)).expect("the packages are there");
2594 assert_eq!(distro.include(), root.join("include"));
2595 assert_eq!(distro.lib(), root.join("lib"));
2596 assert_eq!(
2597 distro.gcc,
2598 [13, 9].map(|v| usr.join("lib/gcc-cross/aarch64-linux-gnu").join(v.to_string()))
2599 );
2600 assert!(cross_for(arm, &opts, Some(host)).is_none());
2602 assert!(distro_for(host, &opts, Some(host)).is_none());
2604 let riscv = Triple::new(Arch::Riscv64, Os::Linux, Env::Gnu);
2605 assert!(distro_for(riscv, &opts, Some(host)).is_none());
2606 let named = LinkOptions { sysroot: Some(PathBuf::from("/opt/root")), ..opts.clone() };
2607 assert!(distro_for(arm, &named, Some(host)).is_none());
2608 let pinned = LinkOptions {
2609 pinned: Some("aarch64-linux-gnu.2.28".parse::<TargetTuple>().expect("a release")),
2610 ..opts.clone()
2611 };
2612 assert!(distro_for(arm, &pinned, Some(host)).is_none());
2613 let cache = usr.join("cache");
2615 fs::create_dir_all(Sysroot::in_cache(&cache, arm.tuple()).lib()).expect("a sysroot");
2616 let fetched = LinkOptions { cache: Some(cache), ..opts };
2617 assert!(distro_for(arm, &fetched, Some(host)).is_none());
2618 let _ = fs::remove_dir_all(&usr);
2619 }
2620
2621 #[test]
2622 fn the_host_takes_the_host_line_and_a_tree_the_user_named_takes_it_too() {
2623 let host = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2624 let other = Triple::new(Arch::Riscv64, Os::Linux, Env::Musl);
2625 assert!(cross_for(host, &cached(), Some(host)).is_none());
2626 assert!(cross_for(other, &cached(), Some(host)).is_some());
2627 let named = LinkOptions { sysroot: Some(PathBuf::from("/opt/root")), ..cached() };
2630 assert!(cross_for(other, &named, Some(host)).is_none());
2631 assert!(cross_for(other, &cached(), None).is_some());
2633 }
2634
2635 #[test]
2636 fn a_pinned_release_on_this_machines_own_target_is_a_cross_compile() {
2637 let host = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2642 let pinned = LinkOptions {
2643 pinned: Some(
2644 "x86_64-linux-gnu.2.28".parse::<TargetTuple>().expect("a spelling with a release"),
2645 ),
2646 ..cached()
2647 };
2648 let at = cross_for(host, &pinned, Some(host)).expect("a pin is a cross compile");
2649 assert!(at.root().ends_with("x86_64-linux-gnu.2.28"), "{:?}", at.root());
2652 let bare = LinkOptions { pinned: None, ..cached() };
2655 assert!(cross_for(host, &bare, Some(host)).is_none());
2656 }
2657
2658 #[test]
2659 fn a_glibc_cross_link_writes_its_stubs_beside_the_sysroot_once() {
2660 let cache = std::env::temp_dir().join(format!("rucc-link-stubs-{}", std::process::id()));
2661 let _ = fs::remove_dir_all(&cache);
2662 let target = Triple::new(Arch::X86_64, Os::Linux, Env::Gnu);
2663 let pinned = LinkOptions {
2664 cache: Some(cache.clone()),
2665 pinned: Some("x86_64-linux-gnu.2.28".parse().expect("a spelling with a release")),
2666 ..LinkOptions::default()
2667 };
2668 write_stubs(target, &pinned).expect("x86_64 glibc has a description");
2669 let dir = cache.join("stubs").join("x86_64-linux-gnu.2.28");
2670 let libc = dir.join("libc.so");
2671 let bytes = fs::read(&libc).expect("libc.so was written");
2672 assert!(bytes.starts_with(b"\x7fELF"));
2673 assert!(dir.join("libm.so").is_file());
2674 assert!(!dir.join("libpthread.so").exists());
2676 let before = fs::metadata(&libc).and_then(|m| m.modified()).expect("a time");
2679 write_stubs(target, &pinned).expect("again");
2680 let after = fs::metadata(&libc).and_then(|m| m.modified()).expect("a time");
2681 assert_eq!(before, after);
2682 let musl = LinkOptions {
2684 cache: Some(cache.clone()),
2685 pinned: Some("x86_64-linux-musl".parse().expect("musl")),
2686 ..LinkOptions::default()
2687 };
2688 write_stubs(Triple::new(Arch::X86_64, Os::Linux, Env::Musl), &musl).expect("nothing");
2689 assert!(!cache.join("stubs").join("x86_64-linux-musl").exists());
2690 let _ = fs::remove_dir_all(&cache);
2691 }
2692
2693 #[test]
2694 fn what_a_cross_link_searches_is_the_sysroot_and_not_this_machine() {
2695 let dirs = search_dirs(&cached(), foreign());
2696 assert_eq!(dirs.len(), 1, "{dirs:?}");
2699 assert!(dirs[0].starts_with("/cache"), "{dirs:?}");
2700 assert!(dirs[0].ends_with("lib"), "{dirs:?}");
2701 let mine = LinkOptions { search: vec![PathBuf::from("/opt/mine")], ..cached() };
2703 assert_eq!(search_dirs(&mine, foreign())[0], PathBuf::from("/opt/mine"));
2704 }
2705
2706 #[test]
2707 fn gnu_ld_is_not_looked_for_against_the_fetched_mingw_sysroot() {
2708 let windows = Triple::new(Arch::X86_64, Os::Windows, Env::Gnu);
2709 assert_eq!(order(windows, &cached()), ["ld.lld", "lld"]);
2710 }
2711
2712 #[test]
2713 fn the_linker_looked_for_on_a_cross_link_is_one_that_can_cross() {
2714 let names = cross_order(Triple::new(Arch::Aarch64, Os::Linux, Env::Gnu));
2715 assert_eq!(names.first().map(String::as_str), Some("ld.lld"));
2716 assert!(names.contains(&"aarch64-linux-gnu-ld".to_owned()), "{names:?}");
2717 assert!(!names.iter().any(|name| name.contains("mold")), "{names:?}");
2720 assert!(!names.contains(&"ld".to_owned()), "{names:?}");
2721 assert_eq!(order(foreign(), &cached()), ["ld.lld", "lld"]);
2723 }
2724
2725 #[test]
2726 fn the_four_flags_become_the_five_modes_they_describe() {
2727 let plain = LinkOptions::default();
2728 assert_eq!(mode(&plain), LinkMode::Dynamic);
2729 assert_eq!(
2730 mode(&LinkOptions { pie: Some(false), ..plain.clone() }),
2731 LinkMode::DynamicNoPie
2732 );
2733 assert_eq!(mode(&LinkOptions { is_static: true, ..plain.clone() }), LinkMode::Static);
2734 let both = LinkOptions { is_static: true, pie: Some(true), ..plain.clone() };
2735 assert_eq!(mode(&both), LinkMode::StaticPie);
2736 assert_eq!(mode(&LinkOptions { shared: true, ..plain }), LinkMode::Shared);
2737 }
2738
2739 #[test]
2740 fn a_sysroot_that_has_not_been_built_is_named_before_anything_is_compiled() {
2741 let opts = LinkOptions {
2742 cache: Some(std::env::temp_dir().join("rucc-a-cache-nobody-filled")),
2743 ..LinkOptions::default()
2744 };
2745 let error = preflight(foreign(), &opts).expect_err("nothing has built one");
2746 let Error::Sysroot { dir, pinned, .. } = &error else { panic!("{error:?}") };
2747 assert!(dir.ends_with("x86_64-none"), "{dir}");
2748 assert!(!pinned, "nothing should be pinned for a bare metal target");
2751 let said = error.to_string();
2752 assert!(said.contains("pins none for it to fetch"), "{said}");
2753 }
2754
2755 #[test]
2759 fn a_sysroot_that_could_be_fetched_is_told_what_to_run() {
2760 let said = Error::Sysroot {
2761 target: "x86_64-linux-musl".to_owned(),
2762 dir: "/somewhere/sysroots/x86_64-linux-musl".to_owned(),
2763 pinned: true,
2764 }
2765 .to_string();
2766 assert!(said.contains("`rucc --fetch x86_64-linux-musl`"), "{said}");
2767 assert!(said.contains("--sysroot=<dir>"), "{said}");
2770 }
2771
2772 #[test]
2773 fn a_link_against_this_machine_has_nothing_to_check_before_it_starts() {
2774 assert!(preflight(linux(), &LinkOptions::default()).is_ok());
2777 }
2778
2779 #[test]
2780 fn a_runtime_directory_that_is_not_on_this_machine_is_not_offered() {
2781 let dirs = runtime_dirs(linux(), Some(Path::new("/definitely/not/a/sysroot")));
2782 assert!(dirs.is_empty(), "{dirs:?}");
2783 }
2784}