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