]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/dependency_format.rs
549a848a39dc1cdb184d263a7ae21944e29e4664
[rust.git] / src / librustc / middle / dependency_format.rs
1 // Copyright 2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
4 //
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
10
11 //! Resolution of mixing rlibs and dylibs
12 //!
13 //! When producing a final artifact, such as a dynamic library, the compiler has
14 //! a choice between linking an rlib or linking a dylib of all upstream
15 //! dependencies. The linking phase must guarantee, however, that a library only
16 //! show up once in the object file. For example, it is illegal for library A to
17 //! be statically linked to B and C in separate dylibs, and then link B and C
18 //! into a crate D (because library A appears twice).
19 //!
20 //! The job of this module is to calculate what format each upstream crate
21 //! should be used when linking each output type requested in this session. This
22 //! generally follows this set of rules:
23 //!
24 //!     1. Each library must appear exactly once in the output.
25 //!     2. Each rlib contains only one library (it's just an object file)
26 //!     3. Each dylib can contain more than one library (due to static linking),
27 //!        and can also bring in many dynamic dependencies.
28 //!
29 //! With these constraints in mind, it's generally a very difficult problem to
30 //! find a solution that's not "all rlibs" or "all dylibs". I have suspicions
31 //! that NP-ness may come into the picture here...
32 //!
33 //! The current selection algorithm below looks mostly similar to:
34 //!
35 //!     1. If static linking is required, then require all upstream dependencies
36 //!        to be available as rlibs. If not, generate an error.
37 //!     2. If static linking is requested (generating an executable), then
38 //!        attempt to use all upstream dependencies as rlibs. If any are not
39 //!        found, bail out and continue to step 3.
40 //!     3. Static linking has failed, at least one library must be dynamically
41 //!        linked. Apply a heuristic by greedily maximizing the number of
42 //!        dynamically linked libraries.
43 //!     4. Each upstream dependency available as a dynamic library is
44 //!        registered. The dependencies all propagate, adding to a map. It is
45 //!        possible for a dylib to add a static library as a dependency, but it
46 //!        is illegal for two dylibs to add the same static library as a
47 //!        dependency. The same dylib can be added twice. Additionally, it is
48 //!        illegal to add a static dependency when it was previously found as a
49 //!        dylib (and vice versa)
50 //!     5. After all dynamic dependencies have been traversed, re-traverse the
51 //!        remaining dependencies and add them statically (if they haven't been
52 //!        added already).
53 //!
54 //! While not perfect, this algorithm should help support use-cases such as leaf
55 //! dependencies being static while the larger tree of inner dependencies are
56 //! all dynamic. This isn't currently very well battle tested, so it will likely
57 //! fall short in some use cases.
58 //!
59 //! Currently, there is no way to specify the preference of linkage with a
60 //! particular library (other than a global dynamic/static switch).
61 //! Additionally, the algorithm is geared towards finding *any* solution rather
62 //! than finding a number of solutions (there are normally quite a few).
63
64 use hir::def_id::CrateNum;
65
66 use session::config;
67 use ty::TyCtxt;
68 use middle::cstore::{self, DepKind};
69 use middle::cstore::LinkagePreference::{self, RequireStatic, RequireDynamic};
70 use util::nodemap::FxHashMap;
71 use rustc_target::spec::PanicStrategy;
72
73 /// A list of dependencies for a certain crate type.
74 ///
75 /// The length of this vector is the same as the number of external crates used.
76 /// The value is None if the crate does not need to be linked (it was found
77 /// statically in another dylib), or Some(kind) if it needs to be linked as
78 /// `kind` (either static or dynamic).
79 pub type DependencyList = Vec<Linkage>;
80
81 /// A mapping of all required dependencies for a particular flavor of output.
82 ///
83 /// This is local to the tcx, and is generally relevant to one session.
84 pub type Dependencies = FxHashMap<config::CrateType, DependencyList>;
85
86 #[derive(Copy, Clone, PartialEq, Debug)]
87 pub enum Linkage {
88     NotLinked,
89     IncludedFromDylib,
90     Static,
91     Dynamic,
92 }
93
94 pub fn calculate<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) {
95     let sess = &tcx.sess;
96     let fmts = sess.crate_types.borrow().iter().map(|&ty| {
97         let linkage = calculate_type(tcx, ty);
98         verify_ok(tcx, &linkage);
99         (ty, linkage)
100     }).collect::<FxHashMap<_, _>>();
101     sess.abort_if_errors();
102     sess.dependency_formats.set(fmts);
103 }
104
105 fn calculate_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
106                             ty: config::CrateType) -> DependencyList {
107
108     let sess = &tcx.sess;
109
110     if !sess.opts.output_types.should_codegen() {
111         return Vec::new();
112     }
113
114     let preferred_linkage = match ty {
115         // cdylibs must have all static dependencies.
116         config::CrateType::Cdylib => Linkage::Static,
117
118         // Generating a dylib without `-C prefer-dynamic` means that we're going
119         // to try to eagerly statically link all dependencies. This is normally
120         // done for end-product dylibs, not intermediate products.
121         config::CrateType::Dylib if !sess.opts.cg.prefer_dynamic => Linkage::Static,
122         config::CrateType::Dylib => Linkage::Dynamic,
123
124         // If the global prefer_dynamic switch is turned off, or the final
125         // executable will be statically linked, prefer static crate linkage.
126         config::CrateType::Executable if !sess.opts.cg.prefer_dynamic ||
127             sess.crt_static() => Linkage::Static,
128         config::CrateType::Executable => Linkage::Dynamic,
129
130         // proc-macro crates are mostly cdylibs, but we also need metadata.
131         config::CrateType::ProcMacro => Linkage::Static,
132
133         // No linkage happens with rlibs, we just needed the metadata (which we
134         // got long ago), so don't bother with anything.
135         config::CrateType::Rlib => Linkage::NotLinked,
136
137         // staticlibs must have all static dependencies.
138         config::CrateType::Staticlib => Linkage::Static,
139     };
140
141     if preferred_linkage == Linkage::NotLinked {
142         // If the crate is not linked, there are no link-time dependencies.
143         return Vec::new();
144     }
145
146     if preferred_linkage == Linkage::Static {
147         // Attempt static linkage first. For dylibs and executables, we may be
148         // able to retry below with dynamic linkage.
149         if let Some(v) = attempt_static(tcx) {
150             return v;
151         }
152
153         // Staticlibs, cdylibs, and static executables must have all static
154         // dependencies. If any are not found, generate some nice pretty errors.
155         if ty == config::CrateType::Cdylib || ty == config::CrateType::Staticlib ||
156                 (ty == config::CrateType::Executable && sess.crt_static() &&
157                 !sess.target.target.options.crt_static_allows_dylibs) {
158             for &cnum in tcx.crates().iter() {
159                 if tcx.dep_kind(cnum).macros_only() { continue }
160                 let src = tcx.used_crate_source(cnum);
161                 if src.rlib.is_some() { continue }
162                 sess.err(&format!("crate `{}` required to be available in rlib format, \
163                                    but was not found in this form",
164                                   tcx.crate_name(cnum)));
165             }
166             return Vec::new();
167         }
168     }
169
170     let mut formats = FxHashMap::default();
171
172     // Sweep all crates for found dylibs. Add all dylibs, as well as their
173     // dependencies, ensuring there are no conflicts. The only valid case for a
174     // dependency to be relied upon twice is for both cases to rely on a dylib.
175     for &cnum in tcx.crates().iter() {
176         if tcx.dep_kind(cnum).macros_only() { continue }
177         let name = tcx.crate_name(cnum);
178         let src = tcx.used_crate_source(cnum);
179         if src.dylib.is_some() {
180             info!("adding dylib: {}", name);
181             add_library(tcx, cnum, RequireDynamic, &mut formats);
182             let deps = tcx.dylib_dependency_formats(cnum);
183             for &(depnum, style) in deps.iter() {
184                 info!("adding {:?}: {}", style, tcx.crate_name(depnum));
185                 add_library(tcx, depnum, style, &mut formats);
186             }
187         }
188     }
189
190     // Collect what we've got so far in the return vector.
191     let last_crate = tcx.crates().len();
192     let mut ret = (1..last_crate+1).map(|cnum| {
193         match formats.get(&CrateNum::new(cnum)) {
194             Some(&RequireDynamic) => Linkage::Dynamic,
195             Some(&RequireStatic) => Linkage::IncludedFromDylib,
196             None => Linkage::NotLinked,
197         }
198     }).collect::<Vec<_>>();
199
200     // Run through the dependency list again, and add any missing libraries as
201     // static libraries.
202     //
203     // If the crate hasn't been included yet and it's not actually required
204     // (e.g. it's an allocator) then we skip it here as well.
205     for &cnum in tcx.crates().iter() {
206         let src = tcx.used_crate_source(cnum);
207         if src.dylib.is_none() &&
208            !formats.contains_key(&cnum) &&
209            tcx.dep_kind(cnum) == DepKind::Explicit {
210             assert!(src.rlib.is_some() || src.rmeta.is_some());
211             info!("adding staticlib: {}", tcx.crate_name(cnum));
212             add_library(tcx, cnum, RequireStatic, &mut formats);
213             ret[cnum.as_usize() - 1] = Linkage::Static;
214         }
215     }
216
217     // We've gotten this far because we're emitting some form of a final
218     // artifact which means that we may need to inject dependencies of some
219     // form.
220     //
221     // Things like allocators and panic runtimes may not have been activated
222     // quite yet, so do so here.
223     activate_injected_dep(*sess.injected_panic_runtime.get(), &mut ret,
224                           &|cnum| tcx.is_panic_runtime(cnum));
225
226     // When dylib B links to dylib A, then when using B we must also link to A.
227     // It could be the case, however, that the rlib for A is present (hence we
228     // found metadata), but the dylib for A has since been removed.
229     //
230     // For situations like this, we perform one last pass over the dependencies,
231     // making sure that everything is available in the requested format.
232     for (cnum, kind) in ret.iter().enumerate() {
233         let cnum = CrateNum::new(cnum + 1);
234         let src = tcx.used_crate_source(cnum);
235         match *kind {
236             Linkage::NotLinked |
237             Linkage::IncludedFromDylib => {}
238             Linkage::Static if src.rlib.is_some() => continue,
239             Linkage::Dynamic if src.dylib.is_some() => continue,
240             kind => {
241                 let kind = match kind {
242                     Linkage::Static => "rlib",
243                     _ => "dylib",
244                 };
245                 sess.err(&format!("crate `{}` required to be available in {} format, \
246                                    but was not found in this form",
247                                   tcx.crate_name(cnum), kind));
248             }
249         }
250     }
251
252     ret
253 }
254
255 fn add_library(tcx: TyCtxt<'_, '_, '_>,
256                cnum: CrateNum,
257                link: LinkagePreference,
258                m: &mut FxHashMap<CrateNum, LinkagePreference>) {
259     match m.get(&cnum) {
260         Some(&link2) => {
261             // If the linkages differ, then we'd have two copies of the library
262             // if we continued linking. If the linkages are both static, then we
263             // would also have two copies of the library (static from two
264             // different locations).
265             //
266             // This error is probably a little obscure, but I imagine that it
267             // can be refined over time.
268             if link2 != link || link == RequireStatic {
269                 tcx.sess.struct_err(&format!("cannot satisfy dependencies so `{}` only \
270                                               shows up once", tcx.crate_name(cnum)))
271                     .help("having upstream crates all available in one format \
272                            will likely make this go away")
273                     .emit();
274             }
275         }
276         None => { m.insert(cnum, link); }
277     }
278 }
279
280 fn attempt_static<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>) -> Option<DependencyList> {
281     let sess = &tcx.sess;
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).map(|cnum| {
291         if tcx.dep_kind(CrateNum::new(cnum)) == DepKind::Explicit {
292             Linkage::Static
293         } else {
294             Linkage::NotLinked
295         }
296     }).collect::<Vec<_>>();
297
298     // Our allocator/panic runtime may not have been linked above if it wasn't
299     // explicitly linked, which is the case for any injected dependency. Handle
300     // that here and activate them.
301     activate_injected_dep(*sess.injected_panic_runtime.get(), &mut ret,
302                           &|cnum| tcx.is_panic_runtime(cnum));
303
304     Some(ret)
305 }
306
307 // Given a list of how to link upstream dependencies so far, ensure that an
308 // injected dependency is activated. This will not do anything if one was
309 // transitively included already (e.g. via a dylib or explicitly so).
310 //
311 // If an injected dependency was not found then we're guaranteed the
312 // metadata::creader module has injected that dependency (not listed as
313 // a required dependency) in one of the session's field. If this field is not
314 // set then this compilation doesn't actually need the dependency and we can
315 // also skip this step entirely.
316 fn activate_injected_dep(injected: Option<CrateNum>,
317                          list: &mut DependencyList,
318                          replaces_injected: &dyn Fn(CrateNum) -> bool) {
319     for (i, slot) in list.iter().enumerate() {
320         let cnum = CrateNum::new(i + 1);
321         if !replaces_injected(cnum) {
322             continue
323         }
324         if *slot != Linkage::NotLinked {
325             return
326         }
327     }
328     if let Some(injected) = injected {
329         let idx = injected.as_usize() - 1;
330         assert_eq!(list[idx], Linkage::NotLinked);
331         list[idx] = Linkage::Static;
332     }
333 }
334
335 // After the linkage for a crate has been determined we need to verify that
336 // there's only going to be one allocator in the output.
337 fn verify_ok<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, list: &[Linkage]) {
338     let sess = &tcx.sess;
339     if list.len() == 0 {
340         return
341     }
342     let mut panic_runtime = None;
343     for (i, linkage) in list.iter().enumerate() {
344         if let Linkage::NotLinked = *linkage {
345             continue
346         }
347         let cnum = CrateNum::new(i + 1);
348
349         if tcx.is_panic_runtime(cnum) {
350             if let Some((prev, _)) = panic_runtime {
351                 let prev_name = tcx.crate_name(prev);
352                 let cur_name = tcx.crate_name(cnum);
353                 sess.err(&format!("cannot link together two \
354                                    panic runtimes: {} and {}",
355                                   prev_name, cur_name));
356             }
357             panic_runtime = Some((cnum, tcx.panic_strategy(cnum)));
358         }
359     }
360
361     // If we found a panic runtime, then we know by this point that it's the
362     // only one, but we perform validation here that all the panic strategy
363     // compilation modes for the whole DAG are valid.
364     if let Some((cnum, found_strategy)) = panic_runtime {
365         let desired_strategy = sess.panic_strategy();
366
367         // First up, validate that our selected panic runtime is indeed exactly
368         // our same strategy.
369         if found_strategy != desired_strategy {
370             sess.err(&format!("the linked panic runtime `{}` is \
371                                not compiled with this crate's \
372                                panic strategy `{}`",
373                               tcx.crate_name(cnum),
374                               desired_strategy.desc()));
375         }
376
377         // Next up, verify that all other crates are compatible with this panic
378         // strategy. If the dep isn't linked, we ignore it, and if our strategy
379         // is abort then it's compatible with everything. Otherwise all crates'
380         // panic strategy must match our own.
381         for (i, linkage) in list.iter().enumerate() {
382             if let Linkage::NotLinked = *linkage {
383                 continue
384             }
385             if desired_strategy == PanicStrategy::Abort {
386                 continue
387             }
388             let cnum = CrateNum::new(i + 1);
389             let found_strategy = tcx.panic_strategy(cnum);
390             let is_compiler_builtins = tcx.is_compiler_builtins(cnum);
391             if is_compiler_builtins || desired_strategy == found_strategy {
392                 continue
393             }
394
395             sess.err(&format!("the crate `{}` is compiled with the \
396                                panic strategy `{}` which is \
397                                incompatible with this crate's \
398                                strategy of `{}`",
399                               tcx.crate_name(cnum),
400                               found_strategy.desc(),
401                               desired_strategy.desc()));
402         }
403     }
404 }