Debian Codegraph @

third_party/rust/uniffi_bindgen/src/macro_metadata/extract.rs

raw
1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4
5 use anyhow::{anyhow, bail, Context};
6 use camino::Utf8Path;
7 use fs_err as fs;
8 use goblin::{
9 archive::Archive,
10 elf::Elf,
11 mach::{segment::Section, symbols, Mach, MachO, SingleArch},
12 pe::{Coff, PE},
13 Object,
14 };
15 use std::collections::HashSet;
16 use uniffi_meta::Metadata;
17
18 /// Extract metadata written by the `uniffi::export` macro from a library file
19 ///
20 /// In addition to generating the scaffolding, that macro and also encodes the
21 /// `uniffi_meta::Metadata` for the components which can be used to generate the bindings side of
22 /// the interface.
23 pub fn extract_from_library(path: &Utf8Path) -> anyhow::Result<Vec<Metadata>> {
24 extract_from_bytes(&fs::read(path)?)
25 }
26
27 fn extract_from_bytes(file_data: &[u8]) -> anyhow::Result<Vec<Metadata>> {
28 match Object::parse(file_data)? {
29 Object::Elf(elf) => extract_from_elf(elf, file_data),
30 Object::PE(pe) => extract_from_pe(pe, file_data),
31 Object::Mach(mach) => extract_from_mach(mach, file_data),
32 Object::Archive(archive) => extract_from_archive(archive, file_data),
33 Object::COFF(coff) => extract_from_coff(coff, file_data),
34 _ => bail!("Unknown library format"),
35 }
36 }
37
38 pub fn extract_from_elf(elf: Elf<'_>, file_data: &[u8]) -> anyhow::Result<Vec<Metadata>> {
39 let mut extracted = ExtractedItems::new();
40
41 // Some ELF files have a SHT_SYMTAB_SHNDX section that we use below. If present, find the
42 // offset for that section.
43 let symtab_shndx_section_offset = elf
44 .section_headers
45 .iter()
46 .find(|sh| sh.sh_type == goblin::elf::section_header::SHT_SYMTAB_SHNDX)
47 .map(|sh| sh.sh_offset as usize);
48
49 for (i, sym) in elf.syms.iter().enumerate() {
50 let name = elf
51 .strtab
52 .get_at(sym.st_name)
53 .context("Error getting symbol name")?;
54 if !is_metadata_symbol(name) {
55 continue;
56 }
57
58 let header_index = match sym.st_shndx as u32 {
59 goblin::elf::section_header::SHN_XINDEX => {
60 // The section header index overflowed 16 bits and we have to look it up from
61 // the extended index table instead. Each item in the SHT_SYMTAB_SHNDX section is
62 // a 32-bit value even for a 64-bit ELF objects.
63 let section_offset = symtab_shndx_section_offset
64 .ok_or_else(|| anyhow!("Symbol {name} has st_shndx=SHN_XINDEX, but no SHT_SYMTAB_SHNDX section present"))?;
65
66 let offset = section_offset + (i * 4);
67 let slice = file_data.get(offset..offset + 4).ok_or_else(|| {
68 anyhow!("Index error looking up {name} in the SHT_SYMTAB_SHNDX section")
69 })?;
70 // If the last statement succeeded, the slice is exactly 4 bytes, so this try_into
71 // will never fail
72 let byte_array = slice.try_into().unwrap();
73 if elf.little_endian {
74 u32::from_le_bytes(byte_array) as usize
75 } else {
76 u32::from_be_bytes(byte_array) as usize
77 }
78 }
79 // The normal case is that we can just use `st_shndx`
80 _ => sym.st_shndx,
81 };
82
83 let sh = elf
84 .section_headers
85 .get(header_index)
86 .ok_or_else(|| anyhow!("Index error looking up section header for {name}"))?;
87
88 // Offset relative to the start of the section.
89 let section_offset = sym.st_value - sh.sh_addr;
90 extracted.extract_item(name, file_data, (sh.sh_offset + section_offset) as usize)?;
91 }
92 Ok(extracted.into_metadata())
93 }
94
95 pub fn extract_from_pe(pe: PE<'_>, file_data: &[u8]) -> anyhow::Result<Vec<Metadata>> {
96 let mut extracted = ExtractedItems::new();
97 for export in pe.exports {
98 if let Some(name) = export.name {
99 if is_metadata_symbol(name) {
100 extracted.extract_item(
101 name,
102 file_data,
103 export.offset.context("Error getting symbol offset")?,
104 )?;
105 }
106 }
107 }
108 Ok(extracted.into_metadata())
109 }
110
111 pub fn extract_from_mach(mach: Mach<'_>, file_data: &[u8]) -> anyhow::Result<Vec<Metadata>> {
112 match mach {
113 Mach::Binary(macho) => extract_from_macho(macho, file_data),
114 // Multi-binary library, just extract the first one
115 Mach::Fat(multi_arch) => match multi_arch.get(0)? {
116 SingleArch::MachO(macho) => extract_from_macho(macho, file_data),
117 SingleArch::Archive(archive) => extract_from_archive(archive, file_data),
118 },
119 }
120 }
121
122 pub fn extract_from_macho(macho: MachO<'_>, file_data: &[u8]) -> anyhow::Result<Vec<Metadata>> {
123 let mut sections: Vec<Section> = Vec::new();
124 for sects in macho.segments.sections() {
125 sections.extend(sects.map(|r| r.expect("section").0));
126 }
127 let mut extracted = ExtractedItems::new();
128 sections.sort_by_key(|s| s.addr);
129
130 // Iterate through the symbols. This picks up symbols from the .o files embedded in a Darwin
131 // archive.
132 for (name, nlist) in macho.symbols().flatten() {
133 // Check that the symbol:
134 // - Is global (exported)
135 // - Has type=N_SECT (it's regular data as opposed to something like
136 // "undefined" or "indirect")
137 // - Has a metadata symbol name
138 if nlist.is_global()
139 && nlist.get_type() == symbols::N_SECT
140 && is_metadata_symbol(name)
141 && nlist.n_sect != symbols::NO_SECT as usize
142 {
143 let section = &sections[nlist.n_sect - 1];
144
145 // `nlist.n_value` is an address, so we can calculating the offset inside the section
146 // using the difference between that and `section.addr`
147 let offset = section.offset as usize + nlist.n_value as usize - section.addr as usize;
148 extracted.extract_item(name, file_data, offset)?;
149 }
150 }
151
152 // Iterate through the exports. This picks up symbols from .dylib files.
153 for export in macho.exports()? {
154 let name = &export.name;
155 if is_metadata_symbol(name) {
156 extracted.extract_item(name, file_data, export.offset as usize)?;
157 }
158 }
159 Ok(extracted.into_metadata())
160 }
161
162 pub fn extract_from_archive(
163 archive: Archive<'_>,
164 file_data: &[u8],
165 ) -> anyhow::Result<Vec<Metadata>> {
166 // Store the names of archive members that have metadata symbols in them
167 let mut members_to_check: HashSet<&str> = HashSet::new();
168 for (member_name, _, symbols) in archive.summarize() {
169 for name in symbols {
170 if is_metadata_symbol(name) {
171 members_to_check.insert(member_name);
172 }
173 }
174 }
175
176 let mut items = vec![];
177 for member_name in members_to_check {
178 items.append(
179 &mut extract_from_bytes(
180 archive
181 .extract(member_name, file_data)
182 .with_context(|| format!("Failed to extract archive member `{member_name}`"))?,
183 )
184 .with_context(|| {
185 format!("Failed to extract data from archive member `{member_name}`")
186 })?,
187 );
188 }
189 Ok(items)
190 }
191
192 pub fn extract_from_coff(coff: Coff<'_>, file_data: &[u8]) -> anyhow::Result<Vec<Metadata>> {
193 // https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#coff-file-header-object-and-image
194 let Some(strings) = coff.strings else {
195 return Ok(vec![]);
196 };
197 let Some(symbols) = coff.symbols else {
198 return Ok(vec![]);
199 };
200
201 let mut extracted = ExtractedItems::new();
202
203 for (_, _, symbol) in symbols.iter() {
204 // COFF uses a one-based section index. Non-positive values have specifial meanings.
205 // 0 : IMAGE_SYM_UNDEFINED
206 // -1: IMAGE_SYM_ABSOLUTE
207 // -2: IMAGE_SYM_DEBUG
208 // See https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#section-number-values
209 // for details.
210 if symbol.section_number <= 0 {
211 continue;
212 }
213 let Ok(name) = symbol.name(&strings) else {
214 continue;
215 };
216 let section = coff
217 .sections
218 .get((symbol.section_number - 1) as usize)
219 .with_context(|| format!("Index error looking up section header for {name}"))?;
220 if !is_metadata_symbol(name) {
221 continue;
222 }
223 extracted.extract_item(
224 name,
225 file_data,
226 (section.pointer_to_raw_data as usize)
227 .checked_add(symbol.value as usize)
228 .context("Error getting symbol offset")?,
229 )?;
230 }
231
232 Ok(extracted.into_metadata())
233 }
234
235 /// Container for extracted metadata items
236 #[derive(Default)]
237 struct ExtractedItems {
238 items: Vec<Metadata>,
239 /// symbol names for the extracted items, we use this to ensure that we don't extract the same
240 /// symbol twice
241 names: HashSet<String>,
242 }
243
244 impl ExtractedItems {
245 fn new() -> Self {
246 Self::default()
247 }
248
249 fn extract_item(&mut self, name: &str, file_data: &[u8], offset: usize) -> anyhow::Result<()> {
250 if self.names.contains(name) {
251 // Already extracted this item
252 return Ok(());
253 }
254
255 // Use the file data starting from offset, without specifying the end position. We don't
256 // always know the end position, because goblin reports the symbol size as 0 for PE and
257 // MachO files.
258 //
259 // This works fine, because `MetadataReader` knows when the serialized data is terminated
260 // and will just ignore the trailing data.
261 let data = &file_data[offset..];
262 self.items.push(
263 Metadata::read(data).with_context(|| format!("extracting metadata for '{name}'"))?,
264 );
265 self.names.insert(name.to_string());
266 Ok(())
267 }
268
269 fn into_metadata(self) -> Vec<Metadata> {
270 self.items
271 }
272 }
273
274 fn is_metadata_symbol(name: &str) -> bool {
275 // Skip the "_" char that Darwin prepends, if present
276 let name = name.strip_prefix('_').unwrap_or(name);
277 name.starts_with("UNIFFI_META")
278 }