Skip to main content

rustc_codegen_ssa/back/
linker.rs

1use std::ffi::{OsStr, OsString};
2use std::fs::{self, File};
3use std::io::prelude::*;
4use std::path::{Path, PathBuf};
5use std::{env, iter, mem, str};
6
7use find_msvc_tools;
8use rustc_hir::attrs::WindowsSubsystemKind;
9use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
10use rustc_metadata::{
11    find_native_static_library, try_find_native_dynamic_library, try_find_native_static_library,
12};
13use rustc_middle::bug;
14use rustc_middle::middle::dependency_format::Linkage;
15use rustc_middle::middle::exported_symbols::{
16    self, ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
17};
18use rustc_middle::ty::{SymbolName, TyCtxt};
19use rustc_session::Session;
20use rustc_session::config::{self, CrateType, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip};
21use rustc_target::spec::{Arch, Cc, CfgAbi, LinkOutputKind, LinkerFlavor, Lld, Os};
22use tracing::{debug, warn};
23
24use super::command::Command;
25use super::symbol_export;
26use crate::back::symbol_export::allocator_shim_symbols;
27use crate::base::needs_allocator_shim_for_linking;
28use crate::{SymbolExport, errors};
29
30#[cfg(test)]
31mod tests;
32
33/// Disables non-English messages from localized linkers.
34/// Such messages may cause issues with text encoding on Windows (#35785)
35/// and prevent inspection of linker output in case of errors, which we occasionally do.
36/// This should be acceptable because other messages from rustc are in English anyway,
37/// and may also be desirable to improve searchability of the linker diagnostics.
38pub(crate) fn disable_localization(linker: &mut Command) {
39    // No harm in setting both env vars simultaneously.
40    // Unix-style linkers.
41    linker.env("LC_ALL", "C");
42    // MSVC's `link.exe`.
43    linker.env("VSLANG", "1033");
44}
45
46/// The third parameter is for env vars, used on windows to set up the
47/// path for MSVC to find its DLLs, and gcc to find its bundled
48/// toolchain
49pub(crate) fn get_linker<'a>(
50    sess: &'a Session,
51    linker: &Path,
52    flavor: LinkerFlavor,
53    self_contained: bool,
54    target_cpu: &'a str,
55    codegen_backend: &'static str,
56) -> Box<dyn Linker + 'a> {
57    let msvc_tool = find_msvc_tools::find_tool(sess.target.arch.desc(), "link.exe");
58
59    // If our linker looks like a batch script on Windows then to execute this
60    // we'll need to spawn `cmd` explicitly. This is primarily done to handle
61    // emscripten where the linker is `emcc.bat` and needs to be spawned as
62    // `cmd /c emcc.bat ...`.
63    //
64    // This worked historically but is needed manually since #42436 (regression
65    // was tagged as #42791) and some more info can be found on #44443 for
66    // emscripten itself.
67    let mut cmd = match linker.to_str() {
68        Some(linker) if falsecfg!(windows) && linker.ends_with(".bat") => Command::bat_script(linker),
69        _ => match flavor {
70            LinkerFlavor::Gnu(Cc::No, Lld::Yes)
71            | LinkerFlavor::Darwin(Cc::No, Lld::Yes)
72            | LinkerFlavor::WasmLld(Cc::No)
73            | LinkerFlavor::Msvc(Lld::Yes) => Command::lld(linker, flavor.lld_flavor()),
74            LinkerFlavor::Msvc(Lld::No)
75                if sess.opts.cg.linker.is_none() && sess.target.linker.is_none() =>
76            {
77                Command::new(msvc_tool.as_ref().map_or(linker, |t| t.path()))
78            }
79            _ => Command::new(linker),
80        },
81    };
82
83    // UWP apps have API restrictions enforced during Store submissions.
84    // To comply with the Windows App Certification Kit,
85    // MSVC needs to link with the Store versions of the runtime libraries (vcruntime, msvcrt, etc).
86    let t = &sess.target;
87    if #[allow(non_exhaustive_omitted_patterns)] match flavor {
    LinkerFlavor::Msvc(..) => true,
    _ => false,
}matches!(flavor, LinkerFlavor::Msvc(..)) && t.cfg_abi == CfgAbi::Uwp {
88        if let Some(ref tool) = msvc_tool {
89            let original_path = tool.path();
90            if let Some(root_lib_path) = original_path.ancestors().nth(4) {
91                let arch = match t.arch {
92                    Arch::X86_64 => Some("x64"),
93                    Arch::X86 => Some("x86"),
94                    Arch::AArch64 => Some("arm64"),
95                    Arch::Arm => Some("arm"),
96                    _ => None,
97                };
98                if let Some(ref a) = arch {
99                    // FIXME: Move this to `fn linker_with_args`.
100                    let mut arg = OsString::from("/LIBPATH:");
101                    arg.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}\\lib\\{1}\\store",
                root_lib_path.display(), a))
    })format!("{}\\lib\\{}\\store", root_lib_path.display(), a));
102                    cmd.arg(&arg);
103                } else {
104                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:104",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(104u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("arch is not supported")
                                            as &dyn Value))])
            });
    } else { ; }
};warn!("arch is not supported");
105                }
106            } else {
107                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:107",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(107u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("MSVC root path lib location not found")
                                            as &dyn Value))])
            });
    } else { ; }
};warn!("MSVC root path lib location not found");
108            }
109        } else {
110            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:110",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::WARN,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(110u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::WARN <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::WARN <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("link.exe not found")
                                            as &dyn Value))])
            });
    } else { ; }
};warn!("link.exe not found");
111        }
112    }
113
114    // The compiler's sysroot often has some bundled tools, so add it to the
115    // PATH for the child.
116    let mut new_path = sess.get_tools_search_paths(self_contained);
117    let mut msvc_changed_path = false;
118    if sess.target.is_like_msvc
119        && let Some(ref tool) = msvc_tool
120    {
121        for (k, v) in tool.env() {
122            if k == "PATH" {
123                new_path.extend(env::split_paths(v));
124                msvc_changed_path = true;
125            } else {
126                cmd.env(k, v);
127            }
128        }
129    }
130
131    if !msvc_changed_path && let Some(path) = env::var_os("PATH") {
132        new_path.extend(env::split_paths(&path));
133    }
134    cmd.env("PATH", env::join_paths(new_path).unwrap());
135
136    // FIXME: Move `/LIBPATH` addition for uwp targets from the linker construction
137    // to the linker args construction.
138    if !(cmd.get_args().is_empty() || sess.target.cfg_abi == CfgAbi::Uwp) {
    ::core::panicking::panic("assertion failed: cmd.get_args().is_empty() || sess.target.cfg_abi == CfgAbi::Uwp")
};assert!(cmd.get_args().is_empty() || sess.target.cfg_abi == CfgAbi::Uwp);
139    match flavor {
140        LinkerFlavor::Unix(Cc::No) if sess.target.os == Os::L4Re => {
141            Box::new(L4Bender::new(cmd, sess)) as Box<dyn Linker>
142        }
143        LinkerFlavor::Unix(Cc::No) if sess.target.os == Os::Aix => {
144            Box::new(AixLinker::new(cmd, sess)) as Box<dyn Linker>
145        }
146        LinkerFlavor::WasmLld(Cc::No) => Box::new(WasmLd::new(cmd, sess)) as Box<dyn Linker>,
147        LinkerFlavor::Gnu(cc, _)
148        | LinkerFlavor::Darwin(cc, _)
149        | LinkerFlavor::WasmLld(cc)
150        | LinkerFlavor::Unix(cc) => Box::new(GccLinker {
151            cmd,
152            sess,
153            target_cpu,
154            hinted_static: None,
155            is_ld: cc == Cc::No,
156            is_gnu: flavor.is_gnu(),
157            uses_lld: flavor.uses_lld(),
158            codegen_backend,
159        }) as Box<dyn Linker>,
160        LinkerFlavor::Msvc(..) => Box::new(MsvcLinker { cmd, sess }) as Box<dyn Linker>,
161        LinkerFlavor::EmCc => Box::new(EmLinker { cmd, sess }) as Box<dyn Linker>,
162        LinkerFlavor::Bpf => Box::new(BpfLinker { cmd, sess }) as Box<dyn Linker>,
163        LinkerFlavor::Llbc => Box::new(LlbcLinker { cmd, sess }) as Box<dyn Linker>,
164    }
165}
166
167// Note: Ideally neither these helper function, nor the macro-generated inherent methods below
168// would exist, and these functions would live in `trait Linker`.
169// Unfortunately, adding these functions to `trait Linker` make it `dyn`-incompatible.
170// If the methods are added to the trait with `where Self: Sized` bounds, then even a separate
171// implementation of them for `dyn Linker {}` wouldn't work due to a conflict with those
172// uncallable methods in the trait.
173
174/// Just pass the arguments to the linker as is.
175/// It is assumed that they are correctly prepared in advance.
176fn verbatim_args<L: Linker + ?Sized>(
177    l: &mut L,
178    args: impl IntoIterator<Item: AsRef<OsStr>>,
179) -> &mut L {
180    for arg in args {
181        l.cmd().arg(arg);
182    }
183    l
184}
185/// Add underlying linker arguments to C compiler command, by wrapping them in
186/// `-Wl` or `-Xlinker`.
187fn convert_link_args_to_cc_args(cmd: &mut Command, args: impl IntoIterator<Item: AsRef<OsStr>>) {
188    let mut combined_arg = OsString::from("-Wl");
189    for arg in args {
190        // If the argument itself contains a comma, we need to emit it
191        // as `-Xlinker`, otherwise we can use `-Wl`.
192        if arg.as_ref().as_encoded_bytes().contains(&b',') {
193            // Emit current `-Wl` argument, if any has been built.
194            if combined_arg != OsStr::new("-Wl") {
195                cmd.arg(combined_arg);
196                // Begin next `-Wl` argument.
197                combined_arg = OsString::from("-Wl");
198            }
199
200            // Emit `-Xlinker` argument.
201            cmd.arg("-Xlinker");
202            cmd.arg(arg);
203        } else {
204            // Append to `-Wl` argument.
205            combined_arg.push(",");
206            combined_arg.push(arg);
207        }
208    }
209    // Emit final `-Wl` argument.
210    if combined_arg != OsStr::new("-Wl") {
211        cmd.arg(combined_arg);
212    }
213}
214/// Arguments for the underlying linker.
215/// Add options to pass them through cc wrapper if `Linker` is a cc wrapper.
216fn link_args<L: Linker + ?Sized>(l: &mut L, args: impl IntoIterator<Item: AsRef<OsStr>>) -> &mut L {
217    if !l.is_cc() {
218        verbatim_args(l, args);
219    } else {
220        convert_link_args_to_cc_args(l.cmd(), args);
221    }
222    l
223}
224/// Arguments for the cc wrapper specifically.
225/// Check that it's indeed a cc wrapper and pass verbatim.
226fn cc_args<L: Linker + ?Sized>(l: &mut L, args: impl IntoIterator<Item: AsRef<OsStr>>) -> &mut L {
227    if !l.is_cc() { ::core::panicking::panic("assertion failed: l.is_cc()") };assert!(l.is_cc());
228    verbatim_args(l, args)
229}
230/// Arguments supported by both underlying linker and cc wrapper, pass verbatim.
231fn link_or_cc_args<L: Linker + ?Sized>(
232    l: &mut L,
233    args: impl IntoIterator<Item: AsRef<OsStr>>,
234) -> &mut L {
235    verbatim_args(l, args)
236}
237
238macro_rules! generate_arg_methods {
239    ($($ty:ty)*) => { $(
240        impl $ty {
241            #[allow(unused)]
242            pub(crate) fn verbatim_args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) -> &mut Self {
243                verbatim_args(self, args)
244            }
245            #[allow(unused)]
246            pub(crate) fn verbatim_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
247                verbatim_args(self, iter::once(arg))
248            }
249            #[allow(unused)]
250            pub(crate) fn link_args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) -> &mut Self {
251                link_args(self, args)
252            }
253            #[allow(unused)]
254            pub(crate) fn link_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
255                link_args(self, iter::once(arg))
256            }
257            #[allow(unused)]
258            pub(crate) fn cc_args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) -> &mut Self {
259                cc_args(self, args)
260            }
261            #[allow(unused)]
262            pub(crate) fn cc_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
263                cc_args(self, iter::once(arg))
264            }
265            #[allow(unused)]
266            pub(crate) fn link_or_cc_args(&mut self, args: impl IntoIterator<Item: AsRef<OsStr>>) -> &mut Self {
267                link_or_cc_args(self, args)
268            }
269            #[allow(unused)]
270            pub(crate) fn link_or_cc_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
271                link_or_cc_args(self, iter::once(arg))
272            }
273        }
274    )* }
275}
276
277impl dyn Linker + '_ {
    #[allow(unused)]
    pub(crate) fn verbatim_args(&mut self,
        args: impl IntoIterator<Item : AsRef<OsStr>>) -> &mut Self {
        verbatim_args(self, args)
    }
    #[allow(unused)]
    pub(crate) fn verbatim_arg(&mut self, arg: impl AsRef<OsStr>)
        -> &mut Self {
        verbatim_args(self, iter::once(arg))
    }
    #[allow(unused)]
    pub(crate) fn link_args(&mut self,
        args: impl IntoIterator<Item : AsRef<OsStr>>) -> &mut Self {
        link_args(self, args)
    }
    #[allow(unused)]
    pub(crate) fn link_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
        link_args(self, iter::once(arg))
    }
    #[allow(unused)]
    pub(crate) fn cc_args(&mut self,
        args: impl IntoIterator<Item : AsRef<OsStr>>) -> &mut Self {
        cc_args(self, args)
    }
    #[allow(unused)]
    pub(crate) fn cc_arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
        cc_args(self, iter::once(arg))
    }
    #[allow(unused)]
    pub(crate) fn link_or_cc_args(&mut self,
        args: impl IntoIterator<Item : AsRef<OsStr>>) -> &mut Self {
        link_or_cc_args(self, args)
    }
    #[allow(unused)]
    pub(crate) fn link_or_cc_arg(&mut self, arg: impl AsRef<OsStr>)
        -> &mut Self {
        link_or_cc_args(self, iter::once(arg))
    }
}generate_arg_methods! {
278    GccLinker<'_>
279    MsvcLinker<'_>
280    EmLinker<'_>
281    WasmLd<'_>
282    L4Bender<'_>
283    AixLinker<'_>
284    LlbcLinker<'_>
285    BpfLinker<'_>
286    dyn Linker + '_
287}
288
289/// Linker abstraction used by `back::link` to build up the command to invoke a
290/// linker.
291///
292/// This trait is the total list of requirements needed by `back::link` and
293/// represents the meaning of each option being passed down. This trait is then
294/// used to dispatch on whether a GNU-like linker (generally `ld.exe`) or an
295/// MSVC linker (e.g., `link.exe`) is being used.
296pub(crate) trait Linker {
297    fn cmd(&mut self) -> &mut Command;
298    fn is_cc(&self) -> bool {
299        false
300    }
301    fn set_output_kind(
302        &mut self,
303        output_kind: LinkOutputKind,
304        crate_type: CrateType,
305        out_filename: &Path,
306    );
307    fn link_dylib_by_name(&mut self, _name: &str, _verbatim: bool, _as_needed: bool) {
308        ::rustc_middle::util::bug::bug_fmt(format_args!("dylib linked with unsupported linker"))bug!("dylib linked with unsupported linker")
309    }
310    fn link_dylib_by_path(&mut self, _path: &Path, _as_needed: bool) {
311        ::rustc_middle::util::bug::bug_fmt(format_args!("dylib linked with unsupported linker"))bug!("dylib linked with unsupported linker")
312    }
313    fn link_framework_by_name(&mut self, _name: &str, _verbatim: bool, _as_needed: bool) {
314        ::rustc_middle::util::bug::bug_fmt(format_args!("framework linked with unsupported linker"))bug!("framework linked with unsupported linker")
315    }
316    fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool);
317    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool);
318    fn include_path(&mut self, path: &Path) {
319        link_or_cc_args(link_or_cc_args(self, &["-L"]), &[path]);
320    }
321    fn framework_path(&mut self, _path: &Path) {
322        ::rustc_middle::util::bug::bug_fmt(format_args!("framework path set with unsupported linker"))bug!("framework path set with unsupported linker")
323    }
324    fn output_filename(&mut self, path: &Path) {
325        link_or_cc_args(link_or_cc_args(self, &["-o"]), &[path]);
326    }
327    fn add_object(&mut self, path: &Path) {
328        link_or_cc_args(self, &[path]);
329    }
330    fn gc_sections(&mut self, keep_metadata: bool);
331    fn full_relro(&mut self);
332    fn partial_relro(&mut self);
333    fn no_relro(&mut self);
334    fn optimize(&mut self);
335    fn pgo_gen(&mut self);
336    fn control_flow_guard(&mut self);
337    fn ehcont_guard(&mut self);
338    fn debuginfo(&mut self, strip: Strip, natvis_debugger_visualizers: &[PathBuf]);
339    fn no_crt_objects(&mut self);
340    fn no_default_libraries(&mut self);
341    fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[SymbolExport]);
342    fn windows_subsystem(&mut self, subsystem: WindowsSubsystemKind);
343    fn linker_plugin_lto(&mut self);
344    fn add_eh_frame_header(&mut self) {}
345    fn add_no_exec(&mut self) {}
346    fn add_as_needed(&mut self) {}
347    fn reset_per_library_state(&mut self) {}
348    fn enable_profiling(&mut self) {}
349}
350
351impl dyn Linker + '_ {
352    pub(crate) fn take_cmd(&mut self) -> Command {
353        mem::replace(self.cmd(), Command::new(""))
354    }
355}
356
357struct GccLinker<'a> {
358    cmd: Command,
359    sess: &'a Session,
360    target_cpu: &'a str,
361    hinted_static: Option<bool>, // Keeps track of the current hinting mode.
362    // Link as ld
363    is_ld: bool,
364    is_gnu: bool,
365    uses_lld: bool,
366    codegen_backend: &'static str,
367}
368
369impl<'a> GccLinker<'a> {
370    fn takes_hints(&self) -> bool {
371        // Really this function only returns true if the underlying linker
372        // configured for a compiler is binutils `ld.bfd` and `ld.gold`. We
373        // don't really have a foolproof way to detect that, so rule out some
374        // platforms where currently this is guaranteed to *not* be the case:
375        //
376        // * On OSX they have their own linker, not binutils'
377        // * For WebAssembly the only functional linker is LLD, which doesn't
378        //   support hint flags
379        !self.sess.target.is_like_darwin && !self.sess.target.is_like_wasm
380    }
381
382    // Some platforms take hints about whether a library is static or dynamic.
383    // For those that support this, we ensure we pass the option if the library
384    // was flagged "static" (most defaults are dynamic) to ensure that if
385    // libfoo.a and libfoo.so both exist that the right one is chosen.
386    fn hint_static(&mut self) {
387        if !self.takes_hints() {
388            return;
389        }
390        if self.hinted_static != Some(true) {
391            self.link_arg("-Bstatic");
392            self.hinted_static = Some(true);
393        }
394    }
395
396    fn hint_dynamic(&mut self) {
397        if !self.takes_hints() {
398            return;
399        }
400        if self.hinted_static != Some(false) {
401            self.link_arg("-Bdynamic");
402            self.hinted_static = Some(false);
403        }
404    }
405
406    fn push_linker_plugin_lto_args(&mut self, plugin_path: Option<&OsStr>) {
407        if let Some(plugin_path) = plugin_path {
408            let mut arg = OsString::from("-plugin=");
409            arg.push(plugin_path);
410            self.link_arg(&arg);
411        }
412
413        let opt_level = match self.sess.opts.optimize {
414            config::OptLevel::No => "O0",
415            config::OptLevel::Less => "O1",
416            config::OptLevel::More | config::OptLevel::Size | config::OptLevel::SizeMin => "O2",
417            config::OptLevel::Aggressive => "O3",
418        };
419
420        if let Some(path) = &self.sess.opts.unstable_opts.profile_sample_use {
421            self.link_arg(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-plugin-opt=sample-profile={0}",
                path.display()))
    })format!("-plugin-opt=sample-profile={}", path.display()));
422        };
423        let prefix = if self.codegen_backend == "gcc" {
424            // The GCC linker plugin requires a leading dash.
425            "-"
426        } else {
427            ""
428        };
429        self.link_args(&[
430            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-plugin-opt={0}{1}", prefix,
                opt_level))
    })format!("-plugin-opt={prefix}{opt_level}"),
431            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-plugin-opt={1}mcpu={0}",
                self.target_cpu, prefix))
    })format!("-plugin-opt={prefix}mcpu={}", self.target_cpu),
432        ]);
433    }
434
435    fn build_dylib(&mut self, crate_type: CrateType, out_filename: &Path) {
436        // On mac we need to tell the linker to let this library be rpathed
437        if self.sess.target.is_like_darwin {
438            if self.is_cc() {
439                // `-dynamiclib` makes `cc` pass `-dylib` to the linker.
440                self.cc_arg("-dynamiclib");
441            } else {
442                self.link_arg("-dylib");
443                // Clang also sets `-dynamic`, but that's implied by `-dylib`, so unnecessary.
444            }
445
446            // Note that the `osx_rpath_install_name` option here is a hack
447            // purely to support bootstrap right now, we should get a more
448            // principled solution at some point to force the compiler to pass
449            // the right `-Wl,-install_name` with an `@rpath` in it.
450            if self.sess.opts.cg.rpath || self.sess.opts.unstable_opts.osx_rpath_install_name {
451                let mut rpath = OsString::from("@rpath/");
452                rpath.push(out_filename.file_name().unwrap());
453                self.link_arg("-install_name").link_arg(rpath);
454            }
455        } else {
456            self.link_or_cc_arg("-shared");
457            if let Some(name) = out_filename.file_name() {
458                if self.sess.target.is_like_windows {
459                    // The output filename already contains `dll_suffix` so
460                    // the resulting import library will have a name in the
461                    // form of libfoo.dll.a
462                    let (prefix, suffix) = self.sess.staticlib_components(false);
463                    let mut implib_name = OsString::from(prefix);
464                    implib_name.push(name);
465                    implib_name.push(suffix);
466                    let mut out_implib = OsString::from("--out-implib=");
467                    out_implib.push(out_filename.with_file_name(implib_name));
468                    self.link_arg(out_implib);
469                } else if crate_type == CrateType::Dylib {
470                    // When dylibs are linked by a full path this value will get into `DT_NEEDED`
471                    // instead of the full path, so the library can be later found in some other
472                    // location than that specific path.
473                    let mut soname = OsString::from("-soname=");
474                    soname.push(name);
475                    self.link_arg(soname);
476                }
477            }
478        }
479    }
480
481    fn with_as_needed(&mut self, as_needed: bool, f: impl FnOnce(&mut Self)) {
482        if !as_needed {
483            if self.sess.target.is_like_darwin {
484                // FIXME(81490): ld64 doesn't support these flags but macOS 11
485                // has -needed-l{} / -needed_library {}
486                // but we have no way to detect that here.
487                self.sess.dcx().emit_warn(errors::Ld64UnimplementedModifier);
488            } else if self.is_gnu && !self.sess.target.is_like_windows {
489                self.link_arg("--no-as-needed");
490            } else {
491                self.sess.dcx().emit_warn(errors::LinkerUnsupportedModifier);
492            }
493        }
494
495        f(self);
496
497        if !as_needed {
498            if self.sess.target.is_like_darwin {
499                // See above FIXME comment
500            } else if self.is_gnu && !self.sess.target.is_like_windows {
501                self.link_arg("--as-needed");
502            }
503        }
504    }
505}
506
507impl<'a> Linker for GccLinker<'a> {
508    fn cmd(&mut self) -> &mut Command {
509        &mut self.cmd
510    }
511
512    fn is_cc(&self) -> bool {
513        !self.is_ld
514    }
515
516    fn set_output_kind(
517        &mut self,
518        output_kind: LinkOutputKind,
519        crate_type: CrateType,
520        out_filename: &Path,
521    ) {
522        match output_kind {
523            LinkOutputKind::DynamicNoPicExe => {
524                // noop on windows w/ gcc, warning w/ clang
525                if !self.is_ld && self.is_gnu && !self.sess.target.is_like_windows {
526                    self.cc_arg("-no-pie");
527                }
528            }
529            LinkOutputKind::DynamicPicExe => {
530                // noop on windows w/ gcc & ld, error w/ lld
531                if !self.sess.target.is_like_windows {
532                    // `-pie` works for both gcc wrapper and ld.
533                    self.link_or_cc_arg("-pie");
534                }
535            }
536            LinkOutputKind::StaticNoPicExe => {
537                // `-static` works for both gcc wrapper and ld.
538                self.link_or_cc_arg("-static");
539                if !self.is_ld && self.is_gnu {
540                    self.cc_arg("-no-pie");
541                }
542            }
543            LinkOutputKind::StaticPicExe => {
544                if !self.is_ld {
545                    // Note that combination `-static -pie` doesn't work as expected
546                    // for the gcc wrapper, `-static` in that case suppresses `-pie`.
547                    self.cc_arg("-static-pie");
548                } else {
549                    // `--no-dynamic-linker` and `-z text` are not strictly necessary for producing
550                    // a static pie, but currently passed because gcc and clang pass them.
551                    // The former suppresses the `INTERP` ELF header specifying dynamic linker,
552                    // which is otherwise implicitly injected by ld (but not lld).
553                    // The latter doesn't change anything, only ensures that everything is pic.
554                    self.link_args(&["-static", "-pie", "--no-dynamic-linker", "-z", "text"]);
555                }
556            }
557            LinkOutputKind::DynamicDylib => self.build_dylib(crate_type, out_filename),
558            LinkOutputKind::StaticDylib => {
559                self.link_or_cc_arg("-static");
560                self.build_dylib(crate_type, out_filename);
561            }
562            LinkOutputKind::WasiReactorExe => {
563                self.link_args(&["--entry", "_initialize"]);
564            }
565        }
566
567        // VxWorks compiler driver introduced `--static-crt` flag specifically for rustc,
568        // it switches linking for libc and similar system libraries to static without using
569        // any `#[link]` attributes in the `libc` crate, see #72782 for details.
570        // FIXME: Switch to using `#[link]` attributes in the `libc` crate
571        // similarly to other targets.
572        if self.sess.target.os == Os::VxWorks
573            && #[allow(non_exhaustive_omitted_patterns)] match output_kind {
    LinkOutputKind::StaticNoPicExe | LinkOutputKind::StaticPicExe |
        LinkOutputKind::StaticDylib => true,
    _ => false,
}matches!(
574                output_kind,
575                LinkOutputKind::StaticNoPicExe
576                    | LinkOutputKind::StaticPicExe
577                    | LinkOutputKind::StaticDylib
578            )
579        {
580            self.cc_arg("--static-crt");
581        }
582
583        // avr-none doesn't have default ISA, users must specify which specific
584        // CPU (well, microcontroller) they are targetting using `-Ctarget-cpu`.
585        //
586        // Currently this makes sense only when using avr-gcc as a linker, since
587        // it brings a couple of hand-written important intrinsics from libgcc.
588        if self.sess.target.arch == Arch::Avr && !self.uses_lld {
589            self.verbatim_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-mmcu={0}", self.target_cpu))
    })format!("-mmcu={}", self.target_cpu));
590        }
591    }
592
593    fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, as_needed: bool) {
594        if self.sess.target.os == Os::Illumos && name == "c" {
595            // libc will be added via late_link_args on illumos so that it will
596            // appear last in the library search order.
597            // FIXME: This should be replaced by a more complete and generic
598            // mechanism for controlling the order of library arguments passed
599            // to the linker.
600            return;
601        }
602        self.hint_dynamic();
603        self.with_as_needed(as_needed, |this| {
604            let colon = if verbatim && this.is_gnu { ":" } else { "" };
605            this.link_or_cc_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}{1}", colon, name))
    })format!("-l{colon}{name}"));
606        });
607    }
608
609    fn link_dylib_by_path(&mut self, path: &Path, as_needed: bool) {
610        self.hint_dynamic();
611        self.with_as_needed(as_needed, |this| {
612            this.link_or_cc_arg(path);
613        })
614    }
615
616    fn link_framework_by_name(&mut self, name: &str, _verbatim: bool, as_needed: bool) {
617        self.hint_dynamic();
618        if !as_needed {
619            // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
620            // flag but we have no way to detect that here.
621            // self.link_or_cc_arg("-needed_framework").link_or_cc_arg(name);
622            self.sess.dcx().emit_warn(errors::Ld64UnimplementedModifier);
623        }
624        self.link_or_cc_args(&["-framework", name]);
625    }
626
627    fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool) {
628        self.hint_static();
629        let colon = if verbatim && self.is_gnu { ":" } else { "" };
630        if !whole_archive {
631            self.link_or_cc_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}{1}", colon, name))
    })format!("-l{colon}{name}"));
632        } else if self.sess.target.is_like_darwin {
633            // -force_load is the macOS equivalent of --whole-archive, but it
634            // involves passing the full path to the library to link.
635            self.link_arg("-force_load");
636            self.link_arg(find_native_static_library(name, verbatim, self.sess));
637        } else {
638            self.link_arg("--whole-archive")
639                .link_or_cc_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}{1}", colon, name))
    })format!("-l{colon}{name}"))
640                .link_arg("--no-whole-archive");
641        }
642    }
643
644    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
645        self.hint_static();
646        if !whole_archive {
647            self.link_or_cc_arg(path);
648        } else if self.sess.target.is_like_darwin {
649            self.link_arg("-force_load").link_arg(path);
650        } else {
651            self.link_arg("--whole-archive").link_arg(path).link_arg("--no-whole-archive");
652        }
653    }
654
655    fn framework_path(&mut self, path: &Path) {
656        self.link_or_cc_arg("-F").link_or_cc_arg(path);
657    }
658    fn full_relro(&mut self) {
659        self.link_args(&["-z", "relro", "-z", "now"]);
660    }
661    fn partial_relro(&mut self) {
662        self.link_args(&["-z", "relro"]);
663    }
664    fn no_relro(&mut self) {
665        self.link_args(&["-z", "norelro"]);
666    }
667
668    fn gc_sections(&mut self, keep_metadata: bool) {
669        // The dead_strip option to the linker specifies that functions and data
670        // unreachable by the entry point will be removed. This is quite useful
671        // with Rust's compilation model of compiling libraries at a time into
672        // one object file. For example, this brings hello world from 1.7MB to
673        // 458K.
674        //
675        // Note that this is done for both executables and dynamic libraries. We
676        // won't get much benefit from dylibs because LLVM will have already
677        // stripped away as much as it could. This has not been seen to impact
678        // link times negatively.
679        //
680        // -dead_strip can't be part of the pre_link_args because it's also used
681        // for partial linking when using multiple codegen units (-r). So we
682        // insert it here.
683        if self.sess.target.is_like_darwin {
684            self.link_arg("-dead_strip");
685
686        // If we're building a dylib, we don't use --gc-sections because LLVM
687        // has already done the best it can do, and we also don't want to
688        // eliminate the metadata. If we're building an executable, however,
689        // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
690        // reduction.
691        } else if (self.is_gnu || self.sess.target.is_like_wasm) && !keep_metadata {
692            self.link_arg("--gc-sections");
693        }
694    }
695
696    fn optimize(&mut self) {
697        if !self.is_gnu && !self.sess.target.is_like_wasm {
698            return;
699        }
700
701        // GNU-style linkers support optimization with -O. GNU ld doesn't
702        // need a numeric argument, but other linkers do.
703        if self.sess.opts.optimize == config::OptLevel::More
704            || self.sess.opts.optimize == config::OptLevel::Aggressive
705        {
706            self.link_arg("-O1");
707        }
708    }
709
710    fn pgo_gen(&mut self) {
711        if !self.is_gnu {
712            return;
713        }
714
715        // If we're doing PGO generation stuff and on a GNU-like linker, use the
716        // "-u" flag to properly pull in the profiler runtime bits.
717        //
718        // This is because LLVM otherwise won't add the needed initialization
719        // for us on Linux (though the extra flag should be harmless if it
720        // does).
721        //
722        // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
723        //
724        // Though it may be worth to try to revert those changes upstream, since
725        // the overhead of the initialization should be minor.
726        self.link_or_cc_args(&["-u", "__llvm_profile_runtime"]);
727    }
728
729    fn enable_profiling(&mut self) {
730        // This flag is also used when linking to choose target specific
731        // libraries needed to enable profiling.
732        if !self.is_ld {
733            self.cc_arg("-pg");
734            // On windows-gnu targets, libgmon also needs to be linked, and this
735            // requires readding libraries to satisfy its dependencies.
736            if self.sess.target.is_like_windows {
737                self.cc_arg("-lgmon");
738                self.cc_arg("-lkernel32");
739                self.cc_arg("-lmsvcrt");
740            }
741        }
742    }
743
744    fn control_flow_guard(&mut self) {}
745
746    fn ehcont_guard(&mut self) {}
747
748    fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
749        // MacOS linker doesn't support stripping symbols directly anymore.
750        if self.sess.target.is_like_darwin {
751            return;
752        }
753
754        match strip {
755            Strip::None => {}
756            Strip::Debuginfo => {
757                // The illumos linker does not support --strip-debug although
758                // it does support --strip-all as a compatibility alias for -s.
759                // The --strip-debug case is handled by running an external
760                // `strip` utility as a separate step after linking.
761                if !self.sess.target.is_like_solaris {
762                    self.link_arg("--strip-debug");
763                }
764            }
765            Strip::Symbols => {
766                self.link_arg("--strip-all");
767            }
768        }
769        match self.sess.opts.unstable_opts.debuginfo_compression {
770            config::DebugInfoCompression::None => {}
771            config::DebugInfoCompression::Zlib => {
772                self.link_arg("--compress-debug-sections=zlib");
773            }
774            config::DebugInfoCompression::Zstd => {
775                self.link_arg("--compress-debug-sections=zstd");
776            }
777        }
778    }
779
780    fn no_crt_objects(&mut self) {
781        if !self.is_ld {
782            self.cc_arg("-nostartfiles");
783        }
784    }
785
786    fn no_default_libraries(&mut self) {
787        if !self.is_ld {
788            self.cc_arg("-nodefaultlibs");
789        }
790    }
791
792    fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[SymbolExport]) {
793        // Symbol visibility in object files typically takes care of this.
794        if crate_type == CrateType::Executable {
795            let should_export_executable_symbols =
796                self.sess.opts.unstable_opts.export_executable_symbols;
797            if self.sess.target.override_export_symbols.is_none()
798                && !should_export_executable_symbols
799            {
800                return;
801            }
802        }
803
804        // We manually create a list of exported symbols to ensure we don't expose any more.
805        // The object files have far more public symbols than we actually want to export,
806        // so we hide them all here.
807
808        if !self.sess.target.limit_rdylib_exports {
809            return;
810        }
811
812        let path = tmpdir.join(if self.sess.target.is_like_windows { "list.def" } else { "list" });
813        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:813",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(813u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("EXPORTED SYMBOLS:")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("EXPORTED SYMBOLS:");
814
815        if self.sess.target.is_like_darwin {
816            // Write a plain, newline-separated list of symbols
817            let res = try {
818                let mut f = File::create_buffered(&path)?;
819                for sym in symbols {
820                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:820",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(820u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("  _{0}",
                                                    sym.name) as &dyn Value))])
            });
    } else { ; }
};debug!("  _{}", sym.name);
821                    f.write_fmt(format_args!("_{0}\n", sym.name))writeln!(f, "_{}", sym.name)?;
822                }
823            };
824            if let Err(error) = res {
825                self.sess.dcx().emit_fatal(errors::LibDefWriteFailure { error });
826            }
827            self.link_arg("-exported_symbols_list").link_arg(path);
828        } else if self.sess.target.is_like_windows {
829            let res = try {
830                let mut f = File::create_buffered(&path)?;
831
832                // .def file similar to MSVC one but without LIBRARY section
833                // because LD doesn't like when it's empty
834                f.write_fmt(format_args!("EXPORTS\n"))writeln!(f, "EXPORTS")?;
835                for symbol in symbols {
836                    let kind_marker =
837                        if symbol.kind == SymbolExportKind::Data { " DATA" } else { "" };
838                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:838",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(838u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("  _{0}",
                                                    symbol.name) as &dyn Value))])
            });
    } else { ; }
};debug!("  _{}", symbol.name);
839                    // Quote the name in case it's reserved by linker in some way
840                    // (this accounts for names with dots in particular).
841                    f.write_fmt(format_args!("  \"{0}\"{1}\n", symbol.name, kind_marker))writeln!(f, "  \"{}\"{kind_marker}", symbol.name)?;
842                }
843            };
844            if let Err(error) = res {
845                self.sess.dcx().emit_fatal(errors::LibDefWriteFailure { error });
846            }
847            self.link_arg(path);
848        } else if self.sess.target.is_like_wasm {
849            self.link_arg("--no-export-dynamic");
850            for sym in symbols {
851                self.link_arg("--export").link_arg(&sym.name);
852            }
853        } else if crate_type == CrateType::Executable && !self.sess.target.is_like_solaris {
854            let res = try {
855                let mut f = File::create_buffered(&path)?;
856                f.write_fmt(format_args!("{{\n"))writeln!(f, "{{")?;
857                for sym in symbols {
858                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:858",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(858u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("{0}",
                                                    sym.name) as &dyn Value))])
            });
    } else { ; }
};debug!("{}", sym.name);
859                    f.write_fmt(format_args!("  {0};\n", sym.name))writeln!(f, "  {};", sym.name)?;
860                }
861                f.write_fmt(format_args!("}};\n"))writeln!(f, "}};")?;
862            };
863            if let Err(error) = res {
864                self.sess.dcx().emit_fatal(errors::VersionScriptWriteFailure { error });
865            }
866            self.link_arg("--dynamic-list").link_arg(path);
867        } else {
868            // Write an LD version script
869            let res = try {
870                let mut f = File::create_buffered(&path)?;
871                f.write_fmt(format_args!("{{\n"))writeln!(f, "{{")?;
872                if !symbols.is_empty() {
873                    f.write_fmt(format_args!("  global:\n"))writeln!(f, "  global:")?;
874                    for sym in symbols {
875                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:875",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(875u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("    {0};",
                                                    sym.name) as &dyn Value))])
            });
    } else { ; }
};debug!("    {};", sym.name);
876                        f.write_fmt(format_args!("    {0};\n", sym.name))writeln!(f, "    {};", sym.name)?;
877                    }
878                }
879                f.write_fmt(format_args!("\n  local:\n    *;\n}};\n"))writeln!(f, "\n  local:\n    *;\n}};")?;
880            };
881            if let Err(error) = res {
882                self.sess.dcx().emit_fatal(errors::VersionScriptWriteFailure { error });
883            }
884            if self.sess.target.is_like_solaris {
885                self.link_arg("-M").link_arg(path);
886            } else {
887                let mut arg = OsString::from("--version-script=");
888                arg.push(path);
889                self.link_arg(arg).link_arg("--no-undefined-version");
890            }
891        }
892    }
893
894    fn windows_subsystem(&mut self, subsystem: WindowsSubsystemKind) {
895        self.link_args(&["--subsystem", subsystem.as_str()]);
896    }
897
898    fn reset_per_library_state(&mut self) {
899        self.hint_dynamic(); // Reset to default before returning the composed command line.
900    }
901
902    fn linker_plugin_lto(&mut self) {
903        match self.sess.opts.cg.linker_plugin_lto {
904            LinkerPluginLto::Disabled => {
905                // Nothing to do
906            }
907            LinkerPluginLto::LinkerPluginAuto => {
908                self.push_linker_plugin_lto_args(None);
909            }
910            LinkerPluginLto::LinkerPlugin(ref path) => {
911                self.push_linker_plugin_lto_args(Some(path.as_os_str()));
912            }
913        }
914    }
915
916    // Add the `GNU_EH_FRAME` program header which is required to locate unwinding information.
917    // Some versions of `gcc` add it implicitly, some (e.g. `musl-gcc`) don't,
918    // so we just always add it.
919    fn add_eh_frame_header(&mut self) {
920        self.link_arg("--eh-frame-hdr");
921    }
922
923    fn add_no_exec(&mut self) {
924        if self.sess.target.is_like_windows {
925            self.link_arg("--nxcompat");
926        } else if self.is_gnu {
927            self.link_args(&["-z", "noexecstack"]);
928        }
929    }
930
931    fn add_as_needed(&mut self) {
932        if self.is_gnu && !self.sess.target.is_like_windows {
933            self.link_arg("--as-needed");
934        } else if self.sess.target.is_like_solaris {
935            // -z ignore is the Solaris equivalent to the GNU ld --as-needed option
936            self.link_args(&["-z", "ignore"]);
937        }
938    }
939}
940
941struct MsvcLinker<'a> {
942    cmd: Command,
943    sess: &'a Session,
944}
945
946impl<'a> Linker for MsvcLinker<'a> {
947    fn cmd(&mut self) -> &mut Command {
948        &mut self.cmd
949    }
950
951    fn set_output_kind(
952        &mut self,
953        output_kind: LinkOutputKind,
954        _crate_type: CrateType,
955        out_filename: &Path,
956    ) {
957        match output_kind {
958            LinkOutputKind::DynamicNoPicExe
959            | LinkOutputKind::DynamicPicExe
960            | LinkOutputKind::StaticNoPicExe
961            | LinkOutputKind::StaticPicExe => {}
962            LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
963                self.link_arg("/DLL");
964                let mut arg: OsString = "/IMPLIB:".into();
965                arg.push(out_filename.with_extension("dll.lib"));
966                self.link_arg(arg);
967            }
968            LinkOutputKind::WasiReactorExe => {
969                {
    ::core::panicking::panic_fmt(format_args!("can\'t link as reactor on non-wasi target"));
};panic!("can't link as reactor on non-wasi target");
970            }
971        }
972    }
973
974    fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, _as_needed: bool) {
975        // On MSVC-like targets rustc supports import libraries using alternative naming
976        // scheme (`libfoo.a`) unsupported by linker, search for such libraries manually.
977        if let Some(path) = try_find_native_dynamic_library(self.sess, name, verbatim) {
978            self.link_arg(path);
979        } else {
980            self.link_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", name,
                if verbatim { "" } else { ".lib" }))
    })format!("{}{}", name, if verbatim { "" } else { ".lib" }));
981        }
982    }
983
984    fn link_dylib_by_path(&mut self, path: &Path, _as_needed: bool) {
985        // When producing a dll, MSVC linker may not emit an implib file if the dll doesn't export
986        // any symbols, so we skip linking if the implib file is not present.
987        let implib_path = path.with_extension("dll.lib");
988        if implib_path.exists() {
989            self.link_or_cc_arg(implib_path);
990        }
991    }
992
993    fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool) {
994        // On MSVC-like targets rustc supports static libraries using alternative naming
995        // scheme (`libfoo.a`) unsupported by linker, search for such libraries manually.
996        if let Some(path) = try_find_native_static_library(self.sess, name, verbatim) {
997            self.link_staticlib_by_path(&path, whole_archive);
998        } else {
999            let opts = if whole_archive { "/WHOLEARCHIVE:" } else { "" };
1000            let (prefix, suffix) = self.sess.staticlib_components(verbatim);
1001            self.link_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}{2}{3}", opts, prefix, name,
                suffix))
    })format!("{opts}{prefix}{name}{suffix}"));
1002        }
1003    }
1004
1005    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
1006        if !whole_archive {
1007            self.link_arg(path);
1008        } else {
1009            let mut arg = OsString::from("/WHOLEARCHIVE:");
1010            arg.push(path);
1011            self.link_arg(arg);
1012        }
1013    }
1014
1015    fn gc_sections(&mut self, _keep_metadata: bool) {
1016        // MSVC's ICF (Identical COMDAT Folding) link optimization is
1017        // slow for Rust and thus we disable it by default when not in
1018        // optimization build.
1019        if self.sess.opts.optimize != config::OptLevel::No {
1020            self.link_arg("/OPT:REF,ICF");
1021        } else {
1022            // It is necessary to specify NOICF here, because /OPT:REF
1023            // implies ICF by default.
1024            self.link_arg("/OPT:REF,NOICF");
1025        }
1026    }
1027
1028    fn full_relro(&mut self) {
1029        // noop
1030    }
1031
1032    fn partial_relro(&mut self) {
1033        // noop
1034    }
1035
1036    fn no_relro(&mut self) {
1037        // noop
1038    }
1039
1040    fn no_crt_objects(&mut self) {
1041        // noop
1042    }
1043
1044    fn no_default_libraries(&mut self) {
1045        self.link_arg("/NODEFAULTLIB");
1046    }
1047
1048    fn include_path(&mut self, path: &Path) {
1049        let mut arg = OsString::from("/LIBPATH:");
1050        arg.push(path);
1051        self.link_arg(&arg);
1052    }
1053
1054    fn output_filename(&mut self, path: &Path) {
1055        let mut arg = OsString::from("/OUT:");
1056        arg.push(path);
1057        self.link_arg(&arg);
1058    }
1059
1060    fn optimize(&mut self) {
1061        // Needs more investigation of `/OPT` arguments
1062    }
1063
1064    fn pgo_gen(&mut self) {
1065        // Nothing needed here.
1066    }
1067
1068    fn control_flow_guard(&mut self) {
1069        self.link_arg("/guard:cf");
1070    }
1071
1072    fn ehcont_guard(&mut self) {
1073        if self.sess.target.pointer_width == 64 {
1074            self.link_arg("/guard:ehcont");
1075        }
1076    }
1077
1078    fn debuginfo(&mut self, _strip: Strip, natvis_debugger_visualizers: &[PathBuf]) {
1079        // This will cause the Microsoft linker to generate a PDB file
1080        // from the CodeView line tables in the object files.
1081        self.link_arg("/DEBUG");
1082
1083        // Default to emitting only the file name of the PDB file into
1084        // the binary instead of the full path. Emitting the full path
1085        // may leak private information (such as user names).
1086        // See https://github.com/rust-lang/rust/issues/87825.
1087        //
1088        // This default behavior can be overridden by explicitly passing
1089        // `-Clink-arg=/PDBALTPATH:...` to rustc.
1090        self.link_arg("/PDBALTPATH:%_PDB%");
1091
1092        // This will cause the Microsoft linker to embed .natvis info into the PDB file
1093        let natvis_dir_path = self.sess.opts.sysroot.path().join("lib\\rustlib\\etc");
1094        if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
1095            for entry in natvis_dir {
1096                match entry {
1097                    Ok(entry) => {
1098                        let path = entry.path();
1099                        if path.extension() == Some("natvis".as_ref()) {
1100                            let mut arg = OsString::from("/NATVIS:");
1101                            arg.push(path);
1102                            self.link_arg(arg);
1103                        }
1104                    }
1105                    Err(error) => {
1106                        self.sess.dcx().emit_warn(errors::NoNatvisDirectory { error });
1107                    }
1108                }
1109            }
1110        }
1111
1112        // This will cause the Microsoft linker to embed .natvis info for all crates into the PDB file
1113        for path in natvis_debugger_visualizers {
1114            let mut arg = OsString::from("/NATVIS:");
1115            arg.push(path);
1116            self.link_arg(arg);
1117        }
1118    }
1119
1120    fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, _symbols: &[SymbolExport]) {
1121        // We already add /EXPORT arguments to the .drectve section of symbols.o.
1122        // Keep passing an empty .def file: link.exe otherwise skips the import
1123        // library for DLLs with no exports.
1124        if crate_type == CrateType::Executable {
1125            let should_export_executable_symbols =
1126                self.sess.opts.unstable_opts.export_executable_symbols;
1127            if !should_export_executable_symbols {
1128                return;
1129            }
1130        }
1131
1132        let path = tmpdir.join("lib.def");
1133        let res = try {
1134            let mut f = File::create_buffered(&path)?;
1135            f.write_fmt(format_args!("LIBRARY\n"))writeln!(f, "LIBRARY")?;
1136            f.write_fmt(format_args!("EXPORTS\n"))writeln!(f, "EXPORTS")?;
1137        };
1138        if let Err(error) = res {
1139            self.sess.dcx().emit_fatal(errors::LibDefWriteFailure { error });
1140        }
1141        let mut arg = OsString::from("/DEF:");
1142        arg.push(path);
1143        self.link_arg(&arg);
1144    }
1145
1146    fn windows_subsystem(&mut self, subsystem: WindowsSubsystemKind) {
1147        let subsystem = subsystem.as_str();
1148        self.link_arg(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/SUBSYSTEM:{0}", subsystem))
    })format!("/SUBSYSTEM:{subsystem}"));
1149
1150        // Windows has two subsystems we're interested in right now, the console
1151        // and windows subsystems. These both implicitly have different entry
1152        // points (starting symbols). The console entry point starts with
1153        // `mainCRTStartup` and the windows entry point starts with
1154        // `WinMainCRTStartup`. These entry points, defined in system libraries,
1155        // will then later probe for either `main` or `WinMain`, respectively to
1156        // start the application.
1157        //
1158        // In Rust we just always generate a `main` function so we want control
1159        // to always start there, so we force the entry point on the windows
1160        // subsystem to be `mainCRTStartup` to get everything booted up
1161        // correctly.
1162        //
1163        // For more information see RFC #1665
1164        if subsystem == "windows" {
1165            self.link_arg("/ENTRY:mainCRTStartup");
1166        }
1167    }
1168
1169    fn linker_plugin_lto(&mut self) {
1170        // Do nothing
1171    }
1172
1173    fn add_no_exec(&mut self) {
1174        self.link_arg("/NXCOMPAT");
1175    }
1176}
1177
1178struct EmLinker<'a> {
1179    cmd: Command,
1180    sess: &'a Session,
1181}
1182
1183impl<'a> Linker for EmLinker<'a> {
1184    fn cmd(&mut self) -> &mut Command {
1185        &mut self.cmd
1186    }
1187
1188    fn is_cc(&self) -> bool {
1189        true
1190    }
1191
1192    fn set_output_kind(
1193        &mut self,
1194        output_kind: LinkOutputKind,
1195        _crate_type: CrateType,
1196        _out_filename: &Path,
1197    ) {
1198        match output_kind {
1199            LinkOutputKind::DynamicNoPicExe | LinkOutputKind::DynamicPicExe => {
1200                self.cmd.arg("-sMAIN_MODULE=2");
1201            }
1202            LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1203                self.cmd.arg("-sSIDE_MODULE=2");
1204            }
1205            // -fno-pie is the default on Emscripten.
1206            LinkOutputKind::StaticNoPicExe | LinkOutputKind::StaticPicExe => {}
1207            LinkOutputKind::WasiReactorExe => {
1208                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1209            }
1210        }
1211    }
1212
1213    fn link_dylib_by_name(&mut self, name: &str, _verbatim: bool, _as_needed: bool) {
1214        // Emscripten always links statically
1215        self.link_or_cc_args(&["-l", name]);
1216    }
1217
1218    fn link_dylib_by_path(&mut self, path: &Path, _as_needed: bool) {
1219        self.link_or_cc_arg(path);
1220    }
1221
1222    fn link_staticlib_by_name(&mut self, name: &str, _verbatim: bool, _whole_archive: bool) {
1223        self.link_or_cc_args(&["-l", name]);
1224    }
1225
1226    fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
1227        self.link_or_cc_arg(path);
1228    }
1229
1230    fn full_relro(&mut self) {
1231        // noop
1232    }
1233
1234    fn partial_relro(&mut self) {
1235        // noop
1236    }
1237
1238    fn no_relro(&mut self) {
1239        // noop
1240    }
1241
1242    fn gc_sections(&mut self, _keep_metadata: bool) {
1243        // noop
1244    }
1245
1246    fn optimize(&mut self) {
1247        // Emscripten performs own optimizations
1248        self.cc_arg(match self.sess.opts.optimize {
1249            OptLevel::No => "-O0",
1250            OptLevel::Less => "-O1",
1251            OptLevel::More => "-O2",
1252            OptLevel::Aggressive => "-O3",
1253            OptLevel::Size => "-Os",
1254            OptLevel::SizeMin => "-Oz",
1255        });
1256    }
1257
1258    fn pgo_gen(&mut self) {
1259        // noop, but maybe we need something like the gnu linker?
1260    }
1261
1262    fn control_flow_guard(&mut self) {}
1263
1264    fn ehcont_guard(&mut self) {}
1265
1266    fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1267        // Preserve names or generate source maps depending on debug info
1268        // For more information see https://emscripten.org/docs/tools_reference/emcc.html#emcc-g
1269        self.cc_arg(match self.sess.opts.debuginfo {
1270            DebugInfo::None => "-g0",
1271            DebugInfo::Limited | DebugInfo::LineTablesOnly | DebugInfo::LineDirectivesOnly => {
1272                "--profiling-funcs"
1273            }
1274            DebugInfo::Full => "-g",
1275        });
1276    }
1277
1278    fn no_crt_objects(&mut self) {}
1279
1280    fn no_default_libraries(&mut self) {
1281        self.cc_arg("-nodefaultlibs");
1282    }
1283
1284    fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1285        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:1285",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(1285u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("EXPORTED SYMBOLS:")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("EXPORTED SYMBOLS:");
1286
1287        self.cc_arg("-s");
1288
1289        let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
1290        let encoded = serde_json::to_string(
1291            &symbols.iter().map(|sym| "_".to_owned() + &sym.name).collect::<Vec<_>>(),
1292        )
1293        .unwrap();
1294        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:1294",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(1294u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("{0}",
                                                    encoded) as &dyn Value))])
            });
    } else { ; }
};debug!("{encoded}");
1295
1296        arg.push(encoded);
1297
1298        self.cc_arg(arg);
1299    }
1300
1301    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {
1302        // noop
1303    }
1304
1305    fn linker_plugin_lto(&mut self) {
1306        // Do nothing
1307    }
1308}
1309
1310struct WasmLd<'a> {
1311    cmd: Command,
1312    sess: &'a Session,
1313}
1314
1315impl<'a> WasmLd<'a> {
1316    fn new(cmd: Command, sess: &'a Session) -> WasmLd<'a> {
1317        WasmLd { cmd, sess }
1318    }
1319}
1320
1321impl<'a> Linker for WasmLd<'a> {
1322    fn cmd(&mut self) -> &mut Command {
1323        &mut self.cmd
1324    }
1325
1326    fn set_output_kind(
1327        &mut self,
1328        output_kind: LinkOutputKind,
1329        _crate_type: CrateType,
1330        _out_filename: &Path,
1331    ) {
1332        match output_kind {
1333            LinkOutputKind::DynamicNoPicExe
1334            | LinkOutputKind::DynamicPicExe
1335            | LinkOutputKind::StaticNoPicExe
1336            | LinkOutputKind::StaticPicExe => {}
1337            LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1338                self.link_arg("--no-entry");
1339            }
1340            LinkOutputKind::WasiReactorExe => {
1341                self.link_args(&["--entry", "_initialize"]);
1342            }
1343        }
1344    }
1345
1346    fn link_dylib_by_name(&mut self, name: &str, _verbatim: bool, _as_needed: bool) {
1347        self.link_or_cc_args(&["-l", name]);
1348    }
1349
1350    fn link_dylib_by_path(&mut self, path: &Path, _as_needed: bool) {
1351        self.link_or_cc_arg(path);
1352    }
1353
1354    fn link_staticlib_by_name(&mut self, name: &str, _verbatim: bool, whole_archive: bool) {
1355        if !whole_archive {
1356            self.link_or_cc_args(&["-l", name]);
1357        } else {
1358            self.link_arg("--whole-archive")
1359                .link_or_cc_args(&["-l", name])
1360                .link_arg("--no-whole-archive");
1361        }
1362    }
1363
1364    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
1365        if !whole_archive {
1366            self.link_or_cc_arg(path);
1367        } else {
1368            self.link_arg("--whole-archive").link_or_cc_arg(path).link_arg("--no-whole-archive");
1369        }
1370    }
1371
1372    fn full_relro(&mut self) {}
1373
1374    fn partial_relro(&mut self) {}
1375
1376    fn no_relro(&mut self) {}
1377
1378    fn gc_sections(&mut self, _keep_metadata: bool) {
1379        self.link_arg("--gc-sections");
1380    }
1381
1382    fn optimize(&mut self) {
1383        // The -O flag is, as of late 2023, only used for merging of strings and debuginfo, and
1384        // only differentiates -O0 and -O1. It does not apply to LTO.
1385        self.link_arg(match self.sess.opts.optimize {
1386            OptLevel::No => "-O0",
1387            OptLevel::Less => "-O1",
1388            OptLevel::More => "-O2",
1389            OptLevel::Aggressive => "-O3",
1390            // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1391            // instead.
1392            OptLevel::Size => "-O2",
1393            OptLevel::SizeMin => "-O2",
1394        });
1395    }
1396
1397    fn pgo_gen(&mut self) {}
1398
1399    fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
1400        match strip {
1401            Strip::None => {}
1402            Strip::Debuginfo => {
1403                self.link_arg("--strip-debug");
1404            }
1405            Strip::Symbols => {
1406                self.link_arg("--strip-all");
1407            }
1408        }
1409    }
1410
1411    fn control_flow_guard(&mut self) {}
1412
1413    fn ehcont_guard(&mut self) {}
1414
1415    fn no_crt_objects(&mut self) {}
1416
1417    fn no_default_libraries(&mut self) {}
1418
1419    fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1420        for sym in symbols {
1421            self.link_args(&["--export", &sym.name]);
1422        }
1423    }
1424
1425    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {}
1426
1427    fn linker_plugin_lto(&mut self) {
1428        match self.sess.opts.cg.linker_plugin_lto {
1429            LinkerPluginLto::Disabled => {
1430                // Nothing to do
1431            }
1432            LinkerPluginLto::LinkerPluginAuto => {
1433                self.push_linker_plugin_lto_args();
1434            }
1435            LinkerPluginLto::LinkerPlugin(_) => {
1436                self.push_linker_plugin_lto_args();
1437            }
1438        }
1439    }
1440}
1441
1442impl<'a> WasmLd<'a> {
1443    fn push_linker_plugin_lto_args(&mut self) {
1444        let opt_level = match self.sess.opts.optimize {
1445            config::OptLevel::No => "O0",
1446            config::OptLevel::Less => "O1",
1447            config::OptLevel::More => "O2",
1448            config::OptLevel::Aggressive => "O3",
1449            // wasm-ld only handles integer LTO opt levels. Use O2
1450            config::OptLevel::Size | config::OptLevel::SizeMin => "O2",
1451        };
1452        self.link_arg(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("--lto-{0}", opt_level))
    })format!("--lto-{opt_level}"));
1453    }
1454}
1455
1456/// Linker shepherd script for L4Re (Fiasco)
1457struct L4Bender<'a> {
1458    cmd: Command,
1459    sess: &'a Session,
1460    hinted_static: bool,
1461}
1462
1463impl<'a> Linker for L4Bender<'a> {
1464    fn cmd(&mut self) -> &mut Command {
1465        &mut self.cmd
1466    }
1467
1468    fn set_output_kind(
1469        &mut self,
1470        _output_kind: LinkOutputKind,
1471        _crate_type: CrateType,
1472        _out_filename: &Path,
1473    ) {
1474    }
1475
1476    fn link_staticlib_by_name(&mut self, name: &str, _verbatim: bool, whole_archive: bool) {
1477        self.hint_static();
1478        if !whole_archive {
1479            self.link_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-PC{0}", name))
    })format!("-PC{name}"));
1480        } else {
1481            self.link_arg("--whole-archive")
1482                .link_or_cc_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}", name))
    })format!("-l{name}"))
1483                .link_arg("--no-whole-archive");
1484        }
1485    }
1486
1487    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
1488        self.hint_static();
1489        if !whole_archive {
1490            self.link_or_cc_arg(path);
1491        } else {
1492            self.link_arg("--whole-archive").link_or_cc_arg(path).link_arg("--no-whole-archive");
1493        }
1494    }
1495
1496    fn full_relro(&mut self) {
1497        self.link_args(&["-z", "relro", "-z", "now"]);
1498    }
1499
1500    fn partial_relro(&mut self) {
1501        self.link_args(&["-z", "relro"]);
1502    }
1503
1504    fn no_relro(&mut self) {
1505        self.link_args(&["-z", "norelro"]);
1506    }
1507
1508    fn gc_sections(&mut self, keep_metadata: bool) {
1509        if !keep_metadata {
1510            self.link_arg("--gc-sections");
1511        }
1512    }
1513
1514    fn optimize(&mut self) {
1515        // GNU-style linkers support optimization with -O. GNU ld doesn't
1516        // need a numeric argument, but other linkers do.
1517        if self.sess.opts.optimize == config::OptLevel::More
1518            || self.sess.opts.optimize == config::OptLevel::Aggressive
1519        {
1520            self.link_arg("-O1");
1521        }
1522    }
1523
1524    fn pgo_gen(&mut self) {}
1525
1526    fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
1527        match strip {
1528            Strip::None => {}
1529            Strip::Debuginfo => {
1530                self.link_arg("--strip-debug");
1531            }
1532            Strip::Symbols => {
1533                self.link_arg("--strip-all");
1534            }
1535        }
1536    }
1537
1538    fn no_default_libraries(&mut self) {
1539        self.cc_arg("-nostdlib");
1540    }
1541
1542    fn export_symbols(&mut self, _: &Path, _: CrateType, _: &[SymbolExport]) {
1543        // ToDo, not implemented, copy from GCC
1544        self.sess.dcx().emit_warn(errors::L4BenderExportingSymbolsUnimplemented);
1545    }
1546
1547    fn windows_subsystem(&mut self, subsystem: WindowsSubsystemKind) {
1548        let subsystem = subsystem.as_str();
1549        self.link_arg(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("--subsystem {0}", subsystem))
    })format!("--subsystem {subsystem}"));
1550    }
1551
1552    fn reset_per_library_state(&mut self) {
1553        self.hint_static(); // Reset to default before returning the composed command line.
1554    }
1555
1556    fn linker_plugin_lto(&mut self) {}
1557
1558    fn control_flow_guard(&mut self) {}
1559
1560    fn ehcont_guard(&mut self) {}
1561
1562    fn no_crt_objects(&mut self) {}
1563}
1564
1565impl<'a> L4Bender<'a> {
1566    fn new(cmd: Command, sess: &'a Session) -> L4Bender<'a> {
1567        L4Bender { cmd, sess, hinted_static: false }
1568    }
1569
1570    fn hint_static(&mut self) {
1571        if !self.hinted_static {
1572            self.link_or_cc_arg("-static");
1573            self.hinted_static = true;
1574        }
1575    }
1576}
1577
1578/// Linker for AIX.
1579struct AixLinker<'a> {
1580    cmd: Command,
1581    sess: &'a Session,
1582    hinted_static: Option<bool>,
1583}
1584
1585impl<'a> AixLinker<'a> {
1586    fn new(cmd: Command, sess: &'a Session) -> AixLinker<'a> {
1587        AixLinker { cmd, sess, hinted_static: None }
1588    }
1589
1590    fn hint_static(&mut self) {
1591        if self.hinted_static != Some(true) {
1592            self.link_arg("-bstatic");
1593            self.hinted_static = Some(true);
1594        }
1595    }
1596
1597    fn hint_dynamic(&mut self) {
1598        if self.hinted_static != Some(false) {
1599            self.link_arg("-bdynamic");
1600            self.hinted_static = Some(false);
1601        }
1602    }
1603
1604    fn build_dylib(&mut self, _out_filename: &Path) {
1605        self.link_args(&["-bM:SRE", "-bnoentry"]);
1606        // FIXME: Use CreateExportList utility to create export list
1607        // and remove -bexpfull.
1608        self.link_arg("-bexpfull");
1609    }
1610}
1611
1612impl<'a> Linker for AixLinker<'a> {
1613    fn cmd(&mut self) -> &mut Command {
1614        &mut self.cmd
1615    }
1616
1617    fn set_output_kind(
1618        &mut self,
1619        output_kind: LinkOutputKind,
1620        _crate_type: CrateType,
1621        out_filename: &Path,
1622    ) {
1623        match output_kind {
1624            LinkOutputKind::DynamicDylib => {
1625                self.hint_dynamic();
1626                self.build_dylib(out_filename);
1627            }
1628            LinkOutputKind::StaticDylib => {
1629                self.hint_static();
1630                self.build_dylib(out_filename);
1631            }
1632            _ => {}
1633        }
1634    }
1635
1636    fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, _as_needed: bool) {
1637        self.hint_dynamic();
1638        self.link_or_cc_arg(if verbatim { String::from(name) } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}", name))
    })format!("-l{name}") });
1639    }
1640
1641    fn link_dylib_by_path(&mut self, path: &Path, _as_needed: bool) {
1642        self.hint_dynamic();
1643        self.link_or_cc_arg(path);
1644    }
1645
1646    fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool) {
1647        self.hint_static();
1648        if !whole_archive {
1649            self.link_or_cc_arg(if verbatim { String::from(name) } else { ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}", name))
    })format!("-l{name}") });
1650        } else {
1651            let mut arg = OsString::from("-bkeepfile:");
1652            arg.push(find_native_static_library(name, verbatim, self.sess));
1653            self.link_or_cc_arg(arg);
1654        }
1655    }
1656
1657    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
1658        self.hint_static();
1659        if !whole_archive {
1660            self.link_or_cc_arg(path);
1661        } else {
1662            let mut arg = OsString::from("-bkeepfile:");
1663            arg.push(path);
1664            self.link_arg(arg);
1665        }
1666    }
1667
1668    fn full_relro(&mut self) {}
1669
1670    fn partial_relro(&mut self) {}
1671
1672    fn no_relro(&mut self) {}
1673
1674    fn gc_sections(&mut self, _keep_metadata: bool) {
1675        self.link_arg("-bgc");
1676    }
1677
1678    fn optimize(&mut self) {}
1679
1680    fn pgo_gen(&mut self) {
1681        self.link_arg("-bdbg:namedsects:ss");
1682        self.link_arg("-u");
1683        self.link_arg("__llvm_profile_runtime");
1684    }
1685
1686    fn control_flow_guard(&mut self) {}
1687
1688    fn ehcont_guard(&mut self) {}
1689
1690    fn debuginfo(&mut self, _: Strip, _: &[PathBuf]) {}
1691
1692    fn no_crt_objects(&mut self) {}
1693
1694    fn no_default_libraries(&mut self) {}
1695
1696    fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1697        let path = tmpdir.join("list.exp");
1698        let res = try {
1699            let mut f = File::create_buffered(&path)?;
1700            // FIXME: use llvm-nm to generate export list.
1701            for symbol in symbols {
1702                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/linker.rs:1702",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(1702u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::linker"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("  _{0}",
                                                    symbol.name) as &dyn Value))])
            });
    } else { ; }
};debug!("  _{}", symbol.name);
1703                f.write_fmt(format_args!("  {0}\n", symbol.name))writeln!(f, "  {}", symbol.name)?;
1704            }
1705        };
1706        if let Err(e) = res {
1707            self.sess.dcx().fatal(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("failed to write export file: {0}",
                e))
    })format!("failed to write export file: {e}"));
1708        }
1709        self.link_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-bE:{0}", path.to_str().unwrap()))
    })format!("-bE:{}", path.to_str().unwrap()));
1710    }
1711
1712    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {}
1713
1714    fn reset_per_library_state(&mut self) {
1715        self.hint_dynamic();
1716    }
1717
1718    fn linker_plugin_lto(&mut self) {}
1719
1720    fn add_eh_frame_header(&mut self) {}
1721
1722    fn add_no_exec(&mut self) {}
1723
1724    fn add_as_needed(&mut self) {}
1725}
1726
1727fn for_each_exported_symbols_include_dep<'tcx>(
1728    tcx: TyCtxt<'tcx>,
1729    crate_type: CrateType,
1730    mut callback: impl FnMut(ExportedSymbol<'tcx>, SymbolExportInfo, CrateNum),
1731) {
1732    let formats = tcx.dependency_formats(());
1733    let deps = &formats[&crate_type];
1734
1735    for (cnum, dep_format) in deps.iter_enumerated() {
1736        // For each dependency that we are linking to statically ...
1737        if *dep_format == Linkage::Static {
1738            for &(symbol, info) in tcx.exported_non_generic_symbols(cnum).iter() {
1739                callback(symbol, info, cnum);
1740            }
1741            for &(symbol, info) in tcx.exported_generic_symbols(cnum).iter() {
1742                callback(symbol, info, cnum);
1743            }
1744        }
1745    }
1746}
1747
1748fn symbol_export_from_exported_symbol<'tcx>(
1749    tcx: TyCtxt<'tcx>,
1750    symbol: ExportedSymbol<'tcx>,
1751    kind: SymbolExportKind,
1752    cnum: CrateNum,
1753) -> SymbolExport {
1754    let name = symbol_export::exporting_symbol_name_for_instance_in_crate(tcx, symbol, cnum);
1755    let link_name =
1756        symbol_export::linking_symbol_name_for_instance_in_crate(tcx, symbol, kind, cnum);
1757    SymbolExport::with_link_name(name, kind, link_name)
1758}
1759
1760fn symbol_export_from_raw_name(
1761    tcx: TyCtxt<'_>,
1762    name: String,
1763    kind: SymbolExportKind,
1764) -> SymbolExport {
1765    let symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &name));
1766    let link_name =
1767        symbol_export::linking_symbol_name_for_instance_in_crate(tcx, symbol, kind, LOCAL_CRATE);
1768    SymbolExport::with_link_name(name, kind, link_name)
1769}
1770
1771pub(crate) fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<SymbolExport> {
1772    if let Some(ref exports) = tcx.sess.target.override_export_symbols {
1773        return exports
1774            .iter()
1775            .map(|name| {
1776                symbol_export_from_raw_name(
1777                    tcx,
1778                    name.to_string(),
1779                    // FIXME use the correct export kind for this symbol. override_export_symbols
1780                    // can't directly specify the SymbolExportKind as it is defined in rustc_middle
1781                    // which rustc_target can't depend on.
1782                    SymbolExportKind::Text,
1783                )
1784            })
1785            .collect();
1786    }
1787
1788    let mut symbols = if let CrateType::ProcMacro = crate_type {
1789        exported_symbols_for_proc_macro_crate(tcx)
1790    } else {
1791        exported_symbols_for_non_proc_macro(tcx, crate_type)
1792    };
1793
1794    // Preserve the metadata symbol to ensure the metadata section doesn't get removed by the
1795    // linker. On wasm however the metadata is put in a custom section, to which symbols can't
1796    // refer, so there is no metadata symbol there. Luckily custom sections are always preserved by
1797    // the linker.
1798    if (crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro)
1799        && !tcx.sess.target.is_like_wasm
1800    {
1801        let metadata_symbol_name = exported_symbols::metadata_symbol_name(tcx);
1802        symbols.push(symbol_export_from_raw_name(
1803            tcx,
1804            metadata_symbol_name,
1805            SymbolExportKind::Data,
1806        ));
1807    }
1808
1809    symbols
1810}
1811
1812fn exported_symbols_for_non_proc_macro(
1813    tcx: TyCtxt<'_>,
1814    crate_type: CrateType,
1815) -> Vec<SymbolExport> {
1816    let mut symbols = Vec::new();
1817    let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1818    for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| {
1819        // Do not export mangled symbols from cdylibs and don't attempt to export compiler-builtins
1820        // from any dylib. The latter doesn't work anyway as we use hidden visibility for
1821        // compiler-builtins. Most linkers silently ignore it, but ld64 gives a warning.
1822        if info.level.is_below_threshold(export_threshold) && !tcx.is_compiler_builtins(cnum) {
1823            symbols.push(symbol_export_from_exported_symbol(tcx, symbol, info.kind, cnum));
1824            symbol_export::extend_exported_symbols(&mut symbols, tcx, symbol, cnum);
1825        }
1826    });
1827
1828    // Mark allocator shim symbols as exported only if they were generated.
1829    if export_threshold == SymbolExportLevel::Rust
1830        && needs_allocator_shim_for_linking(tcx.dependency_formats(()), crate_type)
1831        && let Some(kind) = tcx.allocator_kind(())
1832    {
1833        symbols.extend(
1834            allocator_shim_symbols(tcx, kind)
1835                .map(|(name, kind)| symbol_export_from_raw_name(tcx, name, kind)),
1836        );
1837    }
1838
1839    symbols
1840}
1841
1842fn exported_symbols_for_proc_macro_crate(tcx: TyCtxt<'_>) -> Vec<SymbolExport> {
1843    // `exported_symbols` will be empty when !should_codegen.
1844    if !tcx.sess.opts.output_types.should_codegen() {
1845        return Vec::new();
1846    }
1847
1848    let stable_crate_id = tcx.stable_crate_id(LOCAL_CRATE);
1849    let proc_macro_decls_name = rustc_session::generate_proc_macro_decls_symbol(stable_crate_id);
1850
1851    ::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [symbol_export_from_raw_name(tcx, proc_macro_decls_name,
                    SymbolExportKind::Data)]))vec![symbol_export_from_raw_name(tcx, proc_macro_decls_name, SymbolExportKind::Data)]
1852}
1853
1854pub(crate) fn linked_symbols(
1855    tcx: TyCtxt<'_>,
1856    crate_type: CrateType,
1857) -> Vec<(String, SymbolExportKind)> {
1858    match crate_type {
1859        CrateType::Executable
1860        | CrateType::ProcMacro
1861        | CrateType::Cdylib
1862        | CrateType::Dylib
1863        | CrateType::Sdylib => (),
1864        CrateType::StaticLib | CrateType::Rlib => {
1865            // These are not linked, so no need to generate symbols.o for them.
1866            return Vec::new();
1867        }
1868    }
1869
1870    match tcx.sess.lto() {
1871        Lto::No | Lto::ThinLocal => {}
1872        Lto::Thin | Lto::Fat => {
1873            // We really only need symbols from upstream rlibs to end up in the linked symbols list.
1874            // The rest are in separate object files which the linker will always link in and
1875            // doesn't have rules around the order in which they need to appear.
1876            // When doing LTO, some of the symbols in the linked symbols list happen to be
1877            // internalized by LTO, which then prevents referencing them from symbols.o. When doing
1878            // LTO, all object files that get linked in will be local object files rather than
1879            // pulled in from rlibs, so an empty linked symbols list works fine to avoid referencing
1880            // all those internalized symbols from symbols.o.
1881            return Vec::new();
1882        }
1883    }
1884
1885    let mut symbols = Vec::new();
1886
1887    let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1888    for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| {
1889        if info.level.is_below_threshold(export_threshold) && !tcx.is_compiler_builtins(cnum)
1890            || info.used
1891            || info.rustc_std_internal_symbol
1892        {
1893            symbols.push((
1894                symbol_export::linking_symbol_name_for_instance_in_crate(
1895                    tcx, symbol, info.kind, cnum,
1896                ),
1897                info.kind,
1898            ));
1899        }
1900    });
1901
1902    symbols
1903}
1904
1905/// The `self-contained` LLVM bitcode linker
1906struct LlbcLinker<'a> {
1907    cmd: Command,
1908    sess: &'a Session,
1909}
1910
1911impl<'a> Linker for LlbcLinker<'a> {
1912    fn cmd(&mut self) -> &mut Command {
1913        &mut self.cmd
1914    }
1915
1916    fn set_output_kind(
1917        &mut self,
1918        _output_kind: LinkOutputKind,
1919        _crate_type: CrateType,
1920        _out_filename: &Path,
1921    ) {
1922    }
1923
1924    fn link_staticlib_by_name(&mut self, _name: &str, _verbatim: bool, _whole_archive: bool) {
1925        { ::core::panicking::panic_fmt(format_args!("staticlibs not supported")); }panic!("staticlibs not supported")
1926    }
1927
1928    fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
1929        self.link_or_cc_arg(path);
1930    }
1931
1932    fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1933        self.link_arg("--debug");
1934    }
1935
1936    fn optimize(&mut self) {
1937        self.link_arg(match self.sess.opts.optimize {
1938            OptLevel::No => "-O0",
1939            OptLevel::Less => "-O1",
1940            OptLevel::More => "-O2",
1941            OptLevel::Aggressive => "-O3",
1942            OptLevel::Size => "-Os",
1943            OptLevel::SizeMin => "-Oz",
1944        });
1945    }
1946
1947    fn full_relro(&mut self) {}
1948
1949    fn partial_relro(&mut self) {}
1950
1951    fn no_relro(&mut self) {}
1952
1953    fn gc_sections(&mut self, _keep_metadata: bool) {}
1954
1955    fn pgo_gen(&mut self) {}
1956
1957    fn no_crt_objects(&mut self) {}
1958
1959    fn no_default_libraries(&mut self) {}
1960
1961    fn control_flow_guard(&mut self) {}
1962
1963    fn ehcont_guard(&mut self) {}
1964
1965    fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1966        match _crate_type {
1967            CrateType::Cdylib => {
1968                for sym in symbols {
1969                    self.link_args(&["--export-symbol", &sym.name]);
1970                }
1971            }
1972            _ => (),
1973        }
1974    }
1975
1976    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {}
1977
1978    fn linker_plugin_lto(&mut self) {}
1979}
1980
1981struct BpfLinker<'a> {
1982    cmd: Command,
1983    sess: &'a Session,
1984}
1985
1986impl<'a> Linker for BpfLinker<'a> {
1987    fn cmd(&mut self) -> &mut Command {
1988        &mut self.cmd
1989    }
1990
1991    fn set_output_kind(
1992        &mut self,
1993        _output_kind: LinkOutputKind,
1994        _crate_type: CrateType,
1995        _out_filename: &Path,
1996    ) {
1997    }
1998
1999    fn link_staticlib_by_name(&mut self, _name: &str, _verbatim: bool, _whole_archive: bool) {
2000        self.sess.dcx().emit_fatal(errors::BpfStaticlibNotSupported)
2001    }
2002
2003    fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
2004        self.link_or_cc_arg(path);
2005    }
2006
2007    fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
2008        self.link_arg("--debug");
2009    }
2010
2011    fn optimize(&mut self) {
2012        self.link_arg(match self.sess.opts.optimize {
2013            OptLevel::No => "-O0",
2014            OptLevel::Less => "-O1",
2015            OptLevel::More => "-O2",
2016            OptLevel::Aggressive => "-O3",
2017            OptLevel::Size => "-Os",
2018            OptLevel::SizeMin => "-Oz",
2019        });
2020    }
2021
2022    fn full_relro(&mut self) {}
2023
2024    fn partial_relro(&mut self) {}
2025
2026    fn no_relro(&mut self) {}
2027
2028    fn gc_sections(&mut self, _keep_metadata: bool) {}
2029
2030    fn pgo_gen(&mut self) {}
2031
2032    fn no_crt_objects(&mut self) {}
2033
2034    fn no_default_libraries(&mut self) {}
2035
2036    fn control_flow_guard(&mut self) {}
2037
2038    fn ehcont_guard(&mut self) {}
2039
2040    fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
2041        let path = tmpdir.join("symbols");
2042        let res = try {
2043            let mut f = File::create_buffered(&path)?;
2044            for sym in symbols {
2045                f.write_fmt(format_args!("{0}\n", sym.name))writeln!(f, "{}", sym.name)?;
2046            }
2047        };
2048        if let Err(error) = res {
2049            self.sess.dcx().emit_fatal(errors::SymbolFileWriteFailure { error });
2050        } else {
2051            self.link_arg("--export-symbols").link_arg(&path);
2052        }
2053    }
2054
2055    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {}
2056
2057    fn linker_plugin_lto(&mut self) {}
2058}