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::{Archive, ArchiveBuilder, ArchiveConfig, METADATA_FILENAME};
14 use super::rpath::RPathConfig;
17 use session::config::NoDebugInfo;
18 use session::config::{OutputFilenames, Input, OutputTypeBitcode, OutputTypeExe, OutputTypeObject};
19 use session::search_paths::PathKind;
21 use metadata::common::LinkMeta;
22 use metadata::{encoder, cstore, filesearch, csearch, creader};
23 use metadata::filesearch::FileDoesntMatch;
24 use trans::{CrateContext, CrateTranslation, gensym_name};
25 use middle::ty::{mod, Ty};
26 use util::common::time;
28 use util::sha2::{Digest, Sha256};
30 use std::io::fs::PathExtensions;
31 use std::io::{fs, TempDir, Command};
35 use std::string::String;
37 use serialize::hex::ToHex;
39 use syntax::ast_map::{PathElem, PathElems, PathName};
41 use syntax::attr::AttrMetaMethods;
42 use syntax::codemap::Span;
43 use syntax::parse::token;
45 // RLIB LLVM-BYTECODE OBJECT LAYOUT
48 // 0..10 "RUST_OBJECT" encoded in ASCII
49 // 11..14 format version as little-endian u32
50 // 15..22 size in bytes of deflate compressed LLVM bitcode as
52 // 23.. compressed LLVM bitcode
54 // This is the "magic number" expected at the beginning of a LLVM bytecode
56 pub const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT";
58 // The version number this compiler will write to bytecode objects in rlibs
59 pub const RLIB_BYTECODE_OBJECT_VERSION: u32 = 1;
61 // The offset in bytes the bytecode object format version number can be found at
62 pub const RLIB_BYTECODE_OBJECT_VERSION_OFFSET: uint = 11;
64 // The offset in bytes the size of the compressed bytecode can be found at in
66 pub const RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: uint =
67 RLIB_BYTECODE_OBJECT_VERSION_OFFSET + 4;
69 // The offset in bytes the compressed LLVM bytecode can be found at in format
71 pub const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: uint =
72 RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET + 8;
76 * Name mangling and its relationship to metadata. This is complex. Read
79 * The semantic model of Rust linkage is, broadly, that "there's no global
80 * namespace" between crates. Our aim is to preserve the illusion of this
81 * model despite the fact that it's not *quite* possible to implement on
82 * modern linkers. We initially didn't use system linkers at all, but have
83 * been convinced of their utility.
85 * There are a few issues to handle:
87 * - Linkers operate on a flat namespace, so we have to flatten names.
88 * We do this using the C++ namespace-mangling technique. Foo::bar
91 * - Symbols with the same name but different types need to get different
92 * linkage-names. We do this by hashing a string-encoding of the type into
93 * a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
94 * we use SHA256) to "prevent collisions". This is not airtight but 16 hex
95 * digits on uniform probability means you're going to need 2**32 same-name
96 * symbols in the same process before you're even hitting birthday-paradox
97 * collision probability.
99 * - Symbols in different crates but with same names "within" the crate need
100 * to get different linkage-names.
102 * - The hash shown in the filename needs to be predictable and stable for
103 * build tooling integration. It also needs to be using a hash function
104 * which is easy to use from Python, make, etc.
106 * So here is what we do:
108 * - Consider the package id; every crate has one (specified with crate_id
109 * attribute). If a package id isn't provided explicitly, we infer a
110 * versionless one from the output name. The version will end up being 0.0
111 * in this case. CNAME and CVERS are taken from this package id. For
112 * example, github.com/mozilla/CNAME#CVERS.
114 * - Define CMH as SHA256(crateid).
116 * - Define CMH8 as the first 8 characters of CMH.
118 * - Compile our crate to lib CNAME-CMH8-CVERS.so
120 * - Define STH(sym) as SHA256(CMH, type_str(sym))
122 * - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
123 * name, non-name metadata, and type sense, and versioned in the way
124 * system linkers understand.
127 pub fn find_crate_name(sess: Option<&Session>,
128 attrs: &[ast::Attribute],
129 input: &Input) -> String {
130 let validate = |&: s: String, span: Option<Span>| {
131 creader::validate_crate_name(sess, s[], span);
135 // Look in attributes 100% of the time to make sure the attribute is marked
136 // as used. After doing this, however, we still prioritize a crate name from
137 // the command line over one found in the #[crate_name] attribute. If we
138 // find both we ensure that they're the same later on as well.
139 let attr_crate_name = attrs.iter().find(|at| at.check_name("crate_name"))
140 .and_then(|at| at.value_str().map(|s| (at, s)));
142 if let Some(sess) = sess {
143 if let Some(ref s) = sess.opts.crate_name {
144 if let Some((attr, ref name)) = attr_crate_name {
145 if *s != name.get() {
146 let msg = format!("--crate-name and #[crate_name] are \
147 required to match, but `{}` != `{}`",
149 sess.span_err(attr.span, msg[]);
152 return validate(s.clone(), None);
156 if let Some((attr, s)) = attr_crate_name {
157 return validate(s.get().to_string(), Some(attr.span));
159 if let Input::File(ref path) = *input {
160 if let Some(s) = path.filestem_str() {
161 return validate(s.to_string(), None);
165 "rust-out".to_string()
168 pub fn build_link_meta(sess: &Session, krate: &ast::Crate,
169 name: String) -> LinkMeta {
172 crate_hash: Svh::calculate(&sess.opts.cg.metadata, krate),
178 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> String {
179 let output = symbol_hasher.result_bytes();
180 // 64 bits should be enough to avoid collisions.
181 output.slice_to(8).to_hex().to_string()
185 // This calculates STH for a symbol, as defined above
186 fn symbol_hash<'tcx>(tcx: &ty::ctxt<'tcx>,
187 symbol_hasher: &mut Sha256,
189 link_meta: &LinkMeta)
191 // NB: do *not* use abbrevs here as we want the symbol names
192 // to be independent of one another in the crate.
194 symbol_hasher.reset();
195 symbol_hasher.input_str(link_meta.crate_name[]);
196 symbol_hasher.input_str("-");
197 symbol_hasher.input_str(link_meta.crate_hash.as_str());
198 for meta in tcx.sess.crate_metadata.borrow().iter() {
199 symbol_hasher.input_str(meta[]);
201 symbol_hasher.input_str("-");
202 symbol_hasher.input_str(encoder::encoded_ty(tcx, t)[]);
203 // Prefix with 'h' so that it never blends into adjacent digits
204 let mut hash = String::from_str("h");
205 hash.push_str(truncated_hash_result(symbol_hasher)[]);
209 fn get_symbol_hash<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> String {
210 match ccx.type_hashcodes().borrow().get(&t) {
211 Some(h) => return h.to_string(),
215 let mut symbol_hasher = ccx.symbol_hasher().borrow_mut();
216 let hash = symbol_hash(ccx.tcx(), &mut *symbol_hasher, t, ccx.link_meta());
217 ccx.type_hashcodes().borrow_mut().insert(t, hash.clone());
222 // Name sanitation. LLVM will happily accept identifiers with weird names, but
224 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
225 pub fn sanitize(s: &str) -> String {
226 let mut result = String::new();
229 // Escape these with $ sequences
230 '@' => result.push_str("$SP$"),
231 '~' => result.push_str("$UP$"),
232 '*' => result.push_str("$RP$"),
233 '&' => result.push_str("$BP$"),
234 '<' => result.push_str("$LT$"),
235 '>' => result.push_str("$GT$"),
236 '(' => result.push_str("$LP$"),
237 ')' => result.push_str("$RP$"),
238 ',' => result.push_str("$C$"),
240 // '.' doesn't occur in types and functions, so reuse it
242 '-' | ':' => result.push('.'),
244 // These are legal symbols
248 | '_' | '.' | '$' => result.push(c),
251 let mut tstr = String::new();
252 for c in c.escape_unicode() { tstr.push(c) }
254 result.push_str(tstr[1..]);
259 // Underscore-qualify anything that didn't start as an ident.
260 if result.len() > 0u &&
261 result.as_bytes()[0] != '_' as u8 &&
262 ! (result.as_bytes()[0] as char).is_xid_start() {
263 return format!("_{}", result[]);
269 pub fn mangle<PI: Iterator<Item=PathElem>>(mut path: PI,
270 hash: Option<&str>) -> String {
271 // Follow C++ namespace-mangling style, see
272 // http://en.wikipedia.org/wiki/Name_mangling for more info.
274 // It turns out that on OSX you can actually have arbitrary symbols in
275 // function names (at least when given to LLVM), but this is not possible
276 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
277 // we won't need to do this name mangling. The problem with name mangling is
278 // that it seriously limits the available characters. For example we can't
279 // have things like &T or ~[T] in symbol names when one would theoretically
280 // want them for things like impls of traits on that type.
282 // To be able to work on all platforms and get *some* reasonable output, we
283 // use C++ name-mangling.
285 let mut n = String::from_str("_ZN"); // _Z == Begin name-sequence, N == nested
287 fn push(n: &mut String, s: &str) {
288 let sani = sanitize(s);
289 n.push_str(format!("{}{}", sani.len(), sani)[]);
292 // First, connect each component with <len, name> pairs.
294 push(&mut n, token::get_name(e.name()).get()[])
298 Some(s) => push(&mut n, s),
302 n.push('E'); // End name-sequence.
306 pub fn exported_name(path: PathElems, hash: &str) -> String {
307 mangle(path, Some(hash))
310 pub fn mangle_exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, path: PathElems,
311 t: Ty<'tcx>, id: ast::NodeId) -> String {
312 let mut hash = get_symbol_hash(ccx, t);
314 // Paths can be completely identical for different nodes,
315 // e.g. `fn foo() { { fn a() {} } { fn a() {} } }`, so we
316 // generate unique characters from the node id. For now
317 // hopefully 3 characters is enough to avoid collisions.
318 static EXTRA_CHARS: &'static str =
319 "abcdefghijklmnopqrstuvwxyz\
320 ABCDEFGHIJKLMNOPQRSTUVWXYZ\
323 let extra1 = id % EXTRA_CHARS.len();
324 let id = id / EXTRA_CHARS.len();
325 let extra2 = id % EXTRA_CHARS.len();
326 let id = id / EXTRA_CHARS.len();
327 let extra3 = id % EXTRA_CHARS.len();
328 hash.push(EXTRA_CHARS.as_bytes()[extra1] as char);
329 hash.push(EXTRA_CHARS.as_bytes()[extra2] as char);
330 hash.push(EXTRA_CHARS.as_bytes()[extra3] as char);
332 exported_name(path, hash[])
335 pub fn mangle_internal_name_by_type_and_seq<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
337 name: &str) -> String {
338 let s = ppaux::ty_to_string(ccx.tcx(), t);
339 let path = [PathName(token::intern(s[])),
341 let hash = get_symbol_hash(ccx, t);
342 mangle(ast_map::Values(path.iter()), Some(hash[]))
345 pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> String {
346 mangle(path.chain(Some(gensym_name(flav)).into_iter()), None)
349 pub fn get_cc_prog(sess: &Session) -> String {
350 match sess.opts.cg.linker {
351 Some(ref linker) => return linker.to_string(),
352 None => sess.target.target.options.linker.clone(),
356 pub fn remove(sess: &Session, path: &Path) {
357 match fs::unlink(path) {
360 sess.err(format!("failed to remove {}: {}",
367 /// Perform the linkage portion of the compilation phase. This will generate all
368 /// of the requested outputs for this compilation session.
369 pub fn link_binary(sess: &Session,
370 trans: &CrateTranslation,
371 outputs: &OutputFilenames,
372 crate_name: &str) -> Vec<Path> {
373 let mut out_filenames = Vec::new();
374 for &crate_type in sess.crate_types.borrow().iter() {
375 if invalid_output_for_target(sess, crate_type) {
376 sess.bug(format!("invalid output type `{}` for target os `{}`",
377 crate_type, sess.opts.target_triple)[]);
379 let out_file = link_binary_output(sess, trans, crate_type, outputs,
381 out_filenames.push(out_file);
384 // Remove the temporary object file and metadata if we aren't saving temps
385 if !sess.opts.cg.save_temps {
386 let obj_filename = outputs.temp_path(OutputTypeObject);
387 if !sess.opts.output_types.contains(&OutputTypeObject) {
388 remove(sess, &obj_filename);
390 remove(sess, &obj_filename.with_extension("metadata.o"));
397 /// Returns default crate type for target
399 /// Default crate type is used when crate type isn't provided neither
400 /// through cmd line arguments nor through crate attributes
402 /// It is CrateTypeExecutable for all platforms but iOS as there is no
403 /// way to run iOS binaries anyway without jailbreaking and
404 /// interaction with Rust code through static library is the only
406 pub fn default_output_for_target(sess: &Session) -> config::CrateType {
407 if !sess.target.target.options.executables {
408 config::CrateTypeStaticlib
410 config::CrateTypeExecutable
414 /// Checks if target supports crate_type as output
415 pub fn invalid_output_for_target(sess: &Session,
416 crate_type: config::CrateType) -> bool {
417 match (sess.target.target.options.dynamic_linking,
418 sess.target.target.options.executables, crate_type) {
419 (false, _, config::CrateTypeDylib) => true,
420 (_, false, config::CrateTypeExecutable) => true,
425 fn is_writeable(p: &Path) -> bool {
428 Ok(m) => m.perm & io::USER_WRITE == io::USER_WRITE
432 pub fn filename_for_input(sess: &Session,
433 crate_type: config::CrateType,
435 out_filename: &Path) -> Path {
436 let libname = format!("{}{}", name, sess.opts.cg.extra_filename);
438 config::CrateTypeRlib => {
439 out_filename.with_filename(format!("lib{}.rlib", libname))
441 config::CrateTypeDylib => {
442 let (prefix, suffix) = (sess.target.target.options.dll_prefix[],
443 sess.target.target.options.dll_suffix[]);
444 out_filename.with_filename(format!("{}{}{}",
449 config::CrateTypeStaticlib => {
450 out_filename.with_filename(format!("lib{}.a", libname))
452 config::CrateTypeExecutable => {
453 let suffix = sess.target.target.options.exe_suffix[];
454 out_filename.with_filename(format!("{}{}", libname, suffix))
459 fn link_binary_output(sess: &Session,
460 trans: &CrateTranslation,
461 crate_type: config::CrateType,
462 outputs: &OutputFilenames,
463 crate_name: &str) -> Path {
464 let obj_filename = outputs.temp_path(OutputTypeObject);
465 let out_filename = match outputs.single_output_file {
466 Some(ref file) => file.clone(),
468 let out_filename = outputs.path(OutputTypeExe);
469 filename_for_input(sess, crate_type, crate_name, &out_filename)
473 // Make sure the output and obj_filename are both writeable.
474 // Mac, FreeBSD, and Windows system linkers check this already --
475 // however, the Linux linker will happily overwrite a read-only file.
476 // We should be consistent.
477 let obj_is_writeable = is_writeable(&obj_filename);
478 let out_is_writeable = is_writeable(&out_filename);
479 if !out_is_writeable {
480 sess.fatal(format!("output file {} is not writeable -- check its \
482 out_filename.display())[]);
484 else if !obj_is_writeable {
485 sess.fatal(format!("object file {} is not writeable -- check its \
487 obj_filename.display())[]);
491 config::CrateTypeRlib => {
492 link_rlib(sess, Some(trans), &obj_filename, &out_filename).build();
494 config::CrateTypeStaticlib => {
495 link_staticlib(sess, &obj_filename, &out_filename);
497 config::CrateTypeExecutable => {
498 link_natively(sess, trans, false, &obj_filename, &out_filename);
500 config::CrateTypeDylib => {
501 link_natively(sess, trans, true, &obj_filename, &out_filename);
508 fn archive_search_paths(sess: &Session) -> Vec<Path> {
509 let mut search = Vec::new();
510 sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path| {
511 search.push(path.clone());
519 // An rlib in its current incarnation is essentially a renamed .a file. The
520 // rlib primarily contains the object file of the crate, but it also contains
521 // all of the object files from native libraries. This is done by unzipping
522 // native libraries and inserting all of the contents into this archive.
523 fn link_rlib<'a>(sess: &'a Session,
524 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
526 out_filename: &Path) -> ArchiveBuilder<'a> {
527 let handler = &sess.diagnostic().handler;
528 let config = ArchiveConfig {
530 dst: out_filename.clone(),
531 lib_search_paths: archive_search_paths(sess),
532 slib_prefix: sess.target.target.options.staticlib_prefix.clone(),
533 slib_suffix: sess.target.target.options.staticlib_suffix.clone(),
534 maybe_ar_prog: sess.opts.cg.ar.clone()
536 let mut ab = ArchiveBuilder::create(config);
537 ab.add_file(obj_filename).unwrap();
539 for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() {
541 cstore::NativeStatic => {
542 ab.add_native_library(l[]).unwrap();
544 cstore::NativeFramework | cstore::NativeUnknown => {}
548 // After adding all files to the archive, we need to update the
549 // symbol table of the archive.
552 let mut ab = match sess.target.target.options.is_like_osx {
553 // For OSX/iOS, we must be careful to update symbols only when adding
554 // object files. We're about to start adding non-object files, so run
555 // `ar` now to process the object files.
556 true => ab.build().extend(),
560 // Note that it is important that we add all of our non-object "magical
561 // files" *after* all of the object files in the archive. The reason for
562 // this is as follows:
564 // * When performing LTO, this archive will be modified to remove
565 // obj_filename from above. The reason for this is described below.
567 // * When the system linker looks at an archive, it will attempt to
568 // determine the architecture of the archive in order to see whether its
571 // The algorithm for this detection is: iterate over the files in the
572 // archive. Skip magical SYMDEF names. Interpret the first file as an
573 // object file. Read architecture from the object file.
575 // * As one can probably see, if "metadata" and "foo.bc" were placed
576 // before all of the objects, then the architecture of this archive would
577 // not be correctly inferred once 'foo.o' is removed.
579 // Basically, all this means is that this code should not move above the
583 // Instead of putting the metadata in an object file section, rlibs
584 // contain the metadata in a separate file. We use a temp directory
585 // here so concurrent builds in the same directory don't try to use
586 // the same filename for metadata (stomping over one another)
587 let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
588 let metadata = tmpdir.path().join(METADATA_FILENAME);
589 match fs::File::create(&metadata).write(trans.metadata
593 sess.err(format!("failed to write {}: {}",
596 sess.abort_if_errors();
599 ab.add_file(&metadata).unwrap();
600 remove(sess, &metadata);
602 // For LTO purposes, the bytecode of this library is also inserted
603 // into the archive. If codegen_units > 1, we insert each of the
605 for i in range(0, sess.opts.cg.codegen_units) {
606 // Note that we make sure that the bytecode filename in the
607 // archive is never exactly 16 bytes long by adding a 16 byte
608 // extension to it. This is to work around a bug in LLDB that
609 // would cause it to crash if the name of a file in an archive
610 // was exactly 16 bytes.
611 let bc_filename = obj_filename.with_extension(format!("{}.bc", i)[]);
612 let bc_deflated_filename = obj_filename.with_extension(
613 format!("{}.bytecode.deflate", i)[]);
615 let bc_data = match fs::File::open(&bc_filename).read_to_end() {
616 Ok(buffer) => buffer,
617 Err(e) => sess.fatal(format!("failed to read bytecode: {}",
621 let bc_data_deflated = match flate::deflate_bytes(bc_data[]) {
622 Some(compressed) => compressed,
623 None => sess.fatal(format!("failed to compress bytecode from {}",
624 bc_filename.display())[])
627 let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) {
630 sess.fatal(format!("failed to create compressed bytecode \
635 match write_rlib_bytecode_object_v1(&mut bc_file_deflated,
636 bc_data_deflated.as_slice()) {
639 sess.err(format!("failed to write compressed bytecode: \
641 sess.abort_if_errors()
645 ab.add_file(&bc_deflated_filename).unwrap();
646 remove(sess, &bc_deflated_filename);
648 // See the bottom of back::write::run_passes for an explanation
649 // of when we do and don't keep .0.bc files around.
650 let user_wants_numbered_bitcode =
651 sess.opts.output_types.contains(&OutputTypeBitcode) &&
652 sess.opts.cg.codegen_units > 1;
653 if !sess.opts.cg.save_temps && !user_wants_numbered_bitcode {
654 remove(sess, &bc_filename);
658 // After adding all files to the archive, we need to update the
659 // symbol table of the archive. This currently dies on OSX (see
660 // #11162), and isn't necessary there anyway
661 if !sess.target.target.options.is_like_osx {
672 fn write_rlib_bytecode_object_v1<T: Writer>(writer: &mut T,
673 bc_data_deflated: &[u8])
674 -> ::std::io::IoResult<()> {
675 let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
677 try! { writer.write(RLIB_BYTECODE_OBJECT_MAGIC) };
678 try! { writer.write_le_u32(1) };
679 try! { writer.write_le_u64(bc_data_deflated_size) };
680 try! { writer.write(bc_data_deflated[]) };
682 let number_of_bytes_written_so_far =
683 RLIB_BYTECODE_OBJECT_MAGIC.len() + // magic id
684 mem::size_of_val(&RLIB_BYTECODE_OBJECT_VERSION) + // version
685 mem::size_of_val(&bc_data_deflated_size) + // data size field
686 bc_data_deflated_size as uint; // actual data
688 // If the number of bytes written to the object so far is odd, add a
689 // padding byte to make it even. This works around a crash bug in LLDB
690 // (see issue #15950)
691 if number_of_bytes_written_so_far % 2 == 1 {
692 try! { writer.write_u8(0) };
698 // Create a static archive
700 // This is essentially the same thing as an rlib, but it also involves adding
701 // all of the upstream crates' objects into the archive. This will slurp in
702 // all of the native libraries of upstream dependencies as well.
704 // Additionally, there's no way for us to link dynamic libraries, so we warn
705 // about all dynamic library dependencies that they're not linked in.
707 // There's no need to include metadata in a static archive, so ensure to not
708 // link in the metadata object file (and also don't prepare the archive with a
710 fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) {
711 let ab = link_rlib(sess, None, obj_filename, out_filename);
712 let mut ab = match sess.target.target.options.is_like_osx {
713 true => ab.build().extend(),
716 if sess.target.target.options.morestack {
717 ab.add_native_library("morestack").unwrap();
719 if !sess.target.target.options.no_compiler_rt {
720 ab.add_native_library("compiler-rt").unwrap();
723 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
724 let mut all_native_libs = vec![];
726 for &(cnum, ref path) in crates.iter() {
727 let ref name = sess.cstore.get_crate_data(cnum).name;
728 let p = match *path {
729 Some(ref p) => p.clone(), None => {
730 sess.err(format!("could not find rlib for: `{}`",
735 ab.add_rlib(&p, name[], sess.lto()).unwrap();
737 let native_libs = csearch::get_native_libraries(&sess.cstore, cnum);
738 all_native_libs.extend(native_libs.into_iter());
744 if !all_native_libs.is_empty() {
745 sess.warn("link against the following native artifacts when linking against \
746 this static library");
747 sess.note("the order and any duplication can be significant on some platforms, \
748 and so may need to be preserved");
751 for &(kind, ref lib) in all_native_libs.iter() {
752 let name = match kind {
753 cstore::NativeStatic => "static library",
754 cstore::NativeUnknown => "library",
755 cstore::NativeFramework => "framework",
757 sess.note(format!("{}: {}", name, *lib)[]);
761 // Create a dynamic library or executable
763 // This will invoke the system linker/cc to create the resulting file. This
764 // links to all upstream files as well.
765 fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
766 obj_filename: &Path, out_filename: &Path) {
767 let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
769 // The invocations of cc share some flags across platforms
770 let pname = get_cc_prog(sess);
771 let mut cmd = Command::new(pname[]);
773 cmd.args(sess.target.target.options.pre_link_args[]);
774 link_args(&mut cmd, sess, dylib, tmpdir.path(),
775 trans, obj_filename, out_filename);
776 cmd.args(sess.target.target.options.post_link_args[]);
777 if !sess.target.target.options.no_compiler_rt {
778 cmd.arg("-lcompiler-rt");
781 if (sess.opts.debugging_opts & config::PRINT_LINK_ARGS) != 0 {
782 println!("{}", &cmd);
785 // May have not found libraries in the right formats.
786 sess.abort_if_errors();
788 // Invoke the system linker
790 let prog = time(sess.time_passes(), "running linker", (), |()| cmd.output());
793 if !prog.status.success() {
794 sess.err(format!("linking with `{}` failed: {}",
797 sess.note(format!("{}", &cmd)[]);
798 let mut output = prog.error.clone();
799 output.push_all(prog.output[]);
800 sess.note(str::from_utf8(output[]).unwrap());
801 sess.abort_if_errors();
803 debug!("linker stderr:\n{}", String::from_utf8(prog.error).unwrap());
804 debug!("linker stdout:\n{}", String::from_utf8(prog.output).unwrap());
807 sess.err(format!("could not exec the linker `{}`: {}",
810 sess.abort_if_errors();
815 // On OSX, debuggers need this utility to get run to do some munging of
817 if sess.target.target.options.is_like_osx && sess.opts.debuginfo != NoDebugInfo {
818 match Command::new("dsymutil").arg(out_filename).output() {
821 sess.err(format!("failed to run dsymutil: {}", e)[]);
822 sess.abort_if_errors();
828 fn link_args(cmd: &mut Command,
832 trans: &CrateTranslation,
834 out_filename: &Path) {
836 // The default library location, we need this to find the runtime.
837 // The location of crates will be determined as needed.
838 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
841 let t = &sess.target.target;
843 cmd.arg("-L").arg(&lib_path);
845 cmd.arg("-o").arg(out_filename).arg(obj_filename);
848 // Stack growth requires statically linking a __morestack function. Note
849 // that this is listed *before* all other libraries. Due to the usage of the
850 // --as-needed flag below, the standard library may only be useful for its
851 // rust_stack_exhausted function. In this case, we must ensure that the
852 // libmorestack.a file appears *before* the standard library (so we put it
853 // at the very front).
855 // Most of the time this is sufficient, except for when LLVM gets super
856 // clever. If, for example, we have a main function `fn main() {}`, LLVM
857 // will optimize out calls to `__morestack` entirely because the function
858 // doesn't need any stack at all!
860 // To get around this snag, we specially tell the linker to always include
861 // all contents of this library. This way we're guaranteed that the linker
862 // will include the __morestack symbol 100% of the time, always resolving
863 // references to it even if the object above didn't use it.
864 if t.options.morestack {
865 if t.options.is_like_osx {
866 let morestack = lib_path.join("libmorestack.a");
868 let mut v = b"-Wl,-force_load,".to_vec();
869 v.push_all(morestack.as_vec());
872 cmd.args(&["-Wl,--whole-archive", "-lmorestack", "-Wl,--no-whole-archive"]);
876 // When linking a dynamic library, we put the metadata into a section of the
877 // executable. This metadata is in a separate object file from the main
878 // object file, so we link that in here.
880 cmd.arg(obj_filename.with_extension("metadata.o"));
883 if t.options.is_like_osx {
884 // The dead_strip option to the linker specifies that functions and data
885 // unreachable by the entry point will be removed. This is quite useful
886 // with Rust's compilation model of compiling libraries at a time into
887 // one object file. For example, this brings hello world from 1.7MB to
890 // Note that this is done for both executables and dynamic libraries. We
891 // won't get much benefit from dylibs because LLVM will have already
892 // stripped away as much as it could. This has not been seen to impact
893 // link times negatively.
895 // -dead_strip can't be part of the pre_link_args because it's also used for partial
896 // linking when using multiple codegen units (-r). So we insert it here.
897 cmd.arg("-Wl,-dead_strip");
900 // If we're building a dylib, we don't use --gc-sections because LLVM has
901 // already done the best it can do, and we also don't want to eliminate the
902 // metadata. If we're building an executable, however, --gc-sections drops
903 // the size of hello world from 1.8MB to 597K, a 67% reduction.
904 if !dylib && !t.options.is_like_osx {
905 cmd.arg("-Wl,--gc-sections");
908 let used_link_args = sess.cstore.get_used_link_args().borrow();
910 if t.options.position_independent_executables {
911 let empty_vec = Vec::new();
912 let empty_str = String::new();
913 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
914 let mut args = args.iter().chain(used_link_args.iter());
916 && (t.options.relocation_model == "pic"
917 || *sess.opts.cg.relocation_model.as_ref()
918 .unwrap_or(&empty_str) == "pic")
919 && !args.any(|x| *x == "-static") {
924 if t.options.linker_is_gnu {
925 // GNU-style linkers support optimization with -O. GNU ld doesn't need a
926 // numeric argument, but other linkers do.
927 if sess.opts.optimize == config::Default ||
928 sess.opts.optimize == config::Aggressive {
933 // We want to prevent the compiler from accidentally leaking in any system
934 // libraries, so we explicitly ask gcc to not link to any libraries by
935 // default. Note that this does not happen for windows because windows pulls
936 // in some large number of libraries and I couldn't quite figure out which
938 if !t.options.is_like_windows {
939 cmd.arg("-nodefaultlibs");
942 // Mark all dynamic libraries and executables as compatible with ASLR
943 // FIXME #17098: ASLR breaks gdb
944 if t.options.is_like_windows && sess.opts.debuginfo == NoDebugInfo {
945 // cmd.arg("-Wl,--dynamicbase");
948 // Take careful note of the ordering of the arguments we pass to the linker
949 // here. Linkers will assume that things on the left depend on things to the
950 // right. Things on the right cannot depend on things on the left. This is
951 // all formally implemented in terms of resolving symbols (libs on the right
952 // resolve unknown symbols of libs on the left, but not vice versa).
954 // For this reason, we have organized the arguments we pass to the linker as
957 // 1. The local object that LLVM just generated
958 // 2. Upstream rust libraries
959 // 3. Local native libraries
960 // 4. Upstream native libraries
962 // This is generally fairly natural, but some may expect 2 and 3 to be
963 // swapped. The reason that all native libraries are put last is that it's
964 // not recommended for a native library to depend on a symbol from a rust
965 // crate. If this is the case then a staticlib crate is recommended, solving
968 // Additionally, it is occasionally the case that upstream rust libraries
969 // depend on a local native library. In the case of libraries such as
970 // lua/glfw/etc the name of the library isn't the same across all platforms,
971 // so only the consumer crate of a library knows the actual name. This means
972 // that downstream crates will provide the #[link] attribute which upstream
973 // crates will depend on. Hence local native libraries are after out
974 // upstream rust crates.
976 // In theory this means that a symbol in an upstream native library will be
977 // shadowed by a local native library when it wouldn't have been before, but
978 // this kind of behavior is pretty platform specific and generally not
979 // recommended anyway, so I don't think we're shooting ourself in the foot
981 add_upstream_rust_crates(cmd, sess, dylib, tmpdir, trans);
982 add_local_native_libraries(cmd, sess);
983 add_upstream_native_libraries(cmd, sess);
985 // # Telling the linker what we're doing
988 // On mac we need to tell the linker to let this library be rpathed
989 if sess.target.target.options.is_like_osx {
990 cmd.args(&["-dynamiclib", "-Wl,-dylib"]);
992 if sess.opts.cg.rpath {
993 let mut v = "-Wl,-install_name,@rpath/".as_bytes().to_vec();
994 v.push_all(out_filename.filename().unwrap());
1002 // FIXME (#2397): At some point we want to rpath our guesses as to
1003 // where extern libraries might live, based on the
1004 // addl_lib_search_paths
1005 if sess.opts.cg.rpath {
1006 let sysroot = sess.sysroot();
1007 let target_triple = sess.opts.target_triple[];
1008 let get_install_prefix_lib_path = |:| {
1009 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1010 let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1011 let mut path = Path::new(install_prefix);
1016 let rpath_config = RPathConfig {
1017 used_crates: sess.cstore.get_used_crates(cstore::RequireDynamic),
1018 out_filename: out_filename.clone(),
1019 has_rpath: sess.target.target.options.has_rpath,
1020 is_like_osx: sess.target.target.options.is_like_osx,
1021 get_install_prefix_lib_path: get_install_prefix_lib_path,
1022 realpath: ::util::fs::realpath
1024 cmd.args(rpath::get_rpath_flags(rpath_config)[]);
1027 // Finally add all the linker arguments provided on the command line along
1028 // with any #[link_args] attributes found inside the crate
1029 let empty = Vec::new();
1030 cmd.args(sess.opts.cg.link_args.as_ref().unwrap_or(&empty)[]);
1031 cmd.args(used_link_args[]);
1034 // # Native library linking
1036 // User-supplied library search paths (-L on the command line). These are
1037 // the same paths used to find Rust crates, so some of them may have been
1038 // added already by the previous crate linking code. This only allows them
1039 // to be found at compile time so it is still entirely up to outside
1040 // forces to make sure that library can be found at runtime.
1042 // Also note that the native libraries linked here are only the ones located
1043 // in the current crate. Upstream crates with native library dependencies
1044 // may have their native library pulled in above.
1045 fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
1046 sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path| {
1047 cmd.arg("-L").arg(path);
1051 // Some platforms take hints about whether a library is static or dynamic.
1052 // For those that support this, we ensure we pass the option if the library
1053 // was flagged "static" (most defaults are dynamic) to ensure that if
1054 // libfoo.a and libfoo.so both exist that the right one is chosen.
1055 let takes_hints = !sess.target.target.options.is_like_osx;
1057 let libs = sess.cstore.get_used_libraries();
1058 let libs = libs.borrow();
1060 let mut staticlibs = libs.iter().filter_map(|&(ref l, kind)| {
1061 if kind == cstore::NativeStatic {Some(l)} else {None}
1063 let mut others = libs.iter().filter(|&&(_, kind)| {
1064 kind != cstore::NativeStatic
1067 // Platforms that take hints generally also support the --whole-archive
1068 // flag. We need to pass this flag when linking static native libraries to
1069 // ensure the entire library is included.
1071 // For more details see #15460, but the gist is that the linker will strip
1072 // away any unused objects in the archive if we don't otherwise explicitly
1073 // reference them. This can occur for libraries which are just providing
1074 // bindings, libraries with generic functions, etc.
1076 cmd.arg("-Wl,--whole-archive").arg("-Wl,-Bstatic");
1078 let search_path = archive_search_paths(sess);
1079 for l in staticlibs {
1081 cmd.arg(format!("-l{}", l));
1083 // -force_load is the OSX equivalent of --whole-archive, but it
1084 // involves passing the full path to the library to link.
1085 let lib = archive::find_library(l[],
1086 sess.target.target.options.staticlib_prefix[],
1087 sess.target.target.options.staticlib_suffix[],
1089 &sess.diagnostic().handler);
1090 let mut v = b"-Wl,-force_load,".to_vec();
1091 v.push_all(lib.as_vec());
1096 cmd.arg("-Wl,--no-whole-archive").arg("-Wl,-Bdynamic");
1099 for &(ref l, kind) in others {
1101 cstore::NativeUnknown => {
1102 cmd.arg(format!("-l{}", l));
1104 cstore::NativeFramework => {
1105 cmd.arg("-framework").arg(l[]);
1107 cstore::NativeStatic => unreachable!(),
1112 // # Rust Crate linking
1114 // Rust crates are not considered at all when creating an rlib output. All
1115 // dependencies will be linked when producing the final output (instead of
1116 // the intermediate rlib version)
1117 fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
1118 dylib: bool, tmpdir: &Path,
1119 trans: &CrateTranslation) {
1120 // All of the heavy lifting has previously been accomplished by the
1121 // dependency_format module of the compiler. This is just crawling the
1122 // output of that module, adding crates as necessary.
1124 // Linking to a rlib involves just passing it to the linker (the linker
1125 // will slurp up the object files inside), and linking to a dynamic library
1126 // involves just passing the right -l flag.
1128 let data = if dylib {
1129 &trans.crate_formats[config::CrateTypeDylib]
1131 &trans.crate_formats[config::CrateTypeExecutable]
1134 // Invoke get_used_crates to ensure that we get a topological sorting of
1136 let deps = sess.cstore.get_used_crates(cstore::RequireDynamic);
1138 for &(cnum, _) in deps.iter() {
1139 // We may not pass all crates through to the linker. Some crates may
1140 // appear statically in an existing dylib, meaning we'll pick up all the
1141 // symbols from the dylib.
1142 let kind = match data[cnum as uint - 1] {
1146 let src = sess.cstore.get_used_crate_source(cnum).unwrap();
1148 cstore::RequireDynamic => {
1149 add_dynamic_crate(cmd, sess, src.dylib.unwrap())
1151 cstore::RequireStatic => {
1152 add_static_crate(cmd, sess, tmpdir, src.rlib.unwrap())
1158 // Converts a library file-stem into a cc -l argument
1159 fn unlib<'a>(config: &config::Config, stem: &'a [u8]) -> &'a [u8] {
1160 if stem.starts_with("lib".as_bytes()) && !config.target.options.is_like_windows {
1167 // Adds the static "rlib" versions of all crates to the command line.
1168 fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
1170 // When performing LTO on an executable output, all of the
1171 // bytecode from the upstream libraries has already been
1172 // included in our object file output. We need to modify all of
1173 // the upstream archives to remove their corresponding object
1174 // file to make sure we don't pull the same code in twice.
1176 // We must continue to link to the upstream archives to be sure
1177 // to pull in native static dependencies. As the final caveat,
1178 // on Linux it is apparently illegal to link to a blank archive,
1179 // so if an archive no longer has any object files in it after
1180 // we remove `lib.o`, then don't link against it at all.
1182 // If we're not doing LTO, then our job is simply to just link
1183 // against the archive.
1185 let name = cratepath.filename_str().unwrap();
1186 let name = name[3..name.len() - 5]; // chop off lib/.rlib
1187 time(sess.time_passes(),
1188 format!("altering {}.rlib", name)[],
1190 let dst = tmpdir.join(cratepath.filename().unwrap());
1191 match fs::copy(&cratepath, &dst) {
1194 sess.err(format!("failed to copy {} to {}: {}",
1195 cratepath.display(),
1198 sess.abort_if_errors();
1201 // Fix up permissions of the copy, as fs::copy() preserves
1202 // permissions, but the original file may have been installed
1203 // by a package manager and may be read-only.
1204 match fs::chmod(&dst, io::USER_READ | io::USER_WRITE) {
1207 sess.err(format!("failed to chmod {} when preparing \
1208 for LTO: {}", dst.display(),
1210 sess.abort_if_errors();
1213 let handler = &sess.diagnostic().handler;
1214 let config = ArchiveConfig {
1217 lib_search_paths: archive_search_paths(sess),
1218 slib_prefix: sess.target.target.options.staticlib_prefix.clone(),
1219 slib_suffix: sess.target.target.options.staticlib_suffix.clone(),
1220 maybe_ar_prog: sess.opts.cg.ar.clone()
1222 let mut archive = Archive::open(config);
1223 archive.remove_file(format!("{}.o", name)[]);
1224 let files = archive.files();
1225 if files.iter().any(|s| s[].ends_with(".o")) {
1234 // Same thing as above, but for dynamic crates instead of static crates.
1235 fn add_dynamic_crate(cmd: &mut Command, sess: &Session, cratepath: Path) {
1236 // If we're performing LTO, then it should have been previously required
1237 // that all upstream rust dependencies were available in an rlib format.
1238 assert!(!sess.lto());
1240 // Just need to tell the linker about where the library lives and
1242 let dir = cratepath.dirname();
1243 if !dir.is_empty() { cmd.arg("-L").arg(dir); }
1245 let mut v = "-l".as_bytes().to_vec();
1246 v.push_all(unlib(&sess.target, cratepath.filestem().unwrap()));
1251 // Link in all of our upstream crates' native dependencies. Remember that
1252 // all of these upstream native dependencies are all non-static
1253 // dependencies. We've got two cases then:
1255 // 1. The upstream crate is an rlib. In this case we *must* link in the
1256 // native dependency because the rlib is just an archive.
1258 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1259 // have the dependency present on the system somewhere. Thus, we don't
1260 // gain a whole lot from not linking in the dynamic dependency to this
1263 // The use case for this is a little subtle. In theory the native
1264 // dependencies of a crate are purely an implementation detail of the crate
1265 // itself, but the problem arises with generic and inlined functions. If a
1266 // generic function calls a native function, then the generic function must
1267 // be instantiated in the target crate, meaning that the native symbol must
1268 // also be resolved in the target crate.
1269 fn add_upstream_native_libraries(cmd: &mut Command, sess: &Session) {
1270 // Be sure to use a topological sorting of crates because there may be
1271 // interdependencies between native libraries. When passing -nodefaultlibs,
1272 // for example, almost all native libraries depend on libc, so we have to
1273 // make sure that's all the way at the right (liblibc is near the base of
1274 // the dependency chain).
1276 // This passes RequireStatic, but the actual requirement doesn't matter,
1277 // we're just getting an ordering of crate numbers, we're not worried about
1279 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
1280 for (cnum, _) in crates.into_iter() {
1281 let libs = csearch::get_native_libraries(&sess.cstore, cnum);
1282 for &(kind, ref lib) in libs.iter() {
1284 cstore::NativeUnknown => {
1285 cmd.arg(format!("-l{}", *lib));
1287 cstore::NativeFramework => {
1288 cmd.arg("-framework");
1291 cstore::NativeStatic => {
1292 sess.bug("statics shouldn't be propagated");