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::os::consts::{macos, freebsd, linux, android, win32};
38 use serialize::hex::ToHex;
39 use extra::tempfile::TempDir;
42 use syntax::ast_map::{PathElem, PathElems, PathName};
45 use syntax::attr::AttrMetaMethods;
46 use syntax::crateid::CrateId;
47 use syntax::parse::token;
49 #[deriving(Clone, Eq, Ord, TotalOrd, TotalEq)]
53 OutputTypeLlvmAssembly,
58 pub fn llvm_err(sess: Session, msg: ~str) -> ! {
60 let cstr = llvm::LLVMRustGetLastError();
61 if cstr == ptr::null() {
64 let err = CString::new(cstr, false);
65 let err = str::from_utf8_lossy(err.as_bytes());
66 sess.fatal(msg + ": " + err.as_slice());
71 pub fn WriteOutputFile(
73 target: lib::llvm::TargetMachineRef,
74 pm: lib::llvm::PassManagerRef,
77 file_type: lib::llvm::FileType) {
79 output.with_c_str(|output| {
80 let result = llvm::LLVMRustWriteOutputFile(
81 target, pm, m, output, file_type);
83 llvm_err(sess, ~"could not write output");
92 use back::link::{WriteOutputFile, OutputType};
93 use back::link::{OutputTypeAssembly, OutputTypeBitcode};
94 use back::link::{OutputTypeExe, OutputTypeLlvmAssembly};
95 use back::link::{OutputTypeObject};
96 use driver::driver::{CrateTranslation, OutputFilenames};
97 use driver::session::{NoDebugInfo, Session};
100 use lib::llvm::{ModuleRef, TargetMachineRef, PassManagerRef};
102 use util::common::time;
105 use std::c_str::ToCStr;
106 use std::io::Process;
107 use std::libc::{c_uint, c_int};
110 // On android, we by default compile for armv7 processors. This enables
111 // things like double word CAS instructions (rather than emulating them)
112 // which are *far* more efficient. This is obviously undesirable in some
113 // cases, so if any sort of target feature is specified we don't append v7
114 // to the feature list.
115 fn target_feature<'a>(sess: &'a Session) -> &'a str {
116 match sess.targ_cfg.os {
118 if "" == sess.opts.cg.target_feature {
121 sess.opts.cg.target_feature.as_slice()
124 _ => sess.opts.cg.target_feature.as_slice()
128 pub fn run_passes(sess: Session,
129 trans: &CrateTranslation,
130 output_types: &[OutputType],
131 output: &OutputFilenames) {
132 let llmod = trans.module;
133 let llcx = trans.context;
135 configure_llvm(sess);
137 if sess.opts.cg.save_temps {
138 output.with_extension("no-opt.bc").with_c_str(|buf| {
139 llvm::LLVMWriteBitcodeToFile(llmod, buf);
143 let opt_level = match sess.opts.optimize {
144 session::No => lib::llvm::CodeGenLevelNone,
145 session::Less => lib::llvm::CodeGenLevelLess,
146 session::Default => lib::llvm::CodeGenLevelDefault,
147 session::Aggressive => lib::llvm::CodeGenLevelAggressive,
149 let use_softfp = sess.opts.cg.soft_float;
151 // FIXME: #11906: Omitting frame pointers breaks retrieving the value of a parameter.
152 // FIXME: #11954: mac64 unwinding may not work with fp elim
153 let no_fp_elim = (sess.opts.debuginfo != NoDebugInfo) ||
154 (sess.targ_cfg.os == abi::OsMacos &&
155 sess.targ_cfg.arch == abi::X86_64);
157 let tm = sess.targ_cfg.target_strs.target_triple.with_c_str(|t| {
158 sess.opts.cg.target_cpu.with_c_str(|cpu| {
159 target_feature(&sess).with_c_str(|features| {
160 llvm::LLVMRustCreateTargetMachine(
162 lib::llvm::CodeModelDefault,
173 // Create the two optimizing pass managers. These mirror what clang
174 // does, and are by populated by LLVM's default PassManagerBuilder.
175 // Each manager has a different set of passes, but they also share
176 // some common passes.
177 let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
178 let mpm = llvm::LLVMCreatePassManager();
180 // If we're verifying or linting, add them to the function pass
182 let addpass = |pass: &str| {
183 pass.with_c_str(|s| llvm::LLVMRustAddPass(fpm, s))
185 if !sess.no_verify() { assert!(addpass("verify")); }
187 if !sess.opts.cg.no_prepopulate_passes {
188 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
189 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
190 populate_llvm_passes(fpm, mpm, llmod, opt_level);
193 for pass in sess.opts.cg.passes.iter() {
194 pass.with_c_str(|s| {
195 if !llvm::LLVMRustAddPass(mpm, s) {
196 sess.warn(format!("unknown pass {}, ignoring", *pass));
201 // Finally, run the actual optimization passes
202 time(sess.time_passes(), "llvm function passes", (), |()|
203 llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
204 time(sess.time_passes(), "llvm module passes", (), |()|
205 llvm::LLVMRunPassManager(mpm, llmod));
207 // Deallocate managers that we're now done with
208 llvm::LLVMDisposePassManager(fpm);
209 llvm::LLVMDisposePassManager(mpm);
211 // Emit the bytecode if we're either saving our temporaries or
212 // emitting an rlib. Whenever an rlib is created, the bytecode is
213 // inserted into the archive in order to allow LTO against it.
214 let crate_types = sess.crate_types.borrow();
215 if sess.opts.cg.save_temps ||
216 (crate_types.get().contains(&session::CrateTypeRlib) &&
217 sess.opts.output_types.contains(&OutputTypeExe)) {
218 output.temp_path(OutputTypeBitcode).with_c_str(|buf| {
219 llvm::LLVMWriteBitcodeToFile(llmod, buf);
224 time(sess.time_passes(), "all lto passes", (), |()|
225 lto::run(sess, llmod, tm, trans.reachable));
227 if sess.opts.cg.save_temps {
228 output.with_extension("lto.bc").with_c_str(|buf| {
229 llvm::LLVMWriteBitcodeToFile(llmod, buf);
234 // A codegen-specific pass manager is used to generate object
235 // files for an LLVM module.
237 // Apparently each of these pass managers is a one-shot kind of
238 // thing, so we create a new one for each type of output. The
239 // pass manager passed to the closure should be ensured to not
240 // escape the closure itself, and the manager should only be
242 fn with_codegen(tm: TargetMachineRef, llmod: ModuleRef,
243 f: |PassManagerRef|) {
245 let cpm = llvm::LLVMCreatePassManager();
246 llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
247 llvm::LLVMRustAddLibraryInfo(cpm, llmod);
249 llvm::LLVMDisposePassManager(cpm);
253 let mut object_file = None;
254 let mut needs_metadata = false;
255 for output_type in output_types.iter() {
256 let path = output.path(*output_type);
258 OutputTypeBitcode => {
259 path.with_c_str(|buf| {
260 llvm::LLVMWriteBitcodeToFile(llmod, buf);
263 OutputTypeLlvmAssembly => {
264 path.with_c_str(|output| {
265 with_codegen(tm, llmod, |cpm| {
266 llvm::LLVMRustPrintModule(cpm, llmod, output);
270 OutputTypeAssembly => {
271 // If we're not using the LLVM assembler, this function
272 // could be invoked specially with output_type_assembly,
273 // so in this case we still want the metadata object
275 let ty = OutputTypeAssembly;
276 let path = if sess.opts.output_types.contains(&ty) {
279 needs_metadata = true;
280 output.temp_path(OutputTypeAssembly)
282 with_codegen(tm, llmod, |cpm| {
283 WriteOutputFile(sess, tm, cpm, llmod, &path,
284 lib::llvm::AssemblyFile);
287 OutputTypeObject => {
288 object_file = Some(path);
291 object_file = Some(output.temp_path(OutputTypeObject));
292 needs_metadata = true;
297 time(sess.time_passes(), "codegen passes", (), |()| {
300 with_codegen(tm, llmod, |cpm| {
301 WriteOutputFile(sess, tm, cpm, llmod, path,
302 lib::llvm::ObjectFile);
308 with_codegen(tm, trans.metadata_module, |cpm| {
309 let out = output.temp_path(OutputTypeObject)
310 .with_extension("metadata.o");
311 WriteOutputFile(sess, tm, cpm,
312 trans.metadata_module, &out,
313 lib::llvm::ObjectFile);
318 llvm::LLVMRustDisposeTargetMachine(tm);
319 llvm::LLVMDisposeModule(trans.metadata_module);
320 llvm::LLVMDisposeModule(llmod);
321 llvm::LLVMContextDispose(llcx);
322 if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
326 pub fn run_assembler(sess: Session, outputs: &OutputFilenames) {
327 let cc = super::get_cc_prog(sess);
328 let assembly = outputs.temp_path(OutputTypeAssembly);
329 let object = outputs.path(OutputTypeObject);
331 // FIXME (#9639): This needs to handle non-utf8 paths
334 ~"-o", object.as_str().unwrap().to_owned(),
335 assembly.as_str().unwrap().to_owned()];
337 debug!("{} '{}'", cc, args.connect("' '"));
338 match Process::output(cc, args) {
340 if !prog.status.success() {
341 sess.err(format!("linking with `{}` failed: {}", cc, prog.status));
342 sess.note(format!("{} arguments: '{}'", cc, args.connect("' '")));
343 sess.note(str::from_utf8_owned(prog.error + prog.output).unwrap());
344 sess.abort_if_errors();
348 sess.err(format!("could not exec the linker `{}`: {}", cc, e));
349 sess.abort_if_errors();
354 unsafe fn configure_llvm(sess: Session) {
355 use sync::one::{Once, ONCE_INIT};
356 static mut INIT: Once = ONCE_INIT;
358 // Copy what clang does by turning on loop vectorization at O2 and
359 // slp vectorization at O3
360 let vectorize_loop = !sess.opts.cg.no_vectorize_loops &&
361 (sess.opts.optimize == session::Default ||
362 sess.opts.optimize == session::Aggressive);
363 let vectorize_slp = !sess.opts.cg.no_vectorize_slp &&
364 sess.opts.optimize == session::Aggressive;
366 let mut llvm_c_strs = Vec::new();
367 let mut llvm_args = Vec::new();
369 let add = |arg: &str| {
370 let s = arg.to_c_str();
371 llvm_args.push(s.with_ref(|p| p));
374 add("rustc"); // fake program name
375 if vectorize_loop { add("-vectorize-loops"); }
376 if vectorize_slp { add("-vectorize-slp"); }
377 if sess.time_llvm_passes() { add("-time-passes"); }
378 if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
380 for arg in sess.opts.cg.llvm_args.iter() {
386 llvm::LLVMInitializePasses();
388 // Only initialize the platforms supported by Rust here, because
389 // using --llvm-root will have multiple platforms that rustllvm
390 // doesn't actually link to and it's pointless to put target info
391 // into the registry that Rust cannot generate machine code for.
392 llvm::LLVMInitializeX86TargetInfo();
393 llvm::LLVMInitializeX86Target();
394 llvm::LLVMInitializeX86TargetMC();
395 llvm::LLVMInitializeX86AsmPrinter();
396 llvm::LLVMInitializeX86AsmParser();
398 llvm::LLVMInitializeARMTargetInfo();
399 llvm::LLVMInitializeARMTarget();
400 llvm::LLVMInitializeARMTargetMC();
401 llvm::LLVMInitializeARMAsmPrinter();
402 llvm::LLVMInitializeARMAsmParser();
404 llvm::LLVMInitializeMipsTargetInfo();
405 llvm::LLVMInitializeMipsTarget();
406 llvm::LLVMInitializeMipsTargetMC();
407 llvm::LLVMInitializeMipsAsmPrinter();
408 llvm::LLVMInitializeMipsAsmParser();
410 llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
415 unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
416 mpm: lib::llvm::PassManagerRef,
418 opt: lib::llvm::CodeGenOptLevel) {
419 // Create the PassManagerBuilder for LLVM. We configure it with
420 // reasonable defaults and prepare it to actually populate the pass
422 let builder = llvm::LLVMPassManagerBuilderCreate();
424 lib::llvm::CodeGenLevelNone => {
425 // Don't add lifetime intrinsics at O0
426 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
428 lib::llvm::CodeGenLevelLess => {
429 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
431 // numeric values copied from clang
432 lib::llvm::CodeGenLevelDefault => {
433 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
436 lib::llvm::CodeGenLevelAggressive => {
437 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
441 llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
442 llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
444 // Use the builder to populate the function/module pass managers.
445 llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
446 llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
447 llvm::LLVMPassManagerBuilderDispose(builder);
453 * Name mangling and its relationship to metadata. This is complex. Read
456 * The semantic model of Rust linkage is, broadly, that "there's no global
457 * namespace" between crates. Our aim is to preserve the illusion of this
458 * model despite the fact that it's not *quite* possible to implement on
459 * modern linkers. We initially didn't use system linkers at all, but have
460 * been convinced of their utility.
462 * There are a few issues to handle:
464 * - Linkers operate on a flat namespace, so we have to flatten names.
465 * We do this using the C++ namespace-mangling technique. Foo::bar
468 * - Symbols with the same name but different types need to get different
469 * linkage-names. We do this by hashing a string-encoding of the type into
470 * a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
471 * we use SHA256) to "prevent collisions". This is not airtight but 16 hex
472 * digits on uniform probability means you're going to need 2**32 same-name
473 * symbols in the same process before you're even hitting birthday-paradox
474 * collision probability.
476 * - Symbols in different crates but with same names "within" the crate need
477 * to get different linkage-names.
479 * - The hash shown in the filename needs to be predictable and stable for
480 * build tooling integration. It also needs to be using a hash function
481 * which is easy to use from Python, make, etc.
483 * So here is what we do:
485 * - Consider the package id; every crate has one (specified with crate_id
486 * attribute). If a package id isn't provided explicitly, we infer a
487 * versionless one from the output name. The version will end up being 0.0
488 * in this case. CNAME and CVERS are taken from this package id. For
489 * example, github.com/mozilla/CNAME#CVERS.
491 * - Define CMH as SHA256(crateid).
493 * - Define CMH8 as the first 8 characters of CMH.
495 * - Compile our crate to lib CNAME-CMH8-CVERS.so
497 * - Define STH(sym) as SHA256(CMH, type_str(sym))
499 * - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
500 * name, non-name metadata, and type sense, and versioned in the way
501 * system linkers understand.
504 pub fn find_crate_id(attrs: &[ast::Attribute],
505 output: &OutputFilenames) -> CrateId {
506 match attr::find_crateid(attrs) {
507 None => from_str(output.out_filestem).unwrap(),
512 pub fn crate_id_hash(crate_id: &CrateId) -> ~str {
513 // This calculates CMH as defined above. Note that we don't use the path of
514 // the crate id in the hash because lookups are only done by (name/vers),
516 let mut s = Sha256::new();
517 s.input_str(crate_id.short_name_with_version());
518 truncated_hash_result(&mut s).slice_to(8).to_owned()
521 pub fn build_link_meta(krate: &ast::Crate,
522 output: &OutputFilenames) -> LinkMeta {
524 crateid: find_crate_id(krate.attrs.as_slice(), output),
525 crate_hash: Svh::calculate(krate),
531 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
532 let output = symbol_hasher.result_bytes();
533 // 64 bits should be enough to avoid collisions.
534 output.slice_to(8).to_hex()
538 // This calculates STH for a symbol, as defined above
539 fn symbol_hash(tcx: ty::ctxt, symbol_hasher: &mut Sha256,
540 t: ty::t, link_meta: &LinkMeta) -> ~str {
541 // NB: do *not* use abbrevs here as we want the symbol names
542 // to be independent of one another in the crate.
544 symbol_hasher.reset();
545 symbol_hasher.input_str(link_meta.crateid.name);
546 symbol_hasher.input_str("-");
547 symbol_hasher.input_str(link_meta.crate_hash.as_str());
548 symbol_hasher.input_str("-");
549 symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
550 let mut hash = truncated_hash_result(symbol_hasher);
551 // Prefix with 'h' so that it never blends into adjacent digits
552 hash.unshift_char('h');
556 fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> ~str {
557 match ccx.type_hashcodes.borrow().get().find(&t) {
558 Some(h) => return h.to_str(),
562 let mut type_hashcodes = ccx.type_hashcodes.borrow_mut();
563 let mut symbol_hasher = ccx.symbol_hasher.borrow_mut();
564 let hash = symbol_hash(ccx.tcx, symbol_hasher.get(), t, &ccx.link_meta);
565 type_hashcodes.get().insert(t, hash.clone());
570 // Name sanitation. LLVM will happily accept identifiers with weird names, but
572 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
573 pub fn sanitize(s: &str) -> ~str {
574 let mut result = ~"";
577 // Escape these with $ sequences
578 '@' => result.push_str("$SP$"),
579 '~' => result.push_str("$UP$"),
580 '*' => result.push_str("$RP$"),
581 '&' => result.push_str("$BP$"),
582 '<' => result.push_str("$LT$"),
583 '>' => result.push_str("$GT$"),
584 '(' => result.push_str("$LP$"),
585 ')' => result.push_str("$RP$"),
586 ',' => result.push_str("$C$"),
588 // '.' doesn't occur in types and functions, so reuse it
590 '-' | ':' => result.push_char('.'),
592 // These are legal symbols
596 | '_' | '.' | '$' => result.push_char(c),
600 char::escape_unicode(c, |c| tstr.push_char(c));
601 result.push_char('$');
602 result.push_str(tstr.slice_from(1));
607 // Underscore-qualify anything that didn't start as an ident.
608 if result.len() > 0u &&
609 result[0] != '_' as u8 &&
610 ! char::is_XID_start(result[0] as char) {
611 return ~"_" + result;
617 pub fn mangle<PI: Iterator<PathElem>>(mut path: PI,
619 vers: Option<&str>) -> ~str {
620 // Follow C++ namespace-mangling style, see
621 // http://en.wikipedia.org/wiki/Name_mangling for more info.
623 // It turns out that on OSX you can actually have arbitrary symbols in
624 // function names (at least when given to LLVM), but this is not possible
625 // when using unix's linker. Perhaps one day when we just use a linker from LLVM
626 // we won't need to do this name mangling. The problem with name mangling is
627 // that it seriously limits the available characters. For example we can't
628 // have things like &T or ~[T] in symbol names when one would theoretically
629 // want them for things like impls of traits on that type.
631 // To be able to work on all platforms and get *some* reasonable output, we
632 // use C++ name-mangling.
634 let mut n = ~"_ZN"; // _Z == Begin name-sequence, N == nested
636 fn push(n: &mut ~str, s: &str) {
637 let sani = sanitize(s);
638 n.push_str(format!("{}{}", sani.len(), sani));
641 // First, connect each component with <len, name> pairs.
643 push(&mut n, token::get_name(e.name()).get().as_slice())
647 Some(s) => push(&mut n, s),
651 Some(s) => push(&mut n, s),
655 n.push_char('E'); // End name-sequence.
659 pub fn exported_name(path: PathElems, hash: &str, vers: &str) -> ~str {
660 // The version will get mangled to have a leading '_', but it makes more
661 // sense to lead with a 'v' b/c this is a version...
662 let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
668 mangle(path, Some(hash), Some(vers.as_slice()))
671 pub fn mangle_exported_name(ccx: &CrateContext, path: PathElems,
672 t: ty::t, id: ast::NodeId) -> ~str {
673 let mut hash = get_symbol_hash(ccx, t);
675 // Paths can be completely identical for different nodes,
676 // e.g. `fn foo() { { fn a() {} } { fn a() {} } }`, so we
677 // generate unique characters from the node id. For now
678 // hopefully 3 characters is enough to avoid collisions.
679 static EXTRA_CHARS: &'static str =
680 "abcdefghijklmnopqrstuvwxyz\
681 ABCDEFGHIJKLMNOPQRSTUVWXYZ\
684 let extra1 = id % EXTRA_CHARS.len();
685 let id = id / EXTRA_CHARS.len();
686 let extra2 = id % EXTRA_CHARS.len();
687 let id = id / EXTRA_CHARS.len();
688 let extra3 = id % EXTRA_CHARS.len();
689 hash.push_char(EXTRA_CHARS[extra1] as char);
690 hash.push_char(EXTRA_CHARS[extra2] as char);
691 hash.push_char(EXTRA_CHARS[extra3] as char);
693 exported_name(path, hash, ccx.link_meta.crateid.version_or_default())
696 pub fn mangle_internal_name_by_type_only(ccx: &CrateContext,
698 name: &str) -> ~str {
699 let s = ppaux::ty_to_short_str(ccx.tcx, t);
700 let path = [PathName(token::intern(name)),
701 PathName(token::intern(s))];
702 let hash = get_symbol_hash(ccx, t);
703 mangle(ast_map::Values(path.iter()), Some(hash.as_slice()), None)
706 pub fn mangle_internal_name_by_type_and_seq(ccx: &CrateContext,
708 name: &str) -> ~str {
709 let s = ppaux::ty_to_str(ccx.tcx, t);
710 let path = [PathName(token::intern(s)),
712 let hash = get_symbol_hash(ccx, t);
713 mangle(ast_map::Values(path.iter()), Some(hash.as_slice()), None)
716 pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> ~str {
717 mangle(path.chain(Some(gensym_name(flav)).move_iter()), None, None)
720 pub fn output_lib_filename(id: &CrateId) -> ~str {
721 format!("{}-{}-{}", id.name, crate_id_hash(id), id.version_or_default())
724 pub fn get_cc_prog(sess: Session) -> ~str {
725 match sess.opts.cg.linker {
726 Some(ref linker) => return linker.to_owned(),
730 // In the future, FreeBSD will use clang as default compiler.
731 // It would be flexible to use cc (system's default C compiler)
732 // instead of hard-coded gcc.
733 // For win32, there is no cc command, so we add a condition to make it use gcc.
734 match sess.targ_cfg.os {
735 abi::OsWin32 => return ~"gcc",
739 get_system_tool(sess, "cc")
742 pub fn get_ar_prog(sess: Session) -> ~str {
743 match sess.opts.cg.ar {
744 Some(ref ar) => return ar.to_owned(),
748 get_system_tool(sess, "ar")
751 fn get_system_tool(sess: Session, tool: &str) -> ~str {
752 match sess.targ_cfg.os {
753 abi::OsAndroid => match sess.opts.cg.android_cross_path {
755 let tool_str = match tool {
759 format!("{}/bin/arm-linux-androideabi-{}", *path, tool_str)
762 sess.fatal(format!("need Android NDK path for the '{}' tool \
763 (-C android-cross-path)", tool))
766 _ => tool.to_owned(),
770 fn remove(sess: Session, path: &Path) {
771 match fs::unlink(path) {
774 sess.err(format!("failed to remove {}: {}", path.display(), e));
779 /// Perform the linkage portion of the compilation phase. This will generate all
780 /// of the requested outputs for this compilation session.
781 pub fn link_binary(sess: Session,
782 trans: &CrateTranslation,
783 outputs: &OutputFilenames,
784 id: &CrateId) -> Vec<Path> {
785 let mut out_filenames = Vec::new();
786 let crate_types = sess.crate_types.borrow();
787 for &crate_type in crate_types.get().iter() {
788 let out_file = link_binary_output(sess, trans, crate_type, outputs, id);
789 out_filenames.push(out_file);
792 // Remove the temporary object file and metadata if we aren't saving temps
793 if !sess.opts.cg.save_temps {
794 let obj_filename = outputs.temp_path(OutputTypeObject);
795 if !sess.opts.output_types.contains(&OutputTypeObject) {
796 remove(sess, &obj_filename);
798 remove(sess, &obj_filename.with_extension("metadata.o"));
804 fn is_writeable(p: &Path) -> bool {
807 Ok(m) => m.perm & io::UserWrite == io::UserWrite
811 pub fn filename_for_input(sess: &Session, crate_type: session::CrateType,
812 id: &CrateId, out_filename: &Path) -> Path {
813 let libname = output_lib_filename(id);
815 session::CrateTypeRlib => {
816 out_filename.with_filename(format!("lib{}.rlib", libname))
818 session::CrateTypeDylib => {
819 let (prefix, suffix) = match sess.targ_cfg.os {
820 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
821 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
822 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
823 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
824 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
826 out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
828 session::CrateTypeStaticlib => {
829 out_filename.with_filename(format!("lib{}.a", libname))
831 session::CrateTypeExecutable => out_filename.clone(),
835 fn link_binary_output(sess: Session,
836 trans: &CrateTranslation,
837 crate_type: session::CrateType,
838 outputs: &OutputFilenames,
839 id: &CrateId) -> Path {
840 let obj_filename = outputs.temp_path(OutputTypeObject);
841 let out_filename = match outputs.single_output_file {
842 Some(ref file) => file.clone(),
844 let out_filename = outputs.path(OutputTypeExe);
845 filename_for_input(&sess, crate_type, id, &out_filename)
849 // Make sure the output and obj_filename are both writeable.
850 // Mac, FreeBSD, and Windows system linkers check this already --
851 // however, the Linux linker will happily overwrite a read-only file.
852 // We should be consistent.
853 let obj_is_writeable = is_writeable(&obj_filename);
854 let out_is_writeable = is_writeable(&out_filename);
855 if !out_is_writeable {
856 sess.fatal(format!("output file {} is not writeable -- check its permissions.",
857 out_filename.display()));
859 else if !obj_is_writeable {
860 sess.fatal(format!("object file {} is not writeable -- check its permissions.",
861 obj_filename.display()));
865 session::CrateTypeRlib => {
866 link_rlib(sess, Some(trans), &obj_filename, &out_filename);
868 session::CrateTypeStaticlib => {
869 link_staticlib(sess, &obj_filename, &out_filename);
871 session::CrateTypeExecutable => {
872 link_natively(sess, false, &obj_filename, &out_filename);
874 session::CrateTypeDylib => {
875 link_natively(sess, true, &obj_filename, &out_filename);
884 // An rlib in its current incarnation is essentially a renamed .a file. The
885 // rlib primarily contains the object file of the crate, but it also contains
886 // all of the object files from native libraries. This is done by unzipping
887 // native libraries and inserting all of the contents into this archive.
888 fn link_rlib(sess: Session,
889 trans: Option<&CrateTranslation>, // None == no metadata/bytecode
891 out_filename: &Path) -> Archive {
892 let mut a = Archive::create(sess, out_filename, obj_filename);
894 let used_libraries = sess.cstore.get_used_libraries();
895 let used_libraries = used_libraries.borrow();
896 for &(ref l, kind) in used_libraries.get().iter() {
898 cstore::NativeStatic => {
899 a.add_native_library(l.as_slice()).unwrap();
901 cstore::NativeFramework | cstore::NativeUnknown => {}
905 // Note that it is important that we add all of our non-object "magical
906 // files" *after* all of the object files in the archive. The reason for
907 // this is as follows:
909 // * When performing LTO, this archive will be modified to remove
910 // obj_filename from above. The reason for this is described below.
912 // * When the system linker looks at an archive, it will attempt to
913 // determine the architecture of the archive in order to see whether its
916 // The algorithm for this detection is: iterate over the files in the
917 // archive. Skip magical SYMDEF names. Interpret the first file as an
918 // object file. Read architecture from the object file.
920 // * As one can probably see, if "metadata" and "foo.bc" were placed
921 // before all of the objects, then the architecture of this archive would
922 // not be correctly inferred once 'foo.o' is removed.
924 // Basically, all this means is that this code should not move above the
928 // Instead of putting the metadata in an object file section, rlibs
929 // contain the metadata in a separate file. We use a temp directory
930 // here so concurrent builds in the same directory don't try to use
931 // the same filename for metadata (stomping over one another)
932 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
933 let metadata = tmpdir.path().join(METADATA_FILENAME);
934 match fs::File::create(&metadata).write(trans.metadata) {
937 sess.err(format!("failed to write {}: {}",
938 metadata.display(), e));
939 sess.abort_if_errors();
942 a.add_file(&metadata, false);
943 remove(sess, &metadata);
945 // For LTO purposes, the bytecode of this library is also inserted
947 let bc = obj_filename.with_extension("bc");
948 match fs::File::open(&bc).read_to_end().and_then(|data| {
949 fs::File::create(&bc).write(flate::deflate_bytes(data).as_slice())
953 sess.err(format!("failed to compress bytecode: {}", e));
954 sess.abort_if_errors()
957 a.add_file(&bc, false);
958 if !sess.opts.cg.save_temps &&
959 !sess.opts.output_types.contains(&OutputTypeBitcode) {
963 // After adding all files to the archive, we need to update the
964 // symbol table of the archive. This currently dies on OSX (see
965 // #11162), and isn't necessary there anyway
966 match sess.targ_cfg.os {
968 _ => { a.update_symbols(); }
977 // Create a static archive
979 // This is essentially the same thing as an rlib, but it also involves adding
980 // all of the upstream crates' objects into the archive. This will slurp in
981 // all of the native libraries of upstream dependencies as well.
983 // Additionally, there's no way for us to link dynamic libraries, so we warn
984 // about all dynamic library dependencies that they're not linked in.
986 // There's no need to include metadata in a static archive, so ensure to not
987 // link in the metadata object file (and also don't prepare the archive with a
989 fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
990 let mut a = link_rlib(sess, None, obj_filename, out_filename);
991 a.add_native_library("morestack").unwrap();
992 a.add_native_library("compiler-rt").unwrap();
994 let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
995 for &(cnum, ref path) in crates.iter() {
996 let name = sess.cstore.get_crate_data(cnum).name.clone();
997 let p = match *path {
998 Some(ref p) => p.clone(), None => {
999 sess.err(format!("could not find rlib for: `{}`", name));
1003 a.add_rlib(&p, name, sess.lto()).unwrap();
1004 let native_libs = csearch::get_native_libraries(sess.cstore, cnum);
1005 for &(kind, ref lib) in native_libs.iter() {
1006 let name = match kind {
1007 cstore::NativeStatic => "static library",
1008 cstore::NativeUnknown => "library",
1009 cstore::NativeFramework => "framework",
1011 sess.warn(format!("unlinked native {}: {}", name, *lib));
1016 // Create a dynamic library or executable
1018 // This will invoke the system linker/cc to create the resulting file. This
1019 // links to all upstream files as well.
1020 fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
1021 out_filename: &Path) {
1022 let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
1023 // The invocations of cc share some flags across platforms
1024 let cc_prog = get_cc_prog(sess);
1025 let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
1026 cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
1027 obj_filename, out_filename));
1028 if (sess.opts.debugging_opts & session::PRINT_LINK_ARGS) != 0 {
1029 println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
1032 // May have not found libraries in the right formats.
1033 sess.abort_if_errors();
1035 // Invoke the system linker
1036 debug!("{} {}", cc_prog, cc_args.connect(" "));
1037 let prog = time(sess.time_passes(), "running linker", (), |()|
1038 Process::output(cc_prog, cc_args));
1041 if !prog.status.success() {
1042 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
1043 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
1044 sess.note(str::from_utf8_owned(prog.error + prog.output).unwrap());
1045 sess.abort_if_errors();
1049 sess.err(format!("could not exec the linker `{}`: {}", cc_prog, e));
1050 sess.abort_if_errors();
1055 // On OSX, debuggers need this utility to get run to do some munging of
1057 if sess.targ_cfg.os == abi::OsMacos && (sess.opts.debuginfo != NoDebugInfo) {
1058 // FIXME (#9639): This needs to handle non-utf8 paths
1059 match Process::status("dsymutil",
1060 [out_filename.as_str().unwrap().to_owned()]) {
1063 sess.err(format!("failed to run dsymutil: {}", e));
1064 sess.abort_if_errors();
1070 fn link_args(sess: Session,
1073 obj_filename: &Path,
1074 out_filename: &Path) -> Vec<~str> {
1076 // The default library location, we need this to find the runtime.
1077 // The location of crates will be determined as needed.
1078 // FIXME (#9639): This needs to handle non-utf8 paths
1079 let lib_path = sess.filesearch.get_target_lib_path();
1080 let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
1082 let mut args = vec!(stage);
1084 // FIXME (#9639): This needs to handle non-utf8 paths
1086 ~"-o", out_filename.as_str().unwrap().to_owned(),
1087 obj_filename.as_str().unwrap().to_owned()]);
1089 // When linking a dynamic library, we put the metadata into a section of the
1090 // executable. This metadata is in a separate object file from the main
1091 // object file, so we link that in here.
1093 let metadata = obj_filename.with_extension("metadata.o");
1094 args.push(metadata.as_str().unwrap().to_owned());
1097 // We want to prevent the compiler from accidentally leaking in any system
1098 // libraries, so we explicitly ask gcc to not link to any libraries by
1099 // default. Note that this does not happen for windows because windows pulls
1100 // in some large number of libraries and I couldn't quite figure out which
1101 // subset we wanted.
1103 // FIXME(#11937) we should invoke the system linker directly
1104 if sess.targ_cfg.os != abi::OsWin32 {
1105 args.push(~"-nodefaultlibs");
1108 if sess.targ_cfg.os == abi::OsLinux {
1109 // GNU-style linkers will use this to omit linking to libraries which
1110 // don't actually fulfill any relocations, but only for libraries which
1111 // follow this flag. Thus, use it before specifying libraries to link to.
1112 args.push(~"-Wl,--as-needed");
1114 // GNU-style linkers support optimization with -O. --gc-sections
1115 // removes metadata and potentially other useful things, so don't
1116 // include it. GNU ld doesn't need a numeric argument, but other linkers
1118 if sess.opts.optimize == session::Default ||
1119 sess.opts.optimize == session::Aggressive {
1120 args.push(~"-Wl,-O1");
1124 if sess.targ_cfg.os == abi::OsWin32 {
1125 // Make sure that we link to the dynamic libgcc, otherwise cross-module
1126 // DWARF stack unwinding will not work.
1127 // This behavior may be overridden by --link-args "-static-libgcc"
1128 args.push(~"-shared-libgcc");
1131 if sess.targ_cfg.os == abi::OsAndroid {
1132 // Many of the symbols defined in compiler-rt are also defined in libgcc.
1133 // Android linker doesn't like that by default.
1134 args.push(~"-Wl,--allow-multiple-definition");
1137 // Take careful note of the ordering of the arguments we pass to the linker
1138 // here. Linkers will assume that things on the left depend on things to the
1139 // right. Things on the right cannot depend on things on the left. This is
1140 // all formally implemented in terms of resolving symbols (libs on the right
1141 // resolve unknown symbols of libs on the left, but not vice versa).
1143 // For this reason, we have organized the arguments we pass to the linker as
1146 // 1. The local object that LLVM just generated
1147 // 2. Upstream rust libraries
1148 // 3. Local native libraries
1149 // 4. Upstream native libraries
1151 // This is generally fairly natural, but some may expect 2 and 3 to be
1152 // swapped. The reason that all native libraries are put last is that it's
1153 // not recommended for a native library to depend on a symbol from a rust
1154 // crate. If this is the case then a staticlib crate is recommended, solving
1157 // Additionally, it is occasionally the case that upstream rust libraries
1158 // depend on a local native library. In the case of libraries such as
1159 // lua/glfw/etc the name of the library isn't the same across all platforms,
1160 // so only the consumer crate of a library knows the actual name. This means
1161 // that downstream crates will provide the #[link] attribute which upstream
1162 // crates will depend on. Hence local native libraries are after out
1163 // upstream rust crates.
1165 // In theory this means that a symbol in an upstream native library will be
1166 // shadowed by a local native library when it wouldn't have been before, but
1167 // this kind of behavior is pretty platform specific and generally not
1168 // recommended anyway, so I don't think we're shooting ourself in the foot
1170 add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1171 add_local_native_libraries(&mut args, sess);
1172 add_upstream_native_libraries(&mut args, sess);
1174 // # Telling the linker what we're doing
1177 // On mac we need to tell the linker to let this library be rpathed
1178 if sess.targ_cfg.os == abi::OsMacos {
1179 args.push(~"-dynamiclib");
1180 args.push(~"-Wl,-dylib");
1181 // FIXME (#9639): This needs to handle non-utf8 paths
1182 if !sess.opts.cg.no_rpath {
1183 args.push(~"-Wl,-install_name,@rpath/" +
1184 out_filename.filename_str().unwrap());
1187 args.push(~"-shared")
1191 if sess.targ_cfg.os == abi::OsFreebsd {
1192 args.push_all([~"-L/usr/local/lib",
1193 ~"-L/usr/local/lib/gcc46",
1194 ~"-L/usr/local/lib/gcc44"]);
1197 // FIXME (#2397): At some point we want to rpath our guesses as to
1198 // where extern libraries might live, based on the
1199 // addl_lib_search_paths
1200 if !sess.opts.cg.no_rpath {
1201 args.push_all(rpath::get_rpath_flags(sess, out_filename));
1204 // Stack growth requires statically linking a __morestack function
1205 args.push(~"-lmorestack");
1206 // compiler-rt contains implementations of low-level LLVM helpers
1207 // It should go before platform and user libraries, so it has first dibs
1208 // at resolving symbols that also appear in libgcc.
1209 args.push(~"-lcompiler-rt");
1211 // Finally add all the linker arguments provided on the command line along
1212 // with any #[link_args] attributes found inside the crate
1213 args.push_all(sess.opts.cg.link_args);
1214 let used_link_args = sess.cstore.get_used_link_args();
1215 let used_link_args = used_link_args.borrow();
1216 for arg in used_link_args.get().iter() {
1217 args.push(arg.clone());
1222 // # Native library linking
1224 // User-supplied library search paths (-L on the command line). These are
1225 // the same paths used to find Rust crates, so some of them may have been
1226 // added already by the previous crate linking code. This only allows them
1227 // to be found at compile time so it is still entirely up to outside
1228 // forces to make sure that library can be found at runtime.
1230 // Also note that the native libraries linked here are only the ones located
1231 // in the current crate. Upstream crates with native library dependencies
1232 // may have their native library pulled in above.
1233 fn add_local_native_libraries(args: &mut Vec<~str> , sess: Session) {
1234 let addl_lib_search_paths = sess.opts.addl_lib_search_paths.borrow();
1235 for path in addl_lib_search_paths.get().iter() {
1236 // FIXME (#9639): This needs to handle non-utf8 paths
1237 args.push("-L" + path.as_str().unwrap().to_owned());
1240 let rustpath = filesearch::rust_path();
1241 for path in rustpath.iter() {
1242 // FIXME (#9639): This needs to handle non-utf8 paths
1243 args.push("-L" + path.as_str().unwrap().to_owned());
1246 let used_libraries = sess.cstore.get_used_libraries();
1247 let used_libraries = used_libraries.borrow();
1248 for &(ref l, kind) in used_libraries.get().iter() {
1250 cstore::NativeUnknown | cstore::NativeStatic => {
1251 args.push("-l" + *l);
1253 cstore::NativeFramework => {
1254 args.push(~"-framework");
1255 args.push(l.to_owned());
1261 // # Rust Crate linking
1263 // Rust crates are not considered at all when creating an rlib output. All
1264 // dependencies will be linked when producing the final output (instead of
1265 // the intermediate rlib version)
1266 fn add_upstream_rust_crates(args: &mut Vec<~str> , sess: Session,
1267 dylib: bool, tmpdir: &Path) {
1269 // As a limitation of the current implementation, we require that everything
1270 // must be static or everything must be dynamic. The reasons for this are a
1271 // little subtle, but as with staticlibs and rlibs, the goal is to prevent
1272 // duplicate copies of the same library showing up. For example, a static
1273 // immediate dependency might show up as an upstream dynamic dependency and
1274 // we currently have no way of knowing that. We know that all dynamic
1275 // libraries require dynamic dependencies (see above), so it's satisfactory
1276 // to include either all static libraries or all dynamic libraries.
1278 // With this limitation, we expose a compiler default linkage type and an
1279 // option to reverse that preference. The current behavior looks like:
1281 // * If a dylib is being created, upstream dependencies must be dylibs
1282 // * If nothing else is specified, static linking is preferred
1283 // * If the -C prefer-dynamic flag is given, dynamic linking is preferred
1284 // * If one form of linking fails, the second is also attempted
1285 // * If both forms fail, then we emit an error message
1287 let dynamic = get_deps(sess.cstore, cstore::RequireDynamic);
1288 let statik = get_deps(sess.cstore, cstore::RequireStatic);
1289 match (dynamic, statik, sess.opts.cg.prefer_dynamic, dylib) {
1290 (_, Some(deps), false, false) => {
1291 add_static_crates(args, sess, tmpdir, deps)
1294 (None, Some(deps), true, false) => {
1295 // If you opted in to dynamic linking and we decided to emit a
1296 // static output, you should probably be notified of such an event!
1297 sess.warn("dynamic linking was preferred, but dependencies \
1298 could not all be found in an dylib format.");
1299 sess.warn("linking statically instead, using rlibs");
1300 add_static_crates(args, sess, tmpdir, deps)
1303 (Some(deps), _, _, _) => add_dynamic_crates(args, sess, deps),
1305 (None, _, _, true) => {
1306 sess.err("dylib output requested, but some depenencies could not \
1307 be found in the dylib format");
1308 let deps = sess.cstore.get_used_crates(cstore::RequireDynamic);
1309 for (cnum, path) in deps.move_iter() {
1310 if path.is_some() { continue }
1311 let name = sess.cstore.get_crate_data(cnum).name.clone();
1312 sess.note(format!("dylib not found: {}", name));
1316 (None, None, pref, false) => {
1317 let (pref, name) = if pref {
1318 sess.err("dynamic linking is preferred, but dependencies were \
1319 not found in either dylib or rlib format");
1320 (cstore::RequireDynamic, "dylib")
1322 sess.err("dependencies were not all found in either dylib or \
1324 (cstore::RequireStatic, "rlib")
1326 sess.note(format!("dependencies not found in the `{}` format",
1328 for (cnum, path) in sess.cstore.get_used_crates(pref).move_iter() {
1329 if path.is_some() { continue }
1330 let name = sess.cstore.get_crate_data(cnum).name.clone();
1336 // Converts a library file-stem into a cc -l argument
1337 fn unlib(config: @session::Config, stem: &str) -> ~str {
1338 if stem.starts_with("lib") &&
1339 config.os != abi::OsWin32 {
1340 stem.slice(3, stem.len()).to_owned()
1346 // Attempts to find all dependencies with a certain linkage preference,
1347 // returning `None` if not all libraries could be found with that
1349 fn get_deps(cstore: &cstore::CStore, preference: cstore::LinkagePreference)
1350 -> Option<Vec<(ast::CrateNum, Path)> >
1352 let crates = cstore.get_used_crates(preference);
1353 if crates.iter().all(|&(_, ref p)| p.is_some()) {
1354 Some(crates.move_iter().map(|(a, b)| (a, b.unwrap())).collect())
1360 // Adds the static "rlib" versions of all crates to the command line.
1361 fn add_static_crates(args: &mut Vec<~str> , sess: Session, tmpdir: &Path,
1362 crates: Vec<(ast::CrateNum, Path)> ) {
1363 for (cnum, cratepath) in crates.move_iter() {
1364 // When performing LTO on an executable output, all of the
1365 // bytecode from the upstream libraries has already been
1366 // included in our object file output. We need to modify all of
1367 // the upstream archives to remove their corresponding object
1368 // file to make sure we don't pull the same code in twice.
1370 // We must continue to link to the upstream archives to be sure
1371 // to pull in native static dependencies. As the final caveat,
1372 // on linux it is apparently illegal to link to a blank archive,
1373 // so if an archive no longer has any object files in it after
1374 // we remove `lib.o`, then don't link against it at all.
1376 // If we're not doing LTO, then our job is simply to just link
1377 // against the archive.
1379 let name = sess.cstore.get_crate_data(cnum).name.clone();
1380 time(sess.time_passes(), format!("altering {}.rlib", name),
1382 let dst = tmpdir.join(cratepath.filename().unwrap());
1383 match fs::copy(&cratepath, &dst) {
1386 sess.err(format!("failed to copy {} to {}: {}",
1387 cratepath.display(),
1390 sess.abort_if_errors();
1393 let dst_str = dst.as_str().unwrap().to_owned();
1394 let mut archive = Archive::open(sess, dst);
1395 archive.remove_file(format!("{}.o", name));
1396 let files = archive.files();
1397 if files.iter().any(|s| s.ends_with(".o")) {
1402 args.push(cratepath.as_str().unwrap().to_owned());
1407 // Same thing as above, but for dynamic crates instead of static crates.
1408 fn add_dynamic_crates(args: &mut Vec<~str> , sess: Session,
1409 crates: Vec<(ast::CrateNum, Path)> ) {
1410 // If we're performing LTO, then it should have been previously required
1411 // that all upstream rust dependencies were available in an rlib format.
1412 assert!(!sess.lto());
1414 for (_, cratepath) in crates.move_iter() {
1415 // Just need to tell the linker about where the library lives and
1417 let dir = cratepath.dirname_str().unwrap();
1418 if !dir.is_empty() { args.push("-L" + dir); }
1419 let libarg = unlib(sess.targ_cfg, cratepath.filestem_str().unwrap());
1420 args.push("-l" + libarg);
1425 // Link in all of our upstream crates' native dependencies. Remember that
1426 // all of these upstream native depenencies are all non-static
1427 // dependencies. We've got two cases then:
1429 // 1. The upstream crate is an rlib. In this case we *must* link in the
1430 // native dependency because the rlib is just an archive.
1432 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1433 // have the dependency present on the system somewhere. Thus, we don't
1434 // gain a whole lot from not linking in the dynamic dependency to this
1437 // The use case for this is a little subtle. In theory the native
1438 // dependencies of a crate a purely an implementation detail of the crate
1439 // itself, but the problem arises with generic and inlined functions. If a
1440 // generic function calls a native function, then the generic function must
1441 // be instantiated in the target crate, meaning that the native symbol must
1442 // also be resolved in the target crate.
1443 fn add_upstream_native_libraries(args: &mut Vec<~str> , sess: Session) {
1444 let cstore = sess.cstore;
1445 cstore.iter_crate_data(|cnum, _| {
1446 let libs = csearch::get_native_libraries(cstore, cnum);
1447 for &(kind, ref lib) in libs.iter() {
1449 cstore::NativeUnknown => args.push("-l" + *lib),
1450 cstore::NativeFramework => {
1451 args.push(~"-framework");
1452 args.push(lib.to_owned());
1454 cstore::NativeStatic => {
1455 sess.bug("statics shouldn't be propagated");