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