]> git.lizzy.rs Git - rust.git/blob - src/librustc/back/link.rs
auto merge of #16907 : SimonSapin/rust/tempdir-result, r=huonw
[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::archive;
13 use super::rpath;
14 use super::rpath::RPathConfig;
15 use super::svh::Svh;
16 use super::write::{OutputTypeBitcode, OutputTypeExe, OutputTypeObject};
17 use driver::driver::{CrateTranslation, OutputFilenames, Input, FileInput};
18 use driver::config::NoDebugInfo;
19 use driver::session::Session;
20 use driver::config;
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::char;
31 use std::collections::HashSet;
32 use std::io::{fs, TempDir, Command};
33 use std::io;
34 use std::mem;
35 use std::str;
36 use std::string::String;
37 use flate;
38 use serialize::hex::ToHex;
39 use syntax::abi;
40 use syntax::ast;
41 use syntax::ast_map::{PathElem, PathElems, PathName};
42 use syntax::ast_map;
43 use syntax::attr::AttrMetaMethods;
44 use syntax::codemap::Span;
45 use syntax::parse::token;
46
47 // RLIB LLVM-BYTECODE OBJECT LAYOUT
48 // Version 1
49 // Bytes    Data
50 // 0..10    "RUST_OBJECT" encoded in ASCII
51 // 11..14   format version as little-endian u32
52 // 15..22   size in bytes of deflate compressed LLVM bitcode as
53 //          little-endian u64
54 // 23..     compressed LLVM bitcode
55
56 // This is the "magic number" expected at the beginning of a LLVM bytecode
57 // object in an rlib.
58 pub static RLIB_BYTECODE_OBJECT_MAGIC: &'static [u8] = b"RUST_OBJECT";
59
60 // The version number this compiler will write to bytecode objects in rlibs
61 pub static RLIB_BYTECODE_OBJECT_VERSION: u32 = 1;
62
63 // The offset in bytes the bytecode object format version number can be found at
64 pub static RLIB_BYTECODE_OBJECT_VERSION_OFFSET: uint = 11;
65
66 // The offset in bytes the size of the compressed bytecode can be found at in
67 // format version 1
68 pub static RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET: uint =
69     RLIB_BYTECODE_OBJECT_VERSION_OFFSET + 4;
70
71 // The offset in bytes the compressed LLVM bytecode can be found at in format
72 // version 1
73 pub static RLIB_BYTECODE_OBJECT_V1_DATA_OFFSET: uint =
74     RLIB_BYTECODE_OBJECT_V1_DATASIZE_OFFSET + 8;
75
76
77 /*
78  * Name mangling and its relationship to metadata. This is complex. Read
79  * carefully.
80  *
81  * The semantic model of Rust linkage is, broadly, that "there's no global
82  * namespace" between crates. Our aim is to preserve the illusion of this
83  * model despite the fact that it's not *quite* possible to implement on
84  * modern linkers. We initially didn't use system linkers at all, but have
85  * been convinced of their utility.
86  *
87  * There are a few issues to handle:
88  *
89  *  - Linkers operate on a flat namespace, so we have to flatten names.
90  *    We do this using the C++ namespace-mangling technique. Foo::bar
91  *    symbols and such.
92  *
93  *  - Symbols with the same name but different types need to get different
94  *    linkage-names. We do this by hashing a string-encoding of the type into
95  *    a fixed-size (currently 16-byte hex) cryptographic hash function (CHF:
96  *    we use SHA256) to "prevent collisions". This is not airtight but 16 hex
97  *    digits on uniform probability means you're going to need 2**32 same-name
98  *    symbols in the same process before you're even hitting birthday-paradox
99  *    collision probability.
100  *
101  *  - Symbols in different crates but with same names "within" the crate need
102  *    to get different linkage-names.
103  *
104  *  - The hash shown in the filename needs to be predictable and stable for
105  *    build tooling integration. It also needs to be using a hash function
106  *    which is easy to use from Python, make, etc.
107  *
108  * So here is what we do:
109  *
110  *  - Consider the package id; every crate has one (specified with crate_id
111  *    attribute).  If a package id isn't provided explicitly, we infer a
112  *    versionless one from the output name. The version will end up being 0.0
113  *    in this case. CNAME and CVERS are taken from this package id. For
114  *    example, github.com/mozilla/CNAME#CVERS.
115  *
116  *  - Define CMH as SHA256(crateid).
117  *
118  *  - Define CMH8 as the first 8 characters of CMH.
119  *
120  *  - Compile our crate to lib CNAME-CMH8-CVERS.so
121  *
122  *  - Define STH(sym) as SHA256(CMH, type_str(sym))
123  *
124  *  - Suffix a mangled sym with ::STH@CVERS, so that it is unique in the
125  *    name, non-name metadata, and type sense, and versioned in the way
126  *    system linkers understand.
127  */
128
129 pub fn find_crate_name(sess: Option<&Session>,
130                        attrs: &[ast::Attribute],
131                        input: &Input) -> String {
132     use syntax::crateid::CrateId;
133
134     let validate = |s: String, span: Option<Span>| {
135         creader::validate_crate_name(sess, s.as_slice(), span);
136         s
137     };
138
139     // Look in attributes 100% of the time to make sure the attribute is marked
140     // as used. After doing this, however, we still prioritize a crate name from
141     // the command line over one found in the #[crate_name] attribute. If we
142     // find both we ensure that they're the same later on as well.
143     let attr_crate_name = attrs.iter().find(|at| at.check_name("crate_name"))
144                                .and_then(|at| at.value_str().map(|s| (at, s)));
145
146     match sess {
147         Some(sess) => {
148             match sess.opts.crate_name {
149                 Some(ref s) => {
150                     match attr_crate_name {
151                         Some((attr, ref name)) if s.as_slice() != name.get() => {
152                             let msg = format!("--crate-name and #[crate_name] \
153                                                are required to match, but `{}` \
154                                                != `{}`", s, name);
155                             sess.span_err(attr.span, msg.as_slice());
156                         }
157                         _ => {},
158                     }
159                     return validate(s.clone(), None);
160                 }
161                 None => {}
162             }
163         }
164         None => {}
165     }
166
167     match attr_crate_name {
168         Some((attr, s)) => return validate(s.get().to_string(), Some(attr.span)),
169         None => {}
170     }
171     let crate_id = attrs.iter().find(|at| at.check_name("crate_id"))
172                         .and_then(|at| at.value_str().map(|s| (at, s)))
173                         .and_then(|(at, s)| {
174                             from_str::<CrateId>(s.get()).map(|id| (at, id))
175                         });
176     match crate_id {
177         Some((attr, id)) => {
178             match sess {
179                 Some(sess) => {
180                     sess.span_warn(attr.span, "the #[crate_id] attribute is \
181                                                deprecated for the \
182                                                #[crate_name] attribute");
183                 }
184                 None => {}
185             }
186             return validate(id.name, Some(attr.span))
187         }
188         None => {}
189     }
190     match *input {
191         FileInput(ref path) => {
192             match path.filestem_str() {
193                 Some(s) => return validate(s.to_string(), None),
194                 None => {}
195             }
196         }
197         _ => {}
198     }
199
200     "rust-out".to_string()
201 }
202
203 pub fn build_link_meta(sess: &Session, krate: &ast::Crate,
204                        name: String) -> LinkMeta {
205     let r = LinkMeta {
206         crate_name: name,
207         crate_hash: Svh::calculate(&sess.opts.cg.metadata, krate),
208     };
209     info!("{}", r);
210     return r;
211 }
212
213 fn truncated_hash_result(symbol_hasher: &mut Sha256) -> String {
214     let output = symbol_hasher.result_bytes();
215     // 64 bits should be enough to avoid collisions.
216     output.slice_to(8).to_hex().to_string()
217 }
218
219
220 // This calculates STH for a symbol, as defined above
221 fn symbol_hash(tcx: &ty::ctxt,
222                symbol_hasher: &mut Sha256,
223                t: ty::t,
224                link_meta: &LinkMeta)
225                -> String {
226     // NB: do *not* use abbrevs here as we want the symbol names
227     // to be independent of one another in the crate.
228
229     symbol_hasher.reset();
230     symbol_hasher.input_str(link_meta.crate_name.as_slice());
231     symbol_hasher.input_str("-");
232     symbol_hasher.input_str(link_meta.crate_hash.as_str());
233     for meta in tcx.sess.crate_metadata.borrow().iter() {
234         symbol_hasher.input_str(meta.as_slice());
235     }
236     symbol_hasher.input_str("-");
237     symbol_hasher.input_str(encoder::encoded_ty(tcx, t).as_slice());
238     // Prefix with 'h' so that it never blends into adjacent digits
239     let mut hash = String::from_str("h");
240     hash.push_str(truncated_hash_result(symbol_hasher).as_slice());
241     hash
242 }
243
244 fn get_symbol_hash(ccx: &CrateContext, t: ty::t) -> String {
245     match ccx.type_hashcodes().borrow().find(&t) {
246         Some(h) => return h.to_string(),
247         None => {}
248     }
249
250     let mut symbol_hasher = ccx.symbol_hasher().borrow_mut();
251     let hash = symbol_hash(ccx.tcx(), &mut *symbol_hasher, t, ccx.link_meta());
252     ccx.type_hashcodes().borrow_mut().insert(t, hash.clone());
253     hash
254 }
255
256
257 // Name sanitation. LLVM will happily accept identifiers with weird names, but
258 // gas doesn't!
259 // gas accepts the following characters in symbols: a-z, A-Z, 0-9, ., _, $
260 pub fn sanitize(s: &str) -> String {
261     let mut result = String::new();
262     for c in s.chars() {
263         match c {
264             // Escape these with $ sequences
265             '@' => result.push_str("$SP$"),
266             '~' => result.push_str("$UP$"),
267             '*' => result.push_str("$RP$"),
268             '&' => result.push_str("$BP$"),
269             '<' => result.push_str("$LT$"),
270             '>' => result.push_str("$GT$"),
271             '(' => result.push_str("$LP$"),
272             ')' => result.push_str("$RP$"),
273             ',' => result.push_str("$C$"),
274
275             // '.' doesn't occur in types and functions, so reuse it
276             // for ':' and '-'
277             '-' | ':' => result.push_char('.'),
278
279             // These are legal symbols
280             'a' .. 'z'
281             | 'A' .. 'Z'
282             | '0' .. '9'
283             | '_' | '.' | '$' => result.push_char(c),
284
285             _ => {
286                 let mut tstr = String::new();
287                 char::escape_unicode(c, |c| tstr.push_char(c));
288                 result.push_char('$');
289                 result.push_str(tstr.as_slice().slice_from(1));
290             }
291         }
292     }
293
294     // Underscore-qualify anything that didn't start as an ident.
295     if result.len() > 0u &&
296         result.as_bytes()[0] != '_' as u8 &&
297         ! char::is_XID_start(result.as_bytes()[0] as char) {
298         return format!("_{}", result.as_slice());
299     }
300
301     return result;
302 }
303
304 pub fn mangle<PI: Iterator<PathElem>>(mut path: PI,
305                                       hash: Option<&str>) -> String {
306     // Follow C++ namespace-mangling style, see
307     // http://en.wikipedia.org/wiki/Name_mangling for more info.
308     //
309     // It turns out that on OSX you can actually have arbitrary symbols in
310     // function names (at least when given to LLVM), but this is not possible
311     // when using unix's linker. Perhaps one day when we just use a linker from LLVM
312     // we won't need to do this name mangling. The problem with name mangling is
313     // that it seriously limits the available characters. For example we can't
314     // have things like &T or ~[T] in symbol names when one would theoretically
315     // want them for things like impls of traits on that type.
316     //
317     // To be able to work on all platforms and get *some* reasonable output, we
318     // use C++ name-mangling.
319
320     let mut n = String::from_str("_ZN"); // _Z == Begin name-sequence, N == nested
321
322     fn push(n: &mut String, s: &str) {
323         let sani = sanitize(s);
324         n.push_str(format!("{}{}", sani.len(), sani).as_slice());
325     }
326
327     // First, connect each component with <len, name> pairs.
328     for e in path {
329         push(&mut n, token::get_name(e.name()).get().as_slice())
330     }
331
332     match hash {
333         Some(s) => push(&mut n, s),
334         None => {}
335     }
336
337     n.push_char('E'); // End name-sequence.
338     n
339 }
340
341 pub fn exported_name(path: PathElems, hash: &str) -> String {
342     mangle(path, Some(hash))
343 }
344
345 pub fn mangle_exported_name(ccx: &CrateContext, path: PathElems,
346                             t: ty::t, id: ast::NodeId) -> String {
347     let mut hash = get_symbol_hash(ccx, t);
348
349     // Paths can be completely identical for different nodes,
350     // e.g. `fn foo() { { fn a() {} } { fn a() {} } }`, so we
351     // generate unique characters from the node id. For now
352     // hopefully 3 characters is enough to avoid collisions.
353     static EXTRA_CHARS: &'static str =
354         "abcdefghijklmnopqrstuvwxyz\
355          ABCDEFGHIJKLMNOPQRSTUVWXYZ\
356          0123456789";
357     let id = id as uint;
358     let extra1 = id % EXTRA_CHARS.len();
359     let id = id / EXTRA_CHARS.len();
360     let extra2 = id % EXTRA_CHARS.len();
361     let id = id / EXTRA_CHARS.len();
362     let extra3 = id % EXTRA_CHARS.len();
363     hash.push_char(EXTRA_CHARS.as_bytes()[extra1] as char);
364     hash.push_char(EXTRA_CHARS.as_bytes()[extra2] as char);
365     hash.push_char(EXTRA_CHARS.as_bytes()[extra3] as char);
366
367     exported_name(path, hash.as_slice())
368 }
369
370 pub fn mangle_internal_name_by_type_and_seq(ccx: &CrateContext,
371                                             t: ty::t,
372                                             name: &str) -> String {
373     let s = ppaux::ty_to_string(ccx.tcx(), t);
374     let path = [PathName(token::intern(s.as_slice())),
375                 gensym_name(name)];
376     let hash = get_symbol_hash(ccx, t);
377     mangle(ast_map::Values(path.iter()), Some(hash.as_slice()))
378 }
379
380 pub fn mangle_internal_name_by_path_and_seq(path: PathElems, flav: &str) -> String {
381     mangle(path.chain(Some(gensym_name(flav)).move_iter()), None)
382 }
383
384 pub fn get_cc_prog(sess: &Session) -> String {
385     match sess.opts.cg.linker {
386         Some(ref linker) => return linker.to_string(),
387         None => {}
388     }
389
390     // In the future, FreeBSD will use clang as default compiler.
391     // It would be flexible to use cc (system's default C compiler)
392     // instead of hard-coded gcc.
393     // For Windows, there is no cc command, so we add a condition to make it use gcc.
394     match sess.targ_cfg.os {
395         abi::OsWindows => "gcc",
396         _ => "cc",
397     }.to_string()
398 }
399
400 pub fn get_ar_prog(sess: &Session) -> String {
401     match sess.opts.cg.ar {
402         Some(ref ar) => (*ar).clone(),
403         None => "ar".to_string()
404     }
405 }
406
407 pub fn remove(sess: &Session, path: &Path) {
408     match fs::unlink(path) {
409         Ok(..) => {}
410         Err(e) => {
411             sess.err(format!("failed to remove {}: {}",
412                              path.display(),
413                              e).as_slice());
414         }
415     }
416 }
417
418 /// Perform the linkage portion of the compilation phase. This will generate all
419 /// of the requested outputs for this compilation session.
420 pub fn link_binary(sess: &Session,
421                    trans: &CrateTranslation,
422                    outputs: &OutputFilenames,
423                    crate_name: &str) -> Vec<Path> {
424     let mut out_filenames = Vec::new();
425     for &crate_type in sess.crate_types.borrow().iter() {
426         if invalid_output_for_target(sess, crate_type) {
427             sess.bug(format!("invalid output type `{}` for target os `{}`",
428                              crate_type, sess.targ_cfg.os).as_slice());
429         }
430         let out_file = link_binary_output(sess, trans, crate_type, outputs,
431                                           crate_name);
432         out_filenames.push(out_file);
433     }
434
435     // Remove the temporary object file and metadata if we aren't saving temps
436     if !sess.opts.cg.save_temps {
437         let obj_filename = outputs.temp_path(OutputTypeObject);
438         if !sess.opts.output_types.contains(&OutputTypeObject) {
439             remove(sess, &obj_filename);
440         }
441         remove(sess, &obj_filename.with_extension("metadata.o"));
442     }
443
444     out_filenames
445 }
446
447
448 /// Returns default crate type for target
449 ///
450 /// Default crate type is used when crate type isn't provided neither
451 /// through cmd line arguments nor through crate attributes
452 ///
453 /// It is CrateTypeExecutable for all platforms but iOS as there is no
454 /// way to run iOS binaries anyway without jailbreaking and
455 /// interaction with Rust code through static library is the only
456 /// option for now
457 pub fn default_output_for_target(sess: &Session) -> config::CrateType {
458     match sess.targ_cfg.os {
459         abi::OsiOS => config::CrateTypeStaticlib,
460         _ => config::CrateTypeExecutable
461     }
462 }
463
464 /// Checks if target supports crate_type as output
465 pub fn invalid_output_for_target(sess: &Session,
466                                  crate_type: config::CrateType) -> bool {
467     match (sess.targ_cfg.os, crate_type) {
468         (abi::OsiOS, config::CrateTypeDylib) => true,
469         _ => false
470     }
471 }
472
473 fn is_writeable(p: &Path) -> bool {
474     match p.stat() {
475         Err(..) => true,
476         Ok(m) => m.perm & io::UserWrite == io::UserWrite
477     }
478 }
479
480 pub fn filename_for_input(sess: &Session,
481                           crate_type: config::CrateType,
482                           name: &str,
483                           out_filename: &Path) -> Path {
484     let libname = format!("{}{}", name, sess.opts.cg.extra_filename);
485     match crate_type {
486         config::CrateTypeRlib => {
487             out_filename.with_filename(format!("lib{}.rlib", libname))
488         }
489         config::CrateTypeDylib => {
490             let (prefix, suffix) = match sess.targ_cfg.os {
491                 abi::OsWindows => (loader::WIN32_DLL_PREFIX, loader::WIN32_DLL_SUFFIX),
492                 abi::OsMacos => (loader::MACOS_DLL_PREFIX, loader::MACOS_DLL_SUFFIX),
493                 abi::OsLinux => (loader::LINUX_DLL_PREFIX, loader::LINUX_DLL_SUFFIX),
494                 abi::OsAndroid => (loader::ANDROID_DLL_PREFIX, loader::ANDROID_DLL_SUFFIX),
495                 abi::OsFreebsd => (loader::FREEBSD_DLL_PREFIX, loader::FREEBSD_DLL_SUFFIX),
496                 abi::OsDragonfly => (loader::DRAGONFLY_DLL_PREFIX, loader::DRAGONFLY_DLL_SUFFIX),
497                 abi::OsiOS => unreachable!(),
498             };
499             out_filename.with_filename(format!("{}{}{}",
500                                                prefix,
501                                                libname,
502                                                suffix))
503         }
504         config::CrateTypeStaticlib => {
505             out_filename.with_filename(format!("lib{}.a", libname))
506         }
507         config::CrateTypeExecutable => {
508             match sess.targ_cfg.os {
509                 abi::OsWindows => out_filename.with_extension("exe"),
510                 abi::OsMacos |
511                 abi::OsLinux |
512                 abi::OsAndroid |
513                 abi::OsFreebsd |
514                 abi::OsDragonfly |
515                 abi::OsiOS => out_filename.clone(),
516             }
517         }
518     }
519 }
520
521 fn link_binary_output(sess: &Session,
522                       trans: &CrateTranslation,
523                       crate_type: config::CrateType,
524                       outputs: &OutputFilenames,
525                       crate_name: &str) -> Path {
526     let obj_filename = outputs.temp_path(OutputTypeObject);
527     let out_filename = match outputs.single_output_file {
528         Some(ref file) => file.clone(),
529         None => {
530             let out_filename = outputs.path(OutputTypeExe);
531             filename_for_input(sess, crate_type, crate_name, &out_filename)
532         }
533     };
534
535     // Make sure the output and obj_filename are both writeable.
536     // Mac, FreeBSD, and Windows system linkers check this already --
537     // however, the Linux linker will happily overwrite a read-only file.
538     // We should be consistent.
539     let obj_is_writeable = is_writeable(&obj_filename);
540     let out_is_writeable = is_writeable(&out_filename);
541     if !out_is_writeable {
542         sess.fatal(format!("output file {} is not writeable -- check its \
543                             permissions.",
544                            out_filename.display()).as_slice());
545     }
546     else if !obj_is_writeable {
547         sess.fatal(format!("object file {} is not writeable -- check its \
548                             permissions.",
549                            obj_filename.display()).as_slice());
550     }
551
552     match crate_type {
553         config::CrateTypeRlib => {
554             link_rlib(sess, Some(trans), &obj_filename, &out_filename).build();
555         }
556         config::CrateTypeStaticlib => {
557             link_staticlib(sess, &obj_filename, &out_filename);
558         }
559         config::CrateTypeExecutable => {
560             link_natively(sess, trans, false, &obj_filename, &out_filename);
561         }
562         config::CrateTypeDylib => {
563             link_natively(sess, trans, true, &obj_filename, &out_filename);
564         }
565     }
566
567     out_filename
568 }
569
570 fn archive_search_paths(sess: &Session) -> Vec<Path> {
571     let mut rustpath = filesearch::rust_path();
572     rustpath.push(sess.target_filesearch().get_lib_path());
573     // FIXME: Addl lib search paths are an unordered HashSet?
574     // Shouldn't this search be done in some order?
575     let addl_lib_paths: HashSet<Path> = sess.opts.addl_lib_search_paths.borrow().clone();
576     let mut search: Vec<Path> = addl_lib_paths.move_iter().collect();
577     search.push_all(rustpath.as_slice());
578     return search;
579 }
580
581 // Create an 'rlib'
582 //
583 // An rlib in its current incarnation is essentially a renamed .a file. The
584 // rlib primarily contains the object file of the crate, but it also contains
585 // all of the object files from native libraries. This is done by unzipping
586 // native libraries and inserting all of the contents into this archive.
587 fn link_rlib<'a>(sess: &'a Session,
588                  trans: Option<&CrateTranslation>, // None == no metadata/bytecode
589                  obj_filename: &Path,
590                  out_filename: &Path) -> ArchiveBuilder<'a> {
591     let handler = &sess.diagnostic().handler;
592     let config = ArchiveConfig {
593         handler: handler,
594         dst: out_filename.clone(),
595         lib_search_paths: archive_search_paths(sess),
596         os: sess.targ_cfg.os,
597         maybe_ar_prog: sess.opts.cg.ar.clone()
598     };
599     let mut ab = ArchiveBuilder::create(config);
600     ab.add_file(obj_filename).unwrap();
601
602     for &(ref l, kind) in sess.cstore.get_used_libraries().borrow().iter() {
603         match kind {
604             cstore::NativeStatic => {
605                 ab.add_native_library(l.as_slice()).unwrap();
606             }
607             cstore::NativeFramework | cstore::NativeUnknown => {}
608         }
609     }
610
611     // After adding all files to the archive, we need to update the
612     // symbol table of the archive.
613     ab.update_symbols();
614
615     let mut ab = match sess.targ_cfg.os {
616         // For OSX/iOS, we must be careful to update symbols only when adding
617         // object files.  We're about to start adding non-object files, so run
618         // `ar` now to process the object files.
619         abi::OsMacos | abi::OsiOS => ab.build().extend(),
620         _ => ab,
621     };
622
623     // Note that it is important that we add all of our non-object "magical
624     // files" *after* all of the object files in the archive. The reason for
625     // this is as follows:
626     //
627     // * When performing LTO, this archive will be modified to remove
628     //   obj_filename from above. The reason for this is described below.
629     //
630     // * When the system linker looks at an archive, it will attempt to
631     //   determine the architecture of the archive in order to see whether its
632     //   linkable.
633     //
634     //   The algorithm for this detection is: iterate over the files in the
635     //   archive. Skip magical SYMDEF names. Interpret the first file as an
636     //   object file. Read architecture from the object file.
637     //
638     // * As one can probably see, if "metadata" and "foo.bc" were placed
639     //   before all of the objects, then the architecture of this archive would
640     //   not be correctly inferred once 'foo.o' is removed.
641     //
642     // Basically, all this means is that this code should not move above the
643     // code above.
644     match trans {
645         Some(trans) => {
646             // Instead of putting the metadata in an object file section, rlibs
647             // contain the metadata in a separate file. We use a temp directory
648             // here so concurrent builds in the same directory don't try to use
649             // the same filename for metadata (stomping over one another)
650             let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
651             let metadata = tmpdir.path().join(METADATA_FILENAME);
652             match fs::File::create(&metadata).write(trans.metadata
653                                                          .as_slice()) {
654                 Ok(..) => {}
655                 Err(e) => {
656                     sess.err(format!("failed to write {}: {}",
657                                      metadata.display(),
658                                      e).as_slice());
659                     sess.abort_if_errors();
660                 }
661             }
662             ab.add_file(&metadata).unwrap();
663             remove(sess, &metadata);
664
665             if sess.opts.cg.codegen_units == 1 {
666                 // For LTO purposes, the bytecode of this library is also
667                 // inserted into the archive.  We currently do this only when
668                 // codegen_units == 1, so we don't have to deal with multiple
669                 // bitcode files per crate.
670                 //
671                 // Note that we make sure that the bytecode filename in the
672                 // archive is never exactly 16 bytes long by adding a 16 byte
673                 // extension to it. This is to work around a bug in LLDB that
674                 // would cause it to crash if the name of a file in an archive
675                 // was exactly 16 bytes.
676                 let bc_filename = obj_filename.with_extension("bc");
677                 let bc_deflated_filename = obj_filename.with_extension("bytecode.deflate");
678
679                 let bc_data = match fs::File::open(&bc_filename).read_to_end() {
680                     Ok(buffer) => buffer,
681                     Err(e) => sess.fatal(format!("failed to read bytecode: {}",
682                                                  e).as_slice())
683                 };
684
685                 let bc_data_deflated = match flate::deflate_bytes(bc_data.as_slice()) {
686                     Some(compressed) => compressed,
687                     None => sess.fatal(format!("failed to compress bytecode from {}",
688                                                bc_filename.display()).as_slice())
689                 };
690
691                 let mut bc_file_deflated = match fs::File::create(&bc_deflated_filename) {
692                     Ok(file) => file,
693                     Err(e) => {
694                         sess.fatal(format!("failed to create compressed bytecode \
695                                             file: {}", e).as_slice())
696                     }
697                 };
698
699                 match write_rlib_bytecode_object_v1(&mut bc_file_deflated,
700                                                     bc_data_deflated.as_slice()) {
701                     Ok(()) => {}
702                     Err(e) => {
703                         sess.err(format!("failed to write compressed bytecode: \
704                                           {}", e).as_slice());
705                         sess.abort_if_errors()
706                     }
707                 };
708
709                 ab.add_file(&bc_deflated_filename).unwrap();
710                 remove(sess, &bc_deflated_filename);
711                 if !sess.opts.cg.save_temps &&
712                    !sess.opts.output_types.contains(&OutputTypeBitcode) {
713                     remove(sess, &bc_filename);
714                 }
715             }
716         }
717
718         None => {}
719     }
720
721     ab
722 }
723
724 fn write_rlib_bytecode_object_v1<T: Writer>(writer: &mut T,
725                                             bc_data_deflated: &[u8])
726                                          -> ::std::io::IoResult<()> {
727     let bc_data_deflated_size: u64 = bc_data_deflated.as_slice().len() as u64;
728
729     try! { writer.write(RLIB_BYTECODE_OBJECT_MAGIC) };
730     try! { writer.write_le_u32(1) };
731     try! { writer.write_le_u64(bc_data_deflated_size) };
732     try! { writer.write(bc_data_deflated.as_slice()) };
733
734     let number_of_bytes_written_so_far =
735         RLIB_BYTECODE_OBJECT_MAGIC.len() +                // magic id
736         mem::size_of_val(&RLIB_BYTECODE_OBJECT_VERSION) + // version
737         mem::size_of_val(&bc_data_deflated_size) +        // data size field
738         bc_data_deflated_size as uint;                    // actual data
739
740     // If the number of bytes written to the object so far is odd, add a
741     // padding byte to make it even. This works around a crash bug in LLDB
742     // (see issue #15950)
743     if number_of_bytes_written_so_far % 2 == 1 {
744         try! { writer.write_u8(0) };
745     }
746
747     return Ok(());
748 }
749
750 // Create a static archive
751 //
752 // This is essentially the same thing as an rlib, but it also involves adding
753 // all of the upstream crates' objects into the archive. This will slurp in
754 // all of the native libraries of upstream dependencies as well.
755 //
756 // Additionally, there's no way for us to link dynamic libraries, so we warn
757 // about all dynamic library dependencies that they're not linked in.
758 //
759 // There's no need to include metadata in a static archive, so ensure to not
760 // link in the metadata object file (and also don't prepare the archive with a
761 // metadata file).
762 fn link_staticlib(sess: &Session, obj_filename: &Path, out_filename: &Path) {
763     let ab = link_rlib(sess, None, obj_filename, out_filename);
764     let mut ab = match sess.targ_cfg.os {
765         abi::OsMacos | abi::OsiOS => ab.build().extend(),
766         _ => ab,
767     };
768     ab.add_native_library("morestack").unwrap();
769     ab.add_native_library("compiler-rt").unwrap();
770
771     let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
772     let mut all_native_libs = vec![];
773
774     for &(cnum, ref path) in crates.iter() {
775         let name = sess.cstore.get_crate_data(cnum).name.clone();
776         let p = match *path {
777             Some(ref p) => p.clone(), None => {
778                 sess.err(format!("could not find rlib for: `{}`",
779                                  name).as_slice());
780                 continue
781             }
782         };
783         ab.add_rlib(&p, name.as_slice(), sess.lto()).unwrap();
784
785         let native_libs = csearch::get_native_libraries(&sess.cstore, cnum);
786         all_native_libs.extend(native_libs.move_iter());
787     }
788
789     ab.update_symbols();
790     let _ = ab.build();
791
792     if !all_native_libs.is_empty() {
793         sess.warn("link against the following native artifacts when linking against \
794                   this static library");
795         sess.note("the order and any duplication can be significant on some platforms, \
796                   and so may need to be preserved");
797     }
798
799     for &(kind, ref lib) in all_native_libs.iter() {
800         let name = match kind {
801             cstore::NativeStatic => "static library",
802             cstore::NativeUnknown => "library",
803             cstore::NativeFramework => "framework",
804         };
805         sess.note(format!("{}: {}", name, *lib).as_slice());
806     }
807 }
808
809 // Create a dynamic library or executable
810 //
811 // This will invoke the system linker/cc to create the resulting file. This
812 // links to all upstream files as well.
813 fn link_natively(sess: &Session, trans: &CrateTranslation, dylib: bool,
814                  obj_filename: &Path, out_filename: &Path) {
815     let tmpdir = TempDir::new("rustc").ok().expect("needs a temp dir");
816
817     // The invocations of cc share some flags across platforms
818     let pname = get_cc_prog(sess);
819     let mut cmd = Command::new(pname.as_slice());
820
821     cmd.args(sess.targ_cfg.target_strs.cc_args.as_slice());
822     link_args(&mut cmd, sess, dylib, tmpdir.path(),
823               trans, obj_filename, out_filename);
824
825     if (sess.opts.debugging_opts & config::PRINT_LINK_ARGS) != 0 {
826         println!("{}", &cmd);
827     }
828
829     // May have not found libraries in the right formats.
830     sess.abort_if_errors();
831
832     // Invoke the system linker
833     debug!("{}", &cmd);
834     let prog = time(sess.time_passes(), "running linker", (), |()| cmd.output());
835     match prog {
836         Ok(prog) => {
837             if !prog.status.success() {
838                 sess.err(format!("linking with `{}` failed: {}",
839                                  pname,
840                                  prog.status).as_slice());
841                 sess.note(format!("{}", &cmd).as_slice());
842                 let mut output = prog.error.clone();
843                 output.push_all(prog.output.as_slice());
844                 sess.note(str::from_utf8(output.as_slice()).unwrap());
845                 sess.abort_if_errors();
846             }
847             debug!("linker stderr:\n{}", str::from_utf8_owned(prog.error).unwrap());
848             debug!("linker stdout:\n{}", str::from_utf8_owned(prog.output).unwrap());
849         },
850         Err(e) => {
851             sess.err(format!("could not exec the linker `{}`: {}",
852                              pname,
853                              e).as_slice());
854             sess.abort_if_errors();
855         }
856     }
857
858
859     // On OSX, debuggers need this utility to get run to do some munging of
860     // the symbols
861     if (sess.targ_cfg.os == abi::OsMacos || sess.targ_cfg.os == abi::OsiOS)
862         && (sess.opts.debuginfo != NoDebugInfo) {
863             match Command::new("dsymutil").arg(out_filename).output() {
864                 Ok(..) => {}
865                 Err(e) => {
866                     sess.err(format!("failed to run dsymutil: {}", e).as_slice());
867                     sess.abort_if_errors();
868                 }
869             }
870         }
871 }
872
873 fn link_args(cmd: &mut Command,
874              sess: &Session,
875              dylib: bool,
876              tmpdir: &Path,
877              trans: &CrateTranslation,
878              obj_filename: &Path,
879              out_filename: &Path) {
880
881     // The default library location, we need this to find the runtime.
882     // The location of crates will be determined as needed.
883     let lib_path = sess.target_filesearch().get_lib_path();
884     cmd.arg("-L").arg(&lib_path);
885
886     cmd.arg("-o").arg(out_filename).arg(obj_filename);
887
888     // Stack growth requires statically linking a __morestack function. Note
889     // that this is listed *before* all other libraries. Due to the usage of the
890     // --as-needed flag below, the standard library may only be useful for its
891     // rust_stack_exhausted function. In this case, we must ensure that the
892     // libmorestack.a file appears *before* the standard library (so we put it
893     // at the very front).
894     //
895     // Most of the time this is sufficient, except for when LLVM gets super
896     // clever. If, for example, we have a main function `fn main() {}`, LLVM
897     // will optimize out calls to `__morestack` entirely because the function
898     // doesn't need any stack at all!
899     //
900     // To get around this snag, we specially tell the linker to always include
901     // all contents of this library. This way we're guaranteed that the linker
902     // will include the __morestack symbol 100% of the time, always resolving
903     // references to it even if the object above didn't use it.
904     match sess.targ_cfg.os {
905         abi::OsMacos | abi::OsiOS => {
906             let morestack = lib_path.join("libmorestack.a");
907
908             let mut v = b"-Wl,-force_load,".to_vec();
909             v.push_all(morestack.as_vec());
910             cmd.arg(v.as_slice());
911         }
912         _ => {
913             cmd.args(["-Wl,--whole-archive", "-lmorestack",
914                       "-Wl,--no-whole-archive"]);
915         }
916     }
917
918     // When linking a dynamic library, we put the metadata into a section of the
919     // executable. This metadata is in a separate object file from the main
920     // object file, so we link that in here.
921     if dylib {
922         cmd.arg(obj_filename.with_extension("metadata.o"));
923     }
924
925     // We want to prevent the compiler from accidentally leaking in any system
926     // libraries, so we explicitly ask gcc to not link to any libraries by
927     // default. Note that this does not happen for windows because windows pulls
928     // in some large number of libraries and I couldn't quite figure out which
929     // subset we wanted.
930     //
931     // FIXME(#11937) we should invoke the system linker directly
932     if sess.targ_cfg.os != abi::OsWindows {
933         cmd.arg("-nodefaultlibs");
934     }
935
936     // If we're building a dylib, we don't use --gc-sections because LLVM has
937     // already done the best it can do, and we also don't want to eliminate the
938     // metadata. If we're building an executable, however, --gc-sections drops
939     // the size of hello world from 1.8MB to 597K, a 67% reduction.
940     if !dylib && sess.targ_cfg.os != abi::OsMacos && sess.targ_cfg.os != abi::OsiOS {
941         cmd.arg("-Wl,--gc-sections");
942     }
943
944     let used_link_args = sess.cstore.get_used_link_args().borrow();
945
946     // Dynamically linked executables can be compiled as position independent if the default
947     // relocation model of position independent code is not changed. This is a requirement to take
948     // advantage of ASLR, as otherwise the functions in the executable are not randomized and can
949     // be used during an exploit of a vulnerability in any code.
950     if sess.targ_cfg.os == abi::OsLinux {
951         let mut args = sess.opts.cg.link_args.iter().chain(used_link_args.iter());
952         if !dylib && sess.opts.cg.relocation_model.as_slice() == "pic" &&
953             !args.any(|x| x.as_slice() == "-static") {
954             cmd.arg("-pie");
955         }
956     }
957
958     if sess.targ_cfg.os == abi::OsLinux || sess.targ_cfg.os == abi::OsDragonfly {
959         // GNU-style linkers will use this to omit linking to libraries which
960         // don't actually fulfill any relocations, but only for libraries which
961         // follow this flag. Thus, use it before specifying libraries to link to.
962         cmd.arg("-Wl,--as-needed");
963
964         // GNU-style linkers support optimization with -O. GNU ld doesn't need a
965         // numeric argument, but other linkers do.
966         if sess.opts.optimize == config::Default ||
967            sess.opts.optimize == config::Aggressive {
968             cmd.arg("-Wl,-O1");
969         }
970     } else if sess.targ_cfg.os == abi::OsMacos || sess.targ_cfg.os == abi::OsiOS {
971         // The dead_strip option to the linker specifies that functions and data
972         // unreachable by the entry point will be removed. This is quite useful
973         // with Rust's compilation model of compiling libraries at a time into
974         // one object file. For example, this brings hello world from 1.7MB to
975         // 458K.
976         //
977         // Note that this is done for both executables and dynamic libraries. We
978         // won't get much benefit from dylibs because LLVM will have already
979         // stripped away as much as it could. This has not been seen to impact
980         // link times negatively.
981         cmd.arg("-Wl,-dead_strip");
982     }
983
984     if sess.targ_cfg.os == abi::OsWindows {
985         // Make sure that we link to the dynamic libgcc, otherwise cross-module
986         // DWARF stack unwinding will not work.
987         // This behavior may be overridden by --link-args "-static-libgcc"
988         cmd.arg("-shared-libgcc");
989
990         // And here, we see obscure linker flags #45. On windows, it has been
991         // found to be necessary to have this flag to compile liblibc.
992         //
993         // First a bit of background. On Windows, the file format is not ELF,
994         // but COFF (at least according to LLVM). COFF doesn't officially allow
995         // for section names over 8 characters, apparently. Our metadata
996         // section, ".note.rustc", you'll note is over 8 characters.
997         //
998         // On more recent versions of gcc on mingw, apparently the section name
999         // is *not* truncated, but rather stored elsewhere in a separate lookup
1000         // table. On older versions of gcc, they apparently always truncated the
1001         // section names (at least in some cases). Truncating the section name
1002         // actually creates "invalid" objects [1] [2], but only for some
1003         // introspection tools, not in terms of whether it can be loaded.
1004         //
1005         // Long story short, passing this flag forces the linker to *not*
1006         // truncate section names (so we can find the metadata section after
1007         // it's compiled). The real kicker is that rust compiled just fine on
1008         // windows for quite a long time *without* this flag, so I have no idea
1009         // why it suddenly started failing for liblibc. Regardless, we
1010         // definitely don't want section name truncation, so we're keeping this
1011         // flag for windows.
1012         //
1013         // [1] - https://sourceware.org/bugzilla/show_bug.cgi?id=13130
1014         // [2] - https://code.google.com/p/go/issues/detail?id=2139
1015         cmd.arg("-Wl,--enable-long-section-names");
1016
1017         // Always enable DEP (NX bit) when it is available
1018         cmd.arg("-Wl,--nxcompat");
1019
1020         // Mark all dynamic libraries and executables as compatible with ASLR
1021         cmd.arg("-Wl,--dynamicbase");
1022     }
1023
1024     if sess.targ_cfg.os == abi::OsAndroid {
1025         // Many of the symbols defined in compiler-rt are also defined in libgcc.
1026         // Android linker doesn't like that by default.
1027         cmd.arg("-Wl,--allow-multiple-definition");
1028     }
1029
1030     // Take careful note of the ordering of the arguments we pass to the linker
1031     // here. Linkers will assume that things on the left depend on things to the
1032     // right. Things on the right cannot depend on things on the left. This is
1033     // all formally implemented in terms of resolving symbols (libs on the right
1034     // resolve unknown symbols of libs on the left, but not vice versa).
1035     //
1036     // For this reason, we have organized the arguments we pass to the linker as
1037     // such:
1038     //
1039     //  1. The local object that LLVM just generated
1040     //  2. Upstream rust libraries
1041     //  3. Local native libraries
1042     //  4. Upstream native libraries
1043     //
1044     // This is generally fairly natural, but some may expect 2 and 3 to be
1045     // swapped. The reason that all native libraries are put last is that it's
1046     // not recommended for a native library to depend on a symbol from a rust
1047     // crate. If this is the case then a staticlib crate is recommended, solving
1048     // the problem.
1049     //
1050     // Additionally, it is occasionally the case that upstream rust libraries
1051     // depend on a local native library. In the case of libraries such as
1052     // lua/glfw/etc the name of the library isn't the same across all platforms,
1053     // so only the consumer crate of a library knows the actual name. This means
1054     // that downstream crates will provide the #[link] attribute which upstream
1055     // crates will depend on. Hence local native libraries are after out
1056     // upstream rust crates.
1057     //
1058     // In theory this means that a symbol in an upstream native library will be
1059     // shadowed by a local native library when it wouldn't have been before, but
1060     // this kind of behavior is pretty platform specific and generally not
1061     // recommended anyway, so I don't think we're shooting ourself in the foot
1062     // much with that.
1063     add_upstream_rust_crates(cmd, sess, dylib, tmpdir, trans);
1064     add_local_native_libraries(cmd, sess);
1065     add_upstream_native_libraries(cmd, sess);
1066
1067     // # Telling the linker what we're doing
1068
1069     if dylib {
1070         // On mac we need to tell the linker to let this library be rpathed
1071         if sess.targ_cfg.os == abi::OsMacos {
1072             cmd.args(["-dynamiclib", "-Wl,-dylib"]);
1073
1074             if sess.opts.cg.rpath {
1075                 let mut v = Vec::from_slice("-Wl,-install_name,@rpath/".as_bytes());
1076                 v.push_all(out_filename.filename().unwrap());
1077                 cmd.arg(v.as_slice());
1078             }
1079         } else {
1080             cmd.arg("-shared");
1081         }
1082     }
1083
1084     if sess.targ_cfg.os == abi::OsFreebsd {
1085         cmd.args(["-L/usr/local/lib",
1086                   "-L/usr/local/lib/gcc46",
1087                   "-L/usr/local/lib/gcc44"]);
1088     }
1089     else if sess.targ_cfg.os == abi::OsDragonfly {
1090         cmd.args(["-L/usr/local/lib",
1091                   "-L/usr/lib/gcc47",
1092                   "-L/usr/lib/gcc44"]);
1093     }
1094
1095
1096     // FIXME (#2397): At some point we want to rpath our guesses as to
1097     // where extern libraries might live, based on the
1098     // addl_lib_search_paths
1099     if sess.opts.cg.rpath {
1100         let sysroot = sess.sysroot();
1101         let target_triple = sess.opts.target_triple.as_slice();
1102         let get_install_prefix_lib_path = || {
1103             let install_prefix = option_env!("CFG_PREFIX").expect("CFG_PREFIX");
1104             let tlib = filesearch::relative_target_lib_path(sysroot, target_triple);
1105             let mut path = Path::new(install_prefix);
1106             path.push(&tlib);
1107
1108             path
1109         };
1110         let rpath_config = RPathConfig {
1111             os: sess.targ_cfg.os,
1112             used_crates: sess.cstore.get_used_crates(cstore::RequireDynamic),
1113             out_filename: out_filename.clone(),
1114             get_install_prefix_lib_path: get_install_prefix_lib_path,
1115             realpath: ::util::fs::realpath
1116         };
1117         cmd.args(rpath::get_rpath_flags(rpath_config).as_slice());
1118     }
1119
1120     // compiler-rt contains implementations of low-level LLVM helpers. This is
1121     // used to resolve symbols from the object file we just created, as well as
1122     // any system static libraries that may be expecting gcc instead. Most
1123     // symbols in libgcc also appear in compiler-rt.
1124     //
1125     // This is the end of the command line, so this library is used to resolve
1126     // *all* undefined symbols in all other libraries, and this is intentional.
1127     cmd.arg("-lcompiler-rt");
1128
1129     // Finally add all the linker arguments provided on the command line along
1130     // with any #[link_args] attributes found inside the crate
1131     cmd.args(sess.opts.cg.link_args.as_slice());
1132     cmd.args(used_link_args.as_slice());
1133 }
1134
1135 // # Native library linking
1136 //
1137 // User-supplied library search paths (-L on the command line). These are
1138 // the same paths used to find Rust crates, so some of them may have been
1139 // added already by the previous crate linking code. This only allows them
1140 // to be found at compile time so it is still entirely up to outside
1141 // forces to make sure that library can be found at runtime.
1142 //
1143 // Also note that the native libraries linked here are only the ones located
1144 // in the current crate. Upstream crates with native library dependencies
1145 // may have their native library pulled in above.
1146 fn add_local_native_libraries(cmd: &mut Command, sess: &Session) {
1147     for path in sess.opts.addl_lib_search_paths.borrow().iter() {
1148         cmd.arg("-L").arg(path);
1149     }
1150
1151     let rustpath = filesearch::rust_path();
1152     for path in rustpath.iter() {
1153         cmd.arg("-L").arg(path);
1154     }
1155
1156     // Some platforms take hints about whether a library is static or dynamic.
1157     // For those that support this, we ensure we pass the option if the library
1158     // was flagged "static" (most defaults are dynamic) to ensure that if
1159     // libfoo.a and libfoo.so both exist that the right one is chosen.
1160     let takes_hints = sess.targ_cfg.os != abi::OsMacos &&
1161                       sess.targ_cfg.os != abi::OsiOS;
1162
1163     let libs = sess.cstore.get_used_libraries();
1164     let libs = libs.borrow();
1165
1166     let mut staticlibs = libs.iter().filter_map(|&(ref l, kind)| {
1167         if kind == cstore::NativeStatic {Some(l)} else {None}
1168     });
1169     let mut others = libs.iter().filter(|&&(_, kind)| {
1170         kind != cstore::NativeStatic
1171     });
1172
1173     // Platforms that take hints generally also support the --whole-archive
1174     // flag. We need to pass this flag when linking static native libraries to
1175     // ensure the entire library is included.
1176     //
1177     // For more details see #15460, but the gist is that the linker will strip
1178     // away any unused objects in the archive if we don't otherwise explicitly
1179     // reference them. This can occur for libraries which are just providing
1180     // bindings, libraries with generic functions, etc.
1181     if takes_hints {
1182         cmd.arg("-Wl,--whole-archive").arg("-Wl,-Bstatic");
1183     }
1184     let search_path = archive_search_paths(sess);
1185     for l in staticlibs {
1186         if takes_hints {
1187             cmd.arg(format!("-l{}", l));
1188         } else {
1189             // -force_load is the OSX equivalent of --whole-archive, but it
1190             // involves passing the full path to the library to link.
1191             let lib = archive::find_library(l.as_slice(),
1192                                             sess.targ_cfg.os,
1193                                             search_path.as_slice(),
1194                                             &sess.diagnostic().handler);
1195             let mut v = b"-Wl,-force_load,".to_vec();
1196             v.push_all(lib.as_vec());
1197             cmd.arg(v.as_slice());
1198         }
1199     }
1200     if takes_hints {
1201         cmd.arg("-Wl,--no-whole-archive").arg("-Wl,-Bdynamic");
1202     }
1203
1204     for &(ref l, kind) in others {
1205         match kind {
1206             cstore::NativeUnknown => {
1207                 cmd.arg(format!("-l{}", l));
1208             }
1209             cstore::NativeFramework => {
1210                 cmd.arg("-framework").arg(l.as_slice());
1211             }
1212             cstore::NativeStatic => unreachable!(),
1213         }
1214     }
1215 }
1216
1217 // # Rust Crate linking
1218 //
1219 // Rust crates are not considered at all when creating an rlib output. All
1220 // dependencies will be linked when producing the final output (instead of
1221 // the intermediate rlib version)
1222 fn add_upstream_rust_crates(cmd: &mut Command, sess: &Session,
1223                             dylib: bool, tmpdir: &Path,
1224                             trans: &CrateTranslation) {
1225     // All of the heavy lifting has previously been accomplished by the
1226     // dependency_format module of the compiler. This is just crawling the
1227     // output of that module, adding crates as necessary.
1228     //
1229     // Linking to a rlib involves just passing it to the linker (the linker
1230     // will slurp up the object files inside), and linking to a dynamic library
1231     // involves just passing the right -l flag.
1232
1233     let data = if dylib {
1234         trans.crate_formats.get(&config::CrateTypeDylib)
1235     } else {
1236         trans.crate_formats.get(&config::CrateTypeExecutable)
1237     };
1238
1239     // Invoke get_used_crates to ensure that we get a topological sorting of
1240     // crates.
1241     let deps = sess.cstore.get_used_crates(cstore::RequireDynamic);
1242
1243     for &(cnum, _) in deps.iter() {
1244         // We may not pass all crates through to the linker. Some crates may
1245         // appear statically in an existing dylib, meaning we'll pick up all the
1246         // symbols from the dylib.
1247         let kind = match *data.get(cnum as uint - 1) {
1248             Some(t) => t,
1249             None => continue
1250         };
1251         let src = sess.cstore.get_used_crate_source(cnum).unwrap();
1252         match kind {
1253             cstore::RequireDynamic => {
1254                 add_dynamic_crate(cmd, sess, src.dylib.unwrap())
1255             }
1256             cstore::RequireStatic => {
1257                 add_static_crate(cmd, sess, tmpdir, src.rlib.unwrap())
1258             }
1259         }
1260
1261     }
1262
1263     // Converts a library file-stem into a cc -l argument
1264     fn unlib<'a>(config: &config::Config, stem: &'a [u8]) -> &'a [u8] {
1265         if stem.starts_with("lib".as_bytes()) && config.os != abi::OsWindows {
1266             stem.tailn(3)
1267         } else {
1268             stem
1269         }
1270     }
1271
1272     // Adds the static "rlib" versions of all crates to the command line.
1273     fn add_static_crate(cmd: &mut Command, sess: &Session, tmpdir: &Path,
1274                         cratepath: Path) {
1275         // When performing LTO on an executable output, all of the
1276         // bytecode from the upstream libraries has already been
1277         // included in our object file output. We need to modify all of
1278         // the upstream archives to remove their corresponding object
1279         // file to make sure we don't pull the same code in twice.
1280         //
1281         // We must continue to link to the upstream archives to be sure
1282         // to pull in native static dependencies. As the final caveat,
1283         // on Linux it is apparently illegal to link to a blank archive,
1284         // so if an archive no longer has any object files in it after
1285         // we remove `lib.o`, then don't link against it at all.
1286         //
1287         // If we're not doing LTO, then our job is simply to just link
1288         // against the archive.
1289         if sess.lto() {
1290             let name = cratepath.filename_str().unwrap();
1291             let name = name.slice(3, name.len() - 5); // chop off lib/.rlib
1292             time(sess.time_passes(),
1293                  format!("altering {}.rlib", name).as_slice(),
1294                  (), |()| {
1295                 let dst = tmpdir.join(cratepath.filename().unwrap());
1296                 match fs::copy(&cratepath, &dst) {
1297                     Ok(..) => {}
1298                     Err(e) => {
1299                         sess.err(format!("failed to copy {} to {}: {}",
1300                                          cratepath.display(),
1301                                          dst.display(),
1302                                          e).as_slice());
1303                         sess.abort_if_errors();
1304                     }
1305                 }
1306                 let handler = &sess.diagnostic().handler;
1307                 let config = ArchiveConfig {
1308                     handler: handler,
1309                     dst: dst.clone(),
1310                     lib_search_paths: archive_search_paths(sess),
1311                     os: sess.targ_cfg.os,
1312                     maybe_ar_prog: sess.opts.cg.ar.clone()
1313                 };
1314                 let mut archive = Archive::open(config);
1315                 archive.remove_file(format!("{}.o", name).as_slice());
1316                 let files = archive.files();
1317                 if files.iter().any(|s| s.as_slice().ends_with(".o")) {
1318                     cmd.arg(dst);
1319                 }
1320             });
1321         } else {
1322             cmd.arg(cratepath);
1323         }
1324     }
1325
1326     // Same thing as above, but for dynamic crates instead of static crates.
1327     fn add_dynamic_crate(cmd: &mut Command, sess: &Session, cratepath: Path) {
1328         // If we're performing LTO, then it should have been previously required
1329         // that all upstream rust dependencies were available in an rlib format.
1330         assert!(!sess.lto());
1331
1332         // Just need to tell the linker about where the library lives and
1333         // what its name is
1334         let dir = cratepath.dirname();
1335         if !dir.is_empty() { cmd.arg("-L").arg(dir); }
1336
1337         let mut v = Vec::from_slice("-l".as_bytes());
1338         v.push_all(unlib(&sess.targ_cfg, cratepath.filestem().unwrap()));
1339         cmd.arg(v.as_slice());
1340     }
1341 }
1342
1343 // Link in all of our upstream crates' native dependencies. Remember that
1344 // all of these upstream native dependencies are all non-static
1345 // dependencies. We've got two cases then:
1346 //
1347 // 1. The upstream crate is an rlib. In this case we *must* link in the
1348 // native dependency because the rlib is just an archive.
1349 //
1350 // 2. The upstream crate is a dylib. In order to use the dylib, we have to
1351 // have the dependency present on the system somewhere. Thus, we don't
1352 // gain a whole lot from not linking in the dynamic dependency to this
1353 // crate as well.
1354 //
1355 // The use case for this is a little subtle. In theory the native
1356 // dependencies of a crate are purely an implementation detail of the crate
1357 // itself, but the problem arises with generic and inlined functions. If a
1358 // generic function calls a native function, then the generic function must
1359 // be instantiated in the target crate, meaning that the native symbol must
1360 // also be resolved in the target crate.
1361 fn add_upstream_native_libraries(cmd: &mut Command, sess: &Session) {
1362     // Be sure to use a topological sorting of crates because there may be
1363     // interdependencies between native libraries. When passing -nodefaultlibs,
1364     // for example, almost all native libraries depend on libc, so we have to
1365     // make sure that's all the way at the right (liblibc is near the base of
1366     // the dependency chain).
1367     //
1368     // This passes RequireStatic, but the actual requirement doesn't matter,
1369     // we're just getting an ordering of crate numbers, we're not worried about
1370     // the paths.
1371     let crates = sess.cstore.get_used_crates(cstore::RequireStatic);
1372     for (cnum, _) in crates.move_iter() {
1373         let libs = csearch::get_native_libraries(&sess.cstore, cnum);
1374         for &(kind, ref lib) in libs.iter() {
1375             match kind {
1376                 cstore::NativeUnknown => {
1377                     cmd.arg(format!("-l{}", *lib));
1378                 }
1379                 cstore::NativeFramework => {
1380                     cmd.arg("-framework");
1381                     cmd.arg(lib.as_slice());
1382                 }
1383                 cstore::NativeStatic => {
1384                     sess.bug("statics shouldn't be propagated");
1385                 }
1386             }
1387         }
1388     }
1389 }