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};
15 use driver::driver::CrateTranslation;
16 use driver::session::Session;
19 use lib::llvm::ModuleRef;
21 use metadata::common::LinkMeta;
22 use metadata::{encoder, cstore, filesearch, csearch};
23 use middle::trans::context::CrateContext;
24 use middle::trans::common::gensym_name;
26 use util::common::time;
28 use util::sha2::{Digest, Sha256};
30 use std::c_str::ToCStr;
32 use std::os::consts::{macos, freebsd, linux, android, win32};
38 use extra::tempfile::TempDir;
41 use syntax::ast_map::{path, path_mod, path_name, path_pretty_name};
43 use syntax::attr::AttrMetaMethods;
44 use syntax::pkgid::PkgId;
46 #[deriving(Clone, Eq)]
47 pub enum output_type {
51 output_type_llvm_assembly,
56 pub fn llvm_err(sess: Session, msg: ~str) -> ! {
58 let cstr = llvm::LLVMRustGetLastError();
59 if cstr == ptr::null() {
62 sess.fatal(msg + ": " + str::raw::from_c_str(cstr));
67 pub fn WriteOutputFile(
69 Target: lib::llvm::TargetMachineRef,
70 PM: lib::llvm::PassManagerRef,
73 FileType: lib::llvm::FileType) {
75 Output.with_c_str(|Output| {
76 let result = llvm::LLVMRustWriteOutputFile(
77 Target, PM, M, Output, FileType);
79 llvm_err(sess, ~"Could not write output");
88 use back::link::{WriteOutputFile, output_type};
89 use back::link::{output_type_assembly, output_type_bitcode};
90 use back::link::{output_type_exe, output_type_llvm_assembly};
91 use back::link::{output_type_object};
92 use driver::driver::CrateTranslation;
93 use driver::session::Session;
96 use lib::llvm::{ModuleRef, TargetMachineRef, PassManagerRef};
98 use util::common::time;
100 use std::c_str::ToCStr;
102 use std::libc::{c_uint, c_int};
107 pub fn run_passes(sess: Session,
108 trans: &CrateTranslation,
109 output_type: output_type,
111 let llmod = trans.module;
112 let llcx = trans.context;
114 llvm::LLVMInitializePasses();
116 // Only initialize the platforms supported by Rust here, because
117 // using --llvm-root will have multiple platforms that rustllvm
118 // doesn't actually link to and it's pointless to put target info
119 // into the registry that Rust can not generate machine code for.
120 llvm::LLVMInitializeX86TargetInfo();
121 llvm::LLVMInitializeX86Target();
122 llvm::LLVMInitializeX86TargetMC();
123 llvm::LLVMInitializeX86AsmPrinter();
124 llvm::LLVMInitializeX86AsmParser();
126 llvm::LLVMInitializeARMTargetInfo();
127 llvm::LLVMInitializeARMTarget();
128 llvm::LLVMInitializeARMTargetMC();
129 llvm::LLVMInitializeARMAsmPrinter();
130 llvm::LLVMInitializeARMAsmParser();
132 llvm::LLVMInitializeMipsTargetInfo();
133 llvm::LLVMInitializeMipsTarget();
134 llvm::LLVMInitializeMipsTargetMC();
135 llvm::LLVMInitializeMipsAsmPrinter();
136 llvm::LLVMInitializeMipsAsmParser();
138 if sess.opts.save_temps {
139 output.with_extension("no-opt.bc").with_c_str(|buf| {
140 llvm::LLVMWriteBitcodeToFile(llmod, buf);
144 configure_llvm(sess);
146 let OptLevel = match sess.opts.optimize {
147 session::No => lib::llvm::CodeGenLevelNone,
148 session::Less => lib::llvm::CodeGenLevelLess,
149 session::Default => lib::llvm::CodeGenLevelDefault,
150 session::Aggressive => lib::llvm::CodeGenLevelAggressive,
152 let use_softfp = sess.opts.debugging_opts & session::use_softfp != 0;
154 let tm = sess.targ_cfg.target_strs.target_triple.with_c_str(|T| {
155 sess.opts.target_cpu.with_c_str(|CPU| {
156 sess.opts.target_feature.with_c_str(|Features| {
157 llvm::LLVMRustCreateTargetMachine(
159 lib::llvm::CodeModelDefault,
169 // Create the two optimizing pass managers. These mirror what clang
170 // does, and are by populated by LLVM's default PassManagerBuilder.
171 // Each manager has a different set of passes, but they also share
172 // some common passes.
173 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
174 let mpm = llvm::LLVMCreatePassManager();
176 // If we're verifying or linting, add them to the function pass
178 let addpass = |pass: &str| {
179 pass.with_c_str(|s| llvm::LLVMRustAddPass(fpm, s))
181 if !sess.no_verify() { assert!(addpass("verify")); }
182 if sess.lint_llvm() { assert!(addpass("lint")); }
184 if !sess.no_prepopulate_passes() {
185 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
186 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
187 populate_llvm_passes(fpm, mpm, llmod, OptLevel);
190 for pass in sess.opts.custom_passes.iter() {
191 pass.with_c_str(|s| {
192 if !llvm::LLVMRustAddPass(mpm, s) {
193 sess.warn(format!("Unknown pass {}, ignoring", *pass));
198 // Finally, run the actual optimization passes
199 time(sess.time_passes(), "llvm function passes", (), |()|
200 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
201 time(sess.time_passes(), "llvm module passes", (), |()|
202 llvm::LLVMRunPassManager(mpm, llmod));
204 // Deallocate managers that we're now done with
205 llvm::LLVMDisposePassManager(fpm);
206 llvm::LLVMDisposePassManager(mpm);
208 // Emit the bytecode if we're either saving our temporaries or
209 // emitting an rlib. Whenever an rlib is create, the bytecode is
210 // inserted into the archive in order to allow LTO against it.
211 if sess.opts.save_temps ||
212 sess.outputs.iter().any(|&o| o == session::OutputRlib) {
213 output.with_extension("bc").with_c_str(|buf| {
214 llvm::LLVMWriteBitcodeToFile(llmod, buf);
219 time(sess.time_passes(), "all lto passes", (), |()|
220 lto::run(sess, llmod, tm, trans.reachable));
222 if sess.opts.save_temps {
223 output.with_extension("lto.bc").with_c_str(|buf| {
224 llvm::LLVMWriteBitcodeToFile(llmod, buf);
229 // A codegen-specific pass manager is used to generate object
230 // files for an LLVM module.
232 // Apparently each of these pass managers is a one-shot kind of
233 // thing, so we create a new one for each type of output. The
234 // pass manager passed to the closure should be ensured to not
235 // escape the closure itself, and the manager should only be
237 fn with_codegen(tm: TargetMachineRef, llmod: ModuleRef,
238 f: |PassManagerRef|) {
240 let cpm = llvm::LLVMCreatePassManager();
241 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
242 llvm::LLVMRustAddLibraryInfo(cpm, llmod);
244 llvm::LLVMDisposePassManager(cpm);
248 time(sess.time_passes(), "codegen passes", (), |()| {
250 output_type_none => {}
251 output_type_bitcode => {
252 output.with_c_str(|buf| {
253 llvm::LLVMWriteBitcodeToFile(llmod, buf);
256 output_type_llvm_assembly => {
257 output.with_c_str(|output| {
258 with_codegen(tm, llmod, |cpm| {
259 llvm::LLVMRustPrintModule(cpm, llmod, output);
263 output_type_assembly => {
264 with_codegen(tm, llmod, |cpm| {
265 WriteOutputFile(sess, tm, cpm, llmod, output,
266 lib::llvm::AssemblyFile);
269 // If we're not using the LLVM assembler, this function
270 // could be invoked specially with output_type_assembly,
271 // so in this case we still want the metadata object
273 if sess.opts.output_type != output_type_assembly {
274 with_codegen(tm, trans.metadata_module, |cpm| {
275 let out = output.with_extension("metadata.o");
276 WriteOutputFile(sess, tm, cpm,
277 trans.metadata_module, &out,
278 lib::llvm::ObjectFile);
282 output_type_exe | output_type_object => {
283 with_codegen(tm, llmod, |cpm| {
284 WriteOutputFile(sess, tm, cpm, llmod, output,
285 lib::llvm::ObjectFile);
287 with_codegen(tm, trans.metadata_module, |cpm| {
288 let out = output.with_extension("metadata.o");
289 WriteOutputFile(sess, tm, cpm,
290 trans.metadata_module, &out,
291 lib::llvm::ObjectFile);
297 llvm::LLVMRustDisposeTargetMachine(tm);
298 llvm::LLVMDisposeModule(trans.metadata_module);
299 llvm::LLVMDisposeModule(llmod);
300 llvm::LLVMContextDispose(llcx);
301 if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
305 pub fn run_assembler(sess: Session, assembly: &Path, object: &Path) {
306 let cc = super::get_cc_prog(sess);
308 // FIXME (#9639): This needs to handle non-utf8 paths
311 ~"-o", object.as_str().unwrap().to_owned(),
312 assembly.as_str().unwrap().to_owned()];
314 debug!("{} '{}'", cc, args.connect("' '"));
316 let _guard = io::ignore_io_error();
317 run::process_output(cc, args)
321 if !prog.status.success() {
322 sess.err(format!("linking with `{}` failed: {}", cc, prog.status));
323 sess.note(format!("{} arguments: '{}'", cc, args.connect("' '")));
324 sess.note(str::from_utf8_owned(prog.error + prog.output));
325 sess.abort_if_errors();
329 sess.err(format!("could not exec the linker `{}`", cc));
330 sess.abort_if_errors();
335 unsafe fn configure_llvm(sess: Session) {
336 // Copy what clan does by turning on loop vectorization at O2 and
337 // slp vectorization at O3
338 let vectorize_loop = !sess.no_vectorize_loops() &&
339 (sess.opts.optimize == session::Default ||
340 sess.opts.optimize == session::Aggressive);
341 let vectorize_slp = !sess.no_vectorize_slp() &&
342 sess.opts.optimize == session::Aggressive;
344 let mut llvm_c_strs = ~[];
345 let mut llvm_args = ~[];
346 let add = |arg: &str| {
347 let s = arg.to_c_str();
348 llvm_args.push(s.with_ref(|p| p));
351 add("rustc"); // fake program name
352 add("-arm-enable-ehabi");
353 add("-arm-enable-ehabi-descriptors");
354 if vectorize_loop { add("-vectorize-loops"); }
355 if vectorize_slp { add("-vectorize-slp"); }
356 if sess.time_llvm_passes() { add("-time-passes"); }
357 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
359 for arg in sess.opts.llvm_args.iter() {
363 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
366 unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
367 mpm: lib::llvm::PassManagerRef,
369 opt: lib::llvm::CodeGenOptLevel) {
370 // Create the PassManagerBuilder for LLVM. We configure it with
371 // reasonable defaults and prepare it to actually populate the pass
373 let builder = llvm::LLVMPassManagerBuilderCreate();
375 lib::llvm::CodeGenLevelNone => {
376 // Don't add lifetime intrinsics add O0
377 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
379 lib::llvm::CodeGenLevelLess => {
380 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
382 // numeric values copied from clang
383 lib::llvm::CodeGenLevelDefault => {
384 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
387 lib::llvm::CodeGenLevelAggressive => {
388 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
392 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
393 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
395 // Use the builder to populate the function/module pass managers.
396 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
397 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
398 llvm::LLVMPassManagerBuilderDispose(builder);
404 * Name mangling and its relationship to metadata. This is complex. Read
407 * The semantic model of Rust linkage is, broadly, that "there's no global
408 * namespace" between crates. Our aim is to preserve the illusion of this
409 * model despite the fact that it's not *quite* possible to implement on
410 * modern linkers. We initially didn't use system linkers at all, but have
411 * been convinced of their utility.
413 * There are a few issues to handle:
415 * - Linkers operate on a flat namespace, so we have to flatten names.
416 * We do this using the C++ namespace-mangling technique. Foo::bar
419 * - Symbols with the same name but different types need to get different
420 * linkage-names. We do this by hashing a string-encoding of the type into
421 * a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
422 * we use SHA256) to "prevent collisions". This is not airtight but 16 hex
423 * digits on uniform probability means you're going to need 2**32 same-name
424 * symbols in the same process before you're even hitting birthday-paradox
425 * collision probability.
427 * - Symbols in different crates but with same names "within" the crate need
428 * to get different linkage-names.
430 * - The hash shown in the filename needs to be predictable and stable for
431 * build tooling integration. It also needs to be using a hash function
432 * which is easy to use from Python, make, etc.
434 * So here is what we do:
436 * - Consider the package id; every crate has one (specified with pkgid
437 * attribute). If a package id isn't provided explicitly, we infer a
438 * versionless one from the output name. The version will end up being 0.0
439 * in this case. CNAME and CVERS are taken from this package id. For
440 * example, github.com/mozilla/CNAME#CVERS.
442 * - Define CMH as SHA256(pkgid).
444 * - Define CMH8 as the first 8 characters of CMH.
446 * - Compile our crate to lib CNAME-CMH8-CVERS.so
448 * - Define STH(sym) as SHA256(CMH, type_str(sym))
450 * - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
451 * name, non-name metadata, and type sense, and versioned in the way
452 * system linkers understand.
455 pub fn build_link_meta(sess: Session,
456 attrs: &[ast::Attribute],
458 symbol_hasher: &mut Sha256)
460 // This calculates CMH as defined above
461 fn crate_hash(symbol_hasher: &mut Sha256, pkgid: &PkgId) -> @str {
462 symbol_hasher.reset();
463 symbol_hasher.input_str(pkgid.to_str());
464 truncated_hash_result(symbol_hasher).to_managed()
467 let pkgid = match attr::find_pkgid(attrs) {
469 let stem = session::expect(
471 output.filestem_str(),
472 || format!("output file name '{}' doesn't appear to have a stem",
474 from_str(stem).unwrap()
479 let hash = crate_hash(symbol_hasher, &pkgid);
487 pub fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
488 symbol_hasher.result_str()
492 // This calculates STH for a symbol, as defined above
493 pub fn symbol_hash(tcx: ty::ctxt,
494 symbol_hasher: &mut Sha256,
496 link_meta: &LinkMeta) -> @str {
497 // NB: do *not* use abbrevs here as we want the symbol names
498 // to be independent of one another in the crate.
500 symbol_hasher.reset();
501 symbol_hasher.input_str(link_meta.pkgid.name);
502 symbol_hasher.input_str("-");
503 symbol_hasher.input_str(link_meta.crate_hash);
504 symbol_hasher.input_str("-");
505 symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
506 let mut hash = truncated_hash_result(symbol_hasher);
507 // Prefix with 'h' so that it never blends into adjacent digits
508 hash.unshift_char('h');
509 // tjc: allocation is unfortunate; need to change std::hash
513 pub fn get_symbol_hash(ccx: &mut CrateContext, t: ty::t) -> @str {
514 match ccx.type_hashcodes.find(&t) {
517 let hash = symbol_hash(ccx.tcx, &mut ccx.symbol_hasher, t, &ccx.link_meta);
518 ccx.type_hashcodes.insert(t, hash);
525 // Name sanitation. LLVM will happily accept identifiers with weird names, but
527 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
528 pub fn sanitize(s: &str) -> ~str {
529 let mut result = ~"";
532 // Escape these with $ sequences
533 '@' => result.push_str("$SP$"),
534 '~' => result.push_str("$UP$"),
535 '*' => result.push_str("$RP$"),
536 '&' => result.push_str("$BP$"),
537 '<' => result.push_str("$LT$"),
538 '>' => result.push_str("$GT$"),
539 '(' => result.push_str("$LP$"),
540 ')' => result.push_str("$RP$"),
541 ',' => result.push_str("$C$"),
543 // '.' doesn't occur in types and functions, so reuse it
545 '-' | ':' => result.push_char('.'),
547 // These are legal symbols
551 | '_' | '.' | '$' => result.push_char(c),
555 char::escape_unicode(c, |c| tstr.push_char(c));
556 result.push_char('$');
557 result.push_str(tstr.slice_from(1));
562 // Underscore-qualify anything that didn't start as an ident.
563 if result.len() > 0u &&
564 result[0] != '_' as u8 &&
565 ! char::is_XID_start(result[0] as char) {
566 return ~"_" + result;
572 pub fn mangle(sess: Session, ss: path,
573 hash: Option<&str>, vers: Option<&str>) -> ~str {
574 // Follow C++ namespace-mangling style, see
575 // http://en.wikipedia.org/wiki/Name_mangling for more info.
577 // It turns out that on OSX you can actually have arbitrary symbols in
578 // function names (at least when given to LLVM), but this is not possible
579 // when using unix's linker. Perhaps one day when we just a linker from LLVM
580 // we won't need to do this name mangling. The problem with name mangling is
581 // that it seriously limits the available characters. For example we can't
582 // have things like @T or ~[T] in symbol names when one would theoretically
583 // want them for things like impls of traits on that type.
585 // To be able to work on all platforms and get *some* reasonable output, we
586 // use C++ name-mangling.
588 let mut n = ~"_ZN"; // _Z == Begin name-sequence, N == nested
590 let push = |s: &str| {
591 let sani = sanitize(s);
592 n.push_str(format!("{}{}", sani.len(), sani));
595 // First, connect each component with <len, name> pairs.
598 path_name(s) | path_mod(s) | path_pretty_name(s, _) => {
604 // next, if any identifiers are "pretty" and need extra information tacked
605 // on, then use the hash to generate two unique characters. For now
606 // hopefully 2 characters is enough to avoid collisions.
607 static EXTRA_CHARS: &'static str =
608 "abcdefghijklmnopqrstuvwxyz\
609 ABCDEFGHIJKLMNOPQRSTUVWXYZ\
611 let mut hash = match hash { Some(s) => s.to_owned(), None => ~"" };
614 path_pretty_name(_, extra) => {
615 let hi = (extra >> 32) as u32 as uint;
616 let lo = extra as u32 as uint;
617 hash.push_char(EXTRA_CHARS[hi % EXTRA_CHARS.len()] as char);
618 hash.push_char(EXTRA_CHARS[lo % EXTRA_CHARS.len()] as char);
631 n.push_char('E'); // End name-sequence.
635 pub fn exported_name(sess: Session,
638 vers: &str) -> ~str {
639 // The version will get mangled to have a leading '_', but it makes more
640 // sense to lead with a 'v' b/c this is a version...
641 let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
647 mangle(sess, path, Some(hash), Some(vers.as_slice()))
650 pub fn mangle_exported_name(ccx: &mut CrateContext,
653 let hash = get_symbol_hash(ccx, t);
654 return exported_name(ccx.sess, path,
656 ccx.link_meta.pkgid.version_or_default());
659 pub fn mangle_internal_name_by_type_only(ccx: &mut CrateContext,
661 name: &str) -> ~str {
662 let s = ppaux::ty_to_short_str(ccx.tcx, t);
663 let hash = get_symbol_hash(ccx, t);
664 return mangle(ccx.sess,
665 ~[path_name(ccx.sess.ident_of(name)),
666 path_name(ccx.sess.ident_of(s))],
667 Some(hash.as_slice()),
671 pub fn mangle_internal_name_by_type_and_seq(ccx: &mut CrateContext,
673 name: &str) -> ~str {
674 let s = ppaux::ty_to_str(ccx.tcx, t);
675 let hash = get_symbol_hash(ccx, t);
676 let (_, name) = gensym_name(name);
677 return mangle(ccx.sess,
678 ~[path_name(ccx.sess.ident_of(s)), name],
679 Some(hash.as_slice()),
683 pub fn mangle_internal_name_by_path_and_seq(ccx: &mut CrateContext,
685 flav: &str) -> ~str {
686 let (_, name) = gensym_name(flav);
688 mangle(ccx.sess, path, None, None)
691 pub fn mangle_internal_name_by_path(ccx: &mut CrateContext, path: path) -> ~str {
692 mangle(ccx.sess, path, None, None)
695 pub fn output_lib_filename(lm: &LinkMeta) -> ~str {
698 lm.crate_hash.slice_chars(0, 8),
699 lm.pkgid.version_or_default())
702 pub fn get_cc_prog(sess: Session) -> ~str {
703 match sess.opts.linker {
704 Some(ref linker) => return linker.to_owned(),
708 // In the future, FreeBSD will use clang as default compiler.
709 // It would be flexible to use cc (system's default C compiler)
710 // instead of hard-coded gcc.
711 // For win32, there is no cc command, so we add a condition to make it use
712 // g++. We use g++ rather than gcc because it automatically adds linker
713 // options required for generation of dll modules that correctly register
714 // stack unwind tables.
715 match sess.targ_cfg.os {
716 abi::OsAndroid => match sess.opts.android_cross_path {
717 Some(ref path) => format!("{}/bin/arm-linux-androideabi-gcc", *path),
719 sess.fatal("need Android NDK path for linking \
720 (--android-cross-path)")
723 abi::OsWin32 => ~"g++",
728 /// Perform the linkage portion of the compilation phase. This will generate all
729 /// of the requested outputs for this compilation session.
730 pub fn link_binary(sess: Session,
731 trans: &CrateTranslation,
734 lm: &LinkMeta) -> ~[Path] {
735 let mut out_filenames = ~[];
736 for &output in sess.outputs.iter() {
737 let out_file = link_binary_output(sess, trans, output, obj_filename,
739 out_filenames.push(out_file);
742 // Remove the temporary object file and metadata if we aren't saving temps
743 if !sess.opts.save_temps {
744 fs::unlink(obj_filename);
745 fs::unlink(&obj_filename.with_extension("metadata.o"));
751 fn is_writeable(p: &Path) -> bool {
754 match io::result(|| p.stat()) {
756 Ok(m) => m.perm & io::UserWrite == io::UserWrite
760 pub fn filename_for_input(sess: &Session, output: session::OutputStyle, lm: &LinkMeta,
761 out_filename: &Path) -> Path {
762 let libname = output_lib_filename(lm);
764 session::OutputRlib => {
765 out_filename.with_filename(format!("lib{}.rlib", libname))
767 session::OutputDylib => {
768 let (prefix, suffix) = match sess.targ_cfg.os {
769 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
770 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
771 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
772 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
773 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
775 out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
777 session::OutputStaticlib => {
778 out_filename.with_filename(format!("lib{}.a", libname))
780 session::OutputExecutable => out_filename.clone(),
785 fn link_binary_output(sess: Session,
786 trans: &CrateTranslation,
787 output: session::OutputStyle,
790 lm: &LinkMeta) -> Path {
791 let out_filename = filename_for_input(&sess, output, lm, out_filename);
793 // Make sure the output and obj_filename are both writeable.
794 // Mac, FreeBSD, and Windows system linkers check this already --
795 // however, the Linux linker will happily overwrite a read-only file.
796 // We should be consistent.
797 let obj_is_writeable = is_writeable(obj_filename);
798 let out_is_writeable = is_writeable(&out_filename);
799 if !out_is_writeable {
800 sess.fatal(format!("Output file {} is not writeable -- check its permissions.",
801 out_filename.display()));
803 else if !obj_is_writeable {
804 sess.fatal(format!("Object file {} is not writeable -- check its permissions.",
805 obj_filename.display()));
809 session::OutputRlib => {
810 link_rlib(sess, Some(trans), obj_filename, &out_filename);
812 session::OutputStaticlib => {
813 link_staticlib(sess, obj_filename, &out_filename);
815 session::OutputExecutable => {
816 link_natively(sess, false, obj_filename, &out_filename);
817 // Windows linker will add an ".exe" extension if there was none
818 let out_filename = match out_filename.extension() {
819 Some(_) => out_filename.clone(),
820 None => out_filename.with_extension(win32::EXE_EXTENSION)
822 manifest::postprocess_executable(sess, &out_filename);
824 session::OutputDylib => {
825 link_natively(sess, true, obj_filename, &out_filename);
834 // An rlib in its current incarnation is essentially a renamed .a file. The
835 // rlib primarily contains the object file of the crate, but it also contains
836 // all of the object files from native libraries. This is done by unzipping
837 // native libraries and inserting all of the contents into this archive.
838 fn link_rlib(sess: Session,
839 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
841 out_filename: &Path) -> Archive {
842 let mut a = Archive::create(sess, out_filename, obj_filename);
844 for &(ref l, kind) in cstore::get_used_libraries(sess.cstore).iter() {
846 cstore::NativeStatic => {
847 a.add_native_library(l.as_slice());
849 cstore::NativeFramework | cstore::NativeUnknown => {}
853 // Note that it is important that we add all of our non-object "magical
854 // files" *after* all of the object files in the archive. The reason for
855 // this is as follows:
857 // * When performing LTO, this archive will be modified to remove
858 // obj_filename from above. The reason for this is described below.
860 // * When the system linker looks at an archive, it will attempt to
861 // determine the architecture of the archive in order to see whether its
864 // The algorithm for this detections is: iterate over the files in the
865 // archive. Skip magical SYMDEF names. Interpret the first file as an
866 // object file. Read architecture from the object file.
868 // * As one can probably see, if "metadata" and "foo.bc" were placed
869 // before all of the objects, then the architecture of this archive would
870 // not be correctly inferred once 'foo.o' is removed.
872 // Basically, all this means is that this code should not move above the
876 // Instead of putting the metadata in an object file section, rlibs
877 // contain the metadata in a separate file.
878 let metadata = obj_filename.with_filename(METADATA_FILENAME);
879 fs::File::create(&metadata).write(trans.metadata);
880 a.add_file(&metadata, false);
881 fs::unlink(&metadata);
883 // For LTO purposes, the bytecode of this library is also inserted
885 let bc = obj_filename.with_extension("bc");
886 a.add_file(&bc, false);
887 if !sess.opts.save_temps {
891 // Now that we've added files, some platforms need us to now update
892 // the symbol table in the archive (because some platforms die when
893 // adding files to the archive without symbols).
902 // Create a static archive
904 // This is essentially the same thing as an rlib, but it also involves adding
905 // all of the upstream crates' objects into the the archive. This will slurp in
906 // all of the native libraries of upstream dependencies as well.
908 // Additionally, there's no way for us to link dynamic libraries, so we warn
909 // about all dynamic library dependencies that they're not linked in.
911 // There's no need to include metadata in a static archive, so ensure to not
912 // link in the metadata object file (and also don't prepare the archive with a
914 fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
915 let mut a = link_rlib(sess, None, obj_filename, out_filename);
916 a.add_native_library("morestack");
918 let crates = cstore::get_used_crates(sess.cstore, cstore::RequireStatic);
919 for &(cnum, ref path) in crates.iter() {
920 let name = cstore::get_crate_data(sess.cstore, cnum).name;
921 let p = match *path {
922 Some(ref p) => p.clone(), None => {
923 sess.err(format!("could not find rlib for: `{}`", name));
927 a.add_rlib(&p, name, sess.lto());
928 let native_libs = csearch::get_native_libraries(sess.cstore, cnum);
929 for &(kind, ref lib) in native_libs.iter() {
930 let name = match kind {
931 cstore::NativeStatic => "static library",
932 cstore::NativeUnknown => "library",
933 cstore::NativeFramework => "framework",
935 sess.warn(format!("unlinked native {}: {}", name, *lib));
940 // Create a dynamic library or executable
942 // This will invoke the system linker/cc to create the resulting file. This
943 // links to all upstream files as well.
944 fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
945 out_filename: &Path) {
946 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
947 // The invocations of cc share some flags across platforms
948 let cc_prog = get_cc_prog(sess);
949 let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
950 cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
951 obj_filename, out_filename));
952 if (sess.opts.debugging_opts & session::print_link_args) != 0 {
953 println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
956 // May have not found libraries in the right formats.
957 sess.abort_if_errors();
959 // Invoke the system linker
960 debug!("{} {}", cc_prog, cc_args.connect(" "));
962 let _guard = io::ignore_io_error();
963 time(sess.time_passes(), "running linker", (), |()|
964 run::process_output(cc_prog, cc_args))
969 if !prog.status.success() {
970 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
971 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
972 sess.note(str::from_utf8_owned(prog.error + prog.output));
973 sess.abort_if_errors();
977 sess.err(format!("could not exec the linker `{}`", cc_prog));
978 sess.abort_if_errors();
983 // On OSX, debuggers need this utility to get run to do some munging of
985 if sess.targ_cfg.os == abi::OsMacos && sess.opts.debuginfo {
986 // FIXME (#9639): This needs to handle non-utf8 paths
987 run::process_status("dsymutil",
988 [out_filename.as_str().unwrap().to_owned()]);
992 fn link_args(sess: Session,
996 out_filename: &Path) -> ~[~str] {
998 // The default library location, we need this to find the runtime.
999 // The location of crates will be determined as needed.
1000 // FIXME (#9639): This needs to handle non-utf8 paths
1001 let lib_path = sess.filesearch.get_target_lib_path();
1002 let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
1004 let mut args = ~[stage];
1006 // FIXME (#9639): This needs to handle non-utf8 paths
1008 ~"-o", out_filename.as_str().unwrap().to_owned(),
1009 obj_filename.as_str().unwrap().to_owned()]);
1011 // When linking a dynamic library, we put the metadata into a section of the
1012 // executable. This metadata is in a separate object file from the main
1013 // object file, so we link that in here.
1015 let metadata = obj_filename.with_extension("metadata.o");
1016 args.push(metadata.as_str().unwrap().to_owned());
1019 if sess.targ_cfg.os == abi::OsLinux {
1020 // GNU-style linkers will use this to omit linking to libraries which
1021 // don't actually fulfill any relocations, but only for libraries which
1022 // follow this flag. Thus, use it before specifing libraries to link to.
1023 args.push(~"-Wl,--as-needed");
1025 // GNU-style linkers support optimization with -O. --gc-sections
1026 // removes metadata and potentially other useful things, so don't
1027 // include it. GNU ld doesn't need a numeric argument, but other linkers
1029 if sess.opts.optimize == session::Default ||
1030 sess.opts.optimize == session::Aggressive {
1031 args.push(~"-Wl,-O1");
1035 add_local_native_libraries(&mut args, sess);
1036 add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1037 add_upstream_native_libraries(&mut args, sess);
1039 // # Telling the linker what we're doing
1042 // On mac we need to tell the linker to let this library be rpathed
1043 if sess.targ_cfg.os == abi::OsMacos {
1044 args.push(~"-dynamiclib");
1045 args.push(~"-Wl,-dylib");
1046 // FIXME (#9639): This needs to handle non-utf8 paths
1047 args.push(~"-Wl,-install_name,@rpath/" +
1048 out_filename.filename_str().unwrap());
1050 args.push(~"-shared")
1054 if sess.targ_cfg.os == abi::OsFreebsd {
1055 args.push_all([~"-L/usr/local/lib",
1056 ~"-L/usr/local/lib/gcc46",
1057 ~"-L/usr/local/lib/gcc44"]);
1060 // Stack growth requires statically linking a __morestack function
1061 args.push(~"-lmorestack");
1063 // FIXME (#2397): At some point we want to rpath our guesses as to
1064 // where extern libraries might live, based on the
1065 // addl_lib_search_paths
1066 args.push_all(rpath::get_rpath_flags(sess, out_filename));
1068 // Finally add all the linker arguments provided on the command line along
1069 // with any #[link_args] attributes found inside the crate
1070 args.push_all(sess.opts.linker_args);
1071 for arg in cstore::get_used_link_args(sess.cstore).iter() {
1072 args.push(arg.clone());
1077 // # Native library linking
1079 // User-supplied library search paths (-L on the cammand line) These are
1080 // the same paths used to find Rust crates, so some of them may have been
1081 // added already by the previous crate linking code. This only allows them
1082 // to be found at compile time so it is still entirely up to outside
1083 // forces to make sure that library can be found at runtime.
1085 // Also note that the native libraries linked here are only the ones located
1086 // in the current crate. Upstream crates with native library dependencies
1087 // may have their native library pulled in above.
1088 fn add_local_native_libraries(args: &mut ~[~str], sess: Session) {
1089 for path in sess.opts.addl_lib_search_paths.iter() {
1090 // FIXME (#9639): This needs to handle non-utf8 paths
1091 args.push("-L" + path.as_str().unwrap().to_owned());
1094 let rustpath = filesearch::rust_path();
1095 for path in rustpath.iter() {
1096 // FIXME (#9639): This needs to handle non-utf8 paths
1097 args.push("-L" + path.as_str().unwrap().to_owned());
1100 for &(ref l, kind) in cstore::get_used_libraries(sess.cstore).iter() {
1102 cstore::NativeUnknown | cstore::NativeStatic => {
1103 args.push("-l" + *l);
1105 cstore::NativeFramework => {
1106 args.push(~"-framework");
1107 args.push(l.to_owned());
1113 // # Rust Crate linking
1115 // Rust crates are not considered at all when creating an rlib output. All
1116 // dependencies will be linked when producing the final output (instead of
1117 // the intermediate rlib version)
1118 fn add_upstream_rust_crates(args: &mut ~[~str], sess: Session,
1119 dylib: bool, tmpdir: &Path) {
1120 // Converts a library file-stem into a cc -l argument
1121 fn unlib(config: @session::config, stem: &str) -> ~str {
1122 if stem.starts_with("lib") &&
1123 config.os != abi::OsWin32 {
1124 stem.slice(3, stem.len()).to_owned()
1130 let cstore = sess.cstore;
1131 if !dylib && !sess.prefer_dynamic() {
1132 // With an executable, things get a little interesting. As a limitation
1133 // of the current implementation, we require that everything must be
1134 // static, or everything must be dynamic. The reasons for this are a
1135 // little subtle, but as with the above two cases, the goal is to
1136 // prevent duplicate copies of the same library showing up. For example,
1137 // a static immediate dependency might show up as an upstream dynamic
1138 // dependency and we currently have no way of knowing that. We know that
1139 // all dynamic libaries require dynamic dependencies (see above), so
1140 // it's satisfactory to include either all static libraries or all
1141 // dynamic libraries.
1142 let crates = cstore::get_used_crates(cstore, cstore::RequireStatic);
1143 if crates.iter().all(|&(_, ref p)| p.is_some()) {
1144 for (cnum, path) in crates.move_iter() {
1145 let cratepath = path.unwrap();
1147 // When performing LTO on an executable output, all of the
1148 // bytecode from the upstream libraries has already been
1149 // included in our object file output. We need to modify all of
1150 // the upstream archives to remove their corresponding object
1151 // file to make sure we don't pull the same code in twice.
1153 // We must continue to link to the upstream archives to be sure
1154 // to pull in native static dependencies. As the final caveat,
1155 // on linux it is apparently illegal to link to a blank archive,
1156 // so if an archive no longer has any object files in it after
1157 // we remove `lib.o`, then don't link against it at all.
1159 // If we're not doing LTO, then our job is simply to just link
1160 // against the archive.
1162 let name = cstore::get_crate_data(sess.cstore, cnum).name;
1163 time(sess.time_passes(), format!("altering {}.rlib", name),
1165 let dst = tmpdir.join(cratepath.filename().unwrap());
1166 fs::copy(&cratepath, &dst);
1167 let dst_str = dst.as_str().unwrap().to_owned();
1168 let mut archive = Archive::open(sess, dst);
1169 archive.remove_file(format!("{}.o", name));
1170 let files = archive.files();
1171 if files.iter().any(|s| s.ends_with(".o")) {
1176 args.push(cratepath.as_str().unwrap().to_owned());
1183 // If we're performing LTO, then it should have been previously required
1184 // that all upstream rust depenencies were available in an rlib format.
1185 assert!(!sess.lto());
1187 // This is a fallback of three different cases of linking:
1189 // * When creating a dynamic library, all inputs are required to be dynamic
1191 // * If an executable is created with a preference on dynamic linking, then
1192 // this case is the fallback
1193 // * If an executable is being created, and one of the inputs is missing as
1194 // a static library, then this is the fallback case.
1195 let crates = cstore::get_used_crates(cstore, cstore::RequireDynamic);
1196 for &(cnum, ref path) in crates.iter() {
1197 let cratepath = match *path {
1198 Some(ref p) => p.clone(),
1200 sess.err(format!("could not find dynamic library for: `{}`",
1201 cstore::get_crate_data(sess.cstore, cnum).name));
1205 // Just need to tell the linker about where the library lives and what
1207 let dir = cratepath.dirname_str().unwrap();
1208 if !dir.is_empty() { args.push("-L" + dir); }
1209 let libarg = unlib(sess.targ_cfg, cratepath.filestem_str().unwrap());
1210 args.push("-l" + libarg);
1214 // Link in all of our upstream crates' native dependencies. Remember that
1215 // all of these upstream native depenencies are all non-static
1216 // dependencies. We've got two cases then:
1218 // 1. The upstream crate is an rlib. In this case we *must* link in the
1219 // native dependency because the rlib is just an archive.
1221 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1222 // have the dependency present on the system somewhere. Thus, we don't
1223 // gain a whole lot from not linking in the dynamic dependency to this
1226 // The use case for this is a little subtle. In theory the native
1227 // dependencies of a crate a purely an implementation detail of the crate
1228 // itself, but the problem arises with generic and inlined functions. If a
1229 // generic function calls a native function, then the generic function must
1230 // be instantiated in the target crate, meaning that the native symbol must
1231 // also be resolved in the target crate.
1232 fn add_upstream_native_libraries(args: &mut ~[~str], sess: Session) {
1233 let cstore = sess.cstore;
1234 cstore::iter_crate_data(cstore, |cnum, _| {
1235 let libs = csearch::get_native_libraries(cstore, cnum);
1236 for &(kind, ref lib) in libs.iter() {
1238 cstore::NativeUnknown => args.push("-l" + *lib),
1239 cstore::NativeFramework => {
1240 args.push(~"-framework");
1241 args.push(lib.to_owned());
1243 cstore::NativeStatic => {
1244 sess.bug("statics shouldn't be propagated");