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