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