1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 use back::archive::{Archive, METADATA_FILENAME};
14 use driver::driver::{CrateTranslation, OutputFilenames};
15 use driver::session::{NoDebugInfo, 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, CString};
31 use std::io::{fs, TempDir, Process};
33 use std::os::consts::{macos, freebsd, linux, android, win32};
36 use std::strbuf::StrBuf;
38 use serialize::hex::ToHex;
41 use syntax::ast_map::{PathElem, PathElems, PathName};
44 use syntax::attr::AttrMetaMethods;
45 use syntax::crateid::CrateId;
46 use syntax::parse::token;
48 #[deriving(Clone, Eq, Ord, TotalOrd, TotalEq)]
52 OutputTypeLlvmAssembly,
57 pub fn llvm_err(sess: &Session, msg: ~str) -> ! {
59 let cstr = llvm::LLVMRustGetLastError();
60 if cstr == ptr::null() {
63 let err = CString::new(cstr, false);
64 let err = str::from_utf8_lossy(err.as_bytes());
65 sess.fatal(msg + ": " + err.as_slice());
70 pub fn WriteOutputFile(
72 target: lib::llvm::TargetMachineRef,
73 pm: lib::llvm::PassManagerRef,
76 file_type: lib::llvm::FileType) {
78 output.with_c_str(|output| {
79 let result = llvm::LLVMRustWriteOutputFile(
80 target, pm, m, output, file_type);
82 llvm_err(sess, ~"could not write output");
91 use back::link::{WriteOutputFile, OutputType};
92 use back::link::{OutputTypeAssembly, OutputTypeBitcode};
93 use back::link::{OutputTypeExe, OutputTypeLlvmAssembly};
94 use back::link::{OutputTypeObject};
95 use driver::driver::{CrateTranslation, OutputFilenames};
96 use driver::session::{NoDebugInfo, Session};
99 use lib::llvm::{ModuleRef, TargetMachineRef, PassManagerRef};
101 use util::common::time;
104 use std::c_str::ToCStr;
105 use std::io::Process;
106 use libc::{c_uint, c_int};
109 // On android, we by default compile for armv7 processors. This enables
110 // things like double word CAS instructions (rather than emulating them)
111 // which are *far* more efficient. This is obviously undesirable in some
112 // cases, so if any sort of target feature is specified we don't append v7
113 // to the feature list.
114 fn target_feature<'a>(sess: &'a Session) -> &'a str {
115 match sess.targ_cfg.os {
117 if "" == sess.opts.cg.target_feature {
120 sess.opts.cg.target_feature.as_slice()
123 _ => sess.opts.cg.target_feature.as_slice()
127 pub fn run_passes(sess: &Session,
128 trans: &CrateTranslation,
129 output_types: &[OutputType],
130 output: &OutputFilenames) {
131 let llmod = trans.module;
132 let llcx = trans.context;
134 configure_llvm(sess);
136 if sess.opts.cg.save_temps {
137 output.with_extension("no-opt.bc").with_c_str(|buf| {
138 llvm::LLVMWriteBitcodeToFile(llmod, buf);
142 let opt_level = match sess.opts.optimize {
143 session::No => lib::llvm::CodeGenLevelNone,
144 session::Less => lib::llvm::CodeGenLevelLess,
145 session::Default => lib::llvm::CodeGenLevelDefault,
146 session::Aggressive => lib::llvm::CodeGenLevelAggressive,
148 let use_softfp = sess.opts.cg.soft_float;
150 // FIXME: #11906: Omitting frame pointers breaks retrieving the value of a parameter.
151 // FIXME: #11954: mac64 unwinding may not work with fp elim
152 let no_fp_elim = (sess.opts.debuginfo != NoDebugInfo) ||
153 (sess.targ_cfg.os == abi::OsMacos &&
154 sess.targ_cfg.arch == abi::X86_64);
156 let reloc_model = match sess.opts.cg.relocation_model.as_slice() {
157 "pic" => lib::llvm::RelocPIC,
158 "static" => lib::llvm::RelocStatic,
159 "default" => lib::llvm::RelocDefault,
160 "dynamic-no-pic" => lib::llvm::RelocDynamicNoPic,
162 sess.err(format!("{} is not a valid relocation mode",
163 sess.opts.cg.relocation_model));
164 sess.abort_if_errors();
169 let tm = sess.targ_cfg.target_strs.target_triple.with_c_str(|t| {
170 sess.opts.cg.target_cpu.with_c_str(|cpu| {
171 target_feature(sess).with_c_str(|features| {
172 llvm::LLVMRustCreateTargetMachine(
174 lib::llvm::CodeModelDefault,
185 // Create the two optimizing pass managers. These mirror what clang
186 // does, and are by populated by LLVM's default PassManagerBuilder.
187 // Each manager has a different set of passes, but they also share
188 // some common passes.
189 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
190 let mpm = llvm::LLVMCreatePassManager();
192 // If we're verifying or linting, add them to the function pass
194 let addpass = |pass: &str| {
195 pass.with_c_str(|s| llvm::LLVMRustAddPass(fpm, s))
197 if !sess.no_verify() { assert!(addpass("verify")); }
199 if !sess.opts.cg.no_prepopulate_passes {
200 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
201 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
202 populate_llvm_passes(fpm, mpm, llmod, opt_level);
205 for pass in sess.opts.cg.passes.iter() {
206 pass.with_c_str(|s| {
207 if !llvm::LLVMRustAddPass(mpm, s) {
208 sess.warn(format!("unknown pass {}, ignoring", *pass));
213 // Finally, run the actual optimization passes
214 time(sess.time_passes(), "llvm function passes", (), |()|
215 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
216 time(sess.time_passes(), "llvm module passes", (), |()|
217 llvm::LLVMRunPassManager(mpm, llmod));
219 // Deallocate managers that we're now done with
220 llvm::LLVMDisposePassManager(fpm);
221 llvm::LLVMDisposePassManager(mpm);
223 // Emit the bytecode if we're either saving our temporaries or
224 // emitting an rlib. Whenever an rlib is created, the bytecode is
225 // inserted into the archive in order to allow LTO against it.
226 if sess.opts.cg.save_temps ||
227 (sess.crate_types.borrow().contains(&session::CrateTypeRlib) &&
228 sess.opts.output_types.contains(&OutputTypeExe)) {
229 output.temp_path(OutputTypeBitcode).with_c_str(|buf| {
230 llvm::LLVMWriteBitcodeToFile(llmod, buf);
235 time(sess.time_passes(), "all lto passes", (), |()|
236 lto::run(sess, llmod, tm, trans.reachable.as_slice()));
238 if sess.opts.cg.save_temps {
239 output.with_extension("lto.bc").with_c_str(|buf| {
240 llvm::LLVMWriteBitcodeToFile(llmod, buf);
245 // A codegen-specific pass manager is used to generate object
246 // files for an LLVM module.
248 // Apparently each of these pass managers is a one-shot kind of
249 // thing, so we create a new one for each type of output. The
250 // pass manager passed to the closure should be ensured to not
251 // escape the closure itself, and the manager should only be
253 fn with_codegen(tm: TargetMachineRef, llmod: ModuleRef,
254 f: |PassManagerRef|) {
256 let cpm = llvm::LLVMCreatePassManager();
257 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
258 llvm::LLVMRustAddLibraryInfo(cpm, llmod);
260 llvm::LLVMDisposePassManager(cpm);
264 let mut object_file = None;
265 let mut needs_metadata = false;
266 for output_type in output_types.iter() {
267 let path = output.path(*output_type);
269 OutputTypeBitcode => {
270 path.with_c_str(|buf| {
271 llvm::LLVMWriteBitcodeToFile(llmod, buf);
274 OutputTypeLlvmAssembly => {
275 path.with_c_str(|output| {
276 with_codegen(tm, llmod, |cpm| {
277 llvm::LLVMRustPrintModule(cpm, llmod, output);
281 OutputTypeAssembly => {
282 // If we're not using the LLVM assembler, this function
283 // could be invoked specially with output_type_assembly,
284 // so in this case we still want the metadata object
286 let ty = OutputTypeAssembly;
287 let path = if sess.opts.output_types.contains(&ty) {
290 needs_metadata = true;
291 output.temp_path(OutputTypeAssembly)
293 with_codegen(tm, llmod, |cpm| {
294 WriteOutputFile(sess, tm, cpm, llmod, &path,
295 lib::llvm::AssemblyFile);
298 OutputTypeObject => {
299 object_file = Some(path);
302 object_file = Some(output.temp_path(OutputTypeObject));
303 needs_metadata = true;
308 time(sess.time_passes(), "codegen passes", (), |()| {
311 with_codegen(tm, llmod, |cpm| {
312 WriteOutputFile(sess, tm, cpm, llmod, path,
313 lib::llvm::ObjectFile);
319 with_codegen(tm, trans.metadata_module, |cpm| {
320 let out = output.temp_path(OutputTypeObject)
321 .with_extension("metadata.o");
322 WriteOutputFile(sess, tm, cpm,
323 trans.metadata_module, &out,
324 lib::llvm::ObjectFile);
329 llvm::LLVMRustDisposeTargetMachine(tm);
330 llvm::LLVMDisposeModule(trans.metadata_module);
331 llvm::LLVMDisposeModule(llmod);
332 llvm::LLVMContextDispose(llcx);
333 if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
337 pub fn run_assembler(sess: &Session, outputs: &OutputFilenames) {
338 let cc = super::get_cc_prog(sess);
339 let assembly = outputs.temp_path(OutputTypeAssembly);
340 let object = outputs.path(OutputTypeObject);
342 // FIXME (#9639): This needs to handle non-utf8 paths
345 ~"-o", object.as_str().unwrap().to_owned(),
346 assembly.as_str().unwrap().to_owned()];
348 debug!("{} '{}'", cc, args.connect("' '"));
349 match Process::output(cc, args) {
351 if !prog.status.success() {
352 sess.err(format!("linking with `{}` failed: {}", cc, prog.status));
353 sess.note(format!("{} arguments: '{}'", cc, args.connect("' '")));
354 let mut note = prog.error.clone();
355 note.push_all(prog.output.as_slice());
356 sess.note(str::from_utf8(note.as_slice()).unwrap().to_owned());
357 sess.abort_if_errors();
361 sess.err(format!("could not exec the linker `{}`: {}", cc, e));
362 sess.abort_if_errors();
367 unsafe fn configure_llvm(sess: &Session) {
368 use sync::one::{Once, ONCE_INIT};
369 static mut INIT: Once = ONCE_INIT;
371 // Copy what clang does by turning on loop vectorization at O2 and
372 // slp vectorization at O3
373 let vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
374 (sess.opts.optimize == session::Default ||
375 sess.opts.optimize == session::Aggressive);
376 let vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
377 sess.opts.optimize == session::Aggressive;
379 let mut llvm_c_strs = Vec::new();
380 let mut llvm_args = Vec::new();
382 let add = |arg: &str| {
383 let s = arg.to_c_str();
384 llvm_args.push(s.with_ref(|p| p));
387 add("rustc"); // fake program name
388 if vectorize_loop { add("-vectorize-loops"); }
389 if vectorize_slp { add("-vectorize-slp"); }
390 if sess.time_llvm_passes() { add("-time-passes"); }
391 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
393 for arg in sess.opts.cg.llvm_args.iter() {
399 llvm::LLVMInitializePasses();
401 // Only initialize the platforms supported by Rust here, because
402 // using --llvm-root will have multiple platforms that rustllvm
403 // doesn't actually link to and it's pointless to put target info
404 // into the registry that Rust cannot generate machine code for.
405 llvm::LLVMInitializeX86TargetInfo();
406 llvm::LLVMInitializeX86Target();
407 llvm::LLVMInitializeX86TargetMC();
408 llvm::LLVMInitializeX86AsmPrinter();
409 llvm::LLVMInitializeX86AsmParser();
411 llvm::LLVMInitializeARMTargetInfo();
412 llvm::LLVMInitializeARMTarget();
413 llvm::LLVMInitializeARMTargetMC();
414 llvm::LLVMInitializeARMAsmPrinter();
415 llvm::LLVMInitializeARMAsmParser();
417 llvm::LLVMInitializeMipsTargetInfo();
418 llvm::LLVMInitializeMipsTarget();
419 llvm::LLVMInitializeMipsTargetMC();
420 llvm::LLVMInitializeMipsAsmPrinter();
421 llvm::LLVMInitializeMipsAsmParser();
423 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
428 unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
429 mpm: lib::llvm::PassManagerRef,
431 opt: lib::llvm::CodeGenOptLevel) {
432 // Create the PassManagerBuilder for LLVM. We configure it with
433 // reasonable defaults and prepare it to actually populate the pass
435 let builder = llvm::LLVMPassManagerBuilderCreate();
437 lib::llvm::CodeGenLevelNone => {
438 // Don't add lifetime intrinsics at O0
439 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
441 lib::llvm::CodeGenLevelLess => {
442 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
444 // numeric values copied from clang
445 lib::llvm::CodeGenLevelDefault => {
446 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
449 lib::llvm::CodeGenLevelAggressive => {
450 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
454 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
455 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
457 // Use the builder to populate the function/module pass managers.
458 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
459 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
460 llvm::LLVMPassManagerBuilderDispose(builder);
466 * Name mangling and its relationship to metadata. This is complex. Read
469 * The semantic model of Rust linkage is, broadly, that "there's no global
470 * namespace" between crates. Our aim is to preserve the illusion of this
471 * model despite the fact that it's not *quite* possible to implement on
472 * modern linkers. We initially didn't use system linkers at all, but have
473 * been convinced of their utility.
475 * There are a few issues to handle:
477 * - Linkers operate on a flat namespace, so we have to flatten names.
478 * We do this using the C++ namespace-mangling technique. Foo::bar
481 * - Symbols with the same name but different types need to get different
482 * linkage-names. We do this by hashing a string-encoding of the type into
483 * a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
484 * we use SHA256) to "prevent collisions". This is not airtight but 16 hex
485 * digits on uniform probability means you're going to need 2**32 same-name
486 * symbols in the same process before you're even hitting birthday-paradox
487 * collision probability.
489 * - Symbols in different crates but with same names "within" the crate need
490 * to get different linkage-names.
492 * - The hash shown in the filename needs to be predictable and stable for
493 * build tooling integration. It also needs to be using a hash function
494 * which is easy to use from Python, make, etc.
496 * So here is what we do:
498 * - Consider the package id; every crate has one (specified with crate_id
499 * attribute). If a package id isn't provided explicitly, we infer a
500 * versionless one from the output name. The version will end up being 0.0
501 * in this case. CNAME and CVERS are taken from this package id. For
502 * example, github.com/mozilla/CNAME#CVERS.
504 * - Define CMH as SHA256(crateid).
506 * - Define CMH8 as the first 8 characters of CMH.
508 * - Compile our crate to lib CNAME-CMH8-CVERS.so
510 * - Define STH(sym) as SHA256(CMH, type_str(sym))
512 * - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
513 * name, non-name metadata, and type sense, and versioned in the way
514 * system linkers understand.
517 pub fn find_crate_id(attrs: &[ast::Attribute], out_filestem: &str) -> CrateId {
518 match attr::find_crateid(attrs) {
519 None => from_str(out_filestem).unwrap(),
524 pub fn crate_id_hash(crate_id: &CrateId) -> ~str {
525 // This calculates CMH as defined above. Note that we don't use the path of
526 // the crate id in the hash because lookups are only done by (name/vers),
528 let mut s = Sha256::new();
529 s.input_str(crate_id.short_name_with_version());
530 truncated_hash_result(&mut s).slice_to(8).to_owned()
533 pub fn build_link_meta(krate: &ast::Crate, out_filestem: &str) -> LinkMeta {
535 crateid: find_crate_id(krate.attrs.as_slice(), out_filestem),
536 crate_hash: Svh::calculate(krate),
542 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
543 let output = symbol_hasher.result_bytes();
544 // 64 bits should be enough to avoid collisions.
545 output.slice_to(8).to_hex()
549 // This calculates STH for a symbol, as defined above
550 fn symbol_hash(tcx: &ty::ctxt,
551 symbol_hasher: &mut Sha256,
553 link_meta: &LinkMeta)
555 // NB: do *not* use abbrevs here as we want the symbol names
556 // to be independent of one another in the crate.
558 symbol_hasher.reset();
559 symbol_hasher.input_str(link_meta.crateid.name);
560 symbol_hasher.input_str("-");
561 symbol_hasher.input_str(link_meta.crate_hash.as_str());
562 symbol_hasher.input_str("-");
563 symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
564 // Prefix with 'h' so that it never blends into adjacent digits
565 let mut hash = StrBuf::from_str("h");
566 hash.push_str(truncated_hash_result(symbol_hasher));
570 fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> ~str {
571 match ccx.type_hashcodes.borrow().find(&t) {
572 Some(h) => return h.to_str(),
576 let mut symbol_hasher = ccx.symbol_hasher.borrow_mut();
577 let hash = symbol_hash(ccx.tcx(), &mut *symbol_hasher, t, &ccx.link_meta);
578 ccx.type_hashcodes.borrow_mut().insert(t, hash.clone());
583 // Name sanitation. LLVM will happily accept identifiers with weird names, but
585 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
586 pub fn sanitize(s: &str) -> ~str {
587 let mut result = StrBuf::new();
590 // Escape these with $ sequences
591 '@' => result.push_str("$SP$"),
592 '~' => result.push_str("$UP$"),
593 '*' => result.push_str("$RP$"),
594 '&' => result.push_str("$BP$"),
595 '<' => result.push_str("$LT$"),
596 '>' => result.push_str("$GT$"),
597 '(' => result.push_str("$LP$"),
598 ')' => result.push_str("$RP$"),
599 ',' => result.push_str("$C$"),
601 // '.' doesn't occur in types and functions, so reuse it
603 '-' | ':' => result.push_char('.'),
605 // These are legal symbols
609 | '_' | '.' | '$' => result.push_char(c),
612 let mut tstr = StrBuf::new();
613 char::escape_unicode(c, |c| tstr.push_char(c));
614 result.push_char('$');
615 result.push_str(tstr.as_slice().slice_from(1));
620 // Underscore-qualify anything that didn't start as an ident.
621 let result = result.into_owned();
622 if result.len() > 0u &&
623 result[0] != '_' as u8 &&
624 ! char::is_XID_start(result[0] as char) {
625 return ~"_" + result;
631 pub fn mangle<PI: Iterator<PathElem>>(mut path: PI,
633 vers: Option<&str>) -> ~str {
634 // Follow C++ namespace-mangling style, see
635 // http://en.wikipedia.org/wiki/Name_mangling for more info.
637 // It turns out that on OSX you can actually have arbitrary symbols in
638 // function names (at least when given to LLVM), but this is not possible
639 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
640 // we won't need to do this name mangling. The problem with name mangling is
641 // that it seriously limits the available characters. For example we can't
642 // have things like &T or ~[T] in symbol names when one would theoretically
643 // want them for things like impls of traits on that type.
645 // To be able to work on all platforms and get *some* reasonable output, we
646 // use C++ name-mangling.
648 let mut n = StrBuf::from_str("_ZN"); // _Z == Begin name-sequence, N == nested
650 fn push(n: &mut StrBuf, s: &str) {
651 let sani = sanitize(s);
652 n.push_str(format!("{}{}", sani.len(), sani));
655 // First, connect each component with <len, name> pairs.
657 push(&mut n, token::get_name(e.name()).get().as_slice())
661 Some(s) => push(&mut n, s),
665 Some(s) => push(&mut n, s),
669 n.push_char('E'); // End name-sequence.
673 pub fn exported_name(path: PathElems, hash: &str, vers: &str) -> ~str {
674 // The version will get mangled to have a leading '_', but it makes more
675 // sense to lead with a 'v' b/c this is a version...
676 let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
682 mangle(path, Some(hash), Some(vers.as_slice()))
685 pub fn mangle_exported_name(ccx: &CrateContext, path: PathElems,
686 t: ty::t, id: ast::NodeId) -> ~str {
687 let mut hash = StrBuf::from_owned_str(get_symbol_hash(ccx, t));
689 // Paths can be completely identical for different nodes,
690 // e.g. `fn foo() { { fn a() {} } { fn a() {} } }`, so we
691 // generate unique characters from the node id. For now
692 // hopefully 3 characters is enough to avoid collisions.
693 static EXTRA_CHARS: &'static str =
694 "abcdefghijklmnopqrstuvwxyz\
695 ABCDEFGHIJKLMNOPQRSTUVWXYZ\
698 let extra1 = id % EXTRA_CHARS.len();
699 let id = id / EXTRA_CHARS.len();
700 let extra2 = id % EXTRA_CHARS.len();
701 let id = id / EXTRA_CHARS.len();
702 let extra3 = id % EXTRA_CHARS.len();
703 hash.push_char(EXTRA_CHARS[extra1] as char);
704 hash.push_char(EXTRA_CHARS[extra2] as char);
705 hash.push_char(EXTRA_CHARS[extra3] as char);
709 ccx.link_meta.crateid.version_or_default())
712 pub fn mangle_internal_name_by_type_and_seq(ccx: &CrateContext,
714 name: &str) -> ~str {
715 let s = ppaux::ty_to_str(ccx.tcx(), t);
716 let path = [PathName(token::intern(s)),
718 let hash = get_symbol_hash(ccx, t);
719 mangle(ast_map::Values(path.iter()), Some(hash.as_slice()), None)
722 pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> ~str {
723 mangle(path.chain(Some(gensym_name(flav)).move_iter()), None, None)
726 pub fn output_lib_filename(id: &CrateId) -> ~str {
727 format!("{}-{}-{}", id.name, crate_id_hash(id), id.version_or_default())
730 pub fn get_cc_prog(sess: &Session) -> ~str {
731 match sess.opts.cg.linker {
732 Some(ref linker) => return linker.to_owned(),
736 // In the future, FreeBSD will use clang as default compiler.
737 // It would be flexible to use cc (system's default C compiler)
738 // instead of hard-coded gcc.
739 // For win32, there is no cc command, so we add a condition to make it use gcc.
740 match sess.targ_cfg.os {
741 abi::OsWin32 => return ~"gcc",
745 get_system_tool(sess, "cc")
748 pub fn get_ar_prog(sess: &Session) -> ~str {
749 match sess.opts.cg.ar {
750 Some(ref ar) => return ar.to_owned(),
754 get_system_tool(sess, "ar")
757 fn get_system_tool(sess: &Session, tool: &str) -> ~str {
758 match sess.targ_cfg.os {
759 abi::OsAndroid => match sess.opts.cg.android_cross_path {
761 let tool_str = match tool {
765 format!("{}/bin/arm-linux-androideabi-{}", *path, tool_str)
768 sess.fatal(format!("need Android NDK path for the '{}' tool \
769 (-C android-cross-path)", tool))
772 _ => tool.to_owned(),
776 fn remove(sess: &Session, path: &Path) {
777 match fs::unlink(path) {
780 sess.err(format!("failed to remove {}: {}", path.display(), e));
785 /// Perform the linkage portion of the compilation phase. This will generate all
786 /// of the requested outputs for this compilation session.
787 pub fn link_binary(sess: &Session,
788 trans: &CrateTranslation,
789 outputs: &OutputFilenames,
790 id: &CrateId) -> Vec<Path> {
791 let mut out_filenames = Vec::new();
792 for &crate_type in sess.crate_types.borrow().iter() {
793 let out_file = link_binary_output(sess, trans, crate_type, outputs, id);
794 out_filenames.push(out_file);
797 // Remove the temporary object file and metadata if we aren't saving temps
798 if !sess.opts.cg.save_temps {
799 let obj_filename = outputs.temp_path(OutputTypeObject);
800 if !sess.opts.output_types.contains(&OutputTypeObject) {
801 remove(sess, &obj_filename);
803 remove(sess, &obj_filename.with_extension("metadata.o"));
809 fn is_writeable(p: &Path) -> bool {
812 Ok(m) => m.perm & io::UserWrite == io::UserWrite
816 pub fn filename_for_input(sess: &Session, crate_type: session::CrateType,
817 id: &CrateId, out_filename: &Path) -> Path {
818 let libname = output_lib_filename(id);
820 session::CrateTypeRlib => {
821 out_filename.with_filename(format!("lib{}.rlib", libname))
823 session::CrateTypeDylib => {
824 let (prefix, suffix) = match sess.targ_cfg.os {
825 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
826 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
827 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
828 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
829 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
831 out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
833 session::CrateTypeStaticlib => {
834 out_filename.with_filename(format!("lib{}.a", libname))
836 session::CrateTypeExecutable => out_filename.clone(),
840 fn link_binary_output(sess: &Session,
841 trans: &CrateTranslation,
842 crate_type: session::CrateType,
843 outputs: &OutputFilenames,
844 id: &CrateId) -> Path {
845 let obj_filename = outputs.temp_path(OutputTypeObject);
846 let out_filename = match outputs.single_output_file {
847 Some(ref file) => file.clone(),
849 let out_filename = outputs.path(OutputTypeExe);
850 filename_for_input(sess, crate_type, id, &out_filename)
854 // Make sure the output and obj_filename are both writeable.
855 // Mac, FreeBSD, and Windows system linkers check this already --
856 // however, the Linux linker will happily overwrite a read-only file.
857 // We should be consistent.
858 let obj_is_writeable = is_writeable(&obj_filename);
859 let out_is_writeable = is_writeable(&out_filename);
860 if !out_is_writeable {
861 sess.fatal(format!("output file {} is not writeable -- check its permissions.",
862 out_filename.display()));
864 else if !obj_is_writeable {
865 sess.fatal(format!("object file {} is not writeable -- check its permissions.",
866 obj_filename.display()));
870 session::CrateTypeRlib => {
871 link_rlib(sess, Some(trans), &obj_filename, &out_filename);
873 session::CrateTypeStaticlib => {
874 link_staticlib(sess, &obj_filename, &out_filename);
876 session::CrateTypeExecutable => {
877 link_natively(sess, false, &obj_filename, &out_filename);
879 session::CrateTypeDylib => {
880 link_natively(sess, true, &obj_filename, &out_filename);
889 // An rlib in its current incarnation is essentially a renamed .a file. The
890 // rlib primarily contains the object file of the crate, but it also contains
891 // all of the object files from native libraries. This is done by unzipping
892 // native libraries and inserting all of the contents into this archive.
893 fn link_rlib<'a>(sess: &'a Session,
894 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
896 out_filename: &Path) -> Archive<'a> {
897 let mut a = Archive::create(sess, out_filename, obj_filename);
899 for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() {
901 cstore::NativeStatic => {
902 a.add_native_library(l.as_slice()).unwrap();
904 cstore::NativeFramework | cstore::NativeUnknown => {}
908 // Note that it is important that we add all of our non-object "magical
909 // files" *after* all of the object files in the archive. The reason for
910 // this is as follows:
912 // * When performing LTO, this archive will be modified to remove
913 // obj_filename from above. The reason for this is described below.
915 // * When the system linker looks at an archive, it will attempt to
916 // determine the architecture of the archive in order to see whether its
919 // The algorithm for this detection is: iterate over the files in the
920 // archive. Skip magical SYMDEF names. Interpret the first file as an
921 // object file. Read architecture from the object file.
923 // * As one can probably see, if "metadata" and "foo.bc" were placed
924 // before all of the objects, then the architecture of this archive would
925 // not be correctly inferred once 'foo.o' is removed.
927 // Basically, all this means is that this code should not move above the
931 // Instead of putting the metadata in an object file section, rlibs
932 // contain the metadata in a separate file. We use a temp directory
933 // here so concurrent builds in the same directory don't try to use
934 // the same filename for metadata (stomping over one another)
935 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
936 let metadata = tmpdir.path().join(METADATA_FILENAME);
937 match fs::File::create(&metadata).write(trans.metadata
941 sess.err(format!("failed to write {}: {}",
942 metadata.display(), e));
943 sess.abort_if_errors();
946 a.add_file(&metadata, false);
947 remove(sess, &metadata);
949 // For LTO purposes, the bytecode of this library is also inserted
951 let bc = obj_filename.with_extension("bc");
952 let bc_deflated = obj_filename.with_extension("bc.deflate");
953 match fs::File::open(&bc).read_to_end().and_then(|data| {
954 fs::File::create(&bc_deflated)
955 .write(match flate::deflate_bytes(data.as_slice()) {
956 Some(compressed) => compressed,
957 None => sess.fatal("failed to compress bytecode")
962 sess.err(format!("failed to write compressed bytecode: {}", e));
963 sess.abort_if_errors()
966 a.add_file(&bc_deflated, false);
967 remove(sess, &bc_deflated);
968 if !sess.opts.cg.save_temps &&
969 !sess.opts.output_types.contains(&OutputTypeBitcode) {
973 // After adding all files to the archive, we need to update the
974 // symbol table of the archive. This currently dies on OSX (see
975 // #11162), and isn't necessary there anyway
976 match sess.targ_cfg.os {
978 _ => { a.update_symbols(); }
987 // Create a static archive
989 // This is essentially the same thing as an rlib, but it also involves adding
990 // all of the upstream crates' objects into the archive. This will slurp in
991 // all of the native libraries of upstream dependencies as well.
993 // Additionally, there's no way for us to link dynamic libraries, so we warn
994 // about all dynamic library dependencies that they're not linked in.
996 // There's no need to include metadata in a static archive, so ensure to not
997 // link in the metadata object file (and also don't prepare the archive with a
999 fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) {
1000 let mut a = link_rlib(sess, None, obj_filename, out_filename);
1001 a.add_native_library("morestack").unwrap();
1002 a.add_native_library("compiler-rt").unwrap();
1004 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
1005 for &(cnum, ref path) in crates.iter() {
1006 let name = sess.cstore.get_crate_data(cnum).name.clone();
1007 let p = match *path {
1008 Some(ref p) => p.clone(), None => {
1009 sess.err(format!("could not find rlib for: `{}`", name));
1013 a.add_rlib(&p, name, sess.lto()).unwrap();
1014 let native_libs = csearch::get_native_libraries(&sess.cstore, cnum);
1015 for &(kind, ref lib) in native_libs.iter() {
1016 let name = match kind {
1017 cstore::NativeStatic => "static library",
1018 cstore::NativeUnknown => "library",
1019 cstore::NativeFramework => "framework",
1021 sess.warn(format!("unlinked native {}: {}", name, *lib));
1026 // Create a dynamic library or executable
1028 // This will invoke the system linker/cc to create the resulting file. This
1029 // links to all upstream files as well.
1030 fn link_natively(sess: &Session, dylib: bool, obj_filename: &Path,
1031 out_filename: &Path) {
1032 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
1033 // The invocations of cc share some flags across platforms
1034 let cc_prog = get_cc_prog(sess);
1035 let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
1036 cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
1037 obj_filename, out_filename));
1038 if (sess.opts.debugging_opts & session::PRINT_LINK_ARGS) != 0 {
1039 println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
1042 // May have not found libraries in the right formats.
1043 sess.abort_if_errors();
1045 // Invoke the system linker
1046 debug!("{} {}", cc_prog, cc_args.connect(" "));
1047 let prog = time(sess.time_passes(), "running linker", (), |()|
1048 Process::output(cc_prog, cc_args.as_slice()));
1051 if !prog.status.success() {
1052 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
1053 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
1054 let mut output = prog.error.clone();
1055 output.push_all(prog.output.as_slice());
1056 sess.note(str::from_utf8(output.as_slice()).unwrap().to_owned());
1057 sess.abort_if_errors();
1061 sess.err(format!("could not exec the linker `{}`: {}", cc_prog, e));
1062 sess.abort_if_errors();
1067 // On OSX, debuggers need this utility to get run to do some munging of
1069 if sess.targ_cfg.os == abi::OsMacos && (sess.opts.debuginfo != NoDebugInfo) {
1070 // FIXME (#9639): This needs to handle non-utf8 paths
1071 match Process::status("dsymutil",
1072 [out_filename.as_str().unwrap().to_owned()]) {
1075 sess.err(format!("failed to run dsymutil: {}", e));
1076 sess.abort_if_errors();
1082 fn link_args(sess: &Session,
1085 obj_filename: &Path,
1086 out_filename: &Path) -> Vec<~str> {
1088 // The default library location, we need this to find the runtime.
1089 // The location of crates will be determined as needed.
1090 // FIXME (#9639): This needs to handle non-utf8 paths
1091 let lib_path = sess.filesearch().get_target_lib_path();
1092 let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
1094 let mut args = vec!(stage);
1096 // FIXME (#9639): This needs to handle non-utf8 paths
1098 ~"-o", out_filename.as_str().unwrap().to_owned(),
1099 obj_filename.as_str().unwrap().to_owned()]);
1101 // Stack growth requires statically linking a __morestack function. Note
1102 // that this is listed *before* all other libraries, even though it may be
1103 // used to resolve symbols in other libraries. The only case that this
1104 // wouldn't be pulled in by the object file is if the object file had no
1107 // If we're building an executable, there must be at least one function (the
1108 // main function), and if we're building a dylib then we don't need it for
1109 // later libraries because they're all dylibs (not rlibs).
1111 // I'm honestly not entirely sure why this needs to come first. Apparently
1112 // the --as-needed flag above sometimes strips out libstd from the command
1113 // line, but inserting this farther to the left makes the
1114 // "rust_stack_exhausted" symbol an outstanding undefined symbol, which
1115 // flags libstd as a required library (or whatever provides the symbol).
1116 args.push(~"-lmorestack");
1118 // When linking a dynamic library, we put the metadata into a section of the
1119 // executable. This metadata is in a separate object file from the main
1120 // object file, so we link that in here.
1122 let metadata = obj_filename.with_extension("metadata.o");
1123 args.push(metadata.as_str().unwrap().to_owned());
1126 // We want to prevent the compiler from accidentally leaking in any system
1127 // libraries, so we explicitly ask gcc to not link to any libraries by
1128 // default. Note that this does not happen for windows because windows pulls
1129 // in some large number of libraries and I couldn't quite figure out which
1130 // subset we wanted.
1132 // FIXME(#11937) we should invoke the system linker directly
1133 if sess.targ_cfg.os != abi::OsWin32 {
1134 args.push(~"-nodefaultlibs");
1137 if sess.targ_cfg.os == abi::OsLinux {
1138 // GNU-style linkers will use this to omit linking to libraries which
1139 // don't actually fulfill any relocations, but only for libraries which
1140 // follow this flag. Thus, use it before specifying libraries to link to.
1141 args.push(~"-Wl,--as-needed");
1143 // GNU-style linkers support optimization with -O. --gc-sections
1144 // removes metadata and potentially other useful things, so don't
1145 // include it. GNU ld doesn't need a numeric argument, but other linkers
1147 if sess.opts.optimize == session::Default ||
1148 sess.opts.optimize == session::Aggressive {
1149 args.push(~"-Wl,-O1");
1153 if sess.targ_cfg.os == abi::OsWin32 {
1154 // Make sure that we link to the dynamic libgcc, otherwise cross-module
1155 // DWARF stack unwinding will not work.
1156 // This behavior may be overridden by --link-args "-static-libgcc"
1157 args.push(~"-shared-libgcc");
1159 // And here, we see obscure linker flags #45. On windows, it has been
1160 // found to be necessary to have this flag to compile liblibc.
1162 // First a bit of background. On Windows, the file format is not ELF,
1163 // but COFF (at least according to LLVM). COFF doesn't officially allow
1164 // for section names over 8 characters, apparently. Our metadata
1165 // section, ".note.rustc", you'll note is over 8 characters.
1167 // On more recent versions of gcc on mingw, apparently the section name
1168 // is *not* truncated, but rather stored elsewhere in a separate lookup
1169 // table. On older versions of gcc, they apparently always truncated the
1170 // section names (at least in some cases). Truncating the section name
1171 // actually creates "invalid" objects [1] [2], but only for some
1172 // introspection tools, not in terms of whether it can be loaded.
1174 // Long story shory, passing this flag forces the linker to *not*
1175 // truncate section names (so we can find the metadata section after
1176 // it's compiled). The real kicker is that rust compiled just fine on
1177 // windows for quite a long time *without* this flag, so I have no idea
1178 // why it suddenly started failing for liblibc. Regardless, we
1179 // definitely don't want section name truncation, so we're keeping this
1180 // flag for windows.
1182 // [1] - https://sourceware.org/bugzilla/show_bug.cgi?id=13130
1183 // [2] - https://code.google.com/p/go/issues/detail?id=2139
1184 args.push(~"-Wl,--enable-long-section-names");
1187 if sess.targ_cfg.os == abi::OsAndroid {
1188 // Many of the symbols defined in compiler-rt are also defined in libgcc.
1189 // Android linker doesn't like that by default.
1190 args.push(~"-Wl,--allow-multiple-definition");
1193 // Take careful note of the ordering of the arguments we pass to the linker
1194 // here. Linkers will assume that things on the left depend on things to the
1195 // right. Things on the right cannot depend on things on the left. This is
1196 // all formally implemented in terms of resolving symbols (libs on the right
1197 // resolve unknown symbols of libs on the left, but not vice versa).
1199 // For this reason, we have organized the arguments we pass to the linker as
1202 // 1. The local object that LLVM just generated
1203 // 2. Upstream rust libraries
1204 // 3. Local native libraries
1205 // 4. Upstream native libraries
1207 // This is generally fairly natural, but some may expect 2 and 3 to be
1208 // swapped. The reason that all native libraries are put last is that it's
1209 // not recommended for a native library to depend on a symbol from a rust
1210 // crate. If this is the case then a staticlib crate is recommended, solving
1213 // Additionally, it is occasionally the case that upstream rust libraries
1214 // depend on a local native library. In the case of libraries such as
1215 // lua/glfw/etc the name of the library isn't the same across all platforms,
1216 // so only the consumer crate of a library knows the actual name. This means
1217 // that downstream crates will provide the #[link] attribute which upstream
1218 // crates will depend on. Hence local native libraries are after out
1219 // upstream rust crates.
1221 // In theory this means that a symbol in an upstream native library will be
1222 // shadowed by a local native library when it wouldn't have been before, but
1223 // this kind of behavior is pretty platform specific and generally not
1224 // recommended anyway, so I don't think we're shooting ourself in the foot
1226 add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1227 add_local_native_libraries(&mut args, sess);
1228 add_upstream_native_libraries(&mut args, sess);
1230 // # Telling the linker what we're doing
1233 // On mac we need to tell the linker to let this library be rpathed
1234 if sess.targ_cfg.os == abi::OsMacos {
1235 args.push(~"-dynamiclib");
1236 args.push(~"-Wl,-dylib");
1237 // FIXME (#9639): This needs to handle non-utf8 paths
1238 if !sess.opts.cg.no_rpath {
1239 args.push(~"-Wl,-install_name,@rpath/" +
1240 out_filename.filename_str().unwrap());
1243 args.push(~"-shared")
1247 if sess.targ_cfg.os == abi::OsFreebsd {
1248 args.push_all([~"-L/usr/local/lib",
1249 ~"-L/usr/local/lib/gcc46",
1250 ~"-L/usr/local/lib/gcc44"]);
1253 // FIXME (#2397): At some point we want to rpath our guesses as to
1254 // where extern libraries might live, based on the
1255 // addl_lib_search_paths
1256 if !sess.opts.cg.no_rpath {
1257 args.push_all(rpath::get_rpath_flags(sess, out_filename).as_slice());
1260 // compiler-rt contains implementations of low-level LLVM helpers. This is
1261 // used to resolve symbols from the object file we just created, as well as
1262 // any system static libraries that may be expecting gcc instead. Most
1263 // symbols in libgcc also appear in compiler-rt.
1265 // This is the end of the command line, so this library is used to resolve
1266 // *all* undefined symbols in all other libraries, and this is intentional.
1267 args.push(~"-lcompiler-rt");
1269 // Finally add all the linker arguments provided on the command line along
1270 // with any #[link_args] attributes found inside the crate
1271 args.push_all(sess.opts.cg.link_args.as_slice());
1272 for arg in sess.cstore.get_used_link_args().borrow().iter() {
1273 args.push(arg.clone());
1278 // # Native library linking
1280 // User-supplied library search paths (-L on the command line). These are
1281 // the same paths used to find Rust crates, so some of them may have been
1282 // added already by the previous crate linking code. This only allows them
1283 // to be found at compile time so it is still entirely up to outside
1284 // forces to make sure that library can be found at runtime.
1286 // Also note that the native libraries linked here are only the ones located
1287 // in the current crate. Upstream crates with native library dependencies
1288 // may have their native library pulled in above.
1289 fn add_local_native_libraries(args: &mut Vec<~str>, sess: &Session) {
1290 for path in sess.opts.addl_lib_search_paths.borrow().iter() {
1291 // FIXME (#9639): This needs to handle non-utf8 paths
1292 args.push("-L" + path.as_str().unwrap().to_owned());
1295 let rustpath = filesearch::rust_path();
1296 for path in rustpath.iter() {
1297 // FIXME (#9639): This needs to handle non-utf8 paths
1298 args.push("-L" + path.as_str().unwrap().to_owned());
1301 for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() {
1303 cstore::NativeUnknown | cstore::NativeStatic => {
1304 args.push("-l" + *l);
1306 cstore::NativeFramework => {
1307 args.push(~"-framework");
1308 args.push(l.to_owned());
1314 // # Rust Crate linking
1316 // Rust crates are not considered at all when creating an rlib output. All
1317 // dependencies will be linked when producing the final output (instead of
1318 // the intermediate rlib version)
1319 fn add_upstream_rust_crates(args: &mut Vec<~str>, sess: &Session,
1320 dylib: bool, tmpdir: &Path) {
1322 // As a limitation of the current implementation, we require that everything
1323 // must be static or everything must be dynamic. The reasons for this are a
1324 // little subtle, but as with staticlibs and rlibs, the goal is to prevent
1325 // duplicate copies of the same library showing up. For example, a static
1326 // immediate dependency might show up as an upstream dynamic dependency and
1327 // we currently have no way of knowing that. We know that all dynamic
1328 // libraries require dynamic dependencies (see above), so it's satisfactory
1329 // to include either all static libraries or all dynamic libraries.
1331 // With this limitation, we expose a compiler default linkage type and an
1332 // option to reverse that preference. The current behavior looks like:
1334 // * If a dylib is being created, upstream dependencies must be dylibs
1335 // * If nothing else is specified, static linking is preferred
1336 // * If the -C prefer-dynamic flag is given, dynamic linking is preferred
1337 // * If one form of linking fails, the second is also attempted
1338 // * If both forms fail, then we emit an error message
1340 let dynamic = get_deps(&sess.cstore, cstore::RequireDynamic);
1341 let statik = get_deps(&sess.cstore, cstore::RequireStatic);
1342 match (dynamic, statik, sess.opts.cg.prefer_dynamic, dylib) {
1343 (_, Some(deps), false, false) => {
1344 add_static_crates(args, sess, tmpdir, deps)
1347 (None, Some(deps), true, false) => {
1348 // If you opted in to dynamic linking and we decided to emit a
1349 // static output, you should probably be notified of such an event!
1350 sess.warn("dynamic linking was preferred, but dependencies \
1351 could not all be found in an dylib format.");
1352 sess.warn("linking statically instead, using rlibs");
1353 add_static_crates(args, sess, tmpdir, deps)
1356 (Some(deps), _, _, _) => add_dynamic_crates(args, sess, deps),
1358 (None, _, _, true) => {
1359 sess.err("dylib output requested, but some depenencies could not \
1360 be found in the dylib format");
1361 let deps = sess.cstore.get_used_crates(cstore::RequireDynamic);
1362 for (cnum, path) in deps.move_iter() {
1363 if path.is_some() { continue }
1364 let name = sess.cstore.get_crate_data(cnum).name.clone();
1365 sess.note(format!("dylib not found: {}", name));
1369 (None, None, pref, false) => {
1370 let (pref, name) = if pref {
1371 sess.err("dynamic linking is preferred, but dependencies were \
1372 not found in either dylib or rlib format");
1373 (cstore::RequireDynamic, "dylib")
1375 sess.err("dependencies were not all found in either dylib or \
1377 (cstore::RequireStatic, "rlib")
1379 sess.note(format!("dependencies not found in the `{}` format",
1381 for (cnum, path) in sess.cstore.get_used_crates(pref).move_iter() {
1382 if path.is_some() { continue }
1383 let name = sess.cstore.get_crate_data(cnum).name.clone();
1389 // Converts a library file-stem into a cc -l argument
1390 fn unlib(config: &session::Config, stem: &str) -> ~str {
1391 if stem.starts_with("lib") && config.os != abi::OsWin32 {
1392 stem.slice(3, stem.len()).to_owned()
1398 // Attempts to find all dependencies with a certain linkage preference,
1399 // returning `None` if not all libraries could be found with that
1401 fn get_deps(cstore: &cstore::CStore, preference: cstore::LinkagePreference)
1402 -> Option<Vec<(ast::CrateNum, Path)> >
1404 let crates = cstore.get_used_crates(preference);
1405 if crates.iter().all(|&(_, ref p)| p.is_some()) {
1406 Some(crates.move_iter().map(|(a, b)| (a, b.unwrap())).collect())
1412 // Adds the static "rlib" versions of all crates to the command line.
1413 fn add_static_crates(args: &mut Vec<~str>, sess: &Session, tmpdir: &Path,
1414 crates: Vec<(ast::CrateNum, Path)>) {
1415 for (cnum, cratepath) in crates.move_iter() {
1416 // When performing LTO on an executable output, all of the
1417 // bytecode from the upstream libraries has already been
1418 // included in our object file output. We need to modify all of
1419 // the upstream archives to remove their corresponding object
1420 // file to make sure we don't pull the same code in twice.
1422 // We must continue to link to the upstream archives to be sure
1423 // to pull in native static dependencies. As the final caveat,
1424 // on linux it is apparently illegal to link to a blank archive,
1425 // so if an archive no longer has any object files in it after
1426 // we remove `lib.o`, then don't link against it at all.
1428 // If we're not doing LTO, then our job is simply to just link
1429 // against the archive.
1431 let name = sess.cstore.get_crate_data(cnum).name.clone();
1432 time(sess.time_passes(), format!("altering {}.rlib", name),
1434 let dst = tmpdir.join(cratepath.filename().unwrap());
1435 match fs::copy(&cratepath, &dst) {
1438 sess.err(format!("failed to copy {} to {}: {}",
1439 cratepath.display(),
1442 sess.abort_if_errors();
1445 let dst_str = dst.as_str().unwrap().to_owned();
1446 let mut archive = Archive::open(sess, dst);
1447 archive.remove_file(format!("{}.o", name));
1448 let files = archive.files();
1449 if files.iter().any(|s| s.ends_with(".o")) {
1454 args.push(cratepath.as_str().unwrap().to_owned());
1459 // Same thing as above, but for dynamic crates instead of static crates.
1460 fn add_dynamic_crates(args: &mut Vec<~str>, sess: &Session,
1461 crates: Vec<(ast::CrateNum, Path)> ) {
1462 // If we're performing LTO, then it should have been previously required
1463 // that all upstream rust dependencies were available in an rlib format.
1464 assert!(!sess.lto());
1466 for (_, cratepath) in crates.move_iter() {
1467 // Just need to tell the linker about where the library lives and
1469 let dir = cratepath.dirname_str().unwrap();
1470 if !dir.is_empty() { args.push("-L" + dir); }
1471 let libarg = unlib(&sess.targ_cfg, cratepath.filestem_str().unwrap());
1472 args.push("-l" + libarg);
1477 // Link in all of our upstream crates' native dependencies. Remember that
1478 // all of these upstream native depenencies are all non-static
1479 // dependencies. We've got two cases then:
1481 // 1. The upstream crate is an rlib. In this case we *must* link in the
1482 // native dependency because the rlib is just an archive.
1484 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1485 // have the dependency present on the system somewhere. Thus, we don't
1486 // gain a whole lot from not linking in the dynamic dependency to this
1489 // The use case for this is a little subtle. In theory the native
1490 // dependencies of a crate a purely an implementation detail of the crate
1491 // itself, but the problem arises with generic and inlined functions. If a
1492 // generic function calls a native function, then the generic function must
1493 // be instantiated in the target crate, meaning that the native symbol must
1494 // also be resolved in the target crate.
1495 fn add_upstream_native_libraries(args: &mut Vec<~str>, sess: &Session) {
1496 let cstore = &sess.cstore;
1497 cstore.iter_crate_data(|cnum, _| {
1498 let libs = csearch::get_native_libraries(cstore, cnum);
1499 for &(kind, ref lib) in libs.iter() {
1501 cstore::NativeUnknown => args.push("-l" + *lib),
1502 cstore::NativeFramework => {
1503 args.push(~"-framework");
1504 args.push(lib.to_owned());
1506 cstore::NativeStatic => {
1507 sess.bug("statics shouldn't be propagated");