]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/metadata.rs
Rollup merge of #67636 - semarie:bootstrap-rustfmt, r=Mark-Simulacrum
[rust.git] / src / librustc_codegen_llvm / metadata.rs
1 use crate::llvm;
2 use crate::llvm::archive_ro::ArchiveRO;
3 use crate::llvm::{mk_section_iter, False, ObjectFile};
4 use rustc::middle::cstore::MetadataLoader;
5 use rustc_target::spec::Target;
6
7 use log::debug;
8 use rustc_codegen_ssa::METADATA_FILENAME;
9 use rustc_data_structures::owning_ref::OwningRef;
10 use rustc_data_structures::rustc_erase_owner;
11
12 use rustc_fs_util::path_to_c_string;
13 use std::path::Path;
14 use std::slice;
15
16 pub use rustc_data_structures::sync::MetadataRef;
17
18 pub struct LlvmMetadataLoader;
19
20 impl MetadataLoader for LlvmMetadataLoader {
21     fn get_rlib_metadata(&self, _: &Target, filename: &Path) -> Result<MetadataRef, String> {
22         // Use ArchiveRO for speed here, it's backed by LLVM and uses mmap
23         // internally to read the file. We also avoid even using a memcpy by
24         // just keeping the archive along while the metadata is in use.
25         let archive = ArchiveRO::open(filename).map(|ar| OwningRef::new(box ar)).map_err(|e| {
26             debug!("llvm didn't like `{}`: {}", filename.display(), e);
27             format!("failed to read rlib metadata in '{}': {}", filename.display(), e)
28         })?;
29         let buf: OwningRef<_, [u8]> = archive.try_map(|ar| {
30             ar.iter()
31                 .filter_map(|s| s.ok())
32                 .find(|sect| sect.name() == Some(METADATA_FILENAME))
33                 .map(|s| s.data())
34                 .ok_or_else(|| {
35                     debug!("didn't find '{}' in the archive", METADATA_FILENAME);
36                     format!("failed to read rlib metadata: '{}'", filename.display())
37                 })
38         })?;
39         Ok(rustc_erase_owner!(buf))
40     }
41
42     fn get_dylib_metadata(&self, target: &Target, filename: &Path) -> Result<MetadataRef, String> {
43         unsafe {
44             let buf = path_to_c_string(filename);
45             let mb = llvm::LLVMRustCreateMemoryBufferWithContentsOfFile(buf.as_ptr())
46                 .ok_or_else(|| format!("error reading library: '{}'", filename.display()))?;
47             let of = ObjectFile::new(mb).map(|of| OwningRef::new(box of)).ok_or_else(|| {
48                 format!("provided path not an object file: '{}'", filename.display())
49             })?;
50             let buf = of.try_map(|of| search_meta_section(of, target, filename))?;
51             Ok(rustc_erase_owner!(buf))
52         }
53     }
54 }
55
56 fn search_meta_section<'a>(
57     of: &'a ObjectFile,
58     target: &Target,
59     filename: &Path,
60 ) -> Result<&'a [u8], String> {
61     unsafe {
62         let si = mk_section_iter(of.llof);
63         while llvm::LLVMIsSectionIteratorAtEnd(of.llof, si.llsi) == False {
64             let mut name_buf = None;
65             let name_len = llvm::LLVMRustGetSectionName(si.llsi, &mut name_buf);
66             let name = name_buf.map_or(
67                 String::new(), // We got a NULL ptr, ignore `name_len`.
68                 |buf| {
69                     String::from_utf8(
70                         slice::from_raw_parts(buf.as_ptr() as *const u8, name_len as usize)
71                             .to_vec(),
72                     )
73                     .unwrap()
74                 },
75             );
76             debug!("get_metadata_section: name {}", name);
77             if read_metadata_section_name(target) == name {
78                 let cbuf = llvm::LLVMGetSectionContents(si.llsi);
79                 let csz = llvm::LLVMGetSectionSize(si.llsi) as usize;
80                 // The buffer is valid while the object file is around
81                 let buf: &'a [u8] = slice::from_raw_parts(cbuf as *const u8, csz);
82                 return Ok(buf);
83             }
84             llvm::LLVMMoveToNextSection(si.llsi);
85         }
86     }
87     Err(format!("metadata not found: '{}'", filename.display()))
88 }
89
90 pub fn metadata_section_name(target: &Target) -> &'static str {
91     // Historical note:
92     //
93     // When using link.exe it was seen that the section name `.note.rustc`
94     // was getting shortened to `.note.ru`, and according to the PE and COFF
95     // specification:
96     //
97     // > Executable images do not use a string table and do not support
98     // > section names longer than 8 characters
99     //
100     // https://docs.microsoft.com/en-us/windows/win32/debug/pe-format
101     //
102     // As a result, we choose a slightly shorter name! As to why
103     // `.note.rustc` works on MinGW, that's another good question...
104
105     if target.options.is_like_osx { "__DATA,.rustc" } else { ".rustc" }
106 }
107
108 fn read_metadata_section_name(_target: &Target) -> &'static str {
109     ".rustc"
110 }