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.
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.
11 //! Resolution of mixing rlibs and dylibs
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).
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:
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.
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...
33 //! The current selection algorithm below looks mostly similar to:
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
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.
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).
69 use metadata::csearch;
71 use util::nodemap::FnvHashMap;
73 /// A list of dependencies for a certain crate type.
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>>;
81 /// A mapping of all required dependencies for a particular flavor of output.
83 /// This is local to the tcx, and is generally relevant to one session.
84 pub type Dependencies = FnvHashMap<config::CrateType, DependencyList>;
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));
91 tcx.sess.abort_if_errors();
94 fn calculate_type(sess: &session::Session,
95 ty: config::CrateType) -> DependencyList {
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) {
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(),
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) {
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",
126 // Generating a dylib without `-C prefer-dynamic` means that we're going
127 // to try to eagerly statically link all dependencies. This is normally
128 // done for end-product dylibs, not intermediate products.
129 config::CrateTypeDylib if !sess.opts.cg.prefer_dynamic => {
130 match attempt_static(sess) {
136 // Everything else falls through below
137 config::CrateTypeExecutable | config::CrateTypeDylib => {},
140 let mut formats = FnvHashMap();
142 // Sweep all crates for found dylibs. Add all dylibs, as well as their
143 // dependencies, ensuring there are no conflicts. The only valid case for a
144 // dependency to be relied upon twice is for both cases to rely on a dylib.
145 sess.cstore.iter_crate_data(|cnum, data| {
146 let src = sess.cstore.get_used_crate_source(cnum).unwrap();
147 if src.dylib.is_some() {
148 debug!("adding dylib: {}", data.name);
149 add_library(sess, cnum, cstore::RequireDynamic, &mut formats);
150 let deps = csearch::get_dylib_dependency_formats(&sess.cstore, cnum);
151 for &(depnum, style) in &deps {
152 debug!("adding {:?}: {}", style,
153 sess.cstore.get_crate_data(depnum).name.clone());
154 add_library(sess, depnum, style, &mut formats);
159 // Collect what we've got so far in the return vector.
160 let mut ret = (1..sess.cstore.next_crate_num()).map(|i| {
161 match formats.get(&i).cloned() {
162 v @ Some(cstore::RequireDynamic) => v,
165 }).collect::<Vec<_>>();
167 // Run through the dependency list again, and add any missing libraries as
169 sess.cstore.iter_crate_data(|cnum, data| {
170 let src = sess.cstore.get_used_crate_source(cnum).unwrap();
171 if src.dylib.is_none() && !formats.contains_key(&cnum) {
172 assert!(src.rlib.is_some());
173 debug!("adding staticlib: {}", data.name);
174 add_library(sess, cnum, cstore::RequireStatic, &mut formats);
175 ret[cnum as usize - 1] = Some(cstore::RequireStatic);
179 // When dylib B links to dylib A, then when using B we must also link to A.
180 // It could be the case, however, that the rlib for A is present (hence we
181 // found metadata), but the dylib for A has since been removed.
183 // For situations like this, we perform one last pass over the dependencies,
184 // making sure that everything is available in the requested format.
185 for (cnum, kind) in ret.iter().enumerate() {
186 let cnum = cnum as ast::CrateNum;
187 let src = sess.cstore.get_used_crate_source(cnum + 1).unwrap();
190 Some(cstore::RequireStatic) if src.rlib.is_some() => continue,
191 Some(cstore::RequireDynamic) if src.dylib.is_some() => continue,
193 let data = sess.cstore.get_crate_data(cnum + 1);
194 sess.err(&format!("crate `{}` required to be available in {}, \
195 but it was not available in this form",
198 cstore::RequireStatic => "rlib",
199 cstore::RequireDynamic => "dylib",
208 fn add_library(sess: &session::Session,
210 link: cstore::LinkagePreference,
211 m: &mut FnvHashMap<ast::CrateNum, cstore::LinkagePreference>) {
214 // If the linkages differ, then we'd have two copies of the library
215 // if we continued linking. If the linkages are both static, then we
216 // would also have two copies of the library (static from two
217 // different locations).
219 // This error is probably a little obscure, but I imagine that it
220 // can be refined over time.
221 if link2 != link || link == cstore::RequireStatic {
222 let data = sess.cstore.get_crate_data(cnum);
223 sess.err(&format!("cannot satisfy dependencies so `{}` only \
226 sess.help("having upstream crates all available in one format \
227 will likely make this go away");
230 None => { m.insert(cnum, link); }
234 fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
235 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
236 if crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) {
237 Some(crates.into_iter().map(|_| Some(cstore::RequireStatic)).collect())