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