]> git.lizzy.rs Git - rust.git/blob - src/librustc/back/link.rs
1331067c956eb11a9a697d6ca8d43668bedd53ab
[rust.git] / src / librustc / back / link.rs
1 // Copyright 2012-2013 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
12 use back::archive::{Archive, METADATA_FILENAME};
13 use back::rpath;
14 use back::manifest;
15 use driver::driver::CrateTranslation;
16 use driver::session::Session;
17 use driver::session;
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};
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;
31 use std::char;
32 use std::os::consts::{macos, freebsd, linux, android, win32};
33 use std::ptr;
34 use std::run;
35 use std::str;
36 use std::io;
37 use std::io::fs;
38 use extra::tempfile::TempDir;
39 use syntax::abi;
40 use syntax::ast;
41 use syntax::ast_map::{path, path_mod, path_name, path_pretty_name};
42 use syntax::attr;
43 use syntax::attr::AttrMetaMethods;
44 use syntax::pkgid::PkgId;
45
46 #[deriving(Clone, Eq)]
47 pub enum output_type {
48     output_type_none,
49     output_type_bitcode,
50     output_type_assembly,
51     output_type_llvm_assembly,
52     output_type_object,
53     output_type_exe,
54 }
55
56 pub fn llvm_err(sess: Session, msg: ~str) -> ! {
57     unsafe {
58         let cstr = llvm::LLVMRustGetLastError();
59         if cstr == ptr::null() {
60             sess.fatal(msg);
61         } else {
62             sess.fatal(msg + ": " + str::raw::from_c_str(cstr));
63         }
64     }
65 }
66
67 pub fn WriteOutputFile(
68         sess: Session,
69         Target: lib::llvm::TargetMachineRef,
70         PM: lib::llvm::PassManagerRef,
71         M: ModuleRef,
72         Output: &Path,
73         FileType: lib::llvm::FileType) {
74     unsafe {
75         Output.with_c_str(|Output| {
76             let result = llvm::LLVMRustWriteOutputFile(
77                     Target, PM, M, Output, FileType);
78             if !result {
79                 llvm_err(sess, ~"Could not write output");
80             }
81         })
82     }
83 }
84
85 pub mod write {
86
87     use back::lto;
88     use back::link::{WriteOutputFile, output_type};
89     use back::link::{output_type_assembly, output_type_bitcode};
90     use back::link::{output_type_exe, output_type_llvm_assembly};
91     use back::link::{output_type_object};
92     use driver::driver::CrateTranslation;
93     use driver::session::Session;
94     use driver::session;
95     use lib::llvm::llvm;
96     use lib::llvm::{ModuleRef, TargetMachineRef, PassManagerRef};
97     use lib;
98     use util::common::time;
99
100     use std::c_str::ToCStr;
101     use std::io;
102     use std::libc::{c_uint, c_int};
103     use std::path::Path;
104     use std::run;
105     use std::str;
106
107     pub fn run_passes(sess: Session,
108                       trans: &CrateTranslation,
109                       output_type: output_type,
110                       output: &Path) {
111         let llmod = trans.module;
112         let llcx = trans.context;
113         unsafe {
114             llvm::LLVMInitializePasses();
115
116             // Only initialize the platforms supported by Rust here, because
117             // using --llvm-root will have multiple platforms that rustllvm
118             // doesn't actually link to and it's pointless to put target info
119             // into the registry that Rust can not generate machine code for.
120             llvm::LLVMInitializeX86TargetInfo();
121             llvm::LLVMInitializeX86Target();
122             llvm::LLVMInitializeX86TargetMC();
123             llvm::LLVMInitializeX86AsmPrinter();
124             llvm::LLVMInitializeX86AsmParser();
125
126             llvm::LLVMInitializeARMTargetInfo();
127             llvm::LLVMInitializeARMTarget();
128             llvm::LLVMInitializeARMTargetMC();
129             llvm::LLVMInitializeARMAsmPrinter();
130             llvm::LLVMInitializeARMAsmParser();
131
132             llvm::LLVMInitializeMipsTargetInfo();
133             llvm::LLVMInitializeMipsTarget();
134             llvm::LLVMInitializeMipsTargetMC();
135             llvm::LLVMInitializeMipsAsmPrinter();
136             llvm::LLVMInitializeMipsAsmParser();
137
138             if sess.opts.save_temps {
139                 output.with_extension("no-opt.bc").with_c_str(|buf| {
140                     llvm::LLVMWriteBitcodeToFile(llmod, buf);
141                 })
142             }
143
144             configure_llvm(sess);
145
146             let OptLevel = match sess.opts.optimize {
147               session::No => lib::llvm::CodeGenLevelNone,
148               session::Less => lib::llvm::CodeGenLevelLess,
149               session::Default => lib::llvm::CodeGenLevelDefault,
150               session::Aggressive => lib::llvm::CodeGenLevelAggressive,
151             };
152             let use_softfp = sess.opts.debugging_opts & session::use_softfp != 0;
153
154             let tm = sess.targ_cfg.target_strs.target_triple.with_c_str(|T| {
155                 sess.opts.target_cpu.with_c_str(|CPU| {
156                     sess.opts.target_feature.with_c_str(|Features| {
157                         llvm::LLVMRustCreateTargetMachine(
158                             T, CPU, Features,
159                             lib::llvm::CodeModelDefault,
160                             lib::llvm::RelocPIC,
161                             OptLevel,
162                             true,
163                             use_softfp
164                         )
165                     })
166                 })
167             });
168
169             // Create the two optimizing pass managers. These mirror what clang
170             // does, and are by populated by LLVM's default PassManagerBuilder.
171             // Each manager has a different set of passes, but they also share
172             // some common passes.
173             let fpm = llvm::LLVMCreateFunctionPassManagerForModule(llmod);
174             let mpm = llvm::LLVMCreatePassManager();
175
176             // If we're verifying or linting, add them to the function pass
177             // manager.
178             let addpass = |pass: &str| {
179                 pass.with_c_str(|s| llvm::LLVMRustAddPass(fpm, s))
180             };
181             if !sess.no_verify() { assert!(addpass("verify")); }
182             if sess.lint_llvm()  { assert!(addpass("lint"));   }
183
184             if !sess.no_prepopulate_passes() {
185                 llvm::LLVMRustAddAnalysisPasses(tm, fpm, llmod);
186                 llvm::LLVMRustAddAnalysisPasses(tm, mpm, llmod);
187                 populate_llvm_passes(fpm, mpm, llmod, OptLevel);
188             }
189
190             for pass in sess.opts.custom_passes.iter() {
191                 pass.with_c_str(|s| {
192                     if !llvm::LLVMRustAddPass(mpm, s) {
193                         sess.warn(format!("Unknown pass {}, ignoring", *pass));
194                     }
195                 })
196             }
197
198             // Finally, run the actual optimization passes
199             time(sess.time_passes(), "llvm function passes", (), |()|
200                  llvm::LLVMRustRunFunctionPassManager(fpm, llmod));
201             time(sess.time_passes(), "llvm module passes", (), |()|
202                  llvm::LLVMRunPassManager(mpm, llmod));
203
204             // Deallocate managers that we're now done with
205             llvm::LLVMDisposePassManager(fpm);
206             llvm::LLVMDisposePassManager(mpm);
207
208             // Emit the bytecode if we're either saving our temporaries or
209             // emitting an rlib. Whenever an rlib is create, the bytecode is
210             // inserted into the archive in order to allow LTO against it.
211             if sess.opts.save_temps ||
212                sess.outputs.iter().any(|&o| o == session::OutputRlib) {
213                 output.with_extension("bc").with_c_str(|buf| {
214                     llvm::LLVMWriteBitcodeToFile(llmod, buf);
215                 })
216             }
217
218             if sess.lto() {
219                 time(sess.time_passes(), "all lto passes", (), |()|
220                      lto::run(sess, llmod, tm, trans.reachable));
221
222                 if sess.opts.save_temps {
223                     output.with_extension("lto.bc").with_c_str(|buf| {
224                         llvm::LLVMWriteBitcodeToFile(llmod, buf);
225                     })
226                 }
227             }
228
229             // A codegen-specific pass manager is used to generate object
230             // files for an LLVM module.
231             //
232             // Apparently each of these pass managers is a one-shot kind of
233             // thing, so we create a new one for each type of output. The
234             // pass manager passed to the closure should be ensured to not
235             // escape the closure itself, and the manager should only be
236             // used once.
237             fn with_codegen(tm: TargetMachineRef, llmod: ModuleRef,
238                             f: |PassManagerRef|) {
239                 unsafe {
240                     let cpm = llvm::LLVMCreatePassManager();
241                     llvm::LLVMRustAddAnalysisPasses(tm, cpm, llmod);
242                     llvm::LLVMRustAddLibraryInfo(cpm, llmod);
243                     f(cpm);
244                     llvm::LLVMDisposePassManager(cpm);
245                 }
246             }
247
248             time(sess.time_passes(), "codegen passes", (), |()| {
249                 match output_type {
250                     output_type_none => {}
251                     output_type_bitcode => {
252                         output.with_c_str(|buf| {
253                             llvm::LLVMWriteBitcodeToFile(llmod, buf);
254                         })
255                     }
256                     output_type_llvm_assembly => {
257                         output.with_c_str(|output| {
258                             with_codegen(tm, llmod, |cpm| {
259                                 llvm::LLVMRustPrintModule(cpm, llmod, output);
260                             })
261                         })
262                     }
263                     output_type_assembly => {
264                         with_codegen(tm, llmod, |cpm| {
265                             WriteOutputFile(sess, tm, cpm, llmod, output,
266                                             lib::llvm::AssemblyFile);
267                         });
268
269                         // If we're not using the LLVM assembler, this function
270                         // could be invoked specially with output_type_assembly,
271                         // so in this case we still want the metadata object
272                         // file.
273                         if sess.opts.output_type != output_type_assembly {
274                             with_codegen(tm, trans.metadata_module, |cpm| {
275                                 let out = output.with_extension("metadata.o");
276                                 WriteOutputFile(sess, tm, cpm,
277                                                 trans.metadata_module, &out,
278                                                 lib::llvm::ObjectFile);
279                             })
280                         }
281                     }
282                     output_type_exe | output_type_object => {
283                         with_codegen(tm, llmod, |cpm| {
284                             WriteOutputFile(sess, tm, cpm, llmod, output,
285                                             lib::llvm::ObjectFile);
286                         });
287                         with_codegen(tm, trans.metadata_module, |cpm| {
288                             let out = output.with_extension("metadata.o");
289                             WriteOutputFile(sess, tm, cpm,
290                                             trans.metadata_module, &out,
291                                             lib::llvm::ObjectFile);
292                         })
293                     }
294                 }
295             });
296
297             llvm::LLVMRustDisposeTargetMachine(tm);
298             llvm::LLVMDisposeModule(trans.metadata_module);
299             llvm::LLVMDisposeModule(llmod);
300             llvm::LLVMContextDispose(llcx);
301             if sess.time_llvm_passes() { llvm::LLVMRustPrintPassTimings(); }
302         }
303     }
304
305     pub fn run_assembler(sess: Session, assembly: &Path, object: &Path) {
306         let cc = super::get_cc_prog(sess);
307
308         // FIXME (#9639): This needs to handle non-utf8 paths
309         let args = [
310             ~"-c",
311             ~"-o", object.as_str().unwrap().to_owned(),
312             assembly.as_str().unwrap().to_owned()];
313
314         debug!("{} '{}'", cc, args.connect("' '"));
315         let opt_prog = {
316             let _guard = io::ignore_io_error();
317             run::process_output(cc, args)
318         };
319         match opt_prog {
320             Some(prog) => {
321                 if !prog.status.success() {
322                     sess.err(format!("linking with `{}` failed: {}", cc, prog.status));
323                     sess.note(format!("{} arguments: '{}'", cc, args.connect("' '")));
324                     sess.note(str::from_utf8_owned(prog.error + prog.output));
325                     sess.abort_if_errors();
326                 }
327             },
328             None => {
329                 sess.err(format!("could not exec the linker `{}`", cc));
330                 sess.abort_if_errors();
331             }
332         }
333     }
334
335     unsafe fn configure_llvm(sess: Session) {
336         // Copy what clan does by turning on loop vectorization at O2 and
337         // slp vectorization at O3
338         let vectorize_loop = !sess.no_vectorize_loops() &&
339                              (sess.opts.optimize == session::Default ||
340                               sess.opts.optimize == session::Aggressive);
341         let vectorize_slp = !sess.no_vectorize_slp() &&
342                             sess.opts.optimize == session::Aggressive;
343
344         let mut llvm_c_strs = ~[];
345         let mut llvm_args = ~[];
346         let add = |arg: &str| {
347             let s = arg.to_c_str();
348             llvm_args.push(s.with_ref(|p| p));
349             llvm_c_strs.push(s);
350         };
351         add("rustc"); // fake program name
352         add("-arm-enable-ehabi");
353         add("-arm-enable-ehabi-descriptors");
354         if vectorize_loop { add("-vectorize-loops"); }
355         if vectorize_slp  { add("-vectorize-slp");   }
356         if sess.time_llvm_passes() { add("-time-passes"); }
357         if sess.print_llvm_passes() { add("-debug-pass=Structure"); }
358
359         for arg in sess.opts.llvm_args.iter() {
360             add(*arg);
361         }
362
363         llvm_args.as_imm_buf(|p, len| {
364             llvm::LLVMRustSetLLVMOptions(len as c_int, p);
365         })
366     }
367
368     unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
369                                    mpm: lib::llvm::PassManagerRef,
370                                    llmod: ModuleRef,
371                                    opt: lib::llvm::CodeGenOptLevel) {
372         // Create the PassManagerBuilder for LLVM. We configure it with
373         // reasonable defaults and prepare it to actually populate the pass
374         // manager.
375         let builder = llvm::LLVMPassManagerBuilderCreate();
376         match opt {
377             lib::llvm::CodeGenLevelNone => {
378                 // Don't add lifetime intrinsics add O0
379                 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
380             }
381             lib::llvm::CodeGenLevelLess => {
382                 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
383             }
384             // numeric values copied from clang
385             lib::llvm::CodeGenLevelDefault => {
386                 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
387                                                                     225);
388             }
389             lib::llvm::CodeGenLevelAggressive => {
390                 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
391                                                                     275);
392             }
393         }
394         llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
395         llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
396
397         // Use the builder to populate the function/module pass managers.
398         llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
399         llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
400         llvm::LLVMPassManagerBuilderDispose(builder);
401     }
402 }
403
404
405 /*
406  * Name mangling and its relationship to metadata. This is complex. Read
407  * carefully.
408  *
409  * The semantic model of Rust linkage is, broadly, that "there's no global
410  * namespace" between crates. Our aim is to preserve the illusion of this
411  * model despite the fact that it's not *quite* possible to implement on
412  * modern linkers. We initially didn't use system linkers at all, but have
413  * been convinced of their utility.
414  *
415  * There are a few issues to handle:
416  *
417  *  - Linkers operate on a flat namespace, so we have to flatten names.
418  *    We do this using the C++ namespace-mangling technique. Foo::bar
419  *    symbols and such.
420  *
421  *  - Symbols with the same name but different types need to get different
422  *    linkage-names. We do this by hashing a string-encoding of the type into
423  *    a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
424  *    we use SHA256) to "prevent collisions". This is not airtight but 16 hex
425  *    digits on uniform probability means you're going to need 2**32 same-name
426  *    symbols in the same process before you're even hitting birthday-paradox
427  *    collision probability.
428  *
429  *  - Symbols in different crates but with same names "within" the crate need
430  *    to get different linkage-names.
431  *
432  *  - The hash shown in the filename needs to be predictable and stable for
433  *    build tooling integration. It also needs to be using a hash function
434  *    which is easy to use from Python, make, etc.
435  *
436  * So here is what we do:
437  *
438  *  - Consider the package id; every crate has one (specified with pkgid
439  *    attribute).  If a package id isn't provided explicitly, we infer a
440  *    versionless one from the output name. The version will end up being 0.0
441  *    in this case. CNAME and CVERS are taken from this package id. For
442  *    example, github.com/mozilla/CNAME#CVERS.
443  *
444  *  - Define CMH as SHA256(pkgid).
445  *
446  *  - Define CMH8 as the first 8 characters of CMH.
447  *
448  *  - Compile our crate to lib CNAME-CMH8-CVERS.so
449  *
450  *  - Define STH(sym) as SHA256(CMH, type_str(sym))
451  *
452  *  - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
453  *    name, non-name metadata, and type sense, and versioned in the way
454  *    system linkers understand.
455  */
456
457 pub fn build_link_meta(sess: Session,
458                        c: &ast::Crate,
459                        output: &Path,
460                        symbol_hasher: &mut Sha256)
461                        -> LinkMeta {
462     // This calculates CMH as defined above
463     fn crate_hash(symbol_hasher: &mut Sha256, pkgid: &PkgId) -> @str {
464         symbol_hasher.reset();
465         symbol_hasher.input_str(pkgid.to_str());
466         truncated_hash_result(symbol_hasher).to_managed()
467     }
468
469     let pkgid = match attr::find_pkgid(c.attrs) {
470         None => {
471             let stem = session::expect(
472                 sess,
473                 output.filestem_str(),
474                 || format!("output file name '{}' doesn't appear to have a stem",
475                            output.display()));
476             from_str(stem).unwrap()
477         }
478         Some(s) => s,
479     };
480
481     let hash = crate_hash(symbol_hasher, &pkgid);
482
483     LinkMeta {
484         pkgid: pkgid,
485         crate_hash: hash,
486     }
487 }
488
489 pub fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
490     symbol_hasher.result_str()
491 }
492
493
494 // This calculates STH for a symbol, as defined above
495 pub fn symbol_hash(tcx: ty::ctxt,
496                    symbol_hasher: &mut Sha256,
497                    t: ty::t,
498                    link_meta: &LinkMeta) -> @str {
499     // NB: do *not* use abbrevs here as we want the symbol names
500     // to be independent of one another in the crate.
501
502     symbol_hasher.reset();
503     symbol_hasher.input_str(link_meta.pkgid.name);
504     symbol_hasher.input_str("-");
505     symbol_hasher.input_str(link_meta.crate_hash);
506     symbol_hasher.input_str("-");
507     symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
508     let mut hash = truncated_hash_result(symbol_hasher);
509     // Prefix with 'h' so that it never blends into adjacent digits
510     hash.unshift_char('h');
511     // tjc: allocation is unfortunate; need to change std::hash
512     hash.to_managed()
513 }
514
515 pub fn get_symbol_hash(ccx: &mut CrateContext, t: ty::t) -> @str {
516     match ccx.type_hashcodes.find(&t) {
517       Some(&h) => h,
518       None => {
519         let hash = symbol_hash(ccx.tcx, &mut ccx.symbol_hasher, t, &ccx.link_meta);
520         ccx.type_hashcodes.insert(t, hash);
521         hash
522       }
523     }
524 }
525
526
527 // Name sanitation. LLVM will happily accept identifiers with weird names, but
528 // gas doesn't!
529 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
530 pub fn sanitize(s: &str) -> ~str {
531     let mut result = ~"";
532     for c in s.chars() {
533         match c {
534             // Escape these with $ sequences
535             '@' => result.push_str("$SP$"),
536             '~' => result.push_str("$UP$"),
537             '*' => result.push_str("$RP$"),
538             '&' => result.push_str("$BP$"),
539             '<' => result.push_str("$LT$"),
540             '>' => result.push_str("$GT$"),
541             '(' => result.push_str("$LP$"),
542             ')' => result.push_str("$RP$"),
543             ',' => result.push_str("$C$"),
544
545             // '.' doesn't occur in types and functions, so reuse it
546             // for ':' and '-'
547             '-' | ':' => result.push_char('.'),
548
549             // These are legal symbols
550             'a' .. 'z'
551             | 'A' .. 'Z'
552             | '0' .. '9'
553             | '_' | '.' | '$' => result.push_char(c),
554
555             _ => {
556                 let mut tstr = ~"";
557                 char::escape_unicode(c, |c| tstr.push_char(c));
558                 result.push_char('$');
559                 result.push_str(tstr.slice_from(1));
560             }
561         }
562     }
563
564     // Underscore-qualify anything that didn't start as an ident.
565     if result.len() > 0u &&
566         result[0] != '_' as u8 &&
567         ! char::is_XID_start(result[0] as char) {
568         return ~"_" + result;
569     }
570
571     return result;
572 }
573
574 pub fn mangle(sess: Session, ss: path,
575               hash: Option<&str>, vers: Option<&str>) -> ~str {
576     // Follow C++ namespace-mangling style, see
577     // http://en.wikipedia.org/wiki/Name_mangling for more info.
578     //
579     // It turns out that on OSX you can actually have arbitrary symbols in
580     // function names (at least when given to LLVM), but this is not possible
581     // when using unix's linker. Perhaps one day when we just a linker from LLVM
582     // we won't need to do this name mangling. The problem with name mangling is
583     // that it seriously limits the available characters. For example we can't
584     // have things like @T or ~[T] in symbol names when one would theoretically
585     // want them for things like impls of traits on that type.
586     //
587     // To be able to work on all platforms and get *some* reasonable output, we
588     // use C++ name-mangling.
589
590     let mut n = ~"_ZN"; // _Z == Begin name-sequence, N == nested
591
592     let push = |s: &str| {
593         let sani = sanitize(s);
594         n.push_str(format!("{}{}", sani.len(), sani));
595     };
596
597     // First, connect each component with <len, name> pairs.
598     for s in ss.iter() {
599         match *s {
600             path_name(s) | path_mod(s) | path_pretty_name(s, _) => {
601                 push(sess.str_of(s))
602             }
603         }
604     }
605
606     // next, if any identifiers are "pretty" and need extra information tacked
607     // on, then use the hash to generate two unique characters. For now
608     // hopefully 2 characters is enough to avoid collisions.
609     static EXTRA_CHARS: &'static str =
610         "abcdefghijklmnopqrstuvwxyz\
611          ABCDEFGHIJKLMNOPQRSTUVWXYZ\
612          0123456789";
613     let mut hash = match hash { Some(s) => s.to_owned(), None => ~"" };
614     for s in ss.iter() {
615         match *s {
616             path_pretty_name(_, extra) => {
617                 let hi = (extra >> 32) as u32 as uint;
618                 let lo = extra as u32 as uint;
619                 hash.push_char(EXTRA_CHARS[hi % EXTRA_CHARS.len()] as char);
620                 hash.push_char(EXTRA_CHARS[lo % EXTRA_CHARS.len()] as char);
621             }
622             _ => {}
623         }
624     }
625     if hash.len() > 0 {
626         push(hash);
627     }
628     match vers {
629         Some(s) => push(s),
630         None => {}
631     }
632
633     n.push_char('E'); // End name-sequence.
634     n
635 }
636
637 pub fn exported_name(sess: Session,
638                      path: path,
639                      hash: &str,
640                      vers: &str) -> ~str {
641     // The version will get mangled to have a leading '_', but it makes more
642     // sense to lead with a 'v' b/c this is a version...
643     let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
644         "v" + vers
645     } else {
646         vers.to_owned()
647     };
648
649     mangle(sess, path, Some(hash), Some(vers.as_slice()))
650 }
651
652 pub fn mangle_exported_name(ccx: &mut CrateContext,
653                             path: path,
654                             t: ty::t) -> ~str {
655     let hash = get_symbol_hash(ccx, t);
656     return exported_name(ccx.sess, path,
657                          hash,
658                          ccx.link_meta.pkgid.version_or_default());
659 }
660
661 pub fn mangle_internal_name_by_type_only(ccx: &mut CrateContext,
662                                          t: ty::t,
663                                          name: &str) -> ~str {
664     let s = ppaux::ty_to_short_str(ccx.tcx, t);
665     let hash = get_symbol_hash(ccx, t);
666     return mangle(ccx.sess,
667                   ~[path_name(ccx.sess.ident_of(name)),
668                     path_name(ccx.sess.ident_of(s))],
669                   Some(hash.as_slice()),
670                   None);
671 }
672
673 pub fn mangle_internal_name_by_type_and_seq(ccx: &mut CrateContext,
674                                             t: ty::t,
675                                             name: &str) -> ~str {
676     let s = ppaux::ty_to_str(ccx.tcx, t);
677     let hash = get_symbol_hash(ccx, t);
678     let (_, name) = gensym_name(name);
679     return mangle(ccx.sess,
680                   ~[path_name(ccx.sess.ident_of(s)), name],
681                   Some(hash.as_slice()),
682                   None);
683 }
684
685 pub fn mangle_internal_name_by_path_and_seq(ccx: &mut CrateContext,
686                                             mut path: path,
687                                             flav: &str) -> ~str {
688     let (_, name) = gensym_name(flav);
689     path.push(name);
690     mangle(ccx.sess, path, None, None)
691 }
692
693 pub fn mangle_internal_name_by_path(ccx: &mut CrateContext, path: path) -> ~str {
694     mangle(ccx.sess, path, None, None)
695 }
696
697 pub fn output_lib_filename(lm: &LinkMeta) -> ~str {
698     format!("{}-{}-{}",
699             lm.pkgid.name,
700             lm.crate_hash.slice_chars(0, 8),
701             lm.pkgid.version_or_default())
702 }
703
704 pub fn get_cc_prog(sess: Session) -> ~str {
705     match sess.opts.linker {
706         Some(ref linker) => return linker.to_owned(),
707         None => {}
708     }
709
710     // In the future, FreeBSD will use clang as default compiler.
711     // It would be flexible to use cc (system's default C compiler)
712     // instead of hard-coded gcc.
713     // For win32, there is no cc command, so we add a condition to make it use
714     // g++.  We use g++ rather than gcc because it automatically adds linker
715     // options required for generation of dll modules that correctly register
716     // stack unwind tables.
717     match sess.targ_cfg.os {
718         abi::OsAndroid => match sess.opts.android_cross_path {
719             Some(ref path) => format!("{}/bin/arm-linux-androideabi-gcc", *path),
720             None => {
721                 sess.fatal("need Android NDK path for linking \
722                             (--android-cross-path)")
723             }
724         },
725         abi::OsWin32 => ~"g++",
726         _ => ~"cc",
727     }
728 }
729
730 /// Perform the linkage portion of the compilation phase. This will generate all
731 /// of the requested outputs for this compilation session.
732 pub fn link_binary(sess: Session,
733                    trans: &CrateTranslation,
734                    obj_filename: &Path,
735                    out_filename: &Path,
736                    lm: &LinkMeta) -> ~[Path] {
737     let mut out_filenames = ~[];
738     for &output in sess.outputs.iter() {
739         let out_file = link_binary_output(sess, trans, output, obj_filename,
740                                           out_filename, lm);
741         out_filenames.push(out_file);
742     }
743
744     // Remove the temporary object file and metadata if we aren't saving temps
745     if !sess.opts.save_temps {
746         fs::unlink(obj_filename);
747         fs::unlink(&obj_filename.with_extension("metadata.o"));
748     }
749
750     out_filenames
751 }
752
753 fn is_writeable(p: &Path) -> bool {
754     use std::io;
755
756     match io::result(|| p.stat()) {
757         Err(..) => true,
758         Ok(m) => m.perm & io::UserWrite == io::UserWrite
759     }
760 }
761
762 fn link_binary_output(sess: Session,
763                       trans: &CrateTranslation,
764                       output: session::OutputStyle,
765                       obj_filename: &Path,
766                       out_filename: &Path,
767                       lm: &LinkMeta) -> Path {
768     let libname = output_lib_filename(lm);
769     let out_filename = match output {
770         session::OutputRlib => {
771             out_filename.with_filename(format!("lib{}.rlib", libname))
772         }
773         session::OutputDylib => {
774             let (prefix, suffix) = match sess.targ_cfg.os {
775                 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
776                 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
777                 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
778                 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
779                 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
780             };
781             out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
782         }
783         session::OutputStaticlib => {
784             out_filename.with_filename(format!("lib{}.a", libname))
785         }
786         session::OutputExecutable => out_filename.clone(),
787     };
788
789     // Make sure the output and obj_filename are both writeable.
790     // Mac, FreeBSD, and Windows system linkers check this already --
791     // however, the Linux linker will happily overwrite a read-only file.
792     // We should be consistent.
793     let obj_is_writeable = is_writeable(obj_filename);
794     let out_is_writeable = is_writeable(&out_filename);
795     if !out_is_writeable {
796         sess.fatal(format!("Output file {} is not writeable -- check its permissions.",
797                            out_filename.display()));
798     }
799     else if !obj_is_writeable {
800         sess.fatal(format!("Object file {} is not writeable -- check its permissions.",
801                            obj_filename.display()));
802     }
803
804     match output {
805         session::OutputRlib => {
806             link_rlib(sess, Some(trans), obj_filename, &out_filename);
807         }
808         session::OutputStaticlib => {
809             link_staticlib(sess, obj_filename, &out_filename);
810         }
811         session::OutputExecutable => {
812             link_natively(sess, false, obj_filename, &out_filename);
813             // Windows linker will add an ".exe" extension if there was none
814             let out_filename = match out_filename.extension() {
815                 Some(_) => out_filename.clone(),
816                 None => out_filename.with_extension(win32::EXE_EXTENSION)
817             };
818             manifest::postprocess_executable(sess, &out_filename);
819         }
820         session::OutputDylib => {
821             link_natively(sess, true, obj_filename, &out_filename);
822         }
823     }
824
825     out_filename
826 }
827
828 // Create an 'rlib'
829 //
830 // An rlib in its current incarnation is essentially a renamed .a file. The
831 // rlib primarily contains the object file of the crate, but it also contains
832 // all of the object files from native libraries. This is done by unzipping
833 // native libraries and inserting all of the contents into this archive.
834 fn link_rlib(sess: Session,
835              trans: Option<&CrateTranslation>, // None == no metadata/bytecode
836              obj_filename: &Path,
837              out_filename: &Path) -> Archive {
838     let mut a = Archive::create(sess, out_filename, obj_filename);
839
840     for &(ref l, kind) in cstore::get_used_libraries(sess.cstore).iter() {
841         match kind {
842             cstore::NativeStatic => {
843                 a.add_native_library(l.as_slice());
844             }
845             cstore::NativeFramework | cstore::NativeUnknown => {}
846         }
847     }
848
849     // Note that it is important that we add all of our non-object "magical
850     // files" *after* all of the object files in the archive. The reason for
851     // this is as follows:
852     //
853     // * When performing LTO, this archive will be modified to remove
854     //   obj_filename from above. The reason for this is described below.
855     //
856     // * When the system linker looks at an archive, it will attempt to
857     //   determine the architecture of the archive in order to see whether its
858     //   linkable.
859     //
860     //   The algorithm for this detections is: iterate over the files in the
861     //   archive. Skip magical SYMDEF names. Interpret the first file as an
862     //   object file. Read architecture from the object file.
863     //
864     // * As one can probably see, if "metadata" and "foo.bc" were placed
865     //   before all of the objects, then the architecture of this archive would
866     //   not be correctly inferred once 'foo.o' is removed.
867     //
868     // Basically, all this means is that this code should not move above the
869     // code above.
870     match trans {
871         Some(trans) => {
872             // Instead of putting the metadata in an object file section, rlibs
873             // contain the metadata in a separate file.
874             let metadata = obj_filename.with_filename(METADATA_FILENAME);
875             fs::File::create(&metadata).write(trans.metadata);
876             a.add_file(&metadata, false);
877             fs::unlink(&metadata);
878
879             // For LTO purposes, the bytecode of this library is also inserted
880             // into the archive.
881             let bc = obj_filename.with_extension("bc");
882             a.add_file(&bc, false);
883             if !sess.opts.save_temps {
884                 fs::unlink(&bc);
885             }
886
887             // Now that we've added files, some platforms need us to now update
888             // the symbol table in the archive (because some platforms die when
889             // adding files to the archive without symbols).
890             a.update_symbols();
891         }
892
893         None => {}
894     }
895     return a;
896 }
897
898 // Create a static archive
899 //
900 // This is essentially the same thing as an rlib, but it also involves adding
901 // all of the upstream crates' objects into the the archive. This will slurp in
902 // all of the native libraries of upstream dependencies as well.
903 //
904 // Additionally, there's no way for us to link dynamic libraries, so we warn
905 // about all dynamic library dependencies that they're not linked in.
906 //
907 // There's no need to include metadata in a static archive, so ensure to not
908 // link in the metadata object file (and also don't prepare the archive with a
909 // metadata file).
910 fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
911     let mut a = link_rlib(sess, None, obj_filename, out_filename);
912     a.add_native_library("morestack");
913
914     let crates = cstore::get_used_crates(sess.cstore, cstore::RequireStatic);
915     for &(cnum, ref path) in crates.iter() {
916         let name = cstore::get_crate_data(sess.cstore, cnum).name;
917         let p = match *path {
918             Some(ref p) => p.clone(), None => {
919                 sess.err(format!("could not find rlib for: `{}`", name));
920                 continue
921             }
922         };
923         a.add_rlib(&p, name, sess.lto());
924         let native_libs = csearch::get_native_libraries(sess.cstore, cnum);
925         for &(kind, ref lib) in native_libs.iter() {
926             let name = match kind {
927                 cstore::NativeStatic => "static library",
928                 cstore::NativeUnknown => "library",
929                 cstore::NativeFramework => "framework",
930             };
931             sess.warn(format!("unlinked native {}: {}", name, *lib));
932         }
933     }
934 }
935
936 // Create a dynamic library or executable
937 //
938 // This will invoke the system linker/cc to create the resulting file. This
939 // links to all upstream files as well.
940 fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
941                  out_filename: &Path) {
942     let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
943     // The invocations of cc share some flags across platforms
944     let cc_prog = get_cc_prog(sess);
945     let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
946     cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
947                                     obj_filename, out_filename));
948     if (sess.opts.debugging_opts & session::print_link_args) != 0 {
949         println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
950     }
951
952     // May have not found libraries in the right formats.
953     sess.abort_if_errors();
954
955     // Invoke the system linker
956     debug!("{} {}", cc_prog, cc_args.connect(" "));
957     let opt_prog = {
958         let _guard = io::ignore_io_error();
959         time(sess.time_passes(), "running linker", (), |()|
960              run::process_output(cc_prog, cc_args))
961     };
962
963     match opt_prog {
964         Some(prog) => {
965             if !prog.status.success() {
966                 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
967                 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
968                 sess.note(str::from_utf8_owned(prog.error + prog.output));
969                 sess.abort_if_errors();
970             }
971         },
972         None => {
973             sess.err(format!("could not exec the linker `{}`", cc_prog));
974             sess.abort_if_errors();
975         }
976     }
977
978
979     // On OSX, debuggers need this utility to get run to do some munging of
980     // the symbols
981     if sess.targ_cfg.os == abi::OsMacos && sess.opts.debuginfo {
982         // FIXME (#9639): This needs to handle non-utf8 paths
983         run::process_status("dsymutil",
984                             [out_filename.as_str().unwrap().to_owned()]);
985     }
986 }
987
988 fn link_args(sess: Session,
989              dylib: bool,
990              tmpdir: &Path,
991              obj_filename: &Path,
992              out_filename: &Path) -> ~[~str] {
993
994     // The default library location, we need this to find the runtime.
995     // The location of crates will be determined as needed.
996     // FIXME (#9639): This needs to handle non-utf8 paths
997     let lib_path = sess.filesearch.get_target_lib_path();
998     let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
999
1000     let mut args = ~[stage];
1001
1002     // FIXME (#9639): This needs to handle non-utf8 paths
1003     args.push_all([
1004         ~"-o", out_filename.as_str().unwrap().to_owned(),
1005         obj_filename.as_str().unwrap().to_owned()]);
1006
1007     // When linking a dynamic library, we put the metadata into a section of the
1008     // executable. This metadata is in a separate object file from the main
1009     // object file, so we link that in here.
1010     if dylib {
1011         let metadata = obj_filename.with_extension("metadata.o");
1012         args.push(metadata.as_str().unwrap().to_owned());
1013     }
1014
1015     if sess.targ_cfg.os == abi::OsLinux {
1016         // GNU-style linkers will use this to omit linking to libraries which
1017         // don't actually fulfill any relocations, but only for libraries which
1018         // follow this flag. Thus, use it before specifing libraries to link to.
1019         args.push(~"-Wl,--as-needed");
1020
1021         // GNU-style linkers support optimization with -O. --gc-sections
1022         // removes metadata and potentially other useful things, so don't
1023         // include it. GNU ld doesn't need a numeric argument, but other linkers
1024         // do.
1025         if sess.opts.optimize == session::Default ||
1026            sess.opts.optimize == session::Aggressive {
1027             args.push(~"-Wl,-O1");
1028         }
1029     }
1030
1031     add_local_native_libraries(&mut args, sess);
1032     add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1033     add_upstream_native_libraries(&mut args, sess);
1034
1035     // # Telling the linker what we're doing
1036
1037     if dylib {
1038         // On mac we need to tell the linker to let this library be rpathed
1039         if sess.targ_cfg.os == abi::OsMacos {
1040             args.push(~"-dynamiclib");
1041             args.push(~"-Wl,-dylib");
1042             // FIXME (#9639): This needs to handle non-utf8 paths
1043             args.push(~"-Wl,-install_name,@rpath/" +
1044                       out_filename.filename_str().unwrap());
1045         } else {
1046             args.push(~"-shared")
1047         }
1048     }
1049
1050     if sess.targ_cfg.os == abi::OsFreebsd {
1051         args.push_all([~"-L/usr/local/lib",
1052                        ~"-L/usr/local/lib/gcc46",
1053                        ~"-L/usr/local/lib/gcc44"]);
1054     }
1055
1056     // Stack growth requires statically linking a __morestack function
1057     args.push(~"-lmorestack");
1058
1059     // FIXME (#2397): At some point we want to rpath our guesses as to
1060     // where extern libraries might live, based on the
1061     // addl_lib_search_paths
1062     args.push_all(rpath::get_rpath_flags(sess, out_filename));
1063
1064     // Finally add all the linker arguments provided on the command line along
1065     // with any #[link_args] attributes found inside the crate
1066     args.push_all(sess.opts.linker_args);
1067     for arg in cstore::get_used_link_args(sess.cstore).iter() {
1068         args.push(arg.clone());
1069     }
1070     return args;
1071 }
1072
1073 // # Native library linking
1074 //
1075 // User-supplied library search paths (-L on the cammand line) These are
1076 // the same paths used to find Rust crates, so some of them may have been
1077 // added already by the previous crate linking code. This only allows them
1078 // to be found at compile time so it is still entirely up to outside
1079 // forces to make sure that library can be found at runtime.
1080 //
1081 // Also note that the native libraries linked here are only the ones located
1082 // in the current crate. Upstream crates with native library dependencies
1083 // may have their native library pulled in above.
1084 fn add_local_native_libraries(args: &mut ~[~str], sess: Session) {
1085     for path in sess.opts.addl_lib_search_paths.iter() {
1086         // FIXME (#9639): This needs to handle non-utf8 paths
1087         args.push("-L" + path.as_str().unwrap().to_owned());
1088     }
1089
1090     let rustpath = filesearch::rust_path();
1091     for path in rustpath.iter() {
1092         // FIXME (#9639): This needs to handle non-utf8 paths
1093         args.push("-L" + path.as_str().unwrap().to_owned());
1094     }
1095
1096     for &(ref l, kind) in cstore::get_used_libraries(sess.cstore).iter() {
1097         match kind {
1098             cstore::NativeUnknown | cstore::NativeStatic => {
1099                 args.push("-l" + *l);
1100             }
1101             cstore::NativeFramework => {
1102                 args.push(~"-framework");
1103                 args.push(l.to_owned());
1104             }
1105         }
1106     }
1107 }
1108
1109 // # Rust Crate linking
1110 //
1111 // Rust crates are not considered at all when creating an rlib output. All
1112 // dependencies will be linked when producing the final output (instead of
1113 // the intermediate rlib version)
1114 fn add_upstream_rust_crates(args: &mut ~[~str], sess: Session,
1115                             dylib: bool, tmpdir: &Path) {
1116     // Converts a library file-stem into a cc -l argument
1117     fn unlib(config: @session::config, stem: &str) -> ~str {
1118         if stem.starts_with("lib") &&
1119             config.os != abi::OsWin32 {
1120             stem.slice(3, stem.len()).to_owned()
1121         } else {
1122             stem.to_owned()
1123         }
1124     }
1125
1126     let cstore = sess.cstore;
1127     if !dylib && !sess.prefer_dynamic() {
1128         // With an executable, things get a little interesting. As a limitation
1129         // of the current implementation, we require that everything must be
1130         // static, or everything must be dynamic. The reasons for this are a
1131         // little subtle, but as with the above two cases, the goal is to
1132         // prevent duplicate copies of the same library showing up. For example,
1133         // a static immediate dependency might show up as an upstream dynamic
1134         // dependency and we currently have no way of knowing that. We know that
1135         // all dynamic libaries require dynamic dependencies (see above), so
1136         // it's satisfactory to include either all static libraries or all
1137         // dynamic libraries.
1138         let crates = cstore::get_used_crates(cstore, cstore::RequireStatic);
1139         if crates.iter().all(|&(_, ref p)| p.is_some()) {
1140             for (cnum, path) in crates.move_iter() {
1141                 let cratepath = path.unwrap();
1142
1143                 // When performing LTO on an executable output, all of the
1144                 // bytecode from the upstream libraries has already been
1145                 // included in our object file output. We need to modify all of
1146                 // the upstream archives to remove their corresponding object
1147                 // file to make sure we don't pull the same code in twice.
1148                 //
1149                 // We must continue to link to the upstream archives to be sure
1150                 // to pull in native static dependencies. As the final caveat,
1151                 // on linux it is apparently illegal to link to a blank archive,
1152                 // so if an archive no longer has any object files in it after
1153                 // we remove `lib.o`, then don't link against it at all.
1154                 //
1155                 // If we're not doing LTO, then our job is simply to just link
1156                 // against the archive.
1157                 if sess.lto() {
1158                     let name = cstore::get_crate_data(sess.cstore, cnum).name;
1159                     time(sess.time_passes(), format!("altering {}.rlib", name),
1160                          (), |()| {
1161                         let dst = tmpdir.join(cratepath.filename().unwrap());
1162                         fs::copy(&cratepath, &dst);
1163                         let dst_str = dst.as_str().unwrap().to_owned();
1164                         let mut archive = Archive::open(sess, dst);
1165                         archive.remove_file(format!("{}.o", name));
1166                         let files = archive.files();
1167                         if files.iter().any(|s| s.ends_with(".o")) {
1168                             args.push(dst_str);
1169                         }
1170                     });
1171                 } else {
1172                     args.push(cratepath.as_str().unwrap().to_owned());
1173                 }
1174             }
1175             return;
1176         }
1177     }
1178
1179     // If we're performing LTO, then it should have been previously required
1180     // that all upstream rust depenencies were available in an rlib format.
1181     assert!(!sess.lto());
1182
1183     // This is a fallback of three different  cases of linking:
1184     //
1185     // * When creating a dynamic library, all inputs are required to be dynamic
1186     //   as well
1187     // * If an executable is created with a preference on dynamic linking, then
1188     //   this case is the fallback
1189     // * If an executable is being created, and one of the inputs is missing as
1190     //   a static library, then this is the fallback case.
1191     let crates = cstore::get_used_crates(cstore, cstore::RequireDynamic);
1192     for &(cnum, ref path) in crates.iter() {
1193         let cratepath = match *path {
1194             Some(ref p) => p.clone(),
1195             None => {
1196                 sess.err(format!("could not find dynamic library for: `{}`",
1197                                  cstore::get_crate_data(sess.cstore, cnum).name));
1198                 return
1199             }
1200         };
1201         // Just need to tell the linker about where the library lives and what
1202         // its name is
1203         let dir = cratepath.dirname_str().unwrap();
1204         if !dir.is_empty() { args.push("-L" + dir); }
1205         let libarg = unlib(sess.targ_cfg, cratepath.filestem_str().unwrap());
1206         args.push("-l" + libarg);
1207     }
1208 }
1209
1210 // Link in all of our upstream crates' native dependencies. Remember that
1211 // all of these upstream native depenencies are all non-static
1212 // dependencies. We've got two cases then:
1213 //
1214 // 1. The upstream crate is an rlib. In this case we *must* link in the
1215 //    native dependency because the rlib is just an archive.
1216 //
1217 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1218 //    have the dependency present on the system somewhere. Thus, we don't
1219 //    gain a whole lot from not linking in the dynamic dependency to this
1220 //    crate as well.
1221 //
1222 // The use case for this is a little subtle. In theory the native
1223 // dependencies of a crate a purely an implementation detail of the crate
1224 // itself, but the problem arises with generic and inlined functions. If a
1225 // generic function calls a native function, then the generic function must
1226 // be instantiated in the target crate, meaning that the native symbol must
1227 // also be resolved in the target crate.
1228 fn add_upstream_native_libraries(args: &mut ~[~str], sess: Session) {
1229     let cstore = sess.cstore;
1230     cstore::iter_crate_data(cstore, |cnum, _| {
1231         let libs = csearch::get_native_libraries(cstore, cnum);
1232         for &(kind, ref lib) in libs.iter() {
1233             match kind {
1234                 cstore::NativeUnknown => args.push("-l" + *lib),
1235                 cstore::NativeFramework => {
1236                     args.push(~"-framework");
1237                     args.push(lib.to_owned());
1238                 }
1239                 cstore::NativeStatic => {
1240                     sess.bug("statics shouldn't be propagated");
1241                 }
1242             }
1243         }
1244     });
1245 }