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