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