]> git.lizzy.rs Git - rust.git/blob - src/librustc_metadata/dependency_format.rs
Rollup merge of #67725 - ssomers:into_key_slice_mut, r=RalfJung
[rust.git] / src / librustc_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
54 use crate::creader::CStore;
55
56 use rustc::middle::cstore::LinkagePreference::{self, RequireDynamic, RequireStatic};
57 use rustc::middle::cstore::{self, DepKind};
58 use rustc::middle::dependency_format::{Dependencies, DependencyList, Linkage};
59 use rustc::session::config;
60 use rustc::ty::TyCtxt;
61 use rustc_data_structures::fx::FxHashMap;
62 use rustc_hir::def_id::CrateNum;
63 use rustc_target::spec::PanicStrategy;
64
65 crate fn calculate(tcx: TyCtxt<'_>) -> Dependencies {
66     tcx.sess
67         .crate_types
68         .borrow()
69         .iter()
70         .map(|&ty| {
71             let linkage = calculate_type(tcx, ty);
72             verify_ok(tcx, &linkage);
73             (ty, linkage)
74         })
75         .collect::<Vec<_>>()
76 }
77
78 fn calculate_type(tcx: TyCtxt<'_>, ty: config::CrateType) -> DependencyList {
79     let sess = &tcx.sess;
80
81     if !sess.opts.output_types.should_codegen() {
82         return Vec::new();
83     }
84
85     let preferred_linkage = match ty {
86         // cdylibs must have all static dependencies.
87         config::CrateType::Cdylib => Linkage::Static,
88
89         // Generating a dylib without `-C prefer-dynamic` means that we're going
90         // to try to eagerly statically link all dependencies. This is normally
91         // done for end-product dylibs, not intermediate products.
92         config::CrateType::Dylib if !sess.opts.cg.prefer_dynamic => Linkage::Static,
93         config::CrateType::Dylib => Linkage::Dynamic,
94
95         // If the global prefer_dynamic switch is turned off, or the final
96         // executable will be statically linked, prefer static crate linkage.
97         config::CrateType::Executable if !sess.opts.cg.prefer_dynamic || sess.crt_static() => {
98             Linkage::Static
99         }
100         config::CrateType::Executable => Linkage::Dynamic,
101
102         // proc-macro crates are mostly cdylibs, but we also need metadata.
103         config::CrateType::ProcMacro => Linkage::Static,
104
105         // No linkage happens with rlibs, we just needed the metadata (which we
106         // got long ago), so don't bother with anything.
107         config::CrateType::Rlib => Linkage::NotLinked,
108
109         // staticlibs must have all static dependencies.
110         config::CrateType::Staticlib => Linkage::Static,
111     };
112
113     if preferred_linkage == Linkage::NotLinked {
114         // If the crate is not linked, there are no link-time dependencies.
115         return Vec::new();
116     }
117
118     if preferred_linkage == Linkage::Static {
119         // Attempt static linkage first. For dylibs and executables, we may be
120         // able to retry below with dynamic linkage.
121         if let Some(v) = attempt_static(tcx) {
122             return v;
123         }
124
125         // Staticlibs, cdylibs, and static executables must have all static
126         // dependencies. If any are not found, generate some nice pretty errors.
127         if ty == config::CrateType::Cdylib
128             || ty == config::CrateType::Staticlib
129             || (ty == config::CrateType::Executable
130                 && sess.crt_static()
131                 && !sess.target.target.options.crt_static_allows_dylibs)
132         {
133             for &cnum in tcx.crates().iter() {
134                 if tcx.dep_kind(cnum).macros_only() {
135                     continue;
136                 }
137                 let src = tcx.used_crate_source(cnum);
138                 if src.rlib.is_some() {
139                     continue;
140                 }
141                 sess.err(&format!(
142                     "crate `{}` required to be available in rlib format, \
143                                    but was not found in this form",
144                     tcx.crate_name(cnum)
145                 ));
146             }
147             return Vec::new();
148         }
149     }
150
151     let mut formats = FxHashMap::default();
152
153     // Sweep all crates for found dylibs. Add all dylibs, as well as their
154     // dependencies, ensuring there are no conflicts. The only valid case for a
155     // dependency to be relied upon twice is for both cases to rely on a dylib.
156     for &cnum in tcx.crates().iter() {
157         if tcx.dep_kind(cnum).macros_only() {
158             continue;
159         }
160         let name = tcx.crate_name(cnum);
161         let src = tcx.used_crate_source(cnum);
162         if src.dylib.is_some() {
163             log::info!("adding dylib: {}", name);
164             add_library(tcx, cnum, RequireDynamic, &mut formats);
165             let deps = tcx.dylib_dependency_formats(cnum);
166             for &(depnum, style) in deps.iter() {
167                 log::info!("adding {:?}: {}", style, tcx.crate_name(depnum));
168                 add_library(tcx, depnum, style, &mut formats);
169             }
170         }
171     }
172
173     // Collect what we've got so far in the return vector.
174     let last_crate = tcx.crates().len();
175     let mut ret = (1..last_crate + 1)
176         .map(|cnum| match formats.get(&CrateNum::new(cnum)) {
177             Some(&RequireDynamic) => Linkage::Dynamic,
178             Some(&RequireStatic) => Linkage::IncludedFromDylib,
179             None => Linkage::NotLinked,
180         })
181         .collect::<Vec<_>>();
182
183     // Run through the dependency list again, and add any missing libraries as
184     // static libraries.
185     //
186     // If the crate hasn't been included yet and it's not actually required
187     // (e.g., it's an allocator) then we skip it here as well.
188     for &cnum in tcx.crates().iter() {
189         let src = tcx.used_crate_source(cnum);
190         if src.dylib.is_none()
191             && !formats.contains_key(&cnum)
192             && tcx.dep_kind(cnum) == DepKind::Explicit
193         {
194             assert!(src.rlib.is_some() || src.rmeta.is_some());
195             log::info!("adding staticlib: {}", tcx.crate_name(cnum));
196             add_library(tcx, cnum, RequireStatic, &mut formats);
197             ret[cnum.as_usize() - 1] = Linkage::Static;
198         }
199     }
200
201     // We've gotten this far because we're emitting some form of a final
202     // artifact which means that we may need to inject dependencies of some
203     // form.
204     //
205     // Things like allocators and panic runtimes may not have been activated
206     // quite yet, so do so here.
207     activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
208         tcx.is_panic_runtime(cnum)
209     });
210
211     // When dylib B links to dylib A, then when using B we must also link to A.
212     // It could be the case, however, that the rlib for A is present (hence we
213     // found metadata), but the dylib for A has since been removed.
214     //
215     // For situations like this, we perform one last pass over the dependencies,
216     // making sure that everything is available in the requested format.
217     for (cnum, kind) in ret.iter().enumerate() {
218         let cnum = CrateNum::new(cnum + 1);
219         let src = tcx.used_crate_source(cnum);
220         match *kind {
221             Linkage::NotLinked | Linkage::IncludedFromDylib => {}
222             Linkage::Static if src.rlib.is_some() => continue,
223             Linkage::Dynamic if src.dylib.is_some() => continue,
224             kind => {
225                 let kind = match kind {
226                     Linkage::Static => "rlib",
227                     _ => "dylib",
228                 };
229                 sess.err(&format!(
230                     "crate `{}` required to be available in {} format, \
231                                    but was not found in this form",
232                     tcx.crate_name(cnum),
233                     kind
234                 ));
235             }
236         }
237     }
238
239     ret
240 }
241
242 fn add_library(
243     tcx: TyCtxt<'_>,
244     cnum: CrateNum,
245     link: LinkagePreference,
246     m: &mut FxHashMap<CrateNum, LinkagePreference>,
247 ) {
248     match m.get(&cnum) {
249         Some(&link2) => {
250             // If the linkages differ, then we'd have two copies of the library
251             // if we continued linking. If the linkages are both static, then we
252             // would also have two copies of the library (static from two
253             // different locations).
254             //
255             // This error is probably a little obscure, but I imagine that it
256             // can be refined over time.
257             if link2 != link || link == RequireStatic {
258                 tcx.sess
259                     .struct_err(&format!(
260                         "cannot satisfy dependencies so `{}` only \
261                                               shows up once",
262                         tcx.crate_name(cnum)
263                     ))
264                     .help(
265                         "having upstream crates all available in one format \
266                            will likely make this go away",
267                     )
268                     .emit();
269             }
270         }
271         None => {
272             m.insert(cnum, link);
273         }
274     }
275 }
276
277 fn attempt_static(tcx: TyCtxt<'_>) -> Option<DependencyList> {
278     let crates = cstore::used_crates(tcx, RequireStatic);
279     if !crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) {
280         return None;
281     }
282
283     // All crates are available in an rlib format, so we're just going to link
284     // everything in explicitly so long as it's actually required.
285     let last_crate = tcx.crates().len();
286     let mut ret = (1..last_crate + 1)
287         .map(|cnum| {
288             if tcx.dep_kind(CrateNum::new(cnum)) == DepKind::Explicit {
289                 Linkage::Static
290             } else {
291                 Linkage::NotLinked
292             }
293         })
294         .collect::<Vec<_>>();
295
296     // Our allocator/panic runtime may not have been linked above if it wasn't
297     // explicitly linked, which is the case for any injected dependency. Handle
298     // that here and activate them.
299     activate_injected_dep(CStore::from_tcx(tcx).injected_panic_runtime(), &mut ret, &|cnum| {
300         tcx.is_panic_runtime(cnum)
301     });
302
303     Some(ret)
304 }
305
306 // Given a list of how to link upstream dependencies so far, ensure that an
307 // injected dependency is activated. This will not do anything if one was
308 // transitively included already (e.g., via a dylib or explicitly so).
309 //
310 // If an injected dependency was not found then we're guaranteed the
311 // metadata::creader module has injected that dependency (not listed as
312 // a required dependency) in one of the session's field. If this field is not
313 // set then this compilation doesn't actually need the dependency and we can
314 // also skip this step entirely.
315 fn activate_injected_dep(
316     injected: Option<CrateNum>,
317     list: &mut DependencyList,
318     replaces_injected: &dyn Fn(CrateNum) -> bool,
319 ) {
320     for (i, slot) in list.iter().enumerate() {
321         let cnum = CrateNum::new(i + 1);
322         if !replaces_injected(cnum) {
323             continue;
324         }
325         if *slot != Linkage::NotLinked {
326             return;
327         }
328     }
329     if let Some(injected) = injected {
330         let idx = injected.as_usize() - 1;
331         assert_eq!(list[idx], Linkage::NotLinked);
332         list[idx] = Linkage::Static;
333     }
334 }
335
336 // After the linkage for a crate has been determined we need to verify that
337 // there's only going to be one allocator in the output.
338 fn verify_ok(tcx: TyCtxt<'_>, list: &[Linkage]) {
339     let sess = &tcx.sess;
340     if list.len() == 0 {
341         return;
342     }
343     let mut panic_runtime = None;
344     for (i, linkage) in list.iter().enumerate() {
345         if let Linkage::NotLinked = *linkage {
346             continue;
347         }
348         let cnum = CrateNum::new(i + 1);
349
350         if tcx.is_panic_runtime(cnum) {
351             if let Some((prev, _)) = panic_runtime {
352                 let prev_name = tcx.crate_name(prev);
353                 let cur_name = tcx.crate_name(cnum);
354                 sess.err(&format!(
355                     "cannot link together two \
356                                    panic runtimes: {} and {}",
357                     prev_name, cur_name
358                 ));
359             }
360             panic_runtime = Some((cnum, tcx.panic_strategy(cnum)));
361         }
362     }
363
364     // If we found a panic runtime, then we know by this point that it's the
365     // only one, but we perform validation here that all the panic strategy
366     // compilation modes for the whole DAG are valid.
367     if let Some((cnum, found_strategy)) = panic_runtime {
368         let desired_strategy = sess.panic_strategy();
369
370         // First up, validate that our selected panic runtime is indeed exactly
371         // our same strategy.
372         if found_strategy != desired_strategy {
373             sess.err(&format!(
374                 "the linked panic runtime `{}` is \
375                                not compiled with this crate's \
376                                panic strategy `{}`",
377                 tcx.crate_name(cnum),
378                 desired_strategy.desc()
379             ));
380         }
381
382         // Next up, verify that all other crates are compatible with this panic
383         // strategy. If the dep isn't linked, we ignore it, and if our strategy
384         // is abort then it's compatible with everything. Otherwise all crates'
385         // panic strategy must match our own.
386         for (i, linkage) in list.iter().enumerate() {
387             if let Linkage::NotLinked = *linkage {
388                 continue;
389             }
390             if desired_strategy == PanicStrategy::Abort {
391                 continue;
392             }
393             let cnum = CrateNum::new(i + 1);
394             let found_strategy = tcx.panic_strategy(cnum);
395             let is_compiler_builtins = tcx.is_compiler_builtins(cnum);
396             if is_compiler_builtins || desired_strategy == found_strategy {
397                 continue;
398             }
399
400             sess.err(&format!(
401                 "the crate `{}` is compiled with the \
402                                panic strategy `{}` which is \
403                                incompatible with this crate's \
404                                strategy of `{}`",
405                 tcx.crate_name(cnum),
406                 found_strategy.desc(),
407                 desired_strategy.desc()
408             ));
409         }
410     }
411 }