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