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_codegen() {
88        return IndexVec::new();
89    }
90
91    let preferred_linkage = match ty {
92        // Generating a dylib without `-C prefer-dynamic` means that we're going
93        // to try to eagerly statically link all dependencies. This is normally
94        // done for end-product dylibs, not intermediate products.
95        //
96        // Treat cdylibs and staticlibs similarly. If `-C prefer-dynamic` is set,
97        // the caller may be code-size conscious, but without it, it makes sense
98        // to statically link a cdylib or staticlib. For staticlibs we use
99        // `-Z staticlib-prefer-dynamic` for now. This may be merged into
100        // `-C prefer-dynamic` in the future.
101        CrateType::Dylib | CrateType::Cdylib => {
102            if sess.opts.cg.prefer_dynamic {
103                Linkage::Dynamic
104            } else {
105                Linkage::Static
106            }
107        }
108        CrateType::Staticlib => {
109            if sess.opts.unstable_opts.staticlib_prefer_dynamic {
110                Linkage::Dynamic
111            } else {
112                Linkage::Static
113            }
114        }
115
116        // If the global prefer_dynamic switch is turned off, or the final
117        // executable will be statically linked, prefer static crate linkage.
118        CrateType::Executable if !sess.opts.cg.prefer_dynamic || sess.crt_static(Some(ty)) => {
119            Linkage::Static
120        }
121        CrateType::Executable => Linkage::Dynamic,
122
123        // proc-macro crates are mostly cdylibs, but we also need metadata.
124        CrateType::ProcMacro => Linkage::Static,
125
126        // No linkage happens with rlibs, we just needed the metadata (which we
127        // got long ago), so don't bother with anything.
128        CrateType::Rlib => Linkage::NotLinked,
129    };
130
131    let mut unavailable_as_static = Vec::new();
132
133    match preferred_linkage {
134        // If the crate is not linked, there are no link-time dependencies.
135        Linkage::NotLinked => return IndexVec::new(),
136        Linkage::Static => {
137            // Attempt static linkage first. For dylibs and executables, we may be
138            // able to retry below with dynamic linkage.
139            if let Some(v) = attempt_static(tcx, &mut unavailable_as_static) {
140                return v;
141            }
142
143            // Static executables must have all static dependencies.
144            // If any are not found, generate some nice pretty errors.
145            if (ty == CrateType::Staticlib && !sess.opts.unstable_opts.staticlib_allow_rdylib_deps)
146                || (ty == CrateType::Executable
147                    && sess.crt_static(Some(ty))
148                    && !sess.target.crt_static_allows_dylibs)
149            {
150                for &cnum in tcx.crates(()).iter() {
151                    if tcx.dep_kind(cnum).macros_only() {
152                        continue;
153                    }
154                    let src = tcx.used_crate_source(cnum);
155                    if src.rlib.is_some() {
156                        continue;
157                    }
158                    sess.dcx().emit_err(RlibRequired { crate_name: tcx.crate_name(cnum) });
159                }
160                return IndexVec::new();
161            }
162        }
163        Linkage::Dynamic | Linkage::IncludedFromDylib => {}
164    }
165
166    let all_dylibs = || {
167        tcx.crates(()).iter().filter(|&&cnum| {
168            !tcx.dep_kind(cnum).macros_only() && tcx.used_crate_source(cnum).dylib.is_some()
169        })
170    };
171
172    let mut upstream_in_dylibs = FxHashSet::default();
173
174    if 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`.
177
178        // Find all libraries statically linked to upstream dylibs.
179        for &cnum in all_dylibs() {
180            let deps = tcx.dylib_dependency_formats(cnum);
181            for &(depnum, style) in deps.iter() {
182                if let RequireStatic = style {
183                    upstream_in_dylibs.insert(depnum);
184                }
185            }
186        }
187    }
188
189    let mut formats = FxHashMap::default();
190
191    // 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.
194    for &cnum in all_dylibs() {
195        if upstream_in_dylibs.contains(&cnum) {
196            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.
199            continue;
200        }
201
202        let name = tcx.crate_name(cnum);
203        info!("adding dylib: {}", name);
204        add_library(tcx, cnum, RequireDynamic, &mut formats, &mut unavailable_as_static);
205        let deps = tcx.dylib_dependency_formats(cnum);
206        for &(depnum, style) in deps.iter() {
207            info!("adding {:?}: {}", style, tcx.crate_name(depnum));
208            add_library(tcx, depnum, style, &mut formats, &mut unavailable_as_static);
209        }
210    }
211
212    // Collect what we've got so far in the return vector.
213    let last_crate = tcx.crates(()).len();
214    let mut ret = IndexVec::new();
215
216    // 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.
221    assert_eq!(ret.push(Linkage::Static), LOCAL_CRATE);
222
223    for cnum in 1..last_crate + 1 {
224        let cnum = CrateNum::new(cnum);
225        assert_eq!(
226            ret.push(match formats.get(&cnum) {
227                Some(&RequireDynamic) => Linkage::Dynamic,
228                Some(&RequireStatic) => Linkage::IncludedFromDylib,
229                None => Linkage::NotLinked,
230            }),
231            cnum
232        );
233    }
234
235    // 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.
240    for &cnum in tcx.crates(()).iter() {
241        let src = tcx.used_crate_source(cnum);
242        if src.dylib.is_none()
243            && !formats.contains_key(&cnum)
244            && tcx.dep_kind(cnum) == CrateDepKind::Explicit
245        {
246            assert!(src.rlib.is_some() || src.rmeta.is_some());
247            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    }
252
253    // 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.
258    activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
259        tcx.is_panic_runtime(cnum)
260    });
261
262    // 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.
268    for (cnum, kind) in ret.iter_enumerated() {
269        if cnum == LOCAL_CRATE {
270            continue;
271        }
272        let src = tcx.used_crate_source(cnum);
273        match *kind {
274            Linkage::NotLinked | Linkage::IncludedFromDylib => {}
275            Linkage::Static if src.rlib.is_some() => continue,
276            Linkage::Dynamic if src.dylib.is_some() => continue,
277            kind => {
278                let kind = match kind {
279                    Linkage::Static => "rlib",
280                    _ => "dylib",
281                };
282                let crate_name = tcx.crate_name(cnum);
283                if 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    }
291
292    ret
293}
294
295fn 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) {
302    match m.get(&cnum) {
303        Some(&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.
311            if link2 != link || link == RequireStatic {
312                let 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);
314                tcx.dcx().emit_err(CrateDepMultiple {
315                    crate_name: tcx.crate_name(cnum),
316                    non_static_deps: unavailable_as_static
317                        .drain(..)
318                        .map(|cnum| NonStaticCrateDep { crate_name: tcx.crate_name(cnum) })
319                        .collect(),
320                    rustc_driver_help: linking_to_rustc_driver.then_some(RustcDriverHelp),
321                });
322            }
323        }
324        None => {
325            m.insert(cnum, link);
326        }
327    }
328}
329
330fn attempt_static(tcx: TyCtxt<'_>, unavailable: &mut Vec<CrateNum>) -> Option<DependencyList> {
331    let all_crates_available_as_rlib = tcx
332        .crates(())
333        .iter()
334        .copied()
335        .filter_map(|cnum| {
336            if tcx.dep_kind(cnum).macros_only() {
337                return None;
338            }
339            let is_rlib = tcx.used_crate_source(cnum).rlib.is_some();
340            if !is_rlib {
341                unavailable.push(cnum);
342            }
343            Some(is_rlib)
344        })
345        .all(|is_rlib| is_rlib);
346    if !all_crates_available_as_rlib {
347        return None;
348    }
349
350    // 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.
352    let mut ret = IndexVec::new();
353    assert_eq!(ret.push(Linkage::Static), LOCAL_CRATE);
354    for &cnum in tcx.crates(()) {
355        assert_eq!(
356            ret.push(match tcx.dep_kind(cnum) {
357                CrateDepKind::Explicit => Linkage::Static,
358                CrateDepKind::MacrosOnly | CrateDepKind::Implicit => Linkage::NotLinked,
359            }),
360            cnum
361        );
362    }
363
364    // 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.
367    activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
368        tcx.is_panic_runtime(cnum)
369    });
370
371    Some(ret)
372}
373
374// 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) {
388    for (cnum, slot) in list.iter_enumerated() {
389        if !replaces_injected(cnum) {
390            continue;
391        }
392        if *slot != Linkage::NotLinked {
393            return;
394        }
395    }
396    if let Some(injected) = injected {
397        assert_eq!(list[injected], Linkage::NotLinked);
398        list[injected] = Linkage::Static;
399    }
400}
401
402/// 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) {
405    let sess = &tcx.sess;
406    if list.is_empty() {
407        return;
408    }
409    let mut panic_runtime = None;
410    for (cnum, linkage) in list.iter_enumerated() {
411        if let Linkage::NotLinked = *linkage {
412            continue;
413        }
414
415        if tcx.is_panic_runtime(cnum) {
416            if let Some((prev, _)) = panic_runtime {
417                let prev_name = tcx.crate_name(prev);
418                let cur_name = tcx.crate_name(cnum);
419                sess.dcx().emit_err(TwoPanicRuntimes { prev_name, cur_name });
420            }
421            panic_runtime = Some((
422                cnum,
423                tcx.required_panic_strategy(cnum).unwrap_or_else(|| {
424                    bug!("cannot determine panic strategy of a panic runtime");
425                }),
426            ));
427        }
428    }
429
430    // If we found a panic runtime, then we know by this point that it's the
431    // only one, but we perform validation here that all the panic strategy
432    // compilation modes for the whole DAG are valid.
433    if let Some((runtime_cnum, found_strategy)) = panic_runtime {
434        let desired_strategy = sess.panic_strategy();
435
436        // First up, validate that our selected panic runtime is indeed exactly
437        // our same strategy.
438        if found_strategy != desired_strategy {
439            sess.dcx().emit_err(BadPanicStrategy {
440                runtime: tcx.crate_name(runtime_cnum),
441                strategy: desired_strategy,
442            });
443        }
444
445        // Next up, verify that all other crates are compatible with this panic
446        // strategy. If the dep isn't linked, we ignore it, and if our strategy
447        // is abort then it's compatible with everything. Otherwise all crates'
448        // panic strategy must match our own.
449        for (cnum, linkage) in list.iter_enumerated() {
450            if let Linkage::NotLinked = *linkage {
451                continue;
452            }
453            if cnum == runtime_cnum || tcx.is_compiler_builtins(cnum) {
454                continue;
455            }
456
457            if let Some(found_strategy) = tcx.required_panic_strategy(cnum)
458                && desired_strategy != found_strategy
459            {
460                sess.dcx().emit_err(RequiredPanicStrategy {
461                    crate_name: tcx.crate_name(cnum),
462                    found_strategy,
463                    desired_strategy,
464                });
465            }
466
467            // panic_in_drop_strategy isn't allowed for LOCAL_CRATE
468            if cnum != LOCAL_CRATE {
469                let found_drop_strategy = tcx.panic_in_drop_strategy(cnum);
470                if tcx.sess.opts.unstable_opts.panic_in_drop != found_drop_strategy {
471                    sess.dcx().emit_err(IncompatiblePanicInDropStrategy {
472                        crate_name: tcx.crate_name(cnum),
473                        found_strategy: found_drop_strategy,
474                        desired_strategy: tcx.sess.opts.unstable_opts.panic_in_drop,
475                    });
476                }
477            }
478        }
479    }
480}