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