]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/back/link.rs
Rollup merge of #42496 - Razaekel:feature/integer_max-min, r=BurntSushi
[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;
13 use super::rpath::RPathConfig;
14 use super::rpath;
15 use metadata::METADATA_FILENAME;
16 use rustc::session::config::{self, NoDebugInfo, OutputFilenames, Input, OutputType};
17 use rustc::session::filesearch;
18 use rustc::session::search_paths::PathKind;
19 use rustc::session::Session;
20 use rustc::middle::cstore::{self, LinkMeta, NativeLibrary, LibSource, LinkagePreference,
21                             NativeLibraryKind};
22 use rustc::middle::dependency_format::Linkage;
23 use CrateTranslation;
24 use rustc::util::common::time;
25 use rustc::util::fs::fix_windows_verbatim_for_gcc;
26 use rustc::dep_graph::{DepKind, DepNode};
27 use rustc::hir::def_id::CrateNum;
28 use rustc::hir::svh::Svh;
29 use rustc_back::tempdir::TempDir;
30 use rustc_back::PanicStrategy;
31 use rustc_incremental::IncrementalHashesMap;
32 use context::get_reloc_model;
33 use llvm;
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::mem;
42 use std::path::{Path, PathBuf};
43 use std::process::Command;
44 use std::str;
45 use flate;
46 use syntax::ast;
47 use syntax::attr;
48 use syntax_pos::Span;
49
50 /// The LLVM module name containing crate-metadata. This includes a `.` on
51 /// purpose, so it cannot clash with the name of a user-defined module.
52 pub const METADATA_MODULE_NAME: &'static str = "crate.metadata";
53 /// The name of the crate-metadata object file the compiler generates. Must
54 /// match up with `METADATA_MODULE_NAME`.
55 pub const METADATA_OBJ_NAME: &'static str = "crate.metadata.o";
56
57 // RLIB LLVM-BYTECODE OBJECT LAYOUT
58 // Version 1
59 // Bytes    Data
60 // 0..10    "RUST_OBJECT" encoded in ASCII
61 // 11..14   format version as little-endian u32
62 // 15..22   size in bytes of deflate compressed LLVM bitcode as
63 //          little-endian u64
64 // 23..     compressed LLVM bitcode
65
66 // This is the "magic number" expected at the beginning of a LLVM bytecode
67 // object in an rlib.
68 pub const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT";
69
70 // The version number this compiler will write to bytecode objects in rlibs
71 pub const RLIB_BYTECODE_OBJECT_VERSION: u32 = 1;
72
73 // The offset in bytes the bytecode object format version number can be found at
74 pub const RLIB_BYTECODE_OBJECT_VERSION_OFFSET: usize = 11;
75
76 // The offset in bytes the size of the compressed bytecode can be found at in
77 // format version 1
78 pub const RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: usize =
79     RLIB_BYTECODE_OBJECT_VERSION_OFFSET + 4;
80
81 // The offset in bytes the compressed LLVM bytecode can be found at in format
82 // version 1
83 pub const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: usize =
84     RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET + 8;
85
86
87 pub fn find_crate_name(sess: Option<&Session>,
88                        attrs: &[ast::Attribute],
89                        input: &Input) -> String {
90     let validate = |s: String, span: Option<Span>| {
91         cstore::validate_crate_name(sess, &s, span);
92         s
93     };
94
95     // Look in attributes 100% of the time to make sure the attribute is marked
96     // as used. After doing this, however, we still prioritize a crate name from
97     // the command line over one found in the #[crate_name] attribute. If we
98     // find both we ensure that they're the same later on as well.
99     let attr_crate_name = attrs.iter().find(|at| at.check_name("crate_name"))
100                                .and_then(|at| at.value_str().map(|s| (at, s)));
101
102     if let Some(sess) = sess {
103         if let Some(ref s) = sess.opts.crate_name {
104             if let Some((attr, name)) = attr_crate_name {
105                 if name != &**s {
106                     let msg = format!("--crate-name and #[crate_name] are \
107                                        required to match, but `{}` != `{}`",
108                                       s, name);
109                     sess.span_err(attr.span, &msg);
110                 }
111             }
112             return validate(s.clone(), None);
113         }
114     }
115
116     if let Some((attr, s)) = attr_crate_name {
117         return validate(s.to_string(), Some(attr.span));
118     }
119     if let Input::File(ref path) = *input {
120         if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
121             if s.starts_with("-") {
122                 let msg = format!("crate names cannot start with a `-`, but \
123                                    `{}` has a leading hyphen", s);
124                 if let Some(sess) = sess {
125                     sess.err(&msg);
126                 }
127             } else {
128                 return validate(s.replace("-", "_"), None);
129             }
130         }
131     }
132
133     "rust_out".to_string()
134 }
135
136 pub fn build_link_meta(incremental_hashes_map: &IncrementalHashesMap) -> LinkMeta {
137     let krate_dep_node = &DepNode::new_no_params(DepKind::Krate);
138     let r = LinkMeta {
139         crate_hash: Svh::new(incremental_hashes_map[krate_dep_node].to_smaller_hash()),
140     };
141     info!("{:?}", r);
142     return r;
143 }
144
145 // The third parameter is for env vars, used on windows to set up the
146 // path for MSVC to find its DLLs, and gcc to find its bundled
147 // toolchain
148 pub fn get_linker(sess: &Session) -> (String, Command, Vec<(OsString, OsString)>) {
149     let envs = vec![("PATH".into(), command_path(sess))];
150
151     if let Some(ref linker) = sess.opts.cg.linker {
152         (linker.clone(), Command::new(linker), envs)
153     } else if sess.target.target.options.is_like_msvc {
154         let (cmd, envs) = msvc_link_exe_cmd(sess);
155         ("link.exe".to_string(), cmd, envs)
156     } else {
157         let linker = &sess.target.target.options.linker;
158         (linker.clone(), Command::new(&linker), envs)
159     }
160 }
161
162 #[cfg(windows)]
163 pub fn msvc_link_exe_cmd(sess: &Session) -> (Command, Vec<(OsString, OsString)>) {
164     use gcc::windows_registry;
165
166     let target = &sess.opts.target_triple;
167     let tool = windows_registry::find_tool(target, "link.exe");
168
169     if let Some(tool) = tool {
170         let envs = tool.env().to_vec();
171         (tool.to_command(), envs)
172     } else {
173         debug!("Failed to locate linker.");
174         (Command::new("link.exe"), vec![])
175     }
176 }
177
178 #[cfg(not(windows))]
179 pub fn msvc_link_exe_cmd(_sess: &Session) -> (Command, Vec<(OsString, OsString)>) {
180     (Command::new("link.exe"), vec![])
181 }
182
183 pub fn get_ar_prog(sess: &Session) -> String {
184     sess.opts.cg.ar.clone().unwrap_or_else(|| {
185         sess.target.target.options.ar.clone()
186     })
187 }
188
189 fn command_path(sess: &Session) -> OsString {
190     // The compiler's sysroot often has some bundled tools, so add it to the
191     // PATH for the child.
192     let mut new_path = sess.host_filesearch(PathKind::All)
193                            .get_tools_search_paths();
194     if let Some(path) = env::var_os("PATH") {
195         new_path.extend(env::split_paths(&path));
196     }
197     env::join_paths(new_path).unwrap()
198 }
199
200 pub fn remove(sess: &Session, path: &Path) {
201     match fs::remove_file(path) {
202         Ok(..) => {}
203         Err(e) => {
204             sess.err(&format!("failed to remove {}: {}",
205                              path.display(),
206                              e));
207         }
208     }
209 }
210
211 /// Perform the linkage portion of the compilation phase. This will generate all
212 /// of the requested outputs for this compilation session.
213 pub fn link_binary(sess: &Session,
214                    trans: &CrateTranslation,
215                    outputs: &OutputFilenames,
216                    crate_name: &str) -> Vec<PathBuf> {
217     let mut out_filenames = Vec::new();
218     for &crate_type in sess.crate_types.borrow().iter() {
219         // Ignore executable crates if we have -Z no-trans, as they will error.
220         if (sess.opts.debugging_opts.no_trans ||
221             !sess.opts.output_types.should_trans()) &&
222            crate_type == config::CrateTypeExecutable {
223             continue;
224         }
225
226         if invalid_output_for_target(sess, crate_type) {
227            bug!("invalid output type `{:?}` for target os `{}`",
228                 crate_type, sess.opts.target_triple);
229         }
230         let mut out_files = link_binary_output(sess, trans, crate_type, outputs, crate_name);
231         out_filenames.append(&mut out_files);
232     }
233
234     // Remove the temporary object file and metadata if we aren't saving temps
235     if !sess.opts.cg.save_temps {
236         if sess.opts.output_types.should_trans() {
237             for obj in object_filenames(trans, outputs) {
238                 remove(sess, &obj);
239             }
240         }
241         remove(sess, &outputs.with_extension(METADATA_OBJ_NAME));
242     }
243
244     out_filenames
245 }
246
247
248 /// Returns default crate type for target
249 ///
250 /// Default crate type is used when crate type isn't provided neither
251 /// through cmd line arguments nor through crate attributes
252 ///
253 /// It is CrateTypeExecutable for all platforms but iOS as there is no
254 /// way to run iOS binaries anyway without jailbreaking and
255 /// interaction with Rust code through static library is the only
256 /// option for now
257 pub fn default_output_for_target(sess: &Session) -> config::CrateType {
258     if !sess.target.target.options.executables {
259         config::CrateTypeStaticlib
260     } else {
261         config::CrateTypeExecutable
262     }
263 }
264
265 /// Checks if target supports crate_type as output
266 pub fn invalid_output_for_target(sess: &Session,
267                                  crate_type: config::CrateType) -> bool {
268     match (sess.target.target.options.dynamic_linking,
269            sess.target.target.options.executables, crate_type) {
270         (false, _, config::CrateTypeCdylib) |
271         (false, _, config::CrateTypeProcMacro) |
272         (false, _, config::CrateTypeDylib) => true,
273         (_, false, config::CrateTypeExecutable) => true,
274         _ => false
275     }
276 }
277
278 fn is_writeable(p: &Path) -> bool {
279     match p.metadata() {
280         Err(..) => true,
281         Ok(m) => !m.permissions().readonly()
282     }
283 }
284
285 fn filename_for_metadata(sess: &Session, crate_name: &str, outputs: &OutputFilenames) -> PathBuf {
286     let out_filename = outputs.single_output_file.clone()
287         .unwrap_or(outputs
288             .out_directory
289             .join(&format!("lib{}{}.rmeta", crate_name, sess.opts.cg.extra_filename)));
290     check_file_is_writeable(&out_filename, sess);
291     out_filename
292 }
293
294 pub fn filename_for_input(sess: &Session,
295                           crate_type: config::CrateType,
296                           crate_name: &str,
297                           outputs: &OutputFilenames) -> PathBuf {
298     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
299
300     match crate_type {
301         config::CrateTypeRlib => {
302             outputs.out_directory.join(&format!("lib{}.rlib", libname))
303         }
304         config::CrateTypeCdylib |
305         config::CrateTypeProcMacro |
306         config::CrateTypeDylib => {
307             let (prefix, suffix) = (&sess.target.target.options.dll_prefix,
308                                     &sess.target.target.options.dll_suffix);
309             outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
310                                                 suffix))
311         }
312         config::CrateTypeStaticlib => {
313             let (prefix, suffix) = (&sess.target.target.options.staticlib_prefix,
314                                     &sess.target.target.options.staticlib_suffix);
315             outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
316                                                 suffix))
317         }
318         config::CrateTypeExecutable => {
319             let suffix = &sess.target.target.options.exe_suffix;
320             let out_filename = outputs.path(OutputType::Exe);
321             if suffix.is_empty() {
322                 out_filename.to_path_buf()
323             } else {
324                 out_filename.with_extension(&suffix[1..])
325             }
326         }
327     }
328 }
329
330 pub fn each_linked_rlib(sess: &Session,
331                         f: &mut FnMut(CrateNum, &Path)) {
332     let crates = sess.cstore.used_crates(LinkagePreference::RequireStatic).into_iter();
333     let fmts = sess.dependency_formats.borrow();
334     let fmts = fmts.get(&config::CrateTypeExecutable)
335                    .or_else(|| fmts.get(&config::CrateTypeStaticlib))
336                    .or_else(|| fmts.get(&config::CrateTypeCdylib))
337                    .or_else(|| fmts.get(&config::CrateTypeProcMacro));
338     let fmts = fmts.unwrap_or_else(|| {
339         bug!("could not find formats for rlibs");
340     });
341     for (cnum, path) in crates {
342         match fmts[cnum.as_usize() - 1] {
343             Linkage::NotLinked | Linkage::IncludedFromDylib => continue,
344             _ => {}
345         }
346         let name = sess.cstore.crate_name(cnum).clone();
347         let path = match path {
348             LibSource::Some(p) => p,
349             LibSource::MetadataOnly => {
350                 sess.fatal(&format!("could not find rlib for: `{}`, found rmeta (metadata) file",
351                                     name));
352             }
353             LibSource::None => {
354                 sess.fatal(&format!("could not find rlib for: `{}`", name));
355             }
356         };
357         f(cnum, &path);
358     }
359 }
360
361 fn out_filename(sess: &Session,
362                 crate_type: config::CrateType,
363                 outputs: &OutputFilenames,
364                 crate_name: &str)
365                 -> PathBuf {
366     let default_filename = filename_for_input(sess, crate_type, crate_name, outputs);
367     let out_filename = outputs.outputs.get(&OutputType::Exe)
368                               .and_then(|s| s.to_owned())
369                               .or_else(|| outputs.single_output_file.clone())
370                               .unwrap_or(default_filename);
371
372     check_file_is_writeable(&out_filename, sess);
373
374     out_filename
375 }
376
377 // Make sure files are writeable.  Mac, FreeBSD, and Windows system linkers
378 // check this already -- however, the Linux linker will happily overwrite a
379 // read-only file.  We should be consistent.
380 fn check_file_is_writeable(file: &Path, sess: &Session) {
381     if !is_writeable(file) {
382         sess.fatal(&format!("output file {} is not writeable -- check its \
383                             permissions", file.display()));
384     }
385 }
386
387 fn link_binary_output(sess: &Session,
388                       trans: &CrateTranslation,
389                       crate_type: config::CrateType,
390                       outputs: &OutputFilenames,
391                       crate_name: &str) -> Vec<PathBuf> {
392     let objects = object_filenames(trans, outputs);
393
394     for file in &objects {
395         check_file_is_writeable(file, sess);
396     }
397
398     let tmpdir = match TempDir::new("rustc") {
399         Ok(tmpdir) => tmpdir,
400         Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
401     };
402
403     let mut out_filenames = vec![];
404
405     if outputs.outputs.contains_key(&OutputType::Metadata) {
406         let out_filename = filename_for_metadata(sess, crate_name, outputs);
407         emit_metadata(sess, trans, &out_filename);
408         out_filenames.push(out_filename);
409     }
410
411     if outputs.outputs.should_trans() {
412         let out_filename = out_filename(sess, crate_type, outputs, crate_name);
413         match crate_type {
414             config::CrateTypeRlib => {
415                 link_rlib(sess, Some(trans), &objects, &out_filename,
416                           tmpdir.path()).build();
417             }
418             config::CrateTypeStaticlib => {
419                 link_staticlib(sess, &objects, &out_filename, tmpdir.path());
420             }
421             _ => {
422                 link_natively(sess, crate_type, &objects, &out_filename, trans,
423                               outputs, tmpdir.path());
424             }
425         }
426         out_filenames.push(out_filename);
427     }
428
429     out_filenames
430 }
431
432 fn object_filenames(trans: &CrateTranslation,
433                     outputs: &OutputFilenames)
434                     -> Vec<PathBuf> {
435     trans.modules.iter().map(|module| {
436         outputs.temp_path(OutputType::Object, Some(&module.name))
437     }).collect()
438 }
439
440 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
441     let mut search = Vec::new();
442     sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
443         search.push(path.to_path_buf());
444     });
445     return search;
446 }
447
448 fn archive_config<'a>(sess: &'a Session,
449                       output: &Path,
450                       input: Option<&Path>) -> ArchiveConfig<'a> {
451     ArchiveConfig {
452         sess: sess,
453         dst: output.to_path_buf(),
454         src: input.map(|p| p.to_path_buf()),
455         lib_search_paths: archive_search_paths(sess),
456         ar_prog: get_ar_prog(sess),
457         command_path: command_path(sess),
458     }
459 }
460
461 fn emit_metadata<'a>(sess: &'a Session, trans: &CrateTranslation, out_filename: &Path) {
462     let result = fs::File::create(out_filename).and_then(|mut f| {
463         f.write_all(&trans.metadata.raw_data)
464     });
465
466     if let Err(e) = result {
467         sess.fatal(&format!("failed to write {}: {}", out_filename.display(), e));
468     }
469 }
470
471 // Create an 'rlib'
472 //
473 // An rlib in its current incarnation is essentially a renamed .a file. The
474 // rlib primarily contains the object file of the crate, but it also contains
475 // all of the object files from native libraries. This is done by unzipping
476 // native libraries and inserting all of the contents into this archive.
477 fn link_rlib<'a>(sess: &'a Session,
478                  trans: Option<&CrateTranslation>, // None == no metadata/bytecode
479                  objects: &[PathBuf],
480                  out_filename: &Path,
481                  tmpdir: &Path) -> ArchiveBuilder<'a> {
482     info!("preparing rlib from {:?} to {:?}", objects, out_filename);
483     let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
484
485     for obj in objects {
486         ab.add_file(obj);
487     }
488
489     // Note that in this loop we are ignoring the value of `lib.cfg`. That is,
490     // we may not be configured to actually include a static library if we're
491     // adding it here. That's because later when we consume this rlib we'll
492     // decide whether we actually needed the static library or not.
493     //
494     // To do this "correctly" we'd need to keep track of which libraries added
495     // which object files to the archive. We don't do that here, however. The
496     // #[link(cfg(..))] feature is unstable, though, and only intended to get
497     // liblibc working. In that sense the check below just indicates that if
498     // there are any libraries we want to omit object files for at link time we
499     // just exclude all custom object files.
500     //
501     // Eventually if we want to stabilize or flesh out the #[link(cfg(..))]
502     // feature then we'll need to figure out how to record what objects were
503     // loaded from the libraries found here and then encode that into the
504     // metadata of the rlib we're generating somehow.
505     for lib in sess.cstore.used_libraries() {
506         match lib.kind {
507             NativeLibraryKind::NativeStatic => {}
508             NativeLibraryKind::NativeStaticNobundle |
509             NativeLibraryKind::NativeFramework |
510             NativeLibraryKind::NativeUnknown => continue,
511         }
512         ab.add_native_library(&lib.name.as_str());
513     }
514
515     // After adding all files to the archive, we need to update the
516     // symbol table of the archive.
517     ab.update_symbols();
518
519     // Note that it is important that we add all of our non-object "magical
520     // files" *after* all of the object files in the archive. The reason for
521     // this is as follows:
522     //
523     // * When performing LTO, this archive will be modified to remove
524     //   objects from above. The reason for this is described below.
525     //
526     // * When the system linker looks at an archive, it will attempt to
527     //   determine the architecture of the archive in order to see whether its
528     //   linkable.
529     //
530     //   The algorithm for this detection is: iterate over the files in the
531     //   archive. Skip magical SYMDEF names. Interpret the first file as an
532     //   object file. Read architecture from the object file.
533     //
534     // * As one can probably see, if "metadata" and "foo.bc" were placed
535     //   before all of the objects, then the architecture of this archive would
536     //   not be correctly inferred once 'foo.o' is removed.
537     //
538     // Basically, all this means is that this code should not move above the
539     // code above.
540     match trans {
541         Some(trans) => {
542             // Instead of putting the metadata in an object file section, rlibs
543             // contain the metadata in a separate file. We use a temp directory
544             // here so concurrent builds in the same directory don't try to use
545             // the same filename for metadata (stomping over one another)
546             let metadata = tmpdir.join(METADATA_FILENAME);
547             emit_metadata(sess, trans, &metadata);
548             ab.add_file(&metadata);
549
550             // For LTO purposes, the bytecode of this library is also inserted
551             // into the archive.  If codegen_units > 1, we insert each of the
552             // bitcode files.
553             for obj in objects {
554                 // Note that we make sure that the bytecode filename in the
555                 // archive is never exactly 16 bytes long by adding a 16 byte
556                 // extension to it. This is to work around a bug in LLDB that
557                 // would cause it to crash if the name of a file in an archive
558                 // was exactly 16 bytes.
559                 let bc_filename = obj.with_extension("bc");
560                 let bc_deflated_filename = tmpdir.join({
561                     obj.with_extension("bytecode.deflate").file_name().unwrap()
562                 });
563
564                 let mut bc_data = Vec::new();
565                 match fs::File::open(&bc_filename).and_then(|mut f| {
566                     f.read_to_end(&mut bc_data)
567                 }) {
568                     Ok(..) => {}
569                     Err(e) => sess.fatal(&format!("failed to read bytecode: {}",
570                                                  e))
571                 }
572
573                 let bc_data_deflated = flate::deflate_bytes(&bc_data);
574
575                 let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) {
576                     Ok(file) => file,
577                     Err(e) => {
578                         sess.fatal(&format!("failed to create compressed \
579                                              bytecode file: {}", e))
580                     }
581                 };
582
583                 match write_rlib_bytecode_object_v1(&mut bc_file_deflated,
584                                                     &bc_data_deflated) {
585                     Ok(()) => {}
586                     Err(e) => {
587                         sess.fatal(&format!("failed to write compressed \
588                                              bytecode: {}", e));
589                     }
590                 };
591
592                 ab.add_file(&bc_deflated_filename);
593
594                 // See the bottom of back::write::run_passes for an explanation
595                 // of when we do and don't keep .#module-name#.bc files around.
596                 let user_wants_numbered_bitcode =
597                         sess.opts.output_types.contains_key(&OutputType::Bitcode) &&
598                         sess.opts.cg.codegen_units > 1;
599                 if !sess.opts.cg.save_temps && !user_wants_numbered_bitcode {
600                     remove(sess, &bc_filename);
601                 }
602             }
603
604             // After adding all files to the archive, we need to update the
605             // symbol table of the archive. This currently dies on macOS (see
606             // #11162), and isn't necessary there anyway
607             if !sess.target.target.options.is_like_osx {
608                 ab.update_symbols();
609             }
610         }
611
612         None => {}
613     }
614
615     ab
616 }
617
618 fn write_rlib_bytecode_object_v1(writer: &mut Write,
619                                  bc_data_deflated: &[u8]) -> io::Result<()> {
620     let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
621
622     writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC)?;
623     writer.write_all(&[1, 0, 0, 0])?;
624     writer.write_all(&[
625         (bc_data_deflated_size >>  0) as u8,
626         (bc_data_deflated_size >>  8) as u8,
627         (bc_data_deflated_size >> 16) as u8,
628         (bc_data_deflated_size >> 24) as u8,
629         (bc_data_deflated_size >> 32) as u8,
630         (bc_data_deflated_size >> 40) as u8,
631         (bc_data_deflated_size >> 48) as u8,
632         (bc_data_deflated_size >> 56) as u8,
633     ])?;
634     writer.write_all(&bc_data_deflated)?;
635
636     let number_of_bytes_written_so_far =
637         RLIB_BYTECODE_OBJECT_MAGIC.len() +                // magic id
638         mem::size_of_val(&RLIB_BYTECODE_OBJECT_VERSION) + // version
639         mem::size_of_val(&bc_data_deflated_size) +        // data size field
640         bc_data_deflated_size as usize;                    // actual data
641
642     // If the number of bytes written to the object so far is odd, add a
643     // padding byte to make it even. This works around a crash bug in LLDB
644     // (see issue #15950)
645     if number_of_bytes_written_so_far % 2 == 1 {
646         writer.write_all(&[0])?;
647     }
648
649     return Ok(());
650 }
651
652 // Create a static archive
653 //
654 // This is essentially the same thing as an rlib, but it also involves adding
655 // all of the upstream crates' objects into the archive. This will slurp in
656 // all of the native libraries of upstream dependencies as well.
657 //
658 // Additionally, there's no way for us to link dynamic libraries, so we warn
659 // about all dynamic library dependencies that they're not linked in.
660 //
661 // There's no need to include metadata in a static archive, so ensure to not
662 // link in the metadata object file (and also don't prepare the archive with a
663 // metadata file).
664 fn link_staticlib(sess: &Session, objects: &[PathBuf], out_filename: &Path,
665                   tempdir: &Path) {
666     let mut ab = link_rlib(sess, None, objects, out_filename, tempdir);
667     let mut all_native_libs = vec![];
668
669     each_linked_rlib(sess, &mut |cnum, path| {
670         let name = sess.cstore.crate_name(cnum);
671         let native_libs = sess.cstore.native_libraries(cnum);
672
673         // Here when we include the rlib into our staticlib we need to make a
674         // decision whether to include the extra object files along the way.
675         // These extra object files come from statically included native
676         // libraries, but they may be cfg'd away with #[link(cfg(..))].
677         //
678         // This unstable feature, though, only needs liblibc to work. The only
679         // use case there is where musl is statically included in liblibc.rlib,
680         // so if we don't want the included version we just need to skip it. As
681         // a result the logic here is that if *any* linked library is cfg'd away
682         // we just skip all object files.
683         //
684         // Clearly this is not sufficient for a general purpose feature, and
685         // we'd want to read from the library's metadata to determine which
686         // object files come from where and selectively skip them.
687         let skip_object_files = native_libs.iter().any(|lib| {
688             lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
689         });
690         ab.add_rlib(path, &name.as_str(), sess.lto(), skip_object_files).unwrap();
691
692         all_native_libs.extend(sess.cstore.native_libraries(cnum));
693     });
694
695     ab.update_symbols();
696     ab.build();
697
698     if !all_native_libs.is_empty() {
699         sess.note_without_error("link against the following native artifacts when linking against \
700                                  this static library");
701         sess.note_without_error("the order and any duplication can be significant on some \
702                                  platforms, and so may need to be preserved");
703     }
704
705     for lib in all_native_libs.iter().filter(|l| relevant_lib(sess, l)) {
706         let name = match lib.kind {
707             NativeLibraryKind::NativeStaticNobundle |
708             NativeLibraryKind::NativeUnknown => "library",
709             NativeLibraryKind::NativeFramework => "framework",
710             // These are included, no need to print them
711             NativeLibraryKind::NativeStatic => continue,
712         };
713         sess.note_without_error(&format!("{}: {}", name, lib.name));
714     }
715 }
716
717 // Create a dynamic library or executable
718 //
719 // This will invoke the system linker/cc to create the resulting file. This
720 // links to all upstream files as well.
721 fn link_natively(sess: &Session,
722                  crate_type: config::CrateType,
723                  objects: &[PathBuf],
724                  out_filename: &Path,
725                  trans: &CrateTranslation,
726                  outputs: &OutputFilenames,
727                  tmpdir: &Path) {
728     info!("preparing {:?} from {:?} to {:?}", crate_type, objects, out_filename);
729     let flavor = sess.linker_flavor();
730
731     // The invocations of cc share some flags across platforms
732     let (pname, mut cmd, envs) = get_linker(sess);
733     // This will set PATH on windows
734     cmd.envs(envs);
735
736     let root = sess.target_filesearch(PathKind::Native).get_lib_path();
737     if let Some(args) = sess.target.target.options.pre_link_args.get(&flavor) {
738         cmd.args(args);
739     }
740     if let Some(ref args) = sess.opts.debugging_opts.pre_link_args {
741         cmd.args(args);
742     }
743     cmd.args(&sess.opts.debugging_opts.pre_link_arg);
744
745     let pre_link_objects = if crate_type == config::CrateTypeExecutable {
746         &sess.target.target.options.pre_link_objects_exe
747     } else {
748         &sess.target.target.options.pre_link_objects_dll
749     };
750     for obj in pre_link_objects {
751         cmd.arg(root.join(obj));
752     }
753
754     if sess.target.target.options.is_like_emscripten {
755         cmd.arg("-s");
756         cmd.arg(if sess.panic_strategy() == PanicStrategy::Abort {
757             "DISABLE_EXCEPTION_CATCHING=1"
758         } else {
759             "DISABLE_EXCEPTION_CATCHING=0"
760         });
761     }
762
763     {
764         let mut linker = trans.linker_info.to_linker(cmd, &sess);
765         link_args(&mut *linker, sess, crate_type, tmpdir,
766                   objects, out_filename, outputs, trans);
767         cmd = linker.finalize();
768     }
769     if let Some(args) = sess.target.target.options.late_link_args.get(&flavor) {
770         cmd.args(args);
771     }
772     for obj in &sess.target.target.options.post_link_objects {
773         cmd.arg(root.join(obj));
774     }
775     if let Some(args) = sess.target.target.options.post_link_args.get(&flavor) {
776         cmd.args(args);
777     }
778
779     if sess.opts.debugging_opts.print_link_args {
780         println!("{:?}", &cmd);
781     }
782
783     // May have not found libraries in the right formats.
784     sess.abort_if_errors();
785
786     // Invoke the system linker
787     //
788     // Note that there's a terribly awful hack that really shouldn't be present
789     // in any compiler. Here an environment variable is supported to
790     // automatically retry the linker invocation if the linker looks like it
791     // segfaulted.
792     //
793     // Gee that seems odd, normally segfaults are things we want to know about!
794     // Unfortunately though in rust-lang/rust#38878 we're experiencing the
795     // linker segfaulting on Travis quite a bit which is causing quite a bit of
796     // pain to land PRs when they spuriously fail due to a segfault.
797     //
798     // The issue #38878 has some more debugging information on it as well, but
799     // this unfortunately looks like it's just a race condition in macOS's linker
800     // with some thread pool working in the background. It seems that no one
801     // currently knows a fix for this so in the meantime we're left with this...
802     info!("{:?}", &cmd);
803     let retry_on_segfault = env::var("RUSTC_RETRY_LINKER_ON_SEGFAULT").is_ok();
804     let mut prog;
805     let mut i = 0;
806     loop {
807         i += 1;
808         prog = time(sess.time_passes(), "running linker", || cmd.output());
809         if !retry_on_segfault || i > 3 {
810             break
811         }
812         let output = match prog {
813             Ok(ref output) => output,
814             Err(_) => break,
815         };
816         if output.status.success() {
817             break
818         }
819         let mut out = output.stderr.clone();
820         out.extend(&output.stdout);
821         let out = String::from_utf8_lossy(&out);
822         let msg = "clang: error: unable to execute command: \
823                    Segmentation fault: 11";
824         if !out.contains(msg) {
825             break
826         }
827
828         sess.struct_warn("looks like the linker segfaulted when we tried to \
829                           call it, automatically retrying again")
830             .note(&format!("{:?}", cmd))
831             .note(&out)
832             .emit();
833     }
834
835     match prog {
836         Ok(prog) => {
837             fn escape_string(s: &[u8]) -> String {
838                 str::from_utf8(s).map(|s| s.to_owned())
839                     .unwrap_or_else(|_| {
840                         let mut x = "Non-UTF-8 output: ".to_string();
841                         x.extend(s.iter()
842                                  .flat_map(|&b| ascii::escape_default(b))
843                                  .map(|b| char::from_u32(b as u32).unwrap()));
844                         x
845                     })
846             }
847             if !prog.status.success() {
848                 let mut output = prog.stderr.clone();
849                 output.extend_from_slice(&prog.stdout);
850                 sess.struct_err(&format!("linking with `{}` failed: {}",
851                                          pname,
852                                          prog.status))
853                     .note(&format!("{:?}", &cmd))
854                     .note(&escape_string(&output))
855                     .emit();
856                 sess.abort_if_errors();
857             }
858             info!("linker stderr:\n{}", escape_string(&prog.stderr));
859             info!("linker stdout:\n{}", escape_string(&prog.stdout));
860         },
861         Err(e) => {
862             sess.struct_err(&format!("could not exec the linker `{}`: {}", pname, e))
863                 .note(&format!("{:?}", &cmd))
864                 .emit();
865             if sess.target.target.options.is_like_msvc && e.kind() == io::ErrorKind::NotFound {
866                 sess.note_without_error("the msvc targets depend on the msvc linker \
867                     but `link.exe` was not found");
868                 sess.note_without_error("please ensure that VS 2013 or VS 2015 was installed \
869                     with the Visual C++ option");
870             }
871             sess.abort_if_errors();
872         }
873     }
874
875
876     // On macOS, debuggers need this utility to get run to do some munging of
877     // the symbols
878     if sess.target.target.options.is_like_osx && sess.opts.debuginfo != NoDebugInfo {
879         match Command::new("dsymutil").arg(out_filename).output() {
880             Ok(..) => {}
881             Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
882         }
883     }
884 }
885
886 fn link_args(cmd: &mut Linker,
887              sess: &Session,
888              crate_type: config::CrateType,
889              tmpdir: &Path,
890              objects: &[PathBuf],
891              out_filename: &Path,
892              outputs: &OutputFilenames,
893              trans: &CrateTranslation) {
894
895     // The default library location, we need this to find the runtime.
896     // The location of crates will be determined as needed.
897     let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
898
899     // target descriptor
900     let t = &sess.target.target;
901
902     cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
903     for obj in objects {
904         cmd.add_object(obj);
905     }
906     cmd.output_filename(out_filename);
907
908     if crate_type == config::CrateTypeExecutable &&
909        sess.target.target.options.is_like_windows {
910         if let Some(ref s) = trans.windows_subsystem {
911             cmd.subsystem(s);
912         }
913     }
914
915     // If we're building a dynamic library then some platforms need to make sure
916     // that all symbols are exported correctly from the dynamic library.
917     if crate_type != config::CrateTypeExecutable ||
918        sess.target.target.options.is_like_emscripten {
919         cmd.export_symbols(tmpdir, crate_type);
920     }
921
922     // When linking a dynamic library, we put the metadata into a section of the
923     // executable. This metadata is in a separate object file from the main
924     // object file, so we link that in here.
925     if crate_type == config::CrateTypeDylib ||
926        crate_type == config::CrateTypeProcMacro {
927         cmd.add_object(&outputs.with_extension(METADATA_OBJ_NAME));
928     }
929
930     // Try to strip as much out of the generated object by removing unused
931     // sections if possible. See more comments in linker.rs
932     if !sess.opts.cg.link_dead_code {
933         let keep_metadata = crate_type == config::CrateTypeDylib;
934         cmd.gc_sections(keep_metadata);
935     }
936
937     let used_link_args = sess.cstore.used_link_args();
938
939     if crate_type == config::CrateTypeExecutable &&
940        t.options.position_independent_executables {
941         let empty_vec = Vec::new();
942         let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
943         let more_args = &sess.opts.cg.link_arg;
944         let mut args = args.iter().chain(more_args.iter()).chain(used_link_args.iter());
945
946         if get_reloc_model(sess) == llvm::RelocMode::PIC
947             && !args.any(|x| *x == "-static") {
948             cmd.position_independent_executable();
949         }
950     }
951
952     // Pass optimization flags down to the linker.
953     cmd.optimize();
954
955     // Pass debuginfo flags down to the linker.
956     cmd.debuginfo();
957
958     // We want to prevent the compiler from accidentally leaking in any system
959     // libraries, so we explicitly ask gcc to not link to any libraries by
960     // default. Note that this does not happen for windows because windows pulls
961     // in some large number of libraries and I couldn't quite figure out which
962     // subset we wanted.
963     if t.options.no_default_libraries {
964         cmd.no_default_libraries();
965     }
966
967     // Take careful note of the ordering of the arguments we pass to the linker
968     // here. Linkers will assume that things on the left depend on things to the
969     // right. Things on the right cannot depend on things on the left. This is
970     // all formally implemented in terms of resolving symbols (libs on the right
971     // resolve unknown symbols of libs on the left, but not vice versa).
972     //
973     // For this reason, we have organized the arguments we pass to the linker as
974     // such:
975     //
976     //  1. The local object that LLVM just generated
977     //  2. Local native libraries
978     //  3. Upstream rust libraries
979     //  4. Upstream native libraries
980     //
981     // The rationale behind this ordering is that those items lower down in the
982     // list can't depend on items higher up in the list. For example nothing can
983     // depend on what we just generated (e.g. that'd be a circular dependency).
984     // Upstream rust libraries are not allowed to depend on our local native
985     // libraries as that would violate the structure of the DAG, in that
986     // scenario they are required to link to them as well in a shared fashion.
987     //
988     // Note that upstream rust libraries may contain native dependencies as
989     // well, but they also can't depend on what we just started to add to the
990     // link line. And finally upstream native libraries can't depend on anything
991     // in this DAG so far because they're only dylibs and dylibs can only depend
992     // on other dylibs (e.g. other native deps).
993     add_local_native_libraries(cmd, sess);
994     add_upstream_rust_crates(cmd, sess, crate_type, tmpdir);
995     add_upstream_native_libraries(cmd, sess, crate_type);
996
997     // # Telling the linker what we're doing
998
999     if crate_type != config::CrateTypeExecutable {
1000         cmd.build_dylib(out_filename);
1001     }
1002
1003     // FIXME (#2397): At some point we want to rpath our guesses as to
1004     // where extern libraries might live, based on the
1005     // addl_lib_search_paths
1006     if sess.opts.cg.rpath {
1007         let sysroot = sess.sysroot();
1008         let target_triple = &sess.opts.target_triple;
1009         let mut get_install_prefix_lib_path = || {
1010             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1011             let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1012             let mut path = PathBuf::from(install_prefix);
1013             path.push(&tlib);
1014
1015             path
1016         };
1017         let mut rpath_config = RPathConfig {
1018             used_crates: sess.cstore.used_crates(LinkagePreference::RequireDynamic),
1019             out_filename: out_filename.to_path_buf(),
1020             has_rpath: sess.target.target.options.has_rpath,
1021             is_like_osx: sess.target.target.options.is_like_osx,
1022             linker_is_gnu: sess.target.target.options.linker_is_gnu,
1023             get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
1024         };
1025         cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
1026     }
1027
1028     // Finally add all the linker arguments provided on the command line along
1029     // with any #[link_args] attributes found inside the crate
1030     if let Some(ref args) = sess.opts.cg.link_args {
1031         cmd.args(args);
1032     }
1033     cmd.args(&sess.opts.cg.link_arg);
1034     cmd.args(&used_link_args);
1035 }
1036
1037 // # Native library linking
1038 //
1039 // User-supplied library search paths (-L on the command line). These are
1040 // the same paths used to find Rust crates, so some of them may have been
1041 // added already by the previous crate linking code. This only allows them
1042 // to be found at compile time so it is still entirely up to outside
1043 // forces to make sure that library can be found at runtime.
1044 //
1045 // Also note that the native libraries linked here are only the ones located
1046 // in the current crate. Upstream crates with native library dependencies
1047 // may have their native library pulled in above.
1048 fn add_local_native_libraries(cmd: &mut Linker, sess: &Session) {
1049     sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1050         match k {
1051             PathKind::Framework => { cmd.framework_path(path); }
1052             _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
1053         }
1054     });
1055
1056     let relevant_libs = sess.cstore.used_libraries().into_iter().filter(|l| {
1057         relevant_lib(sess, l)
1058     });
1059
1060     let search_path = archive_search_paths(sess);
1061     for lib in relevant_libs {
1062         match lib.kind {
1063             NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1064             NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1065             NativeLibraryKind::NativeStaticNobundle => cmd.link_staticlib(&lib.name.as_str()),
1066             NativeLibraryKind::NativeStatic => cmd.link_whole_staticlib(&lib.name.as_str(),
1067                                                                         &search_path)
1068         }
1069     }
1070 }
1071
1072 // # Rust Crate linking
1073 //
1074 // Rust crates are not considered at all when creating an rlib output. All
1075 // dependencies will be linked when producing the final output (instead of
1076 // the intermediate rlib version)
1077 fn add_upstream_rust_crates(cmd: &mut Linker,
1078                             sess: &Session,
1079                             crate_type: config::CrateType,
1080                             tmpdir: &Path) {
1081     // All of the heavy lifting has previously been accomplished by the
1082     // dependency_format module of the compiler. This is just crawling the
1083     // output of that module, adding crates as necessary.
1084     //
1085     // Linking to a rlib involves just passing it to the linker (the linker
1086     // will slurp up the object files inside), and linking to a dynamic library
1087     // involves just passing the right -l flag.
1088
1089     let formats = sess.dependency_formats.borrow();
1090     let data = formats.get(&crate_type).unwrap();
1091
1092     // Invoke get_used_crates to ensure that we get a topological sorting of
1093     // crates.
1094     let deps = sess.cstore.used_crates(LinkagePreference::RequireDynamic);
1095
1096     let mut compiler_builtins = None;
1097
1098     for &(cnum, _) in &deps {
1099         // We may not pass all crates through to the linker. Some crates may
1100         // appear statically in an existing dylib, meaning we'll pick up all the
1101         // symbols from the dylib.
1102         let src = sess.cstore.used_crate_source(cnum);
1103         match data[cnum.as_usize() - 1] {
1104             _ if sess.cstore.is_sanitizer_runtime(cnum) => {
1105                 link_sanitizer_runtime(cmd, sess, tmpdir, cnum);
1106             }
1107             // compiler-builtins are always placed last to ensure that they're
1108             // linked correctly.
1109             _ if sess.cstore.is_compiler_builtins(cnum) => {
1110                 assert!(compiler_builtins.is_none());
1111                 compiler_builtins = Some(cnum);
1112             }
1113             Linkage::NotLinked |
1114             Linkage::IncludedFromDylib => {}
1115             Linkage::Static => {
1116                 add_static_crate(cmd, sess, tmpdir, crate_type, cnum);
1117             }
1118             Linkage::Dynamic => {
1119                 add_dynamic_crate(cmd, sess, &src.dylib.unwrap().0)
1120             }
1121         }
1122     }
1123
1124     // compiler-builtins are always placed last to ensure that they're
1125     // linked correctly.
1126     // We must always link the `compiler_builtins` crate statically. Even if it
1127     // was already "included" in a dylib (e.g. `libstd` when `-C prefer-dynamic`
1128     // is used)
1129     if let Some(cnum) = compiler_builtins {
1130         add_static_crate(cmd, sess, tmpdir, crate_type, cnum);
1131     }
1132
1133     // Converts a library file-stem into a cc -l argument
1134     fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
1135         if stem.starts_with("lib") && !config.target.options.is_like_windows {
1136             &stem[3..]
1137         } else {
1138             stem
1139         }
1140     }
1141
1142     // We must link the sanitizer runtime using -Wl,--whole-archive but since
1143     // it's packed in a .rlib, it contains stuff that are not objects that will
1144     // make the linker error. So we must remove those bits from the .rlib before
1145     // linking it.
1146     fn link_sanitizer_runtime(cmd: &mut Linker,
1147                               sess: &Session,
1148                               tmpdir: &Path,
1149                               cnum: CrateNum) {
1150         let src = sess.cstore.used_crate_source(cnum);
1151         let cratepath = &src.rlib.unwrap().0;
1152
1153         if sess.target.target.options.is_like_osx {
1154             // On Apple platforms, the sanitizer is always built as a dylib, and
1155             // LLVM will link to `@rpath/*.dylib`, so we need to specify an
1156             // rpath to the library as well (the rpath should be absolute, see
1157             // PR #41352 for details).
1158             //
1159             // FIXME: Remove this logic into librustc_*san once Cargo supports it
1160             let rpath = cratepath.parent().unwrap();
1161             let rpath = rpath.to_str().expect("non-utf8 component in path");
1162             cmd.args(&["-Wl,-rpath".into(), "-Xlinker".into(), rpath.into()]);
1163         }
1164
1165         let dst = tmpdir.join(cratepath.file_name().unwrap());
1166         let cfg = archive_config(sess, &dst, Some(cratepath));
1167         let mut archive = ArchiveBuilder::new(cfg);
1168         archive.update_symbols();
1169
1170         for f in archive.src_files() {
1171             if f.ends_with("bytecode.deflate") || f == METADATA_FILENAME {
1172                     archive.remove_file(&f);
1173                     continue
1174                 }
1175         }
1176
1177         archive.build();
1178
1179         cmd.link_whole_rlib(&dst);
1180     }
1181
1182     // Adds the static "rlib" versions of all crates to the command line.
1183     // There's a bit of magic which happens here specifically related to LTO and
1184     // dynamic libraries. Specifically:
1185     //
1186     // * For LTO, we remove upstream object files.
1187     // * For dylibs we remove metadata and bytecode from upstream rlibs
1188     //
1189     // When performing LTO, almost(*) all of the bytecode from the upstream
1190     // libraries has already been included in our object file output. As a
1191     // result we need to remove the object files in the upstream libraries so
1192     // the linker doesn't try to include them twice (or whine about duplicate
1193     // symbols). We must continue to include the rest of the rlib, however, as
1194     // it may contain static native libraries which must be linked in.
1195     //
1196     // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
1197     // their bytecode wasn't included. The object files in those libraries must
1198     // still be passed to the linker.
1199     //
1200     // When making a dynamic library, linkers by default don't include any
1201     // object files in an archive if they're not necessary to resolve the link.
1202     // We basically want to convert the archive (rlib) to a dylib, though, so we
1203     // *do* want everything included in the output, regardless of whether the
1204     // linker thinks it's needed or not. As a result we must use the
1205     // --whole-archive option (or the platform equivalent). When using this
1206     // option the linker will fail if there are non-objects in the archive (such
1207     // as our own metadata and/or bytecode). All in all, for rlibs to be
1208     // entirely included in dylibs, we need to remove all non-object files.
1209     //
1210     // Note, however, that if we're not doing LTO or we're not producing a dylib
1211     // (aka we're making an executable), we can just pass the rlib blindly to
1212     // the linker (fast) because it's fine if it's not actually included as
1213     // we're at the end of the dependency chain.
1214     fn add_static_crate(cmd: &mut Linker,
1215                         sess: &Session,
1216                         tmpdir: &Path,
1217                         crate_type: config::CrateType,
1218                         cnum: CrateNum) {
1219         let src = sess.cstore.used_crate_source(cnum);
1220         let cratepath = &src.rlib.unwrap().0;
1221
1222         // See the comment above in `link_staticlib` and `link_rlib` for why if
1223         // there's a static library that's not relevant we skip all object
1224         // files.
1225         let native_libs = sess.cstore.native_libraries(cnum);
1226         let skip_native = native_libs.iter().any(|lib| {
1227             lib.kind == NativeLibraryKind::NativeStatic && !relevant_lib(sess, lib)
1228         });
1229
1230         if !sess.lto() && crate_type != config::CrateTypeDylib && !skip_native {
1231             cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1232             return
1233         }
1234
1235         let dst = tmpdir.join(cratepath.file_name().unwrap());
1236         let name = cratepath.file_name().unwrap().to_str().unwrap();
1237         let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1238
1239         time(sess.time_passes(), &format!("altering {}.rlib", name), || {
1240             let cfg = archive_config(sess, &dst, Some(cratepath));
1241             let mut archive = ArchiveBuilder::new(cfg);
1242             archive.update_symbols();
1243
1244             let mut any_objects = false;
1245             for f in archive.src_files() {
1246                 if f.ends_with("bytecode.deflate") || f == METADATA_FILENAME {
1247                     archive.remove_file(&f);
1248                     continue
1249                 }
1250
1251                 let canonical = f.replace("-", "_");
1252                 let canonical_name = name.replace("-", "_");
1253
1254                 let is_rust_object =
1255                     canonical.starts_with(&canonical_name) && {
1256                         let num = &f[name.len()..f.len() - 2];
1257                         num.len() > 0 && num[1..].parse::<u32>().is_ok()
1258                     };
1259
1260                 // If we've been requested to skip all native object files
1261                 // (those not generated by the rust compiler) then we can skip
1262                 // this file. See above for why we may want to do this.
1263                 let skip_because_cfg_say_so = skip_native && !is_rust_object;
1264
1265                 // If we're performing LTO and this is a rust-generated object
1266                 // file, then we don't need the object file as it's part of the
1267                 // LTO module. Note that `#![no_builtins]` is excluded from LTO,
1268                 // though, so we let that object file slide.
1269                 let skip_because_lto = sess.lto() && is_rust_object &&
1270                                         !sess.cstore.is_no_builtins(cnum);
1271
1272                 if skip_because_cfg_say_so || skip_because_lto {
1273                     archive.remove_file(&f);
1274                 } else {
1275                     any_objects = true;
1276                 }
1277             }
1278
1279             if !any_objects {
1280                 return
1281             }
1282             archive.build();
1283
1284             // If we're creating a dylib, then we need to include the
1285             // whole of each object in our archive into that artifact. This is
1286             // because a `dylib` can be reused as an intermediate artifact.
1287             //
1288             // Note, though, that we don't want to include the whole of a
1289             // compiler-builtins crate (e.g. compiler-rt) because it'll get
1290             // repeatedly linked anyway.
1291             if crate_type == config::CrateTypeDylib &&
1292                !sess.cstore.is_compiler_builtins(cnum) {
1293                 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1294             } else {
1295                 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1296             }
1297         });
1298     }
1299
1300     // Same thing as above, but for dynamic crates instead of static crates.
1301     fn add_dynamic_crate(cmd: &mut Linker, sess: &Session, cratepath: &Path) {
1302         // If we're performing LTO, then it should have been previously required
1303         // that all upstream rust dependencies were available in an rlib format.
1304         assert!(!sess.lto());
1305
1306         // Just need to tell the linker about where the library lives and
1307         // what its name is
1308         let parent = cratepath.parent();
1309         if let Some(dir) = parent {
1310             cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1311         }
1312         let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1313         cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1314                             parent.unwrap_or(Path::new("")));
1315     }
1316 }
1317
1318 // Link in all of our upstream crates' native dependencies. Remember that
1319 // all of these upstream native dependencies are all non-static
1320 // dependencies. We've got two cases then:
1321 //
1322 // 1. The upstream crate is an rlib. In this case we *must* link in the
1323 // native dependency because the rlib is just an archive.
1324 //
1325 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1326 // have the dependency present on the system somewhere. Thus, we don't
1327 // gain a whole lot from not linking in the dynamic dependency to this
1328 // crate as well.
1329 //
1330 // The use case for this is a little subtle. In theory the native
1331 // dependencies of a crate are purely an implementation detail of the crate
1332 // itself, but the problem arises with generic and inlined functions. If a
1333 // generic function calls a native function, then the generic function must
1334 // be instantiated in the target crate, meaning that the native symbol must
1335 // also be resolved in the target crate.
1336 fn add_upstream_native_libraries(cmd: &mut Linker, sess: &Session, crate_type: config::CrateType) {
1337     // Be sure to use a topological sorting of crates because there may be
1338     // interdependencies between native libraries. When passing -nodefaultlibs,
1339     // for example, almost all native libraries depend on libc, so we have to
1340     // make sure that's all the way at the right (liblibc is near the base of
1341     // the dependency chain).
1342     //
1343     // This passes RequireStatic, but the actual requirement doesn't matter,
1344     // we're just getting an ordering of crate numbers, we're not worried about
1345     // the paths.
1346     let formats = sess.dependency_formats.borrow();
1347     let data = formats.get(&crate_type).unwrap();
1348
1349     let crates = sess.cstore.used_crates(LinkagePreference::RequireStatic);
1350     for (cnum, _) in crates {
1351         for lib in sess.cstore.native_libraries(cnum) {
1352             if !relevant_lib(sess, &lib) {
1353                 continue
1354             }
1355             match lib.kind {
1356                 NativeLibraryKind::NativeUnknown => cmd.link_dylib(&lib.name.as_str()),
1357                 NativeLibraryKind::NativeFramework => cmd.link_framework(&lib.name.as_str()),
1358                 NativeLibraryKind::NativeStaticNobundle => {
1359                     // Link "static-nobundle" native libs only if the crate they originate from
1360                     // is being linked statically to the current crate.  If it's linked dynamically
1361                     // or is an rlib already included via some other dylib crate, the symbols from
1362                     // native libs will have already been included in that dylib.
1363                     if data[cnum.as_usize() - 1] == Linkage::Static {
1364                         cmd.link_staticlib(&lib.name.as_str())
1365                     }
1366                 },
1367                 // ignore statically included native libraries here as we've
1368                 // already included them when we included the rust library
1369                 // previously
1370                 NativeLibraryKind::NativeStatic => {}
1371             }
1372         }
1373     }
1374 }
1375
1376 fn relevant_lib(sess: &Session, lib: &NativeLibrary) -> bool {
1377     match lib.cfg {
1378         Some(ref cfg) => attr::cfg_matches(cfg, &sess.parse_sess, None),
1379         None => true,
1380     }
1381 }