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).
5354use rustc_data_structures::fx::{FxHashMap, FxHashSet};
55use rustc_hir::def_id::{CrateNum, LOCAL_CRATE};
56use rustc_index::IndexVec;
57use rustc_middle::bug;
58use rustc_middle::middle::dependency_format::{Dependencies, DependencyList, Linkage};
59use rustc_middle::ty::TyCtxt;
60use rustc_session::config::CrateType;
61use rustc_session::cstore::CrateDepKind;
62use rustc_session::cstore::LinkagePreference::{self, RequireDynamic, RequireStatic};
63use rustc_span::sym;
64use rustc_target::spec::PanicStrategy;
65use tracing::info;
6667use crate::creader::CStore;
68use crate::errors::{
69BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy,
70IncompatibleWithImmediateAbort, IncompatibleWithImmediateAbortCore, LibRequired,
71NonStaticCrateDep, RequiredPanicStrategy, RlibRequired, RustcDriverHelp, RustcLibRequired,
72TwoPanicRuntimes,
73};
7475pub(crate) fn calculate(tcx: TyCtxt<'_>) -> Dependencies {
76tcx.crate_types()
77 .iter()
78 .map(|&ty| {
79let linkage = calculate_type(tcx, ty);
80verify_ok(tcx, &linkage);
81 (ty, linkage)
82 })
83 .collect()
84}
8586fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
87let sess = &tcx.sess;
8889if !sess.opts.output_types.should_link() {
90return IndexVec::new();
91 }
9293let preferred_linkage =
94match ty {
95// Generating a dylib without `-C prefer-dynamic` means that we're going
96 // to try to eagerly statically link all dependencies. This is normally
97 // done for end-product dylibs, not intermediate products.
98 //
99 // Treat cdylibs and staticlibs similarly. If `-C prefer-dynamic` is set,
100 // the caller may be code-size conscious, but without it, it makes sense
101 // to statically link a cdylib or staticlib. For staticlibs we use
102 // `-Z staticlib-prefer-dynamic` for now. This may be merged into
103 // `-C prefer-dynamic` in the future.
104CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
105if sess.opts.cg.prefer_dynamic { Linkage::Dynamic } else { Linkage::Static }
106 }
107 CrateType::StaticLib => {
108if sess.opts.unstable_opts.staticlib_prefer_dynamic {
109 Linkage::Dynamic110 } else {
111 Linkage::Static112 }
113 }
114115// If the global prefer_dynamic switch is turned off, or the final
116 // executable will be statically linked, prefer static crate linkage.
117CrateType::Executableif !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => {
118 Linkage::Static119 }
120 CrateType::Executable => Linkage::Dynamic,
121122// proc-macro crates are mostly cdylibs, but we also need metadata.
123CrateType::ProcMacro => Linkage::Static,
124125// No linkage happens with rlibs, we just needed the metadata (which we
126 // got long ago), so don't bother with anything.
127CrateType::Rlib => Linkage::NotLinked,
128 };
129130let mut unavailable_as_static = Vec::new();
131132match preferred_linkage {
133// If the crate is not linked, there are no link-time dependencies.
134Linkage::NotLinked => return IndexVec::new(),
135 Linkage::Static => {
136// Attempt static linkage first. For dylibs and executables, we may be
137 // able to retry below with dynamic linkage.
138if let Some(v) = attempt_static(tcx, &mut unavailable_as_static) {
139return v;
140 }
141142// Static executables must have all static dependencies.
143 // If any are not found, generate some nice pretty errors.
144if (ty == CrateType::StaticLib && !sess.opts.unstable_opts.staticlib_allow_rdylib_deps)
145 || (ty == CrateType::Executable146 && sess.crt_static(Some(ty))
147 && !sess.target.crt_static_allows_dylibs)
148 {
149for &cnum in tcx.crates(()).iter() {
150if tcx.dep_kind(cnum).macros_only() {
151continue;
152 }
153let src = tcx.used_crate_source(cnum);
154if src.rlib.is_some() {
155continue;
156 }
157 sess.dcx().emit_err(RlibRequired { crate_name: tcx.crate_name(cnum) });
158 }
159return IndexVec::new();
160 }
161 }
162 Linkage::Dynamic | Linkage::IncludedFromDylib => {}
163 }
164165let all_dylibs = || {
166tcx.crates(()).iter().filter(|&&cnum| {
167 !tcx.dep_kind(cnum).macros_only()
168 && (tcx.used_crate_source(cnum).dylib.is_some()
169 || tcx.used_crate_source(cnum).sdylib_interface.is_some())
170 })
171 };
172173let mut upstream_in_dylibs = FxHashSet::default();
174175if tcx.features().rustc_private() {
176// We need this to prevent users of `rustc_driver` from linking dynamically to `std`
177 // which does not work as `std` is also statically linked into `rustc_driver`.
178179 // Find all libraries statically linked to upstream dylibs.
180for &cnum in all_dylibs() {
181let deps = tcx.dylib_dependency_formats(cnum);
182for &(depnum, style) in deps.iter() {
183if let RequireStatic = style {
184 upstream_in_dylibs.insert(depnum);
185 }
186 }
187 }
188 }
189190let mut formats = FxHashMap::default();
191192// Sweep all crates for found dylibs. Add all dylibs, as well as their
193 // dependencies, ensuring there are no conflicts. The only valid case for a
194 // dependency to be relied upon twice is for both cases to rely on a dylib.
195for &cnum in all_dylibs() {
196if upstream_in_dylibs.contains(&cnum) {
197{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/dependency_format.rs:197",
"rustc_metadata::dependency_format", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/dependency_format.rs"),
::tracing_core::__macro_support::Option::Some(197u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("skipping dylib: {0}",
tcx.crate_name(cnum)) as &dyn Value))])
});
} else { ; }
};info!("skipping dylib: {}", tcx.crate_name(cnum));
198// If this dylib is also available statically linked to another dylib
199 // we try to use that instead.
200continue;
201 }
202203let name = tcx.crate_name(cnum);
204{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/dependency_format.rs:204",
"rustc_metadata::dependency_format", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/dependency_format.rs"),
::tracing_core::__macro_support::Option::Some(204u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("adding dylib: {0}",
name) as &dyn Value))])
});
} else { ; }
};info!("adding dylib: {}", name);
205 add_library(tcx, cnum, RequireDynamic, &mut formats, &mut unavailable_as_static);
206let deps = tcx.dylib_dependency_formats(cnum);
207for &(depnum, style) in deps.iter() {
208{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/dependency_format.rs:208",
"rustc_metadata::dependency_format", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/dependency_format.rs"),
::tracing_core::__macro_support::Option::Some(208u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("adding {0:?}: {1}",
style, tcx.crate_name(depnum)) as &dyn Value))])
});
} else { ; }
};info!("adding {:?}: {}", style, tcx.crate_name(depnum));
209 add_library(tcx, depnum, style, &mut formats, &mut unavailable_as_static);
210 }
211 }
212213// Collect what we've got so far in the return vector.
214let last_crate = tcx.crates(()).len();
215let mut ret = IndexVec::new();
216217// We need to fill in something for LOCAL_CRATE as IndexVec is a dense map.
218 // Linkage::Static semantically the most correct thing to use as the local
219 // crate is always statically linked into the linker output, even when
220 // linking a dylib. Using Linkage::Static also allow avoiding special cases
221 // for LOCAL_CRATE in some places.
222match (&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);
223224for cnum in 1..last_crate + 1 {
225let cnum = CrateNum::new(cnum);
226match (&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!(
227 ret.push(match formats.get(&cnum) {
228Some(&RequireDynamic) => Linkage::Dynamic,
229Some(&RequireStatic) => Linkage::IncludedFromDylib,
230None => Linkage::NotLinked,
231 }),
232 cnum
233 );
234 }
235236// Run through the dependency list again, and add any missing libraries as
237 // static libraries.
238 //
239 // If the crate hasn't been included yet and it's not actually required
240 // (e.g., it's a panic runtime) then we skip it here as well.
241for &cnum in tcx.crates(()).iter() {
242let src = tcx.used_crate_source(cnum);
243if src.dylib.is_none()
244 && !formats.contains_key(&cnum)
245 && tcx.dep_kind(cnum) == CrateDepKind::Unconditional
246 {
247if !(src.rlib.is_some() || src.rmeta.is_some()) {
::core::panicking::panic("assertion failed: src.rlib.is_some() || src.rmeta.is_some()")
};assert!(src.rlib.is_some() || src.rmeta.is_some());
248{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event compiler/rustc_metadata/src/dependency_format.rs:248",
"rustc_metadata::dependency_format", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("compiler/rustc_metadata/src/dependency_format.rs"),
::tracing_core::__macro_support::Option::Some(248u32),
::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};
let mut iter = __CALLSITE.metadata().fields().iter();
__CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
::tracing::__macro_support::Option::Some(&format_args!("adding staticlib: {0}",
tcx.crate_name(cnum)) as &dyn Value))])
});
} else { ; }
};info!("adding staticlib: {}", tcx.crate_name(cnum));
249 add_library(tcx, cnum, RequireStatic, &mut formats, &mut unavailable_as_static);
250 ret[cnum] = Linkage::Static;
251 }
252 }
253254// We've gotten this far because we're emitting some form of a final
255 // artifact which means that we may need to inject dependencies of some
256 // form.
257 //
258 // Things like panic runtimes may not have been activated quite yet, so do so here.
259activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
260tcx.is_panic_runtime(cnum)
261 });
262263// When dylib B links to dylib A, then when using B we must also link to A.
264 // It could be the case, however, that the rlib for A is present (hence we
265 // found metadata), but the dylib for A has since been removed.
266 //
267 // For situations like this, we perform one last pass over the dependencies,
268 // making sure that everything is available in the requested format.
269for (cnum, kind) in ret.iter_enumerated() {
270if cnum == LOCAL_CRATE {
271continue;
272 }
273let src = tcx.used_crate_source(cnum);
274match *kind {
275 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
276 Linkage::Static if src.rlib.is_some() => continue,
277 Linkage::Dynamic if src.dylib.is_some() || src.sdylib_interface.is_some() => continue,
278 kind => {
279let kind = match kind {
280 Linkage::Static => "rlib",
281_ => "dylib",
282 };
283let crate_name = tcx.crate_name(cnum);
284if crate_name.as_str().starts_with("rustc_") {
285 sess.dcx().emit_err(RustcLibRequired { crate_name, kind });
286 } else {
287 sess.dcx().emit_err(LibRequired { crate_name, kind });
288 }
289 }
290 }
291 }
292293ret294}
295296fn add_library(
297 tcx: TyCtxt<'_>,
298 cnum: CrateNum,
299 link: LinkagePreference,
300 m: &mut FxHashMap<CrateNum, LinkagePreference>,
301 unavailable_as_static: &mut Vec<CrateNum>,
302) {
303match m.get(&cnum) {
304Some(&link2) => {
305// If the linkages differ, then we'd have two copies of the library
306 // if we continued linking. If the linkages are both static, then we
307 // would also have two copies of the library (static from two
308 // different locations).
309 //
310 // This error is probably a little obscure, but I imagine that it
311 // can be refined over time.
312if link2 != link || link == RequireStatic {
313let linking_to_rustc_driver = tcx.sess.psess.unstable_features.is_nightly_build()
314 && tcx.crates(()).iter().any(|&cnum| tcx.crate_name(cnum) == sym::rustc_driver);
315tcx.dcx().emit_err(CrateDepMultiple {
316 crate_name: tcx.crate_name(cnum),
317 non_static_deps: unavailable_as_static318 .drain(..)
319 .map(|cnum| NonStaticCrateDep { crate_name_: tcx.crate_name(cnum) })
320 .collect(),
321 rustc_driver_help: linking_to_rustc_driver.then_some(RustcDriverHelp),
322 });
323 }
324 }
325None => {
326m.insert(cnum, link);
327 }
328 }
329}
330331fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec<CrateNum>) -> Option<DependencyList> {
332let all_crates_available_as_rlib = tcx333 .crates(())
334 .iter()
335 .copied()
336 .filter_map(|cnum| {
337if tcx.dep_kind(cnum).macros_only() {
338return None;
339 }
340let is_rlib = tcx.used_crate_source(cnum).rlib.is_some();
341if !is_rlib {
342unavailable.push(cnum);
343 }
344Some(is_rlib)
345 })
346 .all(|is_rlib| is_rlib);
347if !all_crates_available_as_rlib {
348return None;
349 }
350351// All crates are available in an rlib format, so we're just going to link
352 // everything in explicitly so long as it's actually required.
353let mut ret = IndexVec::new();
354match (&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);
355for &cnum in tcx.crates(()) {
356match (&ret.push(match tcx.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!(
357 ret.push(match tcx.dep_kind(cnum) {
358 CrateDepKind::Unconditional => Linkage::Static,
359 CrateDepKind::MacrosOnly | CrateDepKind::Conditional => Linkage::NotLinked,
360 }),
361 cnum
362 );
363 }
364365// Our panic runtime may not have been linked above if it wasn't explicitly
366 // linked, which is the case for any injected dependency. Handle that here
367 // and activate it.
368activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
369tcx.is_panic_runtime(cnum)
370 });
371372Some(ret)
373}
374375/// Given a list of how to link upstream dependencies so far, ensure that an
376/// injected dependency is activated. This will not do anything if one was
377/// transitively included already (e.g., via a dylib or explicitly so).
378///
379/// If an injected dependency was not found then we're guaranteed the
380/// metadata::creader module has injected that dependency (not listed as
381/// a required dependency) in one of the session's field. If this field is not
382/// set then this compilation doesn't actually need the dependency and we can
383/// also skip this step entirely.
384fn activate_injected_dep(
385 injected: Option<CrateNum>,
386 list: &mut DependencyList,
387 replaces_injected: &dyn Fn(CrateNum) -> bool,
388) {
389for (cnum, slot) in list.iter_enumerated() {
390if !replaces_injected(cnum) {
391continue;
392 }
393if *slot != Linkage::NotLinked {
394return;
395 }
396 }
397if let Some(injected) = injected {
398match (&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);
399list[injected] = Linkage::Static;
400 }
401}
402403/// After the linkage for a crate has been determined we need to verify that
404/// there's only going to be one panic runtime in the output.
405fn verify_ok(tcx: TyCtxt<'_>, list: &DependencyList) {
406let sess = &tcx.sess;
407let list: Vec<_> = list408 .iter_enumerated()
409 .filter_map(
410 |(cnum, linkage)| if *linkage == Linkage::NotLinked { None } else { Some(cnum) },
411 )
412 .collect();
413if list.is_empty() {
414return;
415 }
416let desired_strategy = sess.panic_strategy();
417418// If we are panic=immediate-abort, make sure everything in the dependency tree has also been
419 // compiled with immediate-abort.
420if list421 .iter()
422 .any(|cnum| tcx.required_panic_strategy(*cnum) == Some(PanicStrategy::ImmediateAbort))
423 {
424let mut invalid_crates = Vec::new();
425for cnum in list.iter().copied() {
426if tcx.required_panic_strategy(cnum) != Some(PanicStrategy::ImmediateAbort) {
427 invalid_crates.push(cnum);
428// If core is incompatible, it's very likely that we'd emit an error for every
429 // sysroot crate, so instead of doing that emit a single fatal error that suggests
430 // using build-std.
431if tcx.crate_name(cnum) == sym::core {
432 sess.dcx().emit_fatal(IncompatibleWithImmediateAbortCore);
433 }
434 }
435 }
436for cnum in invalid_crates {
437 sess.dcx()
438 .emit_err(IncompatibleWithImmediateAbort { crate_name: tcx.crate_name(cnum) });
439 }
440 }
441442let mut panic_runtime = None;
443for cnum in list.iter().copied() {
444if tcx.is_panic_runtime(cnum) {
445if let Some((prev, _)) = panic_runtime {
446let prev_name = tcx.crate_name(prev);
447let cur_name = tcx.crate_name(cnum);
448 sess.dcx().emit_err(TwoPanicRuntimes { prev_name, cur_name });
449 }
450 panic_runtime = Some((
451 cnum,
452 tcx.required_panic_strategy(cnum).unwrap_or_else(|| {
453::rustc_middle::util::bug::bug_fmt(format_args!("cannot determine panic strategy of a panic runtime"));bug!("cannot determine panic strategy of a panic runtime");
454 }),
455 ));
456 }
457 }
458459// If we found a panic runtime, then we know by this point that it's the
460 // only one, but we perform validation here that all the panic strategy
461 // compilation modes for the whole DAG are valid.
462if let Some((runtime_cnum, found_strategy)) = panic_runtime {
463// First up, validate that our selected panic runtime is indeed exactly
464 // our same strategy.
465if found_strategy != desired_strategy {
466sess.dcx().emit_err(BadPanicStrategy {
467 runtime: tcx.crate_name(runtime_cnum),
468 strategy: desired_strategy,
469 });
470 }
471472// Next up, verify that all other crates are compatible with this panic
473 // strategy. If the dep isn't linked, we ignore it, and if our strategy
474 // is abort then it's compatible with everything. Otherwise all crates'
475 // panic strategy must match our own.
476for cnum in list.iter().copied() {
477if cnum == runtime_cnum || tcx.is_compiler_builtins(cnum) {
478continue;
479 }
480481if let Some(found_strategy) = tcx.required_panic_strategy(cnum)
482 && desired_strategy != found_strategy
483 {
484 sess.dcx().emit_err(RequiredPanicStrategy {
485 crate_name: tcx.crate_name(cnum),
486 found_strategy,
487 desired_strategy,
488 });
489 }
490491// panic_in_drop_strategy isn't allowed for LOCAL_CRATE
492if cnum != LOCAL_CRATE {
493let found_drop_strategy = tcx.panic_in_drop_strategy(cnum);
494if tcx.sess.opts.unstable_opts.panic_in_drop != found_drop_strategy {
495 sess.dcx().emit_err(IncompatiblePanicInDropStrategy {
496 crate_name: tcx.crate_name(cnum),
497 found_strategy: found_drop_strategy,
498 desired_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
499 });
500 }
501 }
502 }
503 }
504}