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