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::{self, Ty};
26 use util::common::time;
28 use util::sha2::{Digest, Sha256};
30 use std::old_io::fs::PathExtensions;
31 use std::old_io::{fs, TempDir, Command};
35 use std::string::String;
37 use serialize::hex::ToHex;
39 use syntax::ast_map::{PathElem, PathElems, PathName};
40 use syntax::attr::AttrMetaMethods;
41 use syntax::codemap::Span;
42 use syntax::parse::token;
44 // RLIB LLVM-BYTECODE OBJECT LAYOUT
47 // 0..10 "RUST_OBJECT" encoded in ASCII
48 // 11..14 format version as little-endian u32
49 // 15..22 size in bytes of deflate compressed LLVM bitcode as
51 // 23.. compressed LLVM bitcode
53 // This is the "magic number" expected at the beginning of a LLVM bytecode
55 pub const RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT";
57 // The version number this compiler will write to bytecode objects in rlibs
58 pub const RLIB_BYTECODE_OBJECT_VERSION: u32 = 1;
60 // The offset in bytes the bytecode object format version number can be found at
61 pub const RLIB_BYTECODE_OBJECT_VERSION_OFFSET: uint = 11;
63 // The offset in bytes the size of the compressed bytecode can be found at in
65 pub const RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: uint =
66 RLIB_BYTECODE_OBJECT_VERSION_OFFSET + 4;
68 // The offset in bytes the compressed LLVM bytecode can be found at in format
70 pub const RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: uint =
71 RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET + 8;
75 * Name mangling and its relationship to metadata. This is complex. Read
78 * The semantic model of Rust linkage is, broadly, that "there's no global
79 * namespace" between crates. Our aim is to preserve the illusion of this
80 * model despite the fact that it's not *quite* possible to implement on
81 * modern linkers. We initially didn't use system linkers at all, but have
82 * been convinced of their utility.
84 * There are a few issues to handle:
86 * - Linkers operate on a flat namespace, so we have to flatten names.
87 * We do this using the C++ namespace-mangling technique. Foo::bar
90 * - Symbols with the same name but different types need to get different
91 * linkage-names. We do this by hashing a string-encoding of the type into
92 * a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
93 * we use SHA256) to "prevent collisions". This is not airtight but 16 hex
94 * digits on uniform probability means you're going to need 2**32 same-name
95 * symbols in the same process before you're even hitting birthday-paradox
96 * collision probability.
98 * - Symbols in different crates but with same names "within" the crate need
99 * to get different linkage-names.
101 * - The hash shown in the filename needs to be predictable and stable for
102 * build tooling integration. It also needs to be using a hash function
103 * which is easy to use from Python, make, etc.
105 * So here is what we do:
107 * - Consider the package id; every crate has one (specified with crate_id
108 * attribute). If a package id isn't provided explicitly, we infer a
109 * versionless one from the output name. The version will end up being 0.0
110 * in this case. CNAME and CVERS are taken from this package id. For
111 * example, github.com/mozilla/CNAME#CVERS.
113 * - Define CMH as SHA256(crateid).
115 * - Define CMH8 as the first 8 characters of CMH.
117 * - Compile our crate to lib CNAME-CMH8-CVERS.so
119 * - Define STH(sym) as SHA256(CMH, type_str(sym))
121 * - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
122 * name, non-name metadata, and type sense, and versioned in the way
123 * system linkers understand.
126 pub fn find_crate_name(sess: Option<&Session>,
127 attrs: &[ast::Attribute],
128 input: &Input) -> String {
129 let validate = |s: String, span: Option<Span>| {
130 creader::validate_crate_name(sess, &s[..], span);
134 // Look in attributes 100% of the time to make sure the attribute is marked
135 // as used. After doing this, however, we still prioritize a crate name from
136 // the command line over one found in the #[crate_name] attribute. If we
137 // find both we ensure that they're the same later on as well.
138 let attr_crate_name = attrs.iter().find(|at| at.check_name("crate_name"))
139 .and_then(|at| at.value_str().map(|s| (at, s)));
141 if let Some(sess) = sess {
142 if let Some(ref s) = sess.opts.crate_name {
143 if let Some((attr, ref name)) = attr_crate_name {
145 let msg = format!("--crate-name and #[crate_name] are \
146 required to match, but `{}` != `{}`",
148 sess.span_err(attr.span, &msg[..]);
151 return validate(s.clone(), None);
155 if let Some((attr, s)) = attr_crate_name {
156 return validate(s.to_string(), Some(attr.span));
158 if let Input::File(ref path) = *input {
159 if let Some(s) = path.filestem_str() {
160 return validate(s.to_string(), None);
164 "rust-out".to_string()
167 pub fn build_link_meta(sess: &Session, krate: &ast::Crate,
168 name: String) -> LinkMeta {
171 crate_hash: Svh::calculate(&sess.opts.cg.metadata, krate),
177 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> String {
178 let output = symbol_hasher.result_bytes();
179 // 64 bits should be enough to avoid collisions.
180 output[.. 8].to_hex().to_string()
184 // This calculates STH for a symbol, as defined above
185 fn symbol_hash<'tcx>(tcx: &ty::ctxt<'tcx>,
186 symbol_hasher: &mut Sha256,
188 link_meta: &LinkMeta)
190 // NB: do *not* use abbrevs here as we want the symbol names
191 // to be independent of one another in the crate.
193 symbol_hasher.reset();
194 symbol_hasher.input_str(&link_meta.crate_name[]);
195 symbol_hasher.input_str("-");
196 symbol_hasher.input_str(link_meta.crate_hash.as_str());
197 for meta in &*tcx.sess.crate_metadata.borrow() {
198 symbol_hasher.input_str(&meta[..]);
200 symbol_hasher.input_str("-");
201 symbol_hasher.input_str(&encoder::encoded_ty(tcx, t)[]);
202 // Prefix with 'h' so that it never blends into adjacent digits
203 let mut hash = String::from_str("h");
204 hash.push_str(&truncated_hash_result(symbol_hasher)[]);
208 fn get_symbol_hash<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, t: Ty<'tcx>) -> String {
209 match ccx.type_hashcodes().borrow().get(&t) {
210 Some(h) => return h.to_string(),
214 let mut symbol_hasher = ccx.symbol_hasher().borrow_mut();
215 let hash = symbol_hash(ccx.tcx(), &mut *symbol_hasher, t, ccx.link_meta());
216 ccx.type_hashcodes().borrow_mut().insert(t, hash.clone());
221 // Name sanitation. LLVM will happily accept identifiers with weird names, but
223 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
224 pub fn sanitize(s: &str) -> String {
225 let mut result = String::new();
228 // Escape these with $ sequences
229 '@' => result.push_str("$SP$"),
230 '*' => result.push_str("$BP$"),
231 '&' => result.push_str("$RF$"),
232 '<' => result.push_str("$LT$"),
233 '>' => result.push_str("$GT$"),
234 '(' => result.push_str("$LP$"),
235 ')' => result.push_str("$RP$"),
236 ',' => result.push_str("$C$"),
238 // '.' doesn't occur in types and functions, so reuse it
240 '-' | ':' => result.push('.'),
242 // These are legal symbols
246 | '_' | '.' | '$' => result.push(c),
250 for c in c.escape_unicode().skip(1) {
253 '}' => result.push('$'),
261 // Underscore-qualify anything that didn't start as an ident.
262 if result.len() > 0 &&
263 result.as_bytes()[0] != '_' as u8 &&
264 ! (result.as_bytes()[0] as char).is_xid_start() {
265 return format!("_{}", &result[..]);
271 pub fn mangle<PI: Iterator<Item=PathElem>>(path: PI,
272 hash: Option<&str>) -> String {
273 // Follow C++ namespace-mangling style, see
274 // http://en.wikipedia.org/wiki/Name_mangling for more info.
276 // It turns out that on OSX you can actually have arbitrary symbols in
277 // function names (at least when given to LLVM), but this is not possible
278 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
279 // we won't need to do this name mangling. The problem with name mangling is
280 // that it seriously limits the available characters. For example we can't
281 // have things like &T or ~[T] in symbol names when one would theoretically
282 // want them for things like impls of traits on that type.
284 // To be able to work on all platforms and get *some* reasonable output, we
285 // use C++ name-mangling.
287 let mut n = String::from_str("_ZN"); // _Z == Begin name-sequence, N == nested
289 fn push(n: &mut String, s: &str) {
290 let sani = sanitize(s);
291 n.push_str(&format!("{}{}", sani.len(), sani)[]);
294 // First, connect each component with <len, name> pairs.
296 push(&mut n, &token::get_name(e.name()))
300 Some(s) => push(&mut n, s),
304 n.push('E'); // End name-sequence.
308 pub fn exported_name(path: PathElems, hash: &str) -> String {
309 mangle(path, Some(hash))
312 pub fn mangle_exported_name<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, path: PathElems,
313 t: Ty<'tcx>, id: ast::NodeId) -> String {
314 let mut hash = get_symbol_hash(ccx, t);
316 // Paths can be completely identical for different nodes,
317 // e.g. `fn foo() { { fn a() {} } { fn a() {} } }`, so we
318 // generate unique characters from the node id. For now
319 // hopefully 3 characters is enough to avoid collisions.
320 static EXTRA_CHARS: &'static str =
321 "abcdefghijklmnopqrstuvwxyz\
322 ABCDEFGHIJKLMNOPQRSTUVWXYZ\
325 let extra1 = id % EXTRA_CHARS.len();
326 let id = id / EXTRA_CHARS.len();
327 let extra2 = id % EXTRA_CHARS.len();
328 let id = id / EXTRA_CHARS.len();
329 let extra3 = id % EXTRA_CHARS.len();
330 hash.push(EXTRA_CHARS.as_bytes()[extra1] as char);
331 hash.push(EXTRA_CHARS.as_bytes()[extra2] as char);
332 hash.push(EXTRA_CHARS.as_bytes()[extra3] as char);
334 exported_name(path, &hash[..])
337 pub fn mangle_internal_name_by_type_and_seq<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
339 name: &str) -> String {
340 let s = ppaux::ty_to_string(ccx.tcx(), t);
341 let path = [PathName(token::intern(&s[..])),
343 let hash = get_symbol_hash(ccx, t);
344 mangle(path.iter().cloned(), Some(&hash[..]))
347 pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> String {
348 mangle(path.chain(Some(gensym_name(flav)).into_iter()), None)
351 pub fn get_cc_prog(sess: &Session) -> String {
352 match sess.opts.cg.linker {
353 Some(ref linker) => return linker.to_string(),
354 None => sess.target.target.options.linker.clone(),
358 pub fn remove(sess: &Session, path: &Path) {
359 match fs::unlink(path) {
362 sess.err(&format!("failed to remove {}: {}",
369 /// Perform the linkage portion of the compilation phase. This will generate all
370 /// of the requested outputs for this compilation session.
371 pub fn link_binary(sess: &Session,
372 trans: &CrateTranslation,
373 outputs: &OutputFilenames,
374 crate_name: &str) -> Vec<Path> {
375 let mut out_filenames = Vec::new();
376 for &crate_type in &*sess.crate_types.borrow() {
377 if invalid_output_for_target(sess, crate_type) {
378 sess.bug(&format!("invalid output type `{:?}` for target os `{}`",
379 crate_type, sess.opts.target_triple)[]);
381 let out_file = link_binary_output(sess, trans, crate_type, outputs,
383 out_filenames.push(out_file);
386 // Remove the temporary object file and metadata if we aren't saving temps
387 if !sess.opts.cg.save_temps {
388 let obj_filename = outputs.temp_path(OutputTypeObject);
389 if !sess.opts.output_types.contains(&OutputTypeObject) {
390 remove(sess, &obj_filename);
392 remove(sess, &obj_filename.with_extension("metadata.o"));
399 /// Returns default crate type for target
401 /// Default crate type is used when crate type isn't provided neither
402 /// through cmd line arguments nor through crate attributes
404 /// It is CrateTypeExecutable for all platforms but iOS as there is no
405 /// way to run iOS binaries anyway without jailbreaking and
406 /// interaction with Rust code through static library is the only
408 pub fn default_output_for_target(sess: &Session) -> config::CrateType {
409 if !sess.target.target.options.executables {
410 config::CrateTypeStaticlib
412 config::CrateTypeExecutable
416 /// Checks if target supports crate_type as output
417 pub fn invalid_output_for_target(sess: &Session,
418 crate_type: config::CrateType) -> bool {
419 match (sess.target.target.options.dynamic_linking,
420 sess.target.target.options.executables, crate_type) {
421 (false, _, config::CrateTypeDylib) => true,
422 (_, false, config::CrateTypeExecutable) => true,
427 fn is_writeable(p: &Path) -> bool {
430 Ok(m) => m.perm & old_io::USER_WRITE == old_io::USER_WRITE
434 pub fn filename_for_input(sess: &Session,
435 crate_type: config::CrateType,
437 out_filename: &Path) -> Path {
438 let libname = format!("{}{}", name, sess.opts.cg.extra_filename);
440 config::CrateTypeRlib => {
441 out_filename.with_filename(format!("lib{}.rlib", libname))
443 config::CrateTypeDylib => {
444 let (prefix, suffix) = (&sess.target.target.options.dll_prefix[],
445 &sess.target.target.options.dll_suffix[]);
446 out_filename.with_filename(format!("{}{}{}",
451 config::CrateTypeStaticlib => {
452 out_filename.with_filename(format!("lib{}.a", libname))
454 config::CrateTypeExecutable => {
455 let suffix = &sess.target.target.options.exe_suffix[];
456 out_filename.with_filename(format!("{}{}", libname, suffix))
461 fn link_binary_output(sess: &Session,
462 trans: &CrateTranslation,
463 crate_type: config::CrateType,
464 outputs: &OutputFilenames,
465 crate_name: &str) -> Path {
466 let obj_filename = outputs.temp_path(OutputTypeObject);
467 let out_filename = match outputs.single_output_file {
468 Some(ref file) => file.clone(),
470 let out_filename = outputs.path(OutputTypeExe);
471 filename_for_input(sess, crate_type, crate_name, &out_filename)
475 // Make sure the output and obj_filename are both writeable.
476 // Mac, FreeBSD, and Windows system linkers check this already --
477 // however, the Linux linker will happily overwrite a read-only file.
478 // We should be consistent.
479 let obj_is_writeable = is_writeable(&obj_filename);
480 let out_is_writeable = is_writeable(&out_filename);
481 if !out_is_writeable {
482 sess.fatal(&format!("output file {} is not writeable -- check its \
484 out_filename.display())[]);
486 else if !obj_is_writeable {
487 sess.fatal(&format!("object file {} is not writeable -- check its \
489 obj_filename.display())[]);
493 config::CrateTypeRlib => {
494 link_rlib(sess, Some(trans), &obj_filename, &out_filename).build();
496 config::CrateTypeStaticlib => {
497 link_staticlib(sess, &obj_filename, &out_filename);
499 config::CrateTypeExecutable => {
500 link_natively(sess, trans, false, &obj_filename, &out_filename);
502 config::CrateTypeDylib => {
503 link_natively(sess, trans, true, &obj_filename, &out_filename);
510 fn archive_search_paths(sess: &Session) -> Vec<Path> {
511 let mut search = Vec::new();
512 sess.target_filesearch(PathKind::Native).for_each_lib_search_path(|path, _| {
513 search.push(path.clone());
521 // An rlib in its current incarnation is essentially a renamed .a file. The
522 // rlib primarily contains the object file of the crate, but it also contains
523 // all of the object files from native libraries. This is done by unzipping
524 // native libraries and inserting all of the contents into this archive.
525 fn link_rlib<'a>(sess: &'a Session,
526 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
528 out_filename: &Path) -> ArchiveBuilder<'a> {
529 let handler = &sess.diagnostic().handler;
530 let config = ArchiveConfig {
532 dst: out_filename.clone(),
533 lib_search_paths: archive_search_paths(sess),
534 slib_prefix: sess.target.target.options.staticlib_prefix.clone(),
535 slib_suffix: sess.target.target.options.staticlib_suffix.clone(),
536 maybe_ar_prog: sess.opts.cg.ar.clone()
538 let mut ab = ArchiveBuilder::create(config);
539 ab.add_file(obj_filename).unwrap();
541 for &(ref l, kind) in &*sess.cstore.get_used_libraries().borrow() {
543 cstore::NativeStatic => {
544 ab.add_native_library(&l[..]).unwrap();
546 cstore::NativeFramework | cstore::NativeUnknown => {}
550 // After adding all files to the archive, we need to update the
551 // symbol table of the archive.
554 let mut ab = match sess.target.target.options.is_like_osx {
555 // For OSX/iOS, we must be careful to update symbols only when adding
556 // object files. We're about to start adding non-object files, so run
557 // `ar` now to process the object files.
558 true => ab.build().extend(),
562 // Note that it is important that we add all of our non-object "magical
563 // files" *after* all of the object files in the archive. The reason for
564 // this is as follows:
566 // * When performing LTO, this archive will be modified to remove
567 // obj_filename from above. The reason for this is described below.
569 // * When the system linker looks at an archive, it will attempt to
570 // determine the architecture of the archive in order to see whether its
573 // The algorithm for this detection is: iterate over the files in the
574 // archive. Skip magical SYMDEF names. Interpret the first file as an
575 // object file. Read architecture from the object file.
577 // * As one can probably see, if "metadata" and "foo.bc" were placed
578 // before all of the objects, then the architecture of this archive would
579 // not be correctly inferred once 'foo.o' is removed.
581 // Basically, all this means is that this code should not move above the
585 // Instead of putting the metadata in an object file section, rlibs
586 // contain the metadata in a separate file. We use a temp directory
587 // here so concurrent builds in the same directory don't try to use
588 // the same filename for metadata (stomping over one another)
589 let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
590 let metadata = tmpdir.path().join(METADATA_FILENAME);
591 match fs::File::create(&metadata).write_all(&trans.metadata[]) {
594 sess.err(&format!("failed to write {}: {}",
597 sess.abort_if_errors();
600 ab.add_file(&metadata).unwrap();
601 remove(sess, &metadata);
603 // For LTO purposes, the bytecode of this library is also inserted
604 // into the archive. If codegen_units > 1, we insert each of the
606 for i in 0..sess.opts.cg.codegen_units {
607 // Note that we make sure that the bytecode filename in the
608 // archive is never exactly 16 bytes long by adding a 16 byte
609 // extension to it. This is to work around a bug in LLDB that
610 // would cause it to crash if the name of a file in an archive
611 // was exactly 16 bytes.
612 let bc_filename = obj_filename.with_extension(&format!("{}.bc", i));
613 let bc_deflated_filename = obj_filename.with_extension(
614 &format!("{}.bytecode.deflate", i)[]);
616 let bc_data = match fs::File::open(&bc_filename).read_to_end() {
617 Ok(buffer) => buffer,
618 Err(e) => sess.fatal(&format!("failed to read bytecode: {}",
622 let bc_data_deflated = match flate::deflate_bytes(&bc_data[..]) {
623 Some(compressed) => compressed,
624 None => sess.fatal(&format!("failed to compress bytecode from {}",
625 bc_filename.display())[])
628 let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) {
631 sess.fatal(&format!("failed to create compressed bytecode \
636 match write_rlib_bytecode_object_v1(&mut bc_file_deflated,
637 bc_data_deflated.as_slice()) {
640 sess.err(&format!("failed to write compressed bytecode: \
642 sess.abort_if_errors()
646 ab.add_file(&bc_deflated_filename).unwrap();
647 remove(sess, &bc_deflated_filename);
649 // See the bottom of back::write::run_passes for an explanation
650 // of when we do and don't keep .0.bc files around.
651 let user_wants_numbered_bitcode =
652 sess.opts.output_types.contains(&OutputTypeBitcode) &&
653 sess.opts.cg.codegen_units > 1;
654 if !sess.opts.cg.save_temps && !user_wants_numbered_bitcode {
655 remove(sess, &bc_filename);
659 // After adding all files to the archive, we need to update the
660 // symbol table of the archive. This currently dies on OSX (see
661 // #11162), and isn't necessary there anyway
662 if !sess.target.target.options.is_like_osx {
673 fn write_rlib_bytecode_object_v1<T: Writer>(writer: &mut T,
674 bc_data_deflated: &[u8])
675 -> ::std::old_io::IoResult<()> {
676 let bc_data_deflated_size: u64 = bc_data_deflated.len() as u64;
678 try! { writer.write_all(RLIB_BYTECODE_OBJECT_MAGIC) };
679 try! { writer.write_le_u32(1) };
680 try! { writer.write_le_u64(bc_data_deflated_size) };
681 try! { writer.write_all(&bc_data_deflated[..]) };
683 let number_of_bytes_written_so_far =
684 RLIB_BYTECODE_OBJECT_MAGIC.len() + // magic id
685 mem::size_of_val(&RLIB_BYTECODE_OBJECT_VERSION) + // version
686 mem::size_of_val(&bc_data_deflated_size) + // data size field
687 bc_data_deflated_size as uint; // actual data
689 // If the number of bytes written to the object so far is odd, add a
690 // padding byte to make it even. This works around a crash bug in LLDB
691 // (see issue #15950)
692 if number_of_bytes_written_so_far % 2 == 1 {
693 try! { writer.write_u8(0) };
699 // Create a static archive
701 // This is essentially the same thing as an rlib, but it also involves adding
702 // all of the upstream crates' objects into the archive. This will slurp in
703 // all of the native libraries of upstream dependencies as well.
705 // Additionally, there's no way for us to link dynamic libraries, so we warn
706 // about all dynamic library dependencies that they're not linked in.
708 // There's no need to include metadata in a static archive, so ensure to not
709 // link in the metadata object file (and also don't prepare the archive with a
711 fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) {
712 let ab = link_rlib(sess, None, obj_filename, out_filename);
713 let mut ab = match sess.target.target.options.is_like_osx {
714 true => ab.build().extend(),
717 if sess.target.target.options.morestack {
718 ab.add_native_library("morestack").unwrap();
720 if !sess.target.target.options.no_compiler_rt {
721 ab.add_native_library("compiler-rt").unwrap();
724 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
725 let mut all_native_libs = vec![];
727 for &(cnum, ref path) in &crates {
728 let ref name = sess.cstore.get_crate_data(cnum).name;
729 let p = match *path {
730 Some(ref p) => p.clone(), None => {
731 sess.err(&format!("could not find rlib for: `{}`",
736 ab.add_rlib(&p, &name[..], sess.lto()).unwrap();
738 let native_libs = csearch::get_native_libraries(&sess.cstore, cnum);
739 all_native_libs.extend(native_libs.into_iter());
745 if !all_native_libs.is_empty() {
746 sess.note("link against the following native artifacts when linking against \
747 this static library");
748 sess.note("the order and any duplication can be significant on some platforms, \
749 and so may need to be preserved");
752 for &(kind, ref lib) in &all_native_libs {
753 let name = match kind {
754 cstore::NativeStatic => "static library",
755 cstore::NativeUnknown => "library",
756 cstore::NativeFramework => "framework",
758 sess.note(&format!("{}: {}", name, *lib)[]);
762 // Create a dynamic library or executable
764 // This will invoke the system linker/cc to create the resulting file. This
765 // links to all upstream files as well.
766 fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
767 obj_filename: &Path, out_filename: &Path) {
768 let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
770 // The invocations of cc share some flags across platforms
771 let pname = get_cc_prog(sess);
772 let mut cmd = Command::new(&pname[..]);
774 cmd.args(&sess.target.target.options.pre_link_args[]);
775 link_args(&mut cmd, sess, dylib, tmpdir.path(),
776 trans, obj_filename, out_filename);
777 cmd.args(&sess.target.target.options.post_link_args[]);
778 if !sess.target.target.options.no_compiler_rt {
779 cmd.arg("-lcompiler-rt");
782 if sess.opts.debugging_opts.print_link_args {
783 println!("{:?}", &cmd);
786 // May have not found libraries in the right formats.
787 sess.abort_if_errors();
789 // Invoke the system linker
790 debug!("{:?}", &cmd);
791 let prog = time(sess.time_passes(), "running linker", (), |()| cmd.output());
794 if !prog.status.success() {
795 sess.err(&format!("linking with `{}` failed: {}",
798 sess.note(&format!("{:?}", &cmd)[]);
799 let mut output = prog.error.clone();
800 output.push_all(&prog.output[]);
801 sess.note(str::from_utf8(&output[..]).unwrap());
802 sess.abort_if_errors();
804 debug!("linker stderr:\n{}", String::from_utf8(prog.error).unwrap());
805 debug!("linker stdout:\n{}", String::from_utf8(prog.output).unwrap());
808 sess.err(&format!("could not exec the linker `{}`: {}",
811 sess.abort_if_errors();
816 // On OSX, debuggers need this utility to get run to do some munging of
818 if sess.target.target.options.is_like_osx && sess.opts.debuginfo != NoDebugInfo {
819 match Command::new("dsymutil").arg(out_filename).output() {
822 sess.err(&format!("failed to run dsymutil: {}", e)[]);
823 sess.abort_if_errors();
829 fn link_args(cmd: &mut Command,
833 trans: &CrateTranslation,
835 out_filename: &Path) {
837 // The default library location, we need this to find the runtime.
838 // The location of crates will be determined as needed.
839 let lib_path = sess.target_filesearch(PathKind::All).get_lib_path();
842 let t = &sess.target.target;
844 cmd.arg("-L").arg(&lib_path);
846 cmd.arg("-o").arg(out_filename).arg(obj_filename);
849 // Stack growth requires statically linking a __morestack function. Note
850 // that this is listed *before* all other libraries. Due to the usage of the
851 // --as-needed flag below, the standard library may only be useful for its
852 // rust_stack_exhausted function. In this case, we must ensure that the
853 // libmorestack.a file appears *before* the standard library (so we put it
854 // at the very front).
856 // Most of the time this is sufficient, except for when LLVM gets super
857 // clever. If, for example, we have a main function `fn main() {}`, LLVM
858 // will optimize out calls to `__morestack` entirely because the function
859 // doesn't need any stack at all!
861 // To get around this snag, we specially tell the linker to always include
862 // all contents of this library. This way we're guaranteed that the linker
863 // will include the __morestack symbol 100% of the time, always resolving
864 // references to it even if the object above didn't use it.
865 if t.options.morestack {
866 if t.options.is_like_osx {
867 let morestack = lib_path.join("libmorestack.a");
869 let mut v = b"-Wl,-force_load,".to_vec();
870 v.push_all(morestack.as_vec());
873 cmd.args(&["-Wl,--whole-archive", "-lmorestack", "-Wl,--no-whole-archive"]);
877 // When linking a dynamic library, we put the metadata into a section of the
878 // executable. This metadata is in a separate object file from the main
879 // object file, so we link that in here.
881 cmd.arg(obj_filename.with_extension("metadata.o"));
884 if t.options.is_like_osx {
885 // The dead_strip option to the linker specifies that functions and data
886 // unreachable by the entry point will be removed. This is quite useful
887 // with Rust's compilation model of compiling libraries at a time into
888 // one object file. For example, this brings hello world from 1.7MB to
891 // Note that this is done for both executables and dynamic libraries. We
892 // won't get much benefit from dylibs because LLVM will have already
893 // stripped away as much as it could. This has not been seen to impact
894 // link times negatively.
896 // -dead_strip can't be part of the pre_link_args because it's also used for partial
897 // linking when using multiple codegen units (-r). So we insert it here.
898 cmd.arg("-Wl,-dead_strip");
901 // If we're building a dylib, we don't use --gc-sections because LLVM has
902 // already done the best it can do, and we also don't want to eliminate the
903 // metadata. If we're building an executable, however, --gc-sections drops
904 // the size of hello world from 1.8MB to 597K, a 67% reduction.
905 if !dylib && !t.options.is_like_osx {
906 cmd.arg("-Wl,--gc-sections");
909 let used_link_args = sess.cstore.get_used_link_args().borrow();
911 if t.options.position_independent_executables {
912 let empty_vec = Vec::new();
913 let empty_str = String::new();
914 let args = sess.opts.cg.link_args.as_ref().unwrap_or(&empty_vec);
915 let mut args = args.iter().chain(used_link_args.iter());
917 && (t.options.relocation_model == "pic"
918 || *sess.opts.cg.relocation_model.as_ref()
919 .unwrap_or(&empty_str) == "pic")
920 && !args.any(|x| *x == "-static") {
925 if t.options.linker_is_gnu {
926 // GNU-style linkers support optimization with -O. GNU ld doesn't need a
927 // numeric argument, but other linkers do.
928 if sess.opts.optimize == config::Default ||
929 sess.opts.optimize == config::Aggressive {
934 // We want to prevent the compiler from accidentally leaking in any system
935 // libraries, so we explicitly ask gcc to not link to any libraries by
936 // default. Note that this does not happen for windows because windows pulls
937 // in some large number of libraries and I couldn't quite figure out which
939 if !t.options.is_like_windows {
940 cmd.arg("-nodefaultlibs");
943 // Mark all dynamic libraries and executables as compatible with ASLR
944 // FIXME #17098: ASLR breaks gdb
945 if t.options.is_like_windows && sess.opts.debuginfo == NoDebugInfo {
946 // cmd.arg("-Wl,--dynamicbase");
949 // Take careful note of the ordering of the arguments we pass to the linker
950 // here. Linkers will assume that things on the left depend on things to the
951 // right. Things on the right cannot depend on things on the left. This is
952 // all formally implemented in terms of resolving symbols (libs on the right
953 // resolve unknown symbols of libs on the left, but not vice versa).
955 // For this reason, we have organized the arguments we pass to the linker as
958 // 1. The local object that LLVM just generated
959 // 2. Upstream rust libraries
960 // 3. Local native libraries
961 // 4. Upstream native libraries
963 // This is generally fairly natural, but some may expect 2 and 3 to be
964 // swapped. The reason that all native libraries are put last is that it's
965 // not recommended for a native library to depend on a symbol from a rust
966 // crate. If this is the case then a staticlib crate is recommended, solving
969 // Additionally, it is occasionally the case that upstream rust libraries
970 // depend on a local native library. In the case of libraries such as
971 // lua/glfw/etc the name of the library isn't the same across all platforms,
972 // so only the consumer crate of a library knows the actual name. This means
973 // that downstream crates will provide the #[link] attribute which upstream
974 // crates will depend on. Hence local native libraries are after out
975 // upstream rust crates.
977 // In theory this means that a symbol in an upstream native library will be
978 // shadowed by a local native library when it wouldn't have been before, but
979 // this kind of behavior is pretty platform specific and generally not
980 // recommended anyway, so I don't think we're shooting ourself in the foot
982 add_upstream_rust_crates(cmd, sess, dylib, tmpdir, trans);
983 add_local_native_libraries(cmd, sess);
984 add_upstream_native_libraries(cmd, sess);
986 // # Telling the linker what we're doing
989 // On mac we need to tell the linker to let this library be rpathed
990 if sess.target.target.options.is_like_osx {
991 cmd.args(&["-dynamiclib", "-Wl,-dylib"]);
993 if sess.opts.cg.rpath {
994 let mut v = "-Wl,-install_name,@rpath/".as_bytes().to_vec();
995 v.push_all(out_filename.filename().unwrap());
1003 // FIXME (#2397): At some point we want to rpath our guesses as to
1004 // where extern libraries might live, based on the
1005 // addl_lib_search_paths
1006 if sess.opts.cg.rpath {
1007 let sysroot = sess.sysroot();
1008 let target_triple = &sess.opts.target_triple[];
1009 let get_install_prefix_lib_path = || {
1010 let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1011 let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1012 let mut path = Path::new(install_prefix);
1017 let rpath_config = RPathConfig {
1018 used_crates: sess.cstore.get_used_crates(cstore::RequireDynamic),
1019 out_filename: out_filename.clone(),
1020 has_rpath: sess.target.target.options.has_rpath,
1021 is_like_osx: sess.target.target.options.is_like_osx,
1022 get_install_prefix_lib_path: get_install_prefix_lib_path,
1023 realpath: ::util::fs::realpath
1025 cmd.args(&rpath::get_rpath_flags(rpath_config)[]);
1028 // Finally add all the linker arguments provided on the command line along
1029 // with any #[link_args] attributes found inside the crate
1030 let empty = Vec::new();
1031 cmd.args(&sess.opts.cg.link_args.as_ref().unwrap_or(&empty)[]);
1032 cmd.args(&used_link_args[..]);
1035 // # Native library linking
1037 // User-supplied library search paths (-L on the command line). These are
1038 // the same paths used to find Rust crates, so some of them may have been
1039 // added already by the previous crate linking code. This only allows them
1040 // to be found at compile time so it is still entirely up to outside
1041 // forces to make sure that library can be found at runtime.
1043 // Also note that the native libraries linked here are only the ones located
1044 // in the current crate. Upstream crates with native library dependencies
1045 // may have their native library pulled in above.
1046 fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
1047 sess.target_filesearch(PathKind::All).for_each_lib_search_path(|path, k| {
1049 PathKind::Framework => { cmd.arg("-F").arg(path); }
1050 _ => { cmd.arg("-L").arg(path); }
1055 // Some platforms take hints about whether a library is static or dynamic.
1056 // For those that support this, we ensure we pass the option if the library
1057 // was flagged "static" (most defaults are dynamic) to ensure that if
1058 // libfoo.a and libfoo.so both exist that the right one is chosen.
1059 let takes_hints = !sess.target.target.options.is_like_osx;
1061 let libs = sess.cstore.get_used_libraries();
1062 let libs = libs.borrow();
1064 let staticlibs = libs.iter().filter_map(|&(ref l, kind)| {
1065 if kind == cstore::NativeStatic {Some(l)} else {None}
1067 let others = libs.iter().filter(|&&(_, kind)| {
1068 kind != cstore::NativeStatic
1071 // Platforms that take hints generally also support the --whole-archive
1072 // flag. We need to pass this flag when linking static native libraries to
1073 // ensure the entire library is included.
1075 // For more details see #15460, but the gist is that the linker will strip
1076 // away any unused objects in the archive if we don't otherwise explicitly
1077 // reference them. This can occur for libraries which are just providing
1078 // bindings, libraries with generic functions, etc.
1080 cmd.arg("-Wl,--whole-archive").arg("-Wl,-Bstatic");
1082 let search_path = archive_search_paths(sess);
1083 for l in staticlibs {
1085 cmd.arg(format!("-l{}", l));
1087 // -force_load is the OSX equivalent of --whole-archive, but it
1088 // involves passing the full path to the library to link.
1089 let lib = archive::find_library(&l[..],
1090 &sess.target.target.options.staticlib_prefix,
1091 &sess.target.target.options.staticlib_suffix,
1093 &sess.diagnostic().handler);
1094 let mut v = b"-Wl,-force_load,".to_vec();
1095 v.push_all(lib.as_vec());
1100 cmd.arg("-Wl,--no-whole-archive").arg("-Wl,-Bdynamic");
1103 for &(ref l, kind) in others {
1105 cstore::NativeUnknown => {
1106 cmd.arg(format!("-l{}", l));
1108 cstore::NativeFramework => {
1109 cmd.arg("-framework").arg(&l[..]);
1111 cstore::NativeStatic => unreachable!(),
1116 // # Rust Crate linking
1118 // Rust crates are not considered at all when creating an rlib output. All
1119 // dependencies will be linked when producing the final output (instead of
1120 // the intermediate rlib version)
1121 fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
1122 dylib: bool, tmpdir: &Path,
1123 trans: &CrateTranslation) {
1124 // All of the heavy lifting has previously been accomplished by the
1125 // dependency_format module of the compiler. This is just crawling the
1126 // output of that module, adding crates as necessary.
1128 // Linking to a rlib involves just passing it to the linker (the linker
1129 // will slurp up the object files inside), and linking to a dynamic library
1130 // involves just passing the right -l flag.
1132 let data = if dylib {
1133 &trans.crate_formats[config::CrateTypeDylib]
1135 &trans.crate_formats[config::CrateTypeExecutable]
1138 // Invoke get_used_crates to ensure that we get a topological sorting of
1140 let deps = sess.cstore.get_used_crates(cstore::RequireDynamic);
1142 for &(cnum, _) in &deps {
1143 // We may not pass all crates through to the linker. Some crates may
1144 // appear statically in an existing dylib, meaning we'll pick up all the
1145 // symbols from the dylib.
1146 let kind = match data[cnum as uint - 1] {
1150 let src = sess.cstore.get_used_crate_source(cnum).unwrap();
1152 cstore::RequireDynamic => {
1153 add_dynamic_crate(cmd, sess, src.dylib.unwrap().0)
1155 cstore::RequireStatic => {
1156 add_static_crate(cmd, sess, tmpdir, src.rlib.unwrap().0)
1162 // Converts a library file-stem into a cc -l argument
1163 fn unlib<'a>(config: &config::Config, stem: &'a [u8]) -> &'a [u8] {
1164 if stem.starts_with("lib".as_bytes()) && !config.target.options.is_like_windows {
1171 // Adds the static "rlib" versions of all crates to the command line.
1172 fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
1174 // When performing LTO on an executable output, all of the
1175 // bytecode from the upstream libraries has already been
1176 // included in our object file output. We need to modify all of
1177 // the upstream archives to remove their corresponding object
1178 // file to make sure we don't pull the same code in twice.
1180 // We must continue to link to the upstream archives to be sure
1181 // to pull in native static dependencies. As the final caveat,
1182 // on Linux it is apparently illegal to link to a blank archive,
1183 // so if an archive no longer has any object files in it after
1184 // we remove `lib.o`, then don't link against it at all.
1186 // If we're not doing LTO, then our job is simply to just link
1187 // against the archive.
1189 let name = cratepath.filename_str().unwrap();
1190 let name = &name[3..name.len() - 5]; // chop off lib/.rlib
1191 time(sess.time_passes(),
1192 &format!("altering {}.rlib", name)[],
1194 let dst = tmpdir.join(cratepath.filename().unwrap());
1195 match fs::copy(&cratepath, &dst) {
1198 sess.err(&format!("failed to copy {} to {}: {}",
1199 cratepath.display(),
1202 sess.abort_if_errors();
1205 // Fix up permissions of the copy, as fs::copy() preserves
1206 // permissions, but the original file may have been installed
1207 // by a package manager and may be read-only.
1208 match fs::chmod(&dst, old_io::USER_READ | old_io::USER_WRITE) {
1211 sess.err(&format!("failed to chmod {} when preparing \
1212 for LTO: {}", dst.display(),
1214 sess.abort_if_errors();
1217 let handler = &sess.diagnostic().handler;
1218 let config = ArchiveConfig {
1221 lib_search_paths: archive_search_paths(sess),
1222 slib_prefix: sess.target.target.options.staticlib_prefix.clone(),
1223 slib_suffix: sess.target.target.options.staticlib_suffix.clone(),
1224 maybe_ar_prog: sess.opts.cg.ar.clone()
1226 let mut archive = Archive::open(config);
1227 archive.remove_file(&format!("{}.o", name)[]);
1228 let files = archive.files();
1229 if files.iter().any(|s| s[].ends_with(".o")) {
1238 // Same thing as above, but for dynamic crates instead of static crates.
1239 fn add_dynamic_crate(cmd: &mut Command, sess: &Session, cratepath: Path) {
1240 // If we're performing LTO, then it should have been previously required
1241 // that all upstream rust dependencies were available in an rlib format.
1242 assert!(!sess.lto());
1244 // Just need to tell the linker about where the library lives and
1246 let dir = cratepath.dirname();
1247 if !dir.is_empty() { cmd.arg("-L").arg(dir); }
1249 let mut v = "-l".as_bytes().to_vec();
1250 v.push_all(unlib(&sess.target, cratepath.filestem().unwrap()));
1255 // Link in all of our upstream crates' native dependencies. Remember that
1256 // all of these upstream native dependencies are all non-static
1257 // dependencies. We've got two cases then:
1259 // 1. The upstream crate is an rlib. In this case we *must* link in the
1260 // native dependency because the rlib is just an archive.
1262 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1263 // have the dependency present on the system somewhere. Thus, we don't
1264 // gain a whole lot from not linking in the dynamic dependency to this
1267 // The use case for this is a little subtle. In theory the native
1268 // dependencies of a crate are purely an implementation detail of the crate
1269 // itself, but the problem arises with generic and inlined functions. If a
1270 // generic function calls a native function, then the generic function must
1271 // be instantiated in the target crate, meaning that the native symbol must
1272 // also be resolved in the target crate.
1273 fn add_upstream_native_libraries(cmd: &mut Command, sess: &Session) {
1274 // Be sure to use a topological sorting of crates because there may be
1275 // interdependencies between native libraries. When passing -nodefaultlibs,
1276 // for example, almost all native libraries depend on libc, so we have to
1277 // make sure that's all the way at the right (liblibc is near the base of
1278 // the dependency chain).
1280 // This passes RequireStatic, but the actual requirement doesn't matter,
1281 // we're just getting an ordering of crate numbers, we're not worried about
1283 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
1284 for (cnum, _) in crates {
1285 let libs = csearch::get_native_libraries(&sess.cstore, cnum);
1286 for &(kind, ref lib) in &libs {
1288 cstore::NativeUnknown => {
1289 cmd.arg(format!("-l{}", *lib));
1291 cstore::NativeFramework => {
1292 cmd.arg("-framework");
1295 cstore::NativeStatic => {
1296 sess.bug("statics shouldn't be propagated");