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_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 tracing::info;
65
66use crate::creader::CStore;
67use crate::errors::{
68 BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy, LibRequired,
69 NonStaticCrateDep, RequiredPanicStrategy, RlibRequired, RustcDriverHelp, RustcLibRequired,
70 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.dep_kind(cnum).macros_only() {
149 continue;
150 }
151 let src = tcx.used_crate_source(cnum);
152 if src.rlib.is_some() {
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.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 };
170
171 let mut upstream_in_dylibs = FxHashSet::default();
172
173 if 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`.
176
177 // Find all libraries statically linked to upstream dylibs.
178 for &cnum in all_dylibs() {
179 let deps = tcx.dylib_dependency_formats(cnum);
180 for &(depnum, style) in deps.iter() {
181 if let RequireStatic = style {
182 upstream_in_dylibs.insert(depnum);
183 }
184 }
185 }
186 }
187
188 let mut formats = FxHashMap::default();
189
190 // 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.
193 for &cnum in all_dylibs() {
194 if upstream_in_dylibs.contains(&cnum) {
195 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.
198 continue;
199 }
200
201 let name = tcx.crate_name(cnum);
202 info!("adding dylib: {}", name);
203 add_library(tcx, cnum, RequireDynamic, &mut formats, &mut unavailable_as_static);
204 let deps = tcx.dylib_dependency_formats(cnum);
205 for &(depnum, style) in deps.iter() {
206 info!("adding {:?}: {}", style, tcx.crate_name(depnum));
207 add_library(tcx, depnum, style, &mut formats, &mut unavailable_as_static);
208 }
209 }
210
211 // Collect what we've got so far in the return vector.
212 let last_crate = tcx.crates(()).len();
213 let mut ret = IndexVec::new();
214
215 // 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 assert_eq!(ret.push(Linkage::Static), LOCAL_CRATE);
221
222 for cnum in 1..last_crate + 1 {
223 let cnum = CrateNum::new(cnum);
224 assert_eq!(
225 ret.push(match formats.get(&cnum) {
226 Some(&RequireDynamic) => Linkage::Dynamic,
227 Some(&RequireStatic) => Linkage::IncludedFromDylib,
228 None => Linkage::NotLinked,
229 }),
230 cnum
231 );
232 }
233
234 // 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.
239 for &cnum in tcx.crates(()).iter() {
240 let src = tcx.used_crate_source(cnum);
241 if src.dylib.is_none()
242 && !formats.contains_key(&cnum)
243 && tcx.dep_kind(cnum) == CrateDepKind::Explicit
244 {
245 assert!(src.rlib.is_some() || src.rmeta.is_some());
246 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 }
251
252 // 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.
257 activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
258 tcx.is_panic_runtime(cnum)
259 });
260
261 // 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.
267 for (cnum, kind) in ret.iter_enumerated() {
268 if cnum == LOCAL_CRATE {
269 continue;
270 }
271 let src = tcx.used_crate_source(cnum);
272 match *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 => {
277 let kind = match kind {
278 Linkage::Static => "rlib",
279 _ => "dylib",
280 };
281 let crate_name = tcx.crate_name(cnum);
282 if 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 }
290
291 ret
292}
293
294fn 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) {
301 match m.get(&cnum) {
302 Some(&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.
310 if link2 != link || link == RequireStatic {
311 let linking_to_rustc_driver = tcx.sess.psess.unstable_features.is_nightly_build()
312 && tcx.crates(()).iter().any(|&cnum| tcx.crate_name(cnum) == sym::rustc_driver);
313 tcx.dcx().emit_err(CrateDepMultiple {
314 crate_name: tcx.crate_name(cnum),
315 non_static_deps: unavailable_as_static
316 .drain(..)
317 .map(|cnum| NonStaticCrateDep { crate_name: tcx.crate_name(cnum) })
318 .collect(),
319 rustc_driver_help: linking_to_rustc_driver.then_some(RustcDriverHelp),
320 });
321 }
322 }
323 None => {
324 m.insert(cnum, link);
325 }
326 }
327}
328
329fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec<CrateNum>) -> Option<DependencyList> {
330 let all_crates_available_as_rlib = tcx
331 .crates(())
332 .iter()
333 .copied()
334 .filter_map(|cnum| {
335 if tcx.dep_kind(cnum).macros_only() {
336 return None;
337 }
338 let is_rlib = tcx.used_crate_source(cnum).rlib.is_some();
339 if !is_rlib {
340 unavailable.push(cnum);
341 }
342 Some(is_rlib)
343 })
344 .all(|is_rlib| is_rlib);
345 if !all_crates_available_as_rlib {
346 return None;
347 }
348
349 // 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.
351 let mut ret = IndexVec::new();
352 assert_eq!(ret.push(Linkage::Static), LOCAL_CRATE);
353 for &cnum in tcx.crates(()) {
354 assert_eq!(
355 ret.push(match tcx.dep_kind(cnum) {
356 CrateDepKind::Explicit => Linkage::Static,
357 CrateDepKind::MacrosOnly | CrateDepKind::Implicit => Linkage::NotLinked,
358 }),
359 cnum
360 );
361 }
362
363 // 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.
366 activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
367 tcx.is_panic_runtime(cnum)
368 });
369
370 Some(ret)
371}
372
373// 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) {
387 for (cnum, slot) in list.iter_enumerated() {
388 if !replaces_injected(cnum) {
389 continue;
390 }
391 if *slot != Linkage::NotLinked {
392 return;
393 }
394 }
395 if let Some(injected) = injected {
396 assert_eq!(list[injected], Linkage::NotLinked);
397 list[injected] = Linkage::Static;
398 }
399}
400
401/// 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) {
404 let sess = &tcx.sess;
405 if list.is_empty() {
406 return;
407 }
408 let mut panic_runtime = None;
409 for (cnum, linkage) in list.iter_enumerated() {
410 if let Linkage::NotLinked = *linkage {
411 continue;
412 }
413
414 if tcx.is_panic_runtime(cnum) {
415 if let Some((prev, _)) = panic_runtime {
416 let prev_name = tcx.crate_name(prev);
417 let cur_name = tcx.crate_name(cnum);
418 sess.dcx().emit_err(TwoPanicRuntimes { prev_name, cur_name });
419 }
420 panic_runtime = Some((
421 cnum,
422 tcx.required_panic_strategy(cnum).unwrap_or_else(|| {
423 bug!("cannot determine panic strategy of a panic runtime");
424 }),
425 ));
426 }
427 }
428
429 // If we found a panic runtime, then we know by this point that it's the
430 // only one, but we perform validation here that all the panic strategy
431 // compilation modes for the whole DAG are valid.
432 if let Some((runtime_cnum, found_strategy)) = panic_runtime {
433 let desired_strategy = sess.panic_strategy();
434
435 // First up, validate that our selected panic runtime is indeed exactly
436 // our same strategy.
437 if found_strategy != desired_strategy {
438 sess.dcx().emit_err(BadPanicStrategy {
439 runtime: tcx.crate_name(runtime_cnum),
440 strategy: desired_strategy,
441 });
442 }
443
444 // Next up, verify that all other crates are compatible with this panic
445 // strategy. If the dep isn't linked, we ignore it, and if our strategy
446 // is abort then it's compatible with everything. Otherwise all crates'
447 // panic strategy must match our own.
448 for (cnum, linkage) in list.iter_enumerated() {
449 if let Linkage::NotLinked = *linkage {
450 continue;
451 }
452 if cnum == runtime_cnum || tcx.is_compiler_builtins(cnum) {
453 continue;
454 }
455
456 if let Some(found_strategy) = tcx.required_panic_strategy(cnum)
457 && desired_strategy != found_strategy
458 {
459 sess.dcx().emit_err(RequiredPanicStrategy {
460 crate_name: tcx.crate_name(cnum),
461 found_strategy,
462 desired_strategy,
463 });
464 }
465
466 // panic_in_drop_strategy isn't allowed for LOCAL_CRATE
467 if cnum != LOCAL_CRATE {
468 let found_drop_strategy = tcx.panic_in_drop_strategy(cnum);
469 if tcx.sess.opts.unstable_opts.panic_in_drop != found_drop_strategy {
470 sess.dcx().emit_err(IncompatiblePanicInDropStrategy {
471 crate_name: tcx.crate_name(cnum),
472 found_strategy: found_drop_strategy,
473 desired_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
474 });
475 }
476 }
477 }
478 }
479}