Skip to main content

rustc_codegen_ssa/back/
linker.rs

1use std::ffi::{OsStr, OsString};
2use std::fs::{self, File};
3use std::io::prelude::*;
4use std::path::{Path, PathBuf};
5use std::{env, iter, mem, str};
6
7use find_msvc_tools;
8use rustc_hir::attrs::WindowsSubsystemKind;
9use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
10use rustc_middle::bug;
11use rustc_middle::middle::dependency_format::Linkage;
12use rustc_middle::middle::exported_symbols::{
13    self, ExportedSymbol, SymbolExportInfo, SymbolExportKind, SymbolExportLevel,
14};
15use rustc_middle::ty::{SymbolName, TyCtxt};
16use rustc_session::Session;
17use rustc_session::config::{self, DebugInfo, LinkerPluginLto, Lto, OptLevel, Strip};
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/f248f4038796913873f11ca65b1b901e311c8dae/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/f248f4038796913873f11ca65b1b901e311c8dae/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/f248f4038796913873f11ca65b1b901e311c8dae/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/f248f4038796913873f11ca65b1b901e311c8dae/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/f248f4038796913873f11ca65b1b901e311c8dae/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/f248f4038796913873f11ca65b1b901e311c8dae/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_middle::util::bug::bug_fmt(format_args!("dylib linked with unsupported linker"))bug!("dylib linked with unsupported linker")
306    }
307    fn link_dylib_by_path(&mut self, _path: &Path, _as_needed: bool) {
308        ::rustc_middle::util::bug::bug_fmt(format_args!("dylib linked with unsupported linker"))bug!("dylib linked with unsupported linker")
309    }
310    fn link_framework_by_name(&mut self, _name: &str, _verbatim: bool, _as_needed: bool) {
311        ::rustc_middle::util::bug::bug_fmt(format_args!("framework linked with unsupported linker"))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_middle::util::bug::bug_fmt(format_args!("framework path set with unsupported linker"))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        let opt_level = match self.sess.opts.optimize {
411            config::OptLevel::No => "O0",
412            config::OptLevel::Less => "O1",
413            config::OptLevel::More | config::OptLevel::Size | config::OptLevel::SizeMin => "O2",
414            config::OptLevel::Aggressive => "O3",
415        };
416
417        if let Some(path) = &self.sess.opts.cg.profile_sample_use {
418            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()));
419        };
420        let prefix = if self.codegen_backend == "gcc" {
421            // The GCC linker plugin requires a leading dash.
422            "-"
423        } else {
424            ""
425        };
426        self.link_args(&[
427            &::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-plugin-opt={0}{1}", prefix,
                opt_level))
    })format!("-plugin-opt={prefix}{opt_level}"),
428            &::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),
429        ]);
430    }
431
432    fn build_dylib(&mut self, crate_type: CrateType, out_filename: &Path) {
433        // On mac we need to tell the linker to let this library be rpathed
434        if self.sess.target.is_like_darwin {
435            if self.is_cc() {
436                // `-dynamiclib` makes `cc` pass `-dylib` to the linker.
437                self.cc_arg("-dynamiclib");
438            } else {
439                self.link_arg("-dylib");
440                // Clang also sets `-dynamic`, but that's implied by `-dylib`, so unnecessary.
441            }
442
443            // Note that the `osx_rpath_install_name` option here is a hack
444            // purely to support bootstrap right now, we should get a more
445            // principled solution at some point to force the compiler to pass
446            // the right `-Wl,-install_name` with an `@rpath` in it.
447            if self.sess.opts.cg.rpath || self.sess.opts.unstable_opts.osx_rpath_install_name {
448                let mut rpath = OsString::from("@rpath/");
449                rpath.push(out_filename.file_name().unwrap());
450                self.link_arg("-install_name").link_arg(rpath);
451            }
452        } else {
453            self.link_or_cc_arg("-shared");
454            if let Some(name) = out_filename.file_name() {
455                if self.sess.target.is_like_windows {
456                    // The output filename already contains `dll_suffix` so
457                    // the resulting import library will have a name in the
458                    // form of libfoo.dll.a
459                    let (prefix, suffix) = self.sess.staticlib_components(false);
460                    let mut implib_name = OsString::from(prefix);
461                    implib_name.push(name);
462                    implib_name.push(suffix);
463                    let mut out_implib = OsString::from("--out-implib=");
464                    out_implib.push(out_filename.with_file_name(implib_name));
465                    self.link_arg(out_implib);
466                } else if crate_type == CrateType::Dylib {
467                    // When dylibs are linked by a full path this value will get into `DT_NEEDED`
468                    // instead of the full path, so the library can be later found in some other
469                    // location than that specific path.
470                    let mut soname = OsString::from("-soname=");
471                    soname.push(name);
472                    self.link_arg(soname);
473                }
474            }
475        }
476    }
477
478    fn with_as_needed(&mut self, as_needed: bool, f: impl FnOnce(&mut Self)) {
479        if !as_needed {
480            if self.sess.target.is_like_darwin {
481                // FIXME(81490): ld64 doesn't support these flags but macOS 11
482                // has -needed-l{} / -needed_library {}
483                // but we have no way to detect that here.
484                self.sess.dcx().emit_warn(diagnostics::Ld64UnimplementedModifier);
485            } else if self.is_gnu && !self.sess.target.is_like_windows {
486                self.link_arg("--no-as-needed");
487            } else {
488                self.sess.dcx().emit_warn(diagnostics::LinkerUnsupportedModifier);
489            }
490        }
491
492        f(self);
493
494        if !as_needed {
495            if self.sess.target.is_like_darwin {
496                // See above FIXME comment
497            } else if self.is_gnu && !self.sess.target.is_like_windows {
498                self.link_arg("--as-needed");
499            }
500        }
501    }
502}
503
504impl<'a> Linker for GccLinker<'a> {
505    fn cmd(&mut self) -> &mut Command {
506        &mut self.cmd
507    }
508
509    fn is_cc(&self) -> bool {
510        !self.is_ld
511    }
512
513    fn set_output_kind(
514        &mut self,
515        output_kind: LinkOutputKind,
516        crate_type: CrateType,
517        out_filename: &Path,
518    ) {
519        match output_kind {
520            LinkOutputKind::DynamicNoPicExe => {
521                // noop on windows w/ gcc, warning w/ clang
522                if !self.is_ld && self.is_gnu && !self.sess.target.is_like_windows {
523                    self.cc_arg("-no-pie");
524                }
525            }
526            LinkOutputKind::DynamicPicExe => {
527                // noop on windows w/ gcc & ld, error w/ lld
528                if !self.sess.target.is_like_windows {
529                    // `-pie` works for both gcc wrapper and ld.
530                    self.link_or_cc_arg("-pie");
531                }
532            }
533            LinkOutputKind::StaticNoPicExe => {
534                // `-static` works for both gcc wrapper and ld.
535                self.link_or_cc_arg("-static");
536                // noop on windows w/ gcc, warning w/ clang
537                if !self.is_ld && self.is_gnu && !self.sess.target.is_like_windows {
538                    self.cc_arg("-no-pie");
539                }
540            }
541            LinkOutputKind::StaticPicExe => {
542                if !self.is_ld {
543                    // Note that combination `-static -pie` doesn't work as expected
544                    // for the gcc wrapper, `-static` in that case suppresses `-pie`.
545                    self.cc_arg("-static-pie");
546                } else {
547                    // `--no-dynamic-linker` and `-z text` are not strictly necessary for producing
548                    // a static pie, but currently passed because gcc and clang pass them.
549                    // The former suppresses the `INTERP` ELF header specifying dynamic linker,
550                    // which is otherwise implicitly injected by ld (but not lld).
551                    // The latter doesn't change anything, only ensures that everything is pic.
552                    self.link_args(&["-static", "-pie", "--no-dynamic-linker", "-z", "text"]);
553                }
554            }
555            LinkOutputKind::DynamicDylib => self.build_dylib(crate_type, out_filename),
556            LinkOutputKind::StaticDylib => {
557                self.link_or_cc_arg("-static");
558                self.build_dylib(crate_type, out_filename);
559            }
560            LinkOutputKind::WasiReactorExe => {
561                self.link_args(&["--entry", "_initialize"]);
562            }
563        }
564
565        // VxWorks compiler driver introduced `--static-crt` flag specifically for rustc,
566        // it switches linking for libc and similar system libraries to static without using
567        // any `#[link]` attributes in the `libc` crate, see #72782 for details.
568        // FIXME: Switch to using `#[link]` attributes in the `libc` crate
569        // similarly to other targets.
570        if self.sess.target.os == Os::VxWorks
571            && #[allow(non_exhaustive_omitted_patterns)] match output_kind {
    LinkOutputKind::StaticNoPicExe | LinkOutputKind::StaticPicExe |
        LinkOutputKind::StaticDylib => true,
    _ => false,
}matches!(
572                output_kind,
573                LinkOutputKind::StaticNoPicExe
574                    | LinkOutputKind::StaticPicExe
575                    | LinkOutputKind::StaticDylib
576            )
577        {
578            self.cc_arg("--static-crt");
579        }
580
581        // avr-none doesn't have default ISA, users must specify which specific
582        // CPU (well, microcontroller) they are targetting using `-Ctarget-cpu`.
583        //
584        // Currently this makes sense only when using avr-gcc as a linker, since
585        // it brings a couple of hand-written important intrinsics from libgcc.
586        if self.sess.target.arch == Arch::Avr && !self.uses_lld {
587            self.verbatim_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-mmcu={0}", self.target_cpu))
    })format!("-mmcu={}", self.target_cpu));
588        }
589    }
590
591    fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, as_needed: bool) {
592        if self.sess.target.os == Os::Illumos && name == "c" {
593            // libc will be added via late_link_args on illumos so that it will
594            // appear last in the library search order.
595            // FIXME: This should be replaced by a more complete and generic
596            // mechanism for controlling the order of library arguments passed
597            // to the linker.
598            return;
599        }
600        self.hint_dynamic();
601        self.with_as_needed(as_needed, |this| {
602            let colon = if verbatim && this.is_gnu { ":" } else { "" };
603            this.link_or_cc_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}{1}", colon, name))
    })format!("-l{colon}{name}"));
604        });
605    }
606
607    fn link_dylib_by_path(&mut self, path: &Path, as_needed: bool) {
608        self.hint_dynamic();
609        self.with_as_needed(as_needed, |this| {
610            this.link_or_cc_arg(path);
611        })
612    }
613
614    fn link_framework_by_name(&mut self, name: &str, _verbatim: bool, as_needed: bool) {
615        self.hint_dynamic();
616        if !as_needed {
617            // FIXME(81490): ld64 as of macOS 11 supports the -needed_framework
618            // flag but we have no way to detect that here.
619            // self.link_or_cc_arg("-needed_framework").link_or_cc_arg(name);
620            self.sess.dcx().emit_warn(diagnostics::Ld64UnimplementedModifier);
621        }
622        self.link_or_cc_args(&["-framework", name]);
623    }
624
625    fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool) {
626        self.hint_static();
627        let colon = if verbatim && self.is_gnu { ":" } else { "" };
628        if !whole_archive {
629            self.link_or_cc_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}{1}", colon, name))
    })format!("-l{colon}{name}"));
630        } else if self.sess.target.is_like_darwin {
631            // -force_load is the macOS equivalent of --whole-archive, but it
632            // involves passing the full path to the library to link.
633            self.link_arg("-force_load");
634            self.link_arg(find_native_static_library(name, verbatim, self.sess));
635        } else {
636            self.link_arg("--whole-archive")
637                .link_or_cc_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-l{0}{1}", colon, name))
    })format!("-l{colon}{name}"))
638                .link_arg("--no-whole-archive");
639        }
640    }
641
642    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
643        self.hint_static();
644        if !whole_archive {
645            self.link_or_cc_arg(path);
646        } else if self.sess.target.is_like_darwin {
647            self.link_arg("-force_load").link_arg(path);
648        } else {
649            self.link_arg("--whole-archive").link_arg(path).link_arg("--no-whole-archive");
650        }
651    }
652
653    fn framework_path(&mut self, path: &Path) {
654        self.link_or_cc_arg("-F").link_or_cc_arg(path);
655    }
656    fn full_relro(&mut self) {
657        self.link_args(&["-z", "relro", "-z", "now"]);
658    }
659    fn partial_relro(&mut self) {
660        self.link_args(&["-z", "relro"]);
661    }
662    fn no_relro(&mut self) {
663        self.link_args(&["-z", "norelro"]);
664    }
665
666    fn gc_sections(&mut self, keep_metadata: bool) {
667        // The dead_strip option to the linker specifies that functions and data
668        // unreachable by the entry point will be removed. This is quite useful
669        // with Rust's compilation model of compiling libraries at a time into
670        // one object file. For example, this brings hello world from 1.7MB to
671        // 458K.
672        //
673        // Note that this is done for both executables and dynamic libraries. We
674        // won't get much benefit from dylibs because LLVM will have already
675        // stripped away as much as it could. This has not been seen to impact
676        // link times negatively.
677        //
678        // -dead_strip can't be part of the pre_link_args because it's also used
679        // for partial linking when using multiple codegen units (-r). So we
680        // insert it here.
681        if self.sess.target.is_like_darwin {
682            self.link_arg("-dead_strip");
683
684        // If we're building a dylib, we don't use --gc-sections because LLVM
685        // has already done the best it can do, and we also don't want to
686        // eliminate the metadata. If we're building an executable, however,
687        // --gc-sections drops the size of hello world from 1.8MB to 597K, a 67%
688        // reduction.
689        } else if (self.is_gnu || self.sess.target.is_like_wasm) && !keep_metadata {
690            self.link_arg("--gc-sections");
691        }
692    }
693
694    fn optimize(&mut self) {
695        if !self.is_gnu && !self.sess.target.is_like_wasm {
696            return;
697        }
698
699        // GNU-style linkers support optimization with -O. GNU ld doesn't
700        // need a numeric argument, but other linkers do.
701        if self.sess.opts.optimize == config::OptLevel::More
702            || self.sess.opts.optimize == config::OptLevel::Aggressive
703        {
704            self.link_arg("-O1");
705        }
706    }
707
708    fn pgo_gen(&mut self) {
709        if !self.is_gnu {
710            return;
711        }
712
713        // If we're doing PGO generation stuff and on a GNU-like linker, use the
714        // "-u" flag to properly pull in the profiler runtime bits.
715        //
716        // This is because LLVM otherwise won't add the needed initialization
717        // for us on Linux (though the extra flag should be harmless if it
718        // does).
719        //
720        // See https://reviews.llvm.org/D14033 and https://reviews.llvm.org/D14030.
721        //
722        // Though it may be worth to try to revert those changes upstream, since
723        // the overhead of the initialization should be minor.
724        self.link_or_cc_args(&["-u", "__llvm_profile_runtime"]);
725    }
726
727    fn enable_profiling(&mut self) {
728        // This flag is also used when linking to choose target specific
729        // libraries needed to enable profiling.
730        if !self.is_ld {
731            self.cc_arg("-pg");
732            // On windows-gnu targets, libgmon also needs to be linked, and this
733            // requires readding libraries to satisfy its dependencies.
734            if self.sess.target.is_like_windows {
735                self.cc_arg("-lgmon");
736                self.cc_arg("-lkernel32");
737                self.cc_arg("-lmsvcrt");
738            }
739        }
740    }
741
742    fn control_flow_guard(&mut self) {}
743
744    fn ehcont_guard(&mut self) {}
745
746    fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
747        // MacOS linker doesn't support stripping symbols directly anymore.
748        if self.sess.target.is_like_darwin {
749            return;
750        }
751
752        match strip {
753            Strip::None => {}
754            Strip::Debuginfo => {
755                // The illumos linker does not support --strip-debug although
756                // it does support --strip-all as a compatibility alias for -s.
757                // The --strip-debug case is handled by running an external
758                // `strip` utility as a separate step after linking.
759                if !self.sess.target.is_like_solaris {
760                    self.link_arg("--strip-debug");
761                }
762            }
763            Strip::Symbols => {
764                self.link_arg("--strip-all");
765            }
766        }
767        match self.sess.opts.unstable_opts.debuginfo_compression {
768            config::DebugInfoCompression::None => {}
769            config::DebugInfoCompression::Zlib => {
770                self.link_arg("--compress-debug-sections=zlib");
771            }
772            config::DebugInfoCompression::Zstd => {
773                self.link_arg("--compress-debug-sections=zstd");
774            }
775        }
776    }
777
778    fn no_crt_objects(&mut self) {
779        if !self.is_ld {
780            self.cc_arg("-nostartfiles");
781        }
782    }
783
784    fn no_default_libraries(&mut self) {
785        if !self.is_ld {
786            self.cc_arg("-nodefaultlibs");
787        }
788    }
789
790    fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, symbols: &[SymbolExport]) {
791        // Symbol visibility in object files typically takes care of this.
792        if crate_type == CrateType::Executable {
793            let should_export_executable_symbols =
794                self.sess.opts.unstable_opts.export_executable_symbols;
795            if self.sess.target.override_export_symbols.is_none()
796                && !should_export_executable_symbols
797            {
798                return;
799            }
800        }
801
802        // We manually create a list of exported symbols to ensure we don't expose any more.
803        // The object files have far more public symbols than we actually want to export,
804        // so we hide them all here.
805
806        if !self.sess.target.limit_rdylib_exports {
807            return;
808        }
809
810        let path = tmpdir.join(if self.sess.target.is_like_windows { "list.def" } else { "list" });
811        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs:811",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(811u32),
                        ::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:");
812
813        if self.sess.target.is_like_darwin {
814            // Write a plain, newline-separated list of symbols
815            let res = try {
816                let mut f = File::create_buffered(&path)?;
817                for sym in symbols {
818                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs:818",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(818u32),
                        ::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);
819                    f.write_fmt(format_args!("_{0}\n", sym.name))writeln!(f, "_{}", sym.name)?;
820                }
821            };
822            if let Err(error) = res {
823                self.sess.dcx().emit_fatal(diagnostics::LibDefWriteFailure { error });
824            }
825            self.link_arg("-exported_symbols_list").link_arg(path);
826        } else if self.sess.target.is_like_windows {
827            let res = try {
828                let mut f = File::create_buffered(&path)?;
829
830                // .def file similar to MSVC one but without LIBRARY section
831                // because LD doesn't like when it's empty
832                f.write_fmt(format_args!("EXPORTS\n"))writeln!(f, "EXPORTS")?;
833                for symbol in symbols {
834                    let kind_marker =
835                        if symbol.kind == SymbolExportKind::Data { " DATA" } else { "" };
836                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs:836",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(836u32),
                        ::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);
837                    // Quote the name in case it's reserved by linker in some way
838                    // (this accounts for names with dots in particular).
839                    f.write_fmt(format_args!("  \"{0}\"{1}\n", symbol.name, kind_marker))writeln!(f, "  \"{}\"{kind_marker}", symbol.name)?;
840                }
841            };
842            if let Err(error) = res {
843                self.sess.dcx().emit_fatal(diagnostics::LibDefWriteFailure { error });
844            }
845            self.link_arg(path);
846        } else if self.sess.target.is_like_wasm {
847            self.link_arg("--no-export-dynamic");
848            for sym in symbols {
849                self.link_arg("--export").link_arg(&sym.name);
850            }
851        } else if crate_type == CrateType::Executable && !self.sess.target.is_like_solaris {
852            let res = try {
853                let mut f = File::create_buffered(&path)?;
854                f.write_fmt(format_args!("{{\n"))writeln!(f, "{{")?;
855                for sym in symbols {
856                    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs:856",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(856u32),
                        ::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);
857                    f.write_fmt(format_args!("  {0};\n", sym.name))writeln!(f, "  {};", sym.name)?;
858                }
859                f.write_fmt(format_args!("}};\n"))writeln!(f, "}};")?;
860            };
861            if let Err(error) = res {
862                self.sess.dcx().emit_fatal(diagnostics::VersionScriptWriteFailure { error });
863            }
864            self.link_arg("--dynamic-list").link_arg(path);
865        } else {
866            // Write an LD version script
867            let res = try {
868                let mut f = File::create_buffered(&path)?;
869                f.write_fmt(format_args!("{{\n"))writeln!(f, "{{")?;
870                if !symbols.is_empty() {
871                    f.write_fmt(format_args!("  global:\n"))writeln!(f, "  global:")?;
872                    for sym in symbols {
873                        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs:873",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(873u32),
                        ::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);
874                        f.write_fmt(format_args!("    {0};\n", sym.name))writeln!(f, "    {};", sym.name)?;
875                    }
876                }
877                f.write_fmt(format_args!("\n  local:\n    *;\n}};\n"))writeln!(f, "\n  local:\n    *;\n}};")?;
878            };
879            if let Err(error) = res {
880                self.sess.dcx().emit_fatal(diagnostics::VersionScriptWriteFailure { error });
881            }
882            if self.sess.target.is_like_solaris {
883                self.link_arg("-M").link_arg(path);
884            } else {
885                let mut arg = OsString::from("--version-script=");
886                arg.push(path);
887                self.link_arg(arg).link_arg("--no-undefined-version");
888            }
889        }
890    }
891
892    fn windows_subsystem(&mut self, subsystem: WindowsSubsystemKind) {
893        self.link_args(&["--subsystem", subsystem.as_str()]);
894    }
895
896    fn reset_per_library_state(&mut self) {
897        self.hint_dynamic(); // Reset to default before returning the composed command line.
898    }
899
900    fn linker_plugin_lto(&mut self) {
901        match self.sess.opts.cg.linker_plugin_lto {
902            LinkerPluginLto::Disabled => {
903                // Nothing to do
904            }
905            LinkerPluginLto::LinkerPluginAuto => {
906                self.push_linker_plugin_lto_args(None);
907            }
908            LinkerPluginLto::LinkerPlugin(ref path) => {
909                self.push_linker_plugin_lto_args(Some(path.as_os_str()));
910            }
911        }
912    }
913
914    // Add the `GNU_EH_FRAME` program header which is required to locate unwinding information.
915    // Some versions of `gcc` add it implicitly, some (e.g. `musl-gcc`) don't,
916    // so we just always add it.
917    fn add_eh_frame_header(&mut self) {
918        self.link_arg("--eh-frame-hdr");
919    }
920
921    fn add_no_exec(&mut self) {
922        if self.sess.target.is_like_windows {
923            self.link_arg("--nxcompat");
924        } else if self.is_gnu {
925            self.link_args(&["-z", "noexecstack"]);
926        }
927    }
928
929    fn add_as_needed(&mut self) {
930        if self.is_gnu && !self.sess.target.is_like_windows {
931            self.link_arg("--as-needed");
932        } else if self.sess.target.is_like_solaris {
933            // -z ignore is the Solaris equivalent to the GNU ld --as-needed option
934            self.link_args(&["-z", "ignore"]);
935        }
936    }
937}
938
939struct MsvcLinker<'a> {
940    cmd: Command,
941    sess: &'a Session,
942}
943
944impl<'a> Linker for MsvcLinker<'a> {
945    fn cmd(&mut self) -> &mut Command {
946        &mut self.cmd
947    }
948
949    fn set_output_kind(
950        &mut self,
951        output_kind: LinkOutputKind,
952        _crate_type: CrateType,
953        out_filename: &Path,
954    ) {
955        match output_kind {
956            LinkOutputKind::DynamicNoPicExe
957            | LinkOutputKind::DynamicPicExe
958            | LinkOutputKind::StaticNoPicExe
959            | LinkOutputKind::StaticPicExe => {}
960            LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
961                self.link_arg("/DLL");
962                let mut arg: OsString = "/IMPLIB:".into();
963                arg.push(out_filename.with_extension("dll.lib"));
964                self.link_arg(arg);
965            }
966            LinkOutputKind::WasiReactorExe => {
967                {
    ::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");
968            }
969        }
970    }
971
972    fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, _as_needed: bool) {
973        // On MSVC-like targets rustc supports import libraries using alternative naming
974        // scheme (`libfoo.a`) unsupported by linker, search for such libraries manually.
975        if let Some(path) = try_find_native_dynamic_library(self.sess, name, verbatim) {
976            self.link_arg(path);
977        } else {
978            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" }));
979        }
980    }
981
982    fn link_dylib_by_path(&mut self, path: &Path, _as_needed: bool) {
983        // When producing a dll, MSVC linker may not emit an implib file if the dll doesn't export
984        // any symbols, so we skip linking if the implib file is not present.
985        let implib_path = path.with_extension("dll.lib");
986        if implib_path.exists() {
987            self.link_or_cc_arg(implib_path);
988        }
989    }
990
991    fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool) {
992        // On MSVC-like targets rustc supports static libraries using alternative naming
993        // scheme (`libfoo.a`) unsupported by linker, search for such libraries manually.
994        if let Some(path) = try_find_native_static_library(self.sess, name, verbatim) {
995            self.link_staticlib_by_path(&path, whole_archive);
996        } else {
997            let opts = if whole_archive { "/WHOLEARCHIVE:" } else { "" };
998            let (prefix, suffix) = self.sess.staticlib_components(verbatim);
999            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}"));
1000        }
1001    }
1002
1003    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
1004        if !whole_archive {
1005            self.link_arg(path);
1006        } else {
1007            let mut arg = OsString::from("/WHOLEARCHIVE:");
1008            arg.push(path);
1009            self.link_arg(arg);
1010        }
1011    }
1012
1013    fn gc_sections(&mut self, _keep_metadata: bool) {
1014        // MSVC's ICF (Identical COMDAT Folding) link optimization is
1015        // slow for Rust and thus we disable it by default when not in
1016        // optimization build.
1017        if self.sess.opts.optimize != config::OptLevel::No {
1018            self.link_arg("/OPT:REF,ICF");
1019        } else {
1020            // It is necessary to specify NOICF here, because /OPT:REF
1021            // implies ICF by default.
1022            self.link_arg("/OPT:REF,NOICF");
1023        }
1024    }
1025
1026    fn full_relro(&mut self) {
1027        // noop
1028    }
1029
1030    fn partial_relro(&mut self) {
1031        // noop
1032    }
1033
1034    fn no_relro(&mut self) {
1035        // noop
1036    }
1037
1038    fn no_crt_objects(&mut self) {
1039        // noop
1040    }
1041
1042    fn no_default_libraries(&mut self) {
1043        self.link_arg("/NODEFAULTLIB");
1044    }
1045
1046    fn include_path(&mut self, path: &Path) {
1047        let mut arg = OsString::from("/LIBPATH:");
1048        arg.push(path);
1049        self.link_arg(&arg);
1050    }
1051
1052    fn output_filename(&mut self, path: &Path) {
1053        let mut arg = OsString::from("/OUT:");
1054        arg.push(path);
1055        self.link_arg(&arg);
1056    }
1057
1058    fn optimize(&mut self) {
1059        // Needs more investigation of `/OPT` arguments
1060    }
1061
1062    fn pgo_gen(&mut self) {
1063        // Nothing needed here.
1064    }
1065
1066    fn control_flow_guard(&mut self) {
1067        self.link_arg("/guard:cf");
1068    }
1069
1070    fn ehcont_guard(&mut self) {
1071        if self.sess.target.pointer_width == 64 {
1072            self.link_arg("/guard:ehcont");
1073        }
1074    }
1075
1076    fn debuginfo(&mut self, _strip: Strip, natvis_debugger_visualizers: &[PathBuf]) {
1077        // This will cause the Microsoft linker to generate a PDB file
1078        // from the CodeView line tables in the object files.
1079        self.link_arg("/DEBUG");
1080
1081        // Default to emitting only the file name of the PDB file into
1082        // the binary instead of the full path. Emitting the full path
1083        // may leak private information (such as user names).
1084        // See https://github.com/rust-lang/rust/issues/87825.
1085        //
1086        // This default behavior can be overridden by explicitly passing
1087        // `-Clink-arg=/PDBALTPATH:...` to rustc.
1088        self.link_arg("/PDBALTPATH:%_PDB%");
1089
1090        // This will cause the Microsoft linker to embed .natvis info into the PDB file
1091        let natvis_dir_path = self.sess.opts.sysroot.path().join("lib\\rustlib\\etc");
1092        if let Ok(natvis_dir) = fs::read_dir(&natvis_dir_path) {
1093            for entry in natvis_dir {
1094                match entry {
1095                    Ok(entry) => {
1096                        let path = entry.path();
1097                        if path.extension() == Some("natvis".as_ref()) {
1098                            let mut arg = OsString::from("/NATVIS:");
1099                            arg.push(path);
1100                            self.link_arg(arg);
1101                        }
1102                    }
1103                    Err(error) => {
1104                        self.sess.dcx().emit_warn(diagnostics::NoNatvisDirectory { error });
1105                    }
1106                }
1107            }
1108        }
1109
1110        // This will cause the Microsoft linker to embed .natvis info for all crates into the PDB file
1111        for path in natvis_debugger_visualizers {
1112            let mut arg = OsString::from("/NATVIS:");
1113            arg.push(path);
1114            self.link_arg(arg);
1115        }
1116    }
1117
1118    fn export_symbols(&mut self, tmpdir: &Path, crate_type: CrateType, _symbols: &[SymbolExport]) {
1119        // We already add /EXPORT arguments to the .drectve section of symbols.o.
1120        // Keep passing an empty .def file: link.exe otherwise skips the import
1121        // library for DLLs with no exports.
1122        if crate_type == CrateType::Executable {
1123            let should_export_executable_symbols =
1124                self.sess.opts.unstable_opts.export_executable_symbols;
1125            if !should_export_executable_symbols {
1126                return;
1127            }
1128        }
1129
1130        let path = tmpdir.join("lib.def");
1131        let res = try {
1132            let mut f = File::create_buffered(&path)?;
1133            f.write_fmt(format_args!("LIBRARY\n"))writeln!(f, "LIBRARY")?;
1134            f.write_fmt(format_args!("EXPORTS\n"))writeln!(f, "EXPORTS")?;
1135        };
1136        if let Err(error) = res {
1137            self.sess.dcx().emit_fatal(diagnostics::LibDefWriteFailure { error });
1138        }
1139        let mut arg = OsString::from("/DEF:");
1140        arg.push(path);
1141        self.link_arg(&arg);
1142    }
1143
1144    fn windows_subsystem(&mut self, subsystem: WindowsSubsystemKind) {
1145        let subsystem = subsystem.as_str();
1146        self.link_arg(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("/SUBSYSTEM:{0}", subsystem))
    })format!("/SUBSYSTEM:{subsystem}"));
1147
1148        // Windows has two subsystems we're interested in right now, the console
1149        // and windows subsystems. These both implicitly have different entry
1150        // points (starting symbols). The console entry point starts with
1151        // `mainCRTStartup` and the windows entry point starts with
1152        // `WinMainCRTStartup`. These entry points, defined in system libraries,
1153        // will then later probe for either `main` or `WinMain`, respectively to
1154        // start the application.
1155        //
1156        // In Rust we just always generate a `main` function so we want control
1157        // to always start there, so we force the entry point on the windows
1158        // subsystem to be `mainCRTStartup` to get everything booted up
1159        // correctly.
1160        //
1161        // For more information see RFC #1665
1162        if subsystem == "windows" {
1163            self.link_arg("/ENTRY:mainCRTStartup");
1164        }
1165    }
1166
1167    fn linker_plugin_lto(&mut self) {
1168        // Do nothing
1169    }
1170
1171    fn add_no_exec(&mut self) {
1172        self.link_arg("/NXCOMPAT");
1173    }
1174}
1175
1176struct EmLinker<'a> {
1177    cmd: Command,
1178    sess: &'a Session,
1179}
1180
1181impl<'a> Linker for EmLinker<'a> {
1182    fn cmd(&mut self) -> &mut Command {
1183        &mut self.cmd
1184    }
1185
1186    fn is_cc(&self) -> bool {
1187        true
1188    }
1189
1190    fn set_output_kind(
1191        &mut self,
1192        output_kind: LinkOutputKind,
1193        _crate_type: CrateType,
1194        _out_filename: &Path,
1195    ) {
1196        match output_kind {
1197            LinkOutputKind::DynamicNoPicExe | LinkOutputKind::DynamicPicExe => {
1198                self.cmd.arg("-sMAIN_MODULE=2");
1199            }
1200            LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1201                self.cmd.arg("-sSIDE_MODULE=2");
1202            }
1203            // -fno-pie is the default on Emscripten.
1204            LinkOutputKind::StaticNoPicExe | LinkOutputKind::StaticPicExe => {}
1205            LinkOutputKind::WasiReactorExe => {
1206                ::core::panicking::panic("internal error: entered unreachable code");unreachable!();
1207            }
1208        }
1209    }
1210
1211    fn link_dylib_by_name(&mut self, name: &str, _verbatim: bool, _as_needed: bool) {
1212        // Emscripten always links statically
1213        self.link_or_cc_args(&["-l", name]);
1214    }
1215
1216    fn link_dylib_by_path(&mut self, path: &Path, _as_needed: bool) {
1217        self.link_or_cc_arg(path);
1218    }
1219
1220    fn link_staticlib_by_name(&mut self, name: &str, _verbatim: bool, _whole_archive: bool) {
1221        self.link_or_cc_args(&["-l", name]);
1222    }
1223
1224    fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
1225        self.link_or_cc_arg(path);
1226    }
1227
1228    fn full_relro(&mut self) {
1229        // noop
1230    }
1231
1232    fn partial_relro(&mut self) {
1233        // noop
1234    }
1235
1236    fn no_relro(&mut self) {
1237        // noop
1238    }
1239
1240    fn gc_sections(&mut self, _keep_metadata: bool) {
1241        // noop
1242    }
1243
1244    fn optimize(&mut self) {
1245        // Emscripten performs own optimizations
1246        self.cc_arg(match self.sess.opts.optimize {
1247            OptLevel::No => "-O0",
1248            OptLevel::Less => "-O1",
1249            OptLevel::More => "-O2",
1250            OptLevel::Aggressive => "-O3",
1251            OptLevel::Size => "-Os",
1252            OptLevel::SizeMin => "-Oz",
1253        });
1254    }
1255
1256    fn pgo_gen(&mut self) {
1257        // noop, but maybe we need something like the gnu linker?
1258    }
1259
1260    fn control_flow_guard(&mut self) {}
1261
1262    fn ehcont_guard(&mut self) {}
1263
1264    fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1265        // Preserve names or generate source maps depending on debug info
1266        // For more information see https://emscripten.org/docs/tools_reference/emcc.html#emcc-g
1267        self.cc_arg(match self.sess.opts.debuginfo {
1268            DebugInfo::None => "-g0",
1269            DebugInfo::Limited | DebugInfo::LineTablesOnly | DebugInfo::LineDirectivesOnly => {
1270                "--profiling-funcs"
1271            }
1272            DebugInfo::Full => "-g",
1273        });
1274    }
1275
1276    fn no_crt_objects(&mut self) {}
1277
1278    fn no_default_libraries(&mut self) {
1279        self.cc_arg("-nodefaultlibs");
1280    }
1281
1282    fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1283        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs:1283",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(1283u32),
                        ::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:");
1284
1285        self.cc_arg("-s");
1286
1287        // Emscripten exposes the program entry point under the JS name `_main`
1288        // regardless of the underlying wasm symbol (which is `__main_argc_argv`
1289        // per the wasm C ABI in the tool-conventions BasicCABI spec), bridging
1290        // the two internally. So the entry symbol must be requested as `_main`
1291        // here rather than as a `_`-prefixed form of its wasm name.
1292        let entry_name = self.sess.target.entry_name.as_ref();
1293        let mut arg = OsString::from("EXPORTED_FUNCTIONS=");
1294        let encoded = serde_json::to_string(
1295            &symbols
1296                .iter()
1297                .map(|sym| {
1298                    if sym.name == entry_name {
1299                        "_main".to_owned()
1300                    } else {
1301                        "_".to_owned() + &sym.name
1302                    }
1303                })
1304                .collect::<Vec<_>>(),
1305        )
1306        .unwrap();
1307        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs:1307",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(1307u32),
                        ::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}");
1308
1309        arg.push(encoded);
1310
1311        self.cc_arg(arg);
1312    }
1313
1314    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {
1315        // noop
1316    }
1317
1318    fn linker_plugin_lto(&mut self) {
1319        // Do nothing
1320    }
1321}
1322
1323struct WasmLd<'a> {
1324    cmd: Command,
1325    sess: &'a Session,
1326}
1327
1328impl<'a> WasmLd<'a> {
1329    fn new(cmd: Command, sess: &'a Session) -> WasmLd<'a> {
1330        WasmLd { cmd, sess }
1331    }
1332}
1333
1334impl<'a> Linker for WasmLd<'a> {
1335    fn cmd(&mut self) -> &mut Command {
1336        &mut self.cmd
1337    }
1338
1339    fn set_output_kind(
1340        &mut self,
1341        output_kind: LinkOutputKind,
1342        _crate_type: CrateType,
1343        _out_filename: &Path,
1344    ) {
1345        match output_kind {
1346            LinkOutputKind::DynamicNoPicExe
1347            | LinkOutputKind::DynamicPicExe
1348            | LinkOutputKind::StaticNoPicExe
1349            | LinkOutputKind::StaticPicExe => {}
1350            LinkOutputKind::DynamicDylib | LinkOutputKind::StaticDylib => {
1351                self.link_arg("--no-entry");
1352            }
1353            LinkOutputKind::WasiReactorExe => {
1354                self.link_args(&["--entry", "_initialize"]);
1355            }
1356        }
1357    }
1358
1359    fn link_dylib_by_name(&mut self, name: &str, _verbatim: bool, _as_needed: bool) {
1360        self.link_or_cc_args(&["-l", name]);
1361    }
1362
1363    fn link_dylib_by_path(&mut self, path: &Path, _as_needed: bool) {
1364        self.link_or_cc_arg(path);
1365    }
1366
1367    fn link_staticlib_by_name(&mut self, name: &str, _verbatim: bool, whole_archive: bool) {
1368        if !whole_archive {
1369            self.link_or_cc_args(&["-l", name]);
1370        } else {
1371            self.link_arg("--whole-archive")
1372                .link_or_cc_args(&["-l", name])
1373                .link_arg("--no-whole-archive");
1374        }
1375    }
1376
1377    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
1378        if !whole_archive {
1379            self.link_or_cc_arg(path);
1380        } else {
1381            self.link_arg("--whole-archive").link_or_cc_arg(path).link_arg("--no-whole-archive");
1382        }
1383    }
1384
1385    fn full_relro(&mut self) {}
1386
1387    fn partial_relro(&mut self) {}
1388
1389    fn no_relro(&mut self) {}
1390
1391    fn gc_sections(&mut self, _keep_metadata: bool) {
1392        self.link_arg("--gc-sections");
1393    }
1394
1395    fn optimize(&mut self) {
1396        // The -O flag is, as of late 2023, only used for merging of strings and debuginfo, and
1397        // only differentiates -O0 and -O1. It does not apply to LTO.
1398        self.link_arg(match self.sess.opts.optimize {
1399            OptLevel::No => "-O0",
1400            OptLevel::Less => "-O1",
1401            OptLevel::More => "-O2",
1402            OptLevel::Aggressive => "-O3",
1403            // Currently LLD doesn't support `Os` and `Oz`, so pass through `O2`
1404            // instead.
1405            OptLevel::Size => "-O2",
1406            OptLevel::SizeMin => "-O2",
1407        });
1408    }
1409
1410    fn pgo_gen(&mut self) {}
1411
1412    fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
1413        match strip {
1414            Strip::None => {}
1415            Strip::Debuginfo => {
1416                self.link_arg("--strip-debug");
1417            }
1418            Strip::Symbols => {
1419                self.link_arg("--strip-all");
1420            }
1421        }
1422    }
1423
1424    fn control_flow_guard(&mut self) {}
1425
1426    fn ehcont_guard(&mut self) {}
1427
1428    fn no_crt_objects(&mut self) {}
1429
1430    fn no_default_libraries(&mut self) {}
1431
1432    fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1433        for sym in symbols {
1434            self.link_args(&["--export", &sym.name]);
1435        }
1436    }
1437
1438    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {}
1439
1440    fn linker_plugin_lto(&mut self) {
1441        match self.sess.opts.cg.linker_plugin_lto {
1442            LinkerPluginLto::Disabled => {
1443                // Nothing to do
1444            }
1445            LinkerPluginLto::LinkerPluginAuto => {
1446                self.push_linker_plugin_lto_args();
1447            }
1448            LinkerPluginLto::LinkerPlugin(_) => {
1449                self.push_linker_plugin_lto_args();
1450            }
1451        }
1452    }
1453}
1454
1455impl<'a> WasmLd<'a> {
1456    fn push_linker_plugin_lto_args(&mut self) {
1457        let opt_level = match self.sess.opts.optimize {
1458            config::OptLevel::No => "O0",
1459            config::OptLevel::Less => "O1",
1460            config::OptLevel::More => "O2",
1461            config::OptLevel::Aggressive => "O3",
1462            // wasm-ld only handles integer LTO opt levels. Use O2
1463            config::OptLevel::Size | config::OptLevel::SizeMin => "O2",
1464        };
1465        self.link_arg(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("--lto-{0}", opt_level))
    })format!("--lto-{opt_level}"));
1466    }
1467}
1468
1469/// Linker for AIX.
1470struct AixLinker<'a> {
1471    cmd: Command,
1472    sess: &'a Session,
1473    hinted_static: Option<bool>,
1474}
1475
1476impl<'a> AixLinker<'a> {
1477    fn new(cmd: Command, sess: &'a Session) -> AixLinker<'a> {
1478        AixLinker { cmd, sess, hinted_static: None }
1479    }
1480
1481    fn hint_static(&mut self) {
1482        if self.hinted_static != Some(true) {
1483            self.link_arg("-bstatic");
1484            self.hinted_static = Some(true);
1485        }
1486    }
1487
1488    fn hint_dynamic(&mut self) {
1489        if self.hinted_static != Some(false) {
1490            self.link_arg("-bdynamic");
1491            self.hinted_static = Some(false);
1492        }
1493    }
1494
1495    fn build_dylib(&mut self, _out_filename: &Path) {
1496        self.link_args(&["-bM:SRE", "-bnoentry"]);
1497        // FIXME: Use CreateExportList utility to create export list
1498        // and remove -bexpfull.
1499        self.link_arg("-bexpfull");
1500    }
1501}
1502
1503impl<'a> Linker for AixLinker<'a> {
1504    fn cmd(&mut self) -> &mut Command {
1505        &mut self.cmd
1506    }
1507
1508    fn set_output_kind(
1509        &mut self,
1510        output_kind: LinkOutputKind,
1511        _crate_type: CrateType,
1512        out_filename: &Path,
1513    ) {
1514        match output_kind {
1515            LinkOutputKind::DynamicDylib => {
1516                self.hint_dynamic();
1517                self.build_dylib(out_filename);
1518            }
1519            LinkOutputKind::StaticDylib => {
1520                self.hint_static();
1521                self.build_dylib(out_filename);
1522            }
1523            _ => {}
1524        }
1525    }
1526
1527    fn link_dylib_by_name(&mut self, name: &str, verbatim: bool, _as_needed: bool) {
1528        self.hint_dynamic();
1529        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}") });
1530    }
1531
1532    fn link_dylib_by_path(&mut self, path: &Path, _as_needed: bool) {
1533        self.hint_dynamic();
1534        self.link_or_cc_arg(path);
1535    }
1536
1537    fn link_staticlib_by_name(&mut self, name: &str, verbatim: bool, whole_archive: bool) {
1538        self.hint_static();
1539        if !whole_archive {
1540            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}") });
1541        } else {
1542            let mut arg = OsString::from("-bkeepfile:");
1543            arg.push(find_native_static_library(name, verbatim, self.sess));
1544            self.link_or_cc_arg(arg);
1545        }
1546    }
1547
1548    fn link_staticlib_by_path(&mut self, path: &Path, whole_archive: bool) {
1549        self.hint_static();
1550        if !whole_archive {
1551            self.link_or_cc_arg(path);
1552        } else {
1553            let mut arg = OsString::from("-bkeepfile:");
1554            arg.push(path);
1555            self.link_arg(arg);
1556        }
1557    }
1558
1559    fn full_relro(&mut self) {}
1560
1561    fn partial_relro(&mut self) {}
1562
1563    fn no_relro(&mut self) {}
1564
1565    fn gc_sections(&mut self, _keep_metadata: bool) {
1566        self.link_arg("-bgc");
1567    }
1568
1569    fn optimize(&mut self) {}
1570
1571    fn pgo_gen(&mut self) {
1572        self.link_arg("-bdbg:namedsects:ss");
1573        self.link_arg("-u");
1574        self.link_arg("__llvm_profile_runtime");
1575    }
1576
1577    fn control_flow_guard(&mut self) {}
1578
1579    fn ehcont_guard(&mut self) {}
1580
1581    fn debuginfo(&mut self, _: Strip, _: &[PathBuf]) {}
1582
1583    fn no_crt_objects(&mut self) {}
1584
1585    fn no_default_libraries(&mut self) {}
1586
1587    fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1588        let path = tmpdir.join("list.exp");
1589        let res = try {
1590            let mut f = File::create_buffered(&path)?;
1591            // FIXME: use llvm-nm to generate export list.
1592            for symbol in symbols {
1593                {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs:1593",
                        "rustc_codegen_ssa::back::linker", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/f248f4038796913873f11ca65b1b901e311c8dae/compiler/rustc_codegen_ssa/src/back/linker.rs"),
                        ::tracing_core::__macro_support::Option::Some(1593u32),
                        ::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);
1594                f.write_fmt(format_args!("  {0}\n", symbol.name))writeln!(f, "  {}", symbol.name)?;
1595            }
1596        };
1597        if let Err(e) = res {
1598            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}"));
1599        }
1600        self.link_arg(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("-bE:{0}", path.to_str().unwrap()))
    })format!("-bE:{}", path.to_str().unwrap()));
1601    }
1602
1603    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {}
1604
1605    fn reset_per_library_state(&mut self) {
1606        self.hint_dynamic();
1607    }
1608
1609    fn linker_plugin_lto(&mut self) {}
1610
1611    fn add_eh_frame_header(&mut self) {}
1612
1613    fn add_no_exec(&mut self) {}
1614
1615    fn add_as_needed(&mut self) {}
1616}
1617
1618fn for_each_exported_symbols_include_dep<'tcx>(
1619    tcx: TyCtxt<'tcx>,
1620    crate_type: CrateType,
1621    mut callback: impl FnMut(ExportedSymbol<'tcx>, SymbolExportInfo, CrateNum),
1622) {
1623    let formats = tcx.dependency_formats(());
1624    let deps = &formats[&crate_type];
1625
1626    for (cnum, dep_format) in deps.iter_enumerated() {
1627        // For each dependency that we are linking to statically ...
1628        if *dep_format == Linkage::Static {
1629            for &(symbol, info) in tcx.exported_non_generic_symbols(cnum).iter() {
1630                callback(symbol, info, cnum);
1631            }
1632            for &(symbol, info) in tcx.exported_generic_symbols(cnum).iter() {
1633                callback(symbol, info, cnum);
1634            }
1635        }
1636    }
1637}
1638
1639fn symbol_export_from_exported_symbol<'tcx>(
1640    tcx: TyCtxt<'tcx>,
1641    symbol: ExportedSymbol<'tcx>,
1642    kind: SymbolExportKind,
1643    cnum: CrateNum,
1644) -> SymbolExport {
1645    let name = symbol_export::exporting_symbol_name_for_instance_in_crate(tcx, symbol, cnum);
1646    let link_name =
1647        symbol_export::linking_symbol_name_for_instance_in_crate(tcx, symbol, kind, cnum);
1648    SymbolExport::with_link_name(name, kind, link_name)
1649}
1650
1651fn symbol_export_from_raw_name(
1652    tcx: TyCtxt<'_>,
1653    name: String,
1654    kind: SymbolExportKind,
1655) -> SymbolExport {
1656    let symbol = ExportedSymbol::NoDefId(SymbolName::new(tcx, &name));
1657    let link_name =
1658        symbol_export::linking_symbol_name_for_instance_in_crate(tcx, symbol, kind, LOCAL_CRATE);
1659    SymbolExport::with_link_name(name, kind, link_name)
1660}
1661
1662pub(crate) fn exported_symbols(tcx: TyCtxt<'_>, crate_type: CrateType) -> Vec<SymbolExport> {
1663    if let Some(ref exports) = tcx.sess.target.override_export_symbols {
1664        return exports
1665            .iter()
1666            .map(|name| {
1667                symbol_export_from_raw_name(
1668                    tcx,
1669                    name.to_string(),
1670                    // FIXME use the correct export kind for this symbol. override_export_symbols
1671                    // can't directly specify the SymbolExportKind as it is defined in rustc_middle
1672                    // which rustc_target can't depend on.
1673                    SymbolExportKind::Text,
1674                )
1675            })
1676            .collect();
1677    }
1678
1679    let mut symbols = if let CrateType::ProcMacro = crate_type {
1680        exported_symbols_for_proc_macro_crate(tcx)
1681    } else {
1682        exported_symbols_for_non_proc_macro(tcx, crate_type)
1683    };
1684
1685    // Preserve the metadata symbol to ensure the metadata section doesn't get removed by the
1686    // linker. On wasm however the metadata is put in a custom section, to which symbols can't
1687    // refer, so there is no metadata symbol there. Luckily custom sections are always preserved by
1688    // the linker.
1689    if (crate_type == CrateType::Dylib || crate_type == CrateType::ProcMacro)
1690        && !tcx.sess.target.is_like_wasm
1691    {
1692        let metadata_symbol_name = exported_symbols::metadata_symbol_name(tcx);
1693        symbols.push(symbol_export_from_raw_name(
1694            tcx,
1695            metadata_symbol_name,
1696            SymbolExportKind::Data,
1697        ));
1698    }
1699
1700    symbols
1701}
1702
1703fn exported_symbols_for_non_proc_macro(
1704    tcx: TyCtxt<'_>,
1705    crate_type: CrateType,
1706) -> Vec<SymbolExport> {
1707    let mut symbols = Vec::new();
1708    let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1709    for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| {
1710        // Do not export mangled symbols from cdylibs and don't attempt to export compiler-builtins
1711        // from any dylib. The latter doesn't work anyway as we use hidden visibility for
1712        // compiler-builtins. Most linkers silently ignore it, but ld64 gives a warning.
1713        if info.level.is_below_threshold(export_threshold) && !tcx.is_compiler_builtins(cnum) {
1714            symbols.push(symbol_export_from_exported_symbol(tcx, symbol, info.kind, cnum));
1715            symbol_export::extend_exported_symbols(&mut symbols, tcx, symbol, cnum);
1716        }
1717    });
1718
1719    // Mark allocator shim symbols as exported only if they were generated.
1720    if export_threshold == SymbolExportLevel::Rust
1721        && needs_allocator_shim_for_linking(tcx.dependency_formats(()), crate_type)
1722        && let Some(kind) = tcx.allocator_kind(())
1723    {
1724        symbols.extend(
1725            allocator_shim_symbols(tcx, kind)
1726                .map(|(name, kind)| symbol_export_from_raw_name(tcx, name, kind)),
1727        );
1728    }
1729
1730    symbols
1731}
1732
1733fn exported_symbols_for_proc_macro_crate(tcx: TyCtxt<'_>) -> Vec<SymbolExport> {
1734    // `exported_symbols` will be empty when !should_codegen.
1735    if !tcx.sess.opts.output_types.should_codegen() {
1736        return Vec::new();
1737    }
1738
1739    let stable_crate_id = tcx.stable_crate_id(LOCAL_CRATE);
1740    let proc_macro_decls_name = rustc_session::generate_proc_macro_decls_symbol(stable_crate_id);
1741
1742    ::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)]
1743}
1744
1745pub(crate) fn linked_symbols(
1746    tcx: TyCtxt<'_>,
1747    crate_type: CrateType,
1748) -> Vec<(String, SymbolExportKind)> {
1749    match crate_type {
1750        CrateType::Executable
1751        | CrateType::ProcMacro
1752        | CrateType::Cdylib
1753        | CrateType::Dylib
1754        | CrateType::Sdylib => (),
1755        CrateType::StaticLib | CrateType::Rlib => {
1756            // These are not linked, so no need to generate symbols.o for them.
1757            return Vec::new();
1758        }
1759    }
1760
1761    match tcx.sess.lto() {
1762        Lto::No | Lto::ThinLocal => {}
1763        Lto::Thin | Lto::Fat => {
1764            // We really only need symbols from upstream rlibs to end up in the linked symbols list.
1765            // The rest are in separate object files which the linker will always link in and
1766            // doesn't have rules around the order in which they need to appear.
1767            // When doing LTO, some of the symbols in the linked symbols list happen to be
1768            // internalized by LTO, which then prevents referencing them from symbols.o. When doing
1769            // LTO, all object files that get linked in will be local object files rather than
1770            // pulled in from rlibs, so an empty linked symbols list works fine to avoid referencing
1771            // all those internalized symbols from symbols.o.
1772            return Vec::new();
1773        }
1774    }
1775
1776    let mut symbols = Vec::new();
1777
1778    let export_threshold = symbol_export::crates_export_threshold(&[crate_type]);
1779    for_each_exported_symbols_include_dep(tcx, crate_type, |symbol, info, cnum| {
1780        if info.level.is_below_threshold(export_threshold) && !tcx.is_compiler_builtins(cnum)
1781            || info.used
1782            || info.rustc_std_internal_symbol
1783        {
1784            symbols.push((
1785                symbol_export::linking_symbol_name_for_instance_in_crate(
1786                    tcx, symbol, info.kind, cnum,
1787                ),
1788                info.kind,
1789            ));
1790        }
1791    });
1792
1793    symbols
1794}
1795
1796/// The `self-contained` LLVM bitcode linker
1797struct LlbcLinker<'a> {
1798    cmd: Command,
1799    sess: &'a Session,
1800}
1801
1802impl<'a> Linker for LlbcLinker<'a> {
1803    fn cmd(&mut self) -> &mut Command {
1804        &mut self.cmd
1805    }
1806
1807    fn set_output_kind(
1808        &mut self,
1809        _output_kind: LinkOutputKind,
1810        _crate_type: CrateType,
1811        _out_filename: &Path,
1812    ) {
1813    }
1814
1815    fn link_staticlib_by_name(&mut self, _name: &str, _verbatim: bool, _whole_archive: bool) {
1816        { ::core::panicking::panic_fmt(format_args!("staticlibs not supported")); }panic!("staticlibs not supported")
1817    }
1818
1819    fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
1820        self.link_or_cc_arg(path);
1821    }
1822
1823    fn debuginfo(&mut self, strip: Strip, _: &[PathBuf]) {
1824        match strip {
1825            Strip::None => {
1826                self.link_arg("--debug");
1827            }
1828            Strip::Debuginfo | Strip::Symbols => {}
1829        }
1830    }
1831
1832    fn optimize(&mut self) {
1833        self.link_arg(match self.sess.opts.optimize {
1834            OptLevel::No => "-O0",
1835            OptLevel::Less => "-O1",
1836            OptLevel::More => "-O2",
1837            OptLevel::Aggressive => "-O3",
1838            OptLevel::Size => "-Os",
1839            OptLevel::SizeMin => "-Oz",
1840        });
1841    }
1842
1843    fn full_relro(&mut self) {}
1844
1845    fn partial_relro(&mut self) {}
1846
1847    fn no_relro(&mut self) {}
1848
1849    fn gc_sections(&mut self, _keep_metadata: bool) {}
1850
1851    fn pgo_gen(&mut self) {}
1852
1853    fn no_crt_objects(&mut self) {}
1854
1855    fn no_default_libraries(&mut self) {}
1856
1857    fn control_flow_guard(&mut self) {}
1858
1859    fn ehcont_guard(&mut self) {}
1860
1861    fn export_symbols(&mut self, _tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1862        match _crate_type {
1863            CrateType::Cdylib => {
1864                for sym in symbols {
1865                    self.link_args(&["--export-symbol", &sym.name]);
1866                }
1867            }
1868            _ => (),
1869        }
1870    }
1871
1872    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {}
1873
1874    fn linker_plugin_lto(&mut self) {}
1875}
1876
1877struct BpfLinker<'a> {
1878    cmd: Command,
1879    sess: &'a Session,
1880}
1881
1882impl<'a> Linker for BpfLinker<'a> {
1883    fn cmd(&mut self) -> &mut Command {
1884        &mut self.cmd
1885    }
1886
1887    fn set_output_kind(
1888        &mut self,
1889        _output_kind: LinkOutputKind,
1890        _crate_type: CrateType,
1891        _out_filename: &Path,
1892    ) {
1893    }
1894
1895    fn link_staticlib_by_name(&mut self, _name: &str, _verbatim: bool, _whole_archive: bool) {
1896        self.sess.dcx().emit_fatal(diagnostics::BpfStaticlibNotSupported)
1897    }
1898
1899    fn link_staticlib_by_path(&mut self, path: &Path, _whole_archive: bool) {
1900        self.link_or_cc_arg(path);
1901    }
1902
1903    fn debuginfo(&mut self, _strip: Strip, _: &[PathBuf]) {
1904        self.link_arg("--debug");
1905    }
1906
1907    fn optimize(&mut self) {
1908        self.link_arg(match self.sess.opts.optimize {
1909            OptLevel::No => "-O0",
1910            OptLevel::Less => "-O1",
1911            OptLevel::More => "-O2",
1912            OptLevel::Aggressive => "-O3",
1913            OptLevel::Size => "-Os",
1914            OptLevel::SizeMin => "-Oz",
1915        });
1916    }
1917
1918    fn full_relro(&mut self) {}
1919
1920    fn partial_relro(&mut self) {}
1921
1922    fn no_relro(&mut self) {}
1923
1924    fn gc_sections(&mut self, _keep_metadata: bool) {}
1925
1926    fn pgo_gen(&mut self) {}
1927
1928    fn no_crt_objects(&mut self) {}
1929
1930    fn no_default_libraries(&mut self) {}
1931
1932    fn control_flow_guard(&mut self) {}
1933
1934    fn ehcont_guard(&mut self) {}
1935
1936    fn export_symbols(&mut self, tmpdir: &Path, _crate_type: CrateType, symbols: &[SymbolExport]) {
1937        let path = tmpdir.join("symbols");
1938        let res = try {
1939            let mut f = File::create_buffered(&path)?;
1940            for sym in symbols {
1941                f.write_fmt(format_args!("{0}\n", sym.name))writeln!(f, "{}", sym.name)?;
1942            }
1943        };
1944        if let Err(error) = res {
1945            self.sess.dcx().emit_fatal(diagnostics::SymbolFileWriteFailure { error });
1946        } else {
1947            self.link_arg("--export-symbols").link_arg(&path);
1948        }
1949    }
1950
1951    fn windows_subsystem(&mut self, _subsystem: WindowsSubsystemKind) {}
1952
1953    fn linker_plugin_lto(&mut self) {}
1954}