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