1use std::ffi::OsString;
6use std::path::{Path, PathBuf};
7
8use super::{BuildSettings, OptLevel, ProfileSettings, Subsystem, TARGET_SWITCH};
9use crate::Version;
10use crate::compiler::{CompilerKind, Family};
11
12#[derive(Clone, Copy, Debug)]
14pub struct LinkInput<'a> {
15 pub kind: CompilerKind,
17 pub version: Version,
20 pub build: &'a BuildSettings,
22 pub profile: &'a ProfileSettings,
24 pub output: Linked<'a>,
26 pub cxx: bool,
29}
30
31#[derive(Clone, Copy, Debug)]
34pub enum Linked<'a> {
35 Executable {
37 subsystem: Subsystem,
39 of_shared: bool,
43 },
44 Shared {
49 import: &'a Path,
51 pdb: &'a Path,
53 },
54}
55
56pub fn library_files(kind: CompilerKind, lib: &str) -> Vec<String> {
66 match kind {
67 CompilerKind::Msvc | CompilerKind::ClangCl | CompilerKind::Clang => {
68 vec![format!("{lib}.lib")]
69 }
70 CompilerKind::Gcc => vec![
71 format!("lib{lib}.dll.a"),
72 format!("{lib}.dll.a"),
73 format!("lib{lib}.a"),
74 format!("{lib}.lib"),
75 format!("lib{lib}.lib"),
76 format!("lib{lib}.dll"),
77 format!("{lib}.dll"),
78 ],
79 }
80}
81
82fn gcc_runtime_args(cxx: bool, version: Version) -> Vec<&'static str> {
90 let mut args = vec!["-static-libgcc"];
91 if cxx {
92 args.push("-static-libstdc++");
93 }
94 args.push("-Wl,-Bstatic");
95 if cxx {
96 if version.major >= 14 {
97 args.push("-lstdc++exp");
98 }
99 args.push("-lstdc++");
100 }
101 args.extend(["-lwinpthread", "-Wl,-Bdynamic"]);
102 args
103}
104
105pub fn link_args(input: &LinkInput<'_>, objects: &[PathBuf], exe: &Path) -> Vec<OsString> {
111 let build = input.build;
112 let profile = input.profile;
113 let lto_level = match profile.opt_level {
115 OptLevel::O0 => "0",
116 OptLevel::O1 => "1",
117 OptLevel::O2 | OptLevel::Size => "2",
118 OptLevel::O3 => "3",
119 };
120 let mut args: Vec<OsString> = Vec::new();
121 let push = |args: &mut Vec<OsString>, flags: &[&str]| {
122 args.extend(flags.iter().map(OsString::from));
123 };
124
125 let shared = match input.output {
126 Linked::Executable { .. } => None,
127 Linked::Shared { import, pdb } => Some((import, pdb)),
128 };
129 match input.kind {
130 CompilerKind::Msvc | CompilerKind::ClangCl if shared.is_some() => {
131 push(&mut args, &["/LD"]);
132 }
133 CompilerKind::Clang | CompilerKind::Gcc if shared.is_some() => {
134 push(&mut args, &["-shared"]);
135 }
136 CompilerKind::Msvc | CompilerKind::ClangCl | CompilerKind::Clang | CompilerKind::Gcc => {}
137 }
138 match input.kind {
139 CompilerKind::Msvc => push(&mut args, &["/nologo"]),
140 CompilerKind::ClangCl => {
141 push(&mut args, &["/nologo", "-fuse-ld=lld"]);
142 if profile.lto {
143 push(&mut args, &["-flto"]);
144 }
145 }
146 CompilerKind::Clang => {
147 push(&mut args, &[TARGET_SWITCH, "-fuse-ld=lld"]);
150 if profile.debug_info {
151 push(&mut args, &["-g"]);
152 }
153 if profile.lto {
154 push(&mut args, &["-flto"]);
155 }
156 }
157 CompilerKind::Gcc => {
158 if profile.debug_info {
159 push(&mut args, &["-g"]);
160 }
161 if profile.lto {
165 push(&mut args, &["-flto=auto"]);
166 }
167 }
168 }
169
170 args.extend(objects.iter().map(OsString::from));
171
172 match input.kind {
173 CompilerKind::Clang | CompilerKind::Gcc => {
176 args.extend(["-o".into(), exe.into()]);
177 for lib in &build.links {
178 args.push(format!("-l{lib}").into());
179 }
180 for dir in &build.lib_dirs {
181 let mut arg = OsString::from("-L");
182 arg.push(dir);
183 args.push(arg);
184 }
185 let gcc = input.kind == CompilerKind::Gcc;
186 match (input.output, gcc) {
187 (
188 Linked::Executable {
189 subsystem,
190 of_shared,
191 },
192 gcc,
193 ) => {
194 push(
195 &mut args,
196 match (subsystem, gcc) {
197 (Subsystem::Console, false) => &["-Wl,/subsystem:console"][..],
198 (Subsystem::Windows, false) => {
199 &["-Wl,/subsystem:windows", "-Wl,/entry:mainCRTStartup"]
200 }
201 (Subsystem::Console, true) => &["-mconsole"],
203 (Subsystem::Windows, true) => &["-mwindows"],
204 },
205 );
206 if of_shared && !gcc {
209 push(&mut args, &["-Wl,/noimplib"]);
210 }
211 }
212 (Linked::Shared { import, .. }, true) => {
213 args.extend(["-Xlinker".into(), "--out-implib".into()]);
214 args.extend(["-Xlinker".into(), import.into()]);
215 }
216 (Linked::Shared { import, pdb }, false) => {
217 let mut arg = OsString::from("/implib:");
218 arg.push(import);
219 args.extend(["-Xlinker".into(), arg]);
220 if profile.debug_info {
221 let mut arg = OsString::from("/pdb:");
222 arg.push(pdb);
223 args.extend(["-Xlinker".into(), arg]);
224 }
225 }
226 }
227 if gcc {
228 push(&mut args, &gcc_runtime_args(input.cxx, input.version));
229 } else if profile.lto {
230 args.push(format!("-Wl,/opt:lldlto={lto_level}").into());
231 }
232 for flag in &build.link_flags {
234 args.extend(["-Xlinker".into(), flag.into()]);
235 }
236 return args;
237 }
238 CompilerKind::Msvc | CompilerKind::ClangCl => {}
239 }
240
241 let mut out = OsString::from("/Fe:");
242 out.push(exe);
243 args.push(out);
244 args.push("/link".into());
246 for lib in &build.links {
247 args.push(library_files(input.kind, lib).remove(0).into());
249 }
250 for dir in &build.lib_dirs {
251 let mut arg = OsString::from("/LIBPATH:");
252 arg.push(dir);
253 args.push(arg);
254 }
255 match input.output {
256 Linked::Executable {
257 subsystem,
258 of_shared,
259 } => {
260 push(
263 &mut args,
264 match subsystem {
265 Subsystem::Console => &["/SUBSYSTEM:CONSOLE"][..],
266 Subsystem::Windows => &["/SUBSYSTEM:WINDOWS", "/ENTRY:mainCRTStartup"],
267 },
268 );
269 if of_shared {
275 push(
276 &mut args,
277 match input.kind.family() {
278 Family::Msvc => &["/NOIMPLIB", "/NOEXP"][..],
279 Family::Llvm | Family::Gnu => &["/NOIMPLIB"],
280 },
281 );
282 }
283 }
284 Linked::Shared { import, pdb } => {
285 let mut arg = OsString::from("/IMPLIB:");
286 arg.push(import);
287 args.push(arg);
288 if profile.debug_info {
289 let mut arg = OsString::from("/PDB:");
290 arg.push(pdb);
291 args.push(arg);
292 }
293 }
294 }
295 if profile.debug_info {
296 push(&mut args, &["/DEBUG"]);
297 match input.kind.family() {
298 Family::Msvc => push(&mut args, &["/INCREMENTAL:NO"]),
300 Family::Llvm | Family::Gnu => {}
301 }
302 }
303 if profile.lto {
304 match input.kind.family() {
305 Family::Msvc => push(&mut args, &["/LTCG"]),
306 Family::Llvm | Family::Gnu => args.push(format!("/opt:lldlto={lto_level}").into()),
307 }
308 }
309
310 args.extend(build.link_flags.iter().map(OsString::from));
311 args
312}
313
314#[cfg(test)]
315mod tests {
316 use super::*;
317
318 #[test]
325 fn a_library_is_the_files_its_linker_tries() {
326 for kind in CompilerKind::ALL {
327 let want: Vec<&str> = match kind {
328 CompilerKind::Msvc | CompilerKind::ClangCl | CompilerKind::Clang => {
329 vec!["foo.lib"]
330 }
331 CompilerKind::Gcc => vec![
332 "libfoo.dll.a",
333 "foo.dll.a",
334 "libfoo.a",
335 "foo.lib",
336 "libfoo.lib",
337 "libfoo.dll",
338 "foo.dll",
339 ],
340 };
341 assert_eq!(library_files(kind, "foo"), want, "{kind:?}");
342 }
343 }
344 use crate::flags::Runtime;
345
346 fn build() -> BuildSettings {
347 BuildSettings {
348 warnings: crate::flags::Warnings::Default,
349 warnings_as_errors: false,
350 defines: vec![],
351 include_dirs: vec![],
352 links: vec![],
353 lib_dirs: vec![],
354 link_flags: vec![],
355 flags: vec![],
356 runtime: Runtime::Dynamic,
357 exceptions: true,
358 rtti: true,
359 }
360 }
361
362 fn profile() -> ProfileSettings {
363 ProfileSettings {
364 opt_level: OptLevel::O0,
365 debug_info: false,
366 debug_assertions: true,
367 lto: false,
368 }
369 }
370
371 fn args(
372 kind: CompilerKind,
373 build: &BuildSettings,
374 profile: &ProfileSettings,
375 subsystem: Subsystem,
376 ) -> Vec<String> {
377 args_for(kind, build, profile, subsystem, true)
378 }
379
380 fn args_for(
381 kind: CompilerKind,
382 build: &BuildSettings,
383 profile: &ProfileSettings,
384 subsystem: Subsystem,
385 cxx: bool,
386 ) -> Vec<String> {
387 args_linking(
388 kind,
389 build,
390 profile,
391 Linked::Executable {
392 subsystem,
393 of_shared: false,
394 },
395 cxx,
396 )
397 }
398
399 fn args_linking(
400 kind: CompilerKind,
401 build: &BuildSettings,
402 profile: &ProfileSettings,
403 output: Linked<'_>,
404 cxx: bool,
405 ) -> Vec<String> {
406 let input = LinkInput {
409 kind,
410 version: Version {
411 major: 13,
412 minor: 2,
413 patch: 0,
414 },
415 build,
416 profile,
417 output,
418 cxx,
419 };
420 link_args(
421 &input,
422 &[PathBuf::from("a.obj"), PathBuf::from("b.obj")],
423 Path::new("app.exe"),
424 )
425 .into_iter()
426 .map(|a| a.into_string().unwrap())
427 .collect()
428 }
429
430 #[test]
434 fn the_defaults_give_each_drivers_link_line() {
435 let (b, p) = (build(), profile());
436 assert_eq!(
437 args(CompilerKind::Msvc, &b, &p, Subsystem::Console),
438 [
439 "/nologo",
440 "a.obj",
441 "b.obj",
442 "/Fe:app.exe",
443 "/link",
444 "/SUBSYSTEM:CONSOLE",
445 ]
446 );
447 assert_eq!(
448 args(CompilerKind::ClangCl, &b, &p, Subsystem::Console),
449 [
450 "/nologo",
451 "-fuse-ld=lld",
452 "a.obj",
453 "b.obj",
454 "/Fe:app.exe",
455 "/link",
456 "/SUBSYSTEM:CONSOLE",
457 ]
458 );
459 let static_runtime = BuildSettings {
460 runtime: Runtime::Static,
461 ..build()
462 };
463 for b in [&b, &static_runtime] {
464 assert_eq!(
465 args(CompilerKind::Clang, b, &p, Subsystem::Console),
466 [
467 "--target=x86_64-pc-windows-msvc",
468 "-fuse-ld=lld",
469 "a.obj",
470 "b.obj",
471 "-o",
472 "app.exe",
473 "-Wl,/subsystem:console",
474 ]
475 );
476 }
477 for b in [&b, &static_runtime] {
480 assert_eq!(
481 args_for(CompilerKind::Gcc, b, &p, Subsystem::Console, true),
482 [
483 "a.obj",
484 "b.obj",
485 "-o",
486 "app.exe",
487 "-mconsole",
488 "-static-libgcc",
489 "-static-libstdc++",
490 "-Wl,-Bstatic",
491 "-lstdc++",
492 "-lwinpthread",
493 "-Wl,-Bdynamic"
494 ]
495 );
496 assert_eq!(
497 args_for(CompilerKind::Gcc, b, &p, Subsystem::Console, false),
498 [
499 "a.obj",
500 "b.obj",
501 "-o",
502 "app.exe",
503 "-mconsole",
504 "-static-libgcc",
505 "-Wl,-Bstatic",
506 "-lwinpthread",
507 "-Wl,-Bdynamic"
508 ]
509 );
510 }
511 }
512
513 #[test]
521 fn a_dll_links_with_its_import_library() {
522 let b = build();
523 let debug = ProfileSettings {
524 debug_info: true,
525 ..profile()
526 };
527 let shared = Linked::Shared {
528 import: Path::new("lib/m.lib"),
529 pdb: Path::new("lib/m.pdb"),
530 };
531 let cases: [(CompilerKind, &[&str]); 4] = [
532 (
533 CompilerKind::Msvc,
534 &[
535 "/LD",
536 "/nologo",
537 "a.obj",
538 "b.obj",
539 "/Fe:app.exe",
540 "/link",
541 "/IMPLIB:lib/m.lib",
542 "/PDB:lib/m.pdb",
543 "/DEBUG",
544 "/INCREMENTAL:NO",
545 ],
546 ),
547 (
548 CompilerKind::ClangCl,
549 &[
550 "/LD",
551 "/nologo",
552 "-fuse-ld=lld",
553 "a.obj",
554 "b.obj",
555 "/Fe:app.exe",
556 "/link",
557 "/IMPLIB:lib/m.lib",
558 "/PDB:lib/m.pdb",
559 "/DEBUG",
560 ],
561 ),
562 (
563 CompilerKind::Clang,
564 &[
565 "-shared",
566 TARGET_SWITCH,
567 "-fuse-ld=lld",
568 "-g",
569 "a.obj",
570 "b.obj",
571 "-o",
572 "app.exe",
573 "-Xlinker",
574 "/implib:lib/m.lib",
575 "-Xlinker",
576 "/pdb:lib/m.pdb",
577 ],
578 ),
579 (
580 CompilerKind::Gcc,
581 &[
582 "-shared",
583 "-g",
584 "a.obj",
585 "b.obj",
586 "-o",
587 "app.exe",
588 "-Xlinker",
589 "--out-implib",
590 "-Xlinker",
591 "lib/m.lib",
592 "-static-libgcc",
593 "-Wl,-Bstatic",
594 "-lwinpthread",
595 "-Wl,-Bdynamic",
596 ],
597 ),
598 ];
599 for (kind, want) in cases {
600 assert_eq!(
601 args_linking(kind, &b, &debug, shared, false),
602 want,
603 "{kind:?}"
604 );
605 }
606 for kind in CompilerKind::ALL {
608 let plain = args_linking(kind, &b, &profile(), shared, false);
609 assert!(
610 !plain
611 .iter()
612 .any(|a| a.to_ascii_lowercase().contains("/pdb")),
613 "{kind:?}: {plain:?}"
614 );
615 }
616 }
617
618 #[test]
625 fn only_a_shared_packages_executable_writes_no_import_library() {
626 let (b, p) = (build(), profile());
627 let of_shared = Linked::Executable {
628 subsystem: Subsystem::Console,
629 of_shared: true,
630 };
631 let tail = |kind| {
632 let args = args_linking(kind, &b, &p, of_shared, false);
633 args[args.len() - 2..].to_vec()
634 };
635 assert_eq!(tail(CompilerKind::Msvc), ["/NOIMPLIB", "/NOEXP"]);
636 assert_eq!(
637 tail(CompilerKind::ClangCl),
638 ["/SUBSYSTEM:CONSOLE", "/NOIMPLIB"]
639 );
640 assert_eq!(
641 tail(CompilerKind::Clang),
642 ["-Wl,/subsystem:console", "-Wl,/noimplib"]
643 );
644 let gcc = args_linking(CompilerKind::Gcc, &b, &p, of_shared, false);
645 assert!(!gcc.iter().any(|a| a.contains("implib")), "{gcc:?}");
646 for kind in CompilerKind::ALL {
647 let plain = args(kind, &b, &p, Subsystem::Console);
648 assert!(
649 !plain
650 .iter()
651 .any(|a| a.to_ascii_lowercase().contains("noimplib")),
652 "{kind:?}: {plain:?}"
653 );
654 }
655 }
656
657 #[test]
662 fn every_setting_gives_the_tables_link_arguments() {
663 let full_build = BuildSettings {
664 links: vec!["user32".into(), "gdi32".into()],
665 lib_dirs: vec!["libs".into(), "more".into()],
666 link_flags: vec!["/OPT:REF,ICF".into(), "/STACK:2097152".into()],
667 ..build()
668 };
669 let full_profile = ProfileSettings {
670 opt_level: OptLevel::O3,
671 debug_info: true,
672 lto: true,
673 ..profile()
674 };
675 let w = Subsystem::Windows;
676 assert_eq!(
677 args(CompilerKind::Msvc, &full_build, &full_profile, w),
678 [
679 "/nologo",
680 "a.obj",
681 "b.obj",
682 "/Fe:app.exe",
683 "/link",
684 "user32.lib",
685 "gdi32.lib",
686 "/LIBPATH:libs",
687 "/LIBPATH:more",
688 "/SUBSYSTEM:WINDOWS",
689 "/ENTRY:mainCRTStartup",
690 "/DEBUG",
691 "/INCREMENTAL:NO",
692 "/LTCG",
693 "/OPT:REF,ICF",
694 "/STACK:2097152"
695 ]
696 );
697 assert_eq!(
698 args(CompilerKind::ClangCl, &full_build, &full_profile, w),
699 [
700 "/nologo",
701 "-fuse-ld=lld",
702 "-flto",
703 "a.obj",
704 "b.obj",
705 "/Fe:app.exe",
706 "/link",
707 "user32.lib",
708 "gdi32.lib",
709 "/LIBPATH:libs",
710 "/LIBPATH:more",
711 "/SUBSYSTEM:WINDOWS",
712 "/ENTRY:mainCRTStartup",
713 "/DEBUG",
714 "/opt:lldlto=3",
715 "/OPT:REF,ICF",
716 "/STACK:2097152"
717 ]
718 );
719 assert_eq!(
720 args(CompilerKind::Clang, &full_build, &full_profile, w),
721 [
722 "--target=x86_64-pc-windows-msvc",
723 "-fuse-ld=lld",
724 "-g",
725 "-flto",
726 "a.obj",
727 "b.obj",
728 "-o",
729 "app.exe",
730 "-luser32",
731 "-lgdi32",
732 "-Llibs",
733 "-Lmore",
734 "-Wl,/subsystem:windows",
735 "-Wl,/entry:mainCRTStartup",
736 "-Wl,/opt:lldlto=3",
737 "-Xlinker",
738 "/OPT:REF,ICF",
739 "-Xlinker",
740 "/STACK:2097152"
741 ]
742 );
743 assert_eq!(
744 args(CompilerKind::Gcc, &full_build, &full_profile, w),
745 [
746 "-g",
747 "-flto=auto",
748 "a.obj",
749 "b.obj",
750 "-o",
751 "app.exe",
752 "-luser32",
753 "-lgdi32",
754 "-Llibs",
755 "-Lmore",
756 "-mwindows",
757 "-static-libgcc",
758 "-static-libstdc++",
759 "-Wl,-Bstatic",
760 "-lstdc++",
761 "-lwinpthread",
762 "-Wl,-Bdynamic",
763 "-Xlinker",
764 "/OPT:REF,ICF",
765 "-Xlinker",
766 "/STACK:2097152"
767 ]
768 );
769 }
770
771 #[test]
773 fn lto_optimises_at_the_profiles_level() {
774 for (level, n) in [
775 (OptLevel::O0, "0"),
776 (OptLevel::O1, "1"),
777 (OptLevel::O2, "2"),
778 (OptLevel::O3, "3"),
779 (OptLevel::Size, "2"),
780 ] {
781 let p = ProfileSettings {
782 opt_level: level,
783 lto: true,
784 ..profile()
785 };
786 let clang_cl = args(CompilerKind::ClangCl, &build(), &p, Subsystem::Console);
787 assert!(
788 clang_cl.contains(&format!("/opt:lldlto={n}")),
789 "{level:?} {clang_cl:?}"
790 );
791 let clang = args(CompilerKind::Clang, &build(), &p, Subsystem::Console);
792 assert!(
793 clang.contains(&format!("-Wl,/opt:lldlto={n}")),
794 "{level:?} {clang:?}"
795 );
796 let msvc = args(CompilerKind::Msvc, &build(), &p, Subsystem::Console);
797 assert!(!msvc.iter().any(|a| a.contains("lldlto")), "{msvc:?}");
798 let gcc = args(CompilerKind::Gcc, &build(), &p, Subsystem::Console);
799 assert!(!gcc.iter().any(|a| a.contains("lldlto")), "{gcc:?}");
800 }
801 }
802
803 #[test]
809 fn gcc_14_links_libstdcxx_exp_for_cxx() {
810 let v = |major| Version {
811 major,
812 minor: 1,
813 patch: 0,
814 };
815 assert_eq!(
816 gcc_runtime_args(true, v(14)),
817 [
818 "-static-libgcc",
819 "-static-libstdc++",
820 "-Wl,-Bstatic",
821 "-lstdc++exp",
822 "-lstdc++",
823 "-lwinpthread",
824 "-Wl,-Bdynamic",
825 ]
826 );
827 assert!(!gcc_runtime_args(true, v(13)).contains(&"-lstdc++exp"));
828 assert!(!gcc_runtime_args(false, v(16)).contains(&"-lstdc++exp"));
829 }
830}