Skip to main content

rustc_metadata/
dependency_format.rs

1//! Resolution of mixing rlibs and dylibs
2//!
3//! When producing a final artifact, such as a dynamic library, the compiler has
4//! a choice between linking an rlib or linking a dylib of all upstream
5//! dependencies. The linking phase must guarantee, however, that a library only
6//! show up once in the object file. For example, it is illegal for library A to
7//! be statically linked to B and C in separate dylibs, and then link B and C
8//! into a crate D (because library A appears twice).
9//!
10//! The job of this module is to calculate what format each upstream crate
11//! should be used when linking each output type requested in this session. This
12//! generally follows this set of rules:
13//!
14//! 1. Each library must appear exactly once in the output.
15//! 2. Each rlib contains only one library (it's just an object file)
16//! 3. Each dylib can contain more than one library (due to static linking),
17//!    and can also bring in many dynamic dependencies.
18//!
19//! With these constraints in mind, it's generally a very difficult problem to
20//! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
21//! that NP-ness may come into the picture here...
22//!
23//! The current selection algorithm below looks mostly similar to:
24//!
25//! 1. If static linking is required, then require all upstream dependencies
26//!    to be available as rlibs. If not, generate an error.
27//! 2. If static linking is requested (generating an executable), then
28//!    attempt to use all upstream dependencies as rlibs. If any are not
29//!    found, bail out and continue to step 3.
30//! 3. Static linking has failed, at least one library must be dynamically
31//!    linked. Apply a heuristic by greedily maximizing the number of
32//!    dynamically linked libraries.
33//! 4. Each upstream dependency available as a dynamic library is
34//!    registered. The dependencies all propagate, adding to a map. It is
35//!    possible for a dylib to add a static library as a dependency, but it
36//!    is illegal for two dylibs to add the same static library as a
37//!    dependency. The same dylib can be added twice. Additionally, it is
38//!    illegal to add a static dependency when it was previously found as a
39//!    dylib (and vice versa)
40//! 5. After all dynamic dependencies have been traversed, re-traverse the
41//!    remaining dependencies and add them statically (if they haven't been
42//!    added already).
43//!
44//! While not perfect, this algorithm should help support use-cases such as leaf
45//! dependencies being static while the larger tree of inner dependencies are
46//! all dynamic. This isn't currently very well battle tested, so it will likely
47//! fall short in some use cases.
48//!
49//! Currently, there is no way to specify the preference of linkage with a
50//! particular library (other than a global dynamic/static switch).
51//! Additionally, the algorithm is geared towards finding *any* solution rather
52//! than finding a number of solutions (there are normally quite a few).
53
54use rustc_crate_store::LinkagePreference::{self, RequireDynamic, RequireStatic};
55use rustc_crate_store::{CrateDepKind, CrateSourceFlags};
56use rustc_data_structures::fx::{FxHashMap, FxHashSet};
57use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
58use rustc_index::IndexVec;
59use rustc_middle::middle::dependency_format::{Dependencies, DependencyList, Linkage};
60use rustc_middle::ty::TyCtxt;
61use rustc_span::{bug, sym};
62use rustc_structures::CrateType;
63use rustc_target::spec::PanicStrategy;
64use tracing::info;
65
66use crate::creader::CStore;
67use crate::diagnostics::{
68    BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy,
69    IncompatibleWithImmediateAbort, IncompatibleWithImmediateAbortCore, LibRequired,
70    NonStaticCrateDep, RequiredPanicStrategy, RlibRequired, RustcLibRequired, TwoPanicRuntimes,
71};
72
73pub(crate) fn calculate(tcx: TyCtxt<'_>) -> Dependencies {
74    tcx.crate_types()
75        .iter()
76        .map(|&ty| {
77            let linkage = calculate_type(tcx, ty);
78            verify_ok(tcx, &linkage);
79            (ty, linkage)
80        })
81        .collect()
82}
83
84fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
85    let sess = &tcx.sess;
86
87    if !sess.opts.output_types.should_link() {
88        return IndexVec::new();
89    }
90
91    let preferred_linkage =
92        match ty {
93            // Generating a dylib without `-C prefer-dynamic` means that we're going
94            // to try to eagerly statically link all dependencies. This is normally
95            // done for end-product dylibs, not intermediate products.
96            //
97            // Treat cdylibs and staticlibs similarly. If `-C prefer-dynamic` is set,
98            // the caller may be code-size conscious, but without it, it makes sense
99            // to statically link a cdylib or staticlib. For staticlibs we use
100            // `-Z staticlib-prefer-dynamic` for now. This may be merged into
101            // `-C prefer-dynamic` in the future.
102            CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
103                if sess.opts.cg.prefer_dynamic { Linkage::Dynamic } else { Linkage::Static }
104            }
105            CrateType::StaticLib => {
106                if sess.opts.unstable_opts.staticlib_prefer_dynamic {
107                    Linkage::Dynamic
108                } else {
109                    Linkage::Static
110                }
111            }
112
113            // If the global prefer_dynamic switch is turned off, or the final
114            // executable will be statically linked, prefer static crate linkage.
115            CrateType::Executable if !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => {
116                Linkage::Static
117            }
118            CrateType::Executable => Linkage::Dynamic,
119
120            // proc-macro crates are mostly cdylibs, but we also need metadata.
121            CrateType::ProcMacro => Linkage::Static,
122
123            // No linkage happens with rlibs, we just needed the metadata (which we
124            // got long ago), so don't bother with anything.
125            CrateType::Rlib => Linkage::NotLinked,
126        };
127
128    let mut unavailable_as_static = Vec::new();
129
130    match preferred_linkage {
131        // If the crate is not linked, there are no link-time dependencies.
132        Linkage::NotLinked => return IndexVec::new(),
133        Linkage::Static => {
134            // Attempt static linkage first. For dylibs and executables, we may be
135            // able to retry below with dynamic linkage.
136            if let Some(v) = attempt_static(tcx, &mut unavailable_as_static) {
137                return v;
138            }
139
140            // Static executables must have all static dependencies.
141            // If any are not found, generate some nice pretty errors.
142            if (ty == CrateType::StaticLib && !sess.opts.unstable_opts.staticlib_allow_rdylib_deps)
143                || (ty == CrateType::Executable
144                    && sess.crt_static(Some(ty))
145                    && !sess.target.crt_static_allows_dylibs)
146            {
147                for &cnum in tcx.crates(()).iter() {
148                    if tcx.crate_dep_kind(cnum).macros_only() {
149                        continue;
150                    }
151
152                    if tcx.used_crate_source_flags(cnum).contains(CrateSourceFlags::RLIB) {
153                        continue;
154                    }
155                    sess.dcx().emit_err(RlibRequired { crate_name: tcx.crate_name(cnum) });
156                }
157                return IndexVec::new();
158            }
159        }
160        Linkage::Dynamic | Linkage::IncludedFromDylib => {}
161    }
162
163    let all_dylibs = || {
164        tcx.crates(()).iter().filter(|&&cnum| {
165            !tcx.crate_dep_kind(cnum).macros_only()
166                && (tcx
167                    .used_crate_source_flags(cnum)
168                    .intersects(CrateSourceFlags::DYLIB | CrateSourceFlags::SDYLIB_INTERFACE))
169        })
170    };
171
172    let mut upstream_in_dylibs = FxHashSet::default();
173
174    if tcx.features().rustc_private() {
175        // We need this to prevent users of `rustc_driver` from linking dynamically to `std`
176        // which does not work as `std` is also statically linked into `rustc_driver`.
177
178        // Find all libraries statically linked to upstream dylibs.
179        for &cnum in all_dylibs() {
180            let deps = tcx.dylib_dependency_formats(cnum);
181            for &(depnum, style) in deps.iter() {
182                if let RequireStatic = style {
183                    upstream_in_dylibs.insert(depnum);
184                }
185            }
186        }
187    }
188
189    let mut formats = FxHashMap::default();
190
191    // Sweep all crates for found dylibs. Add all dylibs, as well as their
192    // dependencies, ensuring there are no conflicts. The only valid case for a
193    // dependency to be relied upon twice is for both cases to rely on a dylib.
194    for &cnum in all_dylibs() {
195        if upstream_in_dylibs.contains(&cnum) {
196            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/dependency_format.rs:196",
                        "rustc_metadata::dependency_format", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/dependency_format.rs"),
                        ::tracing_core::__macro_support::Option::Some(196u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::dependency_format"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("skipping dylib: {0}",
                                                    tcx.crate_name(cnum)) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("skipping dylib: {}", tcx.crate_name(cnum));
197            // If this dylib is also available statically linked to another dylib
198            // we try to use that instead.
199            continue;
200        }
201
202        let name = tcx.crate_name(cnum);
203        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/dependency_format.rs:203",
                        "rustc_metadata::dependency_format", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/dependency_format.rs"),
                        ::tracing_core::__macro_support::Option::Some(203u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::dependency_format"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("adding dylib: {0}",
                                                    name) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("adding dylib: {}", name);
204        add_library(tcx, cnum, RequireDynamic, &mut formats, &mut unavailable_as_static);
205        let deps = tcx.dylib_dependency_formats(cnum);
206        for &(depnum, style) in deps.iter() {
207            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/dependency_format.rs:207",
                        "rustc_metadata::dependency_format", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/dependency_format.rs"),
                        ::tracing_core::__macro_support::Option::Some(207u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::dependency_format"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("adding {0:?}: {1}",
                                                    style, tcx.crate_name(depnum)) as
                                            &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("adding {:?}: {}", style, tcx.crate_name(depnum));
208            add_library(tcx, depnum, style, &mut formats, &mut unavailable_as_static);
209        }
210    }
211
212    // Collect what we've got so far in the return vector.
213    let last_crate = tcx.crates(()).len();
214    let mut ret = IndexVec::new();
215
216    // We need to fill in something for LOCAL_CRATE as IndexVec is a dense map.
217    // Linkage::Static semantically the most correct thing to use as the local
218    // crate is always statically linked into the linker output, even when
219    // linking a dylib. Using Linkage::Static also allow avoiding special cases
220    // for LOCAL_CRATE in some places.
221    {
    match (&ret.push(Linkage::Static), &LOCAL_CRATE) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(ret.push(Linkage::Static), LOCAL_CRATE);
222
223    for cnum in 1..last_crate + 1 {
224        let cnum = CrateNum::new(cnum);
225        {
    match (&ret.push(match formats.get(&cnum) {
                        Some(&RequireDynamic) => Linkage::Dynamic,
                        Some(&RequireStatic) => Linkage::IncludedFromDylib,
                        None => Linkage::NotLinked,
                    }), &cnum) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(
226            ret.push(match formats.get(&cnum) {
227                Some(&RequireDynamic) => Linkage::Dynamic,
228                Some(&RequireStatic) => Linkage::IncludedFromDylib,
229                None => Linkage::NotLinked,
230            }),
231            cnum
232        );
233    }
234
235    // Run through the dependency list again, and add any missing libraries as
236    // static libraries.
237    //
238    // If the crate hasn't been included yet and it's not actually required
239    // (e.g., it's a panic runtime) then we skip it here as well.
240    for &cnum in tcx.crates(()).iter() {
241        let src_flags = tcx.used_crate_source_flags(cnum);
242        if !src_flags.contains(CrateSourceFlags::DYLIB)
243            && !formats.contains_key(&cnum)
244            && tcx.crate_dep_kind(cnum) == CrateDepKind::Unconditional
245        {
246            if !src_flags.intersects(CrateSourceFlags::RLIB | CrateSourceFlags::RMETA) {
    ::core::panicking::panic("assertion failed: src_flags.intersects(CrateSourceFlags::RLIB | CrateSourceFlags::RMETA)")
};assert!(src_flags.intersects(CrateSourceFlags::RLIB | CrateSourceFlags::RMETA));
247            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/dependency_format.rs:247",
                        "rustc_metadata::dependency_format", ::tracing::Level::INFO,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/65ce8611fed3142053320be6996ef00e9992671f/compiler/rustc_metadata/src/dependency_format.rs"),
                        ::tracing_core::__macro_support::Option::Some(247u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_metadata::dependency_format"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::INFO <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::INFO <=
                    ::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!("adding staticlib: {0}",
                                                    tcx.crate_name(cnum)) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};info!("adding staticlib: {}", tcx.crate_name(cnum));
248            add_library(tcx, cnum, RequireStatic, &mut formats, &mut unavailable_as_static);
249            ret[cnum] = Linkage::Static;
250        }
251    }
252
253    // We've gotten this far because we're emitting some form of a final
254    // artifact which means that we may need to inject dependencies of some
255    // form.
256    //
257    // Things like panic runtimes may not have been activated quite yet, so do so here.
258    activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
259        tcx.is_panic_runtime(cnum)
260    });
261
262    // When dylib B links to dylib A, then when using B we must also link to A.
263    // It could be the case, however, that the rlib for A is present (hence we
264    // found metadata), but the dylib for A has since been removed.
265    //
266    // For situations like this, we perform one last pass over the dependencies,
267    // making sure that everything is available in the requested format.
268    for (cnum, kind) in ret.iter_enumerated() {
269        if cnum == LOCAL_CRATE {
270            continue;
271        }
272        let src_flags = tcx.used_crate_source_flags(cnum);
273        match *kind {
274            Linkage::NotLinked | Linkage::IncludedFromDylib => {}
275            Linkage::Static if src_flags.contains(CrateSourceFlags::RLIB) => continue,
276            Linkage::Dynamic
277                if src_flags
278                    .intersects(CrateSourceFlags::DYLIB | CrateSourceFlags::SDYLIB_INTERFACE) =>
279            {
280                continue;
281            }
282            kind => {
283                let kind = match kind {
284                    Linkage::Static => "rlib",
285                    _ => "dylib",
286                };
287                let crate_name = tcx.crate_name(cnum);
288                if crate_name.as_str().starts_with("rustc_") {
289                    sess.dcx().emit_err(RustcLibRequired { crate_name, kind });
290                } else {
291                    sess.dcx().emit_err(LibRequired { crate_name, kind });
292                }
293            }
294        }
295    }
296
297    ret
298}
299
300fn add_library(
301    tcx: TyCtxt<'_>,
302    cnum: CrateNum,
303    link: LinkagePreference,
304    m: &mut FxHashMap<CrateNum, LinkagePreference>,
305    unavailable_as_static: &mut Vec<CrateNum>,
306) {
307    match m.get(&cnum) {
308        Some(&link2) => {
309            // If the linkages differ, then we'd have two copies of the library
310            // if we continued linking. If the linkages are both static, then we
311            // would also have two copies of the library (static from two
312            // different locations).
313            //
314            // This error is probably a little obscure, but I imagine that it
315            // can be refined over time.
316            if link2 != link || link == RequireStatic {
317                let linking_to_rustc_driver = tcx.sess.unstable_features.is_nightly_build()
318                    && tcx.crates(()).iter().any(|&cnum| tcx.crate_name(cnum) == sym::rustc_driver);
319                tcx.dcx().emit_err(CrateDepMultiple {
320                    crate_name: tcx.crate_name(cnum),
321                    non_static_deps: unavailable_as_static
322                        .drain(..)
323                        .map(|cnum| NonStaticCrateDep { sub_crate_name: tcx.crate_name(cnum) })
324                        .collect(),
325                    rustc_driver_help: linking_to_rustc_driver,
326                });
327            }
328        }
329        None => {
330            m.insert(cnum, link);
331        }
332    }
333}
334
335fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec<CrateNum>) -> Option<DependencyList> {
336    let all_crates_available_as_rlib = tcx
337        .crates(())
338        .iter()
339        .copied()
340        .filter_map(|cnum| {
341            if tcx.crate_dep_kind(cnum).macros_only() {
342                return None;
343            }
344            let is_rlib = tcx.used_crate_source_flags(cnum).contains(CrateSourceFlags::RLIB);
345            if !is_rlib {
346                unavailable.push(cnum);
347            }
348            Some(is_rlib)
349        })
350        .all(|is_rlib| is_rlib);
351    if !all_crates_available_as_rlib {
352        return None;
353    }
354
355    // All crates are available in an rlib format, so we're just going to link
356    // everything in explicitly so long as it's actually required.
357    let mut ret = IndexVec::new();
358    {
    match (&ret.push(Linkage::Static), &LOCAL_CRATE) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(ret.push(Linkage::Static), LOCAL_CRATE);
359    for &cnum in tcx.crates(()) {
360        {
    match (&ret.push(match tcx.crate_dep_kind(cnum) {
                        CrateDepKind::Unconditional => Linkage::Static,
                        CrateDepKind::MacrosOnly | CrateDepKind::Conditional =>
                            Linkage::NotLinked,
                    }), &cnum) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(
361            ret.push(match tcx.crate_dep_kind(cnum) {
362                CrateDepKind::Unconditional => Linkage::Static,
363                CrateDepKind::MacrosOnly | CrateDepKind::Conditional => Linkage::NotLinked,
364            }),
365            cnum
366        );
367    }
368
369    // Our panic runtime may not have been linked above if it wasn't explicitly
370    // linked, which is the case for any injected dependency. Handle that here
371    // and activate it.
372    activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
373        tcx.is_panic_runtime(cnum)
374    });
375
376    Some(ret)
377}
378
379/// Given a list of how to link upstream dependencies so far, ensure that an
380/// injected dependency is activated. This will not do anything if one was
381/// transitively included already (e.g., via a dylib or explicitly so).
382///
383/// If an injected dependency was not found then we're guaranteed the
384/// metadata::creader module has injected that dependency (not listed as
385/// a required dependency) in one of the session's field. If this field is not
386/// set then this compilation doesn't actually need the dependency and we can
387/// also skip this step entirely.
388fn activate_injected_dep(
389    injected: Option<CrateNum>,
390    list: &mut DependencyList,
391    replaces_injected: &dyn Fn(CrateNum) -> bool,
392) {
393    for (cnum, slot) in list.iter_enumerated() {
394        if !replaces_injected(cnum) {
395            continue;
396        }
397        if *slot != Linkage::NotLinked {
398            return;
399        }
400    }
401    if let Some(injected) = injected {
402        {
    match (&list[injected], &Linkage::NotLinked) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(list[injected], Linkage::NotLinked);
403        list[injected] = Linkage::Static;
404    }
405}
406
407/// After the linkage for a crate has been determined we need to verify that
408/// there's only going to be one panic runtime in the output.
409fn verify_ok(tcx: TyCtxt<'_>, list: &DependencyList) {
410    let sess = &tcx.sess;
411    let list: Vec<_> = list
412        .iter_enumerated()
413        .filter_map(
414            |(cnum, linkage)| if *linkage == Linkage::NotLinked { None } else { Some(cnum) },
415        )
416        .collect();
417    if list.is_empty() {
418        return;
419    }
420    let desired_strategy = sess.panic_strategy();
421
422    // If we are panic=immediate-abort, make sure everything in the dependency tree has also been
423    // compiled with immediate-abort.
424    if list
425        .iter()
426        .any(|cnum| tcx.required_panic_strategy(*cnum) == Some(PanicStrategy::ImmediateAbort))
427    {
428        let mut invalid_crates = Vec::new();
429        for cnum in list.iter().copied() {
430            if tcx.required_panic_strategy(cnum) != Some(PanicStrategy::ImmediateAbort) {
431                invalid_crates.push(cnum);
432                // If core is incompatible, it's very likely that we'd emit an error for every
433                // sysroot crate, so instead of doing that emit a single fatal error that suggests
434                // using build-std.
435                if tcx.crate_name(cnum) == sym::core {
436                    sess.dcx().emit_fatal(IncompatibleWithImmediateAbortCore);
437                }
438            }
439        }
440        for cnum in invalid_crates {
441            sess.dcx()
442                .emit_err(IncompatibleWithImmediateAbort { crate_name: tcx.crate_name(cnum) });
443        }
444    }
445
446    let mut panic_runtime = None;
447    for cnum in list.iter().copied() {
448        if tcx.is_panic_runtime(cnum) {
449            if let Some((prev, _)) = panic_runtime {
450                let prev_name = tcx.crate_name(prev);
451                let cur_name = tcx.crate_name(cnum);
452                sess.dcx().emit_err(TwoPanicRuntimes { prev_name, cur_name });
453            }
454            panic_runtime = Some((
455                cnum,
456                tcx.required_panic_strategy(cnum).unwrap_or_else(|| {
457                    ::rustc_span::macros::bug_impl(None,
    format_args!("cannot determine panic strategy of a panic runtime"),
    Location::caller());bug!("cannot determine panic strategy of a panic runtime");
458                }),
459            ));
460        }
461    }
462
463    // If we found a panic runtime, then we know by this point that it's the
464    // only one, but we perform validation here that all the panic strategy
465    // compilation modes for the whole DAG are valid.
466    if let Some((runtime_cnum, found_strategy)) = panic_runtime {
467        // First up, validate that our selected panic runtime is indeed exactly
468        // our same strategy.
469        if found_strategy != desired_strategy {
470            sess.dcx().emit_err(BadPanicStrategy {
471                runtime: tcx.crate_name(runtime_cnum),
472                strategy: desired_strategy,
473            });
474        }
475
476        // Next up, verify that all other crates are compatible with this panic
477        // strategy. If the dep isn't linked, we ignore it, and if our strategy
478        // is abort then it's compatible with everything. Otherwise all crates'
479        // panic strategy must match our own.
480        for cnum in list.iter().copied() {
481            if cnum == runtime_cnum || tcx.is_compiler_builtins(cnum) {
482                continue;
483            }
484
485            if let Some(found_strategy) = tcx.required_panic_strategy(cnum)
486                && desired_strategy != found_strategy
487            {
488                sess.dcx().emit_err(RequiredPanicStrategy {
489                    crate_name: tcx.crate_name(cnum),
490                    found_strategy,
491                    desired_strategy,
492                });
493            }
494
495            // panic_in_drop_strategy isn't allowed for LOCAL_CRATE
496            if cnum != LOCAL_CRATE {
497                let found_drop_strategy = tcx.panic_in_drop_strategy(cnum);
498                if tcx.sess.opts.unstable_opts.panic_in_drop != found_drop_strategy {
499                    sess.dcx().emit_err(IncompatiblePanicInDropStrategy {
500                        crate_name: tcx.crate_name(cnum),
501                        found_strategy: found_drop_strategy,
502                        desired_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
503                    });
504                }
505            }
506        }
507    }
508}