]> git.lizzy.rs Git - rust.git/blob - src/librustc/back/link.rs
9d348ab2dc653f5dbd690547cccad0eac03e8bef
[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::LLVMRustSetLLVMOptions(llvm_args.len() as c_int, llvm_args.as_ptr());
364     }
365
366     unsafe fn populate_llvm_passes(fpm: lib::llvm::PassManagerRef,
367                                    mpm: lib::llvm::PassManagerRef,
368                                    llmod: ModuleRef,
369                                    opt: lib::llvm::CodeGenOptLevel) {
370         // Create the PassManagerBuilder for LLVM. We configure it with
371         // reasonable defaults and prepare it to actually populate the pass
372         // manager.
373         let builder = llvm::LLVMPassManagerBuilderCreate();
374         match opt {
375             lib::llvm::CodeGenLevelNone => {
376                 // Don't add lifetime intrinsics add O0
377                 llvm::LLVMRustAddAlwaysInlinePass(builder, false);
378             }
379             lib::llvm::CodeGenLevelLess => {
380                 llvm::LLVMRustAddAlwaysInlinePass(builder, true);
381             }
382             // numeric values copied from clang
383             lib::llvm::CodeGenLevelDefault => {
384                 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
385                                                                     225);
386             }
387             lib::llvm::CodeGenLevelAggressive => {
388                 llvm::LLVMPassManagerBuilderUseInlinerWithThreshold(builder,
389                                                                     275);
390             }
391         }
392         llvm::LLVMPassManagerBuilderSetOptLevel(builder, opt as c_uint);
393         llvm::LLVMRustAddBuilderLibraryInfo(builder, llmod);
394
395         // Use the builder to populate the function/module pass managers.
396         llvm::LLVMPassManagerBuilderPopulateFunctionPassManager(builder, fpm);
397         llvm::LLVMPassManagerBuilderPopulateModulePassManager(builder, mpm);
398         llvm::LLVMPassManagerBuilderDispose(builder);
399     }
400 }
401
402
403 /*
404  * Name mangling and its relationship to metadata. This is complex. Read
405  * carefully.
406  *
407  * The semantic model of Rust linkage is, broadly, that "there's no global
408  * namespace" between crates. Our aim is to preserve the illusion of this
409  * model despite the fact that it's not *quite* possible to implement on
410  * modern linkers. We initially didn't use system linkers at all, but have
411  * been convinced of their utility.
412  *
413  * There are a few issues to handle:
414  *
415  *  - Linkers operate on a flat namespace, so we have to flatten names.
416  *    We do this using the C++ namespace-mangling technique. Foo::bar
417  *    symbols and such.
418  *
419  *  - Symbols with the same name but different types need to get different
420  *    linkage-names. We do this by hashing a string-encoding of the type into
421  *    a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
422  *    we use SHA256) to "prevent collisions". This is not airtight but 16 hex
423  *    digits on uniform probability means you're going to need 2**32 same-name
424  *    symbols in the same process before you're even hitting birthday-paradox
425  *    collision probability.
426  *
427  *  - Symbols in different crates but with same names "within" the crate need
428  *    to get different linkage-names.
429  *
430  *  - The hash shown in the filename needs to be predictable and stable for
431  *    build tooling integration. It also needs to be using a hash function
432  *    which is easy to use from Python, make, etc.
433  *
434  * So here is what we do:
435  *
436  *  - Consider the package id; every crate has one (specified with pkgid
437  *    attribute).  If a package id isn't provided explicitly, we infer a
438  *    versionless one from the output name. The version will end up being 0.0
439  *    in this case. CNAME and CVERS are taken from this package id. For
440  *    example, github.com/mozilla/CNAME#CVERS.
441  *
442  *  - Define CMH as SHA256(pkgid).
443  *
444  *  - Define CMH8 as the first 8 characters of CMH.
445  *
446  *  - Compile our crate to lib CNAME-CMH8-CVERS.so
447  *
448  *  - Define STH(sym) as SHA256(CMH, type_str(sym))
449  *
450  *  - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
451  *    name, non-name metadata, and type sense, and versioned in the way
452  *    system linkers understand.
453  */
454
455 pub fn build_link_meta(sess: Session,
456                        attrs: &[ast::Attribute],
457                        output: &Path,
458                        symbol_hasher: &mut Sha256)
459                        -> LinkMeta {
460     // This calculates CMH as defined above
461     fn crate_hash(symbol_hasher: &mut Sha256, pkgid: &PkgId) -> @str {
462         symbol_hasher.reset();
463         symbol_hasher.input_str(pkgid.to_str());
464         truncated_hash_result(symbol_hasher).to_managed()
465     }
466
467     let pkgid = match attr::find_pkgid(attrs) {
468         None => {
469             let stem = session::expect(
470                 sess,
471                 output.filestem_str(),
472                 || format!("output file name '{}' doesn't appear to have a stem",
473                            output.display()));
474             from_str(stem).unwrap()
475         }
476         Some(s) => s,
477     };
478
479     let hash = crate_hash(symbol_hasher, &pkgid);
480
481     LinkMeta {
482         pkgid: pkgid,
483         crate_hash: hash,
484     }
485 }
486
487 pub fn truncated_hash_result(symbol_hasher: &mut Sha256) -> ~str {
488     symbol_hasher.result_str()
489 }
490
491
492 // This calculates STH for a symbol, as defined above
493 pub fn symbol_hash(tcx: ty::ctxt,
494                    symbol_hasher: &mut Sha256,
495                    t: ty::t,
496                    link_meta: &LinkMeta) -> @str {
497     // NB: do *not* use abbrevs here as we want the symbol names
498     // to be independent of one another in the crate.
499
500     symbol_hasher.reset();
501     symbol_hasher.input_str(link_meta.pkgid.name);
502     symbol_hasher.input_str("-");
503     symbol_hasher.input_str(link_meta.crate_hash);
504     symbol_hasher.input_str("-");
505     symbol_hasher.input_str(encoder::encoded_ty(tcx, t));
506     let mut hash = truncated_hash_result(symbol_hasher);
507     // Prefix with 'h' so that it never blends into adjacent digits
508     hash.unshift_char('h');
509     // tjc: allocation is unfortunate; need to change std::hash
510     hash.to_managed()
511 }
512
513 pub fn get_symbol_hash(ccx: &mut CrateContext, t: ty::t) -> @str {
514     match ccx.type_hashcodes.find(&t) {
515       Some(&h) => h,
516       None => {
517         let hash = symbol_hash(ccx.tcx, &mut ccx.symbol_hasher, t, &ccx.link_meta);
518         ccx.type_hashcodes.insert(t, hash);
519         hash
520       }
521     }
522 }
523
524
525 // Name sanitation. LLVM will happily accept identifiers with weird names, but
526 // gas doesn't!
527 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
528 pub fn sanitize(s: &str) -> ~str {
529     let mut result = ~"";
530     for c in s.chars() {
531         match c {
532             // Escape these with $ sequences
533             '@' => result.push_str("$SP$"),
534             '~' => result.push_str("$UP$"),
535             '*' => result.push_str("$RP$"),
536             '&' => result.push_str("$BP$"),
537             '<' => result.push_str("$LT$"),
538             '>' => result.push_str("$GT$"),
539             '(' => result.push_str("$LP$"),
540             ')' => result.push_str("$RP$"),
541             ',' => result.push_str("$C$"),
542
543             // '.' doesn't occur in types and functions, so reuse it
544             // for ':' and '-'
545             '-' | ':' => result.push_char('.'),
546
547             // These are legal symbols
548             'a' .. 'z'
549             | 'A' .. 'Z'
550             | '0' .. '9'
551             | '_' | '.' | '$' => result.push_char(c),
552
553             _ => {
554                 let mut tstr = ~"";
555                 char::escape_unicode(c, |c| tstr.push_char(c));
556                 result.push_char('$');
557                 result.push_str(tstr.slice_from(1));
558             }
559         }
560     }
561
562     // Underscore-qualify anything that didn't start as an ident.
563     if result.len() > 0u &&
564         result[0] != '_' as u8 &&
565         ! char::is_XID_start(result[0] as char) {
566         return ~"_" + result;
567     }
568
569     return result;
570 }
571
572 pub fn mangle(sess: Session, ss: path,
573               hash: Option<&str>, vers: Option<&str>) -> ~str {
574     // Follow C++ namespace-mangling style, see
575     // http://en.wikipedia.org/wiki/Name_mangling for more info.
576     //
577     // It turns out that on OSX you can actually have arbitrary symbols in
578     // function names (at least when given to LLVM), but this is not possible
579     // when using unix's linker. Perhaps one day when we just a linker from LLVM
580     // we won't need to do this name mangling. The problem with name mangling is
581     // that it seriously limits the available characters. For example we can't
582     // have things like @T or ~[T] in symbol names when one would theoretically
583     // want them for things like impls of traits on that type.
584     //
585     // To be able to work on all platforms and get *some* reasonable output, we
586     // use C++ name-mangling.
587
588     let mut n = ~"_ZN"; // _Z == Begin name-sequence, N == nested
589
590     let push = |s: &str| {
591         let sani = sanitize(s);
592         n.push_str(format!("{}{}", sani.len(), sani));
593     };
594
595     // First, connect each component with <len, name> pairs.
596     for s in ss.iter() {
597         match *s {
598             path_name(s) | path_mod(s) | path_pretty_name(s, _) => {
599                 push(sess.str_of(s))
600             }
601         }
602     }
603
604     // next, if any identifiers are "pretty" and need extra information tacked
605     // on, then use the hash to generate two unique characters. For now
606     // hopefully 2 characters is enough to avoid collisions.
607     static EXTRA_CHARS: &'static str =
608         "abcdefghijklmnopqrstuvwxyz\
609          ABCDEFGHIJKLMNOPQRSTUVWXYZ\
610          0123456789";
611     let mut hash = match hash { Some(s) => s.to_owned(), None => ~"" };
612     for s in ss.iter() {
613         match *s {
614             path_pretty_name(_, extra) => {
615                 let hi = (extra >> 32) as u32 as uint;
616                 let lo = extra as u32 as uint;
617                 hash.push_char(EXTRA_CHARS[hi % EXTRA_CHARS.len()] as char);
618                 hash.push_char(EXTRA_CHARS[lo % EXTRA_CHARS.len()] as char);
619             }
620             _ => {}
621         }
622     }
623     if hash.len() > 0 {
624         push(hash);
625     }
626     match vers {
627         Some(s) => push(s),
628         None => {}
629     }
630
631     n.push_char('E'); // End name-sequence.
632     n
633 }
634
635 pub fn exported_name(sess: Session,
636                      path: path,
637                      hash: &str,
638                      vers: &str) -> ~str {
639     // The version will get mangled to have a leading '_', but it makes more
640     // sense to lead with a 'v' b/c this is a version...
641     let vers = if vers.len() > 0 && !char::is_XID_start(vers.char_at(0)) {
642         "v" + vers
643     } else {
644         vers.to_owned()
645     };
646
647     mangle(sess, path, Some(hash), Some(vers.as_slice()))
648 }
649
650 pub fn mangle_exported_name(ccx: &mut CrateContext,
651                             path: path,
652                             t: ty::t) -> ~str {
653     let hash = get_symbol_hash(ccx, t);
654     return exported_name(ccx.sess, path,
655                          hash,
656                          ccx.link_meta.pkgid.version_or_default());
657 }
658
659 pub fn mangle_internal_name_by_type_only(ccx: &mut CrateContext,
660                                          t: ty::t,
661                                          name: &str) -> ~str {
662     let s = ppaux::ty_to_short_str(ccx.tcx, t);
663     let hash = get_symbol_hash(ccx, t);
664     return mangle(ccx.sess,
665                   ~[path_name(ccx.sess.ident_of(name)),
666                     path_name(ccx.sess.ident_of(s))],
667                   Some(hash.as_slice()),
668                   None);
669 }
670
671 pub fn mangle_internal_name_by_type_and_seq(ccx: &mut CrateContext,
672                                             t: ty::t,
673                                             name: &str) -> ~str {
674     let s = ppaux::ty_to_str(ccx.tcx, t);
675     let hash = get_symbol_hash(ccx, t);
676     let (_, name) = gensym_name(name);
677     return mangle(ccx.sess,
678                   ~[path_name(ccx.sess.ident_of(s)), name],
679                   Some(hash.as_slice()),
680                   None);
681 }
682
683 pub fn mangle_internal_name_by_path_and_seq(ccx: &mut CrateContext,
684                                             mut path: path,
685                                             flav: &str) -> ~str {
686     let (_, name) = gensym_name(flav);
687     path.push(name);
688     mangle(ccx.sess, path, None, None)
689 }
690
691 pub fn mangle_internal_name_by_path(ccx: &mut CrateContext, path: path) -> ~str {
692     mangle(ccx.sess, path, None, None)
693 }
694
695 pub fn output_lib_filename(lm: &LinkMeta) -> ~str {
696     format!("{}-{}-{}",
697             lm.pkgid.name,
698             lm.crate_hash.slice_chars(0, 8),
699             lm.pkgid.version_or_default())
700 }
701
702 pub fn get_cc_prog(sess: Session) -> ~str {
703     match sess.opts.linker {
704         Some(ref linker) => return linker.to_owned(),
705         None => {}
706     }
707
708     // In the future, FreeBSD will use clang as default compiler.
709     // It would be flexible to use cc (system's default C compiler)
710     // instead of hard-coded gcc.
711     // For win32, there is no cc command, so we add a condition to make it use
712     // g++.  We use g++ rather than gcc because it automatically adds linker
713     // options required for generation of dll modules that correctly register
714     // stack unwind tables.
715     match sess.targ_cfg.os {
716         abi::OsAndroid => match sess.opts.android_cross_path {
717             Some(ref path) => format!("{}/bin/arm-linux-androideabi-gcc", *path),
718             None => {
719                 sess.fatal("need Android NDK path for linking \
720                             (--android-cross-path)")
721             }
722         },
723         abi::OsWin32 => ~"g++",
724         _ => ~"cc",
725     }
726 }
727
728 /// Perform the linkage portion of the compilation phase. This will generate all
729 /// of the requested outputs for this compilation session.
730 pub fn link_binary(sess: Session,
731                    trans: &CrateTranslation,
732                    obj_filename: &Path,
733                    out_filename: &Path,
734                    lm: &LinkMeta) -> ~[Path] {
735     let mut out_filenames = ~[];
736     for &output in sess.outputs.iter() {
737         let out_file = link_binary_output(sess, trans, output, obj_filename,
738                                           out_filename, lm);
739         out_filenames.push(out_file);
740     }
741
742     // Remove the temporary object file and metadata if we aren't saving temps
743     if !sess.opts.save_temps {
744         fs::unlink(obj_filename);
745         fs::unlink(&obj_filename.with_extension("metadata.o"));
746     }
747
748     out_filenames
749 }
750
751 fn is_writeable(p: &Path) -> bool {
752     use std::io;
753
754     match io::result(|| p.stat()) {
755         Err(..) => true,
756         Ok(m) => m.perm & io::UserWrite == io::UserWrite
757     }
758 }
759
760 pub fn filename_for_input(sess: &Session, output: session::OutputStyle, lm: &LinkMeta,
761                       out_filename: &Path) -> Path {
762     let libname = output_lib_filename(lm);
763     match output {
764         session::OutputRlib => {
765             out_filename.with_filename(format!("lib{}.rlib", libname))
766         }
767         session::OutputDylib => {
768             let (prefix, suffix) = match sess.targ_cfg.os {
769                 abi::OsWin32 => (win32::DLL_PREFIX, win32::DLL_SUFFIX),
770                 abi::OsMacos => (macos::DLL_PREFIX, macos::DLL_SUFFIX),
771                 abi::OsLinux => (linux::DLL_PREFIX, linux::DLL_SUFFIX),
772                 abi::OsAndroid => (android::DLL_PREFIX, android::DLL_SUFFIX),
773                 abi::OsFreebsd => (freebsd::DLL_PREFIX, freebsd::DLL_SUFFIX),
774             };
775             out_filename.with_filename(format!("{}{}{}", prefix, libname, suffix))
776         }
777         session::OutputStaticlib => {
778             out_filename.with_filename(format!("lib{}.a", libname))
779         }
780         session::OutputExecutable => out_filename.clone(),
781     }
782
783 }
784
785 fn link_binary_output(sess: Session,
786                       trans: &CrateTranslation,
787                       output: session::OutputStyle,
788                       obj_filename: &Path,
789                       out_filename: &Path,
790                       lm: &LinkMeta) -> Path {
791     let out_filename = filename_for_input(&sess, output, lm, out_filename);
792
793     // Make sure the output and obj_filename are both writeable.
794     // Mac, FreeBSD, and Windows system linkers check this already --
795     // however, the Linux linker will happily overwrite a read-only file.
796     // We should be consistent.
797     let obj_is_writeable = is_writeable(obj_filename);
798     let out_is_writeable = is_writeable(&out_filename);
799     if !out_is_writeable {
800         sess.fatal(format!("Output file {} is not writeable -- check its permissions.",
801                            out_filename.display()));
802     }
803     else if !obj_is_writeable {
804         sess.fatal(format!("Object file {} is not writeable -- check its permissions.",
805                            obj_filename.display()));
806     }
807
808     match output {
809         session::OutputRlib => {
810             link_rlib(sess, Some(trans), obj_filename, &out_filename);
811         }
812         session::OutputStaticlib => {
813             link_staticlib(sess, obj_filename, &out_filename);
814         }
815         session::OutputExecutable => {
816             link_natively(sess, false, obj_filename, &out_filename);
817             // Windows linker will add an ".exe" extension if there was none
818             let out_filename = match out_filename.extension() {
819                 Some(_) => out_filename.clone(),
820                 None => out_filename.with_extension(win32::EXE_EXTENSION)
821             };
822             manifest::postprocess_executable(sess, &out_filename);
823         }
824         session::OutputDylib => {
825             link_natively(sess, true, obj_filename, &out_filename);
826         }
827     }
828
829     out_filename
830 }
831
832 // Create an 'rlib'
833 //
834 // An rlib in its current incarnation is essentially a renamed .a file. The
835 // rlib primarily contains the object file of the crate, but it also contains
836 // all of the object files from native libraries. This is done by unzipping
837 // native libraries and inserting all of the contents into this archive.
838 fn link_rlib(sess: Session,
839              trans: Option<&CrateTranslation>, // None == no metadata/bytecode
840              obj_filename: &Path,
841              out_filename: &Path) -> Archive {
842     let mut a = Archive::create(sess, out_filename, obj_filename);
843
844     for &(ref l, kind) in cstore::get_used_libraries(sess.cstore).iter() {
845         match kind {
846             cstore::NativeStatic => {
847                 a.add_native_library(l.as_slice());
848             }
849             cstore::NativeFramework | cstore::NativeUnknown => {}
850         }
851     }
852
853     // Note that it is important that we add all of our non-object "magical
854     // files" *after* all of the object files in the archive. The reason for
855     // this is as follows:
856     //
857     // * When performing LTO, this archive will be modified to remove
858     //   obj_filename from above. The reason for this is described below.
859     //
860     // * When the system linker looks at an archive, it will attempt to
861     //   determine the architecture of the archive in order to see whether its
862     //   linkable.
863     //
864     //   The algorithm for this detections is: iterate over the files in the
865     //   archive. Skip magical SYMDEF names. Interpret the first file as an
866     //   object file. Read architecture from the object file.
867     //
868     // * As one can probably see, if "metadata" and "foo.bc" were placed
869     //   before all of the objects, then the architecture of this archive would
870     //   not be correctly inferred once 'foo.o' is removed.
871     //
872     // Basically, all this means is that this code should not move above the
873     // code above.
874     match trans {
875         Some(trans) => {
876             // Instead of putting the metadata in an object file section, rlibs
877             // contain the metadata in a separate file.
878             let metadata = obj_filename.with_filename(METADATA_FILENAME);
879             fs::File::create(&metadata).write(trans.metadata);
880             a.add_file(&metadata, false);
881             fs::unlink(&metadata);
882
883             // For LTO purposes, the bytecode of this library is also inserted
884             // into the archive.
885             let bc = obj_filename.with_extension("bc");
886             a.add_file(&bc, false);
887             if !sess.opts.save_temps {
888                 fs::unlink(&bc);
889             }
890
891             // Now that we've added files, some platforms need us to now update
892             // the symbol table in the archive (because some platforms die when
893             // adding files to the archive without symbols).
894             a.update_symbols();
895         }
896
897         None => {}
898     }
899     return a;
900 }
901
902 // Create a static archive
903 //
904 // This is essentially the same thing as an rlib, but it also involves adding
905 // all of the upstream crates' objects into the the archive. This will slurp in
906 // all of the native libraries of upstream dependencies as well.
907 //
908 // Additionally, there's no way for us to link dynamic libraries, so we warn
909 // about all dynamic library dependencies that they're not linked in.
910 //
911 // There's no need to include metadata in a static archive, so ensure to not
912 // link in the metadata object file (and also don't prepare the archive with a
913 // metadata file).
914 fn link_staticlib(sess: Session, obj_filename: &Path, out_filename: &Path) {
915     let mut a = link_rlib(sess, None, obj_filename, out_filename);
916     a.add_native_library("morestack");
917
918     let crates = cstore::get_used_crates(sess.cstore, cstore::RequireStatic);
919     for &(cnum, ref path) in crates.iter() {
920         let name = cstore::get_crate_data(sess.cstore, cnum).name;
921         let p = match *path {
922             Some(ref p) => p.clone(), None => {
923                 sess.err(format!("could not find rlib for: `{}`", name));
924                 continue
925             }
926         };
927         a.add_rlib(&p, name, sess.lto());
928         let native_libs = csearch::get_native_libraries(sess.cstore, cnum);
929         for &(kind, ref lib) in native_libs.iter() {
930             let name = match kind {
931                 cstore::NativeStatic => "static library",
932                 cstore::NativeUnknown => "library",
933                 cstore::NativeFramework => "framework",
934             };
935             sess.warn(format!("unlinked native {}: {}", name, *lib));
936         }
937     }
938 }
939
940 // Create a dynamic library or executable
941 //
942 // This will invoke the system linker/cc to create the resulting file. This
943 // links to all upstream files as well.
944 fn link_natively(sess: Session, dylib: bool, obj_filename: &Path,
945                  out_filename: &Path) {
946     let tmpdir = TempDir::new("rustc").expect("needs a temp dir");
947     // The invocations of cc share some flags across platforms
948     let cc_prog = get_cc_prog(sess);
949     let mut cc_args = sess.targ_cfg.target_strs.cc_args.clone();
950     cc_args.push_all_move(link_args(sess, dylib, tmpdir.path(),
951                                     obj_filename, out_filename));
952     if (sess.opts.debugging_opts & session::print_link_args) != 0 {
953         println!("{} link args: '{}'", cc_prog, cc_args.connect("' '"));
954     }
955
956     // May have not found libraries in the right formats.
957     sess.abort_if_errors();
958
959     // Invoke the system linker
960     debug!("{} {}", cc_prog, cc_args.connect(" "));
961     let opt_prog = {
962         let _guard = io::ignore_io_error();
963         time(sess.time_passes(), "running linker", (), |()|
964              run::process_output(cc_prog, cc_args))
965     };
966
967     match opt_prog {
968         Some(prog) => {
969             if !prog.status.success() {
970                 sess.err(format!("linking with `{}` failed: {}", cc_prog, prog.status));
971                 sess.note(format!("{} arguments: '{}'", cc_prog, cc_args.connect("' '")));
972                 sess.note(str::from_utf8_owned(prog.error + prog.output));
973                 sess.abort_if_errors();
974             }
975         },
976         None => {
977             sess.err(format!("could not exec the linker `{}`", cc_prog));
978             sess.abort_if_errors();
979         }
980     }
981
982
983     // On OSX, debuggers need this utility to get run to do some munging of
984     // the symbols
985     if sess.targ_cfg.os == abi::OsMacos && sess.opts.debuginfo {
986         // FIXME (#9639): This needs to handle non-utf8 paths
987         run::process_status("dsymutil",
988                             [out_filename.as_str().unwrap().to_owned()]);
989     }
990 }
991
992 fn link_args(sess: Session,
993              dylib: bool,
994              tmpdir: &Path,
995              obj_filename: &Path,
996              out_filename: &Path) -> ~[~str] {
997
998     // The default library location, we need this to find the runtime.
999     // The location of crates will be determined as needed.
1000     // FIXME (#9639): This needs to handle non-utf8 paths
1001     let lib_path = sess.filesearch.get_target_lib_path();
1002     let stage: ~str = ~"-L" + lib_path.as_str().unwrap();
1003
1004     let mut args = ~[stage];
1005
1006     // FIXME (#9639): This needs to handle non-utf8 paths
1007     args.push_all([
1008         ~"-o", out_filename.as_str().unwrap().to_owned(),
1009         obj_filename.as_str().unwrap().to_owned()]);
1010
1011     // When linking a dynamic library, we put the metadata into a section of the
1012     // executable. This metadata is in a separate object file from the main
1013     // object file, so we link that in here.
1014     if dylib {
1015         let metadata = obj_filename.with_extension("metadata.o");
1016         args.push(metadata.as_str().unwrap().to_owned());
1017     }
1018
1019     if sess.targ_cfg.os == abi::OsLinux {
1020         // GNU-style linkers will use this to omit linking to libraries which
1021         // don't actually fulfill any relocations, but only for libraries which
1022         // follow this flag. Thus, use it before specifing libraries to link to.
1023         args.push(~"-Wl,--as-needed");
1024
1025         // GNU-style linkers support optimization with -O. --gc-sections
1026         // removes metadata and potentially other useful things, so don't
1027         // include it. GNU ld doesn't need a numeric argument, but other linkers
1028         // do.
1029         if sess.opts.optimize == session::Default ||
1030            sess.opts.optimize == session::Aggressive {
1031             args.push(~"-Wl,-O1");
1032         }
1033     }
1034
1035     add_local_native_libraries(&mut args, sess);
1036     add_upstream_rust_crates(&mut args, sess, dylib, tmpdir);
1037     add_upstream_native_libraries(&mut args, sess);
1038
1039     // # Telling the linker what we're doing
1040
1041     if dylib {
1042         // On mac we need to tell the linker to let this library be rpathed
1043         if sess.targ_cfg.os == abi::OsMacos {
1044             args.push(~"-dynamiclib");
1045             args.push(~"-Wl,-dylib");
1046             // FIXME (#9639): This needs to handle non-utf8 paths
1047             args.push(~"-Wl,-install_name,@rpath/" +
1048                       out_filename.filename_str().unwrap());
1049         } else {
1050             args.push(~"-shared")
1051         }
1052     }
1053
1054     if sess.targ_cfg.os == abi::OsFreebsd {
1055         args.push_all([~"-L/usr/local/lib",
1056                        ~"-L/usr/local/lib/gcc46",
1057                        ~"-L/usr/local/lib/gcc44"]);
1058     }
1059
1060     // Stack growth requires statically linking a __morestack function
1061     args.push(~"-lmorestack");
1062
1063     // FIXME (#2397): At some point we want to rpath our guesses as to
1064     // where extern libraries might live, based on the
1065     // addl_lib_search_paths
1066     args.push_all(rpath::get_rpath_flags(sess, out_filename));
1067
1068     // Finally add all the linker arguments provided on the command line along
1069     // with any #[link_args] attributes found inside the crate
1070     args.push_all(sess.opts.linker_args);
1071     for arg in cstore::get_used_link_args(sess.cstore).iter() {
1072         args.push(arg.clone());
1073     }
1074     return args;
1075 }
1076
1077 // # Native library linking
1078 //
1079 // User-supplied library search paths (-L on the cammand line) These are
1080 // the same paths used to find Rust crates, so some of them may have been
1081 // added already by the previous crate linking code. This only allows them
1082 // to be found at compile time so it is still entirely up to outside
1083 // forces to make sure that library can be found at runtime.
1084 //
1085 // Also note that the native libraries linked here are only the ones located
1086 // in the current crate. Upstream crates with native library dependencies
1087 // may have their native library pulled in above.
1088 fn add_local_native_libraries(args: &mut ~[~str], sess: Session) {
1089     for path in sess.opts.addl_lib_search_paths.iter() {
1090         // FIXME (#9639): This needs to handle non-utf8 paths
1091         args.push("-L" + path.as_str().unwrap().to_owned());
1092     }
1093
1094     let rustpath = filesearch::rust_path();
1095     for path in rustpath.iter() {
1096         // FIXME (#9639): This needs to handle non-utf8 paths
1097         args.push("-L" + path.as_str().unwrap().to_owned());
1098     }
1099
1100     for &(ref l, kind) in cstore::get_used_libraries(sess.cstore).iter() {
1101         match kind {
1102             cstore::NativeUnknown | cstore::NativeStatic => {
1103                 args.push("-l" + *l);
1104             }
1105             cstore::NativeFramework => {
1106                 args.push(~"-framework");
1107                 args.push(l.to_owned());
1108             }
1109         }
1110     }
1111 }
1112
1113 // # Rust Crate linking
1114 //
1115 // Rust crates are not considered at all when creating an rlib output. All
1116 // dependencies will be linked when producing the final output (instead of
1117 // the intermediate rlib version)
1118 fn add_upstream_rust_crates(args: &mut ~[~str], sess: Session,
1119                             dylib: bool, tmpdir: &Path) {
1120     // Converts a library file-stem into a cc -l argument
1121     fn unlib(config: @session::config, stem: &str) -> ~str {
1122         if stem.starts_with("lib") &&
1123             config.os != abi::OsWin32 {
1124             stem.slice(3, stem.len()).to_owned()
1125         } else {
1126             stem.to_owned()
1127         }
1128     }
1129
1130     let cstore = sess.cstore;
1131     if !dylib && !sess.prefer_dynamic() {
1132         // With an executable, things get a little interesting. As a limitation
1133         // of the current implementation, we require that everything must be
1134         // static, or everything must be dynamic. The reasons for this are a
1135         // little subtle, but as with the above two cases, the goal is to
1136         // prevent duplicate copies of the same library showing up. For example,
1137         // a static immediate dependency might show up as an upstream dynamic
1138         // dependency and we currently have no way of knowing that. We know that
1139         // all dynamic libaries require dynamic dependencies (see above), so
1140         // it's satisfactory to include either all static libraries or all
1141         // dynamic libraries.
1142         let crates = cstore::get_used_crates(cstore, cstore::RequireStatic);
1143         if crates.iter().all(|&(_, ref p)| p.is_some()) {
1144             for (cnum, path) in crates.move_iter() {
1145                 let cratepath = path.unwrap();
1146
1147                 // When performing LTO on an executable output, all of the
1148                 // bytecode from the upstream libraries has already been
1149                 // included in our object file output. We need to modify all of
1150                 // the upstream archives to remove their corresponding object
1151                 // file to make sure we don't pull the same code in twice.
1152                 //
1153                 // We must continue to link to the upstream archives to be sure
1154                 // to pull in native static dependencies. As the final caveat,
1155                 // on linux it is apparently illegal to link to a blank archive,
1156                 // so if an archive no longer has any object files in it after
1157                 // we remove `lib.o`, then don't link against it at all.
1158                 //
1159                 // If we're not doing LTO, then our job is simply to just link
1160                 // against the archive.
1161                 if sess.lto() {
1162                     let name = cstore::get_crate_data(sess.cstore, cnum).name;
1163                     time(sess.time_passes(), format!("altering {}.rlib", name),
1164                          (), |()| {
1165                         let dst = tmpdir.join(cratepath.filename().unwrap());
1166                         fs::copy(&cratepath, &dst);
1167                         let dst_str = dst.as_str().unwrap().to_owned();
1168                         let mut archive = Archive::open(sess, dst);
1169                         archive.remove_file(format!("{}.o", name));
1170                         let files = archive.files();
1171                         if files.iter().any(|s| s.ends_with(".o")) {
1172                             args.push(dst_str);
1173                         }
1174                     });
1175                 } else {
1176                     args.push(cratepath.as_str().unwrap().to_owned());
1177                 }
1178             }
1179             return;
1180         }
1181     }
1182
1183     // If we're performing LTO, then it should have been previously required
1184     // that all upstream rust depenencies were available in an rlib format.
1185     assert!(!sess.lto());
1186
1187     // This is a fallback of three different  cases of linking:
1188     //
1189     // * When creating a dynamic library, all inputs are required to be dynamic
1190     //   as well
1191     // * If an executable is created with a preference on dynamic linking, then
1192     //   this case is the fallback
1193     // * If an executable is being created, and one of the inputs is missing as
1194     //   a static library, then this is the fallback case.
1195     let crates = cstore::get_used_crates(cstore, cstore::RequireDynamic);
1196     for &(cnum, ref path) in crates.iter() {
1197         let cratepath = match *path {
1198             Some(ref p) => p.clone(),
1199             None => {
1200                 sess.err(format!("could not find dynamic library for: `{}`",
1201                                  cstore::get_crate_data(sess.cstore, cnum).name));
1202                 return
1203             }
1204         };
1205         // Just need to tell the linker about where the library lives and what
1206         // its name is
1207         let dir = cratepath.dirname_str().unwrap();
1208         if !dir.is_empty() { args.push("-L" + dir); }
1209         let libarg = unlib(sess.targ_cfg, cratepath.filestem_str().unwrap());
1210         args.push("-l" + libarg);
1211     }
1212 }
1213
1214 // Link in all of our upstream crates' native dependencies. Remember that
1215 // all of these upstream native depenencies are all non-static
1216 // dependencies. We've got two cases then:
1217 //
1218 // 1. The upstream crate is an rlib. In this case we *must* link in the
1219 //    native dependency because the rlib is just an archive.
1220 //
1221 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1222 //    have the dependency present on the system somewhere. Thus, we don't
1223 //    gain a whole lot from not linking in the dynamic dependency to this
1224 //    crate as well.
1225 //
1226 // The use case for this is a little subtle. In theory the native
1227 // dependencies of a crate a purely an implementation detail of the crate
1228 // itself, but the problem arises with generic and inlined functions. If a
1229 // generic function calls a native function, then the generic function must
1230 // be instantiated in the target crate, meaning that the native symbol must
1231 // also be resolved in the target crate.
1232 fn add_upstream_native_libraries(args: &mut ~[~str], sess: Session) {
1233     let cstore = sess.cstore;
1234     cstore::iter_crate_data(cstore, |cnum, _| {
1235         let libs = csearch::get_native_libraries(cstore, cnum);
1236         for &(kind, ref lib) in libs.iter() {
1237             match kind {
1238                 cstore::NativeUnknown => args.push("-l" + *lib),
1239                 cstore::NativeFramework => {
1240                     args.push(~"-framework");
1241                     args.push(lib.to_owned());
1242                 }
1243                 cstore::NativeStatic => {
1244                     sess.bug("statics shouldn't be propagated");
1245                 }
1246             }
1247         }
1248     });
1249 }