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 rustc_target::spec::PanicStrategy;
65use tracing::info;
66
67use crate::creader::CStore;
68use crate::errors::{
69    BadPanicStrategy, CrateDepMultiple, IncompatiblePanicInDropStrategy,
70    IncompatibleWithImmediateAbort, IncompatibleWithImmediateAbortCore, LibRequired,
71    NonStaticCrateDep, RequiredPanicStrategy, RlibRequired, RustcDriverHelp, RustcLibRequired,
72    TwoPanicRuntimes,
73};
74
75pub(crate) fn calculate(tcx: TyCtxt<'_>) -> Dependencies {
76    tcx.crate_types()
77        .iter()
78        .map(|&ty| {
79            let linkage = calculate_type(tcx, ty);
80            verify_ok(tcx, &linkage);
81            (ty, linkage)
82        })
83        .collect()
84}
85
86fn calculate_type(tcx: TyCtxt<'_>, ty: CrateType) -> DependencyList {
87    let sess = &tcx.sess;
88
89    if !sess.opts.output_types.should_link() {
90        return IndexVec::new();
91    }
92
93    let preferred_linkage =
94        match 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.
104            CrateType::Dylib | CrateType::Cdylib | CrateType::Sdylib => {
105                if sess.opts.cg.prefer_dynamic { Linkage::Dynamic } else { Linkage::Static }
106            }
107            CrateType::Staticlib => {
108                if sess.opts.unstable_opts.staticlib_prefer_dynamic {
109                    Linkage::Dynamic
110                } else {
111                    Linkage::Static
112                }
113            }
114
115            // If the global prefer_dynamic switch is turned off, or the final
116            // executable will be statically linked, prefer static crate linkage.
117            CrateType::Executable if !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => {
118                Linkage::Static
119            }
120            CrateType::Executable => Linkage::Dynamic,
121
122            // proc-macro crates are mostly cdylibs, but we also need metadata.
123            CrateType::ProcMacro => Linkage::Static,
124
125            // No linkage happens with rlibs, we just needed the metadata (which we
126            // got long ago), so don't bother with anything.
127            CrateType::Rlib => Linkage::NotLinked,
128        };
129
130    let mut unavailable_as_static = Vec::new();
131
132    match preferred_linkage {
133        // If the crate is not linked, there are no link-time dependencies.
134        Linkage::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.
138            if let Some(v) = attempt_static(tcx, &mut unavailable_as_static) {
139                return v;
140            }
141
142            // Static executables must have all static dependencies.
143            // If any are not found, generate some nice pretty errors.
144            if (ty == CrateType::Staticlib && !sess.opts.unstable_opts.staticlib_allow_rdylib_deps)
145                || (ty == CrateType::Executable
146                    && sess.crt_static(Some(ty))
147                    && !sess.target.crt_static_allows_dylibs)
148            {
149                for &cnum in tcx.crates(()).iter() {
150                    if tcx.dep_kind(cnum).macros_only() {
151                        continue;
152                    }
153                    let src = tcx.used_crate_source(cnum);
154                    if src.rlib.is_some() {
155                        continue;
156                    }
157                    sess.dcx().emit_err(RlibRequired { crate_name: tcx.crate_name(cnum) });
158                }
159                return IndexVec::new();
160            }
161        }
162        Linkage::Dynamic | Linkage::IncludedFromDylib => {}
163    }
164
165    let all_dylibs = || {
166        tcx.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    };
172
173    let mut upstream_in_dylibs = FxHashSet::default();
174
175    if 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`.
178
179        // Find all libraries statically linked to upstream dylibs.
180        for &cnum in all_dylibs() {
181            let deps = tcx.dylib_dependency_formats(cnum);
182            for &(depnum, style) in deps.iter() {
183                if let RequireStatic = style {
184                    upstream_in_dylibs.insert(depnum);
185                }
186            }
187        }
188    }
189
190    let mut formats = FxHashMap::default();
191
192    // 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.
195    for &cnum in all_dylibs() {
196        if upstream_in_dylibs.contains(&cnum) {
197            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.
200            continue;
201        }
202
203        let name = tcx.crate_name(cnum);
204        info!("adding dylib: {}", name);
205        add_library(tcx, cnum, RequireDynamic, &mut formats, &mut unavailable_as_static);
206        let deps = tcx.dylib_dependency_formats(cnum);
207        for &(depnum, style) in deps.iter() {
208            info!("adding {:?}: {}", style, tcx.crate_name(depnum));
209            add_library(tcx, depnum, style, &mut formats, &mut unavailable_as_static);
210        }
211    }
212
213    // Collect what we've got so far in the return vector.
214    let last_crate = tcx.crates(()).len();
215    let mut ret = IndexVec::new();
216
217    // 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.
222    assert_eq!(ret.push(Linkage::Static), LOCAL_CRATE);
223
224    for cnum in 1..last_crate + 1 {
225        let cnum = CrateNum::new(cnum);
226        assert_eq!(
227            ret.push(match formats.get(&cnum) {
228                Some(&RequireDynamic) => Linkage::Dynamic,
229                Some(&RequireStatic) => Linkage::IncludedFromDylib,
230                None => Linkage::NotLinked,
231            }),
232            cnum
233        );
234    }
235
236    // 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.
241    for &cnum in tcx.crates(()).iter() {
242        let src = tcx.used_crate_source(cnum);
243        if src.dylib.is_none()
244            && !formats.contains_key(&cnum)
245            && tcx.dep_kind(cnum) == CrateDepKind::Explicit
246        {
247            assert!(src.rlib.is_some() || src.rmeta.is_some());
248            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    }
253
254    // 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.
259    activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
260        tcx.is_panic_runtime(cnum)
261    });
262
263    // 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.
269    for (cnum, kind) in ret.iter_enumerated() {
270        if cnum == LOCAL_CRATE {
271            continue;
272        }
273        let src = tcx.used_crate_source(cnum);
274        match *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 => {
279                let kind = match kind {
280                    Linkage::Static => "rlib",
281                    _ => "dylib",
282                };
283                let crate_name = tcx.crate_name(cnum);
284                if 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    }
292
293    ret
294}
295
296fn 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) {
303    match m.get(&cnum) {
304        Some(&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.
312            if link2 != link || link == RequireStatic {
313                let 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);
315                tcx.dcx().emit_err(CrateDepMultiple {
316                    crate_name: tcx.crate_name(cnum),
317                    non_static_deps: unavailable_as_static
318                        .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        }
325        None => {
326            m.insert(cnum, link);
327        }
328    }
329}
330
331fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec<CrateNum>) -> Option<DependencyList> {
332    let all_crates_available_as_rlib = tcx
333        .crates(())
334        .iter()
335        .copied()
336        .filter_map(|cnum| {
337            if tcx.dep_kind(cnum).macros_only() {
338                return None;
339            }
340            let is_rlib = tcx.used_crate_source(cnum).rlib.is_some();
341            if !is_rlib {
342                unavailable.push(cnum);
343            }
344            Some(is_rlib)
345        })
346        .all(|is_rlib| is_rlib);
347    if !all_crates_available_as_rlib {
348        return None;
349    }
350
351    // 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.
353    let mut ret = IndexVec::new();
354    assert_eq!(ret.push(Linkage::Static), LOCAL_CRATE);
355    for &cnum in tcx.crates(()) {
356        assert_eq!(
357            ret.push(match tcx.dep_kind(cnum) {
358                CrateDepKind::Explicit => Linkage::Static,
359                CrateDepKind::MacrosOnly | CrateDepKind::Implicit => Linkage::NotLinked,
360            }),
361            cnum
362        );
363    }
364
365    // 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.
368    activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
369        tcx.is_panic_runtime(cnum)
370    });
371
372    Some(ret)
373}
374
375/// 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) {
389    for (cnum, slot) in list.iter_enumerated() {
390        if !replaces_injected(cnum) {
391            continue;
392        }
393        if *slot != Linkage::NotLinked {
394            return;
395        }
396    }
397    if let Some(injected) = injected {
398        assert_eq!(list[injected], Linkage::NotLinked);
399        list[injected] = Linkage::Static;
400    }
401}
402
403/// 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) {
406    let sess = &tcx.sess;
407    let list: Vec<_> = list
408        .iter_enumerated()
409        .filter_map(
410            |(cnum, linkage)| if *linkage == Linkage::NotLinked { None } else { Some(cnum) },
411        )
412        .collect();
413    if list.is_empty() {
414        return;
415    }
416    let desired_strategy = sess.panic_strategy();
417
418    // If we are panic=immediate-abort, make sure everything in the dependency tree has also been
419    // compiled with immediate-abort.
420    if list
421        .iter()
422        .any(|cnum| tcx.required_panic_strategy(*cnum) == Some(PanicStrategy::ImmediateAbort))
423    {
424        let mut invalid_crates = Vec::new();
425        for cnum in list.iter().copied() {
426            if 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.
431                if tcx.crate_name(cnum) == sym::core {
432                    sess.dcx().emit_fatal(IncompatibleWithImmediateAbortCore);
433                }
434            }
435        }
436        for cnum in invalid_crates {
437            sess.dcx()
438                .emit_err(IncompatibleWithImmediateAbort { crate_name: tcx.crate_name(cnum) });
439        }
440    }
441
442    let mut panic_runtime = None;
443    for cnum in list.iter().copied() {
444        if tcx.is_panic_runtime(cnum) {
445            if let Some((prev, _)) = panic_runtime {
446                let prev_name = tcx.crate_name(prev);
447                let 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                    bug!("cannot determine panic strategy of a panic runtime");
454                }),
455            ));
456        }
457    }
458
459    // 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.
462    if let Some((runtime_cnum, found_strategy)) = panic_runtime {
463        // First up, validate that our selected panic runtime is indeed exactly
464        // our same strategy.
465        if found_strategy != desired_strategy {
466            sess.dcx().emit_err(BadPanicStrategy {
467                runtime: tcx.crate_name(runtime_cnum),
468                strategy: desired_strategy,
469            });
470        }
471
472        // 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.
476        for cnum in list.iter().copied() {
477            if cnum == runtime_cnum || tcx.is_compiler_builtins(cnum) {
478                continue;
479            }
480
481            if 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            }
490
491            // panic_in_drop_strategy isn't allowed for LOCAL_CRATE
492            if cnum != LOCAL_CRATE {
493                let found_drop_strategy = tcx.panic_in_drop_strategy(cnum);
494                if 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}