]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_ssa/src/back/linker.rs
Auto merge of #102026 - Bryanskiy:resolve_update, r=petrochenkov
[rust.git] / compiler / rustc_codegen_ssa / src / back / linker.rs
1 use super::command::Command;
2 use super::symbol_export;
3 use crate::errors;
4 use rustc_span::symbol::sym;
5
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};
12
13 use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
14 use rustc_metadata::find_native_static_library;
15 use rustc_middle::middle::dependency_format::Linkage;
16 use rustc_middle::middle::exported_symbols::{ExportedSymbol, SymbolExportInfo, SymbolExportKind};
17 use rustc_middle::ty::TyCtxt;
18 use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip};
19 use rustc_session::Session;
20 use rustc_target::spec::{Cc, LinkOutputKind, LinkerFlavor, Lld};
21
22 use cc::windows_registry;
23
24 /// Disables non-English messages from localized linkers.
25 /// Such messages may cause issues with text encoding on Windows (#35785)
26 /// and prevent inspection of linker output in case of errors, which we occasionally do.
27 /// This should be acceptable because other messages from rustc are in English anyway,
28 /// and may also be desirable to improve searchability of the linker diagnostics.
29 pub fn disable_localization(linker: &mut Command) {
30     // No harm in setting both env vars simultaneously.
31     // Unix-style linkers.
32     linker.env("LC_ALL", "C");
33     // MSVC's `link.exe`.
34     linker.env("VSLANG", "1033");
35 }
36
37 // The third parameter is for env vars, used on windows to set up the
38 // path for MSVC to find its DLLs, and gcc to find its bundled
39 // toolchain
40 pub fn get_linker<'a>(
41     sess: &'a Session,
42     linker: &Path,
43     flavor: LinkerFlavor,
44     self_contained: bool,
45     target_cpu: &'a str,
46 ) -> Box<dyn Linker + 'a> {
47     let msvc_tool = windows_registry::find_tool(&sess.opts.target_triple.triple(), "link.exe");
48
49     // If our linker looks like a batch script on Windows then to execute this
50     // we'll need to spawn `cmd` explicitly. This is primarily done to handle
51     // emscripten where the linker is `emcc.bat` and needs to be spawned as
52     // `cmd /c emcc.bat ...`.
53     //
54     // This worked historically but is needed manually since #42436 (regression
55     // was tagged as #42791) and some more info can be found on #44443 for
56     // emscripten itself.
57     let mut cmd = match linker.to_str() {
58         Some(linker) if cfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
59         _ => match flavor {
60             LinkerFlavor::Gnu(Cc::No, Lld::Yes)
61             | LinkerFlavor::Darwin(Cc::No, Lld::Yes)
62             | LinkerFlavor::WasmLld(Cc::No)
63             | LinkerFlavor::Msvc(Lld::Yes) => Command::lld(linker, flavor.lld_flavor()),
64             LinkerFlavor::Msvc(Lld::No)
65                 if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() =>
66             {
67                 Command::new(msvc_tool.as_ref().map_or(linker, |t| t.path()))
68             }
69             _ => Command::new(linker),
70         },
71     };
72
73     // UWP apps have API restrictions enforced during Store submissions.
74     // To comply with the Windows App Certification Kit,
75     // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
76     let t = &sess.target;
77     if matches!(flavor, LinkerFlavor::Msvc(..)) && t.vendor == "uwp" {
78         if let Some(ref tool) = msvc_tool {
79             let original_path = tool.path();
80             if let Some(ref root_lib_path) = original_path.ancestors().nth(4) {
81                 let arch = match t.arch.as_ref() {
82                     "x86_64" => Some("x64"),
83                     "x86" => Some("x86"),
84                     "aarch64" => Some("arm64"),
85                     "arm" => Some("arm"),
86                     _ => None,
87                 };
88                 if let Some(ref a) = arch {
89                     // FIXME: Move this to `fn linker_with_args`.
90                     let mut arg = OsString::from("/LIBPATH:");
91                     arg.push(format!("{}\\lib\\{}\\store", root_lib_path.display(), a));
92                     cmd.arg(&arg);
93                 } else {
94                     warn!("arch is not supported");
95                 }
96             } else {
97                 warn!("MSVC root path lib location not found");
98             }
99         } else {
100             warn!("link.exe not found");
101         }
102     }
103
104     // The compiler's sysroot often has some bundled tools, so add it to the
105     // PATH for the child.
106     let mut new_path = sess.get_tools_search_paths(self_contained);
107     let mut msvc_changed_path = false;
108     if sess.target.is_like_msvc {
109         if let Some(ref tool) = msvc_tool {
110             cmd.args(tool.args());
111             for &(ref k, ref v) in tool.env() {
112                 if k == "PATH" {
113                     new_path.extend(env::split_paths(v));
114                     msvc_changed_path = true;
115                 } else {
116                     cmd.env(k, v);
117                 }
118             }
119         }
120     }
121
122     if !msvc_changed_path {
123         if let Some(path) = env::var_os("PATH") {
124             new_path.extend(env::split_paths(&path));
125         }
126     }
127     cmd.env("PATH", env::join_paths(new_path).unwrap());
128
129     // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
130     // to the linker args construction.
131     assert!(cmd.get_args().is_empty() || sess.target.vendor == "uwp");
132     match flavor {
133         LinkerFlavor::Unix(Cc::No) if sess.target.os == "l4re" => {
134             Box::new(L4Bender::new(cmd, sess)) as Box<dyn Linker>
135         }
136         LinkerFlavor::WasmLld(Cc::No) => Box::new(WasmLd::new(cmd, sess)) as Box<dyn Linker>,
137         LinkerFlavor::Gnu(cc, _)
138         | LinkerFlavor::Darwin(cc, _)
139         | LinkerFlavor::WasmLld(cc)
140         | LinkerFlavor::Unix(cc) => Box::new(GccLinker {
141             cmd,
142             sess,
143             target_cpu,
144             hinted_static: false,
145             is_ld: cc == Cc::No,
146             is_gnu: flavor.is_gnu(),
147         }) as Box<dyn Linker>,
148         LinkerFlavor::Msvc(..) => Box::new(MsvcLinker { cmd, sess }) as Box<dyn Linker>,
149         LinkerFlavor::EmCc => Box::new(EmLinker { cmd, sess }) as Box<dyn Linker>,
150         LinkerFlavor::Bpf => Box::new(BpfLinker { cmd, sess }) as Box<dyn Linker>,
151         LinkerFlavor::Ptx => Box::new(PtxLinker { cmd, sess }) as Box<dyn Linker>,
152     }
153 }
154
155 /// Linker abstraction used by `back::link` to build up the command to invoke a
156 /// linker.
157 ///
158 /// This trait is the total list of requirements needed by `back::link` and
159 /// represents the meaning of each option being passed down. This trait is then
160 /// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
161 /// MSVC linker (e.g., `link.exe`) is being used.
162 pub trait Linker {
163     fn cmd(&mut self) -> &mut Command;
164     fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path);
165     fn link_dylib(&mut self, lib: &str, verbatim: bool, as_needed: bool);
166     fn link_rust_dylib(&mut self, lib: &str, path: &Path);
167     fn link_framework(&mut self, framework: &str, as_needed: bool);
168     fn link_staticlib(&mut self, lib: &str, verbatim: bool);
169     fn link_rlib(&mut self, lib: &Path);
170     fn link_whole_rlib(&mut self, lib: &Path);
171     fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, search_path: &[PathBuf]);
172     fn include_path(&mut self, path: &Path);
173     fn framework_path(&mut self, path: &Path);
174     fn output_filename(&mut self, path: &Path);
175     fn add_object(&mut self, path: &Path);
176     fn gc_sections(&mut self, keep_metadata: bool);
177     fn no_gc_sections(&mut self);
178     fn full_relro(&mut self);
179     fn partial_relro(&mut self);
180     fn no_relro(&mut self);
181     fn optimize(&mut self);
182     fn pgo_gen(&mut self);
183     fn control_flow_guard(&mut self);
184     fn debuginfo(&mut self, strip: Strip, natvis_debugger_visualizers: &[PathBuf]);
185     fn no_crt_objects(&mut self);
186     fn no_default_libraries(&mut self);
187     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]);
188     fn subsystem(&mut self, subsystem: &str);
189     fn linker_plugin_lto(&mut self);
190     fn add_eh_frame_header(&mut self) {}
191     fn add_no_exec(&mut self) {}
192     fn add_as_needed(&mut self) {}
193     fn reset_per_library_state(&mut self) {}
194 }
195
196 impl dyn Linker + '_ {
197     pub fn arg(&mut self, arg: impl AsRef<OsStr>) {
198         self.cmd().arg(arg);
199     }
200
201     pub fn args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) {
202         self.cmd().args(args);
203     }
204
205     pub fn take_cmd(&mut self) -> Command {
206         mem::replace(self.cmd(), Command::new(""))
207     }
208 }
209
210 pub struct GccLinker<'a> {
211     cmd: Command,
212     sess: &'a Session,
213     target_cpu: &'a str,
214     hinted_static: bool, // Keeps track of the current hinting mode.
215     // Link as ld
216     is_ld: bool,
217     is_gnu: bool,
218 }
219
220 impl<'a> GccLinker<'a> {
221     /// Passes an argument directly to the linker.
222     ///
223     /// When the linker is not ld-like such as when using a compiler as a linker, the argument is
224     /// prepended by `-Wl,`.
225     fn linker_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
226         self.linker_args(&[arg]);
227         self
228     }
229
230     /// Passes a series of arguments directly to the linker.
231     ///
232     /// When the linker is ld-like, the arguments are simply appended to the command. When the
233     /// linker is not ld-like such as when using a compiler as a linker, the arguments are joined by
234     /// commas to form an argument that is then prepended with `-Wl`. In this situation, only a
235     /// single argument is appended to the command to ensure that the order of the arguments is
236     /// preserved by the compiler.
237     fn linker_args(&mut self, args: &[impl AsRef<OsStr>]) -> &mut Self {
238         if self.is_ld {
239             args.into_iter().for_each(|a| {
240                 self.cmd.arg(a);
241             });
242         } else {
243             if !args.is_empty() {
244                 let mut s = OsString::from("-Wl");
245                 for a in args {
246                     s.push(",");
247                     s.push(a);
248                 }
249                 self.cmd.arg(s);
250             }
251         }
252         self
253     }
254
255     fn takes_hints(&self) -> bool {
256         // Really this function only returns true if the underlying linker
257         // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
258         // don't really have a foolproof way to detect that, so rule out some
259         // platforms where currently this is guaranteed to *not* be the case:
260         //
261         // * On OSX they have their own linker, not binutils'
262         // * For WebAssembly the only functional linker is LLD, which doesn't
263         //   support hint flags
264         !self.sess.target.is_like_osx && !self.sess.target.is_like_wasm
265     }
266
267     // Some platforms take hints about whether a library is static or dynamic.
268     // For those that support this, we ensure we pass the option if the library
269     // was flagged "static" (most defaults are dynamic) to ensure that if
270     // libfoo.a and libfoo.so both exist that the right one is chosen.
271     fn hint_static(&mut self) {
272         if !self.takes_hints() {
273             return;
274         }
275         if !self.hinted_static {
276             self.linker_arg("-Bstatic");
277             self.hinted_static = true;
278         }
279     }
280
281     fn hint_dynamic(&mut self) {
282         if !self.takes_hints() {
283             return;
284         }
285         if self.hinted_static {
286             self.linker_arg("-Bdynamic");
287             self.hinted_static = false;
288         }
289     }
290
291     fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
292         if let Some(plugin_path) = plugin_path {
293             let mut arg = OsString::from("-plugin=");
294             arg.push(plugin_path);
295             self.linker_arg(&arg);
296         }
297
298         let opt_level = match self.sess.opts.optimize {
299             config::OptLevel::No => "O0",
300             config::OptLevel::Less => "O1",
301             config::OptLevel::Default | config::OptLevel::Size | config::OptLevel::SizeMin => "O2",
302             config::OptLevel::Aggressive => "O3",
303         };
304
305         if let Some(path) = &self.sess.opts.unstable_opts.profile_sample_use {
306             self.linker_arg(&format!("-plugin-opt=sample-profile={}", path.display()));
307         };
308         self.linker_args(&[
309             &format!("-plugin-opt={}", opt_level),
310             &format!("-plugin-opt=mcpu={}", self.target_cpu),
311         ]);
312     }
313
314     fn build_dylib(&mut self, out_filename: &Path) {
315         // On mac we need to tell the linker to let this library be rpathed
316         if self.sess.target.is_like_osx {
317             if !self.is_ld {
318                 self.cmd.arg("-dynamiclib");
319             }
320
321             self.linker_arg("-dylib");
322
323             // Note that the `osx_rpath_install_name` option here is a hack
324             // purely to support rustbuild right now, we should get a more
325             // principled solution at some point to force the compiler to pass
326             // the right `-Wl,-install_name` with an `@rpath` in it.
327             if self.sess.opts.cg.rpath || self.sess.opts.unstable_opts.osx_rpath_install_name {
328                 let mut rpath = OsString::from("@rpath/");
329                 rpath.push(out_filename.file_name().unwrap());
330                 self.linker_args(&[OsString::from("-install_name"), rpath]);
331             }
332         } else {
333             self.cmd.arg("-shared");
334             if self.sess.target.is_like_windows {
335                 // The output filename already contains `dll_suffix` so
336                 // the resulting import library will have a name in the
337                 // form of libfoo.dll.a
338                 let implib_name =
339                     out_filename.file_name().and_then(|file| file.to_str()).map(|file| {
340                         format!(
341                             "{}{}{}",
342                             self.sess.target.staticlib_prefix,
343                             file,
344                             self.sess.target.staticlib_suffix
345                         )
346                     });
347                 if let Some(implib_name) = implib_name {
348                     let implib = out_filename.parent().map(|dir| dir.join(&implib_name));
349                     if let Some(implib) = implib {
350                         self.linker_arg(&format!("--out-implib={}", (*implib).to_str().unwrap()));
351                     }
352                 }
353             }
354         }
355     }
356 }
357
358 impl<'a> Linker for GccLinker<'a> {
359     fn cmd(&mut self) -> &mut Command {
360         &mut self.cmd
361     }
362
363     fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
364         match output_kind {
365             LinkOutputKind::DynamicNoPicExe => {
366                 if !self.is_ld && self.is_gnu {
367                     self.cmd.arg("-no-pie");
368                 }
369             }
370             LinkOutputKind::DynamicPicExe => {
371                 // noop on windows w/ gcc & ld, error w/ lld
372                 if !self.sess.target.is_like_windows {
373                     // `-pie` works for both gcc wrapper and ld.
374                     self.cmd.arg("-pie");
375                 }
376             }
377             LinkOutputKind::StaticNoPicExe => {
378                 // `-static` works for both gcc wrapper and ld.
379                 self.cmd.arg("-static");
380                 if !self.is_ld && self.is_gnu {
381                     self.cmd.arg("-no-pie");
382                 }
383             }
384             LinkOutputKind::StaticPicExe => {
385                 if !self.is_ld {
386                     // Note that combination `-static -pie` doesn't work as expected
387                     // for the gcc wrapper, `-static` in that case suppresses `-pie`.
388                     self.cmd.arg("-static-pie");
389                 } else {
390                     // `--no-dynamic-linker` and `-z text` are not strictly necessary for producing
391                     // a static pie, but currently passed because gcc and clang pass them.
392                     // The former suppresses the `INTERP` ELF header specifying dynamic linker,
393                     // which is otherwise implicitly injected by ld (but not lld).
394                     // The latter doesn't change anything, only ensures that everything is pic.
395                     self.cmd.args(&["-static", "-pie", "--no-dynamic-linker", "-z", "text"]);
396                 }
397             }
398             LinkOutputKind::DynamicDylib => self.build_dylib(out_filename),
399             LinkOutputKind::StaticDylib => {
400                 self.cmd.arg("-static");
401                 self.build_dylib(out_filename);
402             }
403             LinkOutputKind::WasiReactorExe => {
404                 self.linker_args(&["--entry", "_initialize"]);
405             }
406         }
407         // VxWorks compiler driver introduced `--static-crt` flag specifically for rustc,
408         // it switches linking for libc and similar system libraries to static without using
409         // any `#[link]` attributes in the `libc` crate, see #72782 for details.
410         // FIXME: Switch to using `#[link]` attributes in the `libc` crate
411         // similarly to other targets.
412         if self.sess.target.os == "vxworks"
413             && matches!(
414                 output_kind,
415                 LinkOutputKind::StaticNoPicExe
416                     | LinkOutputKind::StaticPicExe
417                     | LinkOutputKind::StaticDylib
418             )
419         {
420             self.cmd.arg("--static-crt");
421         }
422     }
423
424     fn link_dylib(&mut self, lib: &str, verbatim: bool, as_needed: bool) {
425         if self.sess.target.os == "illumos" && lib == "c" {
426             // libc will be added via late_link_args on illumos so that it will
427             // appear last in the library search order.
428             // FIXME: This should be replaced by a more complete and generic
429             // mechanism for controlling the order of library arguments passed
430             // to the linker.
431             return;
432         }
433         if !as_needed {
434             if self.sess.target.is_like_osx {
435                 // FIXME(81490): ld64 doesn't support these flags but macOS 11
436                 // has -needed-l{} / -needed_library {}
437                 // but we have no way to detect that here.
438                 self.sess.emit_warning(errors::Ld64UnimplementedModifier);
439             } else if self.is_gnu && !self.sess.target.is_like_windows {
440                 self.linker_arg("--no-as-needed");
441             } else {
442                 self.sess.emit_warning(errors::LinkerUnsupportedModifier);
443             }
444         }
445         self.hint_dynamic();
446         self.cmd.arg(format!("-l{}{lib}", if verbatim && self.is_gnu { ":" } else { "" },));
447         if !as_needed {
448             if self.sess.target.is_like_osx {
449                 // See above FIXME comment
450             } else if self.is_gnu && !self.sess.target.is_like_windows {
451                 self.linker_arg("--as-needed");
452             }
453         }
454     }
455     fn link_staticlib(&mut self, lib: &str, verbatim: bool) {
456         self.hint_static();
457         self.cmd.arg(format!("-l{}{lib}", if verbatim && self.is_gnu { ":" } else { "" },));
458     }
459     fn link_rlib(&mut self, lib: &Path) {
460         self.hint_static();
461         self.cmd.arg(lib);
462     }
463     fn include_path(&mut self, path: &Path) {
464         self.cmd.arg("-L").arg(path);
465     }
466     fn framework_path(&mut self, path: &Path) {
467         self.cmd.arg("-F").arg(path);
468     }
469     fn output_filename(&mut self, path: &Path) {
470         self.cmd.arg("-o").arg(path);
471     }
472     fn add_object(&mut self, path: &Path) {
473         self.cmd.arg(path);
474     }
475     fn full_relro(&mut self) {
476         self.linker_args(&["-zrelro", "-znow"]);
477     }
478     fn partial_relro(&mut self) {
479         self.linker_arg("-zrelro");
480     }
481     fn no_relro(&mut self) {
482         self.linker_arg("-znorelro");
483     }
484
485     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
486         self.hint_dynamic();
487         self.cmd.arg(format!("-l{}", lib));
488     }
489
490     fn link_framework(&mut self, framework: &str, as_needed: bool) {
491         self.hint_dynamic();
492         if !as_needed {
493             // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
494             // flag but we have no way to detect that here.
495             // self.cmd.arg("-needed_framework").arg(framework);
496             self.sess.emit_warning(errors::Ld64UnimplementedModifier);
497         }
498         self.cmd.arg("-framework").arg(framework);
499     }
500
501     // Here we explicitly ask that the entire archive is included into the
502     // result artifact. For more details see #15460, but the gist is that
503     // the linker will strip away any unused objects in the archive if we
504     // don't otherwise explicitly reference them. This can occur for
505     // libraries which are just providing bindings, libraries with generic
506     // functions, etc.
507     fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, search_path: &[PathBuf]) {
508         self.hint_static();
509         let target = &self.sess.target;
510         if !target.is_like_osx {
511             self.linker_arg("--whole-archive");
512             self.cmd.arg(format!("-l{}{lib}", if verbatim && self.is_gnu { ":" } else { "" },));
513             self.linker_arg("--no-whole-archive");
514         } else {
515             // -force_load is the macOS equivalent of --whole-archive, but it
516             // involves passing the full path to the library to link.
517             self.linker_arg("-force_load");
518             let lib = find_native_static_library(lib, Some(verbatim), search_path, &self.sess);
519             self.linker_arg(&lib);
520         }
521     }
522
523     fn link_whole_rlib(&mut self, lib: &Path) {
524         self.hint_static();
525         if self.sess.target.is_like_osx {
526             self.linker_arg("-force_load");
527             self.linker_arg(&lib);
528         } else {
529             self.linker_arg("--whole-archive").cmd.arg(lib);
530             self.linker_arg("--no-whole-archive");
531         }
532     }
533
534     fn gc_sections(&mut self, keep_metadata: bool) {
535         // The dead_strip option to the linker specifies that functions and data
536         // unreachable by the entry point will be removed. This is quite useful
537         // with Rust's compilation model of compiling libraries at a time into
538         // one object file. For example, this brings hello world from 1.7MB to
539         // 458K.
540         //
541         // Note that this is done for both executables and dynamic libraries. We
542         // won't get much benefit from dylibs because LLVM will have already
543         // stripped away as much as it could. This has not been seen to impact
544         // link times negatively.
545         //
546         // -dead_strip can't be part of the pre_link_args because it's also used
547         // for partial linking when using multiple codegen units (-r).  So we
548         // insert it here.
549         if self.sess.target.is_like_osx {
550             self.linker_arg("-dead_strip");
551
552         // If we're building a dylib, we don't use --gc-sections because LLVM
553         // has already done the best it can do, and we also don't want to
554         // eliminate the metadata. If we're building an executable, however,
555         // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
556         // reduction.
557         } else if (self.is_gnu || self.sess.target.is_like_wasm) && !keep_metadata {
558             self.linker_arg("--gc-sections");
559         }
560     }
561
562     fn no_gc_sections(&mut self) {
563         if self.is_gnu || self.sess.target.is_like_wasm {
564             self.linker_arg("--no-gc-sections");
565         }
566     }
567
568     fn optimize(&mut self) {
569         if !self.is_gnu && !self.sess.target.is_like_wasm {
570             return;
571         }
572
573         // GNU-style linkers support optimization with -O. GNU ld doesn't
574         // need a numeric argument, but other linkers do.
575         if self.sess.opts.optimize == config::OptLevel::Default
576             || self.sess.opts.optimize == config::OptLevel::Aggressive
577         {
578             self.linker_arg("-O1");
579         }
580     }
581
582     fn pgo_gen(&mut self) {
583         if !self.is_gnu {
584             return;
585         }
586
587         // If we're doing PGO generation stuff and on a GNU-like linker, use the
588         // "-u" flag to properly pull in the profiler runtime bits.
589         //
590         // This is because LLVM otherwise won't add the needed initialization
591         // for us on Linux (though the extra flag should be harmless if it
592         // does).
593         //
594         // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
595         //
596         // Though it may be worth to try to revert those changes upstream, since
597         // the overhead of the initialization should be minor.
598         self.cmd.arg("-u");
599         self.cmd.arg("__llvm_profile_runtime");
600     }
601
602     fn control_flow_guard(&mut self) {}
603
604     fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
605         // MacOS linker doesn't support stripping symbols directly anymore.
606         if self.sess.target.is_like_osx {
607             return;
608         }
609
610         match strip {
611             Strip::None => {}
612             Strip::Debuginfo => {
613                 self.linker_arg("--strip-debug");
614             }
615             Strip::Symbols => {
616                 self.linker_arg("--strip-all");
617             }
618         }
619     }
620
621     fn no_crt_objects(&mut self) {
622         if !self.is_ld {
623             self.cmd.arg("-nostartfiles");
624         }
625     }
626
627     fn no_default_libraries(&mut self) {
628         if !self.is_ld {
629             self.cmd.arg("-nodefaultlibs");
630         }
631     }
632
633     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]) {
634         // Symbol visibility in object files typically takes care of this.
635         if crate_type == CrateType::Executable {
636             let should_export_executable_symbols =
637                 self.sess.opts.unstable_opts.export_executable_symbols;
638             if self.sess.target.override_export_symbols.is_none()
639                 && !should_export_executable_symbols
640             {
641                 return;
642             }
643         }
644
645         // We manually create a list of exported symbols to ensure we don't expose any more.
646         // The object files have far more public symbols than we actually want to export,
647         // so we hide them all here.
648
649         if !self.sess.target.limit_rdylib_exports {
650             return;
651         }
652
653         // FIXME(#99978) hide #[no_mangle] symbols for proc-macros
654
655         let is_windows = self.sess.target.is_like_windows;
656         let path = tmpdir.join(if is_windows { "list.def" } else { "list" });
657
658         debug!("EXPORTED SYMBOLS:");
659
660         if self.sess.target.is_like_osx {
661             // Write a plain, newline-separated list of symbols
662             let res: io::Result<()> = try {
663                 let mut f = BufWriter::new(File::create(&path)?);
664                 for sym in symbols {
665                     debug!("  _{}", sym);
666                     writeln!(f, "_{}", sym)?;
667                 }
668             };
669             if let Err(error) = res {
670                 self.sess.emit_fatal(errors::LibDefWriteFailure { error });
671             }
672         } else if is_windows {
673             let res: io::Result<()> = try {
674                 let mut f = BufWriter::new(File::create(&path)?);
675
676                 // .def file similar to MSVC one but without LIBRARY section
677                 // because LD doesn't like when it's empty
678                 writeln!(f, "EXPORTS")?;
679                 for symbol in symbols {
680                     debug!("  _{}", symbol);
681                     writeln!(f, "  {}", symbol)?;
682                 }
683             };
684             if let Err(error) = res {
685                 self.sess.emit_fatal(errors::LibDefWriteFailure { error });
686             }
687         } else {
688             // Write an LD version script
689             let res: io::Result<()> = try {
690                 let mut f = BufWriter::new(File::create(&path)?);
691                 writeln!(f, "{{")?;
692                 if !symbols.is_empty() {
693                     writeln!(f, "  global:")?;
694                     for sym in symbols {
695                         debug!("    {};", sym);
696                         writeln!(f, "    {};", sym)?;
697                     }
698                 }
699                 writeln!(f, "\n  local:\n    *;\n}};")?;
700             };
701             if let Err(error) = res {
702                 self.sess.emit_fatal(errors::VersionScriptWriteFailure { error });
703             }
704         }
705
706         if self.sess.target.is_like_osx {
707             self.linker_args(&[OsString::from("-exported_symbols_list"), path.into()]);
708         } else if self.sess.target.is_like_solaris {
709             self.linker_args(&[OsString::from("-M"), path.into()]);
710         } else {
711             if is_windows {
712                 self.linker_arg(path);
713             } else {
714                 let mut arg = OsString::from("--version-script=");
715                 arg.push(path);
716                 self.linker_arg(arg);
717             }
718         }
719     }
720
721     fn subsystem(&mut self, subsystem: &str) {
722         self.linker_arg("--subsystem");
723         self.linker_arg(&subsystem);
724     }
725
726     fn reset_per_library_state(&mut self) {
727         self.hint_dynamic(); // Reset to default before returning the composed command line.
728     }
729
730     fn linker_plugin_lto(&mut self) {
731         match self.sess.opts.cg.linker_plugin_lto {
732             LinkerPluginLto::Disabled => {
733                 // Nothing to do
734             }
735             LinkerPluginLto::LinkerPluginAuto => {
736                 self.push_linker_plugin_lto_args(None);
737             }
738             LinkerPluginLto::LinkerPlugin(ref path) => {
739                 self.push_linker_plugin_lto_args(Some(path.as_os_str()));
740             }
741         }
742     }
743
744     // Add the `GNU_EH_FRAME` program header which is required to locate unwinding information.
745     // Some versions of `gcc` add it implicitly, some (e.g. `musl-gcc`) don't,
746     // so we just always add it.
747     fn add_eh_frame_header(&mut self) {
748         self.linker_arg("--eh-frame-hdr");
749     }
750
751     fn add_no_exec(&mut self) {
752         if self.sess.target.is_like_windows {
753             self.linker_arg("--nxcompat");
754         } else if self.is_gnu {
755             self.linker_arg("-znoexecstack");
756         }
757     }
758
759     fn add_as_needed(&mut self) {
760         if self.is_gnu && !self.sess.target.is_like_windows {
761             self.linker_arg("--as-needed");
762         } else if self.sess.target.is_like_solaris {
763             // -z ignore is the Solaris equivalent to the GNU ld --as-needed option
764             self.linker_args(&["-z", "ignore"]);
765         }
766     }
767 }
768
769 pub struct MsvcLinker<'a> {
770     cmd: Command,
771     sess: &'a Session,
772 }
773
774 impl<'a> Linker for MsvcLinker<'a> {
775     fn cmd(&mut self) -> &mut Command {
776         &mut self.cmd
777     }
778
779     fn set_output_kind(&mut self, output_kind: LinkOutputKind, out_filename: &Path) {
780         match output_kind {
781             LinkOutputKind::DynamicNoPicExe
782             | LinkOutputKind::DynamicPicExe
783             | LinkOutputKind::StaticNoPicExe
784             | LinkOutputKind::StaticPicExe => {}
785             LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
786                 self.cmd.arg("/DLL");
787                 let mut arg: OsString = "/IMPLIB:".into();
788                 arg.push(out_filename.with_extension("dll.lib"));
789                 self.cmd.arg(arg);
790             }
791             LinkOutputKind::WasiReactorExe => {
792                 panic!("can't link as reactor on non-wasi target");
793             }
794         }
795     }
796
797     fn link_rlib(&mut self, lib: &Path) {
798         self.cmd.arg(lib);
799     }
800     fn add_object(&mut self, path: &Path) {
801         self.cmd.arg(path);
802     }
803
804     fn gc_sections(&mut self, _keep_metadata: bool) {
805         // MSVC's ICF (Identical COMDAT Folding) link optimization is
806         // slow for Rust and thus we disable it by default when not in
807         // optimization build.
808         if self.sess.opts.optimize != config::OptLevel::No {
809             self.cmd.arg("/OPT:REF,ICF");
810         } else {
811             // It is necessary to specify NOICF here, because /OPT:REF
812             // implies ICF by default.
813             self.cmd.arg("/OPT:REF,NOICF");
814         }
815     }
816
817     fn no_gc_sections(&mut self) {
818         self.cmd.arg("/OPT:NOREF,NOICF");
819     }
820
821     fn link_dylib(&mut self, lib: &str, verbatim: bool, _as_needed: bool) {
822         self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
823     }
824
825     fn link_rust_dylib(&mut self, lib: &str, path: &Path) {
826         // When producing a dll, the MSVC linker may not actually emit a
827         // `foo.lib` file if the dll doesn't actually export any symbols, so we
828         // check to see if the file is there and just omit linking to it if it's
829         // not present.
830         let name = format!("{}.dll.lib", lib);
831         if path.join(&name).exists() {
832             self.cmd.arg(name);
833         }
834     }
835
836     fn link_staticlib(&mut self, lib: &str, verbatim: bool) {
837         self.cmd.arg(format!("{}{}", lib, if verbatim { "" } else { ".lib" }));
838     }
839
840     fn full_relro(&mut self) {
841         // noop
842     }
843
844     fn partial_relro(&mut self) {
845         // noop
846     }
847
848     fn no_relro(&mut self) {
849         // noop
850     }
851
852     fn no_crt_objects(&mut self) {
853         // noop
854     }
855
856     fn no_default_libraries(&mut self) {
857         self.cmd.arg("/NODEFAULTLIB");
858     }
859
860     fn include_path(&mut self, path: &Path) {
861         let mut arg = OsString::from("/LIBPATH:");
862         arg.push(path);
863         self.cmd.arg(&arg);
864     }
865
866     fn output_filename(&mut self, path: &Path) {
867         let mut arg = OsString::from("/OUT:");
868         arg.push(path);
869         self.cmd.arg(&arg);
870     }
871
872     fn framework_path(&mut self, _path: &Path) {
873         bug!("frameworks are not supported on windows")
874     }
875     fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
876         bug!("frameworks are not supported on windows")
877     }
878
879     fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, _search_path: &[PathBuf]) {
880         self.cmd.arg(format!("/WHOLEARCHIVE:{}{}", lib, if verbatim { "" } else { ".lib" }));
881     }
882     fn link_whole_rlib(&mut self, path: &Path) {
883         let mut arg = OsString::from("/WHOLEARCHIVE:");
884         arg.push(path);
885         self.cmd.arg(arg);
886     }
887     fn optimize(&mut self) {
888         // Needs more investigation of `/OPT` arguments
889     }
890
891     fn pgo_gen(&mut self) {
892         // Nothing needed here.
893     }
894
895     fn control_flow_guard(&mut self) {
896         self.cmd.arg("/guard:cf");
897     }
898
899     fn debuginfo(&mut self, strip: Strip, natvis_debugger_visualizers: &[PathBuf]) {
900         match strip {
901             Strip::None => {
902                 // This will cause the Microsoft linker to generate a PDB file
903                 // from the CodeView line tables in the object files.
904                 self.cmd.arg("/DEBUG");
905
906                 // This will cause the Microsoft linker to embed .natvis info into the PDB file
907                 let natvis_dir_path = self.sess.sysroot.join("lib\\rustlib\\etc");
908                 if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
909                     for entry in natvis_dir {
910                         match entry {
911                             Ok(entry) => {
912                                 let path = entry.path();
913                                 if path.extension() == Some("natvis".as_ref()) {
914                                     let mut arg = OsString::from("/NATVIS:");
915                                     arg.push(path);
916                                     self.cmd.arg(arg);
917                                 }
918                             }
919                             Err(error) => {
920                                 self.sess.emit_warning(errors::NoNatvisDirectory { error });
921                             }
922                         }
923                     }
924                 }
925
926                 // This will cause the Microsoft linker to embed .natvis info for all crates into the PDB file
927                 for path in natvis_debugger_visualizers {
928                     let mut arg = OsString::from("/NATVIS:");
929                     arg.push(path);
930                     self.cmd.arg(arg);
931                 }
932             }
933             Strip::Debuginfo | Strip::Symbols => {
934                 self.cmd.arg("/DEBUG:NONE");
935             }
936         }
937     }
938
939     // Currently the compiler doesn't use `dllexport` (an LLVM attribute) to
940     // export symbols from a dynamic library. When building a dynamic library,
941     // however, we're going to want some symbols exported, so this function
942     // generates a DEF file which lists all the symbols.
943     //
944     // The linker will read this `*.def` file and export all the symbols from
945     // the dynamic library. Note that this is not as simple as just exporting
946     // all the symbols in the current crate (as specified by `codegen.reachable`)
947     // but rather we also need to possibly export the symbols of upstream
948     // crates. Upstream rlibs may be linked statically to this dynamic library,
949     // in which case they may continue to transitively be used and hence need
950     // their symbols exported.
951     fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[String]) {
952         // Symbol visibility takes care of this typically
953         if crate_type == CrateType::Executable {
954             let should_export_executable_symbols =
955                 self.sess.opts.unstable_opts.export_executable_symbols;
956             if !should_export_executable_symbols {
957                 return;
958             }
959         }
960
961         let path = tmpdir.join("lib.def");
962         let res: io::Result<()> = try {
963             let mut f = BufWriter::new(File::create(&path)?);
964
965             // Start off with the standard module name header and then go
966             // straight to exports.
967             writeln!(f, "LIBRARY")?;
968             writeln!(f, "EXPORTS")?;
969             for symbol in symbols {
970                 debug!("  _{}", symbol);
971                 writeln!(f, "  {}", symbol)?;
972             }
973         };
974         if let Err(error) = res {
975             self.sess.emit_fatal(errors::LibDefWriteFailure { error });
976         }
977         let mut arg = OsString::from("/DEF:");
978         arg.push(path);
979         self.cmd.arg(&arg);
980     }
981
982     fn subsystem(&mut self, subsystem: &str) {
983         // Note that previous passes of the compiler validated this subsystem,
984         // so we just blindly pass it to the linker.
985         self.cmd.arg(&format!("/SUBSYSTEM:{}", subsystem));
986
987         // Windows has two subsystems we're interested in right now, the console
988         // and windows subsystems. These both implicitly have different entry
989         // points (starting symbols). The console entry point starts with
990         // `mainCRTStartup` and the windows entry point starts with
991         // `WinMainCRTStartup`. These entry points, defined in system libraries,
992         // will then later probe for either `main` or `WinMain`, respectively to
993         // start the application.
994         //
995         // In Rust we just always generate a `main` function so we want control
996         // to always start there, so we force the entry point on the windows
997         // subsystem to be `mainCRTStartup` to get everything booted up
998         // correctly.
999         //
1000         // For more information see RFC #1665
1001         if subsystem == "windows" {
1002             self.cmd.arg("/ENTRY:mainCRTStartup");
1003         }
1004     }
1005
1006     fn linker_plugin_lto(&mut self) {
1007         // Do nothing
1008     }
1009
1010     fn add_no_exec(&mut self) {
1011         self.cmd.arg("/NXCOMPAT");
1012     }
1013 }
1014
1015 pub struct EmLinker<'a> {
1016     cmd: Command,
1017     sess: &'a Session,
1018 }
1019
1020 impl<'a> Linker for EmLinker<'a> {
1021     fn cmd(&mut self) -> &mut Command {
1022         &mut self.cmd
1023     }
1024
1025     fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1026
1027     fn include_path(&mut self, path: &Path) {
1028         self.cmd.arg("-L").arg(path);
1029     }
1030
1031     fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
1032         self.cmd.arg("-l").arg(lib);
1033     }
1034
1035     fn output_filename(&mut self, path: &Path) {
1036         self.cmd.arg("-o").arg(path);
1037     }
1038
1039     fn add_object(&mut self, path: &Path) {
1040         self.cmd.arg(path);
1041     }
1042
1043     fn link_dylib(&mut self, lib: &str, verbatim: bool, _as_needed: bool) {
1044         // Emscripten always links statically
1045         self.link_staticlib(lib, verbatim);
1046     }
1047
1048     fn link_whole_staticlib(&mut self, lib: &str, verbatim: bool, _search_path: &[PathBuf]) {
1049         // not supported?
1050         self.link_staticlib(lib, verbatim);
1051     }
1052
1053     fn link_whole_rlib(&mut self, lib: &Path) {
1054         // not supported?
1055         self.link_rlib(lib);
1056     }
1057
1058     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
1059         self.link_dylib(lib, false, true);
1060     }
1061
1062     fn link_rlib(&mut self, lib: &Path) {
1063         self.add_object(lib);
1064     }
1065
1066     fn full_relro(&mut self) {
1067         // noop
1068     }
1069
1070     fn partial_relro(&mut self) {
1071         // noop
1072     }
1073
1074     fn no_relro(&mut self) {
1075         // noop
1076     }
1077
1078     fn framework_path(&mut self, _path: &Path) {
1079         bug!("frameworks are not supported on Emscripten")
1080     }
1081
1082     fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1083         bug!("frameworks are not supported on Emscripten")
1084     }
1085
1086     fn gc_sections(&mut self, _keep_metadata: bool) {
1087         // noop
1088     }
1089
1090     fn no_gc_sections(&mut self) {
1091         // noop
1092     }
1093
1094     fn optimize(&mut self) {
1095         // Emscripten performs own optimizations
1096         self.cmd.arg(match self.sess.opts.optimize {
1097             OptLevel::No => "-O0",
1098             OptLevel::Less => "-O1",
1099             OptLevel::Default => "-O2",
1100             OptLevel::Aggressive => "-O3",
1101             OptLevel::Size => "-Os",
1102             OptLevel::SizeMin => "-Oz",
1103         });
1104     }
1105
1106     fn pgo_gen(&mut self) {
1107         // noop, but maybe we need something like the gnu linker?
1108     }
1109
1110     fn control_flow_guard(&mut self) {}
1111
1112     fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1113         // Preserve names or generate source maps depending on debug info
1114         self.cmd.arg(match self.sess.opts.debuginfo {
1115             DebugInfo::None => "-g0",
1116             DebugInfo::Limited => "--profiling-funcs",
1117             DebugInfo::Full => "-g",
1118         });
1119     }
1120
1121     fn no_crt_objects(&mut self) {}
1122
1123     fn no_default_libraries(&mut self) {
1124         self.cmd.arg("-nodefaultlibs");
1125     }
1126
1127     fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1128         debug!("EXPORTED SYMBOLS:");
1129
1130         self.cmd.arg("-s");
1131
1132         let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
1133         let encoded = serde_json::to_string(
1134             &symbols.iter().map(|sym| "_".to_owned() + sym).collect::<Vec<_>>(),
1135         )
1136         .unwrap();
1137         debug!("{}", encoded);
1138
1139         arg.push(encoded);
1140
1141         self.cmd.arg(arg);
1142     }
1143
1144     fn subsystem(&mut self, _subsystem: &str) {
1145         // noop
1146     }
1147
1148     fn linker_plugin_lto(&mut self) {
1149         // Do nothing
1150     }
1151 }
1152
1153 pub struct WasmLd<'a> {
1154     cmd: Command,
1155     sess: &'a Session,
1156 }
1157
1158 impl<'a> WasmLd<'a> {
1159     fn new(mut cmd: Command, sess: &'a Session) -> WasmLd<'a> {
1160         // If the atomics feature is enabled for wasm then we need a whole bunch
1161         // of flags:
1162         //
1163         // * `--shared-memory` - the link won't even succeed without this, flags
1164         //   the one linear memory as `shared`
1165         //
1166         // * `--max-memory=1G` - when specifying a shared memory this must also
1167         //   be specified. We conservatively choose 1GB but users should be able
1168         //   to override this with `-C link-arg`.
1169         //
1170         // * `--import-memory` - it doesn't make much sense for memory to be
1171         //   exported in a threaded module because typically you're
1172         //   sharing memory and instantiating the module multiple times. As a
1173         //   result if it were exported then we'd just have no sharing.
1174         //
1175         // On wasm32-unknown-unknown, we also export symbols for glue code to use:
1176         //    * `--export=*tls*` - when `#[thread_local]` symbols are used these
1177         //      symbols are how the TLS segments are initialized and configured.
1178         if sess.target_features.contains(&sym::atomics) {
1179             cmd.arg("--shared-memory");
1180             cmd.arg("--max-memory=1073741824");
1181             cmd.arg("--import-memory");
1182             if sess.target.os == "unknown" {
1183                 cmd.arg("--export=__wasm_init_tls");
1184                 cmd.arg("--export=__tls_size");
1185                 cmd.arg("--export=__tls_align");
1186                 cmd.arg("--export=__tls_base");
1187             }
1188         }
1189         WasmLd { cmd, sess }
1190     }
1191 }
1192
1193 impl<'a> Linker for WasmLd<'a> {
1194     fn cmd(&mut self) -> &mut Command {
1195         &mut self.cmd
1196     }
1197
1198     fn set_output_kind(&mut self, output_kind: LinkOutputKind, _out_filename: &Path) {
1199         match output_kind {
1200             LinkOutputKind::DynamicNoPicExe
1201             | LinkOutputKind::DynamicPicExe
1202             | LinkOutputKind::StaticNoPicExe
1203             | LinkOutputKind::StaticPicExe => {}
1204             LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1205                 self.cmd.arg("--no-entry");
1206             }
1207             LinkOutputKind::WasiReactorExe => {
1208                 self.cmd.arg("--entry");
1209                 self.cmd.arg("_initialize");
1210             }
1211         }
1212     }
1213
1214     fn link_dylib(&mut self, lib: &str, _verbatim: bool, _as_needed: bool) {
1215         self.cmd.arg("-l").arg(lib);
1216     }
1217
1218     fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
1219         self.cmd.arg("-l").arg(lib);
1220     }
1221
1222     fn link_rlib(&mut self, lib: &Path) {
1223         self.cmd.arg(lib);
1224     }
1225
1226     fn include_path(&mut self, path: &Path) {
1227         self.cmd.arg("-L").arg(path);
1228     }
1229
1230     fn framework_path(&mut self, _path: &Path) {
1231         panic!("frameworks not supported")
1232     }
1233
1234     fn output_filename(&mut self, path: &Path) {
1235         self.cmd.arg("-o").arg(path);
1236     }
1237
1238     fn add_object(&mut self, path: &Path) {
1239         self.cmd.arg(path);
1240     }
1241
1242     fn full_relro(&mut self) {}
1243
1244     fn partial_relro(&mut self) {}
1245
1246     fn no_relro(&mut self) {}
1247
1248     fn link_rust_dylib(&mut self, lib: &str, _path: &Path) {
1249         self.cmd.arg("-l").arg(lib);
1250     }
1251
1252     fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1253         panic!("frameworks not supported")
1254     }
1255
1256     fn link_whole_staticlib(&mut self, lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
1257         self.cmd.arg("-l").arg(lib);
1258     }
1259
1260     fn link_whole_rlib(&mut self, lib: &Path) {
1261         self.cmd.arg(lib);
1262     }
1263
1264     fn gc_sections(&mut self, _keep_metadata: bool) {
1265         self.cmd.arg("--gc-sections");
1266     }
1267
1268     fn no_gc_sections(&mut self) {
1269         self.cmd.arg("--no-gc-sections");
1270     }
1271
1272     fn optimize(&mut self) {
1273         self.cmd.arg(match self.sess.opts.optimize {
1274             OptLevel::No => "-O0",
1275             OptLevel::Less => "-O1",
1276             OptLevel::Default => "-O2",
1277             OptLevel::Aggressive => "-O3",
1278             // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1279             // instead.
1280             OptLevel::Size => "-O2",
1281             OptLevel::SizeMin => "-O2",
1282         });
1283     }
1284
1285     fn pgo_gen(&mut self) {}
1286
1287     fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
1288         match strip {
1289             Strip::None => {}
1290             Strip::Debuginfo => {
1291                 self.cmd.arg("--strip-debug");
1292             }
1293             Strip::Symbols => {
1294                 self.cmd.arg("--strip-all");
1295             }
1296         }
1297     }
1298
1299     fn control_flow_guard(&mut self) {}
1300
1301     fn no_crt_objects(&mut self) {}
1302
1303     fn no_default_libraries(&mut self) {}
1304
1305     fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1306         for sym in symbols {
1307             self.cmd.arg("--export").arg(&sym);
1308         }
1309
1310         // LLD will hide these otherwise-internal symbols since it only exports
1311         // symbols explicitly passed via the `--export` flags above and hides all
1312         // others. Various bits and pieces of wasm32-unknown-unknown tooling use
1313         // this, so be sure these symbols make their way out of the linker as well.
1314         if self.sess.target.os == "unknown" {
1315             self.cmd.arg("--export=__heap_base");
1316             self.cmd.arg("--export=__data_end");
1317         }
1318     }
1319
1320     fn subsystem(&mut self, _subsystem: &str) {}
1321
1322     fn linker_plugin_lto(&mut self) {
1323         // Do nothing for now
1324     }
1325 }
1326
1327 /// Linker shepherd script for L4Re (Fiasco)
1328 pub struct L4Bender<'a> {
1329     cmd: Command,
1330     sess: &'a Session,
1331     hinted_static: bool,
1332 }
1333
1334 impl<'a> Linker for L4Bender<'a> {
1335     fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
1336         bug!("dylibs are not supported on L4Re");
1337     }
1338     fn link_staticlib(&mut self, lib: &str, _verbatim: bool) {
1339         self.hint_static();
1340         self.cmd.arg(format!("-PC{}", lib));
1341     }
1342     fn link_rlib(&mut self, lib: &Path) {
1343         self.hint_static();
1344         self.cmd.arg(lib);
1345     }
1346     fn include_path(&mut self, path: &Path) {
1347         self.cmd.arg("-L").arg(path);
1348     }
1349     fn framework_path(&mut self, _: &Path) {
1350         bug!("frameworks are not supported on L4Re");
1351     }
1352     fn output_filename(&mut self, path: &Path) {
1353         self.cmd.arg("-o").arg(path);
1354     }
1355
1356     fn add_object(&mut self, path: &Path) {
1357         self.cmd.arg(path);
1358     }
1359
1360     fn full_relro(&mut self) {
1361         self.cmd.arg("-zrelro");
1362         self.cmd.arg("-znow");
1363     }
1364
1365     fn partial_relro(&mut self) {
1366         self.cmd.arg("-zrelro");
1367     }
1368
1369     fn no_relro(&mut self) {
1370         self.cmd.arg("-znorelro");
1371     }
1372
1373     fn cmd(&mut self) -> &mut Command {
1374         &mut self.cmd
1375     }
1376
1377     fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1378
1379     fn link_rust_dylib(&mut self, _: &str, _: &Path) {
1380         panic!("Rust dylibs not supported");
1381     }
1382
1383     fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1384         bug!("frameworks not supported on L4Re");
1385     }
1386
1387     fn link_whole_staticlib(&mut self, lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
1388         self.hint_static();
1389         self.cmd.arg("--whole-archive").arg(format!("-l{}", lib));
1390         self.cmd.arg("--no-whole-archive");
1391     }
1392
1393     fn link_whole_rlib(&mut self, lib: &Path) {
1394         self.hint_static();
1395         self.cmd.arg("--whole-archive").arg(lib).arg("--no-whole-archive");
1396     }
1397
1398     fn gc_sections(&mut self, keep_metadata: bool) {
1399         if !keep_metadata {
1400             self.cmd.arg("--gc-sections");
1401         }
1402     }
1403
1404     fn no_gc_sections(&mut self) {
1405         self.cmd.arg("--no-gc-sections");
1406     }
1407
1408     fn optimize(&mut self) {
1409         // GNU-style linkers support optimization with -O. GNU ld doesn't
1410         // need a numeric argument, but other linkers do.
1411         if self.sess.opts.optimize == config::OptLevel::Default
1412             || self.sess.opts.optimize == config::OptLevel::Aggressive
1413         {
1414             self.cmd.arg("-O1");
1415         }
1416     }
1417
1418     fn pgo_gen(&mut self) {}
1419
1420     fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
1421         match strip {
1422             Strip::None => {}
1423             Strip::Debuginfo => {
1424                 self.cmd().arg("--strip-debug");
1425             }
1426             Strip::Symbols => {
1427                 self.cmd().arg("--strip-all");
1428             }
1429         }
1430     }
1431
1432     fn no_default_libraries(&mut self) {
1433         self.cmd.arg("-nostdlib");
1434     }
1435
1436     fn export_symbols(&mut self, _: &Path, _: CrateType, _: &[String]) {
1437         // ToDo, not implemented, copy from GCC
1438         self.sess.emit_warning(errors::L4BenderExportingSymbolsUnimplemented);
1439         return;
1440     }
1441
1442     fn subsystem(&mut self, subsystem: &str) {
1443         self.cmd.arg(&format!("--subsystem {}", subsystem));
1444     }
1445
1446     fn reset_per_library_state(&mut self) {
1447         self.hint_static(); // Reset to default before returning the composed command line.
1448     }
1449
1450     fn linker_plugin_lto(&mut self) {}
1451
1452     fn control_flow_guard(&mut self) {}
1453
1454     fn no_crt_objects(&mut self) {}
1455 }
1456
1457 impl<'a> L4Bender<'a> {
1458     pub fn new(cmd: Command, sess: &'a Session) -> L4Bender<'a> {
1459         L4Bender { cmd: cmd, sess: sess, hinted_static: false }
1460     }
1461
1462     fn hint_static(&mut self) {
1463         if !self.hinted_static {
1464             self.cmd.arg("-static");
1465             self.hinted_static = true;
1466         }
1467     }
1468 }
1469
1470 fn for_each_exported_symbols_include_dep<'tcx>(
1471     tcx: TyCtxt<'tcx>,
1472     crate_type: CrateType,
1473     mut callback: impl FnMut(ExportedSymbol<'tcx>, SymbolExportInfo, CrateNum),
1474 ) {
1475     for &(symbol, info) in tcx.exported_symbols(LOCAL_CRATE).iter() {
1476         callback(symbol, info, LOCAL_CRATE);
1477     }
1478
1479     let formats = tcx.dependency_formats(());
1480     let deps = formats.iter().find_map(|(t, list)| (*t == crate_type).then_some(list)).unwrap();
1481
1482     for (index, dep_format) in deps.iter().enumerate() {
1483         let cnum = CrateNum::new(index + 1);
1484         // For each dependency that we are linking to statically ...
1485         if *dep_format == Linkage::Static {
1486             for &(symbol, info) in tcx.exported_symbols(cnum).iter() {
1487                 callback(symbol, info, cnum);
1488             }
1489         }
1490     }
1491 }
1492
1493 pub(crate) fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<String> {
1494     if let Some(ref exports) = tcx.sess.target.override_export_symbols {
1495         return exports.iter().map(ToString::to_string).collect();
1496     }
1497
1498     let mut symbols = Vec::new();
1499
1500     let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1501     for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| {
1502         if info.level.is_below_threshold(export_threshold) {
1503             symbols.push(symbol_export::symbol_name_for_instance_in_crate(tcx, symbol, cnum));
1504         }
1505     });
1506
1507     symbols
1508 }
1509
1510 pub(crate) fn linked_symbols(
1511     tcx: TyCtxt<'_>,
1512     crate_type: CrateType,
1513 ) -> Vec<(String, SymbolExportKind)> {
1514     match crate_type {
1515         CrateType::Executable | CrateType::Cdylib | CrateType::Dylib => (),
1516         CrateType::Staticlib | CrateType::ProcMacro | CrateType::Rlib => {
1517             return Vec::new();
1518         }
1519     }
1520
1521     let mut symbols = Vec::new();
1522
1523     let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1524     for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| {
1525         if info.level.is_below_threshold(export_threshold) || info.used {
1526             symbols.push((
1527                 symbol_export::linking_symbol_name_for_instance_in_crate(tcx, symbol, cnum),
1528                 info.kind,
1529             ));
1530         }
1531     });
1532
1533     symbols
1534 }
1535
1536 /// Much simplified and explicit CLI for the NVPTX linker. The linker operates
1537 /// with bitcode and uses LLVM backend to generate a PTX assembly.
1538 pub struct PtxLinker<'a> {
1539     cmd: Command,
1540     sess: &'a Session,
1541 }
1542
1543 impl<'a> Linker for PtxLinker<'a> {
1544     fn cmd(&mut self) -> &mut Command {
1545         &mut self.cmd
1546     }
1547
1548     fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1549
1550     fn link_rlib(&mut self, path: &Path) {
1551         self.cmd.arg("--rlib").arg(path);
1552     }
1553
1554     fn link_whole_rlib(&mut self, path: &Path) {
1555         self.cmd.arg("--rlib").arg(path);
1556     }
1557
1558     fn include_path(&mut self, path: &Path) {
1559         self.cmd.arg("-L").arg(path);
1560     }
1561
1562     fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1563         self.cmd.arg("--debug");
1564     }
1565
1566     fn add_object(&mut self, path: &Path) {
1567         self.cmd.arg("--bitcode").arg(path);
1568     }
1569
1570     fn optimize(&mut self) {
1571         match self.sess.lto() {
1572             Lto::Thin | Lto::Fat | Lto::ThinLocal => {
1573                 self.cmd.arg("-Olto");
1574             }
1575
1576             Lto::No => {}
1577         };
1578     }
1579
1580     fn output_filename(&mut self, path: &Path) {
1581         self.cmd.arg("-o").arg(path);
1582     }
1583
1584     fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
1585         panic!("external dylibs not supported")
1586     }
1587
1588     fn link_rust_dylib(&mut self, _lib: &str, _path: &Path) {
1589         panic!("external dylibs not supported")
1590     }
1591
1592     fn link_staticlib(&mut self, _lib: &str, _verbatim: bool) {
1593         panic!("staticlibs not supported")
1594     }
1595
1596     fn link_whole_staticlib(&mut self, _lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
1597         panic!("staticlibs not supported")
1598     }
1599
1600     fn framework_path(&mut self, _path: &Path) {
1601         panic!("frameworks not supported")
1602     }
1603
1604     fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1605         panic!("frameworks not supported")
1606     }
1607
1608     fn full_relro(&mut self) {}
1609
1610     fn partial_relro(&mut self) {}
1611
1612     fn no_relro(&mut self) {}
1613
1614     fn gc_sections(&mut self, _keep_metadata: bool) {}
1615
1616     fn no_gc_sections(&mut self) {}
1617
1618     fn pgo_gen(&mut self) {}
1619
1620     fn no_crt_objects(&mut self) {}
1621
1622     fn no_default_libraries(&mut self) {}
1623
1624     fn control_flow_guard(&mut self) {}
1625
1626     fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, _symbols: &[String]) {}
1627
1628     fn subsystem(&mut self, _subsystem: &str) {}
1629
1630     fn linker_plugin_lto(&mut self) {}
1631 }
1632
1633 pub struct BpfLinker<'a> {
1634     cmd: Command,
1635     sess: &'a Session,
1636 }
1637
1638 impl<'a> Linker for BpfLinker<'a> {
1639     fn cmd(&mut self) -> &mut Command {
1640         &mut self.cmd
1641     }
1642
1643     fn set_output_kind(&mut self, _output_kind: LinkOutputKind, _out_filename: &Path) {}
1644
1645     fn link_rlib(&mut self, path: &Path) {
1646         self.cmd.arg(path);
1647     }
1648
1649     fn link_whole_rlib(&mut self, path: &Path) {
1650         self.cmd.arg(path);
1651     }
1652
1653     fn include_path(&mut self, path: &Path) {
1654         self.cmd.arg("-L").arg(path);
1655     }
1656
1657     fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1658         self.cmd.arg("--debug");
1659     }
1660
1661     fn add_object(&mut self, path: &Path) {
1662         self.cmd.arg(path);
1663     }
1664
1665     fn optimize(&mut self) {
1666         self.cmd.arg(match self.sess.opts.optimize {
1667             OptLevel::No => "-O0",
1668             OptLevel::Less => "-O1",
1669             OptLevel::Default => "-O2",
1670             OptLevel::Aggressive => "-O3",
1671             OptLevel::Size => "-Os",
1672             OptLevel::SizeMin => "-Oz",
1673         });
1674     }
1675
1676     fn output_filename(&mut self, path: &Path) {
1677         self.cmd.arg("-o").arg(path);
1678     }
1679
1680     fn link_dylib(&mut self, _lib: &str, _verbatim: bool, _as_needed: bool) {
1681         panic!("external dylibs not supported")
1682     }
1683
1684     fn link_rust_dylib(&mut self, _lib: &str, _path: &Path) {
1685         panic!("external dylibs not supported")
1686     }
1687
1688     fn link_staticlib(&mut self, _lib: &str, _verbatim: bool) {
1689         panic!("staticlibs not supported")
1690     }
1691
1692     fn link_whole_staticlib(&mut self, _lib: &str, _verbatim: bool, _search_path: &[PathBuf]) {
1693         panic!("staticlibs not supported")
1694     }
1695
1696     fn framework_path(&mut self, _path: &Path) {
1697         panic!("frameworks not supported")
1698     }
1699
1700     fn link_framework(&mut self, _framework: &str, _as_needed: bool) {
1701         panic!("frameworks not supported")
1702     }
1703
1704     fn full_relro(&mut self) {}
1705
1706     fn partial_relro(&mut self) {}
1707
1708     fn no_relro(&mut self) {}
1709
1710     fn gc_sections(&mut self, _keep_metadata: bool) {}
1711
1712     fn no_gc_sections(&mut self) {}
1713
1714     fn pgo_gen(&mut self) {}
1715
1716     fn no_crt_objects(&mut self) {}
1717
1718     fn no_default_libraries(&mut self) {}
1719
1720     fn control_flow_guard(&mut self) {}
1721
1722     fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[String]) {
1723         let path = tmpdir.join("symbols");
1724         let res: io::Result<()> = try {
1725             let mut f = BufWriter::new(File::create(&path)?);
1726             for sym in symbols {
1727                 writeln!(f, "{}", sym)?;
1728             }
1729         };
1730         if let Err(error) = res {
1731             self.sess.emit_fatal(errors::SymbolFileWriteFailure { error });
1732         } else {
1733             self.cmd.arg("--export-symbols").arg(&path);
1734         }
1735     }
1736
1737     fn subsystem(&mut self, _subsystem: &str) {}
1738
1739     fn linker_plugin_lto(&mut self) {}
1740 }