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