2 use super::command::Command;
3 use super::symbol_export;
4 use rustc_span::symbol::sym;
6 use std::ffi::{OsStr, OsString};
7 use std::fs::{self, File};
8 use std::io::prelude::*;
9 use std::io::{self, BufWriter};
10 use std::path::{Path, PathBuf};
11 use std::{env, mem, str};
13 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
14 use rustc_middle::middle::dependency_format::Linkage;
15 use rustc_middle::middle::exported_symbols::SymbolExportKind;
16 use rustc_middle::ty::TyCtxt;
17 use rustc_serialize::{json, Encoder};
18 use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip};
19 use rustc_session::Session;
20 use rustc_span::symbol::Symbol;
21 use rustc_target::spec::{LinkOutputKind, LinkerFlavor, LldFlavor};
23 use cc::windows_registry;
25 /// Disables non-English messages from localized linkers.
26 /// Such messages may cause issues with text encoding on Windows (#35785)
27 /// and prevent inspection of linker output in case of errors, which we occasionally do.
28 /// This should be acceptable because other messages from rustc are in English anyway,
29 /// and may also be desirable to improve searchability of the linker diagnostics.
30 pub fn disable_localization(linker: &mut Command) {
31 // No harm in setting both env vars simultaneously.
32 // Unix-style linkers.
33 linker.env("LC_ALL", "C");
35 linker.env("VSLANG", "1033");
38 // The third parameter is for env vars, used on windows to set up the
39 // path for MSVC to find its DLLs, and gcc to find its bundled
41 pub fn get_linker<'a>(
47 ) -> Box<dyn Linker + 'a> {
48 let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
50 // If our linker looks like a batch script on Windows then to execute this
51 // we'll need to spawn `cmd` explicitly. This is primarily done to handle
52 // emscripten where the linker is `emcc.bat` and needs to be spawned as
53 // `cmd /c emcc.bat ...`.
55 // This worked historically but is needed manually since #42436 (regression
56 // was tagged as #42791) and some more info can be found on #44443 for
58 let mut cmd = match linker.to_str() {
59 Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
61 LinkerFlavor::Lld(f) => Command::lld(linker, f),
62 LinkerFlavor::Msvc if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() => {
63 Command::new(msvc_tool.as_ref().map_or(linker, |t| t.path()))
65 _ => Command::new(linker),
69 // UWP apps have API restrictions enforced during Store submissions.
70 // To comply with the Windows App Certification Kit,
71 // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
73 if (flavor == LinkerFlavor::Msvc || flavor == LinkerFlavor::Lld(LldFlavor::Link))
76 if let Some(ref tool) = msvc_tool {
77 let original_path = tool.path();
78 if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
79 let arch = match t.arch.as_str() {
80 "x86_64" => Some("x64"),
82 "aarch64" => Some("arm64"),
86 if let Some(ref a) = arch {
87 // FIXME: Move this to `fn linker_with_args`.
88 let mut arg = OsString::from("/LIBPATH:");
89 arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a));
92 warn!("arch is not supported");
95 warn!("MSVC root path lib location not found");
98 warn!("link.exe not found");
102 // The compiler's sysroot often has some bundled tools, so add it to the
103 // PATH for the child.
104 let mut new_path = sess.get_tools_search_paths(self_contained);
105 let mut msvc_changed_path = false;
106 if sess.target.is_like_msvc {
107 if let Some(ref tool) = msvc_tool {
108 cmd.args(tool.args());
109 for &(ref k, ref v) in tool.env() {
111 new_path.extend(env::split_paths(v));
112 msvc_changed_path = true;
120 if !msvc_changed_path {
121 if let Some(path) = env::var_os("PATH") {
122 new_path.extend(env::split_paths(&path));
125 cmd.env("PATH", env::join_paths(new_path).unwrap());
127 // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
128 // to the linker args construction.
129 assert!(cmd.get_args().is_empty() || sess.target.vendor == "uwp");
131 LinkerFlavor::Lld(LldFlavor::Link) | LinkerFlavor::Msvc => {
132 Box::new(MsvcLinker { cmd, sess }) as Box<dyn Linker>
134 LinkerFlavor::Em => Box::new(EmLinker { cmd, sess }) as Box<dyn Linker>,
135 LinkerFlavor::Gcc => {
136 Box::new(GccLinker { cmd, sess, target_cpu, hinted_static: false, is_ld: false })
140 LinkerFlavor::Lld(LldFlavor::Ld)
141 | LinkerFlavor::Lld(LldFlavor::Ld64)
142 | LinkerFlavor::Ld => {
143 Box::new(GccLinker { cmd, sess, target_cpu, hinted_static: false, is_ld: true })
147 LinkerFlavor::Lld(LldFlavor::Wasm) => Box::new(WasmLd::new(cmd, sess)) as Box<dyn Linker>,
149 LinkerFlavor::PtxLinker => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
151 LinkerFlavor::BpfLinker => Box::new(BpfLinker { cmd, sess }) as Box<dyn Linker>,
153 LinkerFlavor::L4Bender => Box::new(L4Bender::new(cmd, sess)) as Box<dyn Linker>,
157 /// Linker abstraction used by `back::link` to build up the command to invoke a
160 /// This trait is the total list of requirements needed by `back::link` and
161 /// represents the meaning of each option being passed down. This trait is then
162 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
163 /// MSVC linker (e.g., `link.exe`) is being used.
165 fn cmd(&mut self) -> &mut Command;
166 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path);
167 fn link_dylib(&mut self, lib: Symbol, verbatim: bool, as_needed: bool);
168 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path);
169 fn link_framework(&mut self, framework: Symbol, as_needed: bool);
170 fn link_staticlib(&mut self, lib: Symbol, verbatim: bool);
171 fn link_rlib(&mut self, lib: &Path);
172 fn link_whole_rlib(&mut self, lib: &Path);
173 fn link_whole_staticlib(&mut self, lib: Symbol, verbatim: bool, search_path: &[PathBuf]);
174 fn include_path(&mut self, path: &Path);
175 fn framework_path(&mut self, path: &Path);
176 fn output_filename(&mut self, path: &Path);
177 fn add_object(&mut self, path: &Path);
178 fn gc_sections(&mut self, keep_metadata: bool);
179 fn no_gc_sections(&mut self);
180 fn full_relro(&mut self);
181 fn partial_relro(&mut self);
182 fn no_relro(&mut self);
183 fn optimize(&mut self);
184 fn pgo_gen(&mut self);
185 fn control_flow_guard(&mut self);
186 fn debuginfo(&mut self, strip: Strip);
187 fn no_crt_objects(&mut self);
188 fn no_default_libraries(&mut self);
189 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]);
190 fn exported_symbol_means_used_symbol(&self) -> bool {
193 fn subsystem(&mut self, subsystem: &str);
194 fn group_start(&mut self);
195 fn group_end(&mut self);
196 fn linker_plugin_lto(&mut self);
197 fn add_eh_frame_header(&mut self) {}
198 fn add_no_exec(&mut self) {}
199 fn add_as_needed(&mut self) {}
200 fn reset_per_library_state(&mut self) {}
203 impl dyn Linker + '_ {
204 pub fn arg(&mut self, arg: impl AsRef<OsStr>) {
208 pub fn args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) {
209 self.cmd().args(args);
212 pub fn take_cmd(&mut self) -> Command {
213 mem::replace(self.cmd(), Command::new(""))
217 pub struct GccLinker<'a> {
221 hinted_static: bool, // Keeps track of the current hinting mode.
226 impl<'a> GccLinker<'a> {
227 /// Passes an argument directly to the linker.
229 /// When the linker is not ld-like such as when using a compiler as a linker, the argument is
230 /// prepended by `-Wl,`.
231 fn linker_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
232 self.linker_args(&[arg]);
236 /// Passes a series of arguments directly to the linker.
238 /// When the linker is ld-like, the arguments are simply appended to the command. When the
239 /// linker is not ld-like such as when using a compiler as a linker, the arguments are joined by
240 /// commas to form an argument that is then prepended with `-Wl`. In this situation, only a
241 /// single argument is appended to the command to ensure that the order of the arguments is
242 /// preserved by the compiler.
243 fn linker_args(&mut self, args: &[impl AsRef<OsStr>]) -> &mut Self {
245 args.into_iter().for_each(|a| {
249 if !args.is_empty() {
250 let mut s = OsString::from("-Wl");
261 fn takes_hints(&self) -> bool {
262 // Really this function only returns true if the underlying linker
263 // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
264 // don't really have a foolproof way to detect that, so rule out some
265 // platforms where currently this is guaranteed to *not* be the case:
267 // * On OSX they have their own linker, not binutils'
268 // * For WebAssembly the only functional linker is LLD, which doesn't
269 // support hint flags
270 !self.sess.target.is_like_osx && !self.sess.target.is_like_wasm
273 // Some platforms take hints about whether a library is static or dynamic.
274 // For those that support this, we ensure we pass the option if the library
275 // was flagged "static" (most defaults are dynamic) to ensure that if
276 // libfoo.a and libfoo.so both exist that the right one is chosen.
277 fn hint_static(&mut self) {
278 if !self.takes_hints() {
281 if !self.hinted_static {
282 self.linker_arg("-Bstatic");
283 self.hinted_static = true;
287 fn hint_dynamic(&mut self) {
288 if !self.takes_hints() {
291 if self.hinted_static {
292 self.linker_arg("-Bdynamic");
293 self.hinted_static = false;
297 fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
298 if let Some(plugin_path) = plugin_path {
299 let mut arg = OsString::from("-plugin=");
300 arg.push(plugin_path);
301 self.linker_arg(&arg);
304 let opt_level = match self.sess.opts.optimize {
305 config::OptLevel::No => "O0",
306 config::OptLevel::Less => "O1",
307 config::OptLevel::Default | config::OptLevel::Size | config::OptLevel::SizeMin => "O2",
308 config::OptLevel::Aggressive => "O3",
311 if let Some(path) = &self.sess.opts.debugging_opts.profile_sample_use {
312 self.linker_arg(&format!("-plugin-opt=sample-profile={}", path.display()));
315 &format!("-plugin-opt={}", opt_level),
316 &format!("-plugin-opt=mcpu={}", self.target_cpu),
320 fn build_dylib(&mut self, out_filename: &Path) {
321 // On mac we need to tell the linker to let this library be rpathed
322 if self.sess.target.is_like_osx {
324 self.cmd.arg("-dynamiclib");
327 self.linker_arg("-dylib");
329 // Note that the `osx_rpath_install_name` option here is a hack
330 // purely to support rustbuild right now, we should get a more
331 // principled solution at some point to force the compiler to pass
332 // the right `-Wl,-install_name` with an `@rpath` in it.
333 if self.sess.opts.cg.rpath || self.sess.opts.debugging_opts.osx_rpath_install_name {
334 let mut rpath = OsString::from("@rpath/");
335 rpath.push(out_filename.file_name().unwrap());
336 self.linker_args(&[OsString::from("-install_name"), rpath]);
339 self.cmd.arg("-shared");
340 if self.sess.target.is_like_windows {
341 // The output filename already contains `dll_suffix` so
342 // the resulting import library will have a name in the
343 // form of libfoo.dll.a
345 out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
348 self.sess.target.staticlib_prefix,
350 self.sess.target.staticlib_suffix
353 if let Some(implib_name) = implib_name {
354 let implib = out_filename.parent().map(|dir| dir.join(&implib_name));
355 if let Some(implib) = implib {
356 self.linker_arg(&format!("--out-implib={}", (*implib).to_str().unwrap()));
364 impl<'a> Linker for GccLinker<'a> {
365 fn cmd(&mut self) -> &mut Command {
369 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
371 LinkOutputKind::DynamicNoPicExe => {
372 if !self.is_ld && self.sess.target.linker_is_gnu {
373 self.cmd.arg("-no-pie");
376 LinkOutputKind::DynamicPicExe => {
377 // noop on windows w/ gcc & ld, error w/ lld
378 if !self.sess.target.is_like_windows {
379 // `-pie` works for both gcc wrapper and ld.
380 self.cmd.arg("-pie");
383 LinkOutputKind::StaticNoPicExe => {
384 // `-static` works for both gcc wrapper and ld.
385 self.cmd.arg("-static");
386 if !self.is_ld && self.sess.target.linker_is_gnu {
387 self.cmd.arg("-no-pie");
390 LinkOutputKind::StaticPicExe => {
392 // Note that combination `-static -pie` doesn't work as expected
393 // for the gcc wrapper, `-static` in that case suppresses `-pie`.
394 self.cmd.arg("-static-pie");
396 // `--no-dynamic-linker` and `-z text` are not strictly necessary for producing
397 // a static pie, but currently passed because gcc and clang pass them.
398 // The former suppresses the `INTERP` ELF header specifying dynamic linker,
399 // which is otherwise implicitly injected by ld (but not lld).
400 // The latter doesn't change anything, only ensures that everything is pic.
401 self.cmd.args(&["-static", "-pie", "--no-dynamic-linker", "-z", "text"]);
404 LinkOutputKind::DynamicDylib => self.build_dylib(out_filename),
405 LinkOutputKind::StaticDylib => {
406 self.cmd.arg("-static");
407 self.build_dylib(out_filename);
409 LinkOutputKind::WasiReactorExe => {
410 self.linker_args(&["--entry", "_initialize"]);
413 // VxWorks compiler driver introduced `--static-crt` flag specifically for rustc,
414 // it switches linking for libc and similar system libraries to static without using
415 // any `#[link]` attributes in the `libc` crate, see #72782 for details.
416 // FIXME: Switch to using `#[link]` attributes in the `libc` crate
417 // similarly to other targets.
418 if self.sess.target.os == "vxworks"
421 LinkOutputKind::StaticNoPicExe
422 | LinkOutputKind::StaticPicExe
423 | LinkOutputKind::StaticDylib
426 self.cmd.arg("--static-crt");
430 fn link_dylib(&mut self, lib: Symbol, verbatim: bool, as_needed: bool) {
431 if self.sess.target.os == "illumos" && lib.as_str() == "c" {
432 // libc will be added via late_link_args on illumos so that it will
433 // appear last in the library search order.
434 // FIXME: This should be replaced by a more complete and generic
435 // mechanism for controlling the order of library arguments passed
440 if self.sess.target.is_like_osx {
441 // FIXME(81490): ld64 doesn't support these flags but macOS 11
442 // has -needed-l{} / -needed_library {}
443 // but we have no way to detect that here.
444 self.sess.warn("`as-needed` modifier not implemented yet for ld64");
445 } else if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
446 self.linker_arg("--no-as-needed");
448 self.sess.warn("`as-needed` modifier not supported for current linker");
452 self.cmd.arg(format!("-l{}{}", if verbatim { ":" } else { "" }, lib));
454 if self.sess.target.is_like_osx {
455 // See above FIXME comment
456 } else if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
457 self.linker_arg("--as-needed");
461 fn link_staticlib(&mut self, lib: Symbol, verbatim: bool) {
463 self.cmd.arg(format!("-l{}{}", if verbatim { ":" } else { "" }, lib));
465 fn link_rlib(&mut self, lib: &Path) {
469 fn include_path(&mut self, path: &Path) {
470 self.cmd.arg("-L").arg(path);
472 fn framework_path(&mut self, path: &Path) {
473 self.cmd.arg("-F").arg(path);
475 fn output_filename(&mut self, path: &Path) {
476 self.cmd.arg("-o").arg(path);
478 fn add_object(&mut self, path: &Path) {
481 fn full_relro(&mut self) {
482 self.linker_args(&["-zrelro", "-znow"]);
484 fn partial_relro(&mut self) {
485 self.linker_arg("-zrelro");
487 fn no_relro(&mut self) {
488 self.linker_arg("-znorelro");
491 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
493 self.cmd.arg(format!("-l{}", lib));
496 fn link_framework(&mut self, framework: Symbol, as_needed: bool) {
499 // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
500 // flag but we have no way to detect that here.
501 // self.cmd.arg("-needed_framework").sym_arg(framework);
502 self.sess.warn("`as-needed` modifier not implemented yet for ld64");
504 self.cmd.arg("-framework").sym_arg(framework);
507 // Here we explicitly ask that the entire archive is included into the
508 // result artifact. For more details see #15460, but the gist is that
509 // the linker will strip away any unused objects in the archive if we
510 // don't otherwise explicitly reference them. This can occur for
511 // libraries which are just providing bindings, libraries with generic
513 fn link_whole_staticlib(&mut self, lib: Symbol, verbatim: bool, search_path: &[PathBuf]) {
515 let target = &self.sess.target;
516 if !target.is_like_osx {
517 self.linker_arg("--whole-archive").cmd.arg(format!(
519 if verbatim { ":" } else { "" },
522 self.linker_arg("--no-whole-archive");
524 // -force_load is the macOS equivalent of --whole-archive, but it
525 // involves passing the full path to the library to link.
526 self.linker_arg("-force_load");
527 let lib = archive::find_library(lib, verbatim, search_path, &self.sess);
528 self.linker_arg(&lib);
532 fn link_whole_rlib(&mut self, lib: &Path) {
534 if self.sess.target.is_like_osx {
535 self.linker_arg("-force_load");
536 self.linker_arg(&lib);
538 self.linker_arg("--whole-archive").cmd.arg(lib);
539 self.linker_arg("--no-whole-archive");
543 fn gc_sections(&mut self, keep_metadata: bool) {
544 // The dead_strip option to the linker specifies that functions and data
545 // unreachable by the entry point will be removed. This is quite useful
546 // with Rust's compilation model of compiling libraries at a time into
547 // one object file. For example, this brings hello world from 1.7MB to
550 // Note that this is done for both executables and dynamic libraries. We
551 // won't get much benefit from dylibs because LLVM will have already
552 // stripped away as much as it could. This has not been seen to impact
553 // link times negatively.
555 // -dead_strip can't be part of the pre_link_args because it's also used
556 // for partial linking when using multiple codegen units (-r). So we
558 if self.sess.target.is_like_osx {
559 self.linker_arg("-dead_strip");
561 // If we're building a dylib, we don't use --gc-sections because LLVM
562 // has already done the best it can do, and we also don't want to
563 // eliminate the metadata. If we're building an executable, however,
564 // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
566 } else if (self.sess.target.linker_is_gnu || self.sess.target.is_like_wasm)
569 self.linker_arg("--gc-sections");
573 fn no_gc_sections(&mut self) {
574 if self.sess.target.is_like_osx {
575 self.linker_arg("-no_dead_strip");
576 } else if self.sess.target.linker_is_gnu || self.sess.target.is_like_wasm {
577 self.linker_arg("--no-gc-sections");
581 fn optimize(&mut self) {
582 if !self.sess.target.linker_is_gnu && !self.sess.target.is_like_wasm {
586 // GNU-style linkers support optimization with -O. GNU ld doesn't
587 // need a numeric argument, but other linkers do.
588 if self.sess.opts.optimize == config::OptLevel::Default
589 || self.sess.opts.optimize == config::OptLevel::Aggressive
591 self.linker_arg("-O1");
595 fn pgo_gen(&mut self) {
596 if !self.sess.target.linker_is_gnu {
600 // If we're doing PGO generation stuff and on a GNU-like linker, use the
601 // "-u" flag to properly pull in the profiler runtime bits.
603 // This is because LLVM otherwise won't add the needed initialization
604 // for us on Linux (though the extra flag should be harmless if it
607 // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
609 // Though it may be worth to try to revert those changes upstream, since
610 // the overhead of the initialization should be minor.
612 self.cmd.arg("__llvm_profile_runtime");
615 fn control_flow_guard(&mut self) {}
617 fn debuginfo(&mut self, strip: Strip) {
618 // MacOS linker doesn't support stripping symbols directly anymore.
619 if self.sess.target.is_like_osx {
625 Strip::Debuginfo => {
626 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 && self.sess.target.override_export_symbols.is_none()
653 // We manually create a list of exported symbols to ensure we don't expose any more.
654 // The object files have far more public symbols than we actually want to export,
655 // so we hide them all here.
657 if !self.sess.target.limit_rdylib_exports {
661 if crate_type == CrateType::ProcMacro {
665 let is_windows = self.sess.target.is_like_windows;
666 let path = tmpdir.join(if is_windows { "list.def" } else { "list" });
668 debug!("EXPORTED SYMBOLS:");
670 if self.sess.target.is_like_osx {
671 // Write a plain, newline-separated list of symbols
672 let res: io::Result<()> = try {
673 let mut f = BufWriter::new(File::create(&path)?);
676 writeln!(f, "_{}", sym)?;
679 if let Err(e) = res {
680 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
682 } else if is_windows {
683 let res: io::Result<()> = try {
684 let mut f = BufWriter::new(File::create(&path)?);
686 // .def file similar to MSVC one but without LIBRARY section
687 // because LD doesn't like when it's empty
688 writeln!(f, "EXPORTS")?;
689 for symbol in symbols {
690 debug!(" _{}", symbol);
691 writeln!(f, " {}", symbol)?;
694 if let Err(e) = res {
695 self.sess.fatal(&format!("failed to write list.def file: {}", e));
698 // Write an LD version script
699 let res: io::Result<()> = try {
700 let mut f = BufWriter::new(File::create(&path)?);
702 if !symbols.is_empty() {
703 writeln!(f, " global:")?;
706 writeln!(f, " {};", sym)?;
709 writeln!(f, "\n local:\n *;\n}};")?;
711 if let Err(e) = res {
712 self.sess.fatal(&format!("failed to write version script: {}", e));
716 if self.sess.target.is_like_osx {
717 self.linker_args(&[OsString::from("-exported_symbols_list"), path.into()]);
718 } else if self.sess.target.is_like_solaris {
719 self.linker_args(&[OsString::from("-M"), path.into()]);
722 self.linker_arg(path);
724 let mut arg = OsString::from("--version-script=");
726 self.linker_arg(arg);
731 fn exported_symbol_means_used_symbol(&self) -> bool {
732 self.sess.target.is_like_windows || self.sess.target.is_like_osx
735 fn subsystem(&mut self, subsystem: &str) {
736 self.linker_arg("--subsystem");
737 self.linker_arg(&subsystem);
740 fn reset_per_library_state(&mut self) {
741 self.hint_dynamic(); // Reset to default before returning the composed command line.
744 fn group_start(&mut self) {
745 if self.takes_hints() {
746 self.linker_arg("--start-group");
750 fn group_end(&mut self) {
751 if self.takes_hints() {
752 self.linker_arg("--end-group");
756 fn linker_plugin_lto(&mut self) {
757 match self.sess.opts.cg.linker_plugin_lto {
758 LinkerPluginLto::Disabled => {
761 LinkerPluginLto::LinkerPluginAuto => {
762 self.push_linker_plugin_lto_args(None);
764 LinkerPluginLto::LinkerPlugin(ref path) => {
765 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
770 // Add the `GNU_EH_FRAME` program header which is required to locate unwinding information.
771 // Some versions of `gcc` add it implicitly, some (e.g. `musl-gcc`) don't,
772 // so we just always add it.
773 fn add_eh_frame_header(&mut self) {
774 self.linker_arg("--eh-frame-hdr");
777 fn add_no_exec(&mut self) {
778 if self.sess.target.is_like_windows {
779 self.linker_arg("--nxcompat");
780 } else if self.sess.target.linker_is_gnu {
781 self.linker_arg("-znoexecstack");
785 fn add_as_needed(&mut self) {
786 if self.sess.target.linker_is_gnu && !self.sess.target.is_like_windows {
787 self.linker_arg("--as-needed");
788 } else if self.sess.target.is_like_solaris {
789 // -z ignore is the Solaris equivalent to the GNU ld --as-needed option
790 self.linker_args(&["-z", "ignore"]);
795 pub struct MsvcLinker<'a> {
800 impl<'a> Linker for MsvcLinker<'a> {
801 fn cmd(&mut self) -> &mut Command {
805 fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
807 LinkOutputKind::DynamicNoPicExe
808 | LinkOutputKind::DynamicPicExe
809 | LinkOutputKind::StaticNoPicExe
810 | LinkOutputKind::StaticPicExe => {}
811 LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
812 self.cmd.arg("/DLL");
813 let mut arg: OsString = "/IMPLIB:".into();
814 arg.push(out_filename.with_extension("dll.lib"));
817 LinkOutputKind::WasiReactorExe => {
818 panic!("can't link as reactor on non-wasi target");
823 fn link_rlib(&mut self, lib: &Path) {
826 fn add_object(&mut self, path: &Path) {
830 fn gc_sections(&mut self, _keep_metadata: bool) {
831 // MSVC's ICF (Identical COMDAT Folding) link optimization is
832 // slow for Rust and thus we disable it by default when not in
833 // optimization build.
834 if self.sess.opts.optimize != config::OptLevel::No {
835 self.cmd.arg("/OPT:REF,ICF");
837 // It is necessary to specify NOICF here, because /OPT:REF
838 // implies ICF by default.
839 self.cmd.arg("/OPT:REF,NOICF");
843 fn no_gc_sections(&mut self) {
844 self.cmd.arg("/OPT:NOREF,NOICF");
847 fn link_dylib(&mut self, lib: Symbol, verbatim: bool, _as_needed: bool) {
848 self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
851 fn link_rust_dylib(&mut self, lib: Symbol, path: &Path) {
852 // When producing a dll, the MSVC linker may not actually emit a
853 // `foo.lib` file if the dll doesn't actually export any symbols, so we
854 // check to see if the file is there and just omit linking to it if it's
856 let name = format!("{}.dll.lib", lib);
857 if path.join(&name).exists() {
862 fn link_staticlib(&mut self, lib: Symbol, verbatim: bool) {
863 self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
866 fn full_relro(&mut self) {
870 fn partial_relro(&mut self) {
874 fn no_relro(&mut self) {
878 fn no_crt_objects(&mut self) {
882 fn no_default_libraries(&mut self) {
883 self.cmd.arg("/NODEFAULTLIB");
886 fn include_path(&mut self, path: &Path) {
887 let mut arg = OsString::from("/LIBPATH:");
892 fn output_filename(&mut self, path: &Path) {
893 let mut arg = OsString::from("/OUT:");
898 fn framework_path(&mut self, _path: &Path) {
899 bug!("frameworks are not supported on windows")
901 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
902 bug!("frameworks are not supported on windows")
905 fn link_whole_staticlib(&mut self, lib: Symbol, verbatim: bool, _search_path: &[PathBuf]) {
906 self.cmd.arg(format!("/WHOLEARCHIVE:{}{}", lib, if verbatim { "" } else { ".lib" }));
908 fn link_whole_rlib(&mut self, path: &Path) {
909 let mut arg = OsString::from("/WHOLEARCHIVE:");
913 fn optimize(&mut self) {
914 // Needs more investigation of `/OPT` arguments
917 fn pgo_gen(&mut self) {
918 // Nothing needed here.
921 fn control_flow_guard(&mut self) {
922 self.cmd.arg("/guard:cf");
925 fn debuginfo(&mut self, strip: Strip) {
928 // This will cause the Microsoft linker to generate a PDB file
929 // from the CodeView line tables in the object files.
930 self.cmd.arg("/DEBUG");
932 // This will cause the Microsoft linker to embed .natvis info into the PDB file
933 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
934 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
935 for entry in natvis_dir {
938 let path = entry.path();
939 if path.extension() == Some("natvis".as_ref()) {
940 let mut arg = OsString::from("/NATVIS:");
947 .warn(&format!("error enumerating natvis directory: {}", err));
953 Strip::Debuginfo | Strip::Symbols => {
954 self.cmd.arg("/DEBUG:NONE");
959 // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
960 // export symbols from a dynamic library. When building a dynamic library,
961 // however, we're going to want some symbols exported, so this function
962 // generates a DEF file which lists all the symbols.
964 // The linker will read this `*.def` file and export all the symbols from
965 // the dynamic library. Note that this is not as simple as just exporting
966 // all the symbols in the current crate (as specified by `codegen.reachable`)
967 // but rather we also need to possibly export the symbols of upstream
968 // crates. Upstream rlibs may be linked statically to this dynamic library,
969 // in which case they may continue to transitively be used and hence need
970 // their symbols exported.
971 fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]) {
972 // Symbol visibility takes care of this typically
973 if crate_type == CrateType::Executable {
977 let path = tmpdir.join("lib.def");
978 let res: io::Result<()> = try {
979 let mut f = BufWriter::new(File::create(&path)?);
981 // Start off with the standard module name header and then go
982 // straight to exports.
983 writeln!(f, "LIBRARY")?;
984 writeln!(f, "EXPORTS")?;
985 for symbol in symbols {
986 debug!(" _{}", symbol);
987 writeln!(f, " {}", symbol)?;
990 if let Err(e) = res {
991 self.sess.fatal(&format!("failed to write lib.def file: {}", e));
993 let mut arg = OsString::from("/DEF:");
998 fn subsystem(&mut self, subsystem: &str) {
999 // Note that previous passes of the compiler validated this subsystem,
1000 // so we just blindly pass it to the linker.
1001 self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
1003 // Windows has two subsystems we're interested in right now, the console
1004 // and windows subsystems. These both implicitly have different entry
1005 // points (starting symbols). The console entry point starts with
1006 // `mainCRTStartup` and the windows entry point starts with
1007 // `WinMainCRTStartup`. These entry points, defined in system libraries,
1008 // will then later probe for either `main` or `WinMain`, respectively to
1009 // start the application.
1011 // In Rust we just always generate a `main` function so we want control
1012 // to always start there, so we force the entry point on the windows
1013 // subsystem to be `mainCRTStartup` to get everything booted up
1016 // For more information see RFC #1665
1017 if subsystem == "windows" {
1018 self.cmd.arg("/ENTRY:mainCRTStartup");
1022 // MSVC doesn't need group indicators
1023 fn group_start(&mut self) {}
1024 fn group_end(&mut self) {}
1026 fn linker_plugin_lto(&mut self) {
1030 fn add_no_exec(&mut self) {
1031 self.cmd.arg("/NXCOMPAT");
1035 pub struct EmLinker<'a> {
1040 impl<'a> Linker for EmLinker<'a> {
1041 fn cmd(&mut self) -> &mut Command {
1045 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1047 fn include_path(&mut self, path: &Path) {
1048 self.cmd.arg("-L").arg(path);
1051 fn link_staticlib(&mut self, lib: Symbol, _verbatim: bool) {
1052 self.cmd.arg("-l").sym_arg(lib);
1055 fn output_filename(&mut self, path: &Path) {
1056 self.cmd.arg("-o").arg(path);
1059 fn add_object(&mut self, path: &Path) {
1063 fn link_dylib(&mut self, lib: Symbol, verbatim: bool, _as_needed: bool) {
1064 // Emscripten always links statically
1065 self.link_staticlib(lib, verbatim);
1068 fn link_whole_staticlib(&mut self, lib: Symbol, verbatim: bool, _search_path: &[PathBuf]) {
1070 self.link_staticlib(lib, verbatim);
1073 fn link_whole_rlib(&mut self, lib: &Path) {
1075 self.link_rlib(lib);
1078 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1079 self.link_dylib(lib, false, true);
1082 fn link_rlib(&mut self, lib: &Path) {
1083 self.add_object(lib);
1086 fn full_relro(&mut self) {
1090 fn partial_relro(&mut self) {
1094 fn no_relro(&mut self) {
1098 fn framework_path(&mut self, _path: &Path) {
1099 bug!("frameworks are not supported on Emscripten")
1102 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1103 bug!("frameworks are not supported on Emscripten")
1106 fn gc_sections(&mut self, _keep_metadata: bool) {
1110 fn no_gc_sections(&mut self) {
1114 fn optimize(&mut self) {
1115 // Emscripten performs own optimizations
1116 self.cmd.arg(match self.sess.opts.optimize {
1117 OptLevel::No => "-O0",
1118 OptLevel::Less => "-O1",
1119 OptLevel::Default => "-O2",
1120 OptLevel::Aggressive => "-O3",
1121 OptLevel::Size => "-Os",
1122 OptLevel::SizeMin => "-Oz",
1124 // Unusable until https://github.com/rust-lang/rust/issues/38454 is resolved
1125 self.cmd.args(&["--memory-init-file", "0"]);
1128 fn pgo_gen(&mut self) {
1129 // noop, but maybe we need something like the gnu linker?
1132 fn control_flow_guard(&mut self) {}
1134 fn debuginfo(&mut self, _strip: Strip) {
1135 // Preserve names or generate source maps depending on debug info
1136 self.cmd.arg(match self.sess.opts.debuginfo {
1137 DebugInfo::None => "-g0",
1138 DebugInfo::Limited => "-g3",
1139 DebugInfo::Full => "-g4",
1143 fn no_crt_objects(&mut self) {}
1145 fn no_default_libraries(&mut self) {
1146 self.cmd.args(&["-s", "DEFAULT_LIBRARY_FUNCS_TO_INCLUDE=[]"]);
1149 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1150 debug!("EXPORTED SYMBOLS:");
1154 let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
1155 let mut encoded = String::new();
1158 let mut encoder = json::Encoder::new(&mut encoded);
1159 let res = encoder.emit_seq(symbols.len(), |encoder| {
1160 for (i, sym) in symbols.iter().enumerate() {
1161 encoder.emit_seq_elt(i, |encoder| encoder.emit_str(&("_".to_owned() + sym)))?;
1165 if let Err(e) = res {
1166 self.sess.fatal(&format!("failed to encode exported symbols: {}", e));
1169 debug!("{}", encoded);
1175 fn subsystem(&mut self, _subsystem: &str) {
1179 // Appears not necessary on Emscripten
1180 fn group_start(&mut self) {}
1181 fn group_end(&mut self) {}
1183 fn linker_plugin_lto(&mut self) {
1188 pub struct WasmLd<'a> {
1193 impl<'a> WasmLd<'a> {
1194 fn new(mut cmd: Command, sess: &'a Session) -> WasmLd<'a> {
1195 // If the atomics feature is enabled for wasm then we need a whole bunch
1198 // * `--shared-memory` - the link won't even succeed without this, flags
1199 // the one linear memory as `shared`
1201 // * `--max-memory=1G` - when specifying a shared memory this must also
1202 // be specified. We conservatively choose 1GB but users should be able
1203 // to override this with `-C link-arg`.
1205 // * `--import-memory` - it doesn't make much sense for memory to be
1206 // exported in a threaded module because typically you're
1207 // sharing memory and instantiating the module multiple times. As a
1208 // result if it were exported then we'd just have no sharing.
1210 // * `--export=__wasm_init_memory` - when using `--passive-segments` the
1211 // linker will synthesize this function, and so we need to make sure
1212 // that our usage of `--export` below won't accidentally cause this
1213 // function to get deleted.
1215 // * `--export=*tls*` - when `#[thread_local]` symbols are used these
1216 // symbols are how the TLS segments are initialized and configured.
1217 if sess.target_features.contains(&sym::atomics) {
1218 cmd.arg("--shared-memory");
1219 cmd.arg("--max-memory=1073741824");
1220 cmd.arg("--import-memory");
1221 cmd.arg("--export=__wasm_init_memory");
1222 cmd.arg("--export=__wasm_init_tls");
1223 cmd.arg("--export=__tls_size");
1224 cmd.arg("--export=__tls_align");
1225 cmd.arg("--export=__tls_base");
1227 WasmLd { cmd, sess }
1231 impl<'a> Linker for WasmLd<'a> {
1232 fn cmd(&mut self) -> &mut Command {
1236 fn set_output_kind(&mut self, output_kind: LinkOutputKind, _out_filename: &Path) {
1238 LinkOutputKind::DynamicNoPicExe
1239 | LinkOutputKind::DynamicPicExe
1240 | LinkOutputKind::StaticNoPicExe
1241 | LinkOutputKind::StaticPicExe => {}
1242 LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1243 self.cmd.arg("--no-entry");
1245 LinkOutputKind::WasiReactorExe => {
1246 self.cmd.arg("--entry");
1247 self.cmd.arg("_initialize");
1252 fn link_dylib(&mut self, lib: Symbol, _verbatim: bool, _as_needed: bool) {
1253 self.cmd.arg("-l").sym_arg(lib);
1256 fn link_staticlib(&mut self, lib: Symbol, _verbatim: bool) {
1257 self.cmd.arg("-l").sym_arg(lib);
1260 fn link_rlib(&mut self, lib: &Path) {
1264 fn include_path(&mut self, path: &Path) {
1265 self.cmd.arg("-L").arg(path);
1268 fn framework_path(&mut self, _path: &Path) {
1269 panic!("frameworks not supported")
1272 fn output_filename(&mut self, path: &Path) {
1273 self.cmd.arg("-o").arg(path);
1276 fn add_object(&mut self, path: &Path) {
1280 fn full_relro(&mut self) {}
1282 fn partial_relro(&mut self) {}
1284 fn no_relro(&mut self) {}
1286 fn link_rust_dylib(&mut self, lib: Symbol, _path: &Path) {
1287 self.cmd.arg("-l").sym_arg(lib);
1290 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1291 panic!("frameworks not supported")
1294 fn link_whole_staticlib(&mut self, lib: Symbol, _verbatim: bool, _search_path: &[PathBuf]) {
1295 self.cmd.arg("-l").sym_arg(lib);
1298 fn link_whole_rlib(&mut self, lib: &Path) {
1302 fn gc_sections(&mut self, _keep_metadata: bool) {
1303 self.cmd.arg("--gc-sections");
1306 fn no_gc_sections(&mut self) {
1307 self.cmd.arg("--no-gc-sections");
1310 fn optimize(&mut self) {
1311 self.cmd.arg(match self.sess.opts.optimize {
1312 OptLevel::No => "-O0",
1313 OptLevel::Less => "-O1",
1314 OptLevel::Default => "-O2",
1315 OptLevel::Aggressive => "-O3",
1316 // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1318 OptLevel::Size => "-O2",
1319 OptLevel::SizeMin => "-O2",
1323 fn pgo_gen(&mut self) {}
1325 fn debuginfo(&mut self, strip: Strip) {
1328 Strip::Debuginfo => {
1329 self.cmd.arg("--strip-debug");
1332 self.cmd.arg("--strip-all");
1337 fn control_flow_guard(&mut self) {}
1339 fn no_crt_objects(&mut self) {}
1341 fn no_default_libraries(&mut self) {}
1343 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1344 for sym in symbols {
1345 self.cmd.arg("--export").arg(&sym);
1348 // LLD will hide these otherwise-internal symbols since it only exports
1349 // symbols explicitly passed via the `--export` flags above and hides all
1350 // others. Various bits and pieces of tooling use this, so be sure these
1351 // symbols make their way out of the linker as well.
1352 self.cmd.arg("--export=__heap_base");
1353 self.cmd.arg("--export=__data_end");
1356 fn subsystem(&mut self, _subsystem: &str) {}
1358 // Not needed for now with LLD
1359 fn group_start(&mut self) {}
1360 fn group_end(&mut self) {}
1362 fn linker_plugin_lto(&mut self) {
1363 // Do nothing for now
1367 /// Linker shepherd script for L4Re (Fiasco)
1368 pub struct L4Bender<'a> {
1371 hinted_static: bool,
1374 impl<'a> Linker for L4Bender<'a> {
1375 fn link_dylib(&mut self, _lib: Symbol, _verbatim: bool, _as_needed: bool) {
1376 bug!("dylibs are not supported on L4Re");
1378 fn link_staticlib(&mut self, lib: Symbol, _verbatim: bool) {
1380 self.cmd.arg(format!("-PC{}", lib));
1382 fn link_rlib(&mut self, lib: &Path) {
1386 fn include_path(&mut self, path: &Path) {
1387 self.cmd.arg("-L").arg(path);
1389 fn framework_path(&mut self, _: &Path) {
1390 bug!("frameworks are not supported on L4Re");
1392 fn output_filename(&mut self, path: &Path) {
1393 self.cmd.arg("-o").arg(path);
1396 fn add_object(&mut self, path: &Path) {
1400 fn full_relro(&mut self) {
1401 self.cmd.arg("-zrelro");
1402 self.cmd.arg("-znow");
1405 fn partial_relro(&mut self) {
1406 self.cmd.arg("-zrelro");
1409 fn no_relro(&mut self) {
1410 self.cmd.arg("-znorelro");
1413 fn cmd(&mut self) -> &mut Command {
1417 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1419 fn link_rust_dylib(&mut self, _: Symbol, _: &Path) {
1420 panic!("Rust dylibs not supported");
1423 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1424 bug!("frameworks not supported on L4Re");
1427 fn link_whole_staticlib(&mut self, lib: Symbol, _verbatim: bool, _search_path: &[PathBuf]) {
1429 self.cmd.arg("--whole-archive").arg(format!("-l{}", lib));
1430 self.cmd.arg("--no-whole-archive");
1433 fn link_whole_rlib(&mut self, lib: &Path) {
1435 self.cmd.arg("--whole-archive").arg(lib).arg("--no-whole-archive");
1438 fn gc_sections(&mut self, keep_metadata: bool) {
1440 self.cmd.arg("--gc-sections");
1444 fn no_gc_sections(&mut self) {
1445 self.cmd.arg("--no-gc-sections");
1448 fn optimize(&mut self) {
1449 // GNU-style linkers support optimization with -O. GNU ld doesn't
1450 // need a numeric argument, but other linkers do.
1451 if self.sess.opts.optimize == config::OptLevel::Default
1452 || self.sess.opts.optimize == config::OptLevel::Aggressive
1454 self.cmd.arg("-O1");
1458 fn pgo_gen(&mut self) {}
1460 fn debuginfo(&mut self, strip: Strip) {
1463 Strip::Debuginfo => {
1464 self.cmd().arg("--strip-debug");
1467 self.cmd().arg("--strip-all");
1472 fn no_default_libraries(&mut self) {
1473 self.cmd.arg("-nostdlib");
1476 fn export_symbols(&mut self, _: &Path, _: CrateType, _: &[String]) {
1477 // ToDo, not implemented, copy from GCC
1478 self.sess.warn("exporting symbols not implemented yet for L4Bender");
1482 fn exported_symbol_means_used_symbol(&self) -> bool {
1486 fn subsystem(&mut self, subsystem: &str) {
1487 self.cmd.arg(&format!("--subsystem {}", subsystem));
1490 fn reset_per_library_state(&mut self) {
1491 self.hint_static(); // Reset to default before returning the composed command line.
1494 fn group_start(&mut self) {
1495 self.cmd.arg("--start-group");
1498 fn group_end(&mut self) {
1499 self.cmd.arg("--end-group");
1502 fn linker_plugin_lto(&mut self) {}
1504 fn control_flow_guard(&mut self) {}
1506 fn no_crt_objects(&mut self) {}
1509 impl<'a> L4Bender<'a> {
1510 pub fn new(cmd: Command, sess: &'a Session) -> L4Bender<'a> {
1511 L4Bender { cmd: cmd, sess: sess, hinted_static: false }
1514 fn hint_static(&mut self) {
1515 if !self.hinted_static {
1516 self.cmd.arg("-static");
1517 self.hinted_static = true;
1522 pub(crate) fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1523 if let Some(ref exports) = tcx.sess.target.override_export_symbols {
1524 return exports.clone();
1527 let mut symbols = Vec::new();
1529 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1530 for &(symbol, info) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1531 if info.level.is_below_threshold(export_threshold) {
1532 symbols.push(symbol_export::symbol_name_for_instance_in_crate(
1540 let formats = tcx.dependency_formats(());
1541 let deps = formats.iter().find_map(|(t, list)| (*t == crate_type).then_some(list)).unwrap();
1543 for (index, dep_format) in deps.iter().enumerate() {
1544 let cnum = CrateNum::new(index + 1);
1545 // For each dependency that we are linking to statically ...
1546 if *dep_format == Linkage::Static {
1547 // ... we add its symbol list to our export list.
1548 for &(symbol, info) in tcx.exported_symbols(cnum).iter() {
1549 if !info.level.is_below_threshold(export_threshold) {
1553 symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1561 pub(crate) fn linked_symbols(
1563 crate_type: CrateType,
1564 ) -> Vec<(String, SymbolExportKind)> {
1566 CrateType::Executable | CrateType::Cdylib => (),
1567 CrateType::Staticlib | CrateType::ProcMacro | CrateType::Rlib | CrateType::Dylib => {
1572 let mut symbols = Vec::new();
1574 let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1575 for &(symbol, info) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1576 if info.level.is_below_threshold(export_threshold) || info.used {
1578 symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, LOCAL_CRATE),
1584 let formats = tcx.dependency_formats(());
1585 let deps = formats.iter().find_map(|(t, list)| (*t == crate_type).then_some(list)).unwrap();
1587 for (index, dep_format) in deps.iter().enumerate() {
1588 let cnum = CrateNum::new(index + 1);
1589 // For each dependency that we are linking to statically ...
1590 if *dep_format == Linkage::Static {
1591 // ... we add its symbol list to our export list.
1592 for &(symbol, info) in tcx.exported_symbols(cnum).iter() {
1593 if info.level.is_below_threshold(export_threshold) || info.used {
1595 symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum),
1606 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1607 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1608 pub struct PtxLinker<'a> {
1613 impl<'a> Linker for PtxLinker<'a> {
1614 fn cmd(&mut self) -> &mut Command {
1618 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1620 fn link_rlib(&mut self, path: &Path) {
1621 self.cmd.arg("--rlib").arg(path);
1624 fn link_whole_rlib(&mut self, path: &Path) {
1625 self.cmd.arg("--rlib").arg(path);
1628 fn include_path(&mut self, path: &Path) {
1629 self.cmd.arg("-L").arg(path);
1632 fn debuginfo(&mut self, _strip: Strip) {
1633 self.cmd.arg("--debug");
1636 fn add_object(&mut self, path: &Path) {
1637 self.cmd.arg("--bitcode").arg(path);
1640 fn optimize(&mut self) {
1641 match self.sess.lto() {
1642 Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1643 self.cmd.arg("-Olto");
1650 fn output_filename(&mut self, path: &Path) {
1651 self.cmd.arg("-o").arg(path);
1654 fn link_dylib(&mut self, _lib: Symbol, _verbatim: bool, _as_needed: bool) {
1655 panic!("external dylibs not supported")
1658 fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1659 panic!("external dylibs not supported")
1662 fn link_staticlib(&mut self, _lib: Symbol, _verbatim: bool) {
1663 panic!("staticlibs not supported")
1666 fn link_whole_staticlib(&mut self, _lib: Symbol, _verbatim: bool, _search_path: &[PathBuf]) {
1667 panic!("staticlibs not supported")
1670 fn framework_path(&mut self, _path: &Path) {
1671 panic!("frameworks not supported")
1674 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1675 panic!("frameworks not supported")
1678 fn full_relro(&mut self) {}
1680 fn partial_relro(&mut self) {}
1682 fn no_relro(&mut self) {}
1684 fn gc_sections(&mut self, _keep_metadata: bool) {}
1686 fn no_gc_sections(&mut self) {}
1688 fn pgo_gen(&mut self) {}
1690 fn no_crt_objects(&mut self) {}
1692 fn no_default_libraries(&mut self) {}
1694 fn control_flow_guard(&mut self) {}
1696 fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, _symbols: &[String]) {}
1698 fn subsystem(&mut self, _subsystem: &str) {}
1700 fn group_start(&mut self) {}
1702 fn group_end(&mut self) {}
1704 fn linker_plugin_lto(&mut self) {}
1707 pub struct BpfLinker<'a> {
1712 impl<'a> Linker for BpfLinker<'a> {
1713 fn cmd(&mut self) -> &mut Command {
1717 fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1719 fn link_rlib(&mut self, path: &Path) {
1723 fn link_whole_rlib(&mut self, path: &Path) {
1727 fn include_path(&mut self, path: &Path) {
1728 self.cmd.arg("-L").arg(path);
1731 fn debuginfo(&mut self, _strip: Strip) {
1732 self.cmd.arg("--debug");
1735 fn add_object(&mut self, path: &Path) {
1739 fn optimize(&mut self) {
1740 self.cmd.arg(match self.sess.opts.optimize {
1741 OptLevel::No => "-O0",
1742 OptLevel::Less => "-O1",
1743 OptLevel::Default => "-O2",
1744 OptLevel::Aggressive => "-O3",
1745 OptLevel::Size => "-Os",
1746 OptLevel::SizeMin => "-Oz",
1750 fn output_filename(&mut self, path: &Path) {
1751 self.cmd.arg("-o").arg(path);
1754 fn link_dylib(&mut self, _lib: Symbol, _verbatim: bool, _as_needed: bool) {
1755 panic!("external dylibs not supported")
1758 fn link_rust_dylib(&mut self, _lib: Symbol, _path: &Path) {
1759 panic!("external dylibs not supported")
1762 fn link_staticlib(&mut self, _lib: Symbol, _verbatim: bool) {
1763 panic!("staticlibs not supported")
1766 fn link_whole_staticlib(&mut self, _lib: Symbol, _verbatim: bool, _search_path: &[PathBuf]) {
1767 panic!("staticlibs not supported")
1770 fn framework_path(&mut self, _path: &Path) {
1771 panic!("frameworks not supported")
1774 fn link_framework(&mut self, _framework: Symbol, _as_needed: bool) {
1775 panic!("frameworks not supported")
1778 fn full_relro(&mut self) {}
1780 fn partial_relro(&mut self) {}
1782 fn no_relro(&mut self) {}
1784 fn gc_sections(&mut self, _keep_metadata: bool) {}
1786 fn no_gc_sections(&mut self) {}
1788 fn pgo_gen(&mut self) {}
1790 fn no_crt_objects(&mut self) {}
1792 fn no_default_libraries(&mut self) {}
1794 fn control_flow_guard(&mut self) {}
1796 fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1797 let path = tmpdir.join("symbols");
1798 let res: io::Result<()> = try {
1799 let mut f = BufWriter::new(File::create(&path)?);
1800 for sym in symbols {
1801 writeln!(f, "{}", sym)?;
1804 if let Err(e) = res {
1805 self.sess.fatal(&format!("failed to write symbols file: {}", e));
1807 self.cmd.arg("--export-symbols").arg(&path);
1811 fn subsystem(&mut self, _subsystem: &str) {}
1813 fn group_start(&mut self) {}
1815 fn group_end(&mut self) {}
1817 fn linker_plugin_lto(&mut self) {}