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