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