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