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