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