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