]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/back/archive.rs
Rollup merge of #106960 - estebank:parse-anon-enums, r=cjgillot
[rust.git] / compiler / rustc_codegen_llvm / src / back / archive.rs
1 //! A helper class for dealing with static archives
2
3 use std::env;
4 use std::ffi::{c_char, c_void, CStr, CString, OsString};
5 use std::io;
6 use std::mem;
7 use std::path::{Path, PathBuf};
8 use std::ptr;
9 use std::str;
10
11 use crate::common;
12 use crate::errors::{
13     DlltoolFailImportLibrary, ErrorCallingDllTool, ErrorCreatingImportLibrary, ErrorWritingDEFFile,
14 };
15 use crate::llvm::archive_ro::{ArchiveRO, Child};
16 use crate::llvm::{self, ArchiveKind, LLVMMachineType, LLVMRustCOFFShortExport};
17 use rustc_codegen_ssa::back::archive::{
18     get_native_object_symbols, ArArchiveBuilder, ArchiveBuildFailure, ArchiveBuilder,
19     ArchiveBuilderBuilder, UnknownArchiveKind,
20 };
21
22 use rustc_session::cstore::DllImport;
23 use rustc_session::Session;
24
25 /// Helper for adding many files to an archive.
26 #[must_use = "must call build() to finish building the archive"]
27 pub(crate) struct LlvmArchiveBuilder<'a> {
28     sess: &'a Session,
29     additions: Vec<Addition>,
30 }
31
32 enum Addition {
33     File { path: PathBuf, name_in_archive: String },
34     Archive { path: PathBuf, archive: ArchiveRO, skip: Box<dyn FnMut(&str) -> bool> },
35 }
36
37 impl Addition {
38     fn path(&self) -> &Path {
39         match self {
40             Addition::File { path, .. } | Addition::Archive { path, .. } => path,
41         }
42     }
43 }
44
45 fn is_relevant_child(c: &Child<'_>) -> bool {
46     match c.name() {
47         Some(name) => !name.contains("SYMDEF"),
48         None => false,
49     }
50 }
51
52 /// Map machine type strings to values of LLVM's MachineTypes enum.
53 fn llvm_machine_type(cpu: &str) -> LLVMMachineType {
54     match cpu {
55         "x86_64" => LLVMMachineType::AMD64,
56         "x86" => LLVMMachineType::I386,
57         "aarch64" => LLVMMachineType::ARM64,
58         "arm" => LLVMMachineType::ARM,
59         _ => panic!("unsupported cpu type {}", cpu),
60     }
61 }
62
63 impl<'a> ArchiveBuilder<'a> for LlvmArchiveBuilder<'a> {
64     fn add_archive(
65         &mut self,
66         archive: &Path,
67         skip: Box<dyn FnMut(&str) -> bool + 'static>,
68     ) -> io::Result<()> {
69         let archive_ro = match ArchiveRO::open(archive) {
70             Ok(ar) => ar,
71             Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
72         };
73         if self.additions.iter().any(|ar| ar.path() == archive) {
74             return Ok(());
75         }
76         self.additions.push(Addition::Archive {
77             path: archive.to_path_buf(),
78             archive: archive_ro,
79             skip: Box::new(skip),
80         });
81         Ok(())
82     }
83
84     /// Adds an arbitrary file to this archive
85     fn add_file(&mut self, file: &Path) {
86         let name = file.file_name().unwrap().to_str().unwrap();
87         self.additions
88             .push(Addition::File { path: file.to_path_buf(), name_in_archive: name.to_owned() });
89     }
90
91     /// Combine the provided files, rlibs, and native libraries into a single
92     /// `Archive`.
93     fn build(mut self: Box<Self>, output: &Path) -> bool {
94         match self.build_with_llvm(output) {
95             Ok(any_members) => any_members,
96             Err(e) => self.sess.emit_fatal(ArchiveBuildFailure { error: e }),
97         }
98     }
99 }
100
101 pub struct LlvmArchiveBuilderBuilder;
102
103 impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
104     fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder<'a> + 'a> {
105         if sess.target.arch == "wasm32" || sess.target.arch == "wasm64" {
106             Box::new(LlvmArchiveBuilder { sess, additions: Vec::new() })
107         } else {
108             Box::new(ArArchiveBuilder::new(sess, get_llvm_object_symbols))
109         }
110     }
111
112     fn create_dll_import_lib(
113         &self,
114         sess: &Session,
115         lib_name: &str,
116         dll_imports: &[DllImport],
117         tmpdir: &Path,
118         is_direct_dependency: bool,
119     ) -> PathBuf {
120         let name_suffix = if is_direct_dependency { "_imports" } else { "_imports_indirect" };
121         let output_path = {
122             let mut output_path: PathBuf = tmpdir.to_path_buf();
123             output_path.push(format!("{}{}", lib_name, name_suffix));
124             output_path.with_extension("lib")
125         };
126
127         let target = &sess.target;
128         let mingw_gnu_toolchain = common::is_mingw_gnu_toolchain(target);
129
130         let import_name_and_ordinal_vector: Vec<(String, Option<u16>)> = dll_imports
131             .iter()
132             .map(|import: &DllImport| {
133                 if sess.target.arch == "x86" {
134                     (
135                         common::i686_decorated_name(import, mingw_gnu_toolchain, false),
136                         import.ordinal(),
137                     )
138                 } else {
139                     (import.name.to_string(), import.ordinal())
140                 }
141             })
142             .collect();
143
144         if mingw_gnu_toolchain {
145             // The binutils linker used on -windows-gnu targets cannot read the import
146             // libraries generated by LLVM: in our attempts, the linker produced an .EXE
147             // that loaded but crashed with an AV upon calling one of the imported
148             // functions. Therefore, use binutils to create the import library instead,
149             // by writing a .DEF file to the temp dir and calling binutils's dlltool.
150             let def_file_path =
151                 tmpdir.join(format!("{}{}", lib_name, name_suffix)).with_extension("def");
152
153             let def_file_content = format!(
154                 "EXPORTS\n{}",
155                 import_name_and_ordinal_vector
156                     .into_iter()
157                     .map(|(name, ordinal)| {
158                         match ordinal {
159                             Some(n) => format!("{} @{} NONAME", name, n),
160                             None => name,
161                         }
162                     })
163                     .collect::<Vec<String>>()
164                     .join("\n")
165             );
166
167             match std::fs::write(&def_file_path, def_file_content) {
168                 Ok(_) => {}
169                 Err(e) => {
170                     sess.emit_fatal(ErrorWritingDEFFile { error: e });
171                 }
172             };
173
174             // --no-leading-underscore: For the `import_name_type` feature to work, we need to be
175             // able to control the *exact* spelling of each of the symbols that are being imported:
176             // hence we don't want `dlltool` adding leading underscores automatically.
177             let dlltool = find_binutils_dlltool(sess);
178             let result = std::process::Command::new(dlltool)
179                 .args([
180                     "-d",
181                     def_file_path.to_str().unwrap(),
182                     "-D",
183                     lib_name,
184                     "-l",
185                     output_path.to_str().unwrap(),
186                     "--no-leading-underscore",
187                 ])
188                 .output();
189
190             match result {
191                 Err(e) => {
192                     sess.emit_fatal(ErrorCallingDllTool { error: e });
193                 }
194                 Ok(output) if !output.status.success() => {
195                     sess.emit_fatal(DlltoolFailImportLibrary {
196                         stdout: String::from_utf8_lossy(&output.stdout),
197                         stderr: String::from_utf8_lossy(&output.stderr),
198                     })
199                 }
200                 _ => {}
201             }
202         } else {
203             // we've checked for \0 characters in the library name already
204             let dll_name_z = CString::new(lib_name).unwrap();
205
206             let output_path_z = rustc_fs_util::path_to_c_string(&output_path);
207
208             trace!("invoking LLVMRustWriteImportLibrary");
209             trace!("  dll_name {:#?}", dll_name_z);
210             trace!("  output_path {}", output_path.display());
211             trace!(
212                 "  import names: {}",
213                 dll_imports
214                     .iter()
215                     .map(|import| import.name.to_string())
216                     .collect::<Vec<_>>()
217                     .join(", "),
218             );
219
220             // All import names are Rust identifiers and therefore cannot contain \0 characters.
221             // FIXME: when support for #[link_name] is implemented, ensure that the import names
222             // still don't contain any \0 characters. Also need to check that the names don't
223             // contain substrings like " @" or "NONAME" that are keywords or otherwise reserved
224             // in definition files.
225             let cstring_import_name_and_ordinal_vector: Vec<(CString, Option<u16>)> =
226                 import_name_and_ordinal_vector
227                     .into_iter()
228                     .map(|(name, ordinal)| (CString::new(name).unwrap(), ordinal))
229                     .collect();
230
231             let ffi_exports: Vec<LLVMRustCOFFShortExport> = cstring_import_name_and_ordinal_vector
232                 .iter()
233                 .map(|(name_z, ordinal)| LLVMRustCOFFShortExport::new(name_z.as_ptr(), *ordinal))
234                 .collect();
235             let result = unsafe {
236                 crate::llvm::LLVMRustWriteImportLibrary(
237                     dll_name_z.as_ptr(),
238                     output_path_z.as_ptr(),
239                     ffi_exports.as_ptr(),
240                     ffi_exports.len(),
241                     llvm_machine_type(&sess.target.arch) as u16,
242                     !sess.target.is_like_msvc,
243                 )
244             };
245
246             if result == crate::llvm::LLVMRustResult::Failure {
247                 sess.emit_fatal(ErrorCreatingImportLibrary {
248                     lib_name,
249                     error: llvm::last_error().unwrap_or("unknown LLVM error".to_string()),
250                 });
251             }
252         };
253
254         output_path
255     }
256 }
257
258 // The object crate doesn't know how to get symbols for LLVM bitcode and COFF bigobj files.
259 // As such we need to use LLVM for them.
260 #[deny(unsafe_op_in_unsafe_fn)]
261 fn get_llvm_object_symbols(
262     buf: &[u8],
263     f: &mut dyn FnMut(&[u8]) -> io::Result<()>,
264 ) -> io::Result<bool> {
265     let is_bitcode = unsafe { llvm::LLVMRustIsBitcode(buf.as_ptr(), buf.len()) };
266
267     // COFF bigobj file, msvc LTO file or import library. See
268     // https://github.com/llvm/llvm-project/blob/453f27bc9/llvm/lib/BinaryFormat/Magic.cpp#L38-L51
269     let is_unsupported_windows_obj_file = buf.get(0..4) == Some(b"\0\0\xFF\xFF");
270
271     if is_bitcode || is_unsupported_windows_obj_file {
272         let mut state = Box::new(f);
273
274         let err = unsafe {
275             llvm::LLVMRustGetSymbols(
276                 buf.as_ptr(),
277                 buf.len(),
278                 &mut *state as *mut &mut _ as *mut c_void,
279                 callback,
280                 error_callback,
281             )
282         };
283
284         if err.is_null() {
285             return Ok(true);
286         } else {
287             return Err(unsafe { *Box::from_raw(err as *mut io::Error) });
288         }
289
290         unsafe extern "C" fn callback(
291             state: *mut c_void,
292             symbol_name: *const c_char,
293         ) -> *mut c_void {
294             let f = unsafe { &mut *(state as *mut &mut dyn FnMut(&[u8]) -> io::Result<()>) };
295             match f(unsafe { CStr::from_ptr(symbol_name) }.to_bytes()) {
296                 Ok(()) => std::ptr::null_mut(),
297                 Err(err) => Box::into_raw(Box::new(err)) as *mut c_void,
298             }
299         }
300
301         unsafe extern "C" fn error_callback(error: *const c_char) -> *mut c_void {
302             let error = unsafe { CStr::from_ptr(error) };
303             Box::into_raw(Box::new(io::Error::new(
304                 io::ErrorKind::Other,
305                 format!("LLVM error: {}", error.to_string_lossy()),
306             ))) as *mut c_void
307         }
308     } else {
309         get_native_object_symbols(buf, f)
310     }
311 }
312
313 impl<'a> LlvmArchiveBuilder<'a> {
314     fn build_with_llvm(&mut self, output: &Path) -> io::Result<bool> {
315         let kind = &*self.sess.target.archive_format;
316         let kind = kind
317             .parse::<ArchiveKind>()
318             .map_err(|_| kind)
319             .unwrap_or_else(|kind| self.sess.emit_fatal(UnknownArchiveKind { kind }));
320
321         let mut additions = mem::take(&mut self.additions);
322         let mut strings = Vec::new();
323         let mut members = Vec::new();
324
325         let dst = CString::new(output.to_str().unwrap())?;
326
327         unsafe {
328             for addition in &mut additions {
329                 match addition {
330                     Addition::File { path, name_in_archive } => {
331                         let path = CString::new(path.to_str().unwrap())?;
332                         let name = CString::new(name_in_archive.clone())?;
333                         members.push(llvm::LLVMRustArchiveMemberNew(
334                             path.as_ptr(),
335                             name.as_ptr(),
336                             None,
337                         ));
338                         strings.push(path);
339                         strings.push(name);
340                     }
341                     Addition::Archive { archive, skip, .. } => {
342                         for child in archive.iter() {
343                             let child = child.map_err(string_to_io_error)?;
344                             if !is_relevant_child(&child) {
345                                 continue;
346                             }
347                             let child_name = child.name().unwrap();
348                             if skip(child_name) {
349                                 continue;
350                             }
351
352                             // It appears that LLVM's archive writer is a little
353                             // buggy if the name we pass down isn't just the
354                             // filename component, so chop that off here and
355                             // pass it in.
356                             //
357                             // See LLVM bug 25877 for more info.
358                             let child_name =
359                                 Path::new(child_name).file_name().unwrap().to_str().unwrap();
360                             let name = CString::new(child_name)?;
361                             let m = llvm::LLVMRustArchiveMemberNew(
362                                 ptr::null(),
363                                 name.as_ptr(),
364                                 Some(child.raw),
365                             );
366                             members.push(m);
367                             strings.push(name);
368                         }
369                     }
370                 }
371             }
372
373             let r = llvm::LLVMRustWriteArchive(
374                 dst.as_ptr(),
375                 members.len() as libc::size_t,
376                 members.as_ptr() as *const &_,
377                 true,
378                 kind,
379             );
380             let ret = if r.into_result().is_err() {
381                 let err = llvm::LLVMRustGetLastError();
382                 let msg = if err.is_null() {
383                     "failed to write archive".into()
384                 } else {
385                     String::from_utf8_lossy(CStr::from_ptr(err).to_bytes())
386                 };
387                 Err(io::Error::new(io::ErrorKind::Other, msg))
388             } else {
389                 Ok(!members.is_empty())
390             };
391             for member in members {
392                 llvm::LLVMRustArchiveMemberFree(member);
393             }
394             ret
395         }
396     }
397 }
398
399 fn string_to_io_error(s: String) -> io::Error {
400     io::Error::new(io::ErrorKind::Other, format!("bad archive: {}", s))
401 }
402
403 fn find_binutils_dlltool(sess: &Session) -> OsString {
404     assert!(sess.target.options.is_like_windows && !sess.target.options.is_like_msvc);
405     if let Some(dlltool_path) = &sess.opts.unstable_opts.dlltool {
406         return dlltool_path.clone().into_os_string();
407     }
408
409     let mut tool_name: OsString = if sess.host.arch != sess.target.arch {
410         // We are cross-compiling, so we need the tool with the prefix matching our target
411         if sess.target.arch == "x86" {
412             "i686-w64-mingw32-dlltool"
413         } else {
414             "x86_64-w64-mingw32-dlltool"
415         }
416     } else {
417         // We are not cross-compiling, so we just want `dlltool`
418         "dlltool"
419     }
420     .into();
421
422     if sess.host.options.is_like_windows {
423         // If we're compiling on Windows, add the .exe suffix
424         tool_name.push(".exe");
425     }
426
427     // NOTE: it's not clear how useful it is to explicitly search PATH.
428     for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
429         let full_path = dir.join(&tool_name);
430         if full_path.is_file() {
431             return full_path.into_os_string();
432         }
433     }
434
435     // The user didn't specify the location of the dlltool binary, and we weren't able
436     // to find the appropriate one on the PATH. Just return the name of the tool
437     // and let the invocation fail with a hopefully useful error message.
438     tool_name
439 }