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_crate_store::CrateDepKind;
55use rustc_crate_store::LinkagePreference::{self, RequireDynamic, RequireStatic};
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;
6566use crate::creader::CStore;
67use crate::diagnostics::{
68BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy,
69IncompatibleWithImmediateAbort, IncompatibleWithImmediateAbortCore, LibRequired,
70NonStaticCrateDep, RequiredPanicStrategy, RlibRequired, RustcLibRequired, TwoPanicRuntimes,
71};
7273pub(crate) fn calculate(tcx: TyCtxt<'_>) -> Dependencies {
74tcx.crate_types()
75 .iter()
76 .map(|&ty| {
77let linkage = calculate_type(tcx, ty);
78verify_ok(tcx, &linkage);
79 (ty, linkage)
80 })
81 .collect()
82}
8384fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
85let sess = &tcx.sess;
8687if !sess.opts.output_types.should_link() {
88return IndexVec::new();
89 }
9091let preferred_linkage =
92match 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.
102CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
103if sess.opts.cg.prefer_dynamic { Linkage::Dynamic } else { Linkage::Static }
104 }
105 CrateType::StaticLib => {
106if sess.opts.unstable_opts.staticlib_prefer_dynamic {
107 Linkage::Dynamic108 } else {
109 Linkage::Static110 }
111 }
112113// If the global prefer_dynamic switch is turned off, or the final
114 // executable will be statically linked, prefer static crate linkage.
115CrateType::Executableif !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => {
116 Linkage::Static117 }
118 CrateType::Executable => Linkage::Dynamic,
119120// proc-macro crates are mostly cdylibs, but we also need metadata.
121CrateType::ProcMacro => Linkage::Static,
122123// No linkage happens with rlibs, we just needed the metadata (which we
124 // got long ago), so don't bother with anything.
125CrateType::Rlib => Linkage::NotLinked,
126 };
127128let mut unavailable_as_static = Vec::new();
129130match preferred_linkage {
131// If the crate is not linked, there are no link-time dependencies.
132Linkage::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.
136if let Some(v) = attempt_static(tcx, &mut unavailable_as_static) {
137return v;
138 }
139140// Static executables must have all static dependencies.
141 // If any are not found, generate some nice pretty errors.
142if (ty == CrateType::StaticLib && !sess.opts.unstable_opts.staticlib_allow_rdylib_deps)
143 || (ty == CrateType::Executable144 && sess.crt_static(Some(ty))
145 && !sess.target.crt_static_allows_dylibs)
146 {
147for &cnum in tcx.crates(()).iter() {
148if tcx.crate_dep_kind(cnum).macros_only() {
149continue;
150 }
151let src = tcx.used_crate_source(cnum);
152if src.rlib.is_some() {
153continue;
154 }
155 sess.dcx().emit_err(RlibRequired { crate_name: tcx.crate_name(cnum) });
156 }
157return IndexVec::new();
158 }
159 }
160 Linkage::Dynamic | Linkage::IncludedFromDylib => {}
161 }
162163let all_dylibs = || {
164tcx.crates(()).iter().filter(|&&cnum| {
165 !tcx.crate_dep_kind(cnum).macros_only()
166 && (tcx.used_crate_source(cnum).dylib.is_some()
167 || tcx.used_crate_source(cnum).sdylib_interface.is_some())
168 })
169 };
170171let mut upstream_in_dylibs = FxHashSet::default();
172173if tcx.features().rustc_private() {
174// We need this to prevent users of `rustc_driver` from linking dynamically to `std`
175 // which does not work as `std` is also statically linked into `rustc_driver`.
176177 // Find all libraries statically linked to upstream dylibs.
178for &cnum in all_dylibs() {
179let deps = tcx.dylib_dependency_formats(cnum);
180for &(depnum, style) in deps.iter() {
181if let RequireStatic = style {
182 upstream_in_dylibs.insert(depnum);
183 }
184 }
185 }
186 }
187188let mut formats = FxHashMap::default();
189190// Sweep all crates for found dylibs. Add all dylibs, as well as their
191 // dependencies, ensuring there are no conflicts. The only valid case for a
192 // dependency to be relied upon twice is for both cases to rely on a dylib.
193for &cnum in all_dylibs() {
194if upstream_in_dylibs.contains(&cnum) {
195{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/dependency_format.rs:195",
"rustc_metadata::dependency_format", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/dependency_format.rs"),
::tracing_core::__macro_support::Option::Some(195u32),
::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));
196// If this dylib is also available statically linked to another dylib
197 // we try to use that instead.
198continue;
199 }
200201let name = tcx.crate_name(cnum);
202{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/dependency_format.rs:202",
"rustc_metadata::dependency_format", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/dependency_format.rs"),
::tracing_core::__macro_support::Option::Some(202u32),
::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);
203 add_library(tcx, cnum, RequireDynamic, &mut formats, &mut unavailable_as_static);
204let deps = tcx.dylib_dependency_formats(cnum);
205for &(depnum, style) in deps.iter() {
206{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/dependency_format.rs:206",
"rustc_metadata::dependency_format", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/dependency_format.rs"),
::tracing_core::__macro_support::Option::Some(206u32),
::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));
207 add_library(tcx, depnum, style, &mut formats, &mut unavailable_as_static);
208 }
209 }
210211// Collect what we've got so far in the return vector.
212let last_crate = tcx.crates(()).len();
213let mut ret = IndexVec::new();
214215// We need to fill in something for LOCAL_CRATE as IndexVec is a dense map.
216 // Linkage::Static semantically the most correct thing to use as the local
217 // crate is always statically linked into the linker output, even when
218 // linking a dylib. Using Linkage::Static also allow avoiding special cases
219 // for LOCAL_CRATE in some places.
220{
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);
221222for cnum in 1..last_crate + 1 {
223let cnum = CrateNum::new(cnum);
224{
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!(
225 ret.push(match formats.get(&cnum) {
226Some(&RequireDynamic) => Linkage::Dynamic,
227Some(&RequireStatic) => Linkage::IncludedFromDylib,
228None => Linkage::NotLinked,
229 }),
230 cnum
231 );
232 }
233234// Run through the dependency list again, and add any missing libraries as
235 // static libraries.
236 //
237 // If the crate hasn't been included yet and it's not actually required
238 // (e.g., it's a panic runtime) then we skip it here as well.
239for &cnum in tcx.crates(()).iter() {
240let src = tcx.used_crate_source(cnum);
241if src.dylib.is_none()
242 && !formats.contains_key(&cnum)
243 && tcx.crate_dep_kind(cnum) == CrateDepKind::Unconditional
244 {
245if !(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());
246{
use ::tracing::__macro_support::Callsite as _;
static __CALLSITE: ::tracing::callsite::DefaultCallsite =
{
static META: ::tracing::Metadata<'static> =
{
::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/dependency_format.rs:246",
"rustc_metadata::dependency_format", ::tracing::Level::INFO,
::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_metadata/src/dependency_format.rs"),
::tracing_core::__macro_support::Option::Some(246u32),
::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));
247 add_library(tcx, cnum, RequireStatic, &mut formats, &mut unavailable_as_static);
248 ret[cnum] = Linkage::Static;
249 }
250 }
251252// We've gotten this far because we're emitting some form of a final
253 // artifact which means that we may need to inject dependencies of some
254 // form.
255 //
256 // Things like panic runtimes may not have been activated quite yet, so do so here.
257activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
258tcx.is_panic_runtime(cnum)
259 });
260261// When dylib B links to dylib A, then when using B we must also link to A.
262 // It could be the case, however, that the rlib for A is present (hence we
263 // found metadata), but the dylib for A has since been removed.
264 //
265 // For situations like this, we perform one last pass over the dependencies,
266 // making sure that everything is available in the requested format.
267for (cnum, kind) in ret.iter_enumerated() {
268if cnum == LOCAL_CRATE {
269continue;
270 }
271let src = tcx.used_crate_source(cnum);
272match *kind {
273 Linkage::NotLinked | Linkage::IncludedFromDylib => {}
274 Linkage::Static if src.rlib.is_some() => continue,
275 Linkage::Dynamic if src.dylib.is_some() || src.sdylib_interface.is_some() => continue,
276 kind => {
277let kind = match kind {
278 Linkage::Static => "rlib",
279_ => "dylib",
280 };
281let crate_name = tcx.crate_name(cnum);
282if crate_name.as_str().starts_with("rustc_") {
283 sess.dcx().emit_err(RustcLibRequired { crate_name, kind });
284 } else {
285 sess.dcx().emit_err(LibRequired { crate_name, kind });
286 }
287 }
288 }
289 }
290291ret292}
293294fn add_library(
295 tcx: TyCtxt<'_>,
296 cnum: CrateNum,
297 link: LinkagePreference,
298 m: &mut FxHashMap<CrateNum, LinkagePreference>,
299 unavailable_as_static: &mut Vec<CrateNum>,
300) {
301match m.get(&cnum) {
302Some(&link2) => {
303// If the linkages differ, then we'd have two copies of the library
304 // if we continued linking. If the linkages are both static, then we
305 // would also have two copies of the library (static from two
306 // different locations).
307 //
308 // This error is probably a little obscure, but I imagine that it
309 // can be refined over time.
310if link2 != link || link == RequireStatic {
311let linking_to_rustc_driver = tcx.sess.unstable_features.is_nightly_build()
312 && tcx.crates(()).iter().any(|&cnum| tcx.crate_name(cnum) == sym::rustc_driver);
313tcx.dcx().emit_err(CrateDepMultiple {
314 crate_name: tcx.crate_name(cnum),
315 non_static_deps: unavailable_as_static316 .drain(..)
317 .map(|cnum| NonStaticCrateDep { sub_crate_name: tcx.crate_name(cnum) })
318 .collect(),
319 rustc_driver_help: linking_to_rustc_driver,
320 });
321 }
322 }
323None => {
324m.insert(cnum, link);
325 }
326 }
327}
328329fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec<CrateNum>) -> Option<DependencyList> {
330let all_crates_available_as_rlib = tcx331 .crates(())
332 .iter()
333 .copied()
334 .filter_map(|cnum| {
335if tcx.crate_dep_kind(cnum).macros_only() {
336return None;
337 }
338let is_rlib = tcx.used_crate_source(cnum).rlib.is_some();
339if !is_rlib {
340unavailable.push(cnum);
341 }
342Some(is_rlib)
343 })
344 .all(|is_rlib| is_rlib);
345if !all_crates_available_as_rlib {
346return None;
347 }
348349// All crates are available in an rlib format, so we're just going to link
350 // everything in explicitly so long as it's actually required.
351let mut ret = IndexVec::new();
352{
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);
353for &cnum in tcx.crates(()) {
354{
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!(
355 ret.push(match tcx.crate_dep_kind(cnum) {
356 CrateDepKind::Unconditional => Linkage::Static,
357 CrateDepKind::MacrosOnly | CrateDepKind::Conditional => Linkage::NotLinked,
358 }),
359 cnum
360 );
361 }
362363// Our panic runtime may not have been linked above if it wasn't explicitly
364 // linked, which is the case for any injected dependency. Handle that here
365 // and activate it.
366activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
367tcx.is_panic_runtime(cnum)
368 });
369370Some(ret)
371}
372373/// Given a list of how to link upstream dependencies so far, ensure that an
374/// injected dependency is activated. This will not do anything if one was
375/// transitively included already (e.g., via a dylib or explicitly so).
376///
377/// If an injected dependency was not found then we're guaranteed the
378/// metadata::creader module has injected that dependency (not listed as
379/// a required dependency) in one of the session's field. If this field is not
380/// set then this compilation doesn't actually need the dependency and we can
381/// also skip this step entirely.
382fn activate_injected_dep(
383 injected: Option<CrateNum>,
384 list: &mut DependencyList,
385 replaces_injected: &dyn Fn(CrateNum) -> bool,
386) {
387for (cnum, slot) in list.iter_enumerated() {
388if !replaces_injected(cnum) {
389continue;
390 }
391if *slot != Linkage::NotLinked {
392return;
393 }
394 }
395if let Some(injected) = injected {
396{
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);
397list[injected] = Linkage::Static;
398 }
399}
400401/// After the linkage for a crate has been determined we need to verify that
402/// there's only going to be one panic runtime in the output.
403fn verify_ok(tcx: TyCtxt<'_>, list: &DependencyList) {
404let sess = &tcx.sess;
405let list: Vec<_> = list406 .iter_enumerated()
407 .filter_map(
408 |(cnum, linkage)| if *linkage == Linkage::NotLinked { None } else { Some(cnum) },
409 )
410 .collect();
411if list.is_empty() {
412return;
413 }
414let desired_strategy = sess.panic_strategy();
415416// If we are panic=immediate-abort, make sure everything in the dependency tree has also been
417 // compiled with immediate-abort.
418if list419 .iter()
420 .any(|cnum| tcx.required_panic_strategy(*cnum) == Some(PanicStrategy::ImmediateAbort))
421 {
422let mut invalid_crates = Vec::new();
423for cnum in list.iter().copied() {
424if tcx.required_panic_strategy(cnum) != Some(PanicStrategy::ImmediateAbort) {
425 invalid_crates.push(cnum);
426// If core is incompatible, it's very likely that we'd emit an error for every
427 // sysroot crate, so instead of doing that emit a single fatal error that suggests
428 // using build-std.
429if tcx.crate_name(cnum) == sym::core {
430 sess.dcx().emit_fatal(IncompatibleWithImmediateAbortCore);
431 }
432 }
433 }
434for cnum in invalid_crates {
435 sess.dcx()
436 .emit_err(IncompatibleWithImmediateAbort { crate_name: tcx.crate_name(cnum) });
437 }
438 }
439440let mut panic_runtime = None;
441for cnum in list.iter().copied() {
442if tcx.is_panic_runtime(cnum) {
443if let Some((prev, _)) = panic_runtime {
444let prev_name = tcx.crate_name(prev);
445let cur_name = tcx.crate_name(cnum);
446 sess.dcx().emit_err(TwoPanicRuntimes { prev_name, cur_name });
447 }
448 panic_runtime = Some((
449 cnum,
450 tcx.required_panic_strategy(cnum).unwrap_or_else(|| {
451bug_impl(None,
format_args!("cannot determine panic strategy of a panic runtime"),
Location::caller());bug!("cannot determine panic strategy of a panic runtime");
452 }),
453 ));
454 }
455 }
456457// If we found a panic runtime, then we know by this point that it's the
458 // only one, but we perform validation here that all the panic strategy
459 // compilation modes for the whole DAG are valid.
460if let Some((runtime_cnum, found_strategy)) = panic_runtime {
461// First up, validate that our selected panic runtime is indeed exactly
462 // our same strategy.
463if found_strategy != desired_strategy {
464sess.dcx().emit_err(BadPanicStrategy {
465 runtime: tcx.crate_name(runtime_cnum),
466 strategy: desired_strategy,
467 });
468 }
469470// Next up, verify that all other crates are compatible with this panic
471 // strategy. If the dep isn't linked, we ignore it, and if our strategy
472 // is abort then it's compatible with everything. Otherwise all crates'
473 // panic strategy must match our own.
474for cnum in list.iter().copied() {
475if cnum == runtime_cnum || tcx.is_compiler_builtins(cnum) {
476continue;
477 }
478479if let Some(found_strategy) = tcx.required_panic_strategy(cnum)
480 && desired_strategy != found_strategy
481 {
482 sess.dcx().emit_err(RequiredPanicStrategy {
483 crate_name: tcx.crate_name(cnum),
484 found_strategy,
485 desired_strategy,
486 });
487 }
488489// panic_in_drop_strategy isn't allowed for LOCAL_CRATE
490if cnum != LOCAL_CRATE {
491let found_drop_strategy = tcx.panic_in_drop_strategy(cnum);
492if tcx.sess.opts.unstable_opts.panic_in_drop != found_drop_strategy {
493 sess.dcx().emit_err(IncompatiblePanicInDropStrategy {
494 crate_name: tcx.crate_name(cnum),
495 found_strategy: found_drop_strategy,
496 desired_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
497 });
498 }
499 }
500 }
501 }
502}