Skip to main content

rustc_codegen_ssa/back/
archive.rs

1use std::env;
2use std::error::Error;
3use std::ffi::OsString;
4use std::fs::{self, File};
5use std::io::{self, BufWriter, Write};
6use std::path::{Path, PathBuf};
7
8use ar_archive_writer::{
9    ArchiveKind, COFFShortExport, MachineTypes, NewArchiveMember, write_archive_to_stream,
10};
11pub use ar_archive_writer::{DEFAULT_OBJECT_READER, ObjectReader};
12use object::read::archive::{ArchiveFile, ArchiveKind as ObjectArchiveKind};
13use object::read::macho::FatArch;
14use rustc_data_structures::fx::FxIndexSet;
15use rustc_data_structures::memmap::Mmap;
16use rustc_fs_util::TempDirBuilder;
17use rustc_metadata::EncodedMetadata;
18use rustc_session::Session;
19use rustc_span::Symbol;
20use rustc_target::spec::Arch;
21use tracing::trace;
22
23use super::metadata::{create_compressed_metadata_file, search_for_section};
24use crate::common;
25// Public for ArchiveBuilderBuilder::extract_bundled_libs
26pub use crate::errors::ExtractBundledLibsError;
27use crate::errors::{
28    ArchiveBuildFailure, DlltoolFailImportLibrary, ErrorCallingDllTool, ErrorCreatingImportLibrary,
29    ErrorWritingDEFFile, UnknownArchiveKind,
30};
31
32/// An item to be included in an import library.
33/// This is a slimmed down version of `COFFShortExport` from `ar-archive-writer`.
34pub struct ImportLibraryItem {
35    /// The name to be exported.
36    pub name: String,
37    /// The ordinal to be exported, if any.
38    pub ordinal: Option<u16>,
39    /// The original, decorated name if `name` is not decorated.
40    pub symbol_name: Option<String>,
41    /// True if this is a data export, false if it is a function export.
42    pub is_data: bool,
43}
44
45impl ImportLibraryItem {
46    fn into_coff_short_export(self, sess: &Session) -> COFFShortExport {
47        let import_name = (sess.target.arch == Arch::Arm64EC).then(|| self.name.clone());
48        COFFShortExport {
49            name: self.name,
50            ext_name: None,
51            symbol_name: self.symbol_name,
52            import_name,
53            export_as: None,
54            ordinal: self.ordinal.unwrap_or(0),
55            noname: self.ordinal.is_some(),
56            data: self.is_data,
57            private: false,
58            constant: false,
59        }
60    }
61}
62
63pub trait ArchiveBuilderBuilder {
64    fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder + 'a>;
65
66    fn create_dylib_metadata_wrapper(
67        &self,
68        sess: &Session,
69        metadata: &EncodedMetadata,
70        symbol_name: &str,
71    ) -> Vec<u8> {
72        create_compressed_metadata_file(sess, metadata, symbol_name)
73    }
74
75    /// Creates a DLL Import Library <https://docs.microsoft.com/en-us/windows/win32/dlls/dynamic-link-library-creation#creating-an-import-library>.
76    /// and returns the path on disk to that import library.
77    /// This functions doesn't take `self` so that it can be called from
78    /// `linker_with_args`, which is specialized on `ArchiveBuilder` but
79    /// doesn't take or create an instance of that type.
80    fn create_dll_import_lib(
81        &self,
82        sess: &Session,
83        lib_name: &str,
84        items: Vec<ImportLibraryItem>,
85        output_path: &Path,
86    ) {
87        if common::is_mingw_gnu_toolchain(&sess.target) {
88            // The binutils linker used on -windows-gnu targets cannot read the import
89            // libraries generated by LLVM: in our attempts, the linker produced an .EXE
90            // that loaded but crashed with an AV upon calling one of the imported
91            // functions. Therefore, use binutils to create the import library instead,
92            // by writing a .DEF file to the temp dir and calling binutils's dlltool.
93            create_mingw_dll_import_lib(sess, lib_name, items, output_path);
94        } else {
95            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/archive.rs:95",
                        "rustc_codegen_ssa::back::archive", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/archive.rs"),
                        ::tracing_core::__macro_support::Option::Some(95u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::archive"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("creating import library")
                                            as &dyn Value))])
            });
    } else { ; }
};trace!("creating import library");
96            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/archive.rs:96",
                        "rustc_codegen_ssa::back::archive", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/archive.rs"),
                        ::tracing_core::__macro_support::Option::Some(96u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::archive"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("  dll_name {0:#?}",
                                                    lib_name) as &dyn Value))])
            });
    } else { ; }
};trace!("  dll_name {:#?}", lib_name);
97            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/archive.rs:97",
                        "rustc_codegen_ssa::back::archive", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/archive.rs"),
                        ::tracing_core::__macro_support::Option::Some(97u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::archive"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("  output_path {0}",
                                                    output_path.display()) as &dyn Value))])
            });
    } else { ; }
};trace!("  output_path {}", output_path.display());
98            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_codegen_ssa/src/back/archive.rs:98",
                        "rustc_codegen_ssa::back::archive", ::tracing::Level::TRACE,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_codegen_ssa/src/back/archive.rs"),
                        ::tracing_core::__macro_support::Option::Some(98u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_ssa::back::archive"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::TRACE <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::TRACE <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("  import names: {0}",
                                                    items.iter().map(|ImportLibraryItem { name, .. }|
                                                                    name.clone()).collect::<Vec<_>>().join(", ")) as
                                            &dyn Value))])
            });
    } else { ; }
};trace!(
99                "  import names: {}",
100                items
101                    .iter()
102                    .map(|ImportLibraryItem { name, .. }| name.clone())
103                    .collect::<Vec<_>>()
104                    .join(", "),
105            );
106
107            // All import names are Rust identifiers and therefore cannot contain \0 characters.
108            // FIXME: when support for #[link_name] is implemented, ensure that the import names
109            // still don't contain any \0 characters. Also need to check that the names don't
110            // contain substrings like " @" or "NONAME" that are keywords or otherwise reserved
111            // in definition files.
112
113            let mut file = match fs::File::create_new(&output_path) {
114                Ok(file) => file,
115                Err(error) => sess
116                    .dcx()
117                    .emit_fatal(ErrorCreatingImportLibrary { lib_name, error: error.to_string() }),
118            };
119
120            let exports =
121                items.into_iter().map(|item| item.into_coff_short_export(sess)).collect::<Vec<_>>();
122            let machine = match &sess.target.arch {
123                Arch::X86_64 => MachineTypes::AMD64,
124                Arch::X86 => MachineTypes::I386,
125                Arch::AArch64 => MachineTypes::ARM64,
126                Arch::Arm64EC => MachineTypes::ARM64EC,
127                Arch::Arm => MachineTypes::ARMNT,
128                cpu => {
    ::core::panicking::panic_fmt(format_args!("unsupported cpu type {0}",
            cpu));
}panic!("unsupported cpu type {cpu}"),
129            };
130
131            if let Err(error) = ar_archive_writer::write_import_library(
132                &mut file,
133                lib_name,
134                &exports,
135                machine,
136                !sess.target.is_like_msvc,
137                // Enable compatibility with MSVC's `/WHOLEARCHIVE` flag.
138                // Without this flag a duplicate symbol error would be emitted
139                // when linking a rust staticlib using `/WHOLEARCHIVE`.
140                // See #129020
141                true,
142                &[],
143            ) {
144                sess.dcx()
145                    .emit_fatal(ErrorCreatingImportLibrary { lib_name, error: error.to_string() });
146            }
147        }
148    }
149
150    fn extract_bundled_libs<'a>(
151        &'a self,
152        rlib: &'a Path,
153        outdir: &Path,
154        bundled_lib_file_names: &FxIndexSet<Symbol>,
155    ) -> Result<(), ExtractBundledLibsError<'a>> {
156        let archive_map = unsafe {
157            Mmap::map(
158                File::open(rlib)
159                    .map_err(|e| ExtractBundledLibsError::OpenFile { rlib, error: Box::new(e) })?,
160            )
161            .map_err(|e| ExtractBundledLibsError::MmapFile { rlib, error: Box::new(e) })?
162        };
163        let archive = ArchiveFile::parse(&*archive_map)
164            .map_err(|e| ExtractBundledLibsError::ParseArchive { rlib, error: Box::new(e) })?;
165
166        for entry in archive.members() {
167            let entry = entry
168                .map_err(|e| ExtractBundledLibsError::ReadEntry { rlib, error: Box::new(e) })?;
169            let data = entry
170                .data(&*archive_map)
171                .map_err(|e| ExtractBundledLibsError::ArchiveMember { rlib, error: Box::new(e) })?;
172            let name = std::str::from_utf8(entry.name())
173                .map_err(|e| ExtractBundledLibsError::ConvertName { rlib, error: Box::new(e) })?;
174            if !bundled_lib_file_names.contains(&Symbol::intern(name)) {
175                continue; // We need to extract only native libraries.
176            }
177            let data = search_for_section(rlib, data, ".bundled_lib").map_err(|e| {
178                ExtractBundledLibsError::ExtractSection { rlib, error: Box::<dyn Error>::from(e) }
179            })?;
180            std::fs::write(&outdir.join(&name), data)
181                .map_err(|e| ExtractBundledLibsError::WriteFile { rlib, error: Box::new(e) })?;
182        }
183        Ok(())
184    }
185}
186
187fn create_mingw_dll_import_lib(
188    sess: &Session,
189    lib_name: &str,
190    items: Vec<ImportLibraryItem>,
191    output_path: &Path,
192) {
193    let def_file_path = output_path.with_extension("def");
194
195    let def_file_content = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("EXPORTS\n{0}",
                items.into_iter().map(|ImportLibraryItem { name, ordinal, ..
                                    }|
                                {
                                    match ordinal {
                                        Some(n) =>
                                            ::alloc::__export::must_use({
                                                    ::alloc::fmt::format(format_args!("{0} @{1} NONAME", name,
                                                            n))
                                                }),
                                        None => name,
                                    }
                                }).collect::<Vec<String>>().join("\n")))
    })format!(
196        "EXPORTS\n{}",
197        items
198            .into_iter()
199            .map(|ImportLibraryItem { name, ordinal, .. }| {
200                match ordinal {
201                    Some(n) => format!("{name} @{n} NONAME"),
202                    None => name,
203                }
204            })
205            .collect::<Vec<String>>()
206            .join("\n")
207    );
208
209    match std::fs::write(&def_file_path, def_file_content) {
210        Ok(_) => {}
211        Err(e) => {
212            sess.dcx().emit_fatal(ErrorWritingDEFFile { error: e });
213        }
214    };
215
216    // --no-leading-underscore: For the `import_name_type` feature to work, we need to be
217    // able to control the *exact* spelling of each of the symbols that are being imported:
218    // hence we don't want `dlltool` adding leading underscores automatically.
219    let dlltool = find_binutils_dlltool(sess);
220    // temp_prefix doesn't handle paths with spaces so
221    // use a relative path and set the current working directory
222    let cwd = output_path.parent().unwrap_or(output_path);
223    let temp_prefix = lib_name;
224    // dlltool target architecture args from:
225    // https://github.com/llvm/llvm-project-release-prs/blob/llvmorg-15.0.6/llvm/lib/ToolDrivers/llvm-dlltool/DlltoolDriver.cpp#L69
226    let (dlltool_target_arch, dlltool_target_bitness) = match &sess.target.arch {
227        Arch::X86_64 => ("i386:x86-64", "--64"),
228        Arch::X86 => ("i386", "--32"),
229        Arch::AArch64 => ("arm64", "--64"),
230        Arch::Arm => ("arm", "--32"),
231        arch => { ::core::panicking::panic_fmt(format_args!("unsupported arch {0}", arch)); }panic!("unsupported arch {arch}"),
232    };
233    let mut dlltool_cmd = std::process::Command::new(&dlltool);
234    dlltool_cmd
235        .arg("-d")
236        .arg(def_file_path)
237        .arg("-D")
238        .arg(lib_name)
239        .arg("-l")
240        .arg(&output_path)
241        .arg("-m")
242        .arg(dlltool_target_arch)
243        .arg("-f")
244        .arg(dlltool_target_bitness)
245        .arg("--no-leading-underscore")
246        .arg("--temp-prefix")
247        .arg(temp_prefix)
248        .current_dir(cwd);
249
250    match dlltool_cmd.output() {
251        Err(e) => {
252            sess.dcx().emit_fatal(ErrorCallingDllTool {
253                dlltool_path: dlltool.to_string_lossy(),
254                error: e,
255            });
256        }
257        // dlltool returns '0' on failure, so check for error output instead.
258        Ok(output) if !output.stderr.is_empty() => {
259            sess.dcx().emit_fatal(DlltoolFailImportLibrary {
260                dlltool_path: dlltool.to_string_lossy(),
261                dlltool_args: dlltool_cmd
262                    .get_args()
263                    .map(|arg| arg.to_string_lossy())
264                    .collect::<Vec<_>>()
265                    .join(" "),
266                stdout: String::from_utf8_lossy(&output.stdout),
267                stderr: String::from_utf8_lossy(&output.stderr),
268            })
269        }
270        _ => {}
271    }
272}
273
274fn find_binutils_dlltool(sess: &Session) -> OsString {
275    if !(sess.target.options.is_like_windows && !sess.target.options.is_like_msvc)
    {
    ::core::panicking::panic("assertion failed: sess.target.options.is_like_windows && !sess.target.options.is_like_msvc")
};assert!(sess.target.options.is_like_windows && !sess.target.options.is_like_msvc);
276    if let Some(dlltool_path) = &sess.opts.cg.dlltool {
277        return dlltool_path.clone().into_os_string();
278    }
279
280    let tool_name: OsString = if sess.host.options.is_like_windows {
281        // If we're compiling on Windows, always use "dlltool.exe".
282        "dlltool.exe"
283    } else {
284        // On other platforms, use the architecture-specific name.
285        match sess.target.arch {
286            Arch::X86_64 => "x86_64-w64-mingw32-dlltool",
287            Arch::X86 => "i686-w64-mingw32-dlltool",
288            Arch::AArch64 => "aarch64-w64-mingw32-dlltool",
289
290            // For non-standard architectures (e.g., aarch32) fallback to "dlltool".
291            _ => "dlltool",
292        }
293    }
294    .into();
295
296    // NOTE: it's not clear how useful it is to explicitly search PATH.
297    for dir in env::split_paths(&env::var_os("PATH").unwrap_or_default()) {
298        let full_path = dir.join(&tool_name);
299        if full_path.is_file() {
300            return full_path.into_os_string();
301        }
302    }
303
304    // The user didn't specify the location of the dlltool binary, and we weren't able
305    // to find the appropriate one on the PATH. Just return the name of the tool
306    // and let the invocation fail with a hopefully useful error message.
307    tool_name
308}
309
310pub trait ArchiveBuilder {
311    fn add_file(&mut self, path: &Path);
312
313    fn add_archive(
314        &mut self,
315        archive: &Path,
316        skip: Box<dyn FnMut(&str) -> bool + 'static>,
317    ) -> io::Result<()>;
318
319    fn build(self: Box<Self>, output: &Path) -> bool;
320}
321
322fn target_archive_format_to_object_kind(format: &str) -> Option<ObjectArchiveKind> {
323    match format {
324        "gnu" => Some(ObjectArchiveKind::Gnu),
325        "bsd" => Some(ObjectArchiveKind::Bsd),
326        "darwin" => Some(ObjectArchiveKind::Bsd64),
327        "coff" => Some(ObjectArchiveKind::Coff),
328        "aix_big" => Some(ObjectArchiveKind::AixBig),
329        _ => None,
330    }
331}
332
333fn archive_kinds_compatible(actual: ObjectArchiveKind, expected: ObjectArchiveKind) -> bool {
334    if actual == expected {
335        return true;
336    }
337    #[allow(non_exhaustive_omitted_patterns)] match (actual, expected) {
    (ObjectArchiveKind::Unknown, _) |
        (ObjectArchiveKind::Gnu64, ObjectArchiveKind::Gnu) |
        (ObjectArchiveKind::Gnu, ObjectArchiveKind::Gnu64) |
        (ObjectArchiveKind::Bsd64, ObjectArchiveKind::Bsd) |
        (ObjectArchiveKind::Bsd, ObjectArchiveKind::Bsd64) |
        (ObjectArchiveKind::Gnu, ObjectArchiveKind::Coff) |
        (ObjectArchiveKind::Coff, ObjectArchiveKind::Gnu) |
        (ObjectArchiveKind::Gnu64, ObjectArchiveKind::Coff) => true,
    _ => false,
}matches!(
338        (actual, expected),
339        // An archive without long filenames or symbol table is detected as Unknown;
340        // this is compatible with any target format.
341        (ObjectArchiveKind::Unknown, _)
342        // 64-bit symbol table variants are compatible with their 32-bit counterparts
343        | (ObjectArchiveKind::Gnu64, ObjectArchiveKind::Gnu)
344        | (ObjectArchiveKind::Gnu, ObjectArchiveKind::Gnu64)
345        | (ObjectArchiveKind::Bsd64, ObjectArchiveKind::Bsd)
346        | (ObjectArchiveKind::Bsd, ObjectArchiveKind::Bsd64)
347        // GNU and COFF archives share the same magic and member header format;
348        // only the symbol table layout differs.
349        | (ObjectArchiveKind::Gnu, ObjectArchiveKind::Coff)
350        | (ObjectArchiveKind::Coff, ObjectArchiveKind::Gnu)
351        | (ObjectArchiveKind::Gnu64, ObjectArchiveKind::Coff)
352    )
353}
354
355fn archive_kind_display_name(kind: ObjectArchiveKind) -> String {
356    match kind {
357        ObjectArchiveKind::Gnu | ObjectArchiveKind::Gnu64 => "GNU".to_string(),
358        ObjectArchiveKind::Bsd => "BSD".to_string(),
359        ObjectArchiveKind::Bsd64 => "Darwin".to_string(),
360        ObjectArchiveKind::Coff => "COFF".to_string(),
361        ObjectArchiveKind::AixBig => "AIX big".to_string(),
362        _ => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", kind))
    })format!("{kind:?}"),
363    }
364}
365
366pub struct ArArchiveBuilderBuilder;
367
368impl ArchiveBuilderBuilder for ArArchiveBuilderBuilder {
369    fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder + 'a> {
370        Box::new(ArArchiveBuilder::new(sess, &DEFAULT_OBJECT_READER))
371    }
372}
373
374#[must_use = "must call build() to finish building the archive"]
375pub struct ArArchiveBuilder<'a> {
376    sess: &'a Session,
377    object_reader: &'static ObjectReader,
378
379    src_archives: Vec<(PathBuf, Mmap)>,
380    // Don't use an `HashMap` here, as the order is important. `lib.rmeta` needs
381    // to be at the end of an archive in some cases for linkers to not get confused.
382    entries: Vec<(Vec<u8>, ArchiveEntry)>,
383}
384
385#[derive(#[automatically_derived]
impl ::core::fmt::Debug for ArchiveEntry {
    #[inline]
    fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::fmt::Result {
        match self {
            ArchiveEntry::FromArchive {
                archive_index: __self_0, file_range: __self_1 } =>
                ::core::fmt::Formatter::debug_struct_field2_finish(f,
                    "FromArchive", "archive_index", __self_0, "file_range",
                    &__self_1),
            ArchiveEntry::File(__self_0) =>
                ::core::fmt::Formatter::debug_tuple_field1_finish(f, "File",
                    &__self_0),
        }
    }
}Debug)]
386enum ArchiveEntry {
387    FromArchive { archive_index: usize, file_range: (u64, u64) },
388    File(PathBuf),
389}
390
391impl<'a> ArArchiveBuilder<'a> {
392    pub fn new(sess: &'a Session, object_reader: &'static ObjectReader) -> ArArchiveBuilder<'a> {
393        ArArchiveBuilder { sess, object_reader, src_archives: ::alloc::vec::Vec::new()vec![], entries: ::alloc::vec::Vec::new()vec![] }
394    }
395}
396
397fn try_filter_fat_archs(
398    archs: &[impl FatArch],
399    target_arch: object::Architecture,
400    archive_path: &Path,
401    archive_map_data: &[u8],
402) -> io::Result<Option<PathBuf>> {
403    let desired = match archs.iter().find(|a| a.architecture() == target_arch) {
404        Some(a) => a,
405        None => return Ok(None),
406    };
407
408    let (mut new_f, extracted_path) = tempfile::Builder::new()
409        .suffix(archive_path.file_name().unwrap())
410        .tempfile()?
411        .keep()
412        .unwrap();
413
414    new_f.write_all(
415        desired.data(archive_map_data).map_err(|e| io::Error::new(io::ErrorKind::Other, e))?,
416    )?;
417
418    Ok(Some(extracted_path))
419}
420
421pub fn try_extract_macho_fat_archive(
422    sess: &Session,
423    archive_path: &Path,
424) -> io::Result<Option<PathBuf>> {
425    let archive_map = unsafe { Mmap::map(File::open(&archive_path)?)? };
426    let target_arch = match sess.target.arch {
427        Arch::AArch64 => object::Architecture::Aarch64,
428        Arch::X86_64 => object::Architecture::X86_64,
429        _ => return Ok(None),
430    };
431
432    if let Ok(h) = object::read::macho::MachOFatFile32::parse(&*archive_map) {
433        let archs = h.arches();
434        try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map)
435    } else if let Ok(h) = object::read::macho::MachOFatFile64::parse(&*archive_map) {
436        let archs = h.arches();
437        try_filter_fat_archs(archs, target_arch, archive_path, &*archive_map)
438    } else {
439        // Not a FatHeader at all, just return None.
440        Ok(None)
441    }
442}
443
444impl<'a> ArchiveBuilder for ArArchiveBuilder<'a> {
445    fn add_archive(
446        &mut self,
447        archive_path: &Path,
448        mut skip: Box<dyn FnMut(&str) -> bool + 'static>,
449    ) -> io::Result<()> {
450        let mut archive_path = archive_path.to_path_buf();
451        if self.sess.target.llvm_target.contains("-apple-macosx")
452            && let Some(new_archive_path) = try_extract_macho_fat_archive(self.sess, &archive_path)?
453        {
454            archive_path = new_archive_path
455        }
456
457        if self.src_archives.iter().any(|archive| archive.0 == archive_path) {
458            return Ok(());
459        }
460
461        let archive_map = unsafe { Mmap::map(File::open(&archive_path)?)? };
462        let archive = ArchiveFile::parse(&*archive_map)
463            .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
464        let archive_index = self.src_archives.len();
465
466        if let Some(expected_kind) =
467            target_archive_format_to_object_kind(&self.sess.target.archive_format)
468        {
469            let actual_kind = archive.kind();
470            if !archive_kinds_compatible(actual_kind, expected_kind) {
471                self.sess.dcx().emit_warn(crate::errors::IncompatibleArchiveFormat {
472                    path: archive_path.clone(),
473                    actual: archive_kind_display_name(actual_kind),
474                    expected: archive_kind_display_name(expected_kind),
475                });
476            }
477        }
478
479        for entry in archive.members() {
480            let entry = entry.map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
481            let file_name = String::from_utf8(entry.name().to_vec())
482                .map_err(|err| io::Error::new(io::ErrorKind::InvalidData, err))?;
483            if !skip(&file_name) {
484                if entry.is_thin() {
485                    let member_path = archive_path.parent().unwrap().join(Path::new(&file_name));
486                    self.entries.push((file_name.into_bytes(), ArchiveEntry::File(member_path)));
487                } else {
488                    self.entries.push((
489                        file_name.into_bytes(),
490                        ArchiveEntry::FromArchive { archive_index, file_range: entry.file_range() },
491                    ));
492                }
493            }
494        }
495
496        self.src_archives.push((archive_path, archive_map));
497        Ok(())
498    }
499
500    /// Adds an arbitrary file to this archive
501    fn add_file(&mut self, file: &Path) {
502        self.entries.push((
503            file.file_name().unwrap().to_str().unwrap().to_string().into_bytes(),
504            ArchiveEntry::File(file.to_owned()),
505        ));
506    }
507
508    /// Combine the provided files, rlibs, and native libraries into a single
509    /// `Archive`.
510    fn build(self: Box<Self>, output: &Path) -> bool {
511        let sess = self.sess;
512        match self.build_inner(output) {
513            Ok(any_members) => any_members,
514            Err(error) => {
515                sess.dcx().emit_fatal(ArchiveBuildFailure { path: output.to_owned(), error })
516            }
517        }
518    }
519}
520
521impl<'a> ArArchiveBuilder<'a> {
522    fn build_inner(self, output: &Path) -> io::Result<bool> {
523        let archive_kind = match &*self.sess.target.archive_format {
524            "gnu" => ArchiveKind::Gnu,
525            "bsd" => ArchiveKind::Bsd,
526            "darwin" => ArchiveKind::Darwin,
527            "coff" => ArchiveKind::Coff,
528            "aix_big" => ArchiveKind::AixBig,
529            kind => {
530                self.sess.dcx().emit_fatal(UnknownArchiveKind { kind });
531            }
532        };
533
534        let mut entries = Vec::new();
535
536        for (entry_name, entry) in self.entries {
537            let data =
538                match entry {
539                    ArchiveEntry::FromArchive { archive_index, file_range } => {
540                        let src_archive = &self.src_archives[archive_index];
541                        let archive_data = &src_archive.1;
542                        let start = file_range.0 as usize;
543                        let end = start + file_range.1 as usize;
544                        let Some(data) = archive_data.get(start..end) else {
545                            return Err(io_error_context(
546                                "invalid archive member",
547                                io::Error::new(
548                                    io::ErrorKind::InvalidData,
549                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("archive member at offset {3} with size {0} exceeds archive size {1} in `{2}`",
                file_range.1, archive_data.len(), src_archive.0.display(),
                start))
    })format!(
550                                        "archive member at offset {start} with size {} \
551                                         exceeds archive size {} in `{}`",
552                                        file_range.1,
553                                        archive_data.len(),
554                                        src_archive.0.display(),
555                                    ),
556                                ),
557                            ));
558                        };
559
560                        Box::new(data) as Box<dyn AsRef<[u8]>>
561                    }
562                    ArchiveEntry::File(file) => unsafe {
563                        Box::new(
564                            Mmap::map(File::open(file).map_err(|err| {
565                                io_error_context("failed to open object file", err)
566                            })?)
567                            .map_err(|err| io_error_context("failed to map object file", err))?,
568                        ) as Box<dyn AsRef<[u8]>>
569                    },
570                };
571
572            entries.push(NewArchiveMember {
573                buf: data,
574                object_reader: self.object_reader,
575                member_name: String::from_utf8(entry_name).unwrap(),
576                mtime: 0,
577                uid: 0,
578                gid: 0,
579                perms: 0o644,
580            })
581        }
582
583        // Write to a temporary file first before atomically renaming to the final name.
584        // This prevents programs (including rustc) from attempting to read a partial archive.
585        // It also enables writing an archive with the same filename as a dependency on Windows as
586        // required by a test.
587        // The tempfile crate currently uses 0o600 as mode for the temporary files and directories
588        // it creates. We need it to be the default mode for back compat reasons however. (See
589        // #107495) To handle this we are telling tempfile to create a temporary directory instead
590        // and then inside this directory create a file using File::create.
591        let archive_tmpdir = TempDirBuilder::new()
592            .suffix(".temp-archive")
593            .tempdir_in(output.parent().unwrap_or_else(|| Path::new("")))
594            .map_err(|err| {
595                io_error_context("couldn't create a directory for the temp file", err)
596            })?;
597        let archive_tmpfile_path = archive_tmpdir.path().join("tmp.a");
598        let archive_tmpfile = File::create_new(&archive_tmpfile_path)
599            .map_err(|err| io_error_context("couldn't create the temp file", err))?;
600
601        let mut archive_tmpfile = BufWriter::new(archive_tmpfile);
602        write_archive_to_stream(
603            &mut archive_tmpfile,
604            &entries,
605            archive_kind,
606            false,
607            /* is_ec = */ Some(self.sess.target.arch == Arch::Arm64EC),
608        )?;
609        archive_tmpfile.flush()?;
610        drop(archive_tmpfile);
611
612        let any_entries = !entries.is_empty();
613        drop(entries);
614        // Drop src_archives to unmap all input archives, which is necessary if we want to write the
615        // output archive to the same location as an input archive on Windows.
616        drop(self.src_archives);
617
618        fs::rename(archive_tmpfile_path, output)
619            .map_err(|err| io_error_context("failed to rename archive file", err))?;
620        archive_tmpdir
621            .close()
622            .map_err(|err| io_error_context("failed to remove temporary directory", err))?;
623
624        Ok(any_entries)
625    }
626}
627
628fn io_error_context(context: &str, err: io::Error) -> io::Error {
629    io::Error::new(io::ErrorKind::Other, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1}", context, err))
    })format!("{context}: {err}"))
630}