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