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