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