1 use super::command::Command;
2 use super::symbol_export;
3 use rustc_span::symbol::sym;
5 use std::ffi::{OsStr, OsString};
6 use std::fs::{self, File};
7 use std::io::prelude::*;
8 use std::io::{self, BufWriter};
9 use std::path::{Path, PathBuf};
10 use std::{env, mem, str};
12 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
13 use rustc_metadata::find_native_static_library;
14 use rustc_middle::middle::dependency_format::Linkage;
15 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo, SymbolExportKind};
16 use rustc_middle::ty::TyCtxt;
17 use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip};
18 use rustc_session::Session;
19 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor};
21 use cc::windows_registry;
23 /// Disables non-English messages from localized linkers.
24 /// Such messages may cause issues with text encoding on Windows (#35785)
25 /// and prevent inspection of linker output in case of errors, which we occasionally do.
26 /// This should be acceptable because other messages from rustc are in English anyway,
27 /// and may also be desirable to improve searchability of the linker diagnostics.
28 pub fn disable_localization(linker: &mut Command) {
29 // No harm in setting both env vars simultaneously.
30 // Unix-style linkers.
31 linker.env("LC_ALL", "C");
33 linker.env("VSLANG", "1033");
36 // The third parameter is for env vars, used on windows to set up the
37 // path for MSVC to find its DLLs, and gcc to find its bundled
39 pub fn get_linker<'a>(
45 ) -> Box<dyn Linker + 'a> {
46 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
48 // If our linker looks like a batch script on Windows then to execute this
49 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
50 // emscripten where the linker is `emcc.bat` and needs to be spawned as
51 // `cmd /c emcc.bat ...`.
53 // This worked historically but is needed manually since #42436 (regression
54 // was tagged as #42791) and some more info can be found on #44443 for
56 let mut cmd = match linker.to_str() {
57 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
59 LinkerFlavor::Lld(f) => Command::lld(linker, f),
60 LinkerFlavor::Msvc if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() => {
61 Command::new(msvc_tool.as_ref().map_or(linker, |t| t.path()))
63 _ => Command::new(linker),
67 // UWP apps have API restrictions enforced during Store submissions.
68 // To comply with the Windows App Certification Kit,
69 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
71 if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
74 if let Some(ref tool) = msvc_tool {
75 let original_path = tool.path();
76 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
77 let arch = match t.arch.as_ref() {
78 "x86_64" => Some("x64"),
80 "aarch64" => Some("arm64"),
84 if let Some(ref a) = arch {
85 // FIXME: Move this to `fn linker_with_args`.
86 let mut arg = OsString::from("/LIBPATH:");
87 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a));
90 warn!("arch is not supported");
93 warn!("MSVC root path lib location not found");
96 warn!("link.exe not found");
100 // The compiler's sysroot often has some bundled tools, so add it to the
101 // PATH for the child.
102 let mut new_path = sess.get_tools_search_paths(self_contained);
103 let mut msvc_changed_path = false;
104 if sess.target.is_like_msvc {
105 if let Some(ref tool) = msvc_tool {
106 cmd.args(tool.args());
107 for &(ref k, ref v) in tool.env() {
109 new_path.extend(env::split_paths(v));
110 msvc_changed_path = true;
118 if !msvc_changed_path {
119 if let Some(path) = env::var_os("PATH") {
120 new_path.extend(env::split_paths(&path));
123 cmd.env("PATH", env::join_paths(new_path).unwrap());
125 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
126 // to the linker args construction.
127 assert!(cmd.get_args().is_empty() || sess.target.vendor == "uwp");
129 LinkerFlavor::Gcc => {
130 Box::new(GccLinker { cmd, sess, target_cpu, hinted_static: false, is_ld: false })
133 LinkerFlavor::Ld if sess.target.os == "l4re" => {
134 Box::new(L4Bender::new(cmd, sess)) as Box<dyn Linker>
136 LinkerFlavor::Lld(LldFlavor::Ld)
137 | LinkerFlavor::Lld(LldFlavor::Ld64)
138 | LinkerFlavor::Ld => {
139 Box::new(GccLinker { cmd, sess, target_cpu, hinted_static: false, is_ld: true })
142 LinkerFlavor::Lld(LldFlavor::Link) | LinkerFlavor::Msvc => {
143 Box::new(MsvcLinker { cmd, sess }) as Box<dyn Linker>
145 LinkerFlavor::Lld(LldFlavor::Wasm) => Box::new(WasmLd::new(cmd, sess)) as Box<dyn Linker>,
146 LinkerFlavor::EmCc => Box::new(EmLinker { cmd, sess }) as Box<dyn Linker>,
147 LinkerFlavor::Bpf => Box::new(BpfLinker { cmd, sess }) as Box<dyn Linker>,
148 LinkerFlavor::Ptx => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
152 /// Linker abstraction used by `back::link` to build up the command to invoke a
155 /// This trait is the total list of requirements needed by `back::link` and
156 /// represents the meaning of each option being passed down. This trait is then
157 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
158 /// MSVC linker (e.g., `link.exe`) is being used.
160 fn cmd(&mut self) -> &mut Command;
161 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path);
162 fn link_dylib(&mut self, lib: &str, verbatim: bool, as_needed: bool);
163 fn link_rust_dylib(&mut self, lib: &str, path: &Path);
164 fn link_framework(&mut self, framework: &str, as_needed: bool);
165 fn link_staticlib(&mut self, lib: &str, verbatim: bool);
166 fn link_rlib(&mut self, lib: &Path);
167 fn link_whole_rlib(&mut self, lib: &Path);
168 fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, search_path: &[PathBuf]);
169 fn include_path(&mut self, path: &Path);
170 fn framework_path(&mut self, path: &Path);
171 fn output_filename(&mut self, path: &Path);
172 fn add_object(&mut self, path: &Path);
173 fn gc_sections(&mut self, keep_metadata: bool);
174 fn no_gc_sections(&mut self);
175 fn full_relro(&mut self);
176 fn partial_relro(&mut self);
177 fn no_relro(&mut self);
178 fn optimize(&mut self);
179 fn pgo_gen(&mut self);
180 fn control_flow_guard(&mut self);
181 fn debuginfo(&mut self, strip: Strip, natvis_debugger_visualizers: &[PathBuf]);
182 fn no_crt_objects(&mut self);
183 fn no_default_libraries(&mut self);
184 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]);
185 fn subsystem(&mut self, subsystem: &str);
186 fn linker_plugin_lto(&mut self);
187 fn add_eh_frame_header(&mut self) {}
188 fn add_no_exec(&mut self) {}
189 fn add_as_needed(&mut self) {}
190 fn reset_per_library_state(&mut self) {}
193 impl dyn Linker + '_ {
194 pub fn arg(&mut self, arg: impl AsRef<OsStr>) {
198 pub fn args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) {
199 self.cmd().args(args);
202 pub fn take_cmd(&mut self) -> Command {
203 mem::replace(self.cmd(), Command::new(""))
207 pub struct GccLinker<'a> {
211 hinted_static: bool, // Keeps track of the current hinting mode.
216 impl<'a> GccLinker<'a> {
217 /// Passes an argument directly to the linker.
219 /// When the linker is not ld-like such as when using a compiler as a linker, the argument is
220 /// prepended by `-Wl,`.
221 fn linker_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
222 self.linker_args(&[arg]);
226 /// Passes a series of arguments directly to the linker.
228 /// When the linker is ld-like, the arguments are simply appended to the command. When the
229 /// linker is not ld-like such as when using a compiler as a linker, the arguments are joined by
230 /// commas to form an argument that is then prepended with `-Wl`. In this situation, only a
231 /// single argument is appended to the command to ensure that the order of the arguments is
232 /// preserved by the compiler.
233 fn linker_args(&mut self, args: &[impl AsRef<OsStr>]) -> &mut Self {
235 args.into_iter().for_each(|a| {
239 if !args.is_empty() {
240 let mut s = OsString::from("-Wl");
251 fn takes_hints(&self) -> bool {
252 // Really this function only returns true if the underlying linker
253 // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
254 // don't really have a foolproof way to detect that, so rule out some
255 // platforms where currently this is guaranteed to *not* be the case:
257 // * On OSX they have their own linker, not binutils'
258 // * For WebAssembly the only functional linker is LLD, which doesn't
259 // support hint flags
260 !self.sess.target.is_like_osx && !self.sess.target.is_like_wasm
263 // Some platforms take hints about whether a library is static or dynamic.
264 // For those that support this, we ensure we pass the option if the library
265 // was flagged "static" (most defaults are dynamic) to ensure that if
266 // libfoo.a and libfoo.so both exist that the right one is chosen.
267 fn hint_static(&mut self) {
268 if !self.takes_hints() {
271 if !self.hinted_static {
272 self.linker_arg("-Bstatic");
273 self.hinted_static = true;
277 fn hint_dynamic(&mut self) {
278 if !self.takes_hints() {
281 if self.hinted_static {
282 self.linker_arg("-Bdynamic");
283 self.hinted_static = false;
287 fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
288 if let Some(plugin_path) = plugin_path {
289 let mut arg = OsString::from("-plugin=");
290 arg.push(plugin_path);
291 self.linker_arg(&arg);
294 let opt_level = match self.sess.opts.optimize {
295 config::OptLevel::No => "O0",
296 config::OptLevel::Less => "O1",
297 config::OptLevel::Default | config::OptLevel::Size | config::OptLevel::SizeMin => "O2",
298 config::OptLevel::Aggressive => "O3",
301 if let Some(path) = &self.sess.opts.unstable_opts.profile_sample_use {
302 self.linker_arg(&format!("-plugin-opt=sample-profile={}", path.display()));
305 &format!("-plugin-opt={}", opt_level),
306 &format!("-plugin-opt=mcpu={}", self.target_cpu),
310 fn build_dylib(&mut self, out_filename: &Path) {
311 // On mac we need to tell the linker to let this library be rpathed
312 if self.sess.target.is_like_osx {
314 self.cmd.arg("-dynamiclib");
317 self.linker_arg("-dylib");
319 // Note that the `osx_rpath_install_name` option here is a hack
320 // purely to support rustbuild right now, we should get a more
321 // principled solution at some point to force the compiler to pass
322 // the right `-Wl,-install_name` with an `@rpath` in it.
323 if self.sess.opts.cg.rpath || self.sess.opts.unstable_opts.osx_rpath_install_name {
324 let mut rpath = OsString::from("@rpath/");
325 rpath.push(out_filename.file_name().unwrap());
326 self.linker_args(&[OsString::from("-install_name"), rpath]);
329 self.cmd.arg("-shared");
330 if self.sess.target.is_like_windows {
331 // The output filename already contains `dll_suffix` so
332 // the resulting import library will have a name in the
333 // form of libfoo.dll.a
335 out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
338 self.sess.target.staticlib_prefix,
340 self.sess.target.staticlib_suffix
343 if let Some(implib_name) = implib_name {
344 let implib = out_filename.parent().map(|dir| dir.join(&implib_name));
345 if let Some(implib) = implib {
346 self.linker_arg(&format!("--out-implib={}", (*implib).to_str().unwrap()));
354 impl<'a> Linker for GccLinker<'a> {
355 fn cmd(&mut self) -> &mut Command {
359 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
361 LinkOutputKind::DynamicNoPicExe => {
362 if !self.is_ld && self.sess.target.linker_is_gnu {
363 self.cmd.arg("-no-pie");
366 LinkOutputKind::DynamicPicExe => {
367 // noop on windows w/ gcc & ld, error w/ lld
368 if !self.sess.target.is_like_windows {
369 // `-pie` works for both gcc wrapper and ld.
370 self.cmd.arg("-pie");
373 LinkOutputKind::StaticNoPicExe => {
374 // `-static` works for both gcc wrapper and ld.
375 self.cmd.arg("-static");
376 if !self.is_ld && self.sess.target.linker_is_gnu {
377 self.cmd.arg("-no-pie");
380 LinkOutputKind::StaticPicExe => {
382 // Note that combination `-static -pie` doesn't work as expected
383 // for the gcc wrapper, `-static` in that case suppresses `-pie`.
384 self.cmd.arg("-static-pie");
386 // `--no-dynamic-linker` and `-z text` are not strictly necessary for producing
387 // a static pie, but currently passed because gcc and clang pass them.
388 // The former suppresses the `INTERP` ELF header specifying dynamic linker,
389 // which is otherwise implicitly injected by ld (but not lld).
390 // The latter doesn't change anything, only ensures that everything is pic.
391 self.cmd.args(&["-static", "-pie", "--no-dynamic-linker", "-z", "text"]);
394 LinkOutputKind::DynamicDylib => self.build_dylib(out_filename),
395 LinkOutputKind::StaticDylib => {
396 self.cmd.arg("-static");
397 self.build_dylib(out_filename);
399 LinkOutputKind::WasiReactorExe => {
400 self.linker_args(&["--entry", "_initialize"]);
403 // VxWorks compiler driver introduced `--static-crt` flag specifically for rustc,
404 // it switches linking for libc and similar system libraries to static without using
405 // any `#[link]` attributes in the `libc` crate, see #72782 for details.
406 // FIXME: Switch to using `#[link]` attributes in the `libc` crate
407 // similarly to other targets.
408 if self.sess.target.os == "vxworks"
411 LinkOutputKind::StaticNoPicExe
412 | LinkOutputKind::StaticPicExe
413 | LinkOutputKind::StaticDylib
416 self.cmd.arg("--static-crt");
420 fn link_dylib(&mut self, lib: &str, verbatim: bool, as_needed: bool) {
421 if self.sess.target.os == "illumos" && lib == "c" {
422 // libc will be added via late_link_args on illumos so that it will
423 // appear last in the library search order.
424 // FIXME: This should be replaced by a more complete and generic
425 // mechanism for controlling the order of library arguments passed
430 if self.sess.target.is_like_osx {
431 // FIXME(81490): ld64 doesn't support these flags but macOS 11
432 // has -needed-l{} / -needed_library {}
433 // but we have no way to detect that here.
434 self.sess.warn("`as-needed` modifier not implemented yet for ld64");
435 } else if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
436 self.linker_arg("--no-as-needed");
438 self.sess.warn("`as-needed` modifier not supported for current linker");
442 self.cmd.arg(format!(
444 if verbatim && self.sess.target.linker_is_gnu { ":" } else { "" },
447 if self.sess.target.is_like_osx {
448 // See above FIXME comment
449 } else if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
450 self.linker_arg("--as-needed");
454 fn link_staticlib(&mut self, lib: &str, verbatim: bool) {
456 self.cmd.arg(format!(
458 if verbatim && self.sess.target.linker_is_gnu { ":" } else { "" },
461 fn link_rlib(&mut self, lib: &Path) {
465 fn include_path(&mut self, path: &Path) {
466 self.cmd.arg("-L").arg(path);
468 fn framework_path(&mut self, path: &Path) {
469 self.cmd.arg("-F").arg(path);
471 fn output_filename(&mut self, path: &Path) {
472 self.cmd.arg("-o").arg(path);
474 fn add_object(&mut self, path: &Path) {
477 fn full_relro(&mut self) {
478 self.linker_args(&["-zrelro", "-znow"]);
480 fn partial_relro(&mut self) {
481 self.linker_arg("-zrelro");
483 fn no_relro(&mut self) {
484 self.linker_arg("-znorelro");
487 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
489 self.cmd.arg(format!("-l{}", lib));
492 fn link_framework(&mut self, framework: &str, as_needed: bool) {
495 // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
496 // flag but we have no way to detect that here.
497 // self.cmd.arg("-needed_framework").arg(framework);
498 self.sess.warn("`as-needed` modifier not implemented yet for ld64");
500 self.cmd.arg("-framework").arg(framework);
503 // Here we explicitly ask that the entire archive is included into the
504 // result artifact. For more details see #15460, but the gist is that
505 // the linker will strip away any unused objects in the archive if we
506 // don't otherwise explicitly reference them. This can occur for
507 // libraries which are just providing bindings, libraries with generic
509 fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, search_path: &[PathBuf]) {
511 let target = &self.sess.target;
512 if !target.is_like_osx {
513 self.linker_arg("--whole-archive");
514 self.cmd.arg(format!(
516 if verbatim && self.sess.target.linker_is_gnu { ":" } else { "" },
518 self.linker_arg("--no-whole-archive");
520 // -force_load is the macOS equivalent of --whole-archive, but it
521 // involves passing the full path to the library to link.
522 self.linker_arg("-force_load");
523 let lib = find_native_static_library(lib, Some(verbatim), search_path, &self.sess);
524 self.linker_arg(&lib);
528 fn link_whole_rlib(&mut self, lib: &Path) {
530 if self.sess.target.is_like_osx {
531 self.linker_arg("-force_load");
532 self.linker_arg(&lib);
534 self.linker_arg("--whole-archive").cmd.arg(lib);
535 self.linker_arg("--no-whole-archive");
539 fn gc_sections(&mut self, keep_metadata: bool) {
540 // The dead_strip option to the linker specifies that functions and data
541 // unreachable by the entry point will be removed. This is quite useful
542 // with Rust's compilation model of compiling libraries at a time into
543 // one object file. For example, this brings hello world from 1.7MB to
546 // Note that this is done for both executables and dynamic libraries. We
547 // won't get much benefit from dylibs because LLVM will have already
548 // stripped away as much as it could. This has not been seen to impact
549 // link times negatively.
551 // -dead_strip can't be part of the pre_link_args because it's also used
552 // for partial linking when using multiple codegen units (-r). So we
554 if self.sess.target.is_like_osx {
555 self.linker_arg("-dead_strip");
557 // If we're building a dylib, we don't use --gc-sections because LLVM
558 // has already done the best it can do, and we also don't want to
559 // eliminate the metadata. If we're building an executable, however,
560 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
562 } else if (self.sess.target.linker_is_gnu || self.sess.target.is_like_wasm)
565 self.linker_arg("--gc-sections");
569 fn no_gc_sections(&mut self) {
570 if self.sess.target.linker_is_gnu || self.sess.target.is_like_wasm {
571 self.linker_arg("--no-gc-sections");
575 fn optimize(&mut self) {
576 if !self.sess.target.linker_is_gnu && !self.sess.target.is_like_wasm {
580 // GNU-style linkers support optimization with -O. GNU ld doesn't
581 // need a numeric argument, but other linkers do.
582 if self.sess.opts.optimize == config::OptLevel::Default
583 || self.sess.opts.optimize == config::OptLevel::Aggressive
585 self.linker_arg("-O1");
589 fn pgo_gen(&mut self) {
590 if !self.sess.target.linker_is_gnu {
594 // If we're doing PGO generation stuff and on a GNU-like linker, use the
595 // "-u" flag to properly pull in the profiler runtime bits.
597 // This is because LLVM otherwise won't add the needed initialization
598 // for us on Linux (though the extra flag should be harmless if it
601 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
603 // Though it may be worth to try to revert those changes upstream, since
604 // the overhead of the initialization should be minor.
606 self.cmd.arg("__llvm_profile_runtime");
609 fn control_flow_guard(&mut self) {}
611 fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
612 // MacOS linker doesn't support stripping symbols directly anymore.
613 if self.sess.target.is_like_osx {
619 Strip::Debuginfo => {
620 // The illumos linker does not support --strip-debug although
621 // it does support --strip-all as a compatibility alias for -s.
622 // The --strip-debug case is handled by running an external
623 // `strip` utility as a separate step after linking.
624 if self.sess.target.os != "illumos" {
625 self.linker_arg("--strip-debug");
629 self.linker_arg("--strip-all");
634 fn no_crt_objects(&mut self) {
636 self.cmd.arg("-nostartfiles");
640 fn no_default_libraries(&mut self) {
642 self.cmd.arg("-nodefaultlibs");
646 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]) {
647 // Symbol visibility in object files typically takes care of this.
648 if crate_type == CrateType::Executable {
649 let should_export_executable_symbols =
650 self.sess.opts.unstable_opts.export_executable_symbols;
651 if self.sess.target.override_export_symbols.is_none()
652 && !should_export_executable_symbols
658 // We manually create a list of exported symbols to ensure we don't expose any more.
659 // The object files have far more public symbols than we actually want to export,
660 // so we hide them all here.
662 if !self.sess.target.limit_rdylib_exports {
666 // FIXME(#99978) hide #[no_mangle] symbols for proc-macros
668 let is_windows = self.sess.target.is_like_windows;
669 let path = tmpdir.join(if is_windows { "list.def" } else { "list" });
671 debug!("EXPORTED SYMBOLS:");
673 if self.sess.target.is_like_osx {
674 // Write a plain, newline-separated list of symbols
675 let res: io::Result<()> = try {
676 let mut f = BufWriter::new(File::create(&path)?);
679 writeln!(f, "_{}", sym)?;
682 if let Err(e) = res {
683 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
685 } else if is_windows {
686 let res: io::Result<()> = try {
687 let mut f = BufWriter::new(File::create(&path)?);
689 // .def file similar to MSVC one but without LIBRARY section
690 // because LD doesn't like when it's empty
691 writeln!(f, "EXPORTS")?;
692 for symbol in symbols {
693 debug!(" _{}", symbol);
694 writeln!(f, " {}", symbol)?;
697 if let Err(e) = res {
698 self.sess.fatal(&format!("failed to write list.def file: {}", e));
701 // Write an LD version script
702 let res: io::Result<()> = try {
703 let mut f = BufWriter::new(File::create(&path)?);
705 if !symbols.is_empty() {
706 writeln!(f, " global:")?;
709 writeln!(f, " {};", sym)?;
712 writeln!(f, "\n local:\n *;\n}};")?;
714 if let Err(e) = res {
715 self.sess.fatal(&format!("failed to write version script: {}", e));
719 if self.sess.target.is_like_osx {
720 self.linker_args(&[OsString::from("-exported_symbols_list"), path.into()]);
721 } else if self.sess.target.is_like_solaris {
722 self.linker_args(&[OsString::from("-M"), path.into()]);
725 self.linker_arg(path);
727 let mut arg = OsString::from("--version-script=");
729 self.linker_arg(arg);
734 fn subsystem(&mut self, subsystem: &str) {
735 self.linker_arg("--subsystem");
736 self.linker_arg(&subsystem);
739 fn reset_per_library_state(&mut self) {
740 self.hint_dynamic(); // Reset to default before returning the composed command line.
743 fn linker_plugin_lto(&mut self) {
744 match self.sess.opts.cg.linker_plugin_lto {
745 LinkerPluginLto::Disabled => {
748 LinkerPluginLto::LinkerPluginAuto => {
749 self.push_linker_plugin_lto_args(None);
751 LinkerPluginLto::LinkerPlugin(ref path) => {
752 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
757 // Add the `GNU_EH_FRAME` program header which is required to locate unwinding information.
758 // Some versions of `gcc` add it implicitly, some (e.g. `musl-gcc`) don't,
759 // so we just always add it.
760 fn add_eh_frame_header(&mut self) {
761 self.linker_arg("--eh-frame-hdr");
764 fn add_no_exec(&mut self) {
765 if self.sess.target.is_like_windows {
766 self.linker_arg("--nxcompat");
767 } else if self.sess.target.linker_is_gnu {
768 self.linker_arg("-znoexecstack");
772 fn add_as_needed(&mut self) {
773 if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
774 self.linker_arg("--as-needed");
775 } else if self.sess.target.is_like_solaris {
776 // -z ignore is the Solaris equivalent to the GNU ld --as-needed option
777 self.linker_args(&["-z", "ignore"]);
782 pub struct MsvcLinker<'a> {
787 impl<'a> Linker for MsvcLinker<'a> {
788 fn cmd(&mut self) -> &mut Command {
792 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
794 LinkOutputKind::DynamicNoPicExe
795 | LinkOutputKind::DynamicPicExe
796 | LinkOutputKind::StaticNoPicExe
797 | LinkOutputKind::StaticPicExe => {}
798 LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
799 self.cmd.arg("/DLL");
800 let mut arg: OsString = "/IMPLIB:".into();
801 arg.push(out_filename.with_extension("dll.lib"));
804 LinkOutputKind::WasiReactorExe => {
805 panic!("can't link as reactor on non-wasi target");
810 fn link_rlib(&mut self, lib: &Path) {
813 fn add_object(&mut self, path: &Path) {
817 fn gc_sections(&mut self, _keep_metadata: bool) {
818 // MSVC's ICF (Identical COMDAT Folding) link optimization is
819 // slow for Rust and thus we disable it by default when not in
820 // optimization build.
821 if self.sess.opts.optimize != config::OptLevel::No {
822 self.cmd.arg("/OPT:REF,ICF");
824 // It is necessary to specify NOICF here, because /OPT:REF
825 // implies ICF by default.
826 self.cmd.arg("/OPT:REF,NOICF");
830 fn no_gc_sections(&mut self) {
831 self.cmd.arg("/OPT:NOREF,NOICF");
834 fn link_dylib(&mut self, lib: &str, verbatim: bool, _as_needed: bool) {
835 self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
838 fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
839 // When producing a dll, the MSVC linker may not actually emit a
840 // `foo.lib` file if the dll doesn't actually export any symbols, so we
841 // check to see if the file is there and just omit linking to it if it's
843 let name = format!("{}.dll.lib", lib);
844 if path.join(&name).exists() {
849 fn link_staticlib(&mut self, lib: &str, verbatim: bool) {
850 self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
853 fn full_relro(&mut self) {
857 fn partial_relro(&mut self) {
861 fn no_relro(&mut self) {
865 fn no_crt_objects(&mut self) {
869 fn no_default_libraries(&mut self) {
870 self.cmd.arg("/NODEFAULTLIB");
873 fn include_path(&mut self, path: &Path) {
874 let mut arg = OsString::from("/LIBPATH:");
879 fn output_filename(&mut self, path: &Path) {
880 let mut arg = OsString::from("/OUT:");
885 fn framework_path(&mut self, _path: &Path) {
886 bug!("frameworks are not supported on windows")
888 fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
889 bug!("frameworks are not supported on windows")
892 fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, _search_path: &[PathBuf]) {
893 self.cmd.arg(format!("/WHOLEARCHIVE:{}{}", lib, if verbatim { "" } else { ".lib" }));
895 fn link_whole_rlib(&mut self, path: &Path) {
896 let mut arg = OsString::from("/WHOLEARCHIVE:");
900 fn optimize(&mut self) {
901 // Needs more investigation of `/OPT` arguments
904 fn pgo_gen(&mut self) {
905 // Nothing needed here.
908 fn control_flow_guard(&mut self) {
909 self.cmd.arg("/guard:cf");
912 fn debuginfo(&mut self, strip: Strip, natvis_debugger_visualizers: &[PathBuf]) {
915 // This will cause the Microsoft linker to generate a PDB file
916 // from the CodeView line tables in the object files.
917 self.cmd.arg("/DEBUG");
919 // This will cause the Microsoft linker to embed .natvis info into the PDB file
920 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
921 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
922 for entry in natvis_dir {
925 let path = entry.path();
926 if path.extension() == Some("natvis".as_ref()) {
927 let mut arg = OsString::from("/NATVIS:");
934 .warn(&format!("error enumerating natvis directory: {}", err));
940 // This will cause the Microsoft linker to embed .natvis info for all crates into the PDB file
941 for path in natvis_debugger_visualizers {
942 let mut arg = OsString::from("/NATVIS:");
947 Strip::Debuginfo | Strip::Symbols => {
948 self.cmd.arg("/DEBUG:NONE");
953 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
954 // export symbols from a dynamic library. When building a dynamic library,
955 // however, we're going to want some symbols exported, so this function
956 // generates a DEF file which lists all the symbols.
958 // The linker will read this `*.def` file and export all the symbols from
959 // the dynamic library. Note that this is not as simple as just exporting
960 // all the symbols in the current crate (as specified by `codegen.reachable`)
961 // but rather we also need to possibly export the symbols of upstream
962 // crates. Upstream rlibs may be linked statically to this dynamic library,
963 // in which case they may continue to transitively be used and hence need
964 // their symbols exported.
965 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]) {
966 // Symbol visibility takes care of this typically
967 if crate_type == CrateType::Executable {
968 let should_export_executable_symbols =
969 self.sess.opts.unstable_opts.export_executable_symbols;
970 if !should_export_executable_symbols {
975 let path = tmpdir.join("lib.def");
976 let res: io::Result<()> = try {
977 let mut f = BufWriter::new(File::create(&path)?);
979 // Start off with the standard module name header and then go
980 // straight to exports.
981 writeln!(f, "LIBRARY")?;
982 writeln!(f, "EXPORTS")?;
983 for symbol in symbols {
984 debug!(" _{}", symbol);
985 writeln!(f, " {}", symbol)?;
988 if let Err(e) = res {
989 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
991 let mut arg = OsString::from("/DEF:");
996 fn subsystem(&mut self, subsystem: &str) {
997 // Note that previous passes of the compiler validated this subsystem,
998 // so we just blindly pass it to the linker.
999 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
1001 // Windows has two subsystems we're interested in right now, the console
1002 // and windows subsystems. These both implicitly have different entry
1003 // points (starting symbols). The console entry point starts with
1004 // `mainCRTStartup` and the windows entry point starts with
1005 // `WinMainCRTStartup`. These entry points, defined in system libraries,
1006 // will then later probe for either `main` or `WinMain`, respectively to
1007 // start the application.
1009 // In Rust we just always generate a `main` function so we want control
1010 // to always start there, so we force the entry point on the windows
1011 // subsystem to be `mainCRTStartup` to get everything booted up
1014 // For more information see RFC #1665
1015 if subsystem == "windows" {
1016 self.cmd.arg("/ENTRY:mainCRTStartup");
1020 fn linker_plugin_lto(&mut self) {
1024 fn add_no_exec(&mut self) {
1025 self.cmd.arg("/NXCOMPAT");
1029 pub struct EmLinker<'a> {
1034 impl<'a> Linker for EmLinker<'a> {
1035 fn cmd(&mut self) -> &mut Command {
1039 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1041 fn include_path(&mut self, path: &Path) {
1042 self.cmd.arg("-L").arg(path);
1045 fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
1046 self.cmd.arg("-l").arg(lib);
1049 fn output_filename(&mut self, path: &Path) {
1050 self.cmd.arg("-o").arg(path);
1053 fn add_object(&mut self, path: &Path) {
1057 fn link_dylib(&mut self, lib: &str, verbatim: bool, _as_needed: bool) {
1058 // Emscripten always links statically
1059 self.link_staticlib(lib, verbatim);
1062 fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, _search_path: &[PathBuf]) {
1064 self.link_staticlib(lib, verbatim);
1067 fn link_whole_rlib(&mut self, lib: &Path) {
1069 self.link_rlib(lib);
1072 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
1073 self.link_dylib(lib, false, true);
1076 fn link_rlib(&mut self, lib: &Path) {
1077 self.add_object(lib);
1080 fn full_relro(&mut self) {
1084 fn partial_relro(&mut self) {
1088 fn no_relro(&mut self) {
1092 fn framework_path(&mut self, _path: &Path) {
1093 bug!("frameworks are not supported on Emscripten")
1096 fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1097 bug!("frameworks are not supported on Emscripten")
1100 fn gc_sections(&mut self, _keep_metadata: bool) {
1104 fn no_gc_sections(&mut self) {
1108 fn optimize(&mut self) {
1109 // Emscripten performs own optimizations
1110 self.cmd.arg(match self.sess.opts.optimize {
1111 OptLevel::No => "-O0",
1112 OptLevel::Less => "-O1",
1113 OptLevel::Default => "-O2",
1114 OptLevel::Aggressive => "-O3",
1115 OptLevel::Size => "-Os",
1116 OptLevel::SizeMin => "-Oz",
1120 fn pgo_gen(&mut self) {
1121 // noop, but maybe we need something like the gnu linker?
1124 fn control_flow_guard(&mut self) {}
1126 fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1127 // Preserve names or generate source maps depending on debug info
1128 self.cmd.arg(match self.sess.opts.debuginfo {
1129 DebugInfo::None => "-g0",
1130 DebugInfo::Limited => "--profiling-funcs",
1131 DebugInfo::Full => "-g",
1135 fn no_crt_objects(&mut self) {}
1137 fn no_default_libraries(&mut self) {
1138 self.cmd.arg("-nodefaultlibs");
1141 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1142 debug!("EXPORTED SYMBOLS:");
1146 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
1147 let encoded = serde_json::to_string(
1148 &symbols.iter().map(|sym| "_".to_owned() + sym).collect::<Vec<_>>(),
1151 debug!("{}", encoded);
1158 fn subsystem(&mut self, _subsystem: &str) {
1162 fn linker_plugin_lto(&mut self) {
1167 pub struct WasmLd<'a> {
1172 impl<'a> WasmLd<'a> {
1173 fn new(mut cmd: Command, sess: &'a Session) -> WasmLd<'a> {
1174 // If the atomics feature is enabled for wasm then we need a whole bunch
1177 // * `--shared-memory` - the link won't even succeed without this, flags
1178 // the one linear memory as `shared`
1180 // * `--max-memory=1G` - when specifying a shared memory this must also
1181 // be specified. We conservatively choose 1GB but users should be able
1182 // to override this with `-C link-arg`.
1184 // * `--import-memory` - it doesn't make much sense for memory to be
1185 // exported in a threaded module because typically you're
1186 // sharing memory and instantiating the module multiple times. As a
1187 // result if it were exported then we'd just have no sharing.
1189 // * `--export=__wasm_init_memory` - when using `--passive-segments` the
1190 // linker will synthesize this function, and so we need to make sure
1191 // that our usage of `--export` below won't accidentally cause this
1192 // function to get deleted.
1194 // * `--export=*tls*` - when `#[thread_local]` symbols are used these
1195 // symbols are how the TLS segments are initialized and configured.
1196 if sess.target_features.contains(&sym::atomics) {
1197 cmd.arg("--shared-memory");
1198 cmd.arg("--max-memory=1073741824");
1199 cmd.arg("--import-memory");
1200 cmd.arg("--export=__wasm_init_memory");
1201 cmd.arg("--export=__wasm_init_tls");
1202 cmd.arg("--export=__tls_size");
1203 cmd.arg("--export=__tls_align");
1204 cmd.arg("--export=__tls_base");
1206 WasmLd { cmd, sess }
1210 impl<'a> Linker for WasmLd<'a> {
1211 fn cmd(&mut self) -> &mut Command {
1215 fn set_output_kind(&mut self, output_kind: LinkOutputKind, _out_filename: &Path) {
1217 LinkOutputKind::DynamicNoPicExe
1218 | LinkOutputKind::DynamicPicExe
1219 | LinkOutputKind::StaticNoPicExe
1220 | LinkOutputKind::StaticPicExe => {}
1221 LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1222 self.cmd.arg("--no-entry");
1224 LinkOutputKind::WasiReactorExe => {
1225 self.cmd.arg("--entry");
1226 self.cmd.arg("_initialize");
1231 fn link_dylib(&mut self, lib: &str, _verbatim: bool, _as_needed: bool) {
1232 self.cmd.arg("-l").arg(lib);
1235 fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
1236 self.cmd.arg("-l").arg(lib);
1239 fn link_rlib(&mut self, lib: &Path) {
1243 fn include_path(&mut self, path: &Path) {
1244 self.cmd.arg("-L").arg(path);
1247 fn framework_path(&mut self, _path: &Path) {
1248 panic!("frameworks not supported")
1251 fn output_filename(&mut self, path: &Path) {
1252 self.cmd.arg("-o").arg(path);
1255 fn add_object(&mut self, path: &Path) {
1259 fn full_relro(&mut self) {}
1261 fn partial_relro(&mut self) {}
1263 fn no_relro(&mut self) {}
1265 fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
1266 self.cmd.arg("-l").arg(lib);
1269 fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1270 panic!("frameworks not supported")
1273 fn link_whole_staticlib(&mut self, lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
1274 self.cmd.arg("-l").arg(lib);
1277 fn link_whole_rlib(&mut self, lib: &Path) {
1281 fn gc_sections(&mut self, _keep_metadata: bool) {
1282 self.cmd.arg("--gc-sections");
1285 fn no_gc_sections(&mut self) {
1286 self.cmd.arg("--no-gc-sections");
1289 fn optimize(&mut self) {
1290 self.cmd.arg(match self.sess.opts.optimize {
1291 OptLevel::No => "-O0",
1292 OptLevel::Less => "-O1",
1293 OptLevel::Default => "-O2",
1294 OptLevel::Aggressive => "-O3",
1295 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1297 OptLevel::Size => "-O2",
1298 OptLevel::SizeMin => "-O2",
1302 fn pgo_gen(&mut self) {}
1304 fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
1307 Strip::Debuginfo => {
1308 self.cmd.arg("--strip-debug");
1311 self.cmd.arg("--strip-all");
1316 fn control_flow_guard(&mut self) {}
1318 fn no_crt_objects(&mut self) {}
1320 fn no_default_libraries(&mut self) {}
1322 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1323 for sym in symbols {
1324 self.cmd.arg("--export").arg(&sym);
1327 // LLD will hide these otherwise-internal symbols since it only exports
1328 // symbols explicitly passed via the `--export` flags above and hides all
1329 // others. Various bits and pieces of tooling use this, so be sure these
1330 // symbols make their way out of the linker as well.
1331 self.cmd.arg("--export=__heap_base");
1332 self.cmd.arg("--export=__data_end");
1335 fn subsystem(&mut self, _subsystem: &str) {}
1337 fn linker_plugin_lto(&mut self) {
1338 // Do nothing for now
1342 /// Linker shepherd script for L4Re (Fiasco)
1343 pub struct L4Bender<'a> {
1346 hinted_static: bool,
1349 impl<'a> Linker for L4Bender<'a> {
1350 fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
1351 bug!("dylibs are not supported on L4Re");
1353 fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
1355 self.cmd.arg(format!("-PC{}", lib));
1357 fn link_rlib(&mut self, lib: &Path) {
1361 fn include_path(&mut self, path: &Path) {
1362 self.cmd.arg("-L").arg(path);
1364 fn framework_path(&mut self, _: &Path) {
1365 bug!("frameworks are not supported on L4Re");
1367 fn output_filename(&mut self, path: &Path) {
1368 self.cmd.arg("-o").arg(path);
1371 fn add_object(&mut self, path: &Path) {
1375 fn full_relro(&mut self) {
1376 self.cmd.arg("-zrelro");
1377 self.cmd.arg("-znow");
1380 fn partial_relro(&mut self) {
1381 self.cmd.arg("-zrelro");
1384 fn no_relro(&mut self) {
1385 self.cmd.arg("-znorelro");
1388 fn cmd(&mut self) -> &mut Command {
1392 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1394 fn link_rust_dylib(&mut self, _: &str, _: &Path) {
1395 panic!("Rust dylibs not supported");
1398 fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1399 bug!("frameworks not supported on L4Re");
1402 fn link_whole_staticlib(&mut self, lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
1404 self.cmd.arg("--whole-archive").arg(format!("-l{}", lib));
1405 self.cmd.arg("--no-whole-archive");
1408 fn link_whole_rlib(&mut self, lib: &Path) {
1410 self.cmd.arg("--whole-archive").arg(lib).arg("--no-whole-archive");
1413 fn gc_sections(&mut self, keep_metadata: bool) {
1415 self.cmd.arg("--gc-sections");
1419 fn no_gc_sections(&mut self) {
1420 self.cmd.arg("--no-gc-sections");
1423 fn optimize(&mut self) {
1424 // GNU-style linkers support optimization with -O. GNU ld doesn't
1425 // need a numeric argument, but other linkers do.
1426 if self.sess.opts.optimize == config::OptLevel::Default
1427 || self.sess.opts.optimize == config::OptLevel::Aggressive
1429 self.cmd.arg("-O1");
1433 fn pgo_gen(&mut self) {}
1435 fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
1438 Strip::Debuginfo => {
1439 self.cmd().arg("--strip-debug");
1442 self.cmd().arg("--strip-all");
1447 fn no_default_libraries(&mut self) {
1448 self.cmd.arg("-nostdlib");
1451 fn export_symbols(&mut self, _: &Path, _: CrateType, _: &[String]) {
1452 // ToDo, not implemented, copy from GCC
1453 self.sess.warn("exporting symbols not implemented yet for L4Bender");
1457 fn subsystem(&mut self, subsystem: &str) {
1458 self.cmd.arg(&format!("--subsystem {}", subsystem));
1461 fn reset_per_library_state(&mut self) {
1462 self.hint_static(); // Reset to default before returning the composed command line.
1465 fn linker_plugin_lto(&mut self) {}
1467 fn control_flow_guard(&mut self) {}
1469 fn no_crt_objects(&mut self) {}
1472 impl<'a> L4Bender<'a> {
1473 pub fn new(cmd: Command, sess: &'a Session) -> L4Bender<'a> {
1474 L4Bender { cmd: cmd, sess: sess, hinted_static: false }
1477 fn hint_static(&mut self) {
1478 if !self.hinted_static {
1479 self.cmd.arg("-static");
1480 self.hinted_static = true;
1485 fn for_each_exported_symbols_include_dep<'tcx>(
1487 crate_type: CrateType,
1488 mut callback: impl FnMut(ExportedSymbol<'tcx>, SymbolExportInfo, CrateNum),
1490 for &(symbol, info) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1491 callback(symbol, info, LOCAL_CRATE);
1494 let formats = tcx.dependency_formats(());
1495 let deps = formats.iter().find_map(|(t, list)| (*t == crate_type).then_some(list)).unwrap();
1497 for (index, dep_format) in deps.iter().enumerate() {
1498 let cnum = CrateNum::new(index + 1);
1499 // For each dependency that we are linking to statically ...
1500 if *dep_format == Linkage::Static {
1501 for &(symbol, info) in tcx.exported_symbols(cnum).iter() {
1502 callback(symbol, info, cnum);
1508 pub(crate) fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1509 if let Some(ref exports) = tcx.sess.target.override_export_symbols {
1510 return exports.iter().map(ToString::to_string).collect();
1513 let mut symbols = Vec::new();
1515 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1516 for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| {
1517 if info.level.is_below_threshold(export_threshold) {
1518 symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1525 pub(crate) fn linked_symbols(
1527 crate_type: CrateType,
1528 ) -> Vec<(String, SymbolExportKind)> {
1530 CrateType::Executable | CrateType::Cdylib | CrateType::Dylib => (),
1531 CrateType::Staticlib | CrateType::ProcMacro | CrateType::Rlib => {
1536 let mut symbols = Vec::new();
1538 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1539 for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| {
1540 if info.level.is_below_threshold(export_threshold) || info.used {
1542 symbol_export::linking_symbol_name_for_instance_in_crate(tcx, symbol, cnum),
1551 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1552 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1553 pub struct PtxLinker<'a> {
1558 impl<'a> Linker for PtxLinker<'a> {
1559 fn cmd(&mut self) -> &mut Command {
1563 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1565 fn link_rlib(&mut self, path: &Path) {
1566 self.cmd.arg("--rlib").arg(path);
1569 fn link_whole_rlib(&mut self, path: &Path) {
1570 self.cmd.arg("--rlib").arg(path);
1573 fn include_path(&mut self, path: &Path) {
1574 self.cmd.arg("-L").arg(path);
1577 fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1578 self.cmd.arg("--debug");
1581 fn add_object(&mut self, path: &Path) {
1582 self.cmd.arg("--bitcode").arg(path);
1585 fn optimize(&mut self) {
1586 match self.sess.lto() {
1587 Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1588 self.cmd.arg("-Olto");
1595 fn output_filename(&mut self, path: &Path) {
1596 self.cmd.arg("-o").arg(path);
1599 fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
1600 panic!("external dylibs not supported")
1603 fn link_rust_dylib(&mut self, _lib: &str, _path: &Path) {
1604 panic!("external dylibs not supported")
1607 fn link_staticlib(&mut self, _lib: &str, _verbatim: bool) {
1608 panic!("staticlibs not supported")
1611 fn link_whole_staticlib(&mut self, _lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
1612 panic!("staticlibs not supported")
1615 fn framework_path(&mut self, _path: &Path) {
1616 panic!("frameworks not supported")
1619 fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1620 panic!("frameworks not supported")
1623 fn full_relro(&mut self) {}
1625 fn partial_relro(&mut self) {}
1627 fn no_relro(&mut self) {}
1629 fn gc_sections(&mut self, _keep_metadata: bool) {}
1631 fn no_gc_sections(&mut self) {}
1633 fn pgo_gen(&mut self) {}
1635 fn no_crt_objects(&mut self) {}
1637 fn no_default_libraries(&mut self) {}
1639 fn control_flow_guard(&mut self) {}
1641 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, _symbols: &[String]) {}
1643 fn subsystem(&mut self, _subsystem: &str) {}
1645 fn linker_plugin_lto(&mut self) {}
1648 pub struct BpfLinker<'a> {
1653 impl<'a> Linker for BpfLinker<'a> {
1654 fn cmd(&mut self) -> &mut Command {
1658 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1660 fn link_rlib(&mut self, path: &Path) {
1664 fn link_whole_rlib(&mut self, path: &Path) {
1668 fn include_path(&mut self, path: &Path) {
1669 self.cmd.arg("-L").arg(path);
1672 fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1673 self.cmd.arg("--debug");
1676 fn add_object(&mut self, path: &Path) {
1680 fn optimize(&mut self) {
1681 self.cmd.arg(match self.sess.opts.optimize {
1682 OptLevel::No => "-O0",
1683 OptLevel::Less => "-O1",
1684 OptLevel::Default => "-O2",
1685 OptLevel::Aggressive => "-O3",
1686 OptLevel::Size => "-Os",
1687 OptLevel::SizeMin => "-Oz",
1691 fn output_filename(&mut self, path: &Path) {
1692 self.cmd.arg("-o").arg(path);
1695 fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
1696 panic!("external dylibs not supported")
1699 fn link_rust_dylib(&mut self, _lib: &str, _path: &Path) {
1700 panic!("external dylibs not supported")
1703 fn link_staticlib(&mut self, _lib: &str, _verbatim: bool) {
1704 panic!("staticlibs not supported")
1707 fn link_whole_staticlib(&mut self, _lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
1708 panic!("staticlibs not supported")
1711 fn framework_path(&mut self, _path: &Path) {
1712 panic!("frameworks not supported")
1715 fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1716 panic!("frameworks not supported")
1719 fn full_relro(&mut self) {}
1721 fn partial_relro(&mut self) {}
1723 fn no_relro(&mut self) {}
1725 fn gc_sections(&mut self, _keep_metadata: bool) {}
1727 fn no_gc_sections(&mut self) {}
1729 fn pgo_gen(&mut self) {}
1731 fn no_crt_objects(&mut self) {}
1733 fn no_default_libraries(&mut self) {}
1735 fn control_flow_guard(&mut self) {}
1737 fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1738 let path = tmpdir.join("symbols");
1739 let res: io::Result<()> = try {
1740 let mut f = BufWriter::new(File::create(&path)?);
1741 for sym in symbols {
1742 writeln!(f, "{}", sym)?;
1745 if let Err(e) = res {
1746 self.sess.fatal(&format!("failed to write symbols file: {}", e));
1748 self.cmd.arg("--export-symbols").arg(&path);
1752 fn subsystem(&mut self, _subsystem: &str) {}
1754 fn linker_plugin_lto(&mut self) {}