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