]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/dependency_format.rs
Auto merge of #27643 - mitaa:get_item_, r=arielb1
[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 syntax::ast;
65
66 use session;
67 use session::config;
68 use metadata::cstore;
69 use metadata::csearch;
70 use util::nodemap::FnvHashMap;
71
72 /// A list of dependencies for a certain crate type.
73 ///
74 /// The length of this vector is the same as the number of external crates used.
75 /// The value is None if the crate does not need to be linked (it was found
76 /// statically in another dylib), or Some(kind) if it needs to be linked as
77 /// `kind` (either static or dynamic).
78 pub type DependencyList = Vec<Linkage>;
79
80 /// A mapping of all required dependencies for a particular flavor of output.
81 ///
82 /// This is local to the tcx, and is generally relevant to one session.
83 pub type Dependencies = FnvHashMap<config::CrateType, DependencyList>;
84
85 #[derive(Copy, Clone, PartialEq, Debug)]
86 pub enum Linkage {
87     NotLinked,
88     IncludedFromDylib,
89     Static,
90     Dynamic,
91 }
92
93 pub fn calculate(sess: &session::Session) {
94     let mut fmts = sess.dependency_formats.borrow_mut();
95     for &ty in sess.crate_types.borrow().iter() {
96         let linkage = calculate_type(sess, ty);
97         verify_ok(sess, &linkage);
98         fmts.insert(ty, linkage);
99     }
100     sess.abort_if_errors();
101 }
102
103 fn calculate_type(sess: &session::Session,
104                   ty: config::CrateType) -> DependencyList {
105     match ty {
106         // If the global prefer_dynamic switch is turned off, first attempt
107         // static linkage (this can fail).
108         config::CrateTypeExecutable if !sess.opts.cg.prefer_dynamic => {
109             match attempt_static(sess) {
110                 Some(v) => return v,
111                 None => {}
112             }
113         }
114
115         // No linkage happens with rlibs, we just needed the metadata (which we
116         // got long ago), so don't bother with anything.
117         config::CrateTypeRlib => return Vec::new(),
118
119         // Staticlibs must have all static dependencies. If any fail to be
120         // found, we generate some nice pretty errors.
121         config::CrateTypeStaticlib => {
122             match attempt_static(sess) {
123                 Some(v) => return v,
124                 None => {}
125             }
126             sess.cstore.iter_crate_data(|cnum, data| {
127                 let src = sess.cstore.get_used_crate_source(cnum).unwrap();
128                 if src.rlib.is_some() { return }
129                 sess.err(&format!("dependency `{}` not found in rlib format",
130                                  data.name));
131             });
132             return Vec::new();
133         }
134
135         // Generating a dylib without `-C prefer-dynamic` means that we're going
136         // to try to eagerly statically link all dependencies. This is normally
137         // done for end-product dylibs, not intermediate products.
138         config::CrateTypeDylib if !sess.opts.cg.prefer_dynamic => {
139             match attempt_static(sess) {
140                 Some(v) => return v,
141                 None => {}
142             }
143         }
144
145         // Everything else falls through below
146         config::CrateTypeExecutable | config::CrateTypeDylib => {},
147     }
148
149     let mut formats = FnvHashMap();
150
151     // Sweep all crates for found dylibs. Add all dylibs, as well as their
152     // dependencies, ensuring there are no conflicts. The only valid case for a
153     // dependency to be relied upon twice is for both cases to rely on a dylib.
154     sess.cstore.iter_crate_data(|cnum, data| {
155         let src = sess.cstore.get_used_crate_source(cnum).unwrap();
156         if src.dylib.is_some() {
157             info!("adding dylib: {}", data.name);
158             add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
159             let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
160             for &(depnum, style) in &deps {
161                 info!("adding {:?}: {}", style,
162                       sess.cstore.get_crate_data(depnum).name.clone());
163                 add_library(sess, depnum, style, &mut formats);
164             }
165         }
166     });
167
168     // Collect what we've got so far in the return vector.
169     let mut ret = (1..sess.cstore.next_crate_num()).map(|i| {
170         match formats.get(&i) {
171             Some(&cstore::RequireDynamic) => Linkage::Dynamic,
172             Some(&cstore::RequireStatic) => Linkage::IncludedFromDylib,
173             None => Linkage::NotLinked,
174         }
175     }).collect::<Vec<_>>();
176
177     // Run through the dependency list again, and add any missing libraries as
178     // static libraries.
179     //
180     // If the crate hasn't been included yet and it's not actually required
181     // (e.g. it's an allocator) then we skip it here as well.
182     sess.cstore.iter_crate_data(|cnum, data| {
183         let src = sess.cstore.get_used_crate_source(cnum).unwrap();
184         if src.dylib.is_none() &&
185            !formats.contains_key(&cnum) &&
186            data.explicitly_linked.get() {
187             assert!(src.rlib.is_some());
188             info!("adding staticlib: {}", data.name);
189             add_library(sess, cnum, cstore::RequireStatic, &mut formats);
190             ret[cnum as usize - 1] = Linkage::Static;
191         }
192     });
193
194     // We've gotten this far because we're emitting some form of a final
195     // artifact which means that we're going to need an allocator of some form.
196     // No allocator may have been required or linked so far, so activate one
197     // here if one isn't set.
198     activate_allocator(sess, &mut ret);
199
200     // When dylib B links to dylib A, then when using B we must also link to A.
201     // It could be the case, however, that the rlib for A is present (hence we
202     // found metadata), but the dylib for A has since been removed.
203     //
204     // For situations like this, we perform one last pass over the dependencies,
205     // making sure that everything is available in the requested format.
206     for (cnum, kind) in ret.iter().enumerate() {
207         let cnum = (cnum + 1) as ast::CrateNum;
208         let src = sess.cstore.get_used_crate_source(cnum).unwrap();
209         match *kind {
210             Linkage::NotLinked |
211             Linkage::IncludedFromDylib => {}
212             Linkage::Static if src.rlib.is_some() => continue,
213             Linkage::Dynamic if src.dylib.is_some() => continue,
214             kind => {
215                 let kind = match kind {
216                     Linkage::Static => "rlib",
217                     _ => "dylib",
218                 };
219                 let data = sess.cstore.get_crate_data(cnum);
220                 sess.err(&format!("crate `{}` required to be available in {}, \
221                                   but it was not available in this form",
222                                  data.name, kind));
223             }
224         }
225     }
226
227     return ret;
228 }
229
230 fn add_library(sess: &session::Session,
231                cnum: ast::CrateNum,
232                link: cstore::LinkagePreference,
233                m: &mut FnvHashMap<ast::CrateNum, cstore::LinkagePreference>) {
234     match m.get(&cnum) {
235         Some(&link2) => {
236             // If the linkages differ, then we'd have two copies of the library
237             // if we continued linking. If the linkages are both static, then we
238             // would also have two copies of the library (static from two
239             // different locations).
240             //
241             // This error is probably a little obscure, but I imagine that it
242             // can be refined over time.
243             if link2 != link || link == cstore::RequireStatic {
244                 let data = sess.cstore.get_crate_data(cnum);
245                 sess.err(&format!("cannot satisfy dependencies so `{}` only \
246                                    shows up once", data.name));
247                 sess.help("having upstream crates all available in one format \
248                            will likely make this go away");
249             }
250         }
251         None => { m.insert(cnum, link); }
252     }
253 }
254
255 fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
256     let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
257     if !crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) {
258         return None
259     }
260
261     // All crates are available in an rlib format, so we're just going to link
262     // everything in explicitly so long as it's actually required.
263     let mut ret = (1..sess.cstore.next_crate_num()).map(|cnum| {
264         if sess.cstore.get_crate_data(cnum).explicitly_linked.get() {
265             Linkage::Static
266         } else {
267             Linkage::NotLinked
268         }
269     }).collect::<Vec<_>>();
270
271     // Our allocator may not have been activated as it's not flagged with
272     // explicitly_linked, so flag it here if necessary.
273     activate_allocator(sess, &mut ret);
274
275     Some(ret)
276 }
277
278 // Given a list of how to link upstream dependencies so far, ensure that an
279 // allocator is activated. This will not do anything if one was transitively
280 // included already (e.g. via a dylib or explicitly so).
281 //
282 // If an allocator was not found then we're guaranteed the metadata::creader
283 // module has injected an allocator dependency (not listed as a required
284 // dependency) in the session's `injected_allocator` field. If this field is not
285 // set then this compilation doesn't actually need an allocator and we can also
286 // skip this step entirely.
287 fn activate_allocator(sess: &session::Session, list: &mut DependencyList) {
288     let mut allocator_found = false;
289     for (i, slot) in list.iter().enumerate() {
290         let cnum = (i + 1) as ast::CrateNum;
291         if !sess.cstore.get_crate_data(cnum).is_allocator() {
292             continue
293         }
294         if let Linkage::NotLinked = *slot {
295             continue
296         }
297         allocator_found = true;
298     }
299     if !allocator_found {
300         if let Some(injected_allocator) = sess.injected_allocator.get() {
301             let idx = injected_allocator as usize - 1;
302             assert_eq!(list[idx], Linkage::NotLinked);
303             list[idx] = Linkage::Static;
304         }
305     }
306 }
307
308 // After the linkage for a crate has been determined we need to verify that
309 // there's only going to be one allocator in the output.
310 fn verify_ok(sess: &session::Session, list: &[Linkage]) {
311     if list.len() == 0 {
312         return
313     }
314     let mut allocator = None;
315     for (i, linkage) in list.iter().enumerate() {
316         let cnum = (i + 1) as ast::CrateNum;
317         let data = sess.cstore.get_crate_data(cnum);
318         if !data.is_allocator() {
319             continue
320         }
321         if let Linkage::NotLinked = *linkage {
322             continue
323         }
324         if let Some(prev_alloc) = allocator {
325             let prev = sess.cstore.get_crate_data(prev_alloc);
326             sess.err(&format!("cannot link together two \
327                                allocators: {} and {}",
328                               prev.name(), data.name()));
329         }
330         allocator = Some(cnum);
331     }
332 }