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_args.as_imm_buf(|p, len| {
364 llvm::LLVMRustSetLLVMOptions(len as c_int, p);
368 unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
369 mpm: lib::llvm::PassManagerRef,
371 opt: lib::llvm::CodeGenOptLevel) {
372 // Create the PassManagerBuilder for LLVM. We configure it with
373 // reasonable defaults and prepare it to actually populate the pass
375 let builder = llvm::LLVMPassManagerBuilderCreate();
377 lib::llvm::CodeGenLevelNone => {
378 // Don't add lifetime intrinsics add O0
379 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
381 lib::llvm::CodeGenLevelLess => {
382 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
384 // numeric values copied from clang
385 lib::llvm::CodeGenLevelDefault => {
386 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
389 lib::llvm::CodeGenLevelAggressive => {
390 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
394 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
395 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
397 // Use the builder to populate the function/module pass managers.
398 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
399 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
400 llvm::LLVMPassManagerBuilderDispose(builder);
406 * Name mangling and its relationship to metadata. This is complex. Read
409 * The semantic model of Rust linkage is, broadly, that "there's no global
410 * namespace" between crates. Our aim is to preserve the illusion of this
411 * model despite the fact that it's not *quite* possible to implement on
412 * modern linkers. We initially didn't use system linkers at all, but have
413 * been convinced of their utility.
415 * There are a few issues to handle:
417 * - Linkers operate on a flat namespace, so we have to flatten names.
418 * We do this using the C++ namespace-mangling technique. Foo::bar
421 * - Symbols with the same name but different types need to get different
422 * linkage-names. We do this by hashing a string-encoding of the type into
423 * a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
424 * we use SHA256) to "prevent collisions". This is not airtight but 16 hex
425 * digits on uniform probability means you're going to need 2**32 same-name
426 * symbols in the same process before you're even hitting birthday-paradox
427 * collision probability.
429 * - Symbols in different crates but with same names "within" the crate need
430 * to get different linkage-names.
432 * - The hash shown in the filename needs to be predictable and stable for
433 * build tooling integration. It also needs to be using a hash function
434 * which is easy to use from Python, make, etc.
436 * So here is what we do:
438 * - Consider the package id; every crate has one (specified with pkgid
439 * attribute). If a package id isn't provided explicitly, we infer a
440 * versionless one from the output name. The version will end up being 0.0
441 * in this case. CNAME and CVERS are taken from this package id. For
442 * example, github.com/mozilla/CNAME#CVERS.
444 * - Define CMH as SHA256(pkgid).
446 * - Define CMH8 as the first 8 characters of CMH.
448 * - Compile our crate to lib CNAME-CMH8-CVERS.so
450 * - Define STH(sym) as SHA256(CMH, type_str(sym))
452 * - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
453 * name, non-name metadata, and type sense, and versioned in the way
454 * system linkers understand.
457 pub fn build_link_meta(sess: Session,
460 symbol_hasher: &mut Sha256)
462 // This calculates CMH as defined above
463 fn crate_hash(symbol_hasher: &mut Sha256, pkgid: &PkgId) -> @str {
464 symbol_hasher.reset();
465 symbol_hasher.input_str(pkgid.to_str());
466 truncated_hash_result(symbol_hasher).to_managed()
469 let pkgid = match attr::find_pkgid(c.attrs) {
471 let stem = session::expect(
473 output.filestem_str(),
474 || format!("output file name '{}' doesn't appear to have a stem",
476 from_str(stem).unwrap()
481 let hash = crate_hash(symbol_hasher, &pkgid);
489 pub fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
490 symbol_hasher.result_str()
494 // This calculates STH for a symbol, as defined above
495 pub fn symbol_hash(tcx: ty::ctxt,
496 symbol_hasher: &mut Sha256,
498 link_meta: &LinkMeta) -> @str {
499 // NB: do *not* use abbrevs here as we want the symbol names
500 // to be independent of one another in the crate.
502 symbol_hasher.reset();
503 symbol_hasher.input_str(link_meta.pkgid.name);
504 symbol_hasher.input_str("-");
505 symbol_hasher.input_str(link_meta.crate_hash);
506 symbol_hasher.input_str("-");
507 symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
508 let mut hash = truncated_hash_result(symbol_hasher);
509 // Prefix with 'h' so that it never blends into adjacent digits
510 hash.unshift_char('h');
511 // tjc: allocation is unfortunate; need to change std::hash
515 pub fn get_symbol_hash(ccx: &mut CrateContext, t: ty::t) -> @str {
516 match ccx.type_hashcodes.find(&t) {
519 let hash = symbol_hash(ccx.tcx, &mut ccx.symbol_hasher, t, &ccx.link_meta);
520 ccx.type_hashcodes.insert(t, hash);
527 // Name sanitation. LLVM will happily accept identifiers with weird names, but
529 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
530 pub fn sanitize(s: &str) -> ~str {
531 let mut result = ~"";
534 // Escape these with $ sequences
535 '@' => result.push_str("$SP$"),
536 '~' => result.push_str("$UP$"),
537 '*' => result.push_str("$RP$"),
538 '&' => result.push_str("$BP$"),
539 '<' => result.push_str("$LT$"),
540 '>' => result.push_str("$GT$"),
541 '(' => result.push_str("$LP$"),
542 ')' => result.push_str("$RP$"),
543 ',' => result.push_str("$C$"),
545 // '.' doesn't occur in types and functions, so reuse it
547 '-' | ':' => result.push_char('.'),
549 // These are legal symbols
553 | '_' | '.' | '$' => result.push_char(c),
557 char::escape_unicode(c, |c| tstr.push_char(c));
558 result.push_char('$');
559 result.push_str(tstr.slice_from(1));
564 // Underscore-qualify anything that didn't start as an ident.
565 if result.len() > 0u &&
566 result[0] != '_' as u8 &&
567 ! char::is_XID_start(result[0] as char) {
568 return ~"_" + result;
574 pub fn mangle(sess: Session, ss: path,
575 hash: Option<&str>, vers: Option<&str>) -> ~str {
576 // Follow C++ namespace-mangling style, see
577 // http://en.wikipedia.org/wiki/Name_mangling for more info.
579 // It turns out that on OSX you can actually have arbitrary symbols in
580 // function names (at least when given to LLVM), but this is not possible
581 // when using unix's linker. Perhaps one day when we just a linker from LLVM
582 // we won't need to do this name mangling. The problem with name mangling is
583 // that it seriously limits the available characters. For example we can't
584 // have things like @T or ~[T] in symbol names when one would theoretically
585 // want them for things like impls of traits on that type.
587 // To be able to work on all platforms and get *some* reasonable output, we
588 // use C++ name-mangling.
590 let mut n = ~"_ZN"; // _Z == Begin name-sequence, N == nested
592 let push = |s: &str| {
593 let sani = sanitize(s);
594 n.push_str(format!("{}{}", sani.len(), sani));
597 // First, connect each component with <len, name> pairs.
600 path_name(s) | path_mod(s) | path_pretty_name(s, _) => {
606 // next, if any identifiers are "pretty" and need extra information tacked
607 // on, then use the hash to generate two unique characters. For now
608 // hopefully 2 characters is enough to avoid collisions.
609 static EXTRA_CHARS: &'static str =
610 "abcdefghijklmnopqrstuvwxyz\
611 ABCDEFGHIJKLMNOPQRSTUVWXYZ\
613 let mut hash = match hash { Some(s) => s.to_owned(), None => ~"" };
616 path_pretty_name(_, extra) => {
617 let hi = (extra >> 32) as u32 as uint;
618 let lo = extra as u32 as uint;
619 hash.push_char(EXTRA_CHARS[hi % EXTRA_CHARS.len()] as char);
620 hash.push_char(EXTRA_CHARS[lo % EXTRA_CHARS.len()] as char);
633 n.push_char('E'); // End name-sequence.
637 pub fn exported_name(sess: Session,
640 vers: &str) -> ~str {
641 // The version will get mangled to have a leading '_', but it makes more
642 // sense to lead with a 'v' b/c this is a version...
643 let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
649 mangle(sess, path, Some(hash), Some(vers.as_slice()))
652 pub fn mangle_exported_name(ccx: &mut CrateContext,
655 let hash = get_symbol_hash(ccx, t);
656 return exported_name(ccx.sess, path,
658 ccx.link_meta.pkgid.version_or_default());
661 pub fn mangle_internal_name_by_type_only(ccx: &mut CrateContext,
663 name: &str) -> ~str {
664 let s = ppaux::ty_to_short_str(ccx.tcx, t);
665 let hash = get_symbol_hash(ccx, t);
666 return mangle(ccx.sess,
667 ~[path_name(ccx.sess.ident_of(name)),
668 path_name(ccx.sess.ident_of(s))],
669 Some(hash.as_slice()),
673 pub fn mangle_internal_name_by_type_and_seq(ccx: &mut CrateContext,
675 name: &str) -> ~str {
676 let s = ppaux::ty_to_str(ccx.tcx, t);
677 let hash = get_symbol_hash(ccx, t);
678 let (_, name) = gensym_name(name);
679 return mangle(ccx.sess,
680 ~[path_name(ccx.sess.ident_of(s)), name],
681 Some(hash.as_slice()),
685 pub fn mangle_internal_name_by_path_and_seq(ccx: &mut CrateContext,
687 flav: &str) -> ~str {
688 let (_, name) = gensym_name(flav);
690 mangle(ccx.sess, path, None, None)
693 pub fn mangle_internal_name_by_path(ccx: &mut CrateContext, path: path) -> ~str {
694 mangle(ccx.sess, path, None, None)
697 pub fn output_lib_filename(lm: &LinkMeta) -> ~str {
700 lm.crate_hash.slice_chars(0, 8),
701 lm.pkgid.version_or_default())
704 pub fn get_cc_prog(sess: Session) -> ~str {
705 match sess.opts.linker {
706 Some(ref linker) => return linker.to_owned(),
710 // In the future, FreeBSD will use clang as default compiler.
711 // It would be flexible to use cc (system's default C compiler)
712 // instead of hard-coded gcc.
713 // For win32, there is no cc command, so we add a condition to make it use
714 // g++. We use g++ rather than gcc because it automatically adds linker
715 // options required for generation of dll modules that correctly register
716 // stack unwind tables.
717 match sess.targ_cfg.os {
718 abi::OsAndroid => match sess.opts.android_cross_path {
719 Some(ref path) => format!("{}/bin/arm-linux-androideabi-gcc", *path),
721 sess.fatal("need Android NDK path for linking \
722 (--android-cross-path)")
725 abi::OsWin32 => ~"g++",
730 /// Perform the linkage portion of the compilation phase. This will generate all
731 /// of the requested outputs for this compilation session.
732 pub fn link_binary(sess: Session,
733 trans: &CrateTranslation,
736 lm: &LinkMeta) -> ~[Path] {
737 let mut out_filenames = ~[];
738 for &output in sess.outputs.iter() {
739 let out_file = link_binary_output(sess, trans, output, obj_filename,
741 out_filenames.push(out_file);
744 // Remove the temporary object file and metadata if we aren't saving temps
745 if !sess.opts.save_temps {
746 fs::unlink(obj_filename);
747 fs::unlink(&obj_filename.with_extension("metadata.o"));
753 fn is_writeable(p: &Path) -> bool {
756 match io::result(|| p.stat()) {
758 Ok(m) => m.perm & io::UserWrite == io::UserWrite
762 fn link_binary_output(sess: Session,
763 trans: &CrateTranslation,
764 output: session::OutputStyle,
767 lm: &LinkMeta) -> Path {
768 let libname = output_lib_filename(lm);
769 let out_filename = match output {
770 session::OutputRlib => {
771 out_filename.with_filename(format!("lib{}.rlib", libname))
773 session::OutputDylib => {
774 let (prefix, suffix) = match sess.targ_cfg.os {
775 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
776 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
777 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
778 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
779 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
781 out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
783 session::OutputStaticlib => {
784 out_filename.with_filename(format!("lib{}.a", libname))
786 session::OutputExecutable => out_filename.clone(),
789 // Make sure the output and obj_filename are both writeable.
790 // Mac, FreeBSD, and Windows system linkers check this already --
791 // however, the Linux linker will happily overwrite a read-only file.
792 // We should be consistent.
793 let obj_is_writeable = is_writeable(obj_filename);
794 let out_is_writeable = is_writeable(&out_filename);
795 if !out_is_writeable {
796 sess.fatal(format!("Output file {} is not writeable -- check its permissions.",
797 out_filename.display()));
799 else if !obj_is_writeable {
800 sess.fatal(format!("Object file {} is not writeable -- check its permissions.",
801 obj_filename.display()));
805 session::OutputRlib => {
806 link_rlib(sess, Some(trans), obj_filename, &out_filename);
808 session::OutputStaticlib => {
809 link_staticlib(sess, obj_filename, &out_filename);
811 session::OutputExecutable => {
812 link_natively(sess, false, obj_filename, &out_filename);
813 // Windows linker will add an ".exe" extension if there was none
814 let out_filename = match out_filename.extension() {
815 Some(_) => out_filename.clone(),
816 None => out_filename.with_extension(win32::EXE_EXTENSION)
818 manifest::postprocess_executable(sess, &out_filename);
820 session::OutputDylib => {
821 link_natively(sess, true, obj_filename, &out_filename);
830 // An rlib in its current incarnation is essentially a renamed .a file. The
831 // rlib primarily contains the object file of the crate, but it also contains
832 // all of the object files from native libraries. This is done by unzipping
833 // native libraries and inserting all of the contents into this archive.
834 fn link_rlib(sess: Session,
835 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
837 out_filename: &Path) -> Archive {
838 let mut a = Archive::create(sess, out_filename, obj_filename);
840 for &(ref l, kind) in cstore::get_used_libraries(sess.cstore).iter() {
842 cstore::NativeStatic => {
843 a.add_native_library(l.as_slice());
845 cstore::NativeFramework | cstore::NativeUnknown => {}
849 // Note that it is important that we add all of our non-object "magical
850 // files" *after* all of the object files in the archive. The reason for
851 // this is as follows:
853 // * When performing LTO, this archive will be modified to remove
854 // obj_filename from above. The reason for this is described below.
856 // * When the system linker looks at an archive, it will attempt to
857 // determine the architecture of the archive in order to see whether its
860 // The algorithm for this detections is: iterate over the files in the
861 // archive. Skip magical SYMDEF names. Interpret the first file as an
862 // object file. Read architecture from the object file.
864 // * As one can probably see, if "metadata" and "foo.bc" were placed
865 // before all of the objects, then the architecture of this archive would
866 // not be correctly inferred once 'foo.o' is removed.
868 // Basically, all this means is that this code should not move above the
872 // Instead of putting the metadata in an object file section, rlibs
873 // contain the metadata in a separate file.
874 let metadata = obj_filename.with_filename(METADATA_FILENAME);
875 fs::File::create(&metadata).write(trans.metadata);
876 a.add_file(&metadata, false);
877 fs::unlink(&metadata);
879 // For LTO purposes, the bytecode of this library is also inserted
881 let bc = obj_filename.with_extension("bc");
882 a.add_file(&bc, false);
883 if !sess.opts.save_temps {
887 // Now that we've added files, some platforms need us to now update
888 // the symbol table in the archive (because some platforms die when
889 // adding files to the archive without symbols).
898 // Create a static archive
900 // This is essentially the same thing as an rlib, but it also involves adding
901 // all of the upstream crates' objects into the the archive. This will slurp in
902 // all of the native libraries of upstream dependencies as well.
904 // Additionally, there's no way for us to link dynamic libraries, so we warn
905 // about all dynamic library dependencies that they're not linked in.
907 // There's no need to include metadata in a static archive, so ensure to not
908 // link in the metadata object file (and also don't prepare the archive with a
910 fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
911 let mut a = link_rlib(sess, None, obj_filename, out_filename);
912 a.add_native_library("morestack");
914 let crates = cstore::get_used_crates(sess.cstore, cstore::RequireStatic);
915 for &(cnum, ref path) in crates.iter() {
916 let name = cstore::get_crate_data(sess.cstore, cnum).name;
917 let p = match *path {
918 Some(ref p) => p.clone(), None => {
919 sess.err(format!("could not find rlib for: `{}`", name));
923 a.add_rlib(&p, name, sess.lto());
924 let native_libs = csearch::get_native_libraries(sess.cstore, cnum);
925 for &(kind, ref lib) in native_libs.iter() {
926 let name = match kind {
927 cstore::NativeStatic => "static library",
928 cstore::NativeUnknown => "library",
929 cstore::NativeFramework => "framework",
931 sess.warn(format!("unlinked native {}: {}", name, *lib));
936 // Create a dynamic library or executable
938 // This will invoke the system linker/cc to create the resulting file. This
939 // links to all upstream files as well.
940 fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
941 out_filename: &Path) {
942 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
943 // The invocations of cc share some flags across platforms
944 let cc_prog = get_cc_prog(sess);
945 let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
946 cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
947 obj_filename, out_filename));
948 if (sess.opts.debugging_opts & session::print_link_args) != 0 {
949 println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
952 // May have not found libraries in the right formats.
953 sess.abort_if_errors();
955 // Invoke the system linker
956 debug!("{} {}", cc_prog, cc_args.connect(" "));
958 let _guard = io::ignore_io_error();
959 time(sess.time_passes(), "running linker", (), |()|
960 run::process_output(cc_prog, cc_args))
965 if !prog.status.success() {
966 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
967 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
968 sess.note(str::from_utf8_owned(prog.error + prog.output));
969 sess.abort_if_errors();
973 sess.err(format!("could not exec the linker `{}`", cc_prog));
974 sess.abort_if_errors();
979 // On OSX, debuggers need this utility to get run to do some munging of
981 if sess.targ_cfg.os == abi::OsMacos && sess.opts.debuginfo {
982 // FIXME (#9639): This needs to handle non-utf8 paths
983 run::process_status("dsymutil",
984 [out_filename.as_str().unwrap().to_owned()]);
988 fn link_args(sess: Session,
992 out_filename: &Path) -> ~[~str] {
994 // The default library location, we need this to find the runtime.
995 // The location of crates will be determined as needed.
996 // FIXME (#9639): This needs to handle non-utf8 paths
997 let lib_path = sess.filesearch.get_target_lib_path();
998 let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
1000 let mut args = ~[stage];
1002 // FIXME (#9639): This needs to handle non-utf8 paths
1004 ~"-o", out_filename.as_str().unwrap().to_owned(),
1005 obj_filename.as_str().unwrap().to_owned()]);
1007 // When linking a dynamic library, we put the metadata into a section of the
1008 // executable. This metadata is in a separate object file from the main
1009 // object file, so we link that in here.
1011 let metadata = obj_filename.with_extension("metadata.o");
1012 args.push(metadata.as_str().unwrap().to_owned());
1015 if sess.targ_cfg.os == abi::OsLinux {
1016 // GNU-style linkers will use this to omit linking to libraries which
1017 // don't actually fulfill any relocations, but only for libraries which
1018 // follow this flag. Thus, use it before specifing libraries to link to.
1019 args.push(~"-Wl,--as-needed");
1021 // GNU-style linkers support optimization with -O. --gc-sections
1022 // removes metadata and potentially other useful things, so don't
1023 // include it. GNU ld doesn't need a numeric argument, but other linkers
1025 if sess.opts.optimize == session::Default ||
1026 sess.opts.optimize == session::Aggressive {
1027 args.push(~"-Wl,-O1");
1031 add_local_native_libraries(&mut args, sess);
1032 add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1033 add_upstream_native_libraries(&mut args, sess);
1035 // # Telling the linker what we're doing
1038 // On mac we need to tell the linker to let this library be rpathed
1039 if sess.targ_cfg.os == abi::OsMacos {
1040 args.push(~"-dynamiclib");
1041 args.push(~"-Wl,-dylib");
1042 // FIXME (#9639): This needs to handle non-utf8 paths
1043 args.push(~"-Wl,-install_name,@rpath/" +
1044 out_filename.filename_str().unwrap());
1046 args.push(~"-shared")
1050 if sess.targ_cfg.os == abi::OsFreebsd {
1051 args.push_all([~"-L/usr/local/lib",
1052 ~"-L/usr/local/lib/gcc46",
1053 ~"-L/usr/local/lib/gcc44"]);
1056 // Stack growth requires statically linking a __morestack function
1057 args.push(~"-lmorestack");
1059 // FIXME (#2397): At some point we want to rpath our guesses as to
1060 // where extern libraries might live, based on the
1061 // addl_lib_search_paths
1062 args.push_all(rpath::get_rpath_flags(sess, out_filename));
1064 // Finally add all the linker arguments provided on the command line along
1065 // with any #[link_args] attributes found inside the crate
1066 args.push_all(sess.opts.linker_args);
1067 for arg in cstore::get_used_link_args(sess.cstore).iter() {
1068 args.push(arg.clone());
1073 // # Native library linking
1075 // User-supplied library search paths (-L on the cammand line) These are
1076 // the same paths used to find Rust crates, so some of them may have been
1077 // added already by the previous crate linking code. This only allows them
1078 // to be found at compile time so it is still entirely up to outside
1079 // forces to make sure that library can be found at runtime.
1081 // Also note that the native libraries linked here are only the ones located
1082 // in the current crate. Upstream crates with native library dependencies
1083 // may have their native library pulled in above.
1084 fn add_local_native_libraries(args: &mut ~[~str], sess: Session) {
1085 for path in sess.opts.addl_lib_search_paths.iter() {
1086 // FIXME (#9639): This needs to handle non-utf8 paths
1087 args.push("-L" + path.as_str().unwrap().to_owned());
1090 let rustpath = filesearch::rust_path();
1091 for path in rustpath.iter() {
1092 // FIXME (#9639): This needs to handle non-utf8 paths
1093 args.push("-L" + path.as_str().unwrap().to_owned());
1096 for &(ref l, kind) in cstore::get_used_libraries(sess.cstore).iter() {
1098 cstore::NativeUnknown | cstore::NativeStatic => {
1099 args.push("-l" + *l);
1101 cstore::NativeFramework => {
1102 args.push(~"-framework");
1103 args.push(l.to_owned());
1109 // # Rust Crate linking
1111 // Rust crates are not considered at all when creating an rlib output. All
1112 // dependencies will be linked when producing the final output (instead of
1113 // the intermediate rlib version)
1114 fn add_upstream_rust_crates(args: &mut ~[~str], sess: Session,
1115 dylib: bool, tmpdir: &Path) {
1116 // Converts a library file-stem into a cc -l argument
1117 fn unlib(config: @session::config, stem: &str) -> ~str {
1118 if stem.starts_with("lib") &&
1119 config.os != abi::OsWin32 {
1120 stem.slice(3, stem.len()).to_owned()
1126 let cstore = sess.cstore;
1127 if !dylib && !sess.prefer_dynamic() {
1128 // With an executable, things get a little interesting. As a limitation
1129 // of the current implementation, we require that everything must be
1130 // static, or everything must be dynamic. The reasons for this are a
1131 // little subtle, but as with the above two cases, the goal is to
1132 // prevent duplicate copies of the same library showing up. For example,
1133 // a static immediate dependency might show up as an upstream dynamic
1134 // dependency and we currently have no way of knowing that. We know that
1135 // all dynamic libaries require dynamic dependencies (see above), so
1136 // it's satisfactory to include either all static libraries or all
1137 // dynamic libraries.
1138 let crates = cstore::get_used_crates(cstore, cstore::RequireStatic);
1139 if crates.iter().all(|&(_, ref p)| p.is_some()) {
1140 for (cnum, path) in crates.move_iter() {
1141 let cratepath = path.unwrap();
1143 // When performing LTO on an executable output, all of the
1144 // bytecode from the upstream libraries has already been
1145 // included in our object file output. We need to modify all of
1146 // the upstream archives to remove their corresponding object
1147 // file to make sure we don't pull the same code in twice.
1149 // We must continue to link to the upstream archives to be sure
1150 // to pull in native static dependencies. As the final caveat,
1151 // on linux it is apparently illegal to link to a blank archive,
1152 // so if an archive no longer has any object files in it after
1153 // we remove `lib.o`, then don't link against it at all.
1155 // If we're not doing LTO, then our job is simply to just link
1156 // against the archive.
1158 let name = cstore::get_crate_data(sess.cstore, cnum).name;
1159 time(sess.time_passes(), format!("altering {}.rlib", name),
1161 let dst = tmpdir.join(cratepath.filename().unwrap());
1162 fs::copy(&cratepath, &dst);
1163 let dst_str = dst.as_str().unwrap().to_owned();
1164 let mut archive = Archive::open(sess, dst);
1165 archive.remove_file(format!("{}.o", name));
1166 let files = archive.files();
1167 if files.iter().any(|s| s.ends_with(".o")) {
1172 args.push(cratepath.as_str().unwrap().to_owned());
1179 // If we're performing LTO, then it should have been previously required
1180 // that all upstream rust depenencies were available in an rlib format.
1181 assert!(!sess.lto());
1183 // This is a fallback of three different cases of linking:
1185 // * When creating a dynamic library, all inputs are required to be dynamic
1187 // * If an executable is created with a preference on dynamic linking, then
1188 // this case is the fallback
1189 // * If an executable is being created, and one of the inputs is missing as
1190 // a static library, then this is the fallback case.
1191 let crates = cstore::get_used_crates(cstore, cstore::RequireDynamic);
1192 for &(cnum, ref path) in crates.iter() {
1193 let cratepath = match *path {
1194 Some(ref p) => p.clone(),
1196 sess.err(format!("could not find dynamic library for: `{}`",
1197 cstore::get_crate_data(sess.cstore, cnum).name));
1201 // Just need to tell the linker about where the library lives and what
1203 let dir = cratepath.dirname_str().unwrap();
1204 if !dir.is_empty() { args.push("-L" + dir); }
1205 let libarg = unlib(sess.targ_cfg, cratepath.filestem_str().unwrap());
1206 args.push("-l" + libarg);
1210 // Link in all of our upstream crates' native dependencies. Remember that
1211 // all of these upstream native depenencies are all non-static
1212 // dependencies. We've got two cases then:
1214 // 1. The upstream crate is an rlib. In this case we *must* link in the
1215 // native dependency because the rlib is just an archive.
1217 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1218 // have the dependency present on the system somewhere. Thus, we don't
1219 // gain a whole lot from not linking in the dynamic dependency to this
1222 // The use case for this is a little subtle. In theory the native
1223 // dependencies of a crate a purely an implementation detail of the crate
1224 // itself, but the problem arises with generic and inlined functions. If a
1225 // generic function calls a native function, then the generic function must
1226 // be instantiated in the target crate, meaning that the native symbol must
1227 // also be resolved in the target crate.
1228 fn add_upstream_native_libraries(args: &mut ~[~str], sess: Session) {
1229 let cstore = sess.cstore;
1230 cstore::iter_crate_data(cstore, |cnum, _| {
1231 let libs = csearch::get_native_libraries(cstore, cnum);
1232 for &(kind, ref lib) in libs.iter() {
1234 cstore::NativeUnknown => args.push("-l" + *lib),
1235 cstore::NativeFramework => {
1236 args.push(~"-framework");
1237 args.push(lib.to_owned());
1239 cstore::NativeStatic => {
1240 sess.bug("statics shouldn't be propagated");