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