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