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.
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.
11 use super::archive::{ArchiveBuilder, ArchiveConfig};
12 use super::linker::Linker;
13 use super::rpath::RPathConfig;
17 use session::config::NoDebugInfo;
18 use session::config::{OutputFilenames, Input, OutputType};
19 use session::filesearch;
20 use session::search_paths::PathKind;
22 use middle::cstore::{self, LinkMeta};
23 use middle::cstore::{LinkagePreference, NativeLibraryKind};
24 use middle::dependency_format::Linkage;
26 use util::common::time;
27 use util::fs::fix_windows_verbatim_for_gcc;
28 use rustc::dep_graph::DepNode;
29 use rustc::hir::svh::Svh;
30 use rustc_back::tempdir::TempDir;
31 use rustc_incremental::IncrementalHashesMap;
36 use std::ffi::OsString;
38 use std::io::{self, Read, Write};
40 use std::path::{Path, PathBuf};
41 use std::process::Command;
47 // RLIB LLVM-BYTECODE OBJECT LAYOUT
50 // 0..10 "RUST_OBJECT" encoded in ASCII
51 // 11..14 format version as little-endian u32
52 // 15..22 size in bytes of deflate compressed LLVM bitcode as
54 // 23.. compressed LLVM bitcode
56 // This is the "magic number" expected at the beginning of a LLVM bytecode
58 pub const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT";
60 // The version number this compiler will write to bytecode objects in rlibs
61 pub const RLIB_BYTECODE_OBJECT_VERSION: u32 = 1;
63 // The offset in bytes the bytecode object format version number can be found at
64 pub const RLIB_BYTECODE_OBJECT_VERSION_OFFSET: usize = 11;
66 // The offset in bytes the size of the compressed bytecode can be found at in
68 pub const RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: usize =
69 RLIB_BYTECODE_OBJECT_VERSION_OFFSET + 4;
71 // The offset in bytes the compressed LLVM bytecode can be found at in format
73 pub const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: usize =
74 RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET + 8;
77 pub fn find_crate_name(sess: Option<&Session>,
78 attrs: &[ast::Attribute],
79 input: &Input) -> String {
80 let validate = |s: String, span: Option<Span>| {
81 cstore::validate_crate_name(sess, &s[..], span);
85 // Look in attributes 100% of the time to make sure the attribute is marked
86 // as used. After doing this, however, we still prioritize a crate name from
87 // the command line over one found in the #[crate_name] attribute. If we
88 // find both we ensure that they're the same later on as well.
89 let attr_crate_name = attrs.iter().find(|at| at.check_name("crate_name"))
90 .and_then(|at| at.value_str().map(|s| (at, s)));
92 if let Some(sess) = sess {
93 if let Some(ref s) = sess.opts.crate_name {
94 if let Some((attr, ref name)) = attr_crate_name {
96 let msg = format!("--crate-name and #[crate_name] are \
97 required to match, but `{}` != `{}`",
99 sess.span_err(attr.span, &msg[..]);
102 return validate(s.clone(), None);
106 if let Some((attr, s)) = attr_crate_name {
107 return validate(s.to_string(), Some(attr.span));
109 if let Input::File(ref path) = *input {
110 if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
111 if s.starts_with("-") {
112 let msg = format!("crate names cannot start with a `-`, but \
113 `{}` has a leading hyphen", s);
114 if let Some(sess) = sess {
118 return validate(s.replace("-", "_"), None);
123 "rust_out".to_string()
127 pub fn build_link_meta(incremental_hashes_map: &IncrementalHashesMap,
131 crate_name: name.to_owned(),
132 crate_hash: Svh::new(incremental_hashes_map[&DepNode::Krate]),
138 // The third parameter is for an extra path to add to PATH for MSVC
139 // cross linkers for host toolchain DLL dependencies
140 pub fn get_linker(sess: &Session) -> (String, Command, Option<PathBuf>) {
141 if let Some(ref linker) = sess.opts.cg.linker {
142 (linker.clone(), Command::new(linker), None)
143 } else if sess.target.target.options.is_like_msvc {
144 let (cmd, host) = msvc::link_exe_cmd(sess);
145 ("link.exe".to_string(), cmd, host)
147 (sess.target.target.options.linker.clone(),
148 Command::new(&sess.target.target.options.linker), None)
152 pub fn get_ar_prog(sess: &Session) -> String {
153 sess.opts.cg.ar.clone().unwrap_or_else(|| {
154 sess.target.target.options.ar.clone()
158 fn command_path(sess: &Session, extra: Option<PathBuf>) -> OsString {
159 // The compiler's sysroot often has some bundled tools, so add it to the
160 // PATH for the child.
161 let mut new_path = sess.host_filesearch(PathKind::All)
162 .get_tools_search_paths();
163 if let Some(path) = env::var_os("PATH") {
164 new_path.extend(env::split_paths(&path));
166 new_path.extend(extra);
167 env::join_paths(new_path).unwrap()
170 pub fn remove(sess: &Session, path: &Path) {
171 match fs::remove_file(path) {
174 sess.err(&format!("failed to remove {}: {}",
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 _task = sess.dep_graph.in_task(DepNode::LinkBinary);
189 let mut out_filenames = Vec::new();
190 for &crate_type in sess.crate_types.borrow().iter() {
191 // Ignore executable crates if we have -Z no-trans, as they will error.
192 if sess.opts.debugging_opts.no_trans &&
193 crate_type == config::CrateTypeExecutable {
197 if invalid_output_for_target(sess, crate_type) {
198 bug!("invalid output type `{:?}` for target os `{}`",
199 crate_type, sess.opts.target_triple);
201 let out_file = link_binary_output(sess, trans, crate_type, outputs,
203 out_filenames.push(out_file);
206 // Remove the temporary object file and metadata if we aren't saving temps
207 if !sess.opts.cg.save_temps {
208 for obj in object_filenames(trans, outputs) {
211 remove(sess, &outputs.with_extension("metadata.o"));
218 /// Returns default crate type for target
220 /// Default crate type is used when crate type isn't provided neither
221 /// through cmd line arguments nor through crate attributes
223 /// It is CrateTypeExecutable for all platforms but iOS as there is no
224 /// way to run iOS binaries anyway without jailbreaking and
225 /// interaction with Rust code through static library is the only
227 pub fn default_output_for_target(sess: &Session) -> config::CrateType {
228 if !sess.target.target.options.executables {
229 config::CrateTypeStaticlib
231 config::CrateTypeExecutable
235 /// Checks if target supports crate_type as output
236 pub fn invalid_output_for_target(sess: &Session,
237 crate_type: config::CrateType) -> bool {
238 match (sess.target.target.options.dynamic_linking,
239 sess.target.target.options.executables, crate_type) {
240 (false, _, config::CrateTypeCdylib) |
241 (false, _, config::CrateTypeDylib) => true,
242 (_, false, config::CrateTypeExecutable) => true,
247 fn is_writeable(p: &Path) -> bool {
250 Ok(m) => !m.permissions().readonly()
254 pub fn filename_for_input(sess: &Session,
255 crate_type: config::CrateType,
257 outputs: &OutputFilenames) -> PathBuf {
258 let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
260 config::CrateTypeRlib => {
261 outputs.out_directory.join(&format!("lib{}.rlib", libname))
263 config::CrateTypeCdylib |
264 config::CrateTypeDylib => {
265 let (prefix, suffix) = (&sess.target.target.options.dll_prefix,
266 &sess.target.target.options.dll_suffix);
267 outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
270 config::CrateTypeStaticlib => {
271 let (prefix, suffix) = (&sess.target.target.options.staticlib_prefix,
272 &sess.target.target.options.staticlib_suffix);
273 outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
276 config::CrateTypeExecutable => {
277 let suffix = &sess.target.target.options.exe_suffix;
278 let out_filename = outputs.path(OutputType::Exe);
279 if suffix.is_empty() {
280 out_filename.to_path_buf()
282 out_filename.with_extension(&suffix[1..])
288 pub fn each_linked_rlib(sess: &Session,
289 f: &mut FnMut(ast::CrateNum, &Path)) {
290 let crates = sess.cstore.used_crates(LinkagePreference::RequireStatic).into_iter();
291 let fmts = sess.dependency_formats.borrow();
292 let fmts = fmts.get(&config::CrateTypeExecutable)
293 .or_else(|| fmts.get(&config::CrateTypeStaticlib))
294 .or_else(|| fmts.get(&config::CrateTypeCdylib));
295 let fmts = fmts.unwrap_or_else(|| {
296 bug!("could not find formats for rlibs")
298 for (cnum, path) in crates {
299 match fmts[cnum as usize - 1] {
300 Linkage::NotLinked | Linkage::IncludedFromDylib => continue,
303 let name = sess.cstore.crate_name(cnum).clone();
304 let path = match path {
307 sess.fatal(&format!("could not find rlib for: `{}`", name));
314 fn link_binary_output(sess: &Session,
315 trans: &CrateTranslation,
316 crate_type: config::CrateType,
317 outputs: &OutputFilenames,
318 crate_name: &str) -> PathBuf {
319 let objects = object_filenames(trans, outputs);
320 let default_filename = filename_for_input(sess, crate_type, crate_name,
322 let out_filename = outputs.outputs.get(&OutputType::Exe)
323 .and_then(|s| s.to_owned())
324 .or_else(|| outputs.single_output_file.clone())
325 .unwrap_or(default_filename);
327 // Make sure files are writeable. Mac, FreeBSD, and Windows system linkers
328 // check this already -- however, the Linux linker will happily overwrite a
329 // read-only file. We should be consistent.
330 for file in objects.iter().chain(Some(&out_filename)) {
331 if !is_writeable(file) {
332 sess.fatal(&format!("output file {} is not writeable -- check its \
333 permissions", file.display()));
337 let tmpdir = match TempDir::new("rustc") {
338 Ok(tmpdir) => tmpdir,
339 Err(err) => sess.fatal(&format!("couldn't create a temp dir: {}", err)),
343 config::CrateTypeRlib => {
344 link_rlib(sess, Some(trans), &objects, &out_filename,
345 tmpdir.path()).build();
347 config::CrateTypeStaticlib => {
348 link_staticlib(sess, &objects, &out_filename, tmpdir.path());
351 link_natively(sess, crate_type, &objects, &out_filename, trans,
352 outputs, tmpdir.path());
359 fn object_filenames(trans: &CrateTranslation,
360 outputs: &OutputFilenames)
362 trans.modules.iter().map(|module| {
363 outputs.temp_path(OutputType::Object, Some(&module.name[..]))
367 fn archive_search_paths(sess: &Session) -> Vec<PathBuf> {
368 let mut search = Vec::new();
369 sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
370 search.push(path.to_path_buf());
375 fn archive_config<'a>(sess: &'a Session,
377 input: Option<&Path>) -> ArchiveConfig<'a> {
380 dst: output.to_path_buf(),
381 src: input.map(|p| p.to_path_buf()),
382 lib_search_paths: archive_search_paths(sess),
383 ar_prog: get_ar_prog(sess),
384 command_path: command_path(sess, None),
390 // An rlib in its current incarnation is essentially a renamed .a file. The
391 // rlib primarily contains the object file of the crate, but it also contains
392 // all of the object files from native libraries. This is done by unzipping
393 // native libraries and inserting all of the contents into this archive.
394 fn link_rlib<'a>(sess: &'a Session,
395 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
398 tmpdir: &Path) -> ArchiveBuilder<'a> {
399 info!("preparing rlib from {:?} to {:?}", objects, out_filename);
400 let mut ab = ArchiveBuilder::new(archive_config(sess, out_filename, None));
405 for (l, kind) in sess.cstore.used_libraries() {
407 NativeLibraryKind::NativeStatic => ab.add_native_library(&l),
408 NativeLibraryKind::NativeFramework |
409 NativeLibraryKind::NativeUnknown => {}
413 // After adding all files to the archive, we need to update the
414 // symbol table of the archive.
417 // Note that it is important that we add all of our non-object "magical
418 // files" *after* all of the object files in the archive. The reason for
419 // this is as follows:
421 // * When performing LTO, this archive will be modified to remove
422 // objects from above. The reason for this is described below.
424 // * When the system linker looks at an archive, it will attempt to
425 // determine the architecture of the archive in order to see whether its
428 // The algorithm for this detection is: iterate over the files in the
429 // archive. Skip magical SYMDEF names. Interpret the first file as an
430 // object file. Read architecture from the object file.
432 // * As one can probably see, if "metadata" and "foo.bc" were placed
433 // before all of the objects, then the architecture of this archive would
434 // not be correctly inferred once 'foo.o' is removed.
436 // Basically, all this means is that this code should not move above the
440 // Instead of putting the metadata in an object file section, rlibs
441 // contain the metadata in a separate file. We use a temp directory
442 // here so concurrent builds in the same directory don't try to use
443 // the same filename for metadata (stomping over one another)
444 let metadata = tmpdir.join(sess.cstore.metadata_filename());
445 match fs::File::create(&metadata).and_then(|mut f| {
446 f.write_all(&trans.metadata)
450 sess.fatal(&format!("failed to write {}: {}",
451 metadata.display(), e));
454 ab.add_file(&metadata);
456 // For LTO purposes, the bytecode of this library is also inserted
457 // into the archive. If codegen_units > 1, we insert each of the
460 // Note that we make sure that the bytecode filename in the
461 // archive is never exactly 16 bytes long by adding a 16 byte
462 // extension to it. This is to work around a bug in LLDB that
463 // would cause it to crash if the name of a file in an archive
464 // was exactly 16 bytes.
465 let bc_filename = obj.with_extension("bc");
466 let bc_deflated_filename = tmpdir.join({
467 obj.with_extension("bytecode.deflate").file_name().unwrap()
470 let mut bc_data = Vec::new();
471 match fs::File::open(&bc_filename).and_then(|mut f| {
472 f.read_to_end(&mut bc_data)
475 Err(e) => sess.fatal(&format!("failed to read bytecode: {}",
479 let bc_data_deflated = flate::deflate_bytes(&bc_data[..]);
481 let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) {
484 sess.fatal(&format!("failed to create compressed \
485 bytecode file: {}", e))
489 match write_rlib_bytecode_object_v1(&mut bc_file_deflated,
493 sess.fatal(&format!("failed to write compressed \
498 ab.add_file(&bc_deflated_filename);
500 // See the bottom of back::write::run_passes for an explanation
501 // of when we do and don't keep .#module-name#.bc files around.
502 let user_wants_numbered_bitcode =
503 sess.opts.output_types.contains_key(&OutputType::Bitcode) &&
504 sess.opts.cg.codegen_units > 1;
505 if !sess.opts.cg.save_temps && !user_wants_numbered_bitcode {
506 remove(sess, &bc_filename);
510 // After adding all files to the archive, we need to update the
511 // symbol table of the archive. This currently dies on OSX (see
512 // #11162), and isn't necessary there anyway
513 if !sess.target.target.options.is_like_osx {
524 fn write_rlib_bytecode_object_v1(writer: &mut Write,
525 bc_data_deflated: &[u8]) -> io::Result<()> {
526 let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
528 writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC)?;
529 writer.write_all(&[1, 0, 0, 0])?;
531 (bc_data_deflated_size >> 0) as u8,
532 (bc_data_deflated_size >> 8) as u8,
533 (bc_data_deflated_size >> 16) as u8,
534 (bc_data_deflated_size >> 24) as u8,
535 (bc_data_deflated_size >> 32) as u8,
536 (bc_data_deflated_size >> 40) as u8,
537 (bc_data_deflated_size >> 48) as u8,
538 (bc_data_deflated_size >> 56) as u8,
540 writer.write_all(&bc_data_deflated)?;
542 let number_of_bytes_written_so_far =
543 RLIB_BYTECODE_OBJECT_MAGIC.len() + // magic id
544 mem::size_of_val(&RLIB_BYTECODE_OBJECT_VERSION) + // version
545 mem::size_of_val(&bc_data_deflated_size) + // data size field
546 bc_data_deflated_size as usize; // actual data
548 // If the number of bytes written to the object so far is odd, add a
549 // padding byte to make it even. This works around a crash bug in LLDB
550 // (see issue #15950)
551 if number_of_bytes_written_so_far % 2 == 1 {
552 writer.write_all(&[0])?;
558 // Create a static archive
560 // This is essentially the same thing as an rlib, but it also involves adding
561 // all of the upstream crates' objects into the archive. This will slurp in
562 // all of the native libraries of upstream dependencies as well.
564 // Additionally, there's no way for us to link dynamic libraries, so we warn
565 // about all dynamic library dependencies that they're not linked in.
567 // There's no need to include metadata in a static archive, so ensure to not
568 // link in the metadata object file (and also don't prepare the archive with a
570 fn link_staticlib(sess: &Session, objects: &[PathBuf], out_filename: &Path,
572 let mut ab = link_rlib(sess, None, objects, out_filename, tempdir);
573 if !sess.target.target.options.no_compiler_rt {
574 ab.add_native_library("compiler-rt");
577 let mut all_native_libs = vec![];
579 each_linked_rlib(sess, &mut |cnum, path| {
580 let name = sess.cstore.crate_name(cnum);
581 ab.add_rlib(path, &name, sess.lto()).unwrap();
583 let native_libs = sess.cstore.native_libraries(cnum);
584 all_native_libs.extend(native_libs);
590 if !all_native_libs.is_empty() {
591 sess.note_without_error("link against the following native artifacts when linking against \
592 this static library");
593 sess.note_without_error("the order and any duplication can be significant on some \
594 platforms, and so may need to be preserved");
597 for &(kind, ref lib) in &all_native_libs {
598 let name = match kind {
599 NativeLibraryKind::NativeStatic => "static library",
600 NativeLibraryKind::NativeUnknown => "library",
601 NativeLibraryKind::NativeFramework => "framework",
603 sess.note_without_error(&format!("{}: {}", name, *lib));
607 // Create a dynamic library or executable
609 // This will invoke the system linker/cc to create the resulting file. This
610 // links to all upstream files as well.
611 fn link_natively(sess: &Session,
612 crate_type: config::CrateType,
615 trans: &CrateTranslation,
616 outputs: &OutputFilenames,
618 info!("preparing {:?} from {:?} to {:?}", crate_type, objects, out_filename);
620 // The invocations of cc share some flags across platforms
621 let (pname, mut cmd, extra) = get_linker(sess);
622 cmd.env("PATH", command_path(sess, extra));
624 let root = sess.target_filesearch(PathKind::Native).get_lib_path();
625 cmd.args(&sess.target.target.options.pre_link_args);
627 let pre_link_objects = if crate_type == config::CrateTypeExecutable {
628 &sess.target.target.options.pre_link_objects_exe
630 &sess.target.target.options.pre_link_objects_dll
632 for obj in pre_link_objects {
633 cmd.arg(root.join(obj));
637 let mut linker = trans.linker_info.to_linker(&mut cmd, &sess);
638 link_args(&mut *linker, sess, crate_type, tmpdir,
639 objects, out_filename, outputs);
640 if !sess.target.target.options.no_compiler_rt {
641 linker.link_staticlib("compiler-rt");
644 cmd.args(&sess.target.target.options.late_link_args);
645 for obj in &sess.target.target.options.post_link_objects {
646 cmd.arg(root.join(obj));
648 cmd.args(&sess.target.target.options.post_link_args);
650 if sess.opts.debugging_opts.print_link_args {
651 println!("{:?}", &cmd);
654 // May have not found libraries in the right formats.
655 sess.abort_if_errors();
657 // Invoke the system linker
659 let prog = time(sess.time_passes(), "running linker", || cmd.output());
662 fn escape_string(s: &[u8]) -> String {
663 str::from_utf8(s).map(|s| s.to_owned())
664 .unwrap_or_else(|_| {
665 let mut x = "Non-UTF-8 output: ".to_string();
667 .flat_map(|&b| ascii::escape_default(b))
668 .map(|b| char::from_u32(b as u32).unwrap()));
672 if !prog.status.success() {
673 let mut output = prog.stderr.clone();
674 output.extend_from_slice(&prog.stdout);
675 sess.struct_err(&format!("linking with `{}` failed: {}",
678 .note(&format!("{:?}", &cmd))
679 .note(&escape_string(&output[..]))
681 sess.abort_if_errors();
683 info!("linker stderr:\n{}", escape_string(&prog.stderr[..]));
684 info!("linker stdout:\n{}", escape_string(&prog.stdout[..]));
687 sess.struct_err(&format!("could not exec the linker `{}`: {}", pname, e))
688 .note(&format!("{:?}", &cmd))
690 if sess.target.target.options.is_like_msvc && e.kind() == io::ErrorKind::NotFound {
691 sess.note_without_error("the msvc targets depend on the msvc linker \
692 but `link.exe` was not found");
693 sess.note_without_error("please ensure that VS 2013 or VS 2015 was installed \
694 with the Visual C++ option");
696 sess.abort_if_errors();
701 // On OSX, debuggers need this utility to get run to do some munging of
703 if sess.target.target.options.is_like_osx && sess.opts.debuginfo != NoDebugInfo {
704 match Command::new("dsymutil").arg(out_filename).output() {
706 Err(e) => sess.fatal(&format!("failed to run dsymutil: {}", e)),
711 fn link_args(cmd: &mut Linker,
713 crate_type: config::CrateType,
717 outputs: &OutputFilenames) {
719 // The default library location, we need this to find the runtime.
720 // The location of crates will be determined as needed.
721 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
724 let t = &sess.target.target;
726 cmd.include_path(&fix_windows_verbatim_for_gcc(&lib_path));
730 cmd.output_filename(out_filename);
732 // If we're building a dynamic library then some platforms need to make sure
733 // that all symbols are exported correctly from the dynamic library.
734 if crate_type != config::CrateTypeExecutable {
735 cmd.export_symbols(tmpdir, crate_type);
738 // When linking a dynamic library, we put the metadata into a section of the
739 // executable. This metadata is in a separate object file from the main
740 // object file, so we link that in here.
741 if crate_type == config::CrateTypeDylib {
742 cmd.add_object(&outputs.with_extension("metadata.o"));
745 // Try to strip as much out of the generated object by removing unused
746 // sections if possible. See more comments in linker.rs
747 if !sess.opts.cg.link_dead_code {
748 let keep_metadata = crate_type == config::CrateTypeDylib;
749 cmd.gc_sections(keep_metadata);
752 let used_link_args = sess.cstore.used_link_args();
754 if crate_type == config::CrateTypeExecutable &&
755 t.options.position_independent_executables {
756 let empty_vec = Vec::new();
757 let empty_str = String::new();
758 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
759 let mut args = args.iter().chain(used_link_args.iter());
760 let relocation_model = sess.opts.cg.relocation_model.as_ref()
761 .unwrap_or(&empty_str);
762 if (t.options.relocation_model == "pic" || *relocation_model == "pic")
763 && !args.any(|x| *x == "-static") {
764 cmd.position_independent_executable();
768 // Pass optimization flags down to the linker.
771 // Pass debuginfo flags down to the linker.
774 // We want to prevent the compiler from accidentally leaking in any system
775 // libraries, so we explicitly ask gcc to not link to any libraries by
776 // default. Note that this does not happen for windows because windows pulls
777 // in some large number of libraries and I couldn't quite figure out which
779 if t.options.no_default_libraries {
780 cmd.no_default_libraries();
783 // Take careful note of the ordering of the arguments we pass to the linker
784 // here. Linkers will assume that things on the left depend on things to the
785 // right. Things on the right cannot depend on things on the left. This is
786 // all formally implemented in terms of resolving symbols (libs on the right
787 // resolve unknown symbols of libs on the left, but not vice versa).
789 // For this reason, we have organized the arguments we pass to the linker as
792 // 1. The local object that LLVM just generated
793 // 2. Local native libraries
794 // 3. Upstream rust libraries
795 // 4. Upstream native libraries
797 // The rationale behind this ordering is that those items lower down in the
798 // list can't depend on items higher up in the list. For example nothing can
799 // depend on what we just generated (e.g. that'd be a circular dependency).
800 // Upstream rust libraries are not allowed to depend on our local native
801 // libraries as that would violate the structure of the DAG, in that
802 // scenario they are required to link to them as well in a shared fashion.
804 // Note that upstream rust libraries may contain native dependencies as
805 // well, but they also can't depend on what we just started to add to the
806 // link line. And finally upstream native libraries can't depend on anything
807 // in this DAG so far because they're only dylibs and dylibs can only depend
808 // on other dylibs (e.g. other native deps).
809 add_local_native_libraries(cmd, sess);
810 add_upstream_rust_crates(cmd, sess, crate_type, tmpdir);
811 add_upstream_native_libraries(cmd, sess);
813 // # Telling the linker what we're doing
815 if crate_type != config::CrateTypeExecutable {
816 cmd.build_dylib(out_filename);
819 // FIXME (#2397): At some point we want to rpath our guesses as to
820 // where extern libraries might live, based on the
821 // addl_lib_search_paths
822 if sess.opts.cg.rpath {
823 let sysroot = sess.sysroot();
824 let target_triple = &sess.opts.target_triple;
825 let mut get_install_prefix_lib_path = || {
826 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
827 let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
828 let mut path = PathBuf::from(install_prefix);
833 let mut rpath_config = RPathConfig {
834 used_crates: sess.cstore.used_crates(LinkagePreference::RequireDynamic),
835 out_filename: out_filename.to_path_buf(),
836 has_rpath: sess.target.target.options.has_rpath,
837 is_like_osx: sess.target.target.options.is_like_osx,
838 linker_is_gnu: sess.target.target.options.linker_is_gnu,
839 get_install_prefix_lib_path: &mut get_install_prefix_lib_path,
841 cmd.args(&rpath::get_rpath_flags(&mut rpath_config));
844 // Finally add all the linker arguments provided on the command line along
845 // with any #[link_args] attributes found inside the crate
846 if let Some(ref args) = sess.opts.cg.link_args {
849 cmd.args(&used_link_args);
852 // # Native library linking
854 // User-supplied library search paths (-L on the command line). These are
855 // the same paths used to find Rust crates, so some of them may have been
856 // added already by the previous crate linking code. This only allows them
857 // to be found at compile time so it is still entirely up to outside
858 // forces to make sure that library can be found at runtime.
860 // Also note that the native libraries linked here are only the ones located
861 // in the current crate. Upstream crates with native library dependencies
862 // may have their native library pulled in above.
863 fn add_local_native_libraries(cmd: &mut Linker, sess: &Session) {
864 sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
866 PathKind::Framework => { cmd.framework_path(path); }
867 _ => { cmd.include_path(&fix_windows_verbatim_for_gcc(path)); }
871 let libs = sess.cstore.used_libraries();
873 let staticlibs = libs.iter().filter_map(|&(ref l, kind)| {
874 if kind == NativeLibraryKind::NativeStatic {Some(l)} else {None}
876 let others = libs.iter().filter(|&&(_, kind)| {
877 kind != NativeLibraryKind::NativeStatic
880 // Some platforms take hints about whether a library is static or dynamic.
881 // For those that support this, we ensure we pass the option if the library
882 // was flagged "static" (most defaults are dynamic) to ensure that if
883 // libfoo.a and libfoo.so both exist that the right one is chosen.
886 let search_path = archive_search_paths(sess);
887 for l in staticlibs {
888 // Here we explicitly ask that the entire archive is included into the
889 // result artifact. For more details see #15460, but the gist is that
890 // the linker will strip away any unused objects in the archive if we
891 // don't otherwise explicitly reference them. This can occur for
892 // libraries which are just providing bindings, libraries with generic
894 cmd.link_whole_staticlib(l, &search_path);
899 for &(ref l, kind) in others {
901 NativeLibraryKind::NativeUnknown => cmd.link_dylib(l),
902 NativeLibraryKind::NativeFramework => cmd.link_framework(l),
903 NativeLibraryKind::NativeStatic => bug!(),
908 // # Rust Crate linking
910 // Rust crates are not considered at all when creating an rlib output. All
911 // dependencies will be linked when producing the final output (instead of
912 // the intermediate rlib version)
913 fn add_upstream_rust_crates(cmd: &mut Linker,
915 crate_type: config::CrateType,
917 // All of the heavy lifting has previously been accomplished by the
918 // dependency_format module of the compiler. This is just crawling the
919 // output of that module, adding crates as necessary.
921 // Linking to a rlib involves just passing it to the linker (the linker
922 // will slurp up the object files inside), and linking to a dynamic library
923 // involves just passing the right -l flag.
925 let formats = sess.dependency_formats.borrow();
926 let data = formats.get(&crate_type).unwrap();
928 // Invoke get_used_crates to ensure that we get a topological sorting of
930 let deps = sess.cstore.used_crates(LinkagePreference::RequireDynamic);
932 for &(cnum, _) in &deps {
933 // We may not pass all crates through to the linker. Some crates may
934 // appear statically in an existing dylib, meaning we'll pick up all the
935 // symbols from the dylib.
936 let src = sess.cstore.used_crate_source(cnum);
937 match data[cnum as usize - 1] {
939 Linkage::IncludedFromDylib => {}
941 add_static_crate(cmd, sess, tmpdir, crate_type,
942 &src.rlib.unwrap().0, sess.cstore.is_no_builtins(cnum))
944 Linkage::Dynamic => {
945 add_dynamic_crate(cmd, sess, &src.dylib.unwrap().0)
950 // Converts a library file-stem into a cc -l argument
951 fn unlib<'a>(config: &config::Config, stem: &'a str) -> &'a str {
952 if stem.starts_with("lib") && !config.target.options.is_like_windows {
959 // Adds the static "rlib" versions of all crates to the command line.
960 // There's a bit of magic which happens here specifically related to LTO and
961 // dynamic libraries. Specifically:
963 // * For LTO, we remove upstream object files.
964 // * For dylibs we remove metadata and bytecode from upstream rlibs
966 // When performing LTO, almost(*) all of the bytecode from the upstream
967 // libraries has already been included in our object file output. As a
968 // result we need to remove the object files in the upstream libraries so
969 // the linker doesn't try to include them twice (or whine about duplicate
970 // symbols). We must continue to include the rest of the rlib, however, as
971 // it may contain static native libraries which must be linked in.
973 // (*) Crates marked with `#![no_builtins]` don't participate in LTO and
974 // their bytecode wasn't included. The object files in those libraries must
975 // still be passed to the linker.
977 // When making a dynamic library, linkers by default don't include any
978 // object files in an archive if they're not necessary to resolve the link.
979 // We basically want to convert the archive (rlib) to a dylib, though, so we
980 // *do* want everything included in the output, regardless of whether the
981 // linker thinks it's needed or not. As a result we must use the
982 // --whole-archive option (or the platform equivalent). When using this
983 // option the linker will fail if there are non-objects in the archive (such
984 // as our own metadata and/or bytecode). All in all, for rlibs to be
985 // entirely included in dylibs, we need to remove all non-object files.
987 // Note, however, that if we're not doing LTO or we're not producing a dylib
988 // (aka we're making an executable), we can just pass the rlib blindly to
989 // the linker (fast) because it's fine if it's not actually included as
990 // we're at the end of the dependency chain.
991 fn add_static_crate(cmd: &mut Linker,
994 crate_type: config::CrateType,
996 is_a_no_builtins_crate: bool) {
997 if !sess.lto() && crate_type != config::CrateTypeDylib {
998 cmd.link_rlib(&fix_windows_verbatim_for_gcc(cratepath));
1002 let dst = tmpdir.join(cratepath.file_name().unwrap());
1003 let name = cratepath.file_name().unwrap().to_str().unwrap();
1004 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1006 time(sess.time_passes(), &format!("altering {}.rlib", name), || {
1007 let cfg = archive_config(sess, &dst, Some(cratepath));
1008 let mut archive = ArchiveBuilder::new(cfg);
1009 archive.remove_file(sess.cstore.metadata_filename());
1010 archive.update_symbols();
1012 let mut any_objects = false;
1013 for f in archive.src_files() {
1014 if f.ends_with("bytecode.deflate") {
1015 archive.remove_file(&f);
1018 let canonical = f.replace("-", "_");
1019 let canonical_name = name.replace("-", "_");
1020 if sess.lto() && !is_a_no_builtins_crate &&
1021 canonical.starts_with(&canonical_name) &&
1022 canonical.ends_with(".o") {
1023 let num = &f[name.len()..f.len() - 2];
1024 if num.len() > 0 && num[1..].parse::<u32>().is_ok() {
1025 archive.remove_file(&f);
1034 if crate_type == config::CrateTypeDylib {
1035 cmd.link_whole_rlib(&fix_windows_verbatim_for_gcc(&dst));
1037 cmd.link_rlib(&fix_windows_verbatim_for_gcc(&dst));
1043 // Same thing as above, but for dynamic crates instead of static crates.
1044 fn add_dynamic_crate(cmd: &mut Linker, sess: &Session, cratepath: &Path) {
1045 // If we're performing LTO, then it should have been previously required
1046 // that all upstream rust dependencies were available in an rlib format.
1047 assert!(!sess.lto());
1049 // Just need to tell the linker about where the library lives and
1051 let parent = cratepath.parent();
1052 if let Some(dir) = parent {
1053 cmd.include_path(&fix_windows_verbatim_for_gcc(dir));
1055 let filestem = cratepath.file_stem().unwrap().to_str().unwrap();
1056 cmd.link_rust_dylib(&unlib(&sess.target, filestem),
1057 parent.unwrap_or(Path::new("")));
1061 // Link in all of our upstream crates' native dependencies. Remember that
1062 // all of these upstream native dependencies are all non-static
1063 // dependencies. We've got two cases then:
1065 // 1. The upstream crate is an rlib. In this case we *must* link in the
1066 // native dependency because the rlib is just an archive.
1068 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1069 // have the dependency present on the system somewhere. Thus, we don't
1070 // gain a whole lot from not linking in the dynamic dependency to this
1073 // The use case for this is a little subtle. In theory the native
1074 // dependencies of a crate are purely an implementation detail of the crate
1075 // itself, but the problem arises with generic and inlined functions. If a
1076 // generic function calls a native function, then the generic function must
1077 // be instantiated in the target crate, meaning that the native symbol must
1078 // also be resolved in the target crate.
1079 fn add_upstream_native_libraries(cmd: &mut Linker, sess: &Session) {
1080 // Be sure to use a topological sorting of crates because there may be
1081 // interdependencies between native libraries. When passing -nodefaultlibs,
1082 // for example, almost all native libraries depend on libc, so we have to
1083 // make sure that's all the way at the right (liblibc is near the base of
1084 // the dependency chain).
1086 // This passes RequireStatic, but the actual requirement doesn't matter,
1087 // we're just getting an ordering of crate numbers, we're not worried about
1089 let crates = sess.cstore.used_crates(LinkagePreference::RequireStatic);
1090 for (cnum, _) in crates {
1091 let libs = sess.cstore.native_libraries(cnum);
1092 for &(kind, ref lib) in &libs {
1094 NativeLibraryKind::NativeUnknown => cmd.link_dylib(lib),
1095 NativeLibraryKind::NativeFramework => cmd.link_framework(lib),
1096 NativeLibraryKind::NativeStatic => {
1097 bug!("statics shouldn't be propagated");