1 //! A helper class for dealing with static archives
4 use std::ffi::{CStr, CString, OsString};
7 use std::path::{Path, PathBuf};
12 use crate::llvm::archive_ro::{ArchiveRO, Child};
13 use crate::llvm::{self, ArchiveKind, LLVMMachineType, LLVMRustCOFFShortExport};
14 use rustc_codegen_ssa::back::archive::{ArchiveBuilder, ArchiveBuilderBuilder};
15 use rustc_session::cstore::DllImport;
16 use rustc_session::Session;
18 /// Helper for adding many files to an archive.
19 #[must_use = "must call build() to finish building the archive"]
20 pub struct LlvmArchiveBuilder<'a> {
22 additions: Vec<Addition>,
26 File { path: PathBuf, name_in_archive: String },
27 Archive { path: PathBuf, archive: ArchiveRO, skip: Box<dyn FnMut(&str) -> bool> },
31 fn path(&self) -> &Path {
33 Addition::File { path, .. } | Addition::Archive { path, .. } => path,
38 fn is_relevant_child(c: &Child<'_>) -> bool {
40 Some(name) => !name.contains("SYMDEF"),
45 /// Map machine type strings to values of LLVM's MachineTypes enum.
46 fn llvm_machine_type(cpu: &str) -> LLVMMachineType {
48 "x86_64" => LLVMMachineType::AMD64,
49 "x86" => LLVMMachineType::I386,
50 "aarch64" => LLVMMachineType::ARM64,
51 "arm" => LLVMMachineType::ARM,
52 _ => panic!("unsupported cpu type {}", cpu),
56 impl<'a> ArchiveBuilder<'a> for LlvmArchiveBuilder<'a> {
60 skip: Box<dyn FnMut(&str) -> bool + 'static>,
62 let archive_ro = match ArchiveRO::open(archive) {
64 Err(e) => return Err(io::Error::new(io::ErrorKind::Other, e)),
66 if self.additions.iter().any(|ar| ar.path() == archive) {
69 self.additions.push(Addition::Archive {
70 path: archive.to_path_buf(),
77 /// Adds an arbitrary file to this archive
78 fn add_file(&mut self, file: &Path) {
79 let name = file.file_name().unwrap().to_str().unwrap();
81 .push(Addition::File { path: file.to_path_buf(), name_in_archive: name.to_owned() });
84 /// Combine the provided files, rlibs, and native libraries into a single
86 fn build(mut self: Box<Self>, output: &Path) -> bool {
87 match self.build_with_llvm(output) {
88 Ok(any_members) => any_members,
89 Err(e) => self.sess.fatal(&format!("failed to build archive: {}", e)),
94 pub struct LlvmArchiveBuilderBuilder;
96 impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
97 fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder<'a> + 'a> {
98 Box::new(LlvmArchiveBuilder { sess, additions: Vec::new() })
101 fn create_dll_import_lib(
105 dll_imports: &[DllImport],
109 let mut output_path: PathBuf = tmpdir.to_path_buf();
110 output_path.push(format!("{}_imports", lib_name));
111 output_path.with_extension("lib")
114 let target = &sess.target;
115 let mingw_gnu_toolchain = common::is_mingw_gnu_toolchain(target);
117 let import_name_and_ordinal_vector: Vec<(String, Option<u16>)> = dll_imports
119 .map(|import: &DllImport| {
120 if sess.target.arch == "x86" {
122 common::i686_decorated_name(import, mingw_gnu_toolchain, false),
126 (import.name.to_string(), import.ordinal())
131 if mingw_gnu_toolchain {
132 // The binutils linker used on -windows-gnu targets cannot read the import
133 // libraries generated by LLVM: in our attempts, the linker produced an .EXE
134 // that loaded but crashed with an AV upon calling one of the imported
135 // functions. Therefore, use binutils to create the import library instead,
136 // by writing a .DEF file to the temp dir and calling binutils's dlltool.
137 let def_file_path = tmpdir.join(format!("{}_imports", lib_name)).with_extension("def");
139 let def_file_content = format!(
141 import_name_and_ordinal_vector
143 .map(|(name, ordinal)| {
145 Some(n) => format!("{} @{} NONAME", name, n),
149 .collect::<Vec<String>>()
153 match std::fs::write(&def_file_path, def_file_content) {
156 sess.fatal(&format!("Error writing .DEF file: {}", e));
160 // --no-leading-underscore: For the `import_name_type` feature to work, we need to be
161 // able to control the *exact* spelling of each of the symbols that are being imported:
162 // hence we don't want `dlltool` adding leading underscores automatically.
163 let dlltool = find_binutils_dlltool(sess);
164 let result = std::process::Command::new(dlltool)
167 def_file_path.to_str().unwrap(),
171 output_path.to_str().unwrap(),
172 "--no-leading-underscore",
178 sess.fatal(&format!("Error calling dlltool: {}", e));
180 Ok(output) if !output.status.success() => sess.fatal(&format!(
181 "Dlltool could not create import library: {}\n{}",
182 String::from_utf8_lossy(&output.stdout),
183 String::from_utf8_lossy(&output.stderr)
188 // we've checked for \0 characters in the library name already
189 let dll_name_z = CString::new(lib_name).unwrap();
191 let output_path_z = rustc_fs_util::path_to_c_string(&output_path);
193 trace!("invoking LLVMRustWriteImportLibrary");
194 trace!(" dll_name {:#?}", dll_name_z);
195 trace!(" output_path {}", output_path.display());
200 .map(|import| import.name.to_string())
205 // All import names are Rust identifiers and therefore cannot contain \0 characters.
206 // FIXME: when support for #[link_name] is implemented, ensure that the import names
207 // still don't contain any \0 characters. Also need to check that the names don't
208 // contain substrings like " @" or "NONAME" that are keywords or otherwise reserved
209 // in definition files.
210 let cstring_import_name_and_ordinal_vector: Vec<(CString, Option<u16>)> =
211 import_name_and_ordinal_vector
213 .map(|(name, ordinal)| (CString::new(name).unwrap(), ordinal))
216 let ffi_exports: Vec<LLVMRustCOFFShortExport> = cstring_import_name_and_ordinal_vector
218 .map(|(name_z, ordinal)| LLVMRustCOFFShortExport::new(name_z.as_ptr(), *ordinal))
220 let result = unsafe {
221 crate::llvm::LLVMRustWriteImportLibrary(
223 output_path_z.as_ptr(),
224 ffi_exports.as_ptr(),
226 llvm_machine_type(&sess.target.arch) as u16,
227 !sess.target.is_like_msvc,
231 if result == crate::llvm::LLVMRustResult::Failure {
233 "Error creating import library for {}: {}",
235 llvm::last_error().unwrap_or("unknown LLVM error".to_string())
244 impl<'a> LlvmArchiveBuilder<'a> {
245 fn build_with_llvm(&mut self, output: &Path) -> io::Result<bool> {
246 let kind = &*self.sess.target.archive_format;
247 let kind = kind.parse::<ArchiveKind>().map_err(|_| kind).unwrap_or_else(|kind| {
248 self.sess.fatal(&format!("Don't know how to build archive of type: {}", kind))
251 let mut additions = mem::take(&mut self.additions);
252 let mut strings = Vec::new();
253 let mut members = Vec::new();
255 let dst = CString::new(output.to_str().unwrap())?;
258 for addition in &mut additions {
260 Addition::File { path, name_in_archive } => {
261 let path = CString::new(path.to_str().unwrap())?;
262 let name = CString::new(name_in_archive.clone())?;
263 members.push(llvm::LLVMRustArchiveMemberNew(
271 Addition::Archive { archive, skip, .. } => {
272 for child in archive.iter() {
273 let child = child.map_err(string_to_io_error)?;
274 if !is_relevant_child(&child) {
277 let child_name = child.name().unwrap();
278 if skip(child_name) {
282 // It appears that LLVM's archive writer is a little
283 // buggy if the name we pass down isn't just the
284 // filename component, so chop that off here and
287 // See LLVM bug 25877 for more info.
289 Path::new(child_name).file_name().unwrap().to_str().unwrap();
290 let name = CString::new(child_name)?;
291 let m = llvm::LLVMRustArchiveMemberNew(
303 let r = llvm::LLVMRustWriteArchive(
305 members.len() as libc::size_t,
306 members.as_ptr() as *const &_,
310 let ret = if r.into_result().is_err() {
311 let err = llvm::LLVMRustGetLastError();
312 let msg = if err.is_null() {
313 "failed to write archive".into()
315 String::from_utf8_lossy(CStr::from_ptr(err).to_bytes())
317 Err(io::Error::new(io::ErrorKind::Other, msg))
319 Ok(!members.is_empty())
321 for member in members {
322 llvm::LLVMRustArchiveMemberFree(member);
329 fn string_to_io_error(s: String) -> io::Error {
330 io::Error::new(io::ErrorKind::Other, format!("bad archive: {}", s))
333 fn find_binutils_dlltool(sess: &Session) -> OsString {
334 assert!(sess.target.options.is_like_windows && !sess.target.options.is_like_msvc);
335 if let Some(dlltool_path) = &sess.opts.unstable_opts.dlltool {
336 return dlltool_path.clone().into_os_string();
339 let mut tool_name: OsString = if sess.host.arch != sess.target.arch {
340 // We are cross-compiling, so we need the tool with the prefix matching our target
341 if sess.target.arch == "x86" {
342 "i686-w64-mingw32-dlltool"
344 "x86_64-w64-mingw32-dlltool"
347 // We are not cross-compiling, so we just want `dlltool`
352 if sess.host.options.is_like_windows {
353 // If we're compiling on Windows, add the .exe suffix
354 tool_name.push(".exe");
357 // NOTE: it's not clear how useful it is to explicitly search PATH.
358 for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
359 let full_path = dir.join(&tool_name);
360 if full_path.is_file() {
361 return full_path.into_os_string();
365 // The user didn't specify the location of the dlltool binary, and we weren't able
366 // to find the appropriate one on the PATH. Just return the name of the tool
367 // and let the invocation fail with a hopefully useful error message.