]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/link.rs
d5486e84fc43123fc8bdbe99f94931f1e581af71
[rust.git] / src / librustc_trans / back / link.rs
1 // Copyright 2012-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 use super::archive::{ArchiveBuilder, ArchiveConfig};
12 use super::linker::{Linker, GnuLinker, MsvcLinker};
13 use super::rpath::RPathConfig;
14 use super::rpath;
15 use super::msvc;
16 use super::svh::Svh;
17 use session::config;
18 use session::config::NoDebugInfo;
19 use session::config::{OutputFilenames, Input, OutputTypeBitcode, OutputTypeExe, OutputTypeObject};
20 use session::search_paths::PathKind;
21 use session::Session;
22 use metadata::common::LinkMeta;
23 use metadata::filesearch::FileDoesntMatch;
24 use metadata::loader::METADATA_FILENAME;
25 use metadata::{encoder, cstore, filesearch, csearch, creader};
26 use middle::dependency_format::Linkage;
27 use middle::ty::{self, Ty};
28 use rustc::front::map::{PathElem, PathElems, PathName};
29 use trans::{CrateContext, CrateTranslation, gensym_name};
30 use util::common::time;
31 use util::sha2::{Digest, Sha256};
32 use util::fs::fix_windows_verbatim_for_gcc;
33 use rustc_back::tempdir::TempDir;
34
35 use std::env;
36 use std::ffi::OsString;
37 use std::fs::{self, PathExt};
38 use std::io::{self, Read, Write};
39 use std::mem;
40 use std::path::{Path, PathBuf};
41 use std::process::Command;
42 use std::str;
43 use flate;
44 use serialize::hex::ToHex;
45 use syntax::ast;
46 use syntax::codemap::Span;
47 use syntax::parse::token;
48 use syntax::attr::AttrMetaMethods;
49 use rustc_front::attr::AttrMetaMethods as FrontAttrMetaMethods;
50
51 use rustc_front::hir;
52
53 // RLIB LLVM-BYTECODE OBJECT LAYOUT
54 // Version 1
55 // Bytes    Data
56 // 0..10    "RUST_OBJECT" encoded in ASCII
57 // 11..14   format version as little-endian u32
58 // 15..22   size in bytes of deflate compressed LLVM bitcode as
59 //          little-endian u64
60 // 23..     compressed LLVM bitcode
61
62 // This is the "magic number" expected at the beginning of a LLVM bytecode
63 // object in an rlib.
64 pub const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT";
65
66 // The version number this compiler will write to bytecode objects in rlibs
67 pub const RLIB_BYTECODE_OBJECT_VERSION: u32 = 1;
68
69 // The offset in bytes the bytecode object format version number can be found at
70 pub const RLIB_BYTECODE_OBJECT_VERSION_OFFSET: usize = 11;
71
72 // The offset in bytes the size of the compressed bytecode can be found at in
73 // format version 1
74 pub const RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: usize =
75     RLIB_BYTECODE_OBJECT_VERSION_OFFSET + 4;
76
77 // The offset in bytes the compressed LLVM bytecode can be found at in format
78 // version 1
79 pub const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: usize =
80     RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET + 8;
81
82
83 /*
84  * Name mangling and its relationship to metadata. This is complex. Read
85  * carefully.
86  *
87  * The semantic model of Rust linkage is, broadly, that "there's no global
88  * namespace" between crates. Our aim is to preserve the illusion of this
89  * model despite the fact that it's not *quite* possible to implement on
90  * modern linkers. We initially didn't use system linkers at all, but have
91  * been convinced of their utility.
92  *
93  * There are a few issues to handle:
94  *
95  *  - Linkers operate on a flat namespace, so we have to flatten names.
96  *    We do this using the C++ namespace-mangling technique. Foo::bar
97  *    symbols and such.
98  *
99  *  - Symbols with the same name but different types need to get different
100  *    linkage-names. We do this by hashing a string-encoding of the type into
101  *    a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
102  *    we use SHA256) to "prevent collisions". This is not airtight but 16 hex
103  *    digits on uniform probability means you're going to need 2**32 same-name
104  *    symbols in the same process before you're even hitting birthday-paradox
105  *    collision probability.
106  *
107  *  - Symbols in different crates but with same names "within" the crate need
108  *    to get different linkage-names.
109  *
110  *  - The hash shown in the filename needs to be predictable and stable for
111  *    build tooling integration. It also needs to be using a hash function
112  *    which is easy to use from Python, make, etc.
113  *
114  * So here is what we do:
115  *
116  *  - Consider the package id; every crate has one (specified with crate_id
117  *    attribute).  If a package id isn't provided explicitly, we infer a
118  *    versionless one from the output name. The version will end up being 0.0
119  *    in this case. CNAME and CVERS are taken from this package id. For
120  *    example, github.com/mozilla/CNAME#CVERS.
121  *
122  *  - Define CMH as SHA256(crateid).
123  *
124  *  - Define CMH8 as the first 8 characters of CMH.
125  *
126  *  - Compile our crate to lib CNAME-CMH8-CVERS.so
127  *
128  *  - Define STH(sym) as SHA256(CMH, type_str(sym))
129  *
130  *  - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
131  *    name, non-name metadata, and type sense, and versioned in the way
132  *    system linkers understand.
133  */
134
135 pub fn find_crate_name(sess: Option<&Session>,
136                        attrs: &[ast::Attribute],
137                        input: &Input) -> String {
138     let validate = |s: String, span: Option<Span>| {
139         creader::validate_crate_name(sess, &s[..], span);
140         s
141     };
142
143     // Look in attributes 100% of the time to make sure the attribute is marked
144     // as used. After doing this, however, we still prioritize a crate name from
145     // the command line over one found in the #[crate_name] attribute. If we
146     // find both we ensure that they're the same later on as well.
147     let attr_crate_name = attrs.iter().find(|at| at.check_name("crate_name"))
148                                .and_then(|at| at.value_str().map(|s| (at, s)));
149
150     if let Some(sess) = sess {
151         if let Some(ref s) = sess.opts.crate_name {
152             if let Some((attr, ref name)) = attr_crate_name {
153                 if *s != &name[..] {
154                     let msg = format!("--crate-name and #[crate_name] are \
155                                        required to match, but `{}` != `{}`",
156                                       s, name);
157                     sess.span_err(attr.span, &msg[..]);
158                 }
159             }
160             return validate(s.clone(), None);
161         }
162     }
163
164     if let Some((attr, s)) = attr_crate_name {
165         return validate(s.to_string(), Some(attr.span));
166     }
167     if let Input::File(ref path) = *input {
168         if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
169             if s.starts_with("-") {
170                 let msg = format!("crate names cannot start with a `-`, but \
171                                    `{}` has a leading hyphen", s);
172                 if let Some(sess) = sess {
173                     sess.err(&msg);
174                 }
175             } else {
176                 return validate(s.replace("-", "_"), None);
177             }
178         }
179     }
180
181     "rust_out".to_string()
182 }
183
184 pub fn build_link_meta(sess: &Session, krate: &hir::Crate,
185                        name: String) -> LinkMeta {
186     let r = LinkMeta {
187         crate_name: name,
188         crate_hash: Svh::calculate(&sess.opts.cg.metadata, krate),
189     };
190     info!("{:?}", r);
191     return r;
192 }
193
194 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> String {
195     let output = symbol_hasher.result_bytes();
196     // 64 bits should be enough to avoid collisions.
197     output[.. 8].to_hex().to_string()
198 }
199
200
201 // This calculates STH for a symbol, as defined above
202 fn symbol_hash<'tcx>(tcx: &ty::ctxt<'tcx>,
203                      symbol_hasher: &mut Sha256,
204                      t: Ty<'tcx>,
205                      link_meta: &LinkMeta)
206                      -> String {
207     // NB: do *not* use abbrevs here as we want the symbol names
208     // to be independent of one another in the crate.
209
210     symbol_hasher.reset();
211     symbol_hasher.input_str(&link_meta.crate_name);
212     symbol_hasher.input_str("-");
213     symbol_hasher.input_str(link_meta.crate_hash.as_str());
214     for meta in tcx.sess.crate_metadata.borrow().iter() {
215         symbol_hasher.input_str(&meta[..]);
216     }
217     symbol_hasher.input_str("-");
218     symbol_hasher.input_str(&encoder::encoded_ty(tcx, t));
219     // Prefix with 'h' so that it never blends into adjacent digits
220     let mut hash = String::from("h");
221     hash.push_str(&truncated_hash_result(symbol_hasher));
222     hash
223 }
224
225 fn get_symbol_hash<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> String {
226     match ccx.type_hashcodes().borrow().get(&t) {
227         Some(h) => return h.to_string(),
228         None => {}
229     }
230
231     let mut symbol_hasher = ccx.symbol_hasher().borrow_mut();
232     let hash = symbol_hash(ccx.tcx(), &mut *symbol_hasher, t, ccx.link_meta());
233     ccx.type_hashcodes().borrow_mut().insert(t, hash.clone());
234     hash
235 }
236
237
238 // Name sanitation. LLVM will happily accept identifiers with weird names, but
239 // gas doesn't!
240 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
241 pub fn sanitize(s: &str) -> String {
242     let mut result = String::new();
243     for c in s.chars() {
244         match c {
245             // Escape these with $ sequences
246             '@' => result.push_str("$SP$"),
247             '*' => result.push_str("$BP$"),
248             '&' => result.push_str("$RF$"),
249             '<' => result.push_str("$LT$"),
250             '>' => result.push_str("$GT$"),
251             '(' => result.push_str("$LP$"),
252             ')' => result.push_str("$RP$"),
253             ',' => result.push_str("$C$"),
254
255             // '.' doesn't occur in types and functions, so reuse it
256             // for ':' and '-'
257             '-' | ':' => result.push('.'),
258
259             // These are legal symbols
260             'a' ... 'z'
261             | 'A' ... 'Z'
262             | '0' ... '9'
263             | '_' | '.' | '$' => result.push(c),
264
265             _ => {
266                 result.push('$');
267                 for c in c.escape_unicode().skip(1) {
268                     match c {
269                         '{' => {},
270                         '}' => result.push('$'),
271                         c => result.push(c),
272                     }
273                 }
274             }
275         }
276     }
277
278     // Underscore-qualify anything that didn't start as an ident.
279     if !result.is_empty() &&
280         result.as_bytes()[0] != '_' as u8 &&
281         ! (result.as_bytes()[0] as char).is_xid_start() {
282         return format!("_{}", &result[..]);
283     }
284
285     return result;
286 }
287
288 pub fn mangle<PI: Iterator<Item=PathElem>>(path: PI,
289                                            hash: Option<&str>) -> String {
290     // Follow C++ namespace-mangling style, see
291     // http://en.wikipedia.org/wiki/Name_mangling for more info.
292     //
293     // It turns out that on OSX you can actually have arbitrary symbols in
294     // function names (at least when given to LLVM), but this is not possible
295     // when using unix's linker. Perhaps one day when we just use a linker from LLVM
296     // we won't need to do this name mangling. The problem with name mangling is
297     // that it seriously limits the available characters. For example we can't
298     // have things like &T in symbol names when one would theoretically
299     // want them for things like impls of traits on that type.
300     //
301     // To be able to work on all platforms and get *some* reasonable output, we
302     // use C++ name-mangling.
303
304     let mut n = String::from("_ZN"); // _Z == Begin name-sequence, N == nested
305
306     fn push(n: &mut String, s: &str) {
307         let sani = sanitize(s);
308         n.push_str(&format!("{}{}", sani.len(), sani));
309     }
310
311     // First, connect each component with <len, name> pairs.
312     for e in path {
313         push(&mut n, &e.name().as_str())
314     }
315
316     match hash {
317         Some(s) => push(&mut n, s),
318         None => {}
319     }
320
321     n.push('E'); // End name-sequence.
322     n
323 }
324
325 pub fn exported_name(path: PathElems, hash: &str) -> String {
326     mangle(path, Some(hash))
327 }
328
329 pub fn mangle_exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, path: PathElems,
330                                       t: Ty<'tcx>, id: ast::NodeId) -> String {
331     let mut hash = get_symbol_hash(ccx, t);
332
333     // Paths can be completely identical for different nodes,
334     // e.g. `fn foo() { { fn a() {} } { fn a() {} } }`, so we
335     // generate unique characters from the node id. For now
336     // hopefully 3 characters is enough to avoid collisions.
337     const EXTRA_CHARS: &'static str =
338         "abcdefghijklmnopqrstuvwxyz\
339          ABCDEFGHIJKLMNOPQRSTUVWXYZ\
340          0123456789";
341     let id = id as usize;
342     let extra1 = id % EXTRA_CHARS.len();
343     let id = id / EXTRA_CHARS.len();
344     let extra2 = id % EXTRA_CHARS.len();
345     let id = id / EXTRA_CHARS.len();
346     let extra3 = id % EXTRA_CHARS.len();
347     hash.push(EXTRA_CHARS.as_bytes()[extra1] as char);
348     hash.push(EXTRA_CHARS.as_bytes()[extra2] as char);
349     hash.push(EXTRA_CHARS.as_bytes()[extra3] as char);
350
351     exported_name(path, &hash[..])
352 }
353
354 pub fn mangle_internal_name_by_type_and_seq<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
355                                                       t: Ty<'tcx>,
356                                                       name: &str) -> String {
357     let path = [PathName(token::intern(&t.to_string())),
358                 gensym_name(name)];
359     let hash = get_symbol_hash(ccx, t);
360     mangle(path.iter().cloned(), Some(&hash[..]))
361 }
362
363 pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> String {
364     mangle(path.chain(Some(gensym_name(flav))), None)
365 }
366
367 pub fn get_linker(sess: &Session) -> (String, Command) {
368     if let Some(ref linker) = sess.opts.cg.linker {
369         (linker.clone(), Command::new(linker))
370     } else if sess.target.target.options.is_like_msvc {
371         ("link.exe".to_string(), msvc::link_exe_cmd(sess))
372     } else {
373         (sess.target.target.options.linker.clone(),
374          Command::new(&sess.target.target.options.linker))
375     }
376 }
377
378 pub fn get_ar_prog(sess: &Session) -> String {
379     sess.opts.cg.ar.clone().unwrap_or_else(|| {
380         sess.target.target.options.ar.clone()
381     })
382 }
383
384 fn command_path(sess: &Session) -> OsString {
385     // The compiler's sysroot often has some bundled tools, so add it to the
386     // PATH for the child.
387     let mut new_path = sess.host_filesearch(PathKind::All)
388                            .get_tools_search_paths();
389     if let Some(path) = env::var_os("PATH") {
390         new_path.extend(env::split_paths(&path));
391     }
392     env::join_paths(new_path).unwrap()
393 }
394
395 pub fn remove(sess: &Session, path: &Path) {
396     match fs::remove_file(path) {
397         Ok(..) => {}
398         Err(e) => {
399             sess.err(&format!("failed to remove {}: {}",
400                              path.display(),
401                              e));
402         }
403     }
404 }
405
406 /// Perform the linkage portion of the compilation phase. This will generate all
407 /// of the requested outputs for this compilation session.
408 pub fn link_binary(sess: &Session,
409                    trans: &CrateTranslation,
410                    outputs: &OutputFilenames,
411                    crate_name: &str) -> Vec<PathBuf> {
412     let mut out_filenames = Vec::new();
413     for &crate_type in sess.crate_types.borrow().iter() {
414         if invalid_output_for_target(sess, crate_type) {
415             sess.bug(&format!("invalid output type `{:?}` for target os `{}`",
416                              crate_type, sess.opts.target_triple));
417         }
418         let out_file = link_binary_output(sess, trans, crate_type, outputs,
419                                           crate_name);
420         out_filenames.push(out_file);
421     }
422
423     // Remove the temporary object file and metadata if we aren't saving temps
424     if !sess.opts.cg.save_temps {
425         for obj in object_filenames(sess, outputs) {
426             remove(sess, &obj);
427         }
428         remove(sess, &outputs.with_extension("metadata.o"));
429     }
430
431     out_filenames
432 }
433
434
435 /// Returns default crate type for target
436 ///
437 /// Default crate type is used when crate type isn't provided neither
438 /// through cmd line arguments nor through crate attributes
439 ///
440 /// It is CrateTypeExecutable for all platforms but iOS as there is no
441 /// way to run iOS binaries anyway without jailbreaking and
442 /// interaction with Rust code through static library is the only
443 /// option for now
444 pub fn default_output_for_target(sess: &Session) -> config::CrateType {
445     if !sess.target.target.options.executables {
446         config::CrateTypeStaticlib
447     } else {
448         config::CrateTypeExecutable
449     }
450 }
451
452 /// Checks if target supports crate_type as output
453 pub fn invalid_output_for_target(sess: &Session,
454                                  crate_type: config::CrateType) -> bool {
455     match (sess.target.target.options.dynamic_linking,
456            sess.target.target.options.executables, crate_type) {
457         (false, _, config::CrateTypeDylib) => true,
458         (_, false, config::CrateTypeExecutable) => true,
459         _ => false
460     }
461 }
462
463 fn is_writeable(p: &Path) -> bool {
464     match p.metadata() {
465         Err(..) => true,
466         Ok(m) => !m.permissions().readonly()
467     }
468 }
469
470 pub fn filename_for_input(sess: &Session,
471                           crate_type: config::CrateType,
472                           crate_name: &str,
473                           outputs: &OutputFilenames) -> PathBuf {
474     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
475     match crate_type {
476         config::CrateTypeRlib => {
477             outputs.out_directory.join(&format!("lib{}.rlib", libname))
478         }
479         config::CrateTypeDylib => {
480             let (prefix, suffix) = (&sess.target.target.options.dll_prefix,
481                                     &sess.target.target.options.dll_suffix);
482             outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
483                                                 suffix))
484         }
485         config::CrateTypeStaticlib => {
486             outputs.out_directory.join(&format!("lib{}.a", libname))
487         }
488         config::CrateTypeExecutable => {
489             let suffix = &sess.target.target.options.exe_suffix;
490             let out_filename = outputs.path(OutputTypeExe);
491             if suffix.is_empty() {
492                 out_filename.to_path_buf()
493             } else {
494                 out_filename.with_extension(&suffix[1..])
495             }
496         }
497     }
498 }
499
500 pub fn each_linked_rlib(sess: &Session,
501                         f: &mut FnMut(ast::CrateNum, &Path)) {
502     let crates = sess.cstore.get_used_crates(cstore::RequireStatic).into_iter();
503     let fmts = sess.dependency_formats.borrow();
504     let fmts = fmts.get(&config::CrateTypeExecutable).or_else(|| {
505         fmts.get(&config::CrateTypeStaticlib)
506     }).unwrap_or_else(|| {
507         sess.bug("could not find formats for rlibs")
508     });
509     for (cnum, path) in crates {
510         match fmts[cnum as usize - 1] {
511             Linkage::NotLinked | Linkage::IncludedFromDylib => continue,
512             _ => {}
513         }
514         let name = sess.cstore.get_crate_data(cnum).name.clone();
515         let path = match path {
516             Some(p) => p,
517             None => {
518                 sess.fatal(&format!("could not find rlib for: `{}`", name));
519             }
520         };
521         f(cnum, &path);
522     }
523 }
524
525 fn link_binary_output(sess: &Session,
526                       trans: &CrateTranslation,
527                       crate_type: config::CrateType,
528                       outputs: &OutputFilenames,
529                       crate_name: &str) -> PathBuf {
530     let objects = object_filenames(sess, outputs);
531     let out_filename = match outputs.single_output_file {
532         Some(ref file) => file.clone(),
533         None => filename_for_input(sess, crate_type, crate_name, outputs),
534     };
535
536     // Make sure files are writeable.  Mac, FreeBSD, and Windows system linkers
537     // check this already -- however, the Linux linker will happily overwrite a
538     // read-only file.  We should be consistent.
539     for file in objects.iter().chain(Some(&out_filename)) {
540         if !is_writeable(file) {
541             sess.fatal(&format!("output file {} is not writeable -- check its \
542                                 permissions", file.display()));
543         }
544     }
545
546     let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
547     match crate_type {
548         config::CrateTypeRlib => {
549             link_rlib(sess, Some(trans), &objects, &out_filename,
550                       tmpdir.path()).build();
551         }
552         config::CrateTypeStaticlib => {
553             link_staticlib(sess, &objects, &out_filename, tmpdir.path());
554         }
555         config::CrateTypeExecutable => {
556             link_natively(sess, false, &objects, &out_filename, trans, outputs,
557                           tmpdir.path());
558         }
559         config::CrateTypeDylib => {
560             link_natively(sess, true, &objects, &out_filename, trans, outputs,
561                           tmpdir.path());
562         }
563     }
564
565     out_filename
566 }
567
568 fn object_filenames(sess: &Session, outputs: &OutputFilenames) -> Vec<PathBuf> {
569     (0..sess.opts.cg.codegen_units).map(|i| {
570         let ext = format!("{}.o", i);
571         outputs.temp_path(OutputTypeObject).with_extension(&ext)
572     }).collect()
573 }
574
575 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
576     let mut search = Vec::new();
577     sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
578         search.push(path.to_path_buf());
579         FileDoesntMatch
580     });
581     return search;
582 }
583
584 fn archive_config<'a>(sess: &'a Session,
585                       output: &Path,
586                       input: Option<&Path>) -> ArchiveConfig<'a> {
587     ArchiveConfig {
588         sess: sess,
589         dst: output.to_path_buf(),
590         src: input.map(|p| p.to_path_buf()),
591         lib_search_paths: archive_search_paths(sess),
592         ar_prog: get_ar_prog(sess),
593         command_path: command_path(sess),
594     }
595 }
596
597 // Create an 'rlib'
598 //
599 // An rlib in its current incarnation is essentially a renamed .a file. The
600 // rlib primarily contains the object file of the crate, but it also contains
601 // all of the object files from native libraries. This is done by unzipping
602 // native libraries and inserting all of the contents into this archive.
603 fn link_rlib<'a>(sess: &'a Session,
604                  trans: Option<&CrateTranslation>, // None == no metadata/bytecode
605                  objects: &[PathBuf],
606                  out_filename: &Path,
607                  tmpdir: &Path) -> ArchiveBuilder<'a> {
608     info!("preparing rlib from {:?} to {:?}", objects, out_filename);
609     let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
610     for obj in objects {
611         ab.add_file(obj);
612     }
613
614     for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() {
615         match kind {
616             cstore::NativeStatic => ab.add_native_library(&l).unwrap(),
617             cstore::NativeFramework | cstore::NativeUnknown => {}
618         }
619     }
620
621     // After adding all files to the archive, we need to update the
622     // symbol table of the archive.
623     ab.update_symbols();
624
625     // For OSX/iOS, we must be careful to update symbols only when adding
626     // object files.  We're about to start adding non-object files, so run
627     // `ar` now to process the object files.
628     if sess.target.target.options.is_like_osx && !ab.using_llvm() {
629         ab.build();
630     }
631
632     // Note that it is important that we add all of our non-object "magical
633     // files" *after* all of the object files in the archive. The reason for
634     // this is as follows:
635     //
636     // * When performing LTO, this archive will be modified to remove
637     //   objects from above. The reason for this is described below.
638     //
639     // * When the system linker looks at an archive, it will attempt to
640     //   determine the architecture of the archive in order to see whether its
641     //   linkable.
642     //
643     //   The algorithm for this detection is: iterate over the files in the
644     //   archive. Skip magical SYMDEF names. Interpret the first file as an
645     //   object file. Read architecture from the object file.
646     //
647     // * As one can probably see, if "metadata" and "foo.bc" were placed
648     //   before all of the objects, then the architecture of this archive would
649     //   not be correctly inferred once 'foo.o' is removed.
650     //
651     // Basically, all this means is that this code should not move above the
652     // code above.
653     match trans {
654         Some(trans) => {
655             // Instead of putting the metadata in an object file section, rlibs
656             // contain the metadata in a separate file. We use a temp directory
657             // here so concurrent builds in the same directory don't try to use
658             // the same filename for metadata (stomping over one another)
659             let metadata = tmpdir.join(METADATA_FILENAME);
660             match fs::File::create(&metadata).and_then(|mut f| {
661                 f.write_all(&trans.metadata)
662             }) {
663                 Ok(..) => {}
664                 Err(e) => {
665                     sess.fatal(&format!("failed to write {}: {}",
666                                         metadata.display(), e));
667                 }
668             }
669             ab.add_file(&metadata);
670
671             // For LTO purposes, the bytecode of this library is also inserted
672             // into the archive.  If codegen_units > 1, we insert each of the
673             // bitcode files.
674             for obj in objects {
675                 // Note that we make sure that the bytecode filename in the
676                 // archive is never exactly 16 bytes long by adding a 16 byte
677                 // extension to it. This is to work around a bug in LLDB that
678                 // would cause it to crash if the name of a file in an archive
679                 // was exactly 16 bytes.
680                 let bc_filename = obj.with_extension("bc");
681                 let bc_deflated_filename = tmpdir.join({
682                     obj.with_extension("bytecode.deflate").file_name().unwrap()
683                 });
684
685                 let mut bc_data = Vec::new();
686                 match fs::File::open(&bc_filename).and_then(|mut f| {
687                     f.read_to_end(&mut bc_data)
688                 }) {
689                     Ok(..) => {}
690                     Err(e) => sess.fatal(&format!("failed to read bytecode: {}",
691                                                  e))
692                 }
693
694                 let bc_data_deflated = flate::deflate_bytes(&bc_data[..]);
695
696                 let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) {
697                     Ok(file) => file,
698                     Err(e) => {
699                         sess.fatal(&format!("failed to create compressed \
700                                              bytecode file: {}", e))
701                     }
702                 };
703
704                 match write_rlib_bytecode_object_v1(&mut bc_file_deflated,
705                                                     &bc_data_deflated) {
706                     Ok(()) => {}
707                     Err(e) => {
708                         sess.fatal(&format!("failed to write compressed \
709                                              bytecode: {}", e));
710                     }
711                 };
712
713                 ab.add_file(&bc_deflated_filename);
714
715                 // See the bottom of back::write::run_passes for an explanation
716                 // of when we do and don't keep .0.bc files around.
717                 let user_wants_numbered_bitcode =
718                         sess.opts.output_types.contains(&OutputTypeBitcode) &&
719                         sess.opts.cg.codegen_units > 1;
720                 if !sess.opts.cg.save_temps && !user_wants_numbered_bitcode {
721                     remove(sess, &bc_filename);
722                 }
723             }
724
725             // After adding all files to the archive, we need to update the
726             // symbol table of the archive. This currently dies on OSX (see
727             // #11162), and isn't necessary there anyway
728             if !sess.target.target.options.is_like_osx || ab.using_llvm() {
729                 ab.update_symbols();
730             }
731         }
732
733         None => {}
734     }
735
736     ab
737 }
738
739 fn write_rlib_bytecode_object_v1(writer: &mut Write,
740                                  bc_data_deflated: &[u8]) -> io::Result<()> {
741     let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
742
743     try!(writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC));
744     try!(writer.write_all(&[1, 0, 0, 0]));
745     try!(writer.write_all(&[
746         (bc_data_deflated_size >>  0) as u8,
747         (bc_data_deflated_size >>  8) as u8,
748         (bc_data_deflated_size >> 16) as u8,
749         (bc_data_deflated_size >> 24) as u8,
750         (bc_data_deflated_size >> 32) as u8,
751         (bc_data_deflated_size >> 40) as u8,
752         (bc_data_deflated_size >> 48) as u8,
753         (bc_data_deflated_size >> 56) as u8,
754     ]));
755     try!(writer.write_all(&bc_data_deflated));
756
757     let number_of_bytes_written_so_far =
758         RLIB_BYTECODE_OBJECT_MAGIC.len() +                // magic id
759         mem::size_of_val(&RLIB_BYTECODE_OBJECT_VERSION) + // version
760         mem::size_of_val(&bc_data_deflated_size) +        // data size field
761         bc_data_deflated_size as usize;                    // actual data
762
763     // If the number of bytes written to the object so far is odd, add a
764     // padding byte to make it even. This works around a crash bug in LLDB
765     // (see issue #15950)
766     if number_of_bytes_written_so_far % 2 == 1 {
767         try!(writer.write_all(&[0]));
768     }
769
770     return Ok(());
771 }
772
773 // Create a static archive
774 //
775 // This is essentially the same thing as an rlib, but it also involves adding
776 // all of the upstream crates' objects into the archive. This will slurp in
777 // all of the native libraries of upstream dependencies as well.
778 //
779 // Additionally, there's no way for us to link dynamic libraries, so we warn
780 // about all dynamic library dependencies that they're not linked in.
781 //
782 // There's no need to include metadata in a static archive, so ensure to not
783 // link in the metadata object file (and also don't prepare the archive with a
784 // metadata file).
785 fn link_staticlib(sess: &Session, objects: &[PathBuf], out_filename: &Path,
786                   tempdir: &Path) {
787     let mut ab = link_rlib(sess, None, objects, out_filename, tempdir);
788     if sess.target.target.options.is_like_osx && !ab.using_llvm() {
789         ab.build();
790     }
791     if !sess.target.target.options.no_compiler_rt {
792         ab.add_native_library("compiler-rt").unwrap();
793     }
794
795     let mut all_native_libs = vec![];
796
797     each_linked_rlib(sess, &mut |cnum, path| {
798         let name = sess.cstore.get_crate_data(cnum).name();
799         ab.add_rlib(path, &name, sess.lto()).unwrap();
800
801         let native_libs = csearch::get_native_libraries(&sess.cstore, cnum);
802         all_native_libs.extend(native_libs);
803     });
804
805     ab.update_symbols();
806     ab.build();
807
808     if !all_native_libs.is_empty() {
809         sess.note("link against the following native artifacts when linking against \
810                   this static library");
811         sess.note("the order and any duplication can be significant on some platforms, \
812                   and so may need to be preserved");
813     }
814
815     for &(kind, ref lib) in &all_native_libs {
816         let name = match kind {
817             cstore::NativeStatic => "static library",
818             cstore::NativeUnknown => "library",
819             cstore::NativeFramework => "framework",
820         };
821         sess.note(&format!("{}: {}", name, *lib));
822     }
823 }
824
825 // Create a dynamic library or executable
826 //
827 // This will invoke the system linker/cc to create the resulting file. This
828 // links to all upstream files as well.
829 fn link_natively(sess: &Session, dylib: bool,
830                  objects: &[PathBuf], out_filename: &Path,
831                  trans: &CrateTranslation,
832                  outputs: &OutputFilenames,
833                  tmpdir: &Path) {
834     info!("preparing dylib? ({}) from {:?} to {:?}", dylib, objects,
835           out_filename);
836
837     // The invocations of cc share some flags across platforms
838     let (pname, mut cmd) = get_linker(sess);
839     cmd.env("PATH", command_path(sess));
840
841     let root = sess.target_filesearch(PathKind::Native).get_lib_path();
842     cmd.args(&sess.target.target.options.pre_link_args);
843     for obj in &sess.target.target.options.pre_link_objects {
844         cmd.arg(root.join(obj));
845     }
846
847     {
848         let mut linker = if sess.target.target.options.is_like_msvc {
849             Box::new(MsvcLinker { cmd: &mut cmd, sess: &sess }) as Box<Linker>
850         } else {
851             Box::new(GnuLinker { cmd: &mut cmd, sess: &sess }) as Box<Linker>
852         };
853         link_args(&mut *linker, sess, dylib, tmpdir,
854                   objects, out_filename, trans, outputs);
855         if !sess.target.target.options.no_compiler_rt {
856             linker.link_staticlib("compiler-rt");
857         }
858     }
859     for obj in &sess.target.target.options.post_link_objects {
860         cmd.arg(root.join(obj));
861     }
862     cmd.args(&sess.target.target.options.post_link_args);
863
864     if sess.opts.debugging_opts.print_link_args {
865         println!("{:?}", &cmd);
866     }
867
868     // May have not found libraries in the right formats.
869     sess.abort_if_errors();
870
871     // Invoke the system linker
872     info!("{:?}", &cmd);
873     let prog = time(sess.time_passes(), "running linker", || cmd.output());
874     match prog {
875         Ok(prog) => {
876             if !prog.status.success() {
877                 sess.err(&format!("linking with `{}` failed: {}",
878                                  pname,
879                                  prog.status));
880                 sess.note(&format!("{:?}", &cmd));
881                 let mut output = prog.stderr.clone();
882                 output.push_all(&prog.stdout);
883                 sess.note(str::from_utf8(&output[..]).unwrap());
884                 sess.abort_if_errors();
885             }
886             info!("linker stderr:\n{}", String::from_utf8(prog.stderr).unwrap());
887             info!("linker stdout:\n{}", String::from_utf8(prog.stdout).unwrap());
888         },
889         Err(e) => {
890             sess.fatal(&format!("could not exec the linker `{}`: {}", pname, e));
891         }
892     }
893
894
895     // On OSX, debuggers need this utility to get run to do some munging of
896     // the symbols
897     if sess.target.target.options.is_like_osx && sess.opts.debuginfo != NoDebugInfo {
898         match Command::new("dsymutil").arg(out_filename).output() {
899             Ok(..) => {}
900             Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
901         }
902     }
903 }
904
905 fn link_args(cmd: &mut Linker,
906              sess: &Session,
907              dylib: bool,
908              tmpdir: &Path,
909              objects: &[PathBuf],
910              out_filename: &Path,
911              trans: &CrateTranslation,
912              outputs: &OutputFilenames) {
913
914     // The default library location, we need this to find the runtime.
915     // The location of crates will be determined as needed.
916     let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
917
918     // target descriptor
919     let t = &sess.target.target;
920
921     cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
922     for obj in objects {
923         cmd.add_object(obj);
924     }
925     cmd.output_filename(out_filename);
926
927     // If we're building a dynamic library then some platforms need to make sure
928     // that all symbols are exported correctly from the dynamic library.
929     if dylib {
930         cmd.export_symbols(sess, trans, tmpdir);
931     }
932
933     // When linking a dynamic library, we put the metadata into a section of the
934     // executable. This metadata is in a separate object file from the main
935     // object file, so we link that in here.
936     if dylib {
937         cmd.add_object(&outputs.with_extension("metadata.o"));
938     }
939
940     // Try to strip as much out of the generated object by removing unused
941     // sections if possible. See more comments in linker.rs
942     cmd.gc_sections(dylib);
943
944     let used_link_args = sess.cstore.get_used_link_args().borrow();
945
946     if !dylib && t.options.position_independent_executables {
947         let empty_vec = Vec::new();
948         let empty_str = String::new();
949         let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
950         let mut args = args.iter().chain(used_link_args.iter());
951         let relocation_model = sess.opts.cg.relocation_model.as_ref()
952                                    .unwrap_or(&empty_str);
953         if (t.options.relocation_model == "pic" || *relocation_model == "pic")
954             && !args.any(|x| *x == "-static") {
955             cmd.position_independent_executable();
956         }
957     }
958
959     // Pass optimization flags down to the linker.
960     cmd.optimize();
961
962     // Pass debuginfo flags down to the linker.
963     cmd.debuginfo();
964
965     // We want to prevent the compiler from accidentally leaking in any system
966     // libraries, so we explicitly ask gcc to not link to any libraries by
967     // default. Note that this does not happen for windows because windows pulls
968     // in some large number of libraries and I couldn't quite figure out which
969     // subset we wanted.
970     cmd.no_default_libraries();
971
972     // Take careful note of the ordering of the arguments we pass to the linker
973     // here. Linkers will assume that things on the left depend on things to the
974     // right. Things on the right cannot depend on things on the left. This is
975     // all formally implemented in terms of resolving symbols (libs on the right
976     // resolve unknown symbols of libs on the left, but not vice versa).
977     //
978     // For this reason, we have organized the arguments we pass to the linker as
979     // such:
980     //
981     //  1. The local object that LLVM just generated
982     //  2. Upstream rust libraries
983     //  3. Local native libraries
984     //  4. Upstream native libraries
985     //
986     // This is generally fairly natural, but some may expect 2 and 3 to be
987     // swapped. The reason that all native libraries are put last is that it's
988     // not recommended for a native library to depend on a symbol from a rust
989     // crate. If this is the case then a staticlib crate is recommended, solving
990     // the problem.
991     //
992     // Additionally, it is occasionally the case that upstream rust libraries
993     // depend on a local native library. In the case of libraries such as
994     // lua/glfw/etc the name of the library isn't the same across all platforms,
995     // so only the consumer crate of a library knows the actual name. This means
996     // that downstream crates will provide the #[link] attribute which upstream
997     // crates will depend on. Hence local native libraries are after out
998     // upstream rust crates.
999     //
1000     // In theory this means that a symbol in an upstream native library will be
1001     // shadowed by a local native library when it wouldn't have been before, but
1002     // this kind of behavior is pretty platform specific and generally not
1003     // recommended anyway, so I don't think we're shooting ourself in the foot
1004     // much with that.
1005     add_upstream_rust_crates(cmd, sess, dylib, tmpdir);
1006     add_local_native_libraries(cmd, sess);
1007     add_upstream_native_libraries(cmd, sess);
1008
1009     // # Telling the linker what we're doing
1010
1011     if dylib {
1012         cmd.build_dylib(out_filename);
1013     }
1014
1015     // FIXME (#2397): At some point we want to rpath our guesses as to
1016     // where extern libraries might live, based on the
1017     // addl_lib_search_paths
1018     if sess.opts.cg.rpath {
1019         let sysroot = sess.sysroot();
1020         let target_triple = &sess.opts.target_triple;
1021         let mut get_install_prefix_lib_path = || {
1022             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1023             let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1024             let mut path = PathBuf::from(install_prefix);
1025             path.push(&tlib);
1026
1027             path
1028         };
1029         let mut rpath_config = RPathConfig {
1030             used_crates: sess.cstore.get_used_crates(cstore::RequireDynamic),
1031             out_filename: out_filename.to_path_buf(),
1032             has_rpath: sess.target.target.options.has_rpath,
1033             is_like_osx: sess.target.target.options.is_like_osx,
1034             get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1035         };
1036         cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1037     }
1038
1039     // Finally add all the linker arguments provided on the command line along
1040     // with any #[link_args] attributes found inside the crate
1041     if let Some(ref args) = sess.opts.cg.link_args {
1042         cmd.args(args);
1043     }
1044     cmd.args(&used_link_args);
1045 }
1046
1047 // # Native library linking
1048 //
1049 // User-supplied library search paths (-L on the command line). These are
1050 // the same paths used to find Rust crates, so some of them may have been
1051 // added already by the previous crate linking code. This only allows them
1052 // to be found at compile time so it is still entirely up to outside
1053 // forces to make sure that library can be found at runtime.
1054 //
1055 // Also note that the native libraries linked here are only the ones located
1056 // in the current crate. Upstream crates with native library dependencies
1057 // may have their native library pulled in above.
1058 fn add_local_native_libraries(cmd: &mut Linker, sess: &Session) {
1059     sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1060         match k {
1061             PathKind::Framework => { cmd.framework_path(path); }
1062             _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1063         }
1064         FileDoesntMatch
1065     });
1066
1067     let libs = sess.cstore.get_used_libraries();
1068     let libs = libs.borrow();
1069
1070     let staticlibs = libs.iter().filter_map(|&(ref l, kind)| {
1071         if kind == cstore::NativeStatic {Some(l)} else {None}
1072     });
1073     let others = libs.iter().filter(|&&(_, kind)| {
1074         kind != cstore::NativeStatic
1075     });
1076
1077     // Some platforms take hints about whether a library is static or dynamic.
1078     // For those that support this, we ensure we pass the option if the library
1079     // was flagged "static" (most defaults are dynamic) to ensure that if
1080     // libfoo.a and libfoo.so both exist that the right one is chosen.
1081     cmd.hint_static();
1082
1083     let search_path = archive_search_paths(sess);
1084     for l in staticlibs {
1085         // Here we explicitly ask that the entire archive is included into the
1086         // result artifact. For more details see #15460, but the gist is that
1087         // the linker will strip away any unused objects in the archive if we
1088         // don't otherwise explicitly reference them. This can occur for
1089         // libraries which are just providing bindings, libraries with generic
1090         // functions, etc.
1091         cmd.link_whole_staticlib(l, &search_path);
1092     }
1093
1094     cmd.hint_dynamic();
1095
1096     for &(ref l, kind) in others {
1097         match kind {
1098             cstore::NativeUnknown => cmd.link_dylib(l),
1099             cstore::NativeFramework => cmd.link_framework(l),
1100             cstore::NativeStatic => unreachable!(),
1101         }
1102     }
1103 }
1104
1105 // # Rust Crate linking
1106 //
1107 // Rust crates are not considered at all when creating an rlib output. All
1108 // dependencies will be linked when producing the final output (instead of
1109 // the intermediate rlib version)
1110 fn add_upstream_rust_crates(cmd: &mut Linker, sess: &Session,
1111                             dylib: bool, tmpdir: &Path) {
1112     // All of the heavy lifting has previously been accomplished by the
1113     // dependency_format module of the compiler. This is just crawling the
1114     // output of that module, adding crates as necessary.
1115     //
1116     // Linking to a rlib involves just passing it to the linker (the linker
1117     // will slurp up the object files inside), and linking to a dynamic library
1118     // involves just passing the right -l flag.
1119
1120     let formats = sess.dependency_formats.borrow();
1121     let data = if dylib {
1122         formats.get(&config::CrateTypeDylib).unwrap()
1123     } else {
1124         formats.get(&config::CrateTypeExecutable).unwrap()
1125     };
1126
1127     // Invoke get_used_crates to ensure that we get a topological sorting of
1128     // crates.
1129     let deps = sess.cstore.get_used_crates(cstore::RequireDynamic);
1130
1131     for &(cnum, _) in &deps {
1132         // We may not pass all crates through to the linker. Some crates may
1133         // appear statically in an existing dylib, meaning we'll pick up all the
1134         // symbols from the dylib.
1135         let src = sess.cstore.get_used_crate_source(cnum).unwrap();
1136         match data[cnum as usize - 1] {
1137             Linkage::NotLinked |
1138             Linkage::IncludedFromDylib => {}
1139             Linkage::Static => {
1140                 add_static_crate(cmd, sess, tmpdir, dylib, &src.rlib.unwrap().0)
1141             }
1142             Linkage::Dynamic => {
1143                 add_dynamic_crate(cmd, sess, &src.dylib.unwrap().0)
1144             }
1145         }
1146     }
1147
1148     // Converts a library file-stem into a cc -l argument
1149     fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1150         if stem.starts_with("lib") && !config.target.options.is_like_windows {
1151             &stem[3..]
1152         } else {
1153             stem
1154         }
1155     }
1156
1157     // Adds the static "rlib" versions of all crates to the command line.
1158     // There's a bit of magic which happens here specifically related to LTO and
1159     // dynamic libraries. Specifically:
1160     //
1161     // * For LTO, we remove upstream object files.
1162     // * For dylibs we remove metadata and bytecode from upstream rlibs
1163     //
1164     // When performing LTO, all of the bytecode from the upstream libraries has
1165     // already been included in our object file output. As a result we need to
1166     // remove the object files in the upstream libraries so the linker doesn't
1167     // try to include them twice (or whine about duplicate symbols). We must
1168     // continue to include the rest of the rlib, however, as it may contain
1169     // static native libraries which must be linked in.
1170     //
1171     // When making a dynamic library, linkers by default don't include any
1172     // object files in an archive if they're not necessary to resolve the link.
1173     // We basically want to convert the archive (rlib) to a dylib, though, so we
1174     // *do* want everything included in the output, regardless of whether the
1175     // linker thinks it's needed or not. As a result we must use the
1176     // --whole-archive option (or the platform equivalent). When using this
1177     // option the linker will fail if there are non-objects in the archive (such
1178     // as our own metadata and/or bytecode). All in all, for rlibs to be
1179     // entirely included in dylibs, we need to remove all non-object files.
1180     //
1181     // Note, however, that if we're not doing LTO or we're not producing a dylib
1182     // (aka we're making an executable), we can just pass the rlib blindly to
1183     // the linker (fast) because it's fine if it's not actually included as
1184     // we're at the end of the dependency chain.
1185     fn add_static_crate(cmd: &mut Linker, sess: &Session, tmpdir: &Path,
1186                         dylib: bool, cratepath: &Path) {
1187         if !sess.lto() && !dylib {
1188             cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1189             return
1190         }
1191
1192         let dst = tmpdir.join(cratepath.file_name().unwrap());
1193         let name = cratepath.file_name().unwrap().to_str().unwrap();
1194         let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1195
1196         time(sess.time_passes(), &format!("altering {}.rlib", name), || {
1197             let cfg = archive_config(sess, &dst, Some(cratepath));
1198             let mut archive = ArchiveBuilder::new(cfg);
1199             archive.remove_file(METADATA_FILENAME);
1200             archive.update_symbols();
1201
1202             let mut any_objects = false;
1203             for f in archive.src_files() {
1204                 if f.ends_with("bytecode.deflate") {
1205                     archive.remove_file(&f);
1206                     continue
1207                 }
1208                 let canonical = f.replace("-", "_");
1209                 let canonical_name = name.replace("-", "_");
1210                 if sess.lto() && canonical.starts_with(&canonical_name) &&
1211                    canonical.ends_with(".o") {
1212                     let num = &f[name.len()..f.len() - 2];
1213                     if num.len() > 0 && num[1..].parse::<u32>().is_ok() {
1214                         archive.remove_file(&f);
1215                         continue
1216                     }
1217                 }
1218                 any_objects = true;
1219             }
1220
1221             if any_objects {
1222                 archive.build();
1223                 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1224             }
1225         });
1226     }
1227
1228     // Same thing as above, but for dynamic crates instead of static crates.
1229     fn add_dynamic_crate(cmd: &mut Linker, sess: &Session, cratepath: &Path) {
1230         // If we're performing LTO, then it should have been previously required
1231         // that all upstream rust dependencies were available in an rlib format.
1232         assert!(!sess.lto());
1233
1234         // Just need to tell the linker about where the library lives and
1235         // what its name is
1236         let parent = cratepath.parent();
1237         if let Some(dir) = parent {
1238             cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1239         }
1240         let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1241         cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1242                             parent.unwrap_or(Path::new("")));
1243     }
1244 }
1245
1246 // Link in all of our upstream crates' native dependencies. Remember that
1247 // all of these upstream native dependencies are all non-static
1248 // dependencies. We've got two cases then:
1249 //
1250 // 1. The upstream crate is an rlib. In this case we *must* link in the
1251 // native dependency because the rlib is just an archive.
1252 //
1253 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1254 // have the dependency present on the system somewhere. Thus, we don't
1255 // gain a whole lot from not linking in the dynamic dependency to this
1256 // crate as well.
1257 //
1258 // The use case for this is a little subtle. In theory the native
1259 // dependencies of a crate are purely an implementation detail of the crate
1260 // itself, but the problem arises with generic and inlined functions. If a
1261 // generic function calls a native function, then the generic function must
1262 // be instantiated in the target crate, meaning that the native symbol must
1263 // also be resolved in the target crate.
1264 fn add_upstream_native_libraries(cmd: &mut Linker, sess: &Session) {
1265     // Be sure to use a topological sorting of crates because there may be
1266     // interdependencies between native libraries. When passing -nodefaultlibs,
1267     // for example, almost all native libraries depend on libc, so we have to
1268     // make sure that's all the way at the right (liblibc is near the base of
1269     // the dependency chain).
1270     //
1271     // This passes RequireStatic, but the actual requirement doesn't matter,
1272     // we're just getting an ordering of crate numbers, we're not worried about
1273     // the paths.
1274     let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
1275     for (cnum, _) in crates {
1276         let libs = csearch::get_native_libraries(&sess.cstore, cnum);
1277         for &(kind, ref lib) in &libs {
1278             match kind {
1279                 cstore::NativeUnknown => cmd.link_dylib(lib),
1280                 cstore::NativeFramework => cmd.link_framework(lib),
1281                 cstore::NativeStatic => {
1282                     sess.bug("statics shouldn't be propagated");
1283                 }
1284             }
1285         }
1286     }
1287 }