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