]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_utils/link.rs
Separate codepaths for fat and thin LTO in write.rs
[rust.git] / src / librustc_codegen_utils / link.rs
1 // Copyright 2017 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 rustc::session::config::{self, OutputFilenames, Input, OutputType};
12 use rustc::session::Session;
13 use std::path::{Path, PathBuf};
14 use syntax::{ast, attr};
15 use syntax_pos::Span;
16
17 pub fn out_filename(sess: &Session,
18                 crate_type: config::CrateType,
19                 outputs: &OutputFilenames,
20                 crate_name: &str)
21                 -> PathBuf {
22     let default_filename = filename_for_input(sess, crate_type, crate_name, outputs);
23     let out_filename = outputs.outputs.get(&OutputType::Exe)
24                               .and_then(|s| s.to_owned())
25                               .or_else(|| outputs.single_output_file.clone())
26                               .unwrap_or(default_filename);
27
28     check_file_is_writeable(&out_filename, sess);
29
30     out_filename
31 }
32
33 // Make sure files are writeable.  Mac, FreeBSD, and Windows system linkers
34 // check this already -- however, the Linux linker will happily overwrite a
35 // read-only file.  We should be consistent.
36 pub fn check_file_is_writeable(file: &Path, sess: &Session) {
37     if !is_writeable(file) {
38         sess.fatal(&format!("output file {} is not writeable -- check its \
39                             permissions", file.display()));
40     }
41 }
42
43 fn is_writeable(p: &Path) -> bool {
44     match p.metadata() {
45         Err(..) => true,
46         Ok(m) => !m.permissions().readonly()
47     }
48 }
49
50 pub fn find_crate_name(sess: Option<&Session>,
51                        attrs: &[ast::Attribute],
52                        input: &Input) -> String {
53     let validate = |s: String, span: Option<Span>| {
54         ::rustc_metadata::validate_crate_name(sess, &s, span);
55         s
56     };
57
58     // Look in attributes 100% of the time to make sure the attribute is marked
59     // as used. After doing this, however, we still prioritize a crate name from
60     // the command line over one found in the #[crate_name] attribute. If we
61     // find both we ensure that they're the same later on as well.
62     let attr_crate_name = attr::find_by_name(attrs, "crate_name")
63         .and_then(|at| at.value_str().map(|s| (at, s)));
64
65     if let Some(sess) = sess {
66         if let Some(ref s) = sess.opts.crate_name {
67             if let Some((attr, name)) = attr_crate_name {
68                 if name != &**s {
69                     let msg = format!("--crate-name and #[crate_name] are \
70                                        required to match, but `{}` != `{}`",
71                                       s, name);
72                     sess.span_err(attr.span, &msg);
73                 }
74             }
75             return validate(s.clone(), None);
76         }
77     }
78
79     if let Some((attr, s)) = attr_crate_name {
80         return validate(s.to_string(), Some(attr.span));
81     }
82     if let Input::File(ref path) = *input {
83         if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
84             if s.starts_with("-") {
85                 let msg = format!("crate names cannot start with a `-`, but \
86                                    `{}` has a leading hyphen", s);
87                 if let Some(sess) = sess {
88                     sess.err(&msg);
89                 }
90             } else {
91                 return validate(s.replace("-", "_"), None);
92             }
93         }
94     }
95
96     "rust_out".to_string()
97 }
98
99 pub fn filename_for_metadata(sess: &Session,
100                              crate_name: &str,
101                              outputs: &OutputFilenames) -> PathBuf {
102     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
103
104     let out_filename = outputs.single_output_file.clone()
105         .unwrap_or_else(|| outputs.out_directory.join(&format!("lib{}.rmeta", libname)));
106
107     check_file_is_writeable(&out_filename, sess);
108
109     out_filename
110 }
111
112 pub fn filename_for_input(sess: &Session,
113                           crate_type: config::CrateType,
114                           crate_name: &str,
115                           outputs: &OutputFilenames) -> PathBuf {
116     let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
117
118     match crate_type {
119         config::CrateType::Rlib => {
120             outputs.out_directory.join(&format!("lib{}.rlib", libname))
121         }
122         config::CrateType::Cdylib |
123         config::CrateType::ProcMacro |
124         config::CrateType::Dylib => {
125             let (prefix, suffix) = (&sess.target.target.options.dll_prefix,
126                                     &sess.target.target.options.dll_suffix);
127             outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
128                                                 suffix))
129         }
130         config::CrateType::Staticlib => {
131             let (prefix, suffix) = (&sess.target.target.options.staticlib_prefix,
132                                     &sess.target.target.options.staticlib_suffix);
133             outputs.out_directory.join(&format!("{}{}{}", prefix, libname,
134                                                 suffix))
135         }
136         config::CrateType::Executable => {
137             let suffix = &sess.target.target.options.exe_suffix;
138             let out_filename = outputs.path(OutputType::Exe);
139             if suffix.is_empty() {
140                 out_filename
141             } else {
142                 out_filename.with_extension(&suffix[1..])
143             }
144         }
145     }
146 }
147
148 /// Returns default crate type for target
149 ///
150 /// Default crate type is used when crate type isn't provided neither
151 /// through cmd line arguments nor through crate attributes
152 ///
153 /// It is CrateType::Executable for all platforms but iOS as there is no
154 /// way to run iOS binaries anyway without jailbreaking and
155 /// interaction with Rust code through static library is the only
156 /// option for now
157 pub fn default_output_for_target(sess: &Session) -> config::CrateType {
158     if !sess.target.target.options.executables {
159         config::CrateType::Staticlib
160     } else {
161         config::CrateType::Executable
162     }
163 }
164
165 /// Checks if target supports crate_type as output
166 pub fn invalid_output_for_target(sess: &Session,
167                                  crate_type: config::CrateType) -> bool {
168     match crate_type {
169         config::CrateType::Cdylib |
170         config::CrateType::Dylib |
171         config::CrateType::ProcMacro => {
172             if !sess.target.target.options.dynamic_linking {
173                 return true
174             }
175             if sess.crt_static() && !sess.target.target.options.crt_static_allows_dylibs {
176                 return true
177             }
178         }
179         _ => {}
180     }
181     if sess.target.target.options.only_cdylib {
182         match crate_type {
183             config::CrateType::ProcMacro | config::CrateType::Dylib => return true,
184             _ => {}
185         }
186     }
187     if !sess.target.target.options.executables {
188         if crate_type == config::CrateType::Executable {
189             return true
190         }
191     }
192
193     false
194 }