Debian Codegraph @

third_party/rust/goblin/src/pe/import.rs

raw
1 use alloc::borrow::Cow;
2 use alloc::vec::Vec;
3 use core::fmt::{Debug, LowerHex};
4
5 use crate::error;
6 use scroll::ctx::TryFromCtx;
7 use scroll::{Pread, Pwrite, SizeWith};
8
9 use crate::pe::data_directories;
10 use crate::pe::options;
11 use crate::pe::section_table;
12 use crate::pe::utils;
13
14 use log::{debug, warn};
15
16 pub const IMPORT_BY_ORDINAL_32: u32 = 0x8000_0000;
17 pub const IMPORT_BY_ORDINAL_64: u64 = 0x8000_0000_0000_0000;
18 pub const IMPORT_RVA_MASK_32: u32 = 0x7fff_ffff;
19 pub const IMPORT_RVA_MASK_64: u64 = 0x0000_0000_7fff_ffff;
20
21 pub trait Bitfield<'a>:
22 Into<u64>
23 + PartialEq
24 + Eq
25 + LowerHex
26 + Debug
27 + TryFromCtx<'a, scroll::Endian, Error = scroll::Error>
28 {
29 fn is_ordinal(&self) -> bool;
30 fn to_ordinal(&self) -> u16;
31 fn to_rva(&self) -> u32;
32 fn size_of() -> usize;
33 fn is_zero(&self) -> bool;
34 }
35
36 impl<'a> Bitfield<'a> for u64 {
37 fn is_ordinal(&self) -> bool {
38 self & IMPORT_BY_ORDINAL_64 == IMPORT_BY_ORDINAL_64
39 }
40 fn to_ordinal(&self) -> u16 {
41 (0xffff & self) as u16
42 }
43 fn to_rva(&self) -> u32 {
44 (self & IMPORT_RVA_MASK_64) as u32
45 }
46 fn size_of() -> usize {
47 8
48 }
49 fn is_zero(&self) -> bool {
50 *self == 0
51 }
52 }
53
54 impl<'a> Bitfield<'a> for u32 {
55 fn is_ordinal(&self) -> bool {
56 self & IMPORT_BY_ORDINAL_32 == IMPORT_BY_ORDINAL_32
57 }
58 fn to_ordinal(&self) -> u16 {
59 (0xffff & self) as u16
60 }
61 fn to_rva(&self) -> u32 {
62 (self & IMPORT_RVA_MASK_32) as u32
63 }
64 fn size_of() -> usize {
65 4
66 }
67 fn is_zero(&self) -> bool {
68 *self == 0
69 }
70 }
71
72 #[derive(Debug, Clone)]
73 pub struct HintNameTableEntry<'a> {
74 pub hint: u16,
75 pub name: &'a str,
76 }
77
78 impl<'a> HintNameTableEntry<'a> {
79 fn parse(bytes: &'a [u8], mut offset: usize) -> error::Result<Self> {
80 let offset = &mut offset;
81 let hint = bytes.gread_with(offset, scroll::LE)?;
82 let name = bytes.pread::<&'a str>(*offset)?;
83 Ok(HintNameTableEntry { hint, name })
84 }
85 }
86
87 #[derive(Debug, Clone)]
88 pub enum SyntheticImportLookupTableEntry<'a> {
89 OrdinalNumber(u16),
90 HintNameTableRVA((u32, HintNameTableEntry<'a>)), // [u8; 31] bitfield :/
91 }
92
93 pub type ImportLookupTable<'a> = Vec<SyntheticImportLookupTableEntry<'a>>;
94
95 impl<'a> SyntheticImportLookupTableEntry<'a> {
96 pub fn parse<T: Bitfield<'a>>(
97 bytes: &'a [u8],
98 offset: usize,
99 sections: &[section_table::SectionTable],
100 file_alignment: u32,
101 ) -> error::Result<ImportLookupTable<'a>> {
102 Self::parse_with_opts::<T>(
103 bytes,
104 offset,
105 sections,
106 file_alignment,
107 &options::ParseOptions::default(),
108 )
109 }
110
111 pub fn parse_with_opts<T: Bitfield<'a>>(
112 bytes: &'a [u8],
113 mut offset: usize,
114 sections: &[section_table::SectionTable],
115 file_alignment: u32,
116 opts: &options::ParseOptions,
117 ) -> error::Result<ImportLookupTable<'a>> {
118 let le = scroll::LE;
119 let offset = &mut offset;
120 let mut table = Vec::new();
121 loop {
122 let bitfield: T = bytes.gread_with(offset, le)?;
123 if bitfield.is_zero() {
124 debug!("imports done");
125 break;
126 } else {
127 let entry = {
128 debug!("bitfield {:#x}", bitfield);
129 use self::SyntheticImportLookupTableEntry::*;
130 if bitfield.is_ordinal() {
131 let ordinal = bitfield.to_ordinal();
132 debug!("importing by ordinal {:#x}", ordinal);
133 OrdinalNumber(ordinal)
134 } else {
135 let rva = bitfield.to_rva();
136 let hentry = {
137 debug!("searching for RVA {:#x}", rva);
138 if let Some(offset) =
139 utils::find_offset(rva as usize, sections, file_alignment, opts)
140 {
141 debug!("offset {:#x}", offset);
142 HintNameTableEntry::parse(bytes, offset)?
143 } else {
144 warn!("Entry {} has bad RVA: {:#x}", table.len(), rva);
145 continue;
146 }
147 };
148 HintNameTableRVA((rva, hentry))
149 }
150 };
151 table.push(entry);
152 }
153 }
154 Ok(table)
155 }
156 }
157
158 // get until entry is 0
159 pub type ImportAddressTable = Vec<u64>;
160
161 #[repr(C)]
162 #[derive(Debug, Pread, Pwrite, SizeWith)]
163 pub struct ImportDirectoryEntry {
164 pub import_lookup_table_rva: u32,
165 pub time_date_stamp: u32,
166 pub forwarder_chain: u32,
167 pub name_rva: u32,
168 pub import_address_table_rva: u32,
169 }
170
171 pub const SIZEOF_IMPORT_DIRECTORY_ENTRY: usize = 20;
172
173 impl ImportDirectoryEntry {
174 pub fn is_null(&self) -> bool {
175 (self.import_lookup_table_rva == 0)
176 && (self.time_date_stamp == 0)
177 && (self.forwarder_chain == 0)
178 && (self.name_rva == 0)
179 && (self.import_address_table_rva == 0)
180 }
181 }
182
183 #[derive(Debug)]
184 pub struct SyntheticImportDirectoryEntry<'a> {
185 pub import_directory_entry: ImportDirectoryEntry,
186 /// Computed
187 pub name: &'a str,
188 /// The import lookup table is a vector of either ordinals, or RVAs + import names
189 pub import_lookup_table: Option<ImportLookupTable<'a>>,
190 /// Computed
191 pub import_address_table: ImportAddressTable,
192 }
193
194 impl<'a> SyntheticImportDirectoryEntry<'a> {
195 pub fn parse<T: Bitfield<'a>>(
196 bytes: &'a [u8],
197 import_directory_entry: ImportDirectoryEntry,
198 sections: &[section_table::SectionTable],
199 file_alignment: u32,
200 ) -> error::Result<SyntheticImportDirectoryEntry<'a>> {
201 Self::parse_with_opts::<T>(
202 bytes,
203 import_directory_entry,
204 sections,
205 file_alignment,
206 &options::ParseOptions::default(),
207 )
208 }
209
210 pub fn parse_with_opts<T: Bitfield<'a>>(
211 bytes: &'a [u8],
212 import_directory_entry: ImportDirectoryEntry,
213 sections: &[section_table::SectionTable],
214 file_alignment: u32,
215 opts: &options::ParseOptions,
216 ) -> error::Result<SyntheticImportDirectoryEntry<'a>> {
217 const LE: scroll::Endian = scroll::LE;
218 let name_rva = import_directory_entry.name_rva;
219 let name = utils::try_name(bytes, name_rva as usize, sections, file_alignment, opts)?;
220 let import_lookup_table = {
221 let import_lookup_table_rva = import_directory_entry.import_lookup_table_rva;
222 let import_address_table_rva = import_directory_entry.import_address_table_rva;
223 if let Some(import_lookup_table_offset) = utils::find_offset(
224 import_lookup_table_rva as usize,
225 sections,
226 file_alignment,
227 opts,
228 ) {
229 debug!("Synthesizing lookup table imports for {} lib, with import lookup table rva: {:#x}", name, import_lookup_table_rva);
230 let import_lookup_table = SyntheticImportLookupTableEntry::parse_with_opts::<T>(
231 bytes,
232 import_lookup_table_offset,
233 sections,
234 file_alignment,
235 opts,
236 )?;
237 debug!(
238 "Successfully synthesized import lookup table entry from lookup table: {:#?}",
239 import_lookup_table
240 );
241 Some(import_lookup_table)
242 } else if let Some(import_address_table_offset) = utils::find_offset(
243 import_address_table_rva as usize,
244 sections,
245 file_alignment,
246 opts,
247 ) {
248 debug!("Synthesizing lookup table imports for {} lib, with import address table rva: {:#x}", name, import_lookup_table_rva);
249 let import_address_table = SyntheticImportLookupTableEntry::parse_with_opts::<T>(
250 bytes,
251 import_address_table_offset,
252 sections,
253 file_alignment,
254 opts,
255 )?;
256 debug!(
257 "Successfully synthesized import lookup table entry from IAT: {:#?}",
258 import_address_table
259 );
260 Some(import_address_table)
261 } else {
262 None
263 }
264 };
265
266 let import_address_table_offset = &mut utils::find_offset(
267 import_directory_entry.import_address_table_rva as usize,
268 sections,
269 file_alignment,
270 opts,
271 )
272 .ok_or_else(|| {
273 error::Error::Malformed(format!(
274 "Cannot map import_address_table_rva {:#x} into offset for {}",
275 import_directory_entry.import_address_table_rva, name
276 ))
277 })?;
278 let mut import_address_table = Vec::new();
279 loop {
280 let import_address = bytes
281 .gread_with::<T>(import_address_table_offset, LE)?
282 .into();
283 if import_address == 0 {
284 break;
285 } else {
286 import_address_table.push(import_address);
287 }
288 }
289 Ok(SyntheticImportDirectoryEntry {
290 import_directory_entry,
291 name,
292 import_lookup_table,
293 import_address_table,
294 })
295 }
296 }
297
298 #[derive(Debug)]
299 /// Contains a list of synthesized import data for this binary, e.g., which symbols from which libraries it is importing from
300 pub struct ImportData<'a> {
301 pub import_data: Vec<SyntheticImportDirectoryEntry<'a>>,
302 }
303
304 impl<'a> ImportData<'a> {
305 pub fn parse<T: Bitfield<'a>>(
306 bytes: &'a [u8],
307 dd: data_directories::DataDirectory,
308 sections: &[section_table::SectionTable],
309 file_alignment: u32,
310 ) -> error::Result<ImportData<'a>> {
311 Self::parse_with_opts::<T>(
312 bytes,
313 dd,
314 sections,
315 file_alignment,
316 &options::ParseOptions::default(),
317 )
318 }
319
320 pub fn parse_with_opts<T: Bitfield<'a>>(
321 bytes: &'a [u8],
322 dd: data_directories::DataDirectory,
323 sections: &[section_table::SectionTable],
324 file_alignment: u32,
325 opts: &options::ParseOptions,
326 ) -> error::Result<ImportData<'a>> {
327 let import_directory_table_rva = dd.virtual_address as usize;
328 debug!(
329 "import_directory_table_rva {:#x}",
330 import_directory_table_rva
331 );
332 let offset =
333 &mut utils::find_offset(import_directory_table_rva, sections, file_alignment, opts)
334 .ok_or_else(|| {
335 error::Error::Malformed(format!(
336 "Cannot create ImportData; cannot map import_directory_table_rva {:#x} into offset",
337 import_directory_table_rva
338 ))
339 })?;
340 debug!("import data offset {:#x}", offset);
341 let mut import_data = Vec::new();
342 loop {
343 let import_directory_entry: ImportDirectoryEntry =
344 bytes.gread_with(offset, scroll::LE)?;
345 debug!("{:#?}", import_directory_entry);
346 if import_directory_entry.is_null() {
347 break;
348 } else {
349 let entry = SyntheticImportDirectoryEntry::parse_with_opts::<T>(
350 bytes,
351 import_directory_entry,
352 sections,
353 file_alignment,
354 opts,
355 )?;
356 debug!("entry {:#?}", entry);
357 import_data.push(entry);
358 }
359 }
360 debug!("finished ImportData");
361 Ok(ImportData { import_data })
362 }
363 }
364
365 #[derive(Debug)]
366 /// A synthesized symbol import, the name is pre-indexed, and the binary offset is computed, as well as which dll it belongs to
367 pub struct Import<'a> {
368 pub name: Cow<'a, str>,
369 pub dll: &'a str,
370 pub ordinal: u16,
371 pub offset: usize,
372 pub rva: usize,
373 pub size: usize,
374 }
375
376 impl<'a> Import<'a> {
377 pub fn parse<T: Bitfield<'a>>(
378 _bytes: &'a [u8],
379 import_data: &ImportData<'a>,
380 _sections: &[section_table::SectionTable],
381 ) -> error::Result<Vec<Import<'a>>> {
382 let mut imports = Vec::new();
383 for data in &import_data.import_data {
384 if let Some(ref import_lookup_table) = data.import_lookup_table {
385 let dll = data.name;
386 let import_base = data.import_directory_entry.import_address_table_rva as usize;
387 debug!("Getting imports from {}", &dll);
388 for (i, entry) in import_lookup_table.iter().enumerate() {
389 let offset = import_base + (i * T::size_of());
390 use self::SyntheticImportLookupTableEntry::*;
391 let (rva, name, ordinal) = match *entry {
392 HintNameTableRVA((rva, ref hint_entry)) => {
393 // if hint_entry.name = "" && hint_entry.hint = 0 {
394 // println!("<PE.Import> warning hint/name table rva from {} without hint {:#x}", dll, rva);
395 // }
396 (rva, Cow::Borrowed(hint_entry.name), hint_entry.hint)
397 }
398 OrdinalNumber(ordinal) => {
399 let name = format!("ORDINAL {}", ordinal);
400 (0x0, Cow::Owned(name), ordinal)
401 }
402 };
403 let import = Import {
404 name,
405 ordinal,
406 dll,
407 size: T::size_of(),
408 offset,
409 rva: rva as usize,
410 };
411 imports.push(import);
412 }
413 }
414 }
415 Ok(imports)
416 }
417 }