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, RustcLibRequired, TwoPanicRuntimes,
72};
7374pub(crate) fn calculate(tcx: TyCtxt<'_>) -> Dependencies {
75tcx.crate_types()
76 .iter()
77 .map(|&ty| {
78let linkage = calculate_type(tcx, ty);
79verify_ok(tcx, &linkage);
80 (ty, linkage)
81 })
82 .collect()
83}
8485fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
86let sess = &tcx.sess;
8788if !sess.opts.output_types.should_link() {
89return IndexVec::new();
90 }
9192let preferred_linkage =
93match ty {
94// Generating a dylib without `-C prefer-dynamic` means that we're going
95 // to try to eagerly statically link all dependencies. This is normally
96 // done for end-product dylibs, not intermediate products.
97 //
98 // Treat cdylibs and staticlibs similarly. If `-C prefer-dynamic` is set,
99 // the caller may be code-size conscious, but without it, it makes sense
100 // to statically link a cdylib or staticlib. For staticlibs we use
101 // `-Z staticlib-prefer-dynamic` for now. This may be merged into
102 // `-C prefer-dynamic` in the future.
103CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
104if sess.opts.cg.prefer_dynamic { Linkage::Dynamic } else { Linkage::Static }
105 }
106 CrateType::StaticLib => {
107if sess.opts.unstable_opts.staticlib_prefer_dynamic {
108 Linkage::Dynamic109 } else {
110 Linkage::Static111 }
112 }
113114// If the global prefer_dynamic switch is turned off, or the final
115 // executable will be statically linked, prefer static crate linkage.
116CrateType::Executableif !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => {
117 Linkage::Static118 }
119 CrateType::Executable => Linkage::Dynamic,
120121// proc-macro crates are mostly cdylibs, but we also need metadata.
122CrateType::ProcMacro => Linkage::Static,
123124// No linkage happens with rlibs, we just needed the metadata (which we
125 // got long ago), so don't bother with anything.
126CrateType::Rlib => Linkage::NotLinked,
127 };
128129let mut unavailable_as_static = Vec::new();
130131match preferred_linkage {
132// If the crate is not linked, there are no link-time dependencies.
133Linkage::NotLinked => return IndexVec::new(),
134 Linkage::Static => {
135// Attempt static linkage first. For dylibs and executables, we may be
136 // able to retry below with dynamic linkage.
137if let Some(v) = attempt_static(tcx, &mut unavailable_as_static) {
138return v;
139 }
140141// Static executables must have all static dependencies.
142 // If any are not found, generate some nice pretty errors.
143if (ty == CrateType::StaticLib && !sess.opts.unstable_opts.staticlib_allow_rdylib_deps)
144 || (ty == CrateType::Executable145 && sess.crt_static(Some(ty))
146 && !sess.target.crt_static_allows_dylibs)
147 {
148for &cnum in tcx.crates(()).iter() {
149if tcx.dep_kind(cnum).macros_only() {
150continue;
151 }
152let src = tcx.used_crate_source(cnum);
153if src.rlib.is_some() {
154continue;
155 }
156 sess.dcx().emit_err(RlibRequired { crate_name: tcx.crate_name(cnum) });
157 }
158return IndexVec::new();
159 }
160 }
161 Linkage::Dynamic | Linkage::IncludedFromDylib => {}
162 }
163164let all_dylibs = || {
165tcx.crates(()).iter().filter(|&&cnum| {
166 !tcx.dep_kind(cnum).macros_only()
167 && (tcx.used_crate_source(cnum).dylib.is_some()
168 || tcx.used_crate_source(cnum).sdylib_interface.is_some())
169 })
170 };
171172let mut upstream_in_dylibs = FxHashSet::default();
173174if 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`.
177178 // Find all libraries statically linked to upstream dylibs.
179for &cnum in all_dylibs() {
180let deps = tcx.dylib_dependency_formats(cnum);
181for &(depnum, style) in deps.iter() {
182if let RequireStatic = style {
183 upstream_in_dylibs.insert(depnum);
184 }
185 }
186 }
187 }
188189let mut formats = FxHashMap::default();
190191// 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.
194for &cnum in all_dylibs() {
195if 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 compiler/rustc_metadata/src/dependency_format.rs:196",
"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(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};
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));
197// If this dylib is also available statically linked to another dylib
198 // we try to use that instead.
199continue;
200 }
201202let 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 compiler/rustc_metadata/src/dependency_format.rs:203",
"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(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};
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);
204 add_library(tcx, cnum, RequireDynamic, &mut formats, &mut unavailable_as_static);
205let deps = tcx.dylib_dependency_formats(cnum);
206for &(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 compiler/rustc_metadata/src/dependency_format.rs:207",
"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(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};
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));
208 add_library(tcx, depnum, style, &mut formats, &mut unavailable_as_static);
209 }
210 }
211212// Collect what we've got so far in the return vector.
213let last_crate = tcx.crates(()).len();
214let mut ret = IndexVec::new();
215216// 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.
221match (&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);
222223for cnum in 1..last_crate + 1 {
224let cnum = CrateNum::new(cnum);
225match (&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) {
227Some(&RequireDynamic) => Linkage::Dynamic,
228Some(&RequireStatic) => Linkage::IncludedFromDylib,
229None => Linkage::NotLinked,
230 }),
231 cnum
232 );
233 }
234235// 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.
240for &cnum in tcx.crates(()).iter() {
241let src = tcx.used_crate_source(cnum);
242if src.dylib.is_none()
243 && !formats.contains_key(&cnum)
244 && tcx.dep_kind(cnum) == CrateDepKind::Unconditional
245 {
246if !(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());
247{
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:247",
"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(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};
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));
248 add_library(tcx, cnum, RequireStatic, &mut formats, &mut unavailable_as_static);
249 ret[cnum] = Linkage::Static;
250 }
251 }
252253// 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.
258activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
259tcx.is_panic_runtime(cnum)
260 });
261262// 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.
268for (cnum, kind) in ret.iter_enumerated() {
269if cnum == LOCAL_CRATE {
270continue;
271 }
272let src = tcx.used_crate_source(cnum);
273match *kind {
274 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
275 Linkage::Static if src.rlib.is_some() => continue,
276 Linkage::Dynamic if src.dylib.is_some() || src.sdylib_interface.is_some() => continue,
277 kind => {
278let kind = match kind {
279 Linkage::Static => "rlib",
280_ => "dylib",
281 };
282let crate_name = tcx.crate_name(cnum);
283if crate_name.as_str().starts_with("rustc_") {
284 sess.dcx().emit_err(RustcLibRequired { crate_name, kind });
285 } else {
286 sess.dcx().emit_err(LibRequired { crate_name, kind });
287 }
288 }
289 }
290 }
291292ret293}
294295fn add_library(
296 tcx: TyCtxt<'_>,
297 cnum: CrateNum,
298 link: LinkagePreference,
299 m: &mut FxHashMap<CrateNum, LinkagePreference>,
300 unavailable_as_static: &mut Vec<CrateNum>,
301) {
302match m.get(&cnum) {
303Some(&link2) => {
304// If the linkages differ, then we'd have two copies of the library
305 // if we continued linking. If the linkages are both static, then we
306 // would also have two copies of the library (static from two
307 // different locations).
308 //
309 // This error is probably a little obscure, but I imagine that it
310 // can be refined over time.
311if link2 != link || link == RequireStatic {
312let linking_to_rustc_driver = tcx.sess.psess.unstable_features.is_nightly_build()
313 && tcx.crates(()).iter().any(|&cnum| tcx.crate_name(cnum) == sym::rustc_driver);
314tcx.dcx().emit_err(CrateDepMultiple {
315 crate_name: tcx.crate_name(cnum),
316 non_static_deps: unavailable_as_static317 .drain(..)
318 .map(|cnum| NonStaticCrateDep { crate_name_: tcx.crate_name(cnum) })
319 .collect(),
320 rustc_driver_help: linking_to_rustc_driver,
321 });
322 }
323 }
324None => {
325m.insert(cnum, link);
326 }
327 }
328}
329330fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec<CrateNum>) -> Option<DependencyList> {
331let all_crates_available_as_rlib = tcx332 .crates(())
333 .iter()
334 .copied()
335 .filter_map(|cnum| {
336if tcx.dep_kind(cnum).macros_only() {
337return None;
338 }
339let is_rlib = tcx.used_crate_source(cnum).rlib.is_some();
340if !is_rlib {
341unavailable.push(cnum);
342 }
343Some(is_rlib)
344 })
345 .all(|is_rlib| is_rlib);
346if !all_crates_available_as_rlib {
347return None;
348 }
349350// All crates are available in an rlib format, so we're just going to link
351 // everything in explicitly so long as it's actually required.
352let mut ret = IndexVec::new();
353match (&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);
354for &cnum in tcx.crates(()) {
355match (&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!(
356 ret.push(match tcx.dep_kind(cnum) {
357 CrateDepKind::Unconditional => Linkage::Static,
358 CrateDepKind::MacrosOnly | CrateDepKind::Conditional => Linkage::NotLinked,
359 }),
360 cnum
361 );
362 }
363364// Our panic runtime may not have been linked above if it wasn't explicitly
365 // linked, which is the case for any injected dependency. Handle that here
366 // and activate it.
367activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
368tcx.is_panic_runtime(cnum)
369 });
370371Some(ret)
372}
373374/// Given a list of how to link upstream dependencies so far, ensure that an
375/// injected dependency is activated. This will not do anything if one was
376/// transitively included already (e.g., via a dylib or explicitly so).
377///
378/// If an injected dependency was not found then we're guaranteed the
379/// metadata::creader module has injected that dependency (not listed as
380/// a required dependency) in one of the session's field. If this field is not
381/// set then this compilation doesn't actually need the dependency and we can
382/// also skip this step entirely.
383fn activate_injected_dep(
384 injected: Option<CrateNum>,
385 list: &mut DependencyList,
386 replaces_injected: &dyn Fn(CrateNum) -> bool,
387) {
388for (cnum, slot) in list.iter_enumerated() {
389if !replaces_injected(cnum) {
390continue;
391 }
392if *slot != Linkage::NotLinked {
393return;
394 }
395 }
396if let Some(injected) = injected {
397match (&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);
398list[injected] = Linkage::Static;
399 }
400}
401402/// After the linkage for a crate has been determined we need to verify that
403/// there's only going to be one panic runtime in the output.
404fn verify_ok(tcx: TyCtxt<'_>, list: &DependencyList) {
405let sess = &tcx.sess;
406let list: Vec<_> = list407 .iter_enumerated()
408 .filter_map(
409 |(cnum, linkage)| if *linkage == Linkage::NotLinked { None } else { Some(cnum) },
410 )
411 .collect();
412if list.is_empty() {
413return;
414 }
415let desired_strategy = sess.panic_strategy();
416417// If we are panic=immediate-abort, make sure everything in the dependency tree has also been
418 // compiled with immediate-abort.
419if list420 .iter()
421 .any(|cnum| tcx.required_panic_strategy(*cnum) == Some(PanicStrategy::ImmediateAbort))
422 {
423let mut invalid_crates = Vec::new();
424for cnum in list.iter().copied() {
425if tcx.required_panic_strategy(cnum) != Some(PanicStrategy::ImmediateAbort) {
426 invalid_crates.push(cnum);
427// If core is incompatible, it's very likely that we'd emit an error for every
428 // sysroot crate, so instead of doing that emit a single fatal error that suggests
429 // using build-std.
430if tcx.crate_name(cnum) == sym::core {
431 sess.dcx().emit_fatal(IncompatibleWithImmediateAbortCore);
432 }
433 }
434 }
435for cnum in invalid_crates {
436 sess.dcx()
437 .emit_err(IncompatibleWithImmediateAbort { crate_name: tcx.crate_name(cnum) });
438 }
439 }
440441let mut panic_runtime = None;
442for cnum in list.iter().copied() {
443if tcx.is_panic_runtime(cnum) {
444if let Some((prev, _)) = panic_runtime {
445let prev_name = tcx.crate_name(prev);
446let cur_name = tcx.crate_name(cnum);
447 sess.dcx().emit_err(TwoPanicRuntimes { prev_name, cur_name });
448 }
449 panic_runtime = Some((
450 cnum,
451 tcx.required_panic_strategy(cnum).unwrap_or_else(|| {
452::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");
453 }),
454 ));
455 }
456 }
457458// If we found a panic runtime, then we know by this point that it's the
459 // only one, but we perform validation here that all the panic strategy
460 // compilation modes for the whole DAG are valid.
461if let Some((runtime_cnum, found_strategy)) = panic_runtime {
462// First up, validate that our selected panic runtime is indeed exactly
463 // our same strategy.
464if found_strategy != desired_strategy {
465sess.dcx().emit_err(BadPanicStrategy {
466 runtime: tcx.crate_name(runtime_cnum),
467 strategy: desired_strategy,
468 });
469 }
470471// Next up, verify that all other crates are compatible with this panic
472 // strategy. If the dep isn't linked, we ignore it, and if our strategy
473 // is abort then it's compatible with everything. Otherwise all crates'
474 // panic strategy must match our own.
475for cnum in list.iter().copied() {
476if cnum == runtime_cnum || tcx.is_compiler_builtins(cnum) {
477continue;
478 }
479480if let Some(found_strategy) = tcx.required_panic_strategy(cnum)
481 && desired_strategy != found_strategy
482 {
483 sess.dcx().emit_err(RequiredPanicStrategy {
484 crate_name: tcx.crate_name(cnum),
485 found_strategy,
486 desired_strategy,
487 });
488 }
489490// panic_in_drop_strategy isn't allowed for LOCAL_CRATE
491if cnum != LOCAL_CRATE {
492let found_drop_strategy = tcx.panic_in_drop_strategy(cnum);
493if tcx.sess.opts.unstable_opts.panic_in_drop != found_drop_strategy {
494 sess.dcx().emit_err(IncompatiblePanicInDropStrategy {
495 crate_name: tcx.crate_name(cnum),
496 found_strategy: found_drop_strategy,
497 desired_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
498 });
499 }
500 }
501 }
502 }
503}