1 //! Related to out filenames of compilation (e.g. save analysis, binaries).
2 use crate::config::{CrateType, Input, OutFileName, OutputFilenames, OutputType};
3 use crate::errors::{
4 CrateNameDoesNotMatch, CrateNameEmpty, CrateNameInvalid, FileIsNotWriteable,
5 InvalidCharacterInCrateName,
6 };
7 use crate::Session;
8 use rustc_ast::{self as ast, attr};
9 use rustc_span::symbol::sym;
10 use rustc_span::{Span, Symbol};
11 use std::path::Path;
12
out_filename( sess: &Session, crate_type: CrateType, outputs: &OutputFilenames, crate_name: Symbol, ) -> OutFileName13 pub fn out_filename(
14 sess: &Session,
15 crate_type: CrateType,
16 outputs: &OutputFilenames,
17 crate_name: Symbol,
18 ) -> OutFileName {
19 let default_filename = filename_for_input(sess, crate_type, crate_name, outputs);
20 let out_filename = outputs
21 .outputs
22 .get(&OutputType::Exe)
23 .and_then(|s| s.to_owned())
24 .or_else(|| outputs.single_output_file.clone())
25 .unwrap_or(default_filename);
26
27 if let OutFileName::Real(ref path) = out_filename {
28 check_file_is_writeable(path, sess);
29 }
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.
check_file_is_writeable(file: &Path, sess: &Session)37 pub fn check_file_is_writeable(file: &Path, sess: &Session) {
38 if !is_writeable(file) {
39 sess.emit_fatal(FileIsNotWriteable { file });
40 }
41 }
42
is_writeable(p: &Path) -> bool43 fn is_writeable(p: &Path) -> bool {
44 match p.metadata() {
45 Err(..) => true,
46 Ok(m) => !m.permissions().readonly(),
47 }
48 }
49
find_crate_name(sess: &Session, attrs: &[ast::Attribute]) -> Symbol50 pub fn find_crate_name(sess: &Session, attrs: &[ast::Attribute]) -> Symbol {
51 let validate = |s: Symbol, span: Option<Span>| {
52 validate_crate_name(sess, s, span);
53 s
54 };
55
56 // Look in attributes 100% of the time to make sure the attribute is marked
57 // as used. After doing this, however, we still prioritize a crate name from
58 // the command line over one found in the #[crate_name] attribute. If we
59 // find both we ensure that they're the same later on as well.
60 let attr_crate_name =
61 attr::find_by_name(attrs, sym::crate_name).and_then(|at| at.value_str().map(|s| (at, s)));
62
63 if let Some(ref s) = sess.opts.crate_name {
64 let s = Symbol::intern(s);
65 if let Some((attr, name)) = attr_crate_name {
66 if name != s {
67 sess.emit_err(CrateNameDoesNotMatch { span: attr.span, s, name });
68 }
69 }
70 return validate(s, None);
71 }
72
73 if let Some((attr, s)) = attr_crate_name {
74 return validate(s, Some(attr.span));
75 }
76 if let Input::File(ref path) = sess.io.input {
77 if let Some(s) = path.file_stem().and_then(|s| s.to_str()) {
78 if s.starts_with('-') {
79 sess.emit_err(CrateNameInvalid { s });
80 } else {
81 return validate(Symbol::intern(&s.replace('-', "_")), None);
82 }
83 }
84 }
85
86 Symbol::intern("rust_out")
87 }
88
validate_crate_name(sess: &Session, s: Symbol, sp: Option<Span>)89 pub fn validate_crate_name(sess: &Session, s: Symbol, sp: Option<Span>) {
90 let mut err_count = 0;
91 {
92 if s.is_empty() {
93 err_count += 1;
94 sess.emit_err(CrateNameEmpty { span: sp });
95 }
96 for c in s.as_str().chars() {
97 if c.is_alphanumeric() {
98 continue;
99 }
100 if c == '_' {
101 continue;
102 }
103 err_count += 1;
104 sess.emit_err(InvalidCharacterInCrateName { span: sp, character: c, crate_name: s });
105 }
106 }
107
108 if err_count > 0 {
109 sess.abort_if_errors();
110 }
111 }
112
filename_for_metadata( sess: &Session, crate_name: Symbol, outputs: &OutputFilenames, ) -> OutFileName113 pub fn filename_for_metadata(
114 sess: &Session,
115 crate_name: Symbol,
116 outputs: &OutputFilenames,
117 ) -> OutFileName {
118 // If the command-line specified the path, use that directly.
119 if let Some(Some(out_filename)) = sess.opts.output_types.get(&OutputType::Metadata) {
120 return out_filename.clone();
121 }
122
123 let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
124
125 let out_filename = outputs.single_output_file.clone().unwrap_or_else(|| {
126 OutFileName::Real(outputs.out_directory.join(&format!("lib{libname}.rmeta")))
127 });
128
129 if let OutFileName::Real(ref path) = out_filename {
130 check_file_is_writeable(path, sess);
131 }
132
133 out_filename
134 }
135
filename_for_input( sess: &Session, crate_type: CrateType, crate_name: Symbol, outputs: &OutputFilenames, ) -> OutFileName136 pub fn filename_for_input(
137 sess: &Session,
138 crate_type: CrateType,
139 crate_name: Symbol,
140 outputs: &OutputFilenames,
141 ) -> OutFileName {
142 let libname = format!("{}{}", crate_name, sess.opts.cg.extra_filename);
143
144 match crate_type {
145 CrateType::Rlib => {
146 OutFileName::Real(outputs.out_directory.join(&format!("lib{libname}.rlib")))
147 }
148 CrateType::Cdylib | CrateType::ProcMacro | CrateType::Dylib => {
149 let (prefix, suffix) = (&sess.target.dll_prefix, &sess.target.dll_suffix);
150 OutFileName::Real(outputs.out_directory.join(&format!("{prefix}{libname}{suffix}")))
151 }
152 CrateType::Staticlib => {
153 let (prefix, suffix) = (&sess.target.staticlib_prefix, &sess.target.staticlib_suffix);
154 OutFileName::Real(outputs.out_directory.join(&format!("{prefix}{libname}{suffix}")))
155 }
156 CrateType::Executable => {
157 let suffix = &sess.target.exe_suffix;
158 let out_filename = outputs.path(OutputType::Exe);
159 if let OutFileName::Real(ref path) = out_filename {
160 if suffix.is_empty() {
161 out_filename
162 } else {
163 OutFileName::Real(path.with_extension(&suffix[1..]))
164 }
165 } else {
166 out_filename
167 }
168 }
169 }
170 }
171
172 /// Returns default crate type for target
173 ///
174 /// Default crate type is used when crate type isn't provided neither
175 /// through cmd line arguments nor through crate attributes
176 ///
177 /// It is CrateType::Executable for all platforms but iOS as there is no
178 /// way to run iOS binaries anyway without jailbreaking and
179 /// interaction with Rust code through static library is the only
180 /// option for now
default_output_for_target(sess: &Session) -> CrateType181 pub fn default_output_for_target(sess: &Session) -> CrateType {
182 if !sess.target.executables { CrateType::Staticlib } else { CrateType::Executable }
183 }
184
185 /// Checks if target supports crate_type as output
invalid_output_for_target(sess: &Session, crate_type: CrateType) -> bool186 pub fn invalid_output_for_target(sess: &Session, crate_type: CrateType) -> bool {
187 if let CrateType::Cdylib | CrateType::Dylib | CrateType::ProcMacro = crate_type {
188 if !sess.target.dynamic_linking {
189 return true;
190 }
191 if sess.crt_static(Some(crate_type)) && !sess.target.crt_static_allows_dylibs {
192 return true;
193 }
194 }
195 if let CrateType::ProcMacro | CrateType::Dylib = crate_type && sess.target.only_cdylib {
196 return true;
197 }
198 if let CrateType::Executable = crate_type && !sess.target.executables {
199 return true;
200 }
201
202 false
203 }
204