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