rustc_codegen_llvm/back/
archive.rs

1//! A helper class for dealing with static archives
2
3use std::ffi::{CStr, c_char, c_void};
4use std::io;
5
6use rustc_codegen_ssa::back::archive::{
7    ArArchiveBuilder, ArchiveBuilder, ArchiveBuilderBuilder, DEFAULT_OBJECT_READER, ObjectReader,
8};
9use rustc_session::Session;
10
11use crate::llvm;
12
13pub(crate) struct LlvmArchiveBuilderBuilder;
14
15impl ArchiveBuilderBuilder for LlvmArchiveBuilderBuilder {
16    fn new_archive_builder<'a>(&self, sess: &'a Session) -> Box<dyn ArchiveBuilder + 'a> {
17        // Use the `object` crate to build archives, with a little bit of help from LLVM.
18        Box::new(ArArchiveBuilder::new(sess, &LLVM_OBJECT_READER))
19    }
20}
21
22// The object crate doesn't know how to get symbols for LLVM bitcode and COFF bigobj files.
23// As such we need to use LLVM for them.
24
25static LLVM_OBJECT_READER: ObjectReader = ObjectReader {
26    get_symbols: get_llvm_object_symbols,
27    is_64_bit_object_file: llvm_is_64_bit_object_file,
28    is_ec_object_file: llvm_is_ec_object_file,
29    get_xcoff_member_alignment: DEFAULT_OBJECT_READER.get_xcoff_member_alignment,
30};
31
32#[deny(unsafe_op_in_unsafe_fn)]
33fn get_llvm_object_symbols(
34    buf: &[u8],
35    f: &mut dyn FnMut(&[u8]) -> io::Result<()>,
36) -> io::Result<bool> {
37    let mut state = Box::new(f);
38
39    let err = unsafe {
40        llvm::LLVMRustGetSymbols(
41            buf.as_ptr(),
42            buf.len(),
43            (&raw mut *state) as *mut c_void,
44            callback,
45            error_callback,
46        )
47    };
48
49    if err.is_null() {
50        return Ok(true);
51    } else {
52        let error = unsafe { *Box::from_raw(err as *mut io::Error) };
53        // These are the magic constants for LLVM bitcode files:
54        // https://github.com/llvm/llvm-project/blob/7eadc1960d199676f04add402bb0aa6f65b7b234/llvm/lib/BinaryFormat/Magic.cpp#L90-L97
55        if buf.starts_with(&[0xDE, 0xCE, 0x17, 0x0B]) || buf.starts_with(&[b'B', b'C', 0xC0, 0xDE])
56        {
57            // For LLVM bitcode, failure to read the symbols is not fatal. The bitcode may have been
58            // produced by a newer LLVM version that the one linked to rustc. This is fine provided
59            // that the linker does use said newer LLVM version. We skip writing the symbols for the
60            // bitcode to the symbol table of the archive. Traditional linkers don't like this, but
61            // newer linkers like lld, mold and wild ignore the symbol table anyway, so if they link
62            // against a new enough LLVM it will work out in the end.
63            // LLVM's archive writer also has this same behavior of only warning about invalid
64            // bitcode since https://github.com/llvm/llvm-project/pull/96848
65
66            // We don't have access to the DiagCtxt here to produce a nice warning in the correct format.
67            eprintln!("warning: Failed to read symbol table from LLVM bitcode: {}", error);
68            return Ok(true);
69        } else {
70            return Err(error);
71        }
72    }
73
74    unsafe extern "C" fn callback(state: *mut c_void, symbol_name: *const c_char) -> *mut c_void {
75        let f = unsafe { &mut *(state as *mut &mut dyn FnMut(&[u8]) -> io::Result<()>) };
76        match f(unsafe { CStr::from_ptr(symbol_name) }.to_bytes()) {
77            Ok(()) => std::ptr::null_mut(),
78            Err(err) => Box::into_raw(Box::new(err) as Box<io::Error>) as *mut c_void,
79        }
80    }
81
82    unsafe extern "C" fn error_callback(error: *const c_char) -> *mut c_void {
83        let error = unsafe { CStr::from_ptr(error) };
84        Box::into_raw(Box::new(io::Error::new(
85            io::ErrorKind::Other,
86            format!("LLVM error: {}", error.to_string_lossy()),
87        )) as Box<io::Error>) as *mut c_void
88    }
89}
90
91fn llvm_is_64_bit_object_file(buf: &[u8]) -> bool {
92    unsafe { llvm::LLVMRustIs64BitSymbolicFile(buf.as_ptr(), buf.len()) }
93}
94
95fn llvm_is_ec_object_file(buf: &[u8]) -> bool {
96    unsafe { llvm::LLVMRustIsECObject(buf.as_ptr(), buf.len()) }
97}