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