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