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