]> git.lizzy.rs Git - rust.git/blob - src/librustc/back/link.rs
63c4d9f4a2976ee270e7cdcdd50934fb41bb9d3e
[rust.git] / src / librustc / back / link.rs
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.
4 //
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.
10
11
12 use back::archive::{Archive, METADATA_FILENAME};
13 use back::rpath;
14 use driver::driver::CrateTranslation;
15 use driver::session::Session;
16 use driver::session;
17 use lib::llvm::llvm;
18 use lib::llvm::ModuleRef;
19 use lib;
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;
24 use middle::ty;
25 use util::common::time;
26 use util::ppaux;
27 use util::sha2::{Digest, Sha256};
28
29 use std::c_str::ToCStr;
30 use std::char;
31 use std::os::consts::{macos, freebsd, linux, android, win32};
32 use std::ptr;
33 use std::run;
34 use std::str;
35 use std::io;
36 use std::io::fs;
37 use extra::hex::ToHex;
38 use extra::tempfile::TempDir;
39 use syntax::abi;
40 use syntax::ast;
41 use syntax::ast_map::{PathMod, PathName, PathPrettyName};
42 use syntax::ast_map;
43 use syntax::attr;
44 use syntax::attr::AttrMetaMethods;
45 use syntax::crateid::CrateId;
46
47 #[deriving(Clone, Eq)]
48 pub enum OutputType {
49     OutputTypeNone,
50     OutputTypeBitcode,
51     OutputTypeAssembly,
52     OutputTypeLlvmAssembly,
53     OutputTypeObject,
54     OutputTypeExe,
55 }
56
57 pub fn llvm_err(sess: Session, msg: ~str) -> ! {
58     unsafe {
59         let cstr = llvm::LLVMRustGetLastError();
60         if cstr == ptr::null() {
61             sess.fatal(msg);
62         } else {
63             sess.fatal(msg + ": " + str::raw::from_c_str(cstr));
64         }
65     }
66 }
67
68 pub fn WriteOutputFile(
69         sess: Session,
70         Target: lib::llvm::TargetMachineRef,
71         PM: lib::llvm::PassManagerRef,
72         M: ModuleRef,
73         Output: &Path,
74         FileType: lib::llvm::FileType) {
75     unsafe {
76         Output.with_c_str(|Output| {
77             let result = llvm::LLVMRustWriteOutputFile(
78                     Target, PM, M, Output, FileType);
79             if !result {
80                 llvm_err(sess, ~"Could not write output");
81             }
82         })
83     }
84 }
85
86 pub mod write {
87
88     use back::lto;
89     use back::link::{WriteOutputFile, OutputType};
90     use back::link::{OutputTypeAssembly, OutputTypeBitcode};
91     use back::link::{OutputTypeExe, OutputTypeLlvmAssembly};
92     use back::link::{OutputTypeObject};
93     use driver::driver::CrateTranslation;
94     use driver::session::Session;
95     use driver::session;
96     use lib::llvm::llvm;
97     use lib::llvm::{ModuleRef, TargetMachineRef, PassManagerRef};
98     use lib;
99     use util::common::time;
100
101     use std::c_str::ToCStr;
102     use std::io;
103     use std::libc::{c_uint, c_int};
104     use std::path::Path;
105     use std::run;
106     use std::str;
107
108     pub fn run_passes(sess: Session,
109                       trans: &CrateTranslation,
110                       output_type: OutputType,
111                       output: &Path) {
112         let llmod = trans.module;
113         let llcx = trans.context;
114         unsafe {
115             configure_llvm(sess);
116
117             if sess.opts.save_temps {
118                 output.with_extension("no-opt.bc").with_c_str(|buf| {
119                     llvm::LLVMWriteBitcodeToFile(llmod, buf);
120                 })
121             }
122
123             let OptLevel = match sess.opts.optimize {
124               session::No => lib::llvm::CodeGenLevelNone,
125               session::Less => lib::llvm::CodeGenLevelLess,
126               session::Default => lib::llvm::CodeGenLevelDefault,
127               session::Aggressive => lib::llvm::CodeGenLevelAggressive,
128             };
129             let use_softfp = sess.opts.debugging_opts & session::USE_SOFTFP != 0;
130
131             let tm = sess.targ_cfg.target_strs.target_triple.with_c_str(|T| {
132                 sess.opts.target_cpu.with_c_str(|CPU| {
133                     sess.opts.target_feature.with_c_str(|Features| {
134                         llvm::LLVMRustCreateTargetMachine(
135                             T, CPU, Features,
136                             lib::llvm::CodeModelDefault,
137                             lib::llvm::RelocPIC,
138                             OptLevel,
139                             true,
140                             use_softfp
141                         )
142                     })
143                 })
144             });
145
146             // Create the two optimizing pass managers. These mirror what clang
147             // does, and are by populated by LLVM's default PassManagerBuilder.
148             // Each manager has a different set of passes, but they also share
149             // some common passes.
150             let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
151             let mpm = llvm::LLVMCreatePassManager();
152
153             // If we're verifying or linting, add them to the function pass
154             // manager.
155             let addpass = |pass: &str| {
156                 pass.with_c_str(|s| llvm::LLVMRustAddPass(fpm, s))
157             };
158             if !sess.no_verify() { assert!(addpass("verify")); }
159
160             if !sess.no_prepopulate_passes() {
161                 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
162                 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
163                 populate_llvm_passes(fpm, mpm, llmod, OptLevel);
164             }
165
166             for pass in sess.opts.custom_passes.iter() {
167                 pass.with_c_str(|s| {
168                     if !llvm::LLVMRustAddPass(mpm, s) {
169                         sess.warn(format!("Unknown pass {}, ignoring", *pass));
170                     }
171                 })
172             }
173
174             // Finally, run the actual optimization passes
175             time(sess.time_passes(), "llvm function passes", (), |()|
176                  llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
177             time(sess.time_passes(), "llvm module passes", (), |()|
178                  llvm::LLVMRunPassManager(mpm, llmod));
179
180             // Deallocate managers that we're now done with
181             llvm::LLVMDisposePassManager(fpm);
182             llvm::LLVMDisposePassManager(mpm);
183
184             // Emit the bytecode if we're either saving our temporaries or
185             // emitting an rlib. Whenever an rlib is created, the bytecode is
186             // inserted into the archive in order to allow LTO against it.
187             let outputs = sess.outputs.borrow();
188             if sess.opts.save_temps ||
189                outputs.get().iter().any(|&o| o == session::OutputRlib) {
190                 output.with_extension("bc").with_c_str(|buf| {
191                     llvm::LLVMWriteBitcodeToFile(llmod, buf);
192                 })
193             }
194
195             if sess.lto() {
196                 time(sess.time_passes(), "all lto passes", (), |()|
197                      lto::run(sess, llmod, tm, trans.reachable));
198
199                 if sess.opts.save_temps {
200                     output.with_extension("lto.bc").with_c_str(|buf| {
201                         llvm::LLVMWriteBitcodeToFile(llmod, buf);
202                     })
203                 }
204             }
205
206             // A codegen-specific pass manager is used to generate object
207             // files for an LLVM module.
208             //
209             // Apparently each of these pass managers is a one-shot kind of
210             // thing, so we create a new one for each type of output. The
211             // pass manager passed to the closure should be ensured to not
212             // escape the closure itself, and the manager should only be
213             // used once.
214             fn with_codegen(tm: TargetMachineRef, llmod: ModuleRef,
215                             f: |PassManagerRef|) {
216                 unsafe {
217                     let cpm = llvm::LLVMCreatePassManager();
218                     llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
219                     llvm::LLVMRustAddLibraryInfo(cpm, llmod);
220                     f(cpm);
221                     llvm::LLVMDisposePassManager(cpm);
222                 }
223             }
224
225             time(sess.time_passes(), "codegen passes", (), |()| {
226                 match output_type {
227                     OutputTypeNone => {}
228                     OutputTypeBitcode => {
229                         output.with_c_str(|buf| {
230                             llvm::LLVMWriteBitcodeToFile(llmod, buf);
231                         })
232                     }
233                     OutputTypeLlvmAssembly => {
234                         output.with_c_str(|output| {
235                             with_codegen(tm, llmod, |cpm| {
236                                 llvm::LLVMRustPrintModule(cpm, llmod, output);
237                             })
238                         })
239                     }
240                     OutputTypeAssembly => {
241                         with_codegen(tm, llmod, |cpm| {
242                             WriteOutputFile(sess, tm, cpm, llmod, output,
243                                             lib::llvm::AssemblyFile);
244                         });
245
246                         // If we're not using the LLVM assembler, this function
247                         // could be invoked specially with output_type_assembly,
248                         // so in this case we still want the metadata object
249                         // file.
250                         if sess.opts.output_type != OutputTypeAssembly {
251                             with_codegen(tm, trans.metadata_module, |cpm| {
252                                 let out = output.with_extension("metadata.o");
253                                 WriteOutputFile(sess, tm, cpm,
254                                                 trans.metadata_module, &out,
255                                                 lib::llvm::ObjectFile);
256                             })
257                         }
258                     }
259                     OutputTypeExe | OutputTypeObject => {
260                         with_codegen(tm, llmod, |cpm| {
261                             WriteOutputFile(sess, tm, cpm, llmod, output,
262                                             lib::llvm::ObjectFile);
263                         });
264                         with_codegen(tm, trans.metadata_module, |cpm| {
265                             let out = output.with_extension("metadata.o");
266                             WriteOutputFile(sess, tm, cpm,
267                                             trans.metadata_module, &out,
268                                             lib::llvm::ObjectFile);
269                         })
270                     }
271                 }
272             });
273
274             llvm::LLVMRustDisposeTargetMachine(tm);
275             llvm::LLVMDisposeModule(trans.metadata_module);
276             llvm::LLVMDisposeModule(llmod);
277             llvm::LLVMContextDispose(llcx);
278             if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
279         }
280     }
281
282     pub fn run_assembler(sess: Session, assembly: &Path, object: &Path) {
283         let cc = super::get_cc_prog(sess);
284
285         // FIXME (#9639): This needs to handle non-utf8 paths
286         let args = [
287             ~"-c",
288             ~"-o", object.as_str().unwrap().to_owned(),
289             assembly.as_str().unwrap().to_owned()];
290
291         debug!("{} '{}'", cc, args.connect("' '"));
292         let opt_prog = {
293             let _guard = io::ignore_io_error();
294             run::process_output(cc, args)
295         };
296         match opt_prog {
297             Some(prog) => {
298                 if !prog.status.success() {
299                     sess.err(format!("linking with `{}` failed: {}", cc, prog.status));
300                     sess.note(format!("{} arguments: '{}'", cc, args.connect("' '")));
301                     sess.note(str::from_utf8_owned(prog.error + prog.output).unwrap());
302                     sess.abort_if_errors();
303                 }
304             },
305             None => {
306                 sess.err(format!("could not exec the linker `{}`", cc));
307                 sess.abort_if_errors();
308             }
309         }
310     }
311
312     unsafe fn configure_llvm(sess: Session) {
313         use std::unstable::mutex::{Once, ONCE_INIT};
314         static mut INIT: Once = ONCE_INIT;
315
316         // Copy what clang does by turning on loop vectorization at O2 and
317         // slp vectorization at O3
318         let vectorize_loop = !sess.no_vectorize_loops() &&
319                              (sess.opts.optimize == session::Default ||
320                               sess.opts.optimize == session::Aggressive);
321         let vectorize_slp = !sess.no_vectorize_slp() &&
322                             sess.opts.optimize == session::Aggressive;
323
324         let mut llvm_c_strs = ~[];
325         let mut llvm_args = ~[];
326         let add = |arg: &str| {
327             let s = arg.to_c_str();
328             llvm_args.push(s.with_ref(|p| p));
329             llvm_c_strs.push(s);
330         };
331         add("rustc"); // fake program name
332         add("-arm-enable-ehabi");
333         add("-arm-enable-ehabi-descriptors");
334         if vectorize_loop { add("-vectorize-loops"); }
335         if vectorize_slp  { add("-vectorize-slp");   }
336         if sess.time_llvm_passes() { add("-time-passes"); }
337         if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
338
339         for arg in sess.opts.llvm_args.iter() {
340             add(*arg);
341         }
342
343         INIT.doit(|| {
344             llvm::LLVMInitializePasses();
345
346             // Only initialize the platforms supported by Rust here, because
347             // using --llvm-root will have multiple platforms that rustllvm
348             // doesn't actually link to and it's pointless to put target info
349             // into the registry that Rust cannot generate machine code for.
350             llvm::LLVMInitializeX86TargetInfo();
351             llvm::LLVMInitializeX86Target();
352             llvm::LLVMInitializeX86TargetMC();
353             llvm::LLVMInitializeX86AsmPrinter();
354             llvm::LLVMInitializeX86AsmParser();
355
356             llvm::LLVMInitializeARMTargetInfo();
357             llvm::LLVMInitializeARMTarget();
358             llvm::LLVMInitializeARMTargetMC();
359             llvm::LLVMInitializeARMAsmPrinter();
360             llvm::LLVMInitializeARMAsmParser();
361
362             llvm::LLVMInitializeMipsTargetInfo();
363             llvm::LLVMInitializeMipsTarget();
364             llvm::LLVMInitializeMipsTargetMC();
365             llvm::LLVMInitializeMipsAsmPrinter();
366             llvm::LLVMInitializeMipsAsmParser();
367
368             llvm::LLVMRustSetLLVMOptions(llvm_args.len() as c_int,
369                                          llvm_args.as_ptr());
370         });
371     }
372
373     unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
374                                    mpm: lib::llvm::PassManagerRef,
375                                    llmod: ModuleRef,
376                                    opt: lib::llvm::CodeGenOptLevel) {
377         // Create the PassManagerBuilder for LLVM. We configure it with
378         // reasonable defaults and prepare it to actually populate the pass
379         // manager.
380         let builder = llvm::LLVMPassManagerBuilderCreate();
381         match opt {
382             lib::llvm::CodeGenLevelNone => {
383                 // Don't add lifetime intrinsics at O0
384                 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
385             }
386             lib::llvm::CodeGenLevelLess => {
387                 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
388             }
389             // numeric values copied from clang
390             lib::llvm::CodeGenLevelDefault => {
391                 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
392                                                                     225);
393             }
394             lib::llvm::CodeGenLevelAggressive => {
395                 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
396                                                                     275);
397             }
398         }
399         llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
400         llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
401
402         // Use the builder to populate the function/module pass managers.
403         llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
404         llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
405         llvm::LLVMPassManagerBuilderDispose(builder);
406     }
407 }
408
409
410 /*
411  * Name mangling and its relationship to metadata. This is complex. Read
412  * carefully.
413  *
414  * The semantic model of Rust linkage is, broadly, that "there's no global
415  * namespace" between crates. Our aim is to preserve the illusion of this
416  * model despite the fact that it's not *quite* possible to implement on
417  * modern linkers. We initially didn't use system linkers at all, but have
418  * been convinced of their utility.
419  *
420  * There are a few issues to handle:
421  *
422  *  - Linkers operate on a flat namespace, so we have to flatten names.
423  *    We do this using the C++ namespace-mangling technique. Foo::bar
424  *    symbols and such.
425  *
426  *  - Symbols with the same name but different types need to get different
427  *    linkage-names. We do this by hashing a string-encoding of the type into
428  *    a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
429  *    we use SHA256) to "prevent collisions". This is not airtight but 16 hex
430  *    digits on uniform probability means you're going to need 2**32 same-name
431  *    symbols in the same process before you're even hitting birthday-paradox
432  *    collision probability.
433  *
434  *  - Symbols in different crates but with same names "within" the crate need
435  *    to get different linkage-names.
436  *
437  *  - The hash shown in the filename needs to be predictable and stable for
438  *    build tooling integration. It also needs to be using a hash function
439  *    which is easy to use from Python, make, etc.
440  *
441  * So here is what we do:
442  *
443  *  - Consider the package id; every crate has one (specified with crate_id
444  *    attribute).  If a package id isn't provided explicitly, we infer a
445  *    versionless one from the output name. The version will end up being 0.0
446  *    in this case. CNAME and CVERS are taken from this package id. For
447  *    example, github.com/mozilla/CNAME#CVERS.
448  *
449  *  - Define CMH as SHA256(crateid).
450  *
451  *  - Define CMH8 as the first 8 characters of CMH.
452  *
453  *  - Compile our crate to lib CNAME-CMH8-CVERS.so
454  *
455  *  - Define STH(sym) as SHA256(CMH, type_str(sym))
456  *
457  *  - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
458  *    name, non-name metadata, and type sense, and versioned in the way
459  *    system linkers understand.
460  */
461
462 pub fn build_link_meta(sess: Session,
463                        attrs: &[ast::Attribute],
464                        output: &Path,
465                        symbol_hasher: &mut Sha256)
466                        -> LinkMeta {
467     // This calculates CMH as defined above
468     fn crate_hash(symbol_hasher: &mut Sha256, crateid: &CrateId) -> @str {
469         symbol_hasher.reset();
470         symbol_hasher.input_str(crateid.to_str());
471         truncated_hash_result(symbol_hasher).to_managed()
472     }
473
474     let crateid = match attr::find_crateid(attrs) {
475         None => {
476             let stem = session::expect(
477                 sess,
478                 output.filestem_str(),
479                 || format!("output file name '{}' doesn't appear to have a stem",
480                            output.display()));
481             from_str(stem).unwrap()
482         }
483         Some(s) => s,
484     };
485
486     let hash = crate_hash(symbol_hasher, &crateid);
487
488     LinkMeta {
489         crateid: crateid,
490         crate_hash: hash,
491     }
492 }
493
494 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
495     let output = symbol_hasher.result_bytes();
496     // 64 bits should be enough to avoid collisions.
497     output.slice_to(8).to_hex()
498 }
499
500
501 // This calculates STH for a symbol, as defined above
502 pub fn symbol_hash(tcx: ty::ctxt,
503                    symbol_hasher: &mut Sha256,
504                    t: ty::t,
505                    link_meta: &LinkMeta) -> @str {
506     // NB: do *not* use abbrevs here as we want the symbol names
507     // to be independent of one another in the crate.
508
509     symbol_hasher.reset();
510     symbol_hasher.input_str(link_meta.crateid.name);
511     symbol_hasher.input_str("-");
512     symbol_hasher.input_str(link_meta.crate_hash);
513     symbol_hasher.input_str("-");
514     symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
515     let mut hash = truncated_hash_result(symbol_hasher);
516     // Prefix with 'h' so that it never blends into adjacent digits
517     hash.unshift_char('h');
518     // tjc: allocation is unfortunate; need to change std::hash
519     hash.to_managed()
520 }
521
522 pub fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> @str {
523     {
524         let type_hashcodes = ccx.type_hashcodes.borrow();
525         match type_hashcodes.get().find(&t) {
526             Some(&h) => return h,
527             None => {}
528         }
529     }
530
531     let mut type_hashcodes = ccx.type_hashcodes.borrow_mut();
532     let mut symbol_hasher = ccx.symbol_hasher.borrow_mut();
533     let hash = symbol_hash(ccx.tcx, symbol_hasher.get(), t, &ccx.link_meta);
534     type_hashcodes.get().insert(t, hash);
535     hash
536 }
537
538
539 // Name sanitation. LLVM will happily accept identifiers with weird names, but
540 // gas doesn't!
541 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
542 pub fn sanitize(s: &str) -> ~str {
543     let mut result = ~"";
544     for c in s.chars() {
545         match c {
546             // Escape these with $ sequences
547             '@' => result.push_str("$SP$"),
548             '~' => result.push_str("$UP$"),
549             '*' => result.push_str("$RP$"),
550             '&' => result.push_str("$BP$"),
551             '<' => result.push_str("$LT$"),
552             '>' => result.push_str("$GT$"),
553             '(' => result.push_str("$LP$"),
554             ')' => result.push_str("$RP$"),
555             ',' => result.push_str("$C$"),
556
557             // '.' doesn't occur in types and functions, so reuse it
558             // for ':' and '-'
559             '-' | ':' => result.push_char('.'),
560
561             // These are legal symbols
562             'a' .. 'z'
563             | 'A' .. 'Z'
564             | '0' .. '9'
565             | '_' | '.' | '$' => result.push_char(c),
566
567             _ => {
568                 let mut tstr = ~"";
569                 char::escape_unicode(c, |c| tstr.push_char(c));
570                 result.push_char('$');
571                 result.push_str(tstr.slice_from(1));
572             }
573         }
574     }
575
576     // Underscore-qualify anything that didn't start as an ident.
577     if result.len() > 0u &&
578         result[0] != '_' as u8 &&
579         ! char::is_XID_start(result[0] as char) {
580         return ~"_" + result;
581     }
582
583     return result;
584 }
585
586 pub fn mangle(sess: Session, ss: ast_map::Path,
587               hash: Option<&str>, vers: Option<&str>) -> ~str {
588     // Follow C++ namespace-mangling style, see
589     // http://en.wikipedia.org/wiki/Name_mangling for more info.
590     //
591     // It turns out that on OSX you can actually have arbitrary symbols in
592     // function names (at least when given to LLVM), but this is not possible
593     // when using unix's linker. Perhaps one day when we just use a linker from LLVM
594     // we won't need to do this name mangling. The problem with name mangling is
595     // that it seriously limits the available characters. For example we can't
596     // have things like @T or ~[T] in symbol names when one would theoretically
597     // want them for things like impls of traits on that type.
598     //
599     // To be able to work on all platforms and get *some* reasonable output, we
600     // use C++ name-mangling.
601
602     let mut n = ~"_ZN"; // _Z == Begin name-sequence, N == nested
603
604     let push = |s: &str| {
605         let sani = sanitize(s);
606         n.push_str(format!("{}{}", sani.len(), sani));
607     };
608
609     // First, connect each component with <len, name> pairs.
610     for s in ss.iter() {
611         match *s {
612             PathName(s) | PathMod(s) | PathPrettyName(s, _) => {
613                 push(sess.str_of(s))
614             }
615         }
616     }
617
618     // next, if any identifiers are "pretty" and need extra information tacked
619     // on, then use the hash to generate two unique characters. For now
620     // hopefully 2 characters is enough to avoid collisions.
621     static EXTRA_CHARS: &'static str =
622         "abcdefghijklmnopqrstuvwxyz\
623          ABCDEFGHIJKLMNOPQRSTUVWXYZ\
624          0123456789";
625     let mut hash = match hash { Some(s) => s.to_owned(), None => ~"" };
626     for s in ss.iter() {
627         match *s {
628             PathPrettyName(_, extra) => {
629                 let hi = (extra >> 32) as u32 as uint;
630                 let lo = extra as u32 as uint;
631                 hash.push_char(EXTRA_CHARS[hi % EXTRA_CHARS.len()] as char);
632                 hash.push_char(EXTRA_CHARS[lo % EXTRA_CHARS.len()] as char);
633             }
634             _ => {}
635         }
636     }
637     if hash.len() > 0 {
638         push(hash);
639     }
640     match vers {
641         Some(s) => push(s),
642         None => {}
643     }
644
645     n.push_char('E'); // End name-sequence.
646     n
647 }
648
649 pub fn exported_name(sess: Session,
650                      path: ast_map::Path,
651                      hash: &str,
652                      vers: &str) -> ~str {
653     // The version will get mangled to have a leading '_', but it makes more
654     // sense to lead with a 'v' b/c this is a version...
655     let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
656         "v" + vers
657     } else {
658         vers.to_owned()
659     };
660
661     mangle(sess, path, Some(hash), Some(vers.as_slice()))
662 }
663
664 pub fn mangle_exported_name(ccx: &CrateContext,
665                             path: ast_map::Path,
666                             t: ty::t) -> ~str {
667     let hash = get_symbol_hash(ccx, t);
668     return exported_name(ccx.sess, path,
669                          hash,
670                          ccx.link_meta.crateid.version_or_default());
671 }
672
673 pub fn mangle_internal_name_by_type_only(ccx: &CrateContext,
674                                          t: ty::t,
675                                          name: &str) -> ~str {
676     let s = ppaux::ty_to_short_str(ccx.tcx, t);
677     let hash = get_symbol_hash(ccx, t);
678     return mangle(ccx.sess,
679                   ~[PathName(ccx.sess.ident_of(name)),
680                     PathName(ccx.sess.ident_of(s))],
681                   Some(hash.as_slice()),
682                   None);
683 }
684
685 pub fn mangle_internal_name_by_type_and_seq(ccx: &CrateContext,
686                                             t: ty::t,
687                                             name: &str) -> ~str {
688     let s = ppaux::ty_to_str(ccx.tcx, t);
689     let hash = get_symbol_hash(ccx, t);
690     let (_, name) = gensym_name(name);
691     return mangle(ccx.sess,
692                   ~[PathName(ccx.sess.ident_of(s)), name],
693                   Some(hash.as_slice()),
694                   None);
695 }
696
697 pub fn mangle_internal_name_by_path_and_seq(ccx: &CrateContext,
698                                             mut path: ast_map::Path,
699                                             flav: &str) -> ~str {
700     let (_, name) = gensym_name(flav);
701     path.push(name);
702     mangle(ccx.sess, path, None, None)
703 }
704
705 pub fn mangle_internal_name_by_path(ccx: &CrateContext,
706                                     path: ast_map::Path) -> ~str {
707     mangle(ccx.sess, path, None, None)
708 }
709
710 pub fn output_lib_filename(lm: &LinkMeta) -> ~str {
711     format!("{}-{}-{}",
712             lm.crateid.name,
713             lm.crate_hash.slice_chars(0, 8),
714             lm.crateid.version_or_default())
715 }
716
717 pub fn get_cc_prog(sess: Session) -> ~str {
718     match sess.opts.linker {
719         Some(ref linker) => return linker.to_owned(),
720         None => {}
721     }
722
723     // In the future, FreeBSD will use clang as default compiler.
724     // It would be flexible to use cc (system's default C compiler)
725     // instead of hard-coded gcc.
726     // For win32, there is no cc command, so we add a condition to make it use gcc.
727     match sess.targ_cfg.os {
728         abi::OsWin32 => return ~"gcc",
729         _ => {},
730     }
731
732     get_system_tool(sess, "cc")
733 }
734
735 pub fn get_ar_prog(sess: Session) -> ~str {
736     match sess.opts.ar {
737         Some(ref ar) => return ar.to_owned(),
738         None => {}
739     }
740
741     get_system_tool(sess, "ar")
742 }
743
744 fn get_system_tool(sess: Session, tool: &str) -> ~str {
745     match sess.targ_cfg.os {
746         abi::OsAndroid => match sess.opts.android_cross_path {
747             Some(ref path) => {
748                 let tool_str = match tool {
749                     "cc" => "gcc",
750                     _ => tool
751                 };
752                 format!("{}/bin/arm-linux-androideabi-{}", *path, tool_str)
753             }
754             None => {
755                 sess.fatal(format!("need Android NDK path for the '{}' tool \
756                                     (--android-cross-path)", tool))
757             }
758         },
759         _ => tool.to_owned(),
760     }
761 }
762
763 /// Perform the linkage portion of the compilation phase. This will generate all
764 /// of the requested outputs for this compilation session.
765 pub fn link_binary(sess: Session,
766                    trans: &CrateTranslation,
767                    obj_filename: &Path,
768                    out_filename: &Path,
769                    lm: &LinkMeta) -> ~[Path] {
770     let mut out_filenames = ~[];
771     let outputs = sess.outputs.borrow();
772     for &output in outputs.get().iter() {
773         let out_file = link_binary_output(sess, trans, output, obj_filename,
774                                           out_filename, lm);
775         out_filenames.push(out_file);
776     }
777
778     // Remove the temporary object file and metadata if we aren't saving temps
779     if !sess.opts.save_temps {
780         fs::unlink(obj_filename);
781         fs::unlink(&obj_filename.with_extension("metadata.o"));
782     }
783
784     out_filenames
785 }
786
787 fn is_writeable(p: &Path) -> bool {
788     use std::io;
789
790     match io::result(|| p.stat()) {
791         Err(..) => true,
792         Ok(m) => m.perm & io::UserWrite == io::UserWrite
793     }
794 }
795
796 pub fn filename_for_input(sess: &Session, output: session::OutputStyle, lm: &LinkMeta,
797                       out_filename: &Path) -> Path {
798     let libname = output_lib_filename(lm);
799     match output {
800         session::OutputRlib => {
801             out_filename.with_filename(format!("lib{}.rlib", libname))
802         }
803         session::OutputDylib => {
804             let (prefix, suffix) = match sess.targ_cfg.os {
805                 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
806                 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
807                 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
808                 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
809                 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
810             };
811             out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
812         }
813         session::OutputStaticlib => {
814             out_filename.with_filename(format!("lib{}.a", libname))
815         }
816         session::OutputExecutable => out_filename.clone(),
817     }
818
819 }
820
821 fn link_binary_output(sess: Session,
822                       trans: &CrateTranslation,
823                       output: session::OutputStyle,
824                       obj_filename: &Path,
825                       out_filename: &Path,
826                       lm: &LinkMeta) -> Path {
827     let out_filename = filename_for_input(&sess, output, lm, out_filename);
828
829     // Make sure the output and obj_filename are both writeable.
830     // Mac, FreeBSD, and Windows system linkers check this already --
831     // however, the Linux linker will happily overwrite a read-only file.
832     // We should be consistent.
833     let obj_is_writeable = is_writeable(obj_filename);
834     let out_is_writeable = is_writeable(&out_filename);
835     if !out_is_writeable {
836         sess.fatal(format!("Output file {} is not writeable -- check its permissions.",
837                            out_filename.display()));
838     }
839     else if !obj_is_writeable {
840         sess.fatal(format!("Object file {} is not writeable -- check its permissions.",
841                            obj_filename.display()));
842     }
843
844     match output {
845         session::OutputRlib => {
846             link_rlib(sess, Some(trans), obj_filename, &out_filename);
847         }
848         session::OutputStaticlib => {
849             link_staticlib(sess, obj_filename, &out_filename);
850         }
851         session::OutputExecutable => {
852             link_natively(sess, false, obj_filename, &out_filename);
853         }
854         session::OutputDylib => {
855             link_natively(sess, true, obj_filename, &out_filename);
856         }
857     }
858
859     out_filename
860 }
861
862 // Create an 'rlib'
863 //
864 // An rlib in its current incarnation is essentially a renamed .a file. The
865 // rlib primarily contains the object file of the crate, but it also contains
866 // all of the object files from native libraries. This is done by unzipping
867 // native libraries and inserting all of the contents into this archive.
868 fn link_rlib(sess: Session,
869              trans: Option<&CrateTranslation>, // None == no metadata/bytecode
870              obj_filename: &Path,
871              out_filename: &Path) -> Archive {
872     let mut a = Archive::create(sess, out_filename, obj_filename);
873
874     let used_libraries = sess.cstore.get_used_libraries();
875     let used_libraries = used_libraries.borrow();
876     for &(ref l, kind) in used_libraries.get().iter() {
877         match kind {
878             cstore::NativeStatic => {
879                 a.add_native_library(l.as_slice());
880             }
881             cstore::NativeFramework | cstore::NativeUnknown => {}
882         }
883     }
884
885     // Note that it is important that we add all of our non-object "magical
886     // files" *after* all of the object files in the archive. The reason for
887     // this is as follows:
888     //
889     // * When performing LTO, this archive will be modified to remove
890     //   obj_filename from above. The reason for this is described below.
891     //
892     // * When the system linker looks at an archive, it will attempt to
893     //   determine the architecture of the archive in order to see whether its
894     //   linkable.
895     //
896     //   The algorithm for this detection is: iterate over the files in the
897     //   archive. Skip magical SYMDEF names. Interpret the first file as an
898     //   object file. Read architecture from the object file.
899     //
900     // * As one can probably see, if "metadata" and "foo.bc" were placed
901     //   before all of the objects, then the architecture of this archive would
902     //   not be correctly inferred once 'foo.o' is removed.
903     //
904     // Basically, all this means is that this code should not move above the
905     // code above.
906     match trans {
907         Some(trans) => {
908             // Instead of putting the metadata in an object file section, rlibs
909             // contain the metadata in a separate file. We use a temp directory
910             // here so concurrent builds in the same directory don't try to use
911             // the same filename for metadata (stomping over one another)
912             let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
913             let metadata = tmpdir.path().join(METADATA_FILENAME);
914             fs::File::create(&metadata).write(trans.metadata);
915             a.add_file(&metadata, false);
916             fs::unlink(&metadata);
917
918             // For LTO purposes, the bytecode of this library is also inserted
919             // into the archive.
920             let bc = obj_filename.with_extension("bc");
921             a.add_file(&bc, false);
922             if !sess.opts.save_temps {
923                 fs::unlink(&bc);
924             }
925
926             // After adding all files to the archive, we need to update the
927             // symbol table of the archive. This currently dies on OSX (see
928             // #11162), and isn't necessary there anyway
929             match sess.targ_cfg.os {
930                 abi::OsMacos => {}
931                 _ => { a.update_symbols(); }
932             }
933         }
934
935         None => {}
936     }
937     return a;
938 }
939
940 // Create a static archive
941 //
942 // This is essentially the same thing as an rlib, but it also involves adding
943 // all of the upstream crates' objects into the archive. This will slurp in
944 // all of the native libraries of upstream dependencies as well.
945 //
946 // Additionally, there's no way for us to link dynamic libraries, so we warn
947 // about all dynamic library dependencies that they're not linked in.
948 //
949 // There's no need to include metadata in a static archive, so ensure to not
950 // link in the metadata object file (and also don't prepare the archive with a
951 // metadata file).
952 fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
953     let mut a = link_rlib(sess, None, obj_filename, out_filename);
954     a.add_native_library("morestack");
955
956     let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
957     for &(cnum, ref path) in crates.iter() {
958         let name = sess.cstore.get_crate_data(cnum).name;
959         let p = match *path {
960             Some(ref p) => p.clone(), None => {
961                 sess.err(format!("could not find rlib for: `{}`", name));
962                 continue
963             }
964         };
965         a.add_rlib(&p, name, sess.lto());
966         let native_libs = csearch::get_native_libraries(sess.cstore, cnum);
967         for &(kind, ref lib) in native_libs.iter() {
968             let name = match kind {
969                 cstore::NativeStatic => "static library",
970                 cstore::NativeUnknown => "library",
971                 cstore::NativeFramework => "framework",
972             };
973             sess.warn(format!("unlinked native {}: {}", name, *lib));
974         }
975     }
976 }
977
978 // Create a dynamic library or executable
979 //
980 // This will invoke the system linker/cc to create the resulting file. This
981 // links to all upstream files as well.
982 fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
983                  out_filename: &Path) {
984     let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
985     // The invocations of cc share some flags across platforms
986     let cc_prog = get_cc_prog(sess);
987     let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
988     cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
989                                     obj_filename, out_filename));
990     if (sess.opts.debugging_opts & session::PRINT_LINK_ARGS) != 0 {
991         println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
992     }
993
994     // May have not found libraries in the right formats.
995     sess.abort_if_errors();
996
997     // Invoke the system linker
998     debug!("{} {}", cc_prog, cc_args.connect(" "));
999     let opt_prog = {
1000         let _guard = io::ignore_io_error();
1001         time(sess.time_passes(), "running linker", (), |()|
1002              run::process_output(cc_prog, cc_args))
1003     };
1004
1005     match opt_prog {
1006         Some(prog) => {
1007             if !prog.status.success() {
1008                 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
1009                 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
1010                 sess.note(str::from_utf8_owned(prog.error + prog.output).unwrap());
1011                 sess.abort_if_errors();
1012             }
1013         },
1014         None => {
1015             sess.err(format!("could not exec the linker `{}`", cc_prog));
1016             sess.abort_if_errors();
1017         }
1018     }
1019
1020
1021     // On OSX, debuggers need this utility to get run to do some munging of
1022     // the symbols
1023     if sess.targ_cfg.os == abi::OsMacos && sess.opts.debuginfo {
1024         // FIXME (#9639): This needs to handle non-utf8 paths
1025         run::process_status("dsymutil",
1026                             [out_filename.as_str().unwrap().to_owned()]);
1027     }
1028 }
1029
1030 fn link_args(sess: Session,
1031              dylib: bool,
1032              tmpdir: &Path,
1033              obj_filename: &Path,
1034              out_filename: &Path) -> ~[~str] {
1035
1036     // The default library location, we need this to find the runtime.
1037     // The location of crates will be determined as needed.
1038     // FIXME (#9639): This needs to handle non-utf8 paths
1039     let lib_path = sess.filesearch.get_target_lib_path();
1040     let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
1041
1042     let mut args = ~[stage];
1043
1044     // FIXME (#9639): This needs to handle non-utf8 paths
1045     args.push_all([
1046         ~"-o", out_filename.as_str().unwrap().to_owned(),
1047         obj_filename.as_str().unwrap().to_owned()]);
1048
1049     // When linking a dynamic library, we put the metadata into a section of the
1050     // executable. This metadata is in a separate object file from the main
1051     // object file, so we link that in here.
1052     if dylib {
1053         let metadata = obj_filename.with_extension("metadata.o");
1054         args.push(metadata.as_str().unwrap().to_owned());
1055     }
1056
1057     if sess.targ_cfg.os == abi::OsLinux {
1058         // GNU-style linkers will use this to omit linking to libraries which
1059         // don't actually fulfill any relocations, but only for libraries which
1060         // follow this flag. Thus, use it before specifying libraries to link to.
1061         args.push(~"-Wl,--as-needed");
1062
1063         // GNU-style linkers support optimization with -O. --gc-sections
1064         // removes metadata and potentially other useful things, so don't
1065         // include it. GNU ld doesn't need a numeric argument, but other linkers
1066         // do.
1067         if sess.opts.optimize == session::Default ||
1068            sess.opts.optimize == session::Aggressive {
1069             args.push(~"-Wl,-O1");
1070         }
1071     }
1072
1073     if sess.targ_cfg.os == abi::OsWin32 {
1074         // Make sure that we link to the dynamic libgcc, otherwise cross-module
1075         // DWARF stack unwinding will not work.
1076         // This behavior may be overridden by --link-args "-static-libgcc"
1077         args.push(~"-shared-libgcc");
1078     }
1079
1080     add_local_native_libraries(&mut args, sess);
1081     add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1082     add_upstream_native_libraries(&mut args, sess);
1083
1084     // # Telling the linker what we're doing
1085
1086     if dylib {
1087         // On mac we need to tell the linker to let this library be rpathed
1088         if sess.targ_cfg.os == abi::OsMacos {
1089             args.push(~"-dynamiclib");
1090             args.push(~"-Wl,-dylib");
1091             // FIXME (#9639): This needs to handle non-utf8 paths
1092             args.push(~"-Wl,-install_name,@rpath/" +
1093                       out_filename.filename_str().unwrap());
1094         } else {
1095             args.push(~"-shared")
1096         }
1097     }
1098
1099     if sess.targ_cfg.os == abi::OsFreebsd {
1100         args.push_all([~"-L/usr/local/lib",
1101                        ~"-L/usr/local/lib/gcc46",
1102                        ~"-L/usr/local/lib/gcc44"]);
1103     }
1104
1105     // Stack growth requires statically linking a __morestack function
1106     args.push(~"-lmorestack");
1107
1108     // FIXME (#2397): At some point we want to rpath our guesses as to
1109     // where extern libraries might live, based on the
1110     // addl_lib_search_paths
1111     args.push_all(rpath::get_rpath_flags(sess, out_filename));
1112
1113     // Finally add all the linker arguments provided on the command line along
1114     // with any #[link_args] attributes found inside the crate
1115     args.push_all(sess.opts.linker_args);
1116     let used_link_args = sess.cstore.get_used_link_args();
1117     let used_link_args = used_link_args.borrow();
1118     for arg in used_link_args.get().iter() {
1119         args.push(arg.clone());
1120     }
1121     return args;
1122 }
1123
1124 // # Native library linking
1125 //
1126 // User-supplied library search paths (-L on the command line). These are
1127 // the same paths used to find Rust crates, so some of them may have been
1128 // added already by the previous crate linking code. This only allows them
1129 // to be found at compile time so it is still entirely up to outside
1130 // forces to make sure that library can be found at runtime.
1131 //
1132 // Also note that the native libraries linked here are only the ones located
1133 // in the current crate. Upstream crates with native library dependencies
1134 // may have their native library pulled in above.
1135 fn add_local_native_libraries(args: &mut ~[~str], sess: Session) {
1136     let addl_lib_search_paths = sess.opts.addl_lib_search_paths.borrow();
1137     for path in addl_lib_search_paths.get().iter() {
1138         // FIXME (#9639): This needs to handle non-utf8 paths
1139         args.push("-L" + path.as_str().unwrap().to_owned());
1140     }
1141
1142     let rustpath = filesearch::rust_path();
1143     for path in rustpath.iter() {
1144         // FIXME (#9639): This needs to handle non-utf8 paths
1145         args.push("-L" + path.as_str().unwrap().to_owned());
1146     }
1147
1148     let used_libraries = sess.cstore.get_used_libraries();
1149     let used_libraries = used_libraries.borrow();
1150     for &(ref l, kind) in used_libraries.get().iter() {
1151         match kind {
1152             cstore::NativeUnknown | cstore::NativeStatic => {
1153                 args.push("-l" + *l);
1154             }
1155             cstore::NativeFramework => {
1156                 args.push(~"-framework");
1157                 args.push(l.to_owned());
1158             }
1159         }
1160     }
1161 }
1162
1163 // # Rust Crate linking
1164 //
1165 // Rust crates are not considered at all when creating an rlib output. All
1166 // dependencies will be linked when producing the final output (instead of
1167 // the intermediate rlib version)
1168 fn add_upstream_rust_crates(args: &mut ~[~str], sess: Session,
1169                             dylib: bool, tmpdir: &Path) {
1170     // Converts a library file-stem into a cc -l argument
1171     fn unlib(config: @session::Config, stem: &str) -> ~str {
1172         if stem.starts_with("lib") &&
1173             config.os != abi::OsWin32 {
1174             stem.slice(3, stem.len()).to_owned()
1175         } else {
1176             stem.to_owned()
1177         }
1178     }
1179
1180     let cstore = sess.cstore;
1181     if !dylib && !sess.prefer_dynamic() {
1182         // With an executable, things get a little interesting. As a limitation
1183         // of the current implementation, we require that everything must be
1184         // static or everything must be dynamic. The reasons for this are a
1185         // little subtle, but as with the above two cases, the goal is to
1186         // prevent duplicate copies of the same library showing up. For example,
1187         // a static immediate dependency might show up as an upstream dynamic
1188         // dependency and we currently have no way of knowing that. We know that
1189         // all dynamic libraries require dynamic dependencies (see above), so
1190         // it's satisfactory to include either all static libraries or all
1191         // dynamic libraries.
1192         let crates = cstore.get_used_crates(cstore::RequireStatic);
1193         if crates.iter().all(|&(_, ref p)| p.is_some()) {
1194             for (cnum, path) in crates.move_iter() {
1195                 let cratepath = path.unwrap();
1196
1197                 // When performing LTO on an executable output, all of the
1198                 // bytecode from the upstream libraries has already been
1199                 // included in our object file output. We need to modify all of
1200                 // the upstream archives to remove their corresponding object
1201                 // file to make sure we don't pull the same code in twice.
1202                 //
1203                 // We must continue to link to the upstream archives to be sure
1204                 // to pull in native static dependencies. As the final caveat,
1205                 // on linux it is apparently illegal to link to a blank archive,
1206                 // so if an archive no longer has any object files in it after
1207                 // we remove `lib.o`, then don't link against it at all.
1208                 //
1209                 // If we're not doing LTO, then our job is simply to just link
1210                 // against the archive.
1211                 if sess.lto() {
1212                     let name = sess.cstore.get_crate_data(cnum).name;
1213                     time(sess.time_passes(), format!("altering {}.rlib", name),
1214                          (), |()| {
1215                         let dst = tmpdir.join(cratepath.filename().unwrap());
1216                         fs::copy(&cratepath, &dst);
1217                         let dst_str = dst.as_str().unwrap().to_owned();
1218                         let mut archive = Archive::open(sess, dst);
1219                         archive.remove_file(format!("{}.o", name));
1220                         let files = archive.files();
1221                         if files.iter().any(|s| s.ends_with(".o")) {
1222                             args.push(dst_str);
1223                         }
1224                     });
1225                 } else {
1226                     args.push(cratepath.as_str().unwrap().to_owned());
1227                 }
1228             }
1229             return;
1230         }
1231     }
1232
1233     // If we're performing LTO, then it should have been previously required
1234     // that all upstream rust dependencies were available in an rlib format.
1235     assert!(!sess.lto());
1236
1237     // This is a fallback of three different  cases of linking:
1238     //
1239     // * When creating a dynamic library, all inputs are required to be dynamic
1240     //   as well
1241     // * If an executable is created with a preference on dynamic linking, then
1242     //   this case is the fallback
1243     // * If an executable is being created, and one of the inputs is missing as
1244     //   a static library, then this is the fallback case.
1245     let crates = cstore.get_used_crates(cstore::RequireDynamic);
1246     for &(cnum, ref path) in crates.iter() {
1247         let cratepath = match *path {
1248             Some(ref p) => p.clone(),
1249             None => {
1250                 sess.err(format!("could not find dynamic library for: `{}`",
1251                                  sess.cstore.get_crate_data(cnum).name));
1252                 return
1253             }
1254         };
1255         // Just need to tell the linker about where the library lives and what
1256         // its name is
1257         let dir = cratepath.dirname_str().unwrap();
1258         if !dir.is_empty() { args.push("-L" + dir); }
1259         let libarg = unlib(sess.targ_cfg, cratepath.filestem_str().unwrap());
1260         args.push("-l" + libarg);
1261     }
1262 }
1263
1264 // Link in all of our upstream crates' native dependencies. Remember that
1265 // all of these upstream native depenencies are all non-static
1266 // dependencies. We've got two cases then:
1267 //
1268 // 1. The upstream crate is an rlib. In this case we *must* link in the
1269 //    native dependency because the rlib is just an archive.
1270 //
1271 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1272 //    have the dependency present on the system somewhere. Thus, we don't
1273 //    gain a whole lot from not linking in the dynamic dependency to this
1274 //    crate as well.
1275 //
1276 // The use case for this is a little subtle. In theory the native
1277 // dependencies of a crate a purely an implementation detail of the crate
1278 // itself, but the problem arises with generic and inlined functions. If a
1279 // generic function calls a native function, then the generic function must
1280 // be instantiated in the target crate, meaning that the native symbol must
1281 // also be resolved in the target crate.
1282 fn add_upstream_native_libraries(args: &mut ~[~str], sess: Session) {
1283     let cstore = sess.cstore;
1284     cstore.iter_crate_data(|cnum, _| {
1285         let libs = csearch::get_native_libraries(cstore, cnum);
1286         for &(kind, ref lib) in libs.iter() {
1287             match kind {
1288                 cstore::NativeUnknown => args.push("-l" + *lib),
1289                 cstore::NativeFramework => {
1290                     args.push(~"-framework");
1291                     args.push(lib.to_owned());
1292                 }
1293                 cstore::NativeStatic => {
1294                     sess.bug("statics shouldn't be propagated");
1295                 }
1296             }
1297         }
1298     });
1299 }