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