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