1 // Copyright 2012-2013 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.
12 use back::archive::{Archive, METADATA_FILENAME};
14 use driver::driver::CrateTranslation;
15 use driver::session::Session;
18 use lib::llvm::ModuleRef;
20 use metadata::common::LinkMeta;
21 use metadata::{encoder, cstore, filesearch, csearch};
22 use middle::trans::context::CrateContext;
23 use middle::trans::common::gensym_name;
25 use util::common::time;
27 use util::sha2::{Digest, Sha256};
29 use std::c_str::ToCStr;
31 use std::os::consts::{macos, freebsd, linux, android, win32};
37 use extra::hex::ToHex;
38 use extra::tempfile::TempDir;
41 use syntax::ast_map::{PathMod, PathName, PathPrettyName};
44 use syntax::attr::AttrMetaMethods;
45 use syntax::crateid::CrateId;
47 #[deriving(Clone, Eq)]
52 OutputTypeLlvmAssembly,
57 pub fn llvm_err(sess: Session, msg: ~str) -> ! {
59 let cstr = llvm::LLVMRustGetLastError();
60 if cstr == ptr::null() {
63 sess.fatal(msg + ": " + str::raw::from_c_str(cstr));
68 pub fn WriteOutputFile(
70 Target: lib::llvm::TargetMachineRef,
71 PM: lib::llvm::PassManagerRef,
74 FileType: lib::llvm::FileType) {
76 Output.with_c_str(|Output| {
77 let result = llvm::LLVMRustWriteOutputFile(
78 Target, PM, M, Output, FileType);
80 llvm_err(sess, ~"Could not write output");
89 use back::link::{WriteOutputFile, OutputType};
90 use back::link::{OutputTypeAssembly, OutputTypeBitcode};
91 use back::link::{OutputTypeExe, OutputTypeLlvmAssembly};
92 use back::link::{OutputTypeObject};
93 use driver::driver::CrateTranslation;
94 use driver::session::Session;
97 use lib::llvm::{ModuleRef, TargetMachineRef, PassManagerRef};
99 use util::common::time;
101 use std::c_str::ToCStr;
103 use std::libc::{c_uint, c_int};
108 pub fn run_passes(sess: Session,
109 trans: &CrateTranslation,
110 output_type: OutputType,
112 let llmod = trans.module;
113 let llcx = trans.context;
115 configure_llvm(sess);
117 if sess.opts.save_temps {
118 output.with_extension("no-opt.bc").with_c_str(|buf| {
119 llvm::LLVMWriteBitcodeToFile(llmod, buf);
123 let OptLevel = match sess.opts.optimize {
124 session::No => lib::llvm::CodeGenLevelNone,
125 session::Less => lib::llvm::CodeGenLevelLess,
126 session::Default => lib::llvm::CodeGenLevelDefault,
127 session::Aggressive => lib::llvm::CodeGenLevelAggressive,
129 let use_softfp = sess.opts.debugging_opts & session::use_softfp != 0;
131 let tm = sess.targ_cfg.target_strs.target_triple.with_c_str(|T| {
132 sess.opts.target_cpu.with_c_str(|CPU| {
133 sess.opts.target_feature.with_c_str(|Features| {
134 llvm::LLVMRustCreateTargetMachine(
136 lib::llvm::CodeModelDefault,
146 // Create the two optimizing pass managers. These mirror what clang
147 // does, and are by populated by LLVM's default PassManagerBuilder.
148 // Each manager has a different set of passes, but they also share
149 // some common passes.
150 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
151 let mpm = llvm::LLVMCreatePassManager();
153 // If we're verifying or linting, add them to the function pass
155 let addpass = |pass: &str| {
156 pass.with_c_str(|s| llvm::LLVMRustAddPass(fpm, s))
158 if !sess.no_verify() { assert!(addpass("verify")); }
159 if sess.lint_llvm() { assert!(addpass("lint")); }
161 if !sess.no_prepopulate_passes() {
162 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
163 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
164 populate_llvm_passes(fpm, mpm, llmod, OptLevel);
167 for pass in sess.opts.custom_passes.iter() {
168 pass.with_c_str(|s| {
169 if !llvm::LLVMRustAddPass(mpm, s) {
170 sess.warn(format!("Unknown pass {}, ignoring", *pass));
175 // Finally, run the actual optimization passes
176 time(sess.time_passes(), "llvm function passes", (), |()|
177 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
178 time(sess.time_passes(), "llvm module passes", (), |()|
179 llvm::LLVMRunPassManager(mpm, llmod));
181 // Deallocate managers that we're now done with
182 llvm::LLVMDisposePassManager(fpm);
183 llvm::LLVMDisposePassManager(mpm);
185 // Emit the bytecode if we're either saving our temporaries or
186 // emitting an rlib. Whenever an rlib is create, the bytecode is
187 // inserted into the archive in order to allow LTO against it.
188 let outputs = sess.outputs.borrow();
189 if sess.opts.save_temps ||
190 outputs.get().iter().any(|&o| o == session::OutputRlib) {
191 output.with_extension("bc").with_c_str(|buf| {
192 llvm::LLVMWriteBitcodeToFile(llmod, buf);
197 time(sess.time_passes(), "all lto passes", (), |()|
198 lto::run(sess, llmod, tm, trans.reachable));
200 if sess.opts.save_temps {
201 output.with_extension("lto.bc").with_c_str(|buf| {
202 llvm::LLVMWriteBitcodeToFile(llmod, buf);
207 // A codegen-specific pass manager is used to generate object
208 // files for an LLVM module.
210 // Apparently each of these pass managers is a one-shot kind of
211 // thing, so we create a new one for each type of output. The
212 // pass manager passed to the closure should be ensured to not
213 // escape the closure itself, and the manager should only be
215 fn with_codegen(tm: TargetMachineRef, llmod: ModuleRef,
216 f: |PassManagerRef|) {
218 let cpm = llvm::LLVMCreatePassManager();
219 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
220 llvm::LLVMRustAddLibraryInfo(cpm, llmod);
222 llvm::LLVMDisposePassManager(cpm);
226 time(sess.time_passes(), "codegen passes", (), |()| {
229 OutputTypeBitcode => {
230 output.with_c_str(|buf| {
231 llvm::LLVMWriteBitcodeToFile(llmod, buf);
234 OutputTypeLlvmAssembly => {
235 output.with_c_str(|output| {
236 with_codegen(tm, llmod, |cpm| {
237 llvm::LLVMRustPrintModule(cpm, llmod, output);
241 OutputTypeAssembly => {
242 with_codegen(tm, llmod, |cpm| {
243 WriteOutputFile(sess, tm, cpm, llmod, output,
244 lib::llvm::AssemblyFile);
247 // If we're not using the LLVM assembler, this function
248 // could be invoked specially with output_type_assembly,
249 // so in this case we still want the metadata object
251 if sess.opts.output_type != OutputTypeAssembly {
252 with_codegen(tm, trans.metadata_module, |cpm| {
253 let out = output.with_extension("metadata.o");
254 WriteOutputFile(sess, tm, cpm,
255 trans.metadata_module, &out,
256 lib::llvm::ObjectFile);
260 OutputTypeExe | OutputTypeObject => {
261 with_codegen(tm, llmod, |cpm| {
262 WriteOutputFile(sess, tm, cpm, llmod, output,
263 lib::llvm::ObjectFile);
265 with_codegen(tm, trans.metadata_module, |cpm| {
266 let out = output.with_extension("metadata.o");
267 WriteOutputFile(sess, tm, cpm,
268 trans.metadata_module, &out,
269 lib::llvm::ObjectFile);
275 llvm::LLVMRustDisposeTargetMachine(tm);
276 llvm::LLVMDisposeModule(trans.metadata_module);
277 llvm::LLVMDisposeModule(llmod);
278 llvm::LLVMContextDispose(llcx);
279 if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
283 pub fn run_assembler(sess: Session, assembly: &Path, object: &Path) {
284 let cc = super::get_cc_prog(sess);
286 // FIXME (#9639): This needs to handle non-utf8 paths
289 ~"-o", object.as_str().unwrap().to_owned(),
290 assembly.as_str().unwrap().to_owned()];
292 debug!("{} '{}'", cc, args.connect("' '"));
294 let _guard = io::ignore_io_error();
295 run::process_output(cc, args)
299 if !prog.status.success() {
300 sess.err(format!("linking with `{}` failed: {}", cc, prog.status));
301 sess.note(format!("{} arguments: '{}'", cc, args.connect("' '")));
302 sess.note(str::from_utf8_owned(prog.error + prog.output));
303 sess.abort_if_errors();
307 sess.err(format!("could not exec the linker `{}`", cc));
308 sess.abort_if_errors();
313 unsafe fn configure_llvm(sess: Session) {
314 use std::unstable::mutex::{Once, ONCE_INIT};
315 static mut INIT: Once = ONCE_INIT;
317 // Copy what clan does by turning on loop vectorization at O2 and
318 // slp vectorization at O3
319 let vectorize_loop = !sess.no_vectorize_loops() &&
320 (sess.opts.optimize == session::Default ||
321 sess.opts.optimize == session::Aggressive);
322 let vectorize_slp = !sess.no_vectorize_slp() &&
323 sess.opts.optimize == session::Aggressive;
325 let mut llvm_c_strs = ~[];
326 let mut llvm_args = ~[];
327 let add = |arg: &str| {
328 let s = arg.to_c_str();
329 llvm_args.push(s.with_ref(|p| p));
332 add("rustc"); // fake program name
333 add("-arm-enable-ehabi");
334 add("-arm-enable-ehabi-descriptors");
335 if vectorize_loop { add("-vectorize-loops"); }
336 if vectorize_slp { add("-vectorize-slp"); }
337 if sess.time_llvm_passes() { add("-time-passes"); }
338 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
340 for arg in sess.opts.llvm_args.iter() {
345 llvm::LLVMInitializePasses();
347 // Only initialize the platforms supported by Rust here, because
348 // using --llvm-root will have multiple platforms that rustllvm
349 // doesn't actually link to and it's pointless to put target info
350 // into the registry that Rust can not generate machine code for.
351 llvm::LLVMInitializeX86TargetInfo();
352 llvm::LLVMInitializeX86Target();
353 llvm::LLVMInitializeX86TargetMC();
354 llvm::LLVMInitializeX86AsmPrinter();
355 llvm::LLVMInitializeX86AsmParser();
357 llvm::LLVMInitializeARMTargetInfo();
358 llvm::LLVMInitializeARMTarget();
359 llvm::LLVMInitializeARMTargetMC();
360 llvm::LLVMInitializeARMAsmPrinter();
361 llvm::LLVMInitializeARMAsmParser();
363 llvm::LLVMInitializeMipsTargetInfo();
364 llvm::LLVMInitializeMipsTarget();
365 llvm::LLVMInitializeMipsTargetMC();
366 llvm::LLVMInitializeMipsAsmPrinter();
367 llvm::LLVMInitializeMipsAsmParser();
369 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
374 unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
375 mpm: lib::llvm::PassManagerRef,
377 opt: lib::llvm::CodeGenOptLevel) {
378 // Create the PassManagerBuilder for LLVM. We configure it with
379 // reasonable defaults and prepare it to actually populate the pass
381 let builder = llvm::LLVMPassManagerBuilderCreate();
383 lib::llvm::CodeGenLevelNone => {
384 // Don't add lifetime intrinsics add O0
385 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
387 lib::llvm::CodeGenLevelLess => {
388 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
390 // numeric values copied from clang
391 lib::llvm::CodeGenLevelDefault => {
392 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
395 lib::llvm::CodeGenLevelAggressive => {
396 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
400 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
401 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
403 // Use the builder to populate the function/module pass managers.
404 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
405 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
406 llvm::LLVMPassManagerBuilderDispose(builder);
412 * Name mangling and its relationship to metadata. This is complex. Read
415 * The semantic model of Rust linkage is, broadly, that "there's no global
416 * namespace" between crates. Our aim is to preserve the illusion of this
417 * model despite the fact that it's not *quite* possible to implement on
418 * modern linkers. We initially didn't use system linkers at all, but have
419 * been convinced of their utility.
421 * There are a few issues to handle:
423 * - Linkers operate on a flat namespace, so we have to flatten names.
424 * We do this using the C++ namespace-mangling technique. Foo::bar
427 * - Symbols with the same name but different types need to get different
428 * linkage-names. We do this by hashing a string-encoding of the type into
429 * a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
430 * we use SHA256) to "prevent collisions". This is not airtight but 16 hex
431 * digits on uniform probability means you're going to need 2**32 same-name
432 * symbols in the same process before you're even hitting birthday-paradox
433 * collision probability.
435 * - Symbols in different crates but with same names "within" the crate need
436 * to get different linkage-names.
438 * - The hash shown in the filename needs to be predictable and stable for
439 * build tooling integration. It also needs to be using a hash function
440 * which is easy to use from Python, make, etc.
442 * So here is what we do:
444 * - Consider the package id; every crate has one (specified with crate_id
445 * attribute). If a package id isn't provided explicitly, we infer a
446 * versionless one from the output name. The version will end up being 0.0
447 * in this case. CNAME and CVERS are taken from this package id. For
448 * example, github.com/mozilla/CNAME#CVERS.
450 * - Define CMH as SHA256(crateid).
452 * - Define CMH8 as the first 8 characters of CMH.
454 * - Compile our crate to lib CNAME-CMH8-CVERS.so
456 * - Define STH(sym) as SHA256(CMH, type_str(sym))
458 * - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
459 * name, non-name metadata, and type sense, and versioned in the way
460 * system linkers understand.
463 pub fn build_link_meta(sess: Session,
464 attrs: &[ast::Attribute],
466 symbol_hasher: &mut Sha256)
468 // This calculates CMH as defined above
469 fn crate_hash(symbol_hasher: &mut Sha256, crateid: &CrateId) -> @str {
470 symbol_hasher.reset();
471 symbol_hasher.input_str(crateid.to_str());
472 truncated_hash_result(symbol_hasher).to_managed()
475 let crateid = match attr::find_crateid(attrs) {
477 let stem = session::expect(
479 output.filestem_str(),
480 || format!("output file name '{}' doesn't appear to have a stem",
482 from_str(stem).unwrap()
487 let hash = crate_hash(symbol_hasher, &crateid);
495 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
496 let output = symbol_hasher.result_bytes();
497 // 64 bits should be enough to avoid collisions.
498 output.slice_to(8).to_hex()
502 // This calculates STH for a symbol, as defined above
503 pub fn symbol_hash(tcx: ty::ctxt,
504 symbol_hasher: &mut Sha256,
506 link_meta: &LinkMeta) -> @str {
507 // NB: do *not* use abbrevs here as we want the symbol names
508 // to be independent of one another in the crate.
510 symbol_hasher.reset();
511 symbol_hasher.input_str(link_meta.crateid.name);
512 symbol_hasher.input_str("-");
513 symbol_hasher.input_str(link_meta.crate_hash);
514 symbol_hasher.input_str("-");
515 symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
516 let mut hash = truncated_hash_result(symbol_hasher);
517 // Prefix with 'h' so that it never blends into adjacent digits
518 hash.unshift_char('h');
519 // tjc: allocation is unfortunate; need to change std::hash
523 pub fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> @str {
525 let type_hashcodes = ccx.type_hashcodes.borrow();
526 match type_hashcodes.get().find(&t) {
527 Some(&h) => return h,
532 let mut type_hashcodes = ccx.type_hashcodes.borrow_mut();
533 let mut symbol_hasher = ccx.symbol_hasher.borrow_mut();
534 let hash = symbol_hash(ccx.tcx, symbol_hasher.get(), t, &ccx.link_meta);
535 type_hashcodes.get().insert(t, hash);
540 // Name sanitation. LLVM will happily accept identifiers with weird names, but
542 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
543 pub fn sanitize(s: &str) -> ~str {
544 let mut result = ~"";
547 // Escape these with $ sequences
548 '@' => result.push_str("$SP$"),
549 '~' => result.push_str("$UP$"),
550 '*' => result.push_str("$RP$"),
551 '&' => result.push_str("$BP$"),
552 '<' => result.push_str("$LT$"),
553 '>' => result.push_str("$GT$"),
554 '(' => result.push_str("$LP$"),
555 ')' => result.push_str("$RP$"),
556 ',' => result.push_str("$C$"),
558 // '.' doesn't occur in types and functions, so reuse it
560 '-' | ':' => result.push_char('.'),
562 // These are legal symbols
566 | '_' | '.' | '$' => result.push_char(c),
570 char::escape_unicode(c, |c| tstr.push_char(c));
571 result.push_char('$');
572 result.push_str(tstr.slice_from(1));
577 // Underscore-qualify anything that didn't start as an ident.
578 if result.len() > 0u &&
579 result[0] != '_' as u8 &&
580 ! char::is_XID_start(result[0] as char) {
581 return ~"_" + result;
587 pub fn mangle(sess: Session, ss: ast_map::Path,
588 hash: Option<&str>, vers: Option<&str>) -> ~str {
589 // Follow C++ namespace-mangling style, see
590 // http://en.wikipedia.org/wiki/Name_mangling for more info.
592 // It turns out that on OSX you can actually have arbitrary symbols in
593 // function names (at least when given to LLVM), but this is not possible
594 // when using unix's linker. Perhaps one day when we just a linker from LLVM
595 // we won't need to do this name mangling. The problem with name mangling is
596 // that it seriously limits the available characters. For example we can't
597 // have things like @T or ~[T] in symbol names when one would theoretically
598 // want them for things like impls of traits on that type.
600 // To be able to work on all platforms and get *some* reasonable output, we
601 // use C++ name-mangling.
603 let mut n = ~"_ZN"; // _Z == Begin name-sequence, N == nested
605 let push = |s: &str| {
606 let sani = sanitize(s);
607 n.push_str(format!("{}{}", sani.len(), sani));
610 // First, connect each component with <len, name> pairs.
613 PathName(s) | PathMod(s) | PathPrettyName(s, _) => {
619 // next, if any identifiers are "pretty" and need extra information tacked
620 // on, then use the hash to generate two unique characters. For now
621 // hopefully 2 characters is enough to avoid collisions.
622 static EXTRA_CHARS: &'static str =
623 "abcdefghijklmnopqrstuvwxyz\
624 ABCDEFGHIJKLMNOPQRSTUVWXYZ\
626 let mut hash = match hash { Some(s) => s.to_owned(), None => ~"" };
629 PathPrettyName(_, extra) => {
630 let hi = (extra >> 32) as u32 as uint;
631 let lo = extra as u32 as uint;
632 hash.push_char(EXTRA_CHARS[hi % EXTRA_CHARS.len()] as char);
633 hash.push_char(EXTRA_CHARS[lo % EXTRA_CHARS.len()] as char);
646 n.push_char('E'); // End name-sequence.
650 pub fn exported_name(sess: Session,
653 vers: &str) -> ~str {
654 // The version will get mangled to have a leading '_', but it makes more
655 // sense to lead with a 'v' b/c this is a version...
656 let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
662 mangle(sess, path, Some(hash), Some(vers.as_slice()))
665 pub fn mangle_exported_name(ccx: &CrateContext,
668 let hash = get_symbol_hash(ccx, t);
669 return exported_name(ccx.sess, path,
671 ccx.link_meta.crateid.version_or_default());
674 pub fn mangle_internal_name_by_type_only(ccx: &CrateContext,
676 name: &str) -> ~str {
677 let s = ppaux::ty_to_short_str(ccx.tcx, t);
678 let hash = get_symbol_hash(ccx, t);
679 return mangle(ccx.sess,
680 ~[PathName(ccx.sess.ident_of(name)),
681 PathName(ccx.sess.ident_of(s))],
682 Some(hash.as_slice()),
686 pub fn mangle_internal_name_by_type_and_seq(ccx: &CrateContext,
688 name: &str) -> ~str {
689 let s = ppaux::ty_to_str(ccx.tcx, t);
690 let hash = get_symbol_hash(ccx, t);
691 let (_, name) = gensym_name(name);
692 return mangle(ccx.sess,
693 ~[PathName(ccx.sess.ident_of(s)), name],
694 Some(hash.as_slice()),
698 pub fn mangle_internal_name_by_path_and_seq(ccx: &CrateContext,
699 mut path: ast_map::Path,
700 flav: &str) -> ~str {
701 let (_, name) = gensym_name(flav);
703 mangle(ccx.sess, path, None, None)
706 pub fn mangle_internal_name_by_path(ccx: &CrateContext,
707 path: ast_map::Path) -> ~str {
708 mangle(ccx.sess, path, None, None)
711 pub fn output_lib_filename(lm: &LinkMeta) -> ~str {
714 lm.crate_hash.slice_chars(0, 8),
715 lm.crateid.version_or_default())
718 pub fn get_cc_prog(sess: Session) -> ~str {
719 match sess.opts.linker {
720 Some(ref linker) => return linker.to_owned(),
724 // In the future, FreeBSD will use clang as default compiler.
725 // It would be flexible to use cc (system's default C compiler)
726 // instead of hard-coded gcc.
727 // For win32, there is no cc command, so we add a condition to make it use gcc.
728 match sess.targ_cfg.os {
729 abi::OsWin32 => return ~"gcc",
733 get_system_tool(sess, "cc")
736 pub fn get_ar_prog(sess: Session) -> ~str {
738 Some(ref ar) => return ar.to_owned(),
742 get_system_tool(sess, "ar")
745 fn get_system_tool(sess: Session, tool: &str) -> ~str {
746 match sess.targ_cfg.os {
747 abi::OsAndroid => match sess.opts.android_cross_path {
749 let tool_str = match tool {
753 format!("{}/bin/arm-linux-androideabi-{}", *path, tool_str)
756 sess.fatal(format!("need Android NDK path for the '{}' tool \
757 (--android-cross-path)", tool))
760 _ => tool.to_owned(),
764 /// Perform the linkage portion of the compilation phase. This will generate all
765 /// of the requested outputs for this compilation session.
766 pub fn link_binary(sess: Session,
767 trans: &CrateTranslation,
770 lm: &LinkMeta) -> ~[Path] {
771 let mut out_filenames = ~[];
772 let outputs = sess.outputs.borrow();
773 for &output in outputs.get().iter() {
774 let out_file = link_binary_output(sess, trans, output, obj_filename,
776 out_filenames.push(out_file);
779 // Remove the temporary object file and metadata if we aren't saving temps
780 if !sess.opts.save_temps {
781 fs::unlink(obj_filename);
782 fs::unlink(&obj_filename.with_extension("metadata.o"));
788 fn is_writeable(p: &Path) -> bool {
791 match io::result(|| p.stat()) {
793 Ok(m) => m.perm & io::UserWrite == io::UserWrite
797 pub fn filename_for_input(sess: &Session, output: session::OutputStyle, lm: &LinkMeta,
798 out_filename: &Path) -> Path {
799 let libname = output_lib_filename(lm);
801 session::OutputRlib => {
802 out_filename.with_filename(format!("lib{}.rlib", libname))
804 session::OutputDylib => {
805 let (prefix, suffix) = match sess.targ_cfg.os {
806 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
807 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
808 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
809 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
810 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
812 out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
814 session::OutputStaticlib => {
815 out_filename.with_filename(format!("lib{}.a", libname))
817 session::OutputExecutable => out_filename.clone(),
822 fn link_binary_output(sess: Session,
823 trans: &CrateTranslation,
824 output: session::OutputStyle,
827 lm: &LinkMeta) -> Path {
828 let out_filename = filename_for_input(&sess, output, lm, out_filename);
830 // Make sure the output and obj_filename are both writeable.
831 // Mac, FreeBSD, and Windows system linkers check this already --
832 // however, the Linux linker will happily overwrite a read-only file.
833 // We should be consistent.
834 let obj_is_writeable = is_writeable(obj_filename);
835 let out_is_writeable = is_writeable(&out_filename);
836 if !out_is_writeable {
837 sess.fatal(format!("Output file {} is not writeable -- check its permissions.",
838 out_filename.display()));
840 else if !obj_is_writeable {
841 sess.fatal(format!("Object file {} is not writeable -- check its permissions.",
842 obj_filename.display()));
846 session::OutputRlib => {
847 link_rlib(sess, Some(trans), obj_filename, &out_filename);
849 session::OutputStaticlib => {
850 link_staticlib(sess, obj_filename, &out_filename);
852 session::OutputExecutable => {
853 link_natively(sess, false, obj_filename, &out_filename);
855 session::OutputDylib => {
856 link_natively(sess, true, obj_filename, &out_filename);
865 // An rlib in its current incarnation is essentially a renamed .a file. The
866 // rlib primarily contains the object file of the crate, but it also contains
867 // all of the object files from native libraries. This is done by unzipping
868 // native libraries and inserting all of the contents into this archive.
869 fn link_rlib(sess: Session,
870 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
872 out_filename: &Path) -> Archive {
873 let mut a = Archive::create(sess, out_filename, obj_filename);
875 let used_libraries = sess.cstore.get_used_libraries();
876 let used_libraries = used_libraries.borrow();
877 for &(ref l, kind) in used_libraries.get().iter() {
879 cstore::NativeStatic => {
880 a.add_native_library(l.as_slice());
882 cstore::NativeFramework | cstore::NativeUnknown => {}
886 // Note that it is important that we add all of our non-object "magical
887 // files" *after* all of the object files in the archive. The reason for
888 // this is as follows:
890 // * When performing LTO, this archive will be modified to remove
891 // obj_filename from above. The reason for this is described below.
893 // * When the system linker looks at an archive, it will attempt to
894 // determine the architecture of the archive in order to see whether its
897 // The algorithm for this detections is: iterate over the files in the
898 // archive. Skip magical SYMDEF names. Interpret the first file as an
899 // object file. Read architecture from the object file.
901 // * As one can probably see, if "metadata" and "foo.bc" were placed
902 // before all of the objects, then the architecture of this archive would
903 // not be correctly inferred once 'foo.o' is removed.
905 // Basically, all this means is that this code should not move above the
909 // Instead of putting the metadata in an object file section, rlibs
910 // contain the metadata in a separate file. We use a temp directory
911 // here so concurrent builds in the same directory don't try to use
912 // the same filename for metadata (stomping over one another)
913 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
914 let metadata = tmpdir.path().join(METADATA_FILENAME);
915 fs::File::create(&metadata).write(trans.metadata);
916 a.add_file(&metadata, false);
917 fs::unlink(&metadata);
919 // For LTO purposes, the bytecode of this library is also inserted
921 let bc = obj_filename.with_extension("bc");
922 a.add_file(&bc, false);
923 if !sess.opts.save_temps {
927 // After adding all files to the archive, we need to update the
928 // symbol table of the archive. This currently dies on OSX (see
929 // #11162), and isn't necessary there anyway
930 match sess.targ_cfg.os {
932 _ => { a.update_symbols(); }
941 // Create a static archive
943 // This is essentially the same thing as an rlib, but it also involves adding
944 // all of the upstream crates' objects into the the archive. This will slurp in
945 // all of the native libraries of upstream dependencies as well.
947 // Additionally, there's no way for us to link dynamic libraries, so we warn
948 // about all dynamic library dependencies that they're not linked in.
950 // There's no need to include metadata in a static archive, so ensure to not
951 // link in the metadata object file (and also don't prepare the archive with a
953 fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
954 let mut a = link_rlib(sess, None, obj_filename, out_filename);
955 a.add_native_library("morestack");
957 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
958 for &(cnum, ref path) in crates.iter() {
959 let name = sess.cstore.get_crate_data(cnum).name;
960 let p = match *path {
961 Some(ref p) => p.clone(), None => {
962 sess.err(format!("could not find rlib for: `{}`", name));
966 a.add_rlib(&p, name, sess.lto());
967 let native_libs = csearch::get_native_libraries(sess.cstore, cnum);
968 for &(kind, ref lib) in native_libs.iter() {
969 let name = match kind {
970 cstore::NativeStatic => "static library",
971 cstore::NativeUnknown => "library",
972 cstore::NativeFramework => "framework",
974 sess.warn(format!("unlinked native {}: {}", name, *lib));
979 // Create a dynamic library or executable
981 // This will invoke the system linker/cc to create the resulting file. This
982 // links to all upstream files as well.
983 fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
984 out_filename: &Path) {
985 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
986 // The invocations of cc share some flags across platforms
987 let cc_prog = get_cc_prog(sess);
988 let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
989 cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
990 obj_filename, out_filename));
991 if (sess.opts.debugging_opts & session::print_link_args) != 0 {
992 println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
995 // May have not found libraries in the right formats.
996 sess.abort_if_errors();
998 // Invoke the system linker
999 debug!("{} {}", cc_prog, cc_args.connect(" "));
1001 let _guard = io::ignore_io_error();
1002 time(sess.time_passes(), "running linker", (), |()|
1003 run::process_output(cc_prog, cc_args))
1008 if !prog.status.success() {
1009 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
1010 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
1011 sess.note(str::from_utf8_owned(prog.error + prog.output));
1012 sess.abort_if_errors();
1016 sess.err(format!("could not exec the linker `{}`", cc_prog));
1017 sess.abort_if_errors();
1022 // On OSX, debuggers need this utility to get run to do some munging of
1024 if sess.targ_cfg.os == abi::OsMacos && sess.opts.debuginfo {
1025 // FIXME (#9639): This needs to handle non-utf8 paths
1026 run::process_status("dsymutil",
1027 [out_filename.as_str().unwrap().to_owned()]);
1031 fn link_args(sess: Session,
1034 obj_filename: &Path,
1035 out_filename: &Path) -> ~[~str] {
1037 // The default library location, we need this to find the runtime.
1038 // The location of crates will be determined as needed.
1039 // FIXME (#9639): This needs to handle non-utf8 paths
1040 let lib_path = sess.filesearch.get_target_lib_path();
1041 let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
1043 let mut args = ~[stage];
1045 // FIXME (#9639): This needs to handle non-utf8 paths
1047 ~"-o", out_filename.as_str().unwrap().to_owned(),
1048 obj_filename.as_str().unwrap().to_owned()]);
1050 // When linking a dynamic library, we put the metadata into a section of the
1051 // executable. This metadata is in a separate object file from the main
1052 // object file, so we link that in here.
1054 let metadata = obj_filename.with_extension("metadata.o");
1055 args.push(metadata.as_str().unwrap().to_owned());
1058 if sess.targ_cfg.os == abi::OsLinux {
1059 // GNU-style linkers will use this to omit linking to libraries which
1060 // don't actually fulfill any relocations, but only for libraries which
1061 // follow this flag. Thus, use it before specifing libraries to link to.
1062 args.push(~"-Wl,--as-needed");
1064 // GNU-style linkers support optimization with -O. --gc-sections
1065 // removes metadata and potentially other useful things, so don't
1066 // include it. GNU ld doesn't need a numeric argument, but other linkers
1068 if sess.opts.optimize == session::Default ||
1069 sess.opts.optimize == session::Aggressive {
1070 args.push(~"-Wl,-O1");
1074 if sess.targ_cfg.os == abi::OsWin32 {
1075 // Make sure that we link to the dynamic libgcc, otherwise cross-module
1076 // DWARF stack unwinding will not work.
1077 // This behavior may be overriden by --link-args "-static-libgcc"
1078 args.push(~"-shared-libgcc");
1081 add_local_native_libraries(&mut args, sess);
1082 add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1083 add_upstream_native_libraries(&mut args, sess);
1085 // # Telling the linker what we're doing
1088 // On mac we need to tell the linker to let this library be rpathed
1089 if sess.targ_cfg.os == abi::OsMacos {
1090 args.push(~"-dynamiclib");
1091 args.push(~"-Wl,-dylib");
1092 // FIXME (#9639): This needs to handle non-utf8 paths
1093 args.push(~"-Wl,-install_name,@rpath/" +
1094 out_filename.filename_str().unwrap());
1096 args.push(~"-shared")
1100 if sess.targ_cfg.os == abi::OsFreebsd {
1101 args.push_all([~"-L/usr/local/lib",
1102 ~"-L/usr/local/lib/gcc46",
1103 ~"-L/usr/local/lib/gcc44"]);
1106 // Stack growth requires statically linking a __morestack function
1107 args.push(~"-lmorestack");
1109 // FIXME (#2397): At some point we want to rpath our guesses as to
1110 // where extern libraries might live, based on the
1111 // addl_lib_search_paths
1112 args.push_all(rpath::get_rpath_flags(sess, out_filename));
1114 // Finally add all the linker arguments provided on the command line along
1115 // with any #[link_args] attributes found inside the crate
1116 args.push_all(sess.opts.linker_args);
1117 let used_link_args = sess.cstore.get_used_link_args();
1118 let used_link_args = used_link_args.borrow();
1119 for arg in used_link_args.get().iter() {
1120 args.push(arg.clone());
1125 // # Native library linking
1127 // User-supplied library search paths (-L on the cammand line) These are
1128 // the same paths used to find Rust crates, so some of them may have been
1129 // added already by the previous crate linking code. This only allows them
1130 // to be found at compile time so it is still entirely up to outside
1131 // forces to make sure that library can be found at runtime.
1133 // Also note that the native libraries linked here are only the ones located
1134 // in the current crate. Upstream crates with native library dependencies
1135 // may have their native library pulled in above.
1136 fn add_local_native_libraries(args: &mut ~[~str], sess: Session) {
1137 let addl_lib_search_paths = sess.opts.addl_lib_search_paths.borrow();
1138 for path in addl_lib_search_paths.get().iter() {
1139 // FIXME (#9639): This needs to handle non-utf8 paths
1140 args.push("-L" + path.as_str().unwrap().to_owned());
1143 let rustpath = filesearch::rust_path();
1144 for path in rustpath.iter() {
1145 // FIXME (#9639): This needs to handle non-utf8 paths
1146 args.push("-L" + path.as_str().unwrap().to_owned());
1149 let used_libraries = sess.cstore.get_used_libraries();
1150 let used_libraries = used_libraries.borrow();
1151 for &(ref l, kind) in used_libraries.get().iter() {
1153 cstore::NativeUnknown | cstore::NativeStatic => {
1154 args.push("-l" + *l);
1156 cstore::NativeFramework => {
1157 args.push(~"-framework");
1158 args.push(l.to_owned());
1164 // # Rust Crate linking
1166 // Rust crates are not considered at all when creating an rlib output. All
1167 // dependencies will be linked when producing the final output (instead of
1168 // the intermediate rlib version)
1169 fn add_upstream_rust_crates(args: &mut ~[~str], sess: Session,
1170 dylib: bool, tmpdir: &Path) {
1171 // Converts a library file-stem into a cc -l argument
1172 fn unlib(config: @session::Config, stem: &str) -> ~str {
1173 if stem.starts_with("lib") &&
1174 config.os != abi::OsWin32 {
1175 stem.slice(3, stem.len()).to_owned()
1181 let cstore = sess.cstore;
1182 if !dylib && !sess.prefer_dynamic() {
1183 // With an executable, things get a little interesting. As a limitation
1184 // of the current implementation, we require that everything must be
1185 // static, or everything must be dynamic. The reasons for this are a
1186 // little subtle, but as with the above two cases, the goal is to
1187 // prevent duplicate copies of the same library showing up. For example,
1188 // a static immediate dependency might show up as an upstream dynamic
1189 // dependency and we currently have no way of knowing that. We know that
1190 // all dynamic libaries require dynamic dependencies (see above), so
1191 // it's satisfactory to include either all static libraries or all
1192 // dynamic libraries.
1193 let crates = cstore.get_used_crates(cstore::RequireStatic);
1194 if crates.iter().all(|&(_, ref p)| p.is_some()) {
1195 for (cnum, path) in crates.move_iter() {
1196 let cratepath = path.unwrap();
1198 // When performing LTO on an executable output, all of the
1199 // bytecode from the upstream libraries has already been
1200 // included in our object file output. We need to modify all of
1201 // the upstream archives to remove their corresponding object
1202 // file to make sure we don't pull the same code in twice.
1204 // We must continue to link to the upstream archives to be sure
1205 // to pull in native static dependencies. As the final caveat,
1206 // on linux it is apparently illegal to link to a blank archive,
1207 // so if an archive no longer has any object files in it after
1208 // we remove `lib.o`, then don't link against it at all.
1210 // If we're not doing LTO, then our job is simply to just link
1211 // against the archive.
1213 let name = sess.cstore.get_crate_data(cnum).name;
1214 time(sess.time_passes(), format!("altering {}.rlib", name),
1216 let dst = tmpdir.join(cratepath.filename().unwrap());
1217 fs::copy(&cratepath, &dst);
1218 let dst_str = dst.as_str().unwrap().to_owned();
1219 let mut archive = Archive::open(sess, dst);
1220 archive.remove_file(format!("{}.o", name));
1221 let files = archive.files();
1222 if files.iter().any(|s| s.ends_with(".o")) {
1227 args.push(cratepath.as_str().unwrap().to_owned());
1234 // If we're performing LTO, then it should have been previously required
1235 // that all upstream rust depenencies were available in an rlib format.
1236 assert!(!sess.lto());
1238 // This is a fallback of three different cases of linking:
1240 // * When creating a dynamic library, all inputs are required to be dynamic
1242 // * If an executable is created with a preference on dynamic linking, then
1243 // this case is the fallback
1244 // * If an executable is being created, and one of the inputs is missing as
1245 // a static library, then this is the fallback case.
1246 let crates = cstore.get_used_crates(cstore::RequireDynamic);
1247 for &(cnum, ref path) in crates.iter() {
1248 let cratepath = match *path {
1249 Some(ref p) => p.clone(),
1251 sess.err(format!("could not find dynamic library for: `{}`",
1252 sess.cstore.get_crate_data(cnum).name));
1256 // Just need to tell the linker about where the library lives and what
1258 let dir = cratepath.dirname_str().unwrap();
1259 if !dir.is_empty() { args.push("-L" + dir); }
1260 let libarg = unlib(sess.targ_cfg, cratepath.filestem_str().unwrap());
1261 args.push("-l" + libarg);
1265 // Link in all of our upstream crates' native dependencies. Remember that
1266 // all of these upstream native depenencies are all non-static
1267 // dependencies. We've got two cases then:
1269 // 1. The upstream crate is an rlib. In this case we *must* link in the
1270 // native dependency because the rlib is just an archive.
1272 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1273 // have the dependency present on the system somewhere. Thus, we don't
1274 // gain a whole lot from not linking in the dynamic dependency to this
1277 // The use case for this is a little subtle. In theory the native
1278 // dependencies of a crate a purely an implementation detail of the crate
1279 // itself, but the problem arises with generic and inlined functions. If a
1280 // generic function calls a native function, then the generic function must
1281 // be instantiated in the target crate, meaning that the native symbol must
1282 // also be resolved in the target crate.
1283 fn add_upstream_native_libraries(args: &mut ~[~str], sess: Session) {
1284 let cstore = sess.cstore;
1285 cstore.iter_crate_data(|cnum, _| {
1286 let libs = csearch::get_native_libraries(cstore, cnum);
1287 for &(kind, ref lib) in libs.iter() {
1289 cstore::NativeUnknown => args.push("-l" + *lib),
1290 cstore::NativeFramework => {
1291 args.push(~"-framework");
1292 args.push(lib.to_owned());
1294 cstore::NativeStatic => {
1295 sess.bug("statics shouldn't be propagated");