Debian Codegraph @

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

raw
1 use crate::error;
2 use crate::strtab;
3 use alloc::vec::Vec;
4 use core::fmt::{self, Debug};
5 use scroll::{ctx, IOread, IOwrite, Pread, Pwrite, SizeWith};
6
7 /// Size of a single symbol in the COFF Symbol Table.
8 pub const COFF_SYMBOL_SIZE: usize = 18;
9
10 // Values for `Symbol::section_number`.
11
12 /// The symbol record is not yet assigned a section. A `value` of zero
13 /// indicates that a reference to an external symbol is defined elsewhere.
14 /// A `value` of non-zero is a common symbol with a size that is specified by the `value`.
15 pub const IMAGE_SYM_UNDEFINED: i16 = 0;
16 /// The symbol has an absolute (non-relocatable) `value` and is not an address.
17 pub const IMAGE_SYM_ABSOLUTE: i16 = -1;
18 /// The symbol provides general type or debugging information but does not
19 /// correspond to a section.
20 pub const IMAGE_SYM_DEBUG: i16 = -2;
21
22 // Base types for `Symbol::typ`.
23
24 /// No type information or unknown base type. Microsoft tools use this setting
25 pub const IMAGE_SYM_TYPE_NULL: u16 = 0;
26 /// No valid type; used with void pointers and functions
27 pub const IMAGE_SYM_TYPE_VOID: u16 = 1;
28 /// A character (signed byte)
29 pub const IMAGE_SYM_TYPE_CHAR: u16 = 2;
30 /// A 2-byte signed integer
31 pub const IMAGE_SYM_TYPE_SHORT: u16 = 3;
32 /// A natural integer type (normally 4 bytes in Windows)
33 pub const IMAGE_SYM_TYPE_INT: u16 = 4;
34 /// A 4-byte signed integer
35 pub const IMAGE_SYM_TYPE_LONG: u16 = 5;
36 /// A 4-byte floating-point number
37 pub const IMAGE_SYM_TYPE_FLOAT: u16 = 6;
38 /// An 8-byte floating-point number
39 pub const IMAGE_SYM_TYPE_DOUBLE: u16 = 7;
40 /// A structure
41 pub const IMAGE_SYM_TYPE_STRUCT: u16 = 8;
42 /// A union
43 pub const IMAGE_SYM_TYPE_UNION: u16 = 9;
44 /// An enumerated type
45 pub const IMAGE_SYM_TYPE_ENUM: u16 = 10;
46 /// A member of enumeration (a specific value)
47 pub const IMAGE_SYM_TYPE_MOE: u16 = 11;
48 /// A byte; unsigned 1-byte integer
49 pub const IMAGE_SYM_TYPE_BYTE: u16 = 12;
50 /// A word; unsigned 2-byte integer
51 pub const IMAGE_SYM_TYPE_WORD: u16 = 13;
52 /// An unsigned integer of natural size (normally, 4 bytes)
53 pub const IMAGE_SYM_TYPE_UINT: u16 = 14;
54 /// An unsigned 4-byte integer
55 pub const IMAGE_SYM_TYPE_DWORD: u16 = 15;
56
57 // Derived types for `Symbol::typ`.
58
59 /// No derived type; the symbol is a simple scalar variable.
60 pub const IMAGE_SYM_DTYPE_NULL: u16 = 0;
61 /// The symbol is a pointer to base type.
62 pub const IMAGE_SYM_DTYPE_POINTER: u16 = 1;
63 /// The symbol is a function that returns a base type.
64 pub const IMAGE_SYM_DTYPE_FUNCTION: u16 = 2;
65 /// The symbol is an array of base type.
66 pub const IMAGE_SYM_DTYPE_ARRAY: u16 = 3;
67
68 pub const IMAGE_SYM_TYPE_MASK: u16 = 0xf;
69 pub const IMAGE_SYM_DTYPE_SHIFT: usize = 4;
70
71 // Values for `Symbol::storage_class`.
72
73 /// A special symbol that represents the end of function, for debugging purposes.
74 pub const IMAGE_SYM_CLASS_END_OF_FUNCTION: u8 = 0xff;
75 /// No assigned storage class.
76 pub const IMAGE_SYM_CLASS_NULL: u8 = 0;
77 /// The automatic (stack) variable.
78 ///
79 /// The `value` field specifies the stack frame offset.
80 pub const IMAGE_SYM_CLASS_AUTOMATIC: u8 = 1;
81 /// A value that Microsoft tools use for external symbols.
82 ///
83 /// The `value` field indicates the size if the section number is
84 /// `IMAGE_SYM_UNDEFINED` (0). If the section number is not zero,
85 /// then the `value` field specifies the offset within the section.
86 pub const IMAGE_SYM_CLASS_EXTERNAL: u8 = 2;
87 /// A static symbol.
88 ///
89 /// The 'value' field specifies the offset of the symbol within the section.
90 /// If the `value` field is zero, then the symbol represents a section name.
91 pub const IMAGE_SYM_CLASS_STATIC: u8 = 3;
92 /// A register variable.
93 ///
94 /// The `value` field specifies the register number.
95 pub const IMAGE_SYM_CLASS_REGISTER: u8 = 4;
96 /// A symbol that is defined externally.
97 pub const IMAGE_SYM_CLASS_EXTERNAL_DEF: u8 = 5;
98 /// A code label that is defined within the module.
99 ///
100 /// The `value` field specifies the offset of the symbol within the section.
101 pub const IMAGE_SYM_CLASS_LABEL: u8 = 6;
102 /// A reference to a code label that is not defined.
103 pub const IMAGE_SYM_CLASS_UNDEFINED_LABEL: u8 = 7;
104 /// The structure member.
105 ///
106 /// The `value` field specifies the n th member.
107 pub const IMAGE_SYM_CLASS_MEMBER_OF_STRUCT: u8 = 8;
108 /// A formal argument (parameter) of a function.
109 ///
110 /// The `value` field specifies the n th argument.
111 pub const IMAGE_SYM_CLASS_ARGUMENT: u8 = 9;
112 /// The structure tag-name entry.
113 pub const IMAGE_SYM_CLASS_STRUCT_TAG: u8 = 10;
114 /// A union member.
115 ///
116 /// The `value` field specifies the n th member.
117 pub const IMAGE_SYM_CLASS_MEMBER_OF_UNION: u8 = 11;
118 /// The Union tag-name entry.
119 pub const IMAGE_SYM_CLASS_UNION_TAG: u8 = 12;
120 /// A Typedef entry.
121 pub const IMAGE_SYM_CLASS_TYPE_DEFINITION: u8 = 13;
122 /// A static data declaration.
123 pub const IMAGE_SYM_CLASS_UNDEFINED_STATIC: u8 = 14;
124 /// An enumerated type tagname entry.
125 pub const IMAGE_SYM_CLASS_ENUM_TAG: u8 = 15;
126 /// A member of an enumeration.
127 ///
128 /// The `value` field specifies the n th member.
129 pub const IMAGE_SYM_CLASS_MEMBER_OF_ENUM: u8 = 16;
130 /// A register parameter.
131 pub const IMAGE_SYM_CLASS_REGISTER_PARAM: u8 = 17;
132 /// A bit-field reference.
133 ///
134 /// The `value` field specifies the n th bit in the bit field.
135 pub const IMAGE_SYM_CLASS_BIT_FIELD: u8 = 18;
136 /// A .bb (beginning of block) or .eb (end of block) record.
137 ///
138 /// The `value` field is the relocatable address of the code location.
139 pub const IMAGE_SYM_CLASS_BLOCK: u8 = 100;
140 /// A value that Microsoft tools use for symbol records that define the extent of a function.
141 ///
142 /// Records may be begin function (.bf ), end function ( .ef ), and lines in function ( .lf ).
143 /// For .lf records, the `value` field gives the number of source lines in the function.
144 /// For .ef records, the `value` field gives the size of the function code.
145 pub const IMAGE_SYM_CLASS_FUNCTION: u8 = 101;
146 /// An end-of-structure entry.
147 pub const IMAGE_SYM_CLASS_END_OF_STRUCT: u8 = 102;
148 /// The source-file symbol record.
149 ///
150 /// The symbol is followed by auxiliary records that name the file.
151 pub const IMAGE_SYM_CLASS_FILE: u8 = 103;
152 /// A definition of a section (Microsoft tools use STATIC storage class instead).
153 pub const IMAGE_SYM_CLASS_SECTION: u8 = 104;
154 /// A weak external.
155 pub const IMAGE_SYM_CLASS_WEAK_EXTERNAL: u8 = 105;
156 /// A CLR token symbol.
157 ///
158 /// The name is an ASCII string that consists of the hexadecimal value of the token.
159 pub const IMAGE_SYM_CLASS_CLR_TOKEN: u8 = 107;
160
161 /// A COFF symbol.
162 ///
163 /// Unwind information for this function can be loaded with [`ExceptionData::get_unwind_info`].
164 ///
165 /// [`ExceptionData::get_unwind_info`]: struct.ExceptionData.html#method.get_unwind_info
166 #[repr(C)]
167 #[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
168 pub struct Symbol {
169 /// The name of the symbol.
170 ///
171 /// An array of 8 bytes is used if the name is not more than 8 bytes long.
172 /// This array is padded with nulls on the right if the name is less than 8 bytes long.
173 ///
174 /// For longer names, the first 4 bytes are all zeros, and the second 4 bytes
175 /// are an offset into the string table.
176 pub name: [u8; 8],
177 /// The value that is associated with the symbol.
178 ///
179 /// The interpretation of this field depends on `section_number` and
180 /// `storage_class`. A typical meaning is the relocatable address.
181 pub value: u32,
182 /// A one-based index into the section table. Zero and negative values have special meanings.
183 pub section_number: i16,
184 /// A number that represents type.
185 ///
186 /// Microsoft tools set this field to 0x20 (function) or 0x0 (not a function).
187 pub typ: u16,
188 /// An enumerated value that represents storage class.
189 pub storage_class: u8,
190 /// The number of auxiliary symbol table entries that follow this record.
191 ///
192 /// Each auxiliary record is the same size as a standard symbol-table record (18 bytes),
193 /// but rather than define a new symbol, the auxiliary record gives additional information
194 /// on the last symbol defined.
195 pub number_of_aux_symbols: u8,
196 }
197
198 impl Symbol {
199 /// Parse the symbol at the given offset.
200 ///
201 /// If the symbol has an inline name, then also returns a reference to the name's
202 /// location in `bytes`.
203 pub fn parse<'a>(bytes: &'a [u8], offset: usize) -> error::Result<(Option<&'a str>, Symbol)> {
204 let symbol = bytes.pread::<Symbol>(offset)?;
205 let name = if symbol.name[0] != 0 {
206 bytes
207 .pread_with(offset, ctx::StrCtx::DelimiterUntil(0, 8))
208 .ok()
209 } else {
210 None
211 };
212 Ok((name, symbol))
213 }
214
215 /// Returns the symbol name.
216 ///
217 /// This may be a reference to an inline name in the symbol, or to
218 /// a strtab entry.
219 pub fn name<'a>(&'a self, strtab: &'a strtab::Strtab) -> error::Result<&'a str> {
220 if let Some(offset) = self.name_offset() {
221 strtab.get_at(offset as usize).ok_or_else(|| {
222 error::Error::Malformed(format!("Invalid Symbol name offset {:#x}", offset))
223 })
224 } else {
225 Ok(self.name.pread(0)?)
226 }
227 }
228
229 /// Return the strtab offset of the symbol name.
230 ///
231 /// Returns `None` if the name is inline.
232 pub fn name_offset(&self) -> Option<u32> {
233 // Symbol offset starts at the strtable's length, so let's adjust it
234 let length_field_size = core::mem::size_of::<u32>() as u32;
235
236 if self.name[0] == 0 {
237 self.name
238 .pread_with(4, scroll::LE)
239 .ok()
240 .map(|offset: u32| offset - length_field_size)
241 } else {
242 None
243 }
244 }
245
246 /// Set the strtab offset of the symbol name.
247 pub fn set_name_offset(&mut self, offset: u32) {
248 self.name[..4].copy_from_slice(&[0; 4]);
249 self.name.pwrite_with(offset, 4, scroll::LE).unwrap();
250 }
251
252 /// Return the base type of the symbol.
253 ///
254 /// This type uses the `IMAGE_SYM_TYPE_*` definitions.
255 pub fn base_type(&self) -> u16 {
256 self.typ & IMAGE_SYM_TYPE_MASK
257 }
258
259 /// Return the derived type of the symbol.
260 ///
261 /// This type uses the `IMAGE_SYM_DTYPE_*` definitions.
262 pub fn derived_type(&self) -> u16 {
263 self.typ >> IMAGE_SYM_DTYPE_SHIFT
264 }
265
266 /// Return true for function definitions.
267 ///
268 /// These symbols use `AuxFunctionDefinition` for auxiliary symbol records.
269 pub fn is_function_definition(&self) -> bool {
270 self.storage_class == IMAGE_SYM_CLASS_EXTERNAL
271 && self.derived_type() == IMAGE_SYM_DTYPE_FUNCTION
272 && self.section_number > 0
273 }
274
275 /// Return true for weak external symbols.
276 ///
277 /// These symbols use `AuxWeakExternal` for auxiliary symbol records.
278 pub fn is_weak_external(&self) -> bool {
279 self.storage_class == IMAGE_SYM_CLASS_WEAK_EXTERNAL
280 }
281
282 /// Return true for file symbol records.
283 ///
284 /// The auxiliary records contain the name of the source code file.
285 pub fn is_file(&self) -> bool {
286 self.storage_class == IMAGE_SYM_CLASS_FILE
287 }
288
289 /// Return true for section definitions.
290 ///
291 /// These symbols use `AuxSectionDefinition` for auxiliary symbol records.
292 pub fn is_section_definition(&self) -> bool {
293 self.storage_class == IMAGE_SYM_CLASS_STATIC && self.number_of_aux_symbols > 0
294 }
295 }
296
297 /// Auxiliary symbol record for function definitions.
298 #[repr(C)]
299 #[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
300 pub struct AuxFunctionDefinition {
301 /// The symbol-table index of the corresponding `.bf` (begin function) symbol record.
302 pub tag_index: u32,
303 /// The size of the executable code for the function itself.
304 ///
305 /// If the function is in its own section, the `size_of_raw_data` in the section header
306 /// is greater or equal to this field, depending on alignment considerations.
307 pub total_size: u32,
308 /// The file offset of the first COFF line-number entry for the function,
309 /// or zero if none exists.
310 pub pointer_to_line_number: u32,
311 /// The symbol-table index of the record for the next function.
312 ///
313 /// If the function is the last in the symbol table, this field is set to zero.
314 pub pointer_to_next_function: u32,
315 /// Unused padding.
316 pub unused: [u8; 2],
317 }
318
319 /// Auxiliary symbol record for symbols with storage class `IMAGE_SYM_CLASS_FUNCTION`.
320 #[repr(C)]
321 #[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
322 pub struct AuxBeginAndEndFunction {
323 /// Unused padding.
324 pub unused1: [u8; 4],
325 /// The actual ordinal line number within the source file, corresponding
326 /// to the `.bf` or `.ef` record.
327 pub line_number: u16,
328 /// Unused padding.
329 pub unused2: [u8; 6],
330 /// The symbol-table index of the next `.bf` symbol record.
331 ///
332 /// If the function is the last in the symbol table, this field is set to zero.
333 /// It is not used for `.ef` records.
334 pub pointer_to_next_function: u32,
335 /// Unused padding.
336 pub unused3: [u8; 2],
337 }
338
339 // Values for the `characteristics` field of `AuxWeakExternal`.
340
341 /// Indicates that no library search for the symbol should be performed.
342 pub const IMAGE_WEAK_EXTERN_SEARCH_NOLIBRARY: u32 = 1;
343 /// Indicates that a library search for the symbol should be performed.
344 pub const IMAGE_WEAK_EXTERN_SEARCH_LIBRARY: u32 = 2;
345 /// Indicates that the symbol is an alias for the symbol given by the `tag_index` field.
346 pub const IMAGE_WEAK_EXTERN_SEARCH_ALIAS: u32 = 3;
347
348 /// Auxiliary symbol record for weak external symbols.
349 #[repr(C)]
350 #[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
351 pub struct AuxWeakExternal {
352 /// The symbol-table index of the symbol to be linked if an external definition is not found.
353 pub tag_index: u32,
354 /// Flags that control how the symbol should be linked.
355 pub characteristics: u32,
356 /// Unused padding.
357 pub unused: [u8; 10],
358 }
359
360 // Values for the `selection` field of `AuxSectionDefinition`.
361
362 /// If this symbol is already defined, the linker issues a "multiply defined symbol" error.
363 pub const IMAGE_COMDAT_SELECT_NODUPLICATES: u8 = 1;
364 /// Any section that defines the same COMDAT symbol can be linked; the rest are removed.
365 pub const IMAGE_COMDAT_SELECT_ANY: u8 = 2;
366 /// The linker chooses an arbitrary section among the definitions for this symbol.
367 ///
368 /// If all definitions are not the same size, a "multiply defined symbol" error is issued.
369 pub const IMAGE_COMDAT_SELECT_SAME_SIZE: u8 = 3;
370 /// The linker chooses an arbitrary section among the definitions for this symbol.
371 ///
372 /// If all definitions do not match exactly, a "multiply defined symbol" error is issued.
373 pub const IMAGE_COMDAT_SELECT_EXACT_MATCH: u8 = 4;
374 /// The section is linked if a certain other COMDAT section is linked.
375 ///
376 /// This other section is indicated by the `number` field of the auxiliary symbol record
377 /// for the section definition. This setting is useful for definitions that have components
378 /// in multiple sections (for example, code in one and data in another), but where all must
379 /// be linked or discarded as a set. The other section with which this section is associated
380 /// must be a COMDAT section; it cannot be another associative COMDAT section (that is, the
381 /// other section cannot have `IMAGE_COMDAT_SELECT_ASSOCIATIVE` set).
382 pub const IMAGE_COMDAT_SELECT_ASSOCIATIVE: u8 = 5;
383 /// The linker chooses the largest definition from among all of the definitions for this symbol.
384 ///
385 /// If multiple definitions have this size, the choice between them is arbitrary.
386 pub const IMAGE_COMDAT_SELECT_LARGEST: u8 = 6;
387
388 /// Auxiliary symbol record for section definitions.
389 #[repr(C)]
390 #[derive(Debug, Copy, Clone, PartialEq, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
391 pub struct AuxSectionDefinition {
392 /// The size of section data; the same as `size_of_raw_data` in the section header.
393 pub length: u32,
394 /// The number of relocation entries for the section.
395 pub number_of_relocations: u16,
396 /// The number of line-number entries for the section.
397 pub number_of_line_numbers: u16,
398 /// The checksum for communal data.
399 ///
400 /// It is applicable if the `IMAGE_SCN_LNK_COMDAT` flag is set in the section header.
401 pub checksum: u32,
402 /// One-based index into the section table for the associated section.
403 ///
404 /// This is used when the `selection` field is `IMAGE_COMDAT_SELECT_ASSOCIATIVE`.
405 pub number: u16,
406 /// The COMDAT selection number.
407 ///
408 /// This is applicable if the section is a COMDAT section.
409 pub selection: u8,
410 /// Unused padding.
411 pub unused: [u8; 3],
412 }
413
414 /// A COFF symbol table.
415 // TODO: #[derive(Pwrite)] produce unparseable tokens
416 pub struct SymbolTable<'a> {
417 symbols: &'a [u8],
418 }
419
420 impl<'a> SymbolTable<'a> {
421 /// Parse a COFF symbol table at the given offset.
422 ///
423 /// The offset and number of symbols should be from the COFF header.
424 pub fn parse(bytes: &'a [u8], offset: usize, number: usize) -> error::Result<SymbolTable<'a>> {
425 let symbols = bytes.pread_with(offset, Self::size(number))?;
426 Ok(SymbolTable { symbols })
427 }
428
429 /// Get the size in bytes of the symbol table.
430 pub fn size(number: usize) -> usize {
431 number * COFF_SYMBOL_SIZE
432 }
433
434 /// Get the symbol at the given index.
435 ///
436 /// If the symbol has an inline name, then also returns a reference to the name's
437 /// location in `bytes`.
438 pub fn get(&self, index: usize) -> Option<(Option<&'a str>, Symbol)> {
439 let offset = index * COFF_SYMBOL_SIZE;
440 Symbol::parse(self.symbols, offset).ok()
441 }
442
443 /// Get the auxiliary symbol record for a function definition.
444 pub fn aux_function_definition(&self, index: usize) -> Option<AuxFunctionDefinition> {
445 let offset = index * COFF_SYMBOL_SIZE;
446 self.symbols.pread(offset).ok()
447 }
448
449 /// Get the auxiliary symbol record for a `.bf` or `.ef` symbol record.
450 pub fn aux_begin_and_end_function(&self, index: usize) -> Option<AuxBeginAndEndFunction> {
451 let offset = index * COFF_SYMBOL_SIZE;
452 self.symbols.pread(offset).ok()
453 }
454
455 /// Get the auxiliary symbol record for a weak external.
456 pub fn aux_weak_external(&self, index: usize) -> Option<AuxWeakExternal> {
457 let offset = index * COFF_SYMBOL_SIZE;
458 self.symbols.pread(offset).ok()
459 }
460
461 /// Get the file name from the auxiliary symbol record for a file symbol record.
462 pub fn aux_file(&self, index: usize, number: usize) -> Option<&'a str> {
463 let offset = index * COFF_SYMBOL_SIZE;
464 let length = number * COFF_SYMBOL_SIZE;
465 self.symbols
466 .pread_with(offset, ctx::StrCtx::DelimiterUntil(0, length))
467 .ok()
468 }
469
470 /// Get the auxiliary symbol record for a section definition.
471 pub fn aux_section_definition(&self, index: usize) -> Option<AuxSectionDefinition> {
472 let offset = index * COFF_SYMBOL_SIZE;
473 self.symbols.pread(offset).ok()
474 }
475
476 /// Return an iterator for the COFF symbols.
477 ///
478 /// This iterator skips over auxiliary symbol records.
479 pub fn iter(&self) -> SymbolIterator<'a> {
480 SymbolIterator {
481 index: 0,
482 symbols: self.symbols,
483 }
484 }
485 }
486
487 impl<'a> ctx::TryIntoCtx<scroll::Endian> for SymbolTable<'a> {
488 type Error = error::Error;
489
490 fn try_into_ctx(self, bytes: &mut [u8], _ctx: scroll::Endian) -> Result<usize, Self::Error> {
491 bytes.pwrite(self.symbols, 0).map_err(|err| err.into())
492 }
493 }
494
495 impl<'a> Debug for SymbolTable<'a> {
496 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
497 fmt.debug_struct("SymbolTable")
498 .field("symbols", &self.iter().collect::<Vec<_>>())
499 .finish()
500 }
501 }
502
503 /// An iterator for COFF symbols.
504 ///
505 /// This iterator skips over auxiliary symbol records.
506 #[derive(Default)]
507 pub struct SymbolIterator<'a> {
508 index: usize,
509 symbols: &'a [u8],
510 }
511
512 impl<'a> Iterator for SymbolIterator<'a> {
513 type Item = (usize, Option<&'a str>, Symbol);
514 fn next(&mut self) -> Option<Self::Item> {
515 let offset = self.index * COFF_SYMBOL_SIZE;
516 if offset >= self.symbols.len() {
517 None
518 } else {
519 let index = self.index;
520 let (name, symbol) = Symbol::parse(self.symbols, offset).ok()?;
521 self.index += 1 + symbol.number_of_aux_symbols as usize;
522 Some((index, name, symbol))
523 }
524 }
525 }