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).
64 use hir::def_id::CrateNum;
68 use middle::cstore::DepKind;
69 use middle::cstore::LinkagePreference::{self, RequireStatic, RequireDynamic};
70 use util::nodemap::FxHashMap;
71 use rustc_back::PanicStrategy;
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<Linkage>;
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 = FxHashMap<config::CrateType, DependencyList>;
86 #[derive(Copy, Clone, PartialEq, Debug)]
94 pub fn calculate(sess: &session::Session) {
95 let mut fmts = sess.dependency_formats.borrow_mut();
96 for &ty in sess.crate_types.borrow().iter() {
97 let linkage = calculate_type(sess, ty);
98 verify_ok(sess, &linkage);
99 fmts.insert(ty, linkage);
101 sess.abort_if_errors();
104 fn calculate_type(sess: &session::Session,
105 ty: config::CrateType) -> DependencyList {
106 if !sess.opts.output_types.should_trans() {
111 // If the global prefer_dynamic switch is turned off, first attempt
112 // static linkage (this can fail).
113 config::CrateTypeExecutable if !sess.opts.cg.prefer_dynamic => {
114 if let Some(v) = attempt_static(sess) {
119 // No linkage happens with rlibs, we just needed the metadata (which we
120 // got long ago), so don't bother with anything.
121 config::CrateTypeRlib => return Vec::new(),
123 // Staticlibs and cdylibs must have all static dependencies. If any fail
124 // to be found, we generate some nice pretty errors.
125 config::CrateTypeStaticlib |
126 config::CrateTypeCdylib => {
127 if let Some(v) = attempt_static(sess) {
130 for cnum in sess.cstore.crates() {
131 if sess.cstore.dep_kind(cnum).macros_only() { continue }
132 let src = sess.cstore.used_crate_source(cnum);
133 if src.rlib.is_some() { continue }
134 sess.err(&format!("dependency `{}` not found in rlib format",
135 sess.cstore.crate_name(cnum)));
140 // Generating a dylib without `-C prefer-dynamic` means that we're going
141 // to try to eagerly statically link all dependencies. This is normally
142 // done for end-product dylibs, not intermediate products.
143 config::CrateTypeDylib if !sess.opts.cg.prefer_dynamic => {
144 if let Some(v) = attempt_static(sess) {
149 // Everything else falls through below. This will happen either with the
150 // `-C prefer-dynamic` or because we're a proc-macro crate. Note that
151 // proc-macro crates are required to be dylibs, and they're currently
152 // required to link to libsyntax as well.
153 config::CrateTypeExecutable |
154 config::CrateTypeDylib |
155 config::CrateTypeProcMacro => {},
158 let mut formats = FxHashMap();
160 // Sweep all crates for found dylibs. Add all dylibs, as well as their
161 // dependencies, ensuring there are no conflicts. The only valid case for a
162 // dependency to be relied upon twice is for both cases to rely on a dylib.
163 for cnum in sess.cstore.crates() {
164 if sess.cstore.dep_kind(cnum).macros_only() { continue }
165 let name = sess.cstore.crate_name(cnum);
166 let src = sess.cstore.used_crate_source(cnum);
167 if src.dylib.is_some() {
168 info!("adding dylib: {}", name);
169 add_library(sess, cnum, RequireDynamic, &mut formats);
170 let deps = sess.cstore.dylib_dependency_formats(cnum);
171 for &(depnum, style) in &deps {
172 info!("adding {:?}: {}", style,
173 sess.cstore.crate_name(depnum));
174 add_library(sess, depnum, style, &mut formats);
179 // Collect what we've got so far in the return vector.
180 let last_crate = sess.cstore.crates().len();
181 let mut ret = (1..last_crate+1).map(|cnum| {
182 match formats.get(&CrateNum::new(cnum)) {
183 Some(&RequireDynamic) => Linkage::Dynamic,
184 Some(&RequireStatic) => Linkage::IncludedFromDylib,
185 None => Linkage::NotLinked,
187 }).collect::<Vec<_>>();
189 // Run through the dependency list again, and add any missing libraries as
192 // If the crate hasn't been included yet and it's not actually required
193 // (e.g. it's an allocator) then we skip it here as well.
194 for cnum in sess.cstore.crates() {
195 let src = sess.cstore.used_crate_source(cnum);
196 if src.dylib.is_none() &&
197 !formats.contains_key(&cnum) &&
198 sess.cstore.dep_kind(cnum) == DepKind::Explicit {
199 assert!(src.rlib.is_some() || src.rmeta.is_some());
200 info!("adding staticlib: {}", sess.cstore.crate_name(cnum));
201 add_library(sess, cnum, RequireStatic, &mut formats);
202 ret[cnum.as_usize() - 1] = Linkage::Static;
206 // We've gotten this far because we're emitting some form of a final
207 // artifact which means that we may need to inject dependencies of some
210 // Things like allocators and panic runtimes may not have been activated
211 // quite yet, so do so here.
212 activate_injected_dep(sess.injected_allocator.get(), &mut ret,
213 &|cnum| sess.cstore.is_allocator(cnum));
214 activate_injected_dep(sess.injected_panic_runtime.get(), &mut ret,
215 &|cnum| sess.cstore.is_panic_runtime(cnum));
217 // When dylib B links to dylib A, then when using B we must also link to A.
218 // It could be the case, however, that the rlib for A is present (hence we
219 // found metadata), but the dylib for A has since been removed.
221 // For situations like this, we perform one last pass over the dependencies,
222 // making sure that everything is available in the requested format.
223 for (cnum, kind) in ret.iter().enumerate() {
224 let cnum = CrateNum::new(cnum + 1);
225 let src = sess.cstore.used_crate_source(cnum);
228 Linkage::IncludedFromDylib => {}
229 Linkage::Static if src.rlib.is_some() => continue,
230 Linkage::Dynamic if src.dylib.is_some() => continue,
232 let kind = match kind {
233 Linkage::Static => "rlib",
236 let name = sess.cstore.crate_name(cnum);
237 sess.err(&format!("crate `{}` required to be available in {}, \
238 but it was not available in this form",
247 fn add_library(sess: &session::Session,
249 link: LinkagePreference,
250 m: &mut FxHashMap<CrateNum, LinkagePreference>) {
253 // If the linkages differ, then we'd have two copies of the library
254 // if we continued linking. If the linkages are both static, then we
255 // would also have two copies of the library (static from two
256 // different locations).
258 // This error is probably a little obscure, but I imagine that it
259 // can be refined over time.
260 if link2 != link || link == RequireStatic {
261 sess.struct_err(&format!("cannot satisfy dependencies so `{}` only \
262 shows up once", sess.cstore.crate_name(cnum)))
263 .help("having upstream crates all available in one format \
264 will likely make this go away")
268 None => { m.insert(cnum, link); }
272 fn attempt_static(sess: &session::Session) -> Option<DependencyList> {
273 let crates = sess.cstore.used_crates(RequireStatic);
274 if !crates.iter().by_ref().all(|&(_, ref p)| p.is_some()) {
278 // All crates are available in an rlib format, so we're just going to link
279 // everything in explicitly so long as it's actually required.
280 let last_crate = sess.cstore.crates().len();
281 let mut ret = (1..last_crate+1).map(|cnum| {
282 if sess.cstore.dep_kind(CrateNum::new(cnum)) == DepKind::Explicit {
287 }).collect::<Vec<_>>();
289 // Our allocator/panic runtime may not have been linked above if it wasn't
290 // explicitly linked, which is the case for any injected dependency. Handle
291 // that here and activate them.
292 activate_injected_dep(sess.injected_allocator.get(), &mut ret,
293 &|cnum| sess.cstore.is_allocator(cnum));
294 activate_injected_dep(sess.injected_panic_runtime.get(), &mut ret,
295 &|cnum| sess.cstore.is_panic_runtime(cnum));
300 // Given a list of how to link upstream dependencies so far, ensure that an
301 // injected dependency is activated. This will not do anything if one was
302 // transitively included already (e.g. via a dylib or explicitly so).
304 // If an injected dependency was not found then we're guaranteed the
305 // metadata::creader module has injected that dependency (not listed as
306 // a required dependency) in one of the session's field. If this field is not
307 // set then this compilation doesn't actually need the dependency and we can
308 // also skip this step entirely.
309 fn activate_injected_dep(injected: Option<CrateNum>,
310 list: &mut DependencyList,
311 replaces_injected: &Fn(CrateNum) -> bool) {
312 for (i, slot) in list.iter().enumerate() {
313 let cnum = CrateNum::new(i + 1);
314 if !replaces_injected(cnum) {
317 if *slot != Linkage::NotLinked {
321 if let Some(injected) = injected {
322 let idx = injected.as_usize() - 1;
323 assert_eq!(list[idx], Linkage::NotLinked);
324 list[idx] = Linkage::Static;
328 // After the linkage for a crate has been determined we need to verify that
329 // there's only going to be one allocator in the output.
330 fn verify_ok(sess: &session::Session, list: &[Linkage]) {
334 let mut allocator = None;
335 let mut panic_runtime = None;
336 for (i, linkage) in list.iter().enumerate() {
337 if let Linkage::NotLinked = *linkage {
340 let cnum = CrateNum::new(i + 1);
341 if sess.cstore.is_allocator(cnum) {
342 if let Some(prev) = allocator {
343 let prev_name = sess.cstore.crate_name(prev);
344 let cur_name = sess.cstore.crate_name(cnum);
345 sess.err(&format!("cannot link together two \
346 allocators: {} and {}",
347 prev_name, cur_name));
349 allocator = Some(cnum);
352 if sess.cstore.is_panic_runtime(cnum) {
353 if let Some((prev, _)) = panic_runtime {
354 let prev_name = sess.cstore.crate_name(prev);
355 let cur_name = sess.cstore.crate_name(cnum);
356 sess.err(&format!("cannot link together two \
357 panic runtimes: {} and {}",
358 prev_name, cur_name));
360 panic_runtime = Some((cnum, sess.cstore.panic_strategy(cnum)));
364 // If we found a panic runtime, then we know by this point that it's the
365 // only one, but we perform validation here that all the panic strategy
366 // compilation modes for the whole DAG are valid.
367 if let Some((cnum, found_strategy)) = panic_runtime {
368 let desired_strategy = sess.panic_strategy();
370 // First up, validate that our selected panic runtime is indeed exactly
371 // our same strategy.
372 if found_strategy != desired_strategy {
373 sess.err(&format!("the linked panic runtime `{}` is \
374 not compiled with this crate's \
375 panic strategy `{}`",
376 sess.cstore.crate_name(cnum),
377 desired_strategy.desc()));
380 // Next up, verify that all other crates are compatible with this panic
381 // strategy. If the dep isn't linked, we ignore it, and if our strategy
382 // is abort then it's compatible with everything. Otherwise all crates'
383 // panic strategy must match our own.
384 for (i, linkage) in list.iter().enumerate() {
385 if let Linkage::NotLinked = *linkage {
388 if desired_strategy == PanicStrategy::Abort {
391 let cnum = CrateNum::new(i + 1);
392 let found_strategy = sess.cstore.panic_strategy(cnum);
393 if desired_strategy == found_strategy {
397 sess.err(&format!("the crate `{}` is compiled with the \
398 panic strategy `{}` which is \
399 incompatible with this crate's \
401 sess.cstore.crate_name(cnum),
402 found_strategy.desc(),
403 desired_strategy.desc()));