]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/dependency_format.rs
rollup merge of #17355 : gamazeps/issue17210
[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 std::collections::HashMap;
65 use syntax::ast;
66
67 use driver::session;
68 use driver::config;
69 use metadata::cstore;
70 use metadata::csearch;
71 use middle::ty;
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<Option<cstore::LinkagePreference>>;
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 = HashMap<config::CrateType, DependencyList>;
85
86 pub fn calculate(tcx: &ty::ctxt) {
87     let mut fmts = tcx.dependency_formats.borrow_mut();
88     for &ty in tcx.sess.crate_types.borrow().iter() {
89         fmts.insert(ty, calculate_type(&tcx.sess, ty));
90     }
91     tcx.sess.abort_if_errors();
92 }
93
94 fn calculate_type(sess: &session::Session,
95                   ty: config::CrateType) -> DependencyList {
96     match ty {
97         // If the global prefer_dynamic switch is turned off, first attempt
98         // static linkage (this can fail).
99         config::CrateTypeExecutable if !sess.opts.cg.prefer_dynamic => {
100             match attempt_static(sess) {
101                 Some(v) => return v,
102                 None => {}
103             }
104         }
105
106         // No linkage happens with rlibs, we just needed the metadata (which we
107         // got long ago), so don't bother with anything.
108         config::CrateTypeRlib => return Vec::new(),
109
110         // Staticlibs must have all static dependencies. If any fail to be
111         // found, we generate some nice pretty errors.
112         config::CrateTypeStaticlib => {
113             match attempt_static(sess) {
114                 Some(v) => return v,
115                 None => {}
116             }
117             sess.cstore.iter_crate_data(|cnum, data| {
118                 let src = sess.cstore.get_used_crate_source(cnum).unwrap();
119                 if src.rlib.is_some() { return }
120                 sess.err(format!("dependency `{}` not found in rlib format",
121                                  data.name).as_slice());
122             });
123             return Vec::new();
124         }
125
126         // Everything else falls through below
127         config::CrateTypeExecutable | config::CrateTypeDylib => {},
128     }
129
130     let mut formats = HashMap::new();
131
132     // Sweep all crates for found dylibs. Add all dylibs, as well as their
133     // dependencies, ensuring there are no conflicts. The only valid case for a
134     // dependency to be relied upon twice is for both cases to rely on a dylib.
135     sess.cstore.iter_crate_data(|cnum, data| {
136         let src = sess.cstore.get_used_crate_source(cnum).unwrap();
137         if src.dylib.is_some() {
138             add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
139             debug!("adding dylib: {}", data.name);
140             let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
141             for &(depnum, style) in deps.iter() {
142                 add_library(sess, depnum, style, &mut formats);
143                 debug!("adding {}: {}", style,
144                        sess.cstore.get_crate_data(depnum).name.clone());
145             }
146         }
147     });
148
149     // Collect what we've got so far in the return vector.
150     let mut ret = range(1, sess.cstore.next_crate_num()).map(|i| {
151         match formats.find(&i).map(|v| *v) {
152             v @ Some(cstore::RequireDynamic) => v,
153             _ => None,
154         }
155     }).collect::<Vec<_>>();
156
157     // Run through the dependency list again, and add any missing libraries as
158     // static libraries.
159     sess.cstore.iter_crate_data(|cnum, data| {
160         let src = sess.cstore.get_used_crate_source(cnum).unwrap();
161         if src.dylib.is_none() && !formats.contains_key(&cnum) {
162             assert!(src.rlib.is_some());
163             add_library(sess, cnum, cstore::RequireStatic, &mut formats);
164             *ret.get_mut(cnum as uint - 1) = Some(cstore::RequireStatic);
165             debug!("adding staticlib: {}", data.name);
166         }
167     });
168
169     // When dylib B links to dylib A, then when using B we must also link to A.
170     // It could be the case, however, that the rlib for A is present (hence we
171     // found metadata), but the dylib for A has since been removed.
172     //
173     // For situations like this, we perform one last pass over the dependencies,
174     // making sure that everything is available in the requested format.
175     for (cnum, kind) in ret.iter().enumerate() {
176         let cnum = cnum as ast::CrateNum;
177         let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
178         match *kind {
179             None => continue,
180             Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
181             Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
182             Some(kind) => {
183                 let data = sess.cstore.get_crate_data(cnum + 1);
184                 sess.err(format!("crate `{}` required to be available in {}, \
185                                   but it was not available in this form",
186                                  data.name,
187                                  match kind {
188                                      cstore::RequireStatic => "rlib",
189                                      cstore::RequireDynamic => "dylib",
190                                  }).as_slice());
191             }
192         }
193     }
194
195     return ret;
196 }
197
198 fn add_library(sess: &session::Session,
199                cnum: ast::CrateNum,
200                link: cstore::LinkagePreference,
201                m: &mut HashMap<ast::CrateNum, cstore::LinkagePreference>) {
202     match m.find(&cnum) {
203         Some(&link2) => {
204             // If the linkages differ, then we'd have two copies of the library
205             // if we continued linking. If the linkages are both static, then we
206             // would also have two copies of the library (static from two
207             // different locations).
208             //
209             // This error is probably a little obscure, but I imagine that it
210             // can be refined over time.
211             if link2 != link || link == cstore::RequireStatic {
212                 let data = sess.cstore.get_crate_data(cnum);
213                 sess.err(format!("cannot satisfy dependencies so `{}` only \
214                                   shows up once",
215                                  data.name).as_slice());
216                 sess.note("having upstream crates all available in one format \
217                            will likely make this go away");
218             }
219         }
220         None => { m.insert(cnum, link); }
221     }
222 }
223
224 fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
225     let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
226     if crates.iter().all(|&(_, ref p)| p.is_some()) {
227         Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())
228     } else {
229         None
230     }
231 }