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