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