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