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.
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")); }
160 if !sess.no_prepopulate_passes() {
161 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
162 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
163 populate_llvm_passes(fpm, mpm, llmod, OptLevel);
166 for pass in sess.opts.custom_passes.iter() {
167 pass.with_c_str(|s| {
168 if !llvm::LLVMRustAddPass(mpm, s) {
169 sess.warn(format!("Unknown pass {}, ignoring", *pass));
174 // Finally, run the actual optimization passes
175 time(sess.time_passes(), "llvm function passes", (), |()|
176 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
177 time(sess.time_passes(), "llvm module passes", (), |()|
178 llvm::LLVMRunPassManager(mpm, llmod));
180 // Deallocate managers that we're now done with
181 llvm::LLVMDisposePassManager(fpm);
182 llvm::LLVMDisposePassManager(mpm);
184 // Emit the bytecode if we're either saving our temporaries or
185 // emitting an rlib. Whenever an rlib is created, the bytecode is
186 // inserted into the archive in order to allow LTO against it.
187 let outputs = sess.outputs.borrow();
188 if sess.opts.save_temps ||
189 outputs.get().iter().any(|&o| o == session::OutputRlib) {
190 output.with_extension("bc").with_c_str(|buf| {
191 llvm::LLVMWriteBitcodeToFile(llmod, buf);
196 time(sess.time_passes(), "all lto passes", (), |()|
197 lto::run(sess, llmod, tm, trans.reachable));
199 if sess.opts.save_temps {
200 output.with_extension("lto.bc").with_c_str(|buf| {
201 llvm::LLVMWriteBitcodeToFile(llmod, buf);
206 // A codegen-specific pass manager is used to generate object
207 // files for an LLVM module.
209 // Apparently each of these pass managers is a one-shot kind of
210 // thing, so we create a new one for each type of output. The
211 // pass manager passed to the closure should be ensured to not
212 // escape the closure itself, and the manager should only be
214 fn with_codegen(tm: TargetMachineRef, llmod: ModuleRef,
215 f: |PassManagerRef|) {
217 let cpm = llvm::LLVMCreatePassManager();
218 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
219 llvm::LLVMRustAddLibraryInfo(cpm, llmod);
221 llvm::LLVMDisposePassManager(cpm);
225 time(sess.time_passes(), "codegen passes", (), |()| {
228 OutputTypeBitcode => {
229 output.with_c_str(|buf| {
230 llvm::LLVMWriteBitcodeToFile(llmod, buf);
233 OutputTypeLlvmAssembly => {
234 output.with_c_str(|output| {
235 with_codegen(tm, llmod, |cpm| {
236 llvm::LLVMRustPrintModule(cpm, llmod, output);
240 OutputTypeAssembly => {
241 with_codegen(tm, llmod, |cpm| {
242 WriteOutputFile(sess, tm, cpm, llmod, output,
243 lib::llvm::AssemblyFile);
246 // If we're not using the LLVM assembler, this function
247 // could be invoked specially with output_type_assembly,
248 // so in this case we still want the metadata object
250 if sess.opts.output_type != OutputTypeAssembly {
251 with_codegen(tm, trans.metadata_module, |cpm| {
252 let out = output.with_extension("metadata.o");
253 WriteOutputFile(sess, tm, cpm,
254 trans.metadata_module, &out,
255 lib::llvm::ObjectFile);
259 OutputTypeExe | OutputTypeObject => {
260 with_codegen(tm, llmod, |cpm| {
261 WriteOutputFile(sess, tm, cpm, llmod, output,
262 lib::llvm::ObjectFile);
264 with_codegen(tm, trans.metadata_module, |cpm| {
265 let out = output.with_extension("metadata.o");
266 WriteOutputFile(sess, tm, cpm,
267 trans.metadata_module, &out,
268 lib::llvm::ObjectFile);
274 llvm::LLVMRustDisposeTargetMachine(tm);
275 llvm::LLVMDisposeModule(trans.metadata_module);
276 llvm::LLVMDisposeModule(llmod);
277 llvm::LLVMContextDispose(llcx);
278 if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
282 pub fn run_assembler(sess: Session, assembly: &Path, object: &Path) {
283 let cc = super::get_cc_prog(sess);
285 // FIXME (#9639): This needs to handle non-utf8 paths
288 ~"-o", object.as_str().unwrap().to_owned(),
289 assembly.as_str().unwrap().to_owned()];
291 debug!("{} '{}'", cc, args.connect("' '"));
293 let _guard = io::ignore_io_error();
294 run::process_output(cc, args)
298 if !prog.status.success() {
299 sess.err(format!("linking with `{}` failed: {}", cc, prog.status));
300 sess.note(format!("{} arguments: '{}'", cc, args.connect("' '")));
301 sess.note(str::from_utf8_owned(prog.error + prog.output).unwrap());
302 sess.abort_if_errors();
306 sess.err(format!("could not exec the linker `{}`", cc));
307 sess.abort_if_errors();
312 unsafe fn configure_llvm(sess: Session) {
313 use std::unstable::mutex::{Once, ONCE_INIT};
314 static mut INIT: Once = ONCE_INIT;
316 // Copy what clang does by turning on loop vectorization at O2 and
317 // slp vectorization at O3
318 let vectorize_loop = !sess.no_vectorize_loops() &&
319 (sess.opts.optimize == session::Default ||
320 sess.opts.optimize == session::Aggressive);
321 let vectorize_slp = !sess.no_vectorize_slp() &&
322 sess.opts.optimize == session::Aggressive;
324 let mut llvm_c_strs = ~[];
325 let mut llvm_args = ~[];
326 let add = |arg: &str| {
327 let s = arg.to_c_str();
328 llvm_args.push(s.with_ref(|p| p));
331 add("rustc"); // fake program name
332 add("-arm-enable-ehabi");
333 add("-arm-enable-ehabi-descriptors");
334 if vectorize_loop { add("-vectorize-loops"); }
335 if vectorize_slp { add("-vectorize-slp"); }
336 if sess.time_llvm_passes() { add("-time-passes"); }
337 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
339 for arg in sess.opts.llvm_args.iter() {
344 llvm::LLVMInitializePasses();
346 // Only initialize the platforms supported by Rust here, because
347 // using --llvm-root will have multiple platforms that rustllvm
348 // doesn't actually link to and it's pointless to put target info
349 // into the registry that Rust cannot generate machine code for.
350 llvm::LLVMInitializeX86TargetInfo();
351 llvm::LLVMInitializeX86Target();
352 llvm::LLVMInitializeX86TargetMC();
353 llvm::LLVMInitializeX86AsmPrinter();
354 llvm::LLVMInitializeX86AsmParser();
356 llvm::LLVMInitializeARMTargetInfo();
357 llvm::LLVMInitializeARMTarget();
358 llvm::LLVMInitializeARMTargetMC();
359 llvm::LLVMInitializeARMAsmPrinter();
360 llvm::LLVMInitializeARMAsmParser();
362 llvm::LLVMInitializeMipsTargetInfo();
363 llvm::LLVMInitializeMipsTarget();
364 llvm::LLVMInitializeMipsTargetMC();
365 llvm::LLVMInitializeMipsAsmPrinter();
366 llvm::LLVMInitializeMipsAsmParser();
368 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
373 unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
374 mpm: lib::llvm::PassManagerRef,
376 opt: lib::llvm::CodeGenOptLevel) {
377 // Create the PassManagerBuilder for LLVM. We configure it with
378 // reasonable defaults and prepare it to actually populate the pass
380 let builder = llvm::LLVMPassManagerBuilderCreate();
382 lib::llvm::CodeGenLevelNone => {
383 // Don't add lifetime intrinsics at O0
384 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
386 lib::llvm::CodeGenLevelLess => {
387 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
389 // numeric values copied from clang
390 lib::llvm::CodeGenLevelDefault => {
391 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
394 lib::llvm::CodeGenLevelAggressive => {
395 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
399 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
400 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
402 // Use the builder to populate the function/module pass managers.
403 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
404 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
405 llvm::LLVMPassManagerBuilderDispose(builder);
411 * Name mangling and its relationship to metadata. This is complex. Read
414 * The semantic model of Rust linkage is, broadly, that "there's no global
415 * namespace" between crates. Our aim is to preserve the illusion of this
416 * model despite the fact that it's not *quite* possible to implement on
417 * modern linkers. We initially didn't use system linkers at all, but have
418 * been convinced of their utility.
420 * There are a few issues to handle:
422 * - Linkers operate on a flat namespace, so we have to flatten names.
423 * We do this using the C++ namespace-mangling technique. Foo::bar
426 * - Symbols with the same name but different types need to get different
427 * linkage-names. We do this by hashing a string-encoding of the type into
428 * a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
429 * we use SHA256) to "prevent collisions". This is not airtight but 16 hex
430 * digits on uniform probability means you're going to need 2**32 same-name
431 * symbols in the same process before you're even hitting birthday-paradox
432 * collision probability.
434 * - Symbols in different crates but with same names "within" the crate need
435 * to get different linkage-names.
437 * - The hash shown in the filename needs to be predictable and stable for
438 * build tooling integration. It also needs to be using a hash function
439 * which is easy to use from Python, make, etc.
441 * So here is what we do:
443 * - Consider the package id; every crate has one (specified with crate_id
444 * attribute). If a package id isn't provided explicitly, we infer a
445 * versionless one from the output name. The version will end up being 0.0
446 * in this case. CNAME and CVERS are taken from this package id. For
447 * example, github.com/mozilla/CNAME#CVERS.
449 * - Define CMH as SHA256(crateid).
451 * - Define CMH8 as the first 8 characters of CMH.
453 * - Compile our crate to lib CNAME-CMH8-CVERS.so
455 * - Define STH(sym) as SHA256(CMH, type_str(sym))
457 * - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
458 * name, non-name metadata, and type sense, and versioned in the way
459 * system linkers understand.
462 pub fn build_link_meta(sess: Session,
463 attrs: &[ast::Attribute],
465 symbol_hasher: &mut Sha256)
467 // This calculates CMH as defined above
468 fn crate_hash(symbol_hasher: &mut Sha256, crateid: &CrateId) -> @str {
469 symbol_hasher.reset();
470 symbol_hasher.input_str(crateid.to_str());
471 truncated_hash_result(symbol_hasher).to_managed()
474 let crateid = match attr::find_crateid(attrs) {
476 let stem = session::expect(
478 output.filestem_str(),
479 || format!("output file name '{}' doesn't appear to have a stem",
481 from_str(stem).unwrap()
486 let hash = crate_hash(symbol_hasher, &crateid);
494 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
495 let output = symbol_hasher.result_bytes();
496 // 64 bits should be enough to avoid collisions.
497 output.slice_to(8).to_hex()
501 // This calculates STH for a symbol, as defined above
502 pub fn symbol_hash(tcx: ty::ctxt,
503 symbol_hasher: &mut Sha256,
505 link_meta: &LinkMeta) -> @str {
506 // NB: do *not* use abbrevs here as we want the symbol names
507 // to be independent of one another in the crate.
509 symbol_hasher.reset();
510 symbol_hasher.input_str(link_meta.crateid.name);
511 symbol_hasher.input_str("-");
512 symbol_hasher.input_str(link_meta.crate_hash);
513 symbol_hasher.input_str("-");
514 symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
515 let mut hash = truncated_hash_result(symbol_hasher);
516 // Prefix with 'h' so that it never blends into adjacent digits
517 hash.unshift_char('h');
518 // tjc: allocation is unfortunate; need to change std::hash
522 pub fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> @str {
524 let type_hashcodes = ccx.type_hashcodes.borrow();
525 match type_hashcodes.get().find(&t) {
526 Some(&h) => return h,
531 let mut type_hashcodes = ccx.type_hashcodes.borrow_mut();
532 let mut symbol_hasher = ccx.symbol_hasher.borrow_mut();
533 let hash = symbol_hash(ccx.tcx, symbol_hasher.get(), t, &ccx.link_meta);
534 type_hashcodes.get().insert(t, hash);
539 // Name sanitation. LLVM will happily accept identifiers with weird names, but
541 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
542 pub fn sanitize(s: &str) -> ~str {
543 let mut result = ~"";
546 // Escape these with $ sequences
547 '@' => result.push_str("$SP$"),
548 '~' => result.push_str("$UP$"),
549 '*' => result.push_str("$RP$"),
550 '&' => result.push_str("$BP$"),
551 '<' => result.push_str("$LT$"),
552 '>' => result.push_str("$GT$"),
553 '(' => result.push_str("$LP$"),
554 ')' => result.push_str("$RP$"),
555 ',' => result.push_str("$C$"),
557 // '.' doesn't occur in types and functions, so reuse it
559 '-' | ':' => result.push_char('.'),
561 // These are legal symbols
565 | '_' | '.' | '$' => result.push_char(c),
569 char::escape_unicode(c, |c| tstr.push_char(c));
570 result.push_char('$');
571 result.push_str(tstr.slice_from(1));
576 // Underscore-qualify anything that didn't start as an ident.
577 if result.len() > 0u &&
578 result[0] != '_' as u8 &&
579 ! char::is_XID_start(result[0] as char) {
580 return ~"_" + result;
586 pub fn mangle(sess: Session, ss: ast_map::Path,
587 hash: Option<&str>, vers: Option<&str>) -> ~str {
588 // Follow C++ namespace-mangling style, see
589 // http://en.wikipedia.org/wiki/Name_mangling for more info.
591 // It turns out that on OSX you can actually have arbitrary symbols in
592 // function names (at least when given to LLVM), but this is not possible
593 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
594 // we won't need to do this name mangling. The problem with name mangling is
595 // that it seriously limits the available characters. For example we can't
596 // have things like @T or ~[T] in symbol names when one would theoretically
597 // want them for things like impls of traits on that type.
599 // To be able to work on all platforms and get *some* reasonable output, we
600 // use C++ name-mangling.
602 let mut n = ~"_ZN"; // _Z == Begin name-sequence, N == nested
604 let push = |s: &str| {
605 let sani = sanitize(s);
606 n.push_str(format!("{}{}", sani.len(), sani));
609 // First, connect each component with <len, name> pairs.
612 PathName(s) | PathMod(s) | PathPrettyName(s, _) => {
618 // next, if any identifiers are "pretty" and need extra information tacked
619 // on, then use the hash to generate two unique characters. For now
620 // hopefully 2 characters is enough to avoid collisions.
621 static EXTRA_CHARS: &'static str =
622 "abcdefghijklmnopqrstuvwxyz\
623 ABCDEFGHIJKLMNOPQRSTUVWXYZ\
625 let mut hash = match hash { Some(s) => s.to_owned(), None => ~"" };
628 PathPrettyName(_, extra) => {
629 let hi = (extra >> 32) as u32 as uint;
630 let lo = extra as u32 as uint;
631 hash.push_char(EXTRA_CHARS[hi % EXTRA_CHARS.len()] as char);
632 hash.push_char(EXTRA_CHARS[lo % EXTRA_CHARS.len()] as char);
645 n.push_char('E'); // End name-sequence.
649 pub fn exported_name(sess: Session,
652 vers: &str) -> ~str {
653 // The version will get mangled to have a leading '_', but it makes more
654 // sense to lead with a 'v' b/c this is a version...
655 let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
661 mangle(sess, path, Some(hash), Some(vers.as_slice()))
664 pub fn mangle_exported_name(ccx: &CrateContext,
667 let hash = get_symbol_hash(ccx, t);
668 return exported_name(ccx.sess, path,
670 ccx.link_meta.crateid.version_or_default());
673 pub fn mangle_internal_name_by_type_only(ccx: &CrateContext,
675 name: &str) -> ~str {
676 let s = ppaux::ty_to_short_str(ccx.tcx, t);
677 let hash = get_symbol_hash(ccx, t);
678 return mangle(ccx.sess,
679 ~[PathName(ccx.sess.ident_of(name)),
680 PathName(ccx.sess.ident_of(s))],
681 Some(hash.as_slice()),
685 pub fn mangle_internal_name_by_type_and_seq(ccx: &CrateContext,
687 name: &str) -> ~str {
688 let s = ppaux::ty_to_str(ccx.tcx, t);
689 let hash = get_symbol_hash(ccx, t);
690 let (_, name) = gensym_name(name);
691 return mangle(ccx.sess,
692 ~[PathName(ccx.sess.ident_of(s)), name],
693 Some(hash.as_slice()),
697 pub fn mangle_internal_name_by_path_and_seq(ccx: &CrateContext,
698 mut path: ast_map::Path,
699 flav: &str) -> ~str {
700 let (_, name) = gensym_name(flav);
702 mangle(ccx.sess, path, None, None)
705 pub fn mangle_internal_name_by_path(ccx: &CrateContext,
706 path: ast_map::Path) -> ~str {
707 mangle(ccx.sess, path, None, None)
710 pub fn output_lib_filename(lm: &LinkMeta) -> ~str {
713 lm.crate_hash.slice_chars(0, 8),
714 lm.crateid.version_or_default())
717 pub fn get_cc_prog(sess: Session) -> ~str {
718 match sess.opts.linker {
719 Some(ref linker) => return linker.to_owned(),
723 // In the future, FreeBSD will use clang as default compiler.
724 // It would be flexible to use cc (system's default C compiler)
725 // instead of hard-coded gcc.
726 // For win32, there is no cc command, so we add a condition to make it use gcc.
727 match sess.targ_cfg.os {
728 abi::OsWin32 => return ~"gcc",
732 get_system_tool(sess, "cc")
735 pub fn get_ar_prog(sess: Session) -> ~str {
737 Some(ref ar) => return ar.to_owned(),
741 get_system_tool(sess, "ar")
744 fn get_system_tool(sess: Session, tool: &str) -> ~str {
745 match sess.targ_cfg.os {
746 abi::OsAndroid => match sess.opts.android_cross_path {
748 let tool_str = match tool {
752 format!("{}/bin/arm-linux-androideabi-{}", *path, tool_str)
755 sess.fatal(format!("need Android NDK path for the '{}' tool \
756 (--android-cross-path)", tool))
759 _ => tool.to_owned(),
763 /// Perform the linkage portion of the compilation phase. This will generate all
764 /// of the requested outputs for this compilation session.
765 pub fn link_binary(sess: Session,
766 trans: &CrateTranslation,
769 lm: &LinkMeta) -> ~[Path] {
770 let mut out_filenames = ~[];
771 let outputs = sess.outputs.borrow();
772 for &output in outputs.get().iter() {
773 let out_file = link_binary_output(sess, trans, output, obj_filename,
775 out_filenames.push(out_file);
778 // Remove the temporary object file and metadata if we aren't saving temps
779 if !sess.opts.save_temps {
780 fs::unlink(obj_filename);
781 fs::unlink(&obj_filename.with_extension("metadata.o"));
787 fn is_writeable(p: &Path) -> bool {
790 match io::result(|| p.stat()) {
792 Ok(m) => m.perm & io::UserWrite == io::UserWrite
796 pub fn filename_for_input(sess: &Session, output: session::OutputStyle, lm: &LinkMeta,
797 out_filename: &Path) -> Path {
798 let libname = output_lib_filename(lm);
800 session::OutputRlib => {
801 out_filename.with_filename(format!("lib{}.rlib", libname))
803 session::OutputDylib => {
804 let (prefix, suffix) = match sess.targ_cfg.os {
805 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
806 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
807 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
808 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
809 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
811 out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
813 session::OutputStaticlib => {
814 out_filename.with_filename(format!("lib{}.a", libname))
816 session::OutputExecutable => out_filename.clone(),
821 fn link_binary_output(sess: Session,
822 trans: &CrateTranslation,
823 output: session::OutputStyle,
826 lm: &LinkMeta) -> Path {
827 let out_filename = filename_for_input(&sess, output, lm, out_filename);
829 // Make sure the output and obj_filename are both writeable.
830 // Mac, FreeBSD, and Windows system linkers check this already --
831 // however, the Linux linker will happily overwrite a read-only file.
832 // We should be consistent.
833 let obj_is_writeable = is_writeable(obj_filename);
834 let out_is_writeable = is_writeable(&out_filename);
835 if !out_is_writeable {
836 sess.fatal(format!("Output file {} is not writeable -- check its permissions.",
837 out_filename.display()));
839 else if !obj_is_writeable {
840 sess.fatal(format!("Object file {} is not writeable -- check its permissions.",
841 obj_filename.display()));
845 session::OutputRlib => {
846 link_rlib(sess, Some(trans), obj_filename, &out_filename);
848 session::OutputStaticlib => {
849 link_staticlib(sess, obj_filename, &out_filename);
851 session::OutputExecutable => {
852 link_natively(sess, false, obj_filename, &out_filename);
854 session::OutputDylib => {
855 link_natively(sess, true, obj_filename, &out_filename);
864 // An rlib in its current incarnation is essentially a renamed .a file. The
865 // rlib primarily contains the object file of the crate, but it also contains
866 // all of the object files from native libraries. This is done by unzipping
867 // native libraries and inserting all of the contents into this archive.
868 fn link_rlib(sess: Session,
869 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
871 out_filename: &Path) -> Archive {
872 let mut a = Archive::create(sess, out_filename, obj_filename);
874 let used_libraries = sess.cstore.get_used_libraries();
875 let used_libraries = used_libraries.borrow();
876 for &(ref l, kind) in used_libraries.get().iter() {
878 cstore::NativeStatic => {
879 a.add_native_library(l.as_slice());
881 cstore::NativeFramework | cstore::NativeUnknown => {}
885 // Note that it is important that we add all of our non-object "magical
886 // files" *after* all of the object files in the archive. The reason for
887 // this is as follows:
889 // * When performing LTO, this archive will be modified to remove
890 // obj_filename from above. The reason for this is described below.
892 // * When the system linker looks at an archive, it will attempt to
893 // determine the architecture of the archive in order to see whether its
896 // The algorithm for this detection is: iterate over the files in the
897 // archive. Skip magical SYMDEF names. Interpret the first file as an
898 // object file. Read architecture from the object file.
900 // * As one can probably see, if "metadata" and "foo.bc" were placed
901 // before all of the objects, then the architecture of this archive would
902 // not be correctly inferred once 'foo.o' is removed.
904 // Basically, all this means is that this code should not move above the
908 // Instead of putting the metadata in an object file section, rlibs
909 // contain the metadata in a separate file. We use a temp directory
910 // here so concurrent builds in the same directory don't try to use
911 // the same filename for metadata (stomping over one another)
912 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
913 let metadata = tmpdir.path().join(METADATA_FILENAME);
914 fs::File::create(&metadata).write(trans.metadata);
915 a.add_file(&metadata, false);
916 fs::unlink(&metadata);
918 // For LTO purposes, the bytecode of this library is also inserted
920 let bc = obj_filename.with_extension("bc");
921 a.add_file(&bc, false);
922 if !sess.opts.save_temps {
926 // After adding all files to the archive, we need to update the
927 // symbol table of the archive. This currently dies on OSX (see
928 // #11162), and isn't necessary there anyway
929 match sess.targ_cfg.os {
931 _ => { a.update_symbols(); }
940 // Create a static archive
942 // This is essentially the same thing as an rlib, but it also involves adding
943 // all of the upstream crates' objects into the archive. This will slurp in
944 // all of the native libraries of upstream dependencies as well.
946 // Additionally, there's no way for us to link dynamic libraries, so we warn
947 // about all dynamic library dependencies that they're not linked in.
949 // There's no need to include metadata in a static archive, so ensure to not
950 // link in the metadata object file (and also don't prepare the archive with a
952 fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
953 let mut a = link_rlib(sess, None, obj_filename, out_filename);
954 a.add_native_library("morestack");
956 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
957 for &(cnum, ref path) in crates.iter() {
958 let name = sess.cstore.get_crate_data(cnum).name;
959 let p = match *path {
960 Some(ref p) => p.clone(), None => {
961 sess.err(format!("could not find rlib for: `{}`", name));
965 a.add_rlib(&p, name, sess.lto());
966 let native_libs = csearch::get_native_libraries(sess.cstore, cnum);
967 for &(kind, ref lib) in native_libs.iter() {
968 let name = match kind {
969 cstore::NativeStatic => "static library",
970 cstore::NativeUnknown => "library",
971 cstore::NativeFramework => "framework",
973 sess.warn(format!("unlinked native {}: {}", name, *lib));
978 // Create a dynamic library or executable
980 // This will invoke the system linker/cc to create the resulting file. This
981 // links to all upstream files as well.
982 fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
983 out_filename: &Path) {
984 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
985 // The invocations of cc share some flags across platforms
986 let cc_prog = get_cc_prog(sess);
987 let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
988 cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
989 obj_filename, out_filename));
990 if (sess.opts.debugging_opts & session::PRINT_LINK_ARGS) != 0 {
991 println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
994 // May have not found libraries in the right formats.
995 sess.abort_if_errors();
997 // Invoke the system linker
998 debug!("{} {}", cc_prog, cc_args.connect(" "));
1000 let _guard = io::ignore_io_error();
1001 time(sess.time_passes(), "running linker", (), |()|
1002 run::process_output(cc_prog, cc_args))
1007 if !prog.status.success() {
1008 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
1009 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
1010 sess.note(str::from_utf8_owned(prog.error + prog.output).unwrap());
1011 sess.abort_if_errors();
1015 sess.err(format!("could not exec the linker `{}`", cc_prog));
1016 sess.abort_if_errors();
1021 // On OSX, debuggers need this utility to get run to do some munging of
1023 if sess.targ_cfg.os == abi::OsMacos && sess.opts.debuginfo {
1024 // FIXME (#9639): This needs to handle non-utf8 paths
1025 run::process_status("dsymutil",
1026 [out_filename.as_str().unwrap().to_owned()]);
1030 fn link_args(sess: Session,
1033 obj_filename: &Path,
1034 out_filename: &Path) -> ~[~str] {
1036 // The default library location, we need this to find the runtime.
1037 // The location of crates will be determined as needed.
1038 // FIXME (#9639): This needs to handle non-utf8 paths
1039 let lib_path = sess.filesearch.get_target_lib_path();
1040 let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
1042 let mut args = ~[stage];
1044 // FIXME (#9639): This needs to handle non-utf8 paths
1046 ~"-o", out_filename.as_str().unwrap().to_owned(),
1047 obj_filename.as_str().unwrap().to_owned()]);
1049 // When linking a dynamic library, we put the metadata into a section of the
1050 // executable. This metadata is in a separate object file from the main
1051 // object file, so we link that in here.
1053 let metadata = obj_filename.with_extension("metadata.o");
1054 args.push(metadata.as_str().unwrap().to_owned());
1057 if sess.targ_cfg.os == abi::OsLinux {
1058 // GNU-style linkers will use this to omit linking to libraries which
1059 // don't actually fulfill any relocations, but only for libraries which
1060 // follow this flag. Thus, use it before specifying libraries to link to.
1061 args.push(~"-Wl,--as-needed");
1063 // GNU-style linkers support optimization with -O. --gc-sections
1064 // removes metadata and potentially other useful things, so don't
1065 // include it. GNU ld doesn't need a numeric argument, but other linkers
1067 if sess.opts.optimize == session::Default ||
1068 sess.opts.optimize == session::Aggressive {
1069 args.push(~"-Wl,-O1");
1073 if sess.targ_cfg.os == abi::OsWin32 {
1074 // Make sure that we link to the dynamic libgcc, otherwise cross-module
1075 // DWARF stack unwinding will not work.
1076 // This behavior may be overridden by --link-args "-static-libgcc"
1077 args.push(~"-shared-libgcc");
1080 add_local_native_libraries(&mut args, sess);
1081 add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1082 add_upstream_native_libraries(&mut args, sess);
1084 // # Telling the linker what we're doing
1087 // On mac we need to tell the linker to let this library be rpathed
1088 if sess.targ_cfg.os == abi::OsMacos {
1089 args.push(~"-dynamiclib");
1090 args.push(~"-Wl,-dylib");
1091 // FIXME (#9639): This needs to handle non-utf8 paths
1092 args.push(~"-Wl,-install_name,@rpath/" +
1093 out_filename.filename_str().unwrap());
1095 args.push(~"-shared")
1099 if sess.targ_cfg.os == abi::OsFreebsd {
1100 args.push_all([~"-L/usr/local/lib",
1101 ~"-L/usr/local/lib/gcc46",
1102 ~"-L/usr/local/lib/gcc44"]);
1105 // Stack growth requires statically linking a __morestack function
1106 args.push(~"-lmorestack");
1108 // FIXME (#2397): At some point we want to rpath our guesses as to
1109 // where extern libraries might live, based on the
1110 // addl_lib_search_paths
1111 args.push_all(rpath::get_rpath_flags(sess, out_filename));
1113 // Finally add all the linker arguments provided on the command line along
1114 // with any #[link_args] attributes found inside the crate
1115 args.push_all(sess.opts.linker_args);
1116 let used_link_args = sess.cstore.get_used_link_args();
1117 let used_link_args = used_link_args.borrow();
1118 for arg in used_link_args.get().iter() {
1119 args.push(arg.clone());
1124 // # Native library linking
1126 // User-supplied library search paths (-L on the command line). These are
1127 // the same paths used to find Rust crates, so some of them may have been
1128 // added already by the previous crate linking code. This only allows them
1129 // to be found at compile time so it is still entirely up to outside
1130 // forces to make sure that library can be found at runtime.
1132 // Also note that the native libraries linked here are only the ones located
1133 // in the current crate. Upstream crates with native library dependencies
1134 // may have their native library pulled in above.
1135 fn add_local_native_libraries(args: &mut ~[~str], sess: Session) {
1136 let addl_lib_search_paths = sess.opts.addl_lib_search_paths.borrow();
1137 for path in addl_lib_search_paths.get().iter() {
1138 // FIXME (#9639): This needs to handle non-utf8 paths
1139 args.push("-L" + path.as_str().unwrap().to_owned());
1142 let rustpath = filesearch::rust_path();
1143 for path in rustpath.iter() {
1144 // FIXME (#9639): This needs to handle non-utf8 paths
1145 args.push("-L" + path.as_str().unwrap().to_owned());
1148 let used_libraries = sess.cstore.get_used_libraries();
1149 let used_libraries = used_libraries.borrow();
1150 for &(ref l, kind) in used_libraries.get().iter() {
1152 cstore::NativeUnknown | cstore::NativeStatic => {
1153 args.push("-l" + *l);
1155 cstore::NativeFramework => {
1156 args.push(~"-framework");
1157 args.push(l.to_owned());
1163 // # Rust Crate linking
1165 // Rust crates are not considered at all when creating an rlib output. All
1166 // dependencies will be linked when producing the final output (instead of
1167 // the intermediate rlib version)
1168 fn add_upstream_rust_crates(args: &mut ~[~str], sess: Session,
1169 dylib: bool, tmpdir: &Path) {
1170 // Converts a library file-stem into a cc -l argument
1171 fn unlib(config: @session::Config, stem: &str) -> ~str {
1172 if stem.starts_with("lib") &&
1173 config.os != abi::OsWin32 {
1174 stem.slice(3, stem.len()).to_owned()
1180 let cstore = sess.cstore;
1181 if !dylib && !sess.prefer_dynamic() {
1182 // With an executable, things get a little interesting. As a limitation
1183 // of the current implementation, we require that everything must be
1184 // static or everything must be dynamic. The reasons for this are a
1185 // little subtle, but as with the above two cases, the goal is to
1186 // prevent duplicate copies of the same library showing up. For example,
1187 // a static immediate dependency might show up as an upstream dynamic
1188 // dependency and we currently have no way of knowing that. We know that
1189 // all dynamic libraries require dynamic dependencies (see above), so
1190 // it's satisfactory to include either all static libraries or all
1191 // dynamic libraries.
1192 let crates = cstore.get_used_crates(cstore::RequireStatic);
1193 if crates.iter().all(|&(_, ref p)| p.is_some()) {
1194 for (cnum, path) in crates.move_iter() {
1195 let cratepath = path.unwrap();
1197 // When performing LTO on an executable output, all of the
1198 // bytecode from the upstream libraries has already been
1199 // included in our object file output. We need to modify all of
1200 // the upstream archives to remove their corresponding object
1201 // file to make sure we don't pull the same code in twice.
1203 // We must continue to link to the upstream archives to be sure
1204 // to pull in native static dependencies. As the final caveat,
1205 // on linux it is apparently illegal to link to a blank archive,
1206 // so if an archive no longer has any object files in it after
1207 // we remove `lib.o`, then don't link against it at all.
1209 // If we're not doing LTO, then our job is simply to just link
1210 // against the archive.
1212 let name = sess.cstore.get_crate_data(cnum).name;
1213 time(sess.time_passes(), format!("altering {}.rlib", name),
1215 let dst = tmpdir.join(cratepath.filename().unwrap());
1216 fs::copy(&cratepath, &dst);
1217 let dst_str = dst.as_str().unwrap().to_owned();
1218 let mut archive = Archive::open(sess, dst);
1219 archive.remove_file(format!("{}.o", name));
1220 let files = archive.files();
1221 if files.iter().any(|s| s.ends_with(".o")) {
1226 args.push(cratepath.as_str().unwrap().to_owned());
1233 // If we're performing LTO, then it should have been previously required
1234 // that all upstream rust dependencies were available in an rlib format.
1235 assert!(!sess.lto());
1237 // This is a fallback of three different cases of linking:
1239 // * When creating a dynamic library, all inputs are required to be dynamic
1241 // * If an executable is created with a preference on dynamic linking, then
1242 // this case is the fallback
1243 // * If an executable is being created, and one of the inputs is missing as
1244 // a static library, then this is the fallback case.
1245 let crates = cstore.get_used_crates(cstore::RequireDynamic);
1246 for &(cnum, ref path) in crates.iter() {
1247 let cratepath = match *path {
1248 Some(ref p) => p.clone(),
1250 sess.err(format!("could not find dynamic library for: `{}`",
1251 sess.cstore.get_crate_data(cnum).name));
1255 // Just need to tell the linker about where the library lives and what
1257 let dir = cratepath.dirname_str().unwrap();
1258 if !dir.is_empty() { args.push("-L" + dir); }
1259 let libarg = unlib(sess.targ_cfg, cratepath.filestem_str().unwrap());
1260 args.push("-l" + libarg);
1264 // Link in all of our upstream crates' native dependencies. Remember that
1265 // all of these upstream native depenencies are all non-static
1266 // dependencies. We've got two cases then:
1268 // 1. The upstream crate is an rlib. In this case we *must* link in the
1269 // native dependency because the rlib is just an archive.
1271 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1272 // have the dependency present on the system somewhere. Thus, we don't
1273 // gain a whole lot from not linking in the dynamic dependency to this
1276 // The use case for this is a little subtle. In theory the native
1277 // dependencies of a crate a purely an implementation detail of the crate
1278 // itself, but the problem arises with generic and inlined functions. If a
1279 // generic function calls a native function, then the generic function must
1280 // be instantiated in the target crate, meaning that the native symbol must
1281 // also be resolved in the target crate.
1282 fn add_upstream_native_libraries(args: &mut ~[~str], sess: Session) {
1283 let cstore = sess.cstore;
1284 cstore.iter_crate_data(|cnum, _| {
1285 let libs = csearch::get_native_libraries(cstore, cnum);
1286 for &(kind, ref lib) in libs.iter() {
1288 cstore::NativeUnknown => args.push("-l" + *lib),
1289 cstore::NativeFramework => {
1290 args.push(~"-framework");
1291 args.push(lib.to_owned());
1293 cstore::NativeStatic => {
1294 sess.bug("statics shouldn't be propagated");