Debian Codegraph @

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

raw
1 use crate::error;
2 use crate::pe::{data_directories, optional_header, section_table, symbol};
3 use crate::strtab;
4 use alloc::vec::Vec;
5 use log::debug;
6 use scroll::{ctx, IOread, IOwrite, Pread, Pwrite, SizeWith};
7
8 /// In `winnt.h` and `pe.h`, it's `IMAGE_DOS_HEADER`. It's a DOS header present in all PE binaries.
9 ///
10 /// The DOS header is a relic from the MS-DOS era. It used to be useful to display an
11 /// error message if the binary is run in MS-DOS by utilizing the DOS stub.
12 ///
13 /// Nowadays, only two fields from
14 /// the DOS header are used on Windows: [`signature` (aka `e_magic`)](DosHeader::signature)
15 /// and [`pe_pointer` (aka `e_lfanew`)](DosHeader::pe_pointer).
16 ///
17 /// ## Position in a modern PE file
18 ///
19 /// The DOS header is located at the beginning of the PE file and is usually followed by the [DosStub].
20 ///
21 /// ## Note on the archaic "formatted header"
22 ///
23 /// The subset of the structure spanning from its start to the [`overlay_number` (aka `e_ovno`)](DosHeader::overlay_number) field
24 /// included (i.e. till the offset 0x1C) used to be commonly known as "formatted header", since their position and contents were
25 /// fixed. Optional information used by overlay managers could have followed the formatted header. In the absence of optional
26 /// information, the formatted header was followed by the ["relocation pointer table"](https://www.tavi.co.uk/phobos/exeformat.html#reloctable).
27 ///
28 /// Overlays were sections of a program that remained on disk until the program actually required them. Different overlays
29 /// could thus share the same memory area. The overlays were loaded and unloaded by special code provided by the program
30 /// or its run-time library.
31 ///
32 /// [Source](https://www.tavi.co.uk/phobos/exeformat.html#:~:text=Format%20of%20the%20.EXE%20file%20header).
33 #[repr(C)]
34 #[derive(Debug, PartialEq, Copy, Clone, Default, Pwrite)]
35 #[doc(alias("IMAGE_DOS_HEADER"))]
36 pub struct DosHeader {
37 /// Magic number: `[0x5A, 0x4D]`. In [little endian](https://en.wikipedia.org/wiki/Endianness)
38 /// [ASCII](https://en.wikipedia.org/wiki/ASCII), it reads "MZ" for [Mark Zbikowski](https://en.wikipedia.org/wiki/Mark_Zbikowski)).
39 ///
40 /// ## Non-MZ DOS executables
41 ///
42 /// * For [IBM OS/2](https://www.britannica.com/technology/IBM-OS-2), the value was "NE".
43 /// * For IBM OS/2 LE, the value was "LE".
44 /// * For [NT](https://en.wikipedia.org/wiki/Windows_NT), the value was "PE00".
45 ///
46 /// Sources:
47 ///
48 /// * <https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/>
49 /// * <https://learn.microsoft.com/en-us/archive/msdn-magazine/2002/february/inside-windows-win32-portable-executable-file-format-in-detail>
50 #[doc(alias("e_magic"))]
51 pub signature: u16,
52 /// In `winnt.h` and `pe.h`, it's `e_cblp`.
53 ///
54 /// It used to specify the number of bytes actually used in the last "page".
55 /// Page used to refer to a segment of memory, usually of 512 bytes size.
56 ///
57 /// The case of full page was represented by 0x0000 (since the last page is never empty).
58 ///
59 /// For example, assuming a page size of 512 bytes, this value would
60 /// be 0x0000 for a 1024 byte file, and 0x0001 for a 1025 byte file
61 /// (since it only contains one valid byte).
62 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
63 ///
64 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
65 #[doc(alias("e_cblp"))]
66 pub bytes_on_last_page: u16,
67 /// In `winnt.h` and `pe.h`, it's `e_cp`.
68 ///
69 /// It used to specify the number of pages required to hold a file. For example,
70 /// if the file contained 1024 bytes, and the file had pages of a size of 512 bytes,
71 /// this [word](https://en.wikipedia.org/wiki/Word_(computer_architecture)) would contain
72 /// 0x0002 (2 pages); if the file contained 1025 bytes, this word would contain 0x0003 (3 pages).
73 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
74 ///
75 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
76 #[doc(alias("e_cp"))]
77 pub pages_in_file: u16,
78 /// In `winnt.h` and `pe.h`, it's `e_crlc`.
79 ///
80 /// It used to specify the number of "relocation items", i.e. the number of entries that
81 /// existed in the ["relocation pointer table"](https://www.tavi.co.uk/phobos/exeformat.html#reloctable).
82 /// If there were no relocations, this field would contain 0x0000.
83 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
84 ///
85 /// ## On relocation items and relocation pointer table
86 ///
87 /// When a program is compiled, memory addresses are often hard-coded into the binary code.
88 /// These addresses are usually relative to the base address where the program expects to be loaded into memory.
89 /// However, when the program is loaded into memory, it might not be loaded at its preferred base address due to
90 /// various reasons such as memory fragmentation or other programs already occupying that space.
91 ///
92 /// Relocation items, also known as fixups or relocations, are pieces of data embedded within the executable file
93 /// that indicate which memory addresses need to be adjusted when the program is loaded at a different base address.
94 /// These relocations specify the location and type of adjustment needed.
95 ///
96 /// The relocation pointer table is a data structure that contains pointers to the locations within the executable file
97 /// where relocations need to be applied. It allows the operating system's loader to efficiently locate and process the
98 /// relocation data during the loading process.
99 ///
100 /// ---
101 ///
102 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
103 #[doc(alias("e_crlc"))]
104 pub relocations: u16,
105 /// In `winnt.h` and `pe.h`, it's `e_cparhdr`.
106 ///
107 /// It used to specify the size of the "executable header" in terms of "paragraphs" (16 byte chunks). It used to indicate
108 /// the offset of the program's compiled/assembled and linked image (the [load module](https://www.tavi.co.uk/phobos/exeformat.html#loadmodule)) within the executable file. The size
109 /// of the load module could have been deduced by substructing this value (converted to bytes) from the overall size that could
110 /// have been derived from combining the value of [`pages_in_file` (aka `e_cp`)](DosHeader::pages_in_file) and the value of
111 /// [`bytes_on_last_page` (aka `e_cblp)`](DosHeader::bytes_on_last_page). The header used to always span an even number of
112 /// paragraphs.
113 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
114 ///
115 /// The "executable header" in this context refers to the DOS header itself.
116 ///
117 /// Typically, this field is set to 4. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
118 /// This is because the modern DOS header is 64 bytes long, and 64 / 16 = 4.
119 #[doc(alias("e_cparhdr"))]
120 pub size_of_header_in_paragraphs: u16,
121 /// In `winnt.h` and `pe.h`, it's `e_minalloc`.
122 ///
123 /// It used to specify the minimum number of extra paragraphs needed to be allocated to begin execution. This is
124 /// **in addition** to the memory required to hold the [load module](https://www.tavi.co.uk/phobos/exeformat.html#loadmodule). This value normally represented the total size
125 /// of any uninitialized data and/or stack segments that were linked at the end of the program. This space was not
126 /// directly included in the load module, since there were no particular initializing values and it would simply waste
127 /// disk space.
128 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
129 ///
130 /// If both the [`minimum_extra_paragraphs_needed` (aka `e_minalloc`)](DosHeader::minimum_extra_paragraphs_needed) and
131 /// [`maximum_extra_paragraphs_needed` (aka `e_maxalloc`)](DosHeader::maximum_extra_paragraphs_needed) fields were set to 0x0000,
132 /// the program would be allocated as much memory as available. [Source](https://www.tavi.co.uk/phobos/exeformat.html)
133 ///
134 /// Typically, this field is set to 0x10. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
135 #[doc(alias("e_minalloc"))]
136 pub minimum_extra_paragraphs_needed: u16,
137 /// In `winnt.h` and `pe.h`, it's `e_maxalloc`.
138 ///
139 /// It used to specify the maximum number of extra paragraphs needed to be allocated by to begin execution. This indicated
140 /// **additional** memory over and above that required by the [load module](https://www.tavi.co.uk/phobos/exeformat.html#loadmodule) and the value specified in
141 /// [`minimum_extra_paragraphs_needed` (aka `e_minalloc`)](DosHeader::minimum_extra_paragraphs_needed).
142 /// If the request could not be satisfied, the program would be allocated as much memory as available.
143 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
144 ///
145 /// If both the [`minimum_extra_paragraphs_needed` (aka `e_minalloc`)](DosHeader::minimum_extra_paragraphs_needed) and
146 /// [`maximum_extra_paragraphs_needed` (aka `e_maxalloc`)](DosHeader::maximum_extra_paragraphs_needed) fields were set to 0x0000,
147 /// the program would be allocated as much memory as available. [Source](https://www.tavi.co.uk/phobos/exeformat.html)
148 ///
149 /// Typically, this field is set to 0xFFFF. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
150 #[doc(alias("e_maxalloc"))]
151 pub maximum_extra_paragraphs_needed: u16,
152 /// In `winnt.h` and `pe.h`, it's `e_ss`.
153 ///
154 /// It used to specify the initial SS ("stack segment") value. SS value was a paragraph address of the stack segment
155 /// relative to the start of the [load module](https://www.tavi.co.uk/phobos/exeformat.html#loadmodule). At load time, the value was relocated by adding the address of the
156 /// start segment of the program to it, and the resulting value was placed in the SS register before the program is
157 /// started. To read more about x86 memory segmentation and SS register, see the
158 /// [wikipedia article](https://en.wikipedia.org/wiki/X86_memory_segmentation) on this topic. In DOS, the start segment
159 /// boundary of the program was the first segment boundary in memory after
160 /// [Program Segment Prefix (PSP)](https://en.wikipedia.org/wiki/Program_Segment_Prefix).
161 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
162 ///
163 /// The Program Segment Prefix (PSP) was a data structure used in DOS (Disk Operating System) environments.
164 /// It was located at the beginning of the memory allocated for a running program and it contained various
165 /// pieces of information about the program, including command-line arguments, environment variables,
166 /// and pointers to various system resources.
167 ///
168 /// [According to Wikipedia](https://en.wikipedia.org/wiki/Data_segment#Stack), the stack segment contains the call stack,
169 /// a LIFO structure, typically located in the higher parts of memory. A "stack pointer" register tracks the top of the
170 /// stack; it is adjusted each time a value is "pushed" onto the stack. The set of values pushed for one function call
171 /// is termed a "stack frame".
172 ///
173 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
174 #[doc(alias("e_ss"))]
175 pub initial_relative_ss: u16,
176 /// In `winnt.h` and `pe.h`, it's `e_sp`.
177 ///
178 /// It used to specify the initial SP ("stack pointer") value. SP value was the absolute value that must have been loaded
179 /// into the SP register before the program is given control. Since the actual stack segment was determined by the loader,
180 /// and this was merely a value within that segment, it didn't need to be relocated.
181 ///
182 /// [According to Wikipedia](https://en.wikipedia.org/wiki/Data_segment#Stack), the stack segment contains the call stack,
183 /// a LIFO structure, typically located in the higher parts of memory. A "stack pointer" register tracks the top of the
184 /// stack; it is adjusted each time a value is "pushed" onto the stack. The set of values pushed for one function call
185 /// is termed a "stack frame".
186 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
187 ///
188 /// Typically, this field is set to 0xB8. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
189 // TODO: Clarify what exactly is meany by "this was merely a value within that segment".
190 #[doc(alias("e_sp"))]
191 pub initial_sp: u16,
192 /// In `winnt.h` and `pe.h`, it's `e_csum`.
193 ///
194 /// It used to specify the checksum of the contents of the executable file It used to ensure the integrity of the data
195 /// within the file. For full details on how this checksum was calculated, see <http://www.tavi.co.uk/phobos/exeformat.html#checksum>.
196 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
197 ///
198 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
199 #[doc(alias("e_csum"))]
200 pub checksum: u16,
201 /// In `winnt.h` and `pe.h`, it's `e_ip`.
202 ///
203 /// It used to specify the initial IP ("instruction pointer") value. IP value was the absolute value that must have been
204 /// loaded into the IP register in order to transfer control to the program. Since the actual code segment was determined
205 /// by the loader and, and this was merely a value within that segment, it didn't need to be relocated.
206 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
207 ///
208 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
209 // TODO: Clarify what exactly is meany by "this was merely a value within that segment".
210 #[doc(alias("e_ip"))]
211 pub initial_ip: u16,
212 /// In `winnt.h` and `pe.h`, it's `e_cs`.
213 ///
214 /// It used to specify the pre-relocated initial CS ("code segment") value relative to the start of the [load module](https://www.tavi.co.uk/phobos/exeformat.html#loadmodule),
215 /// that should have been placed in the CS register in order to transfer control to the program. At load time, this value
216 /// was relocated by adding the address of the start segment of the program to it, and the resulting value was placed in
217 /// the CS register when control is transferred.
218 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
219 ///
220 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
221 #[doc(alias("e_cs"))]
222 pub initial_relative_cs: u16,
223 /// In `winnt.h` and `pe.h`, it's `e_lfarlc`.
224 ///
225 /// It used to specify the logical file address of the relocation table, or more specifically, the offset from the start
226 /// of the file to the [relocation pointer table](https://www.tavi.co.uk/phobos/exeformat.html#reloctable). This value
227 /// must have been used to locate the relocation table (rather than assuming a fixed location) because variable-length
228 /// information pertaining to program overlays could have occurred before this table, causing its position to vary.
229 /// A value of 0x40 in this field generally indicated a different kind of executable, not a DOS 'MZ' type.
230 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
231 ///
232 /// Typically, this field is set to 0x40. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
233 #[doc(alias("e_lfarlc"))]
234 pub file_address_of_relocation_table: u16,
235 /// In `winnt.h` and `pe.h`, it's `e_ovno`.
236 ///
237 /// It used to specify the overlay number, which was normally set to 0x0000, because few programs actually had overlays.
238 /// It changed only in files containing programs that used overlays.
239 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
240 ///
241 /// Overlays were sections of a program that remained on disk until the program actually required them. Different overlays
242 /// could thus share the same memory area. The overlays were loaded and unloaded by special code provided by the program
243 /// or its run-time library.
244 ///
245 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
246 #[doc(alias("e_ovno"))]
247 pub overlay_number: u16,
248 /// In `winnt.h` and `pe.h`, it's `e_res[4]`.
249 ///
250 /// It used to specify the reserved words for the program, i.e. an array reserved for future use.
251 /// Usually, the array was zeroed by the linker.
252 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
253 ///
254 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
255 #[doc(alias("e_res"))]
256 pub reserved: [u16; 4],
257 /// In `winnt.h` and `pe.h`, it's `e_oemid`.
258 ///
259 /// It used to specify the identifier for the OEM ("Original Equipment Manufacturer") for [`oem_info` aka `e_oeminfo`](DosHeader::oem_info).
260 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
261 ///
262 /// More specifically, it used to specify the OEM of the system or hardware platform for which the executable file was created.
263 /// This field was used to specify certain characteristics or requirements related to the hardware environment in which the
264 /// executable was intended to run.
265 ///
266 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
267 #[doc(alias("e_oemid"))]
268 pub oem_id: u16,
269 /// In `winnt.h` and `pe.h`, it's `e_oeminfo`.
270 ///
271 /// It used to specify the extra information, the kind of which was specific to the OEM identified by [`oem_id` aka `e_oemid`](DosHeader::oem_id).
272 #[doc(alias("e_oeminfo"))]
273 pub oem_info: u16,
274 /// In `winnt.h` and `pe.h`, it's `e_res2[10]`.
275 ///
276 /// It used to specify the reserved words for the program, i.e. an array reserved for future use.
277 /// Usually, the array was zeroed by the linker.
278 /// [Source](https://stixproject.github.io/data-model/1.2/WinExecutableFileObj/DOSHeaderType/).
279 ///
280 /// Typically, this field is set to 0. [Source](https://offwhitesecurity.dev/malware-development/portable-executable-pe/dos-header/).
281 #[doc(alias("e_res2"))]
282 pub reserved2: [u16; 10],
283 /// In `winnt.h` and `pe.h`, it's `e_lfanew`.
284 ///
285 /// Today, it specifies the logcal file address of the of the new exe header. In particular, it is a 4-byte offset into
286 /// the file where the PE file header is located. It is necessary to use this offset to locate the PE header in the file.
287 ///
288 /// Typically, this field is set to 0x3c ([`PE_POINTER_OFFSET`]).
289 #[doc(alias("e_lfanew"))]
290 pub pe_pointer: u32,
291 }
292
293 #[doc(alias("IMAGE_DOS_SIGNATURE"))]
294 pub const DOS_MAGIC: u16 = 0x5a4d;
295 pub const PE_POINTER_OFFSET: u32 = 0x3c;
296 pub const DOS_STUB_OFFSET: u32 = PE_POINTER_OFFSET + (core::mem::size_of::<u32>() as u32);
297
298 impl DosHeader {
299 pub fn parse(bytes: &[u8]) -> error::Result<Self> {
300 let mut offset = 0;
301 let signature = bytes.gread_with(&mut offset, scroll::LE).map_err(|_| {
302 error::Error::Malformed(format!("cannot parse DOS signature (offset {:#x})", 0))
303 })?;
304 if signature != DOS_MAGIC {
305 return Err(error::Error::Malformed(format!(
306 "DOS header is malformed (signature {:#x})",
307 signature
308 )));
309 }
310
311 let bytes_on_last_page = bytes.gread_with(&mut offset, scroll::LE)?;
312 let pages_in_file = bytes.gread_with(&mut offset, scroll::LE)?;
313 let relocations = bytes.gread_with(&mut offset, scroll::LE)?;
314 let size_of_header_in_paragraphs = bytes.gread_with(&mut offset, scroll::LE)?;
315 let minimum_extra_paragraphs_needed = bytes.gread_with(&mut offset, scroll::LE)?;
316 let maximum_extra_paragraphs_needed = bytes.gread_with(&mut offset, scroll::LE)?;
317 let initial_relative_ss = bytes.gread_with(&mut offset, scroll::LE)?;
318 let initial_sp = bytes.gread_with(&mut offset, scroll::LE)?;
319 let checksum = bytes.gread_with(&mut offset, scroll::LE)?;
320 let initial_ip = bytes.gread_with(&mut offset, scroll::LE)?;
321 let initial_relative_cs = bytes.gread_with(&mut offset, scroll::LE)?;
322 let file_address_of_relocation_table = bytes.gread_with(&mut offset, scroll::LE)?;
323 let overlay_number = bytes.gread_with(&mut offset, scroll::LE)?;
324 let reserved = bytes.gread_with(&mut offset, scroll::LE)?; // 4
325 let oem_id = bytes.gread_with(&mut offset, scroll::LE)?;
326 let oem_info = bytes.gread_with(&mut offset, scroll::LE)?;
327 let reserved2 = bytes.gread_with(&mut offset, scroll::LE)?; // 10
328
329 debug_assert!(
330 offset == PE_POINTER_OFFSET as usize,
331 "expected offset ({:#x}) after reading DOS header to be at 0x3C",
332 offset
333 );
334
335 let pe_pointer = bytes
336 .pread_with(PE_POINTER_OFFSET as usize, scroll::LE)
337 .map_err(|_| {
338 error::Error::Malformed(format!(
339 "cannot parse PE header pointer (offset {:#x})",
340 PE_POINTER_OFFSET
341 ))
342 })?;
343
344 let pe_signature: u32 =
345 bytes
346 .pread_with(pe_pointer as usize, scroll::LE)
347 .map_err(|_| {
348 error::Error::Malformed(format!(
349 "cannot parse PE header signature (offset {:#x})",
350 pe_pointer
351 ))
352 })?;
353 if pe_signature != PE_MAGIC {
354 return Err(error::Error::Malformed(format!(
355 "PE header is malformed (signature {:#x})",
356 pe_signature
357 )));
358 }
359
360 Ok(DosHeader {
361 signature,
362 bytes_on_last_page,
363 pages_in_file,
364 relocations,
365 size_of_header_in_paragraphs,
366 minimum_extra_paragraphs_needed,
367 maximum_extra_paragraphs_needed,
368 initial_relative_ss,
369 initial_sp,
370 checksum,
371 initial_ip,
372 initial_relative_cs,
373 file_address_of_relocation_table,
374 overlay_number,
375 reserved,
376 oem_id,
377 oem_info,
378 reserved2,
379 pe_pointer,
380 })
381 }
382 }
383
384 #[repr(C)]
385 #[derive(Debug, PartialEq, Copy, Clone, Pread, Pwrite)]
386 /// The DOS stub program which should be executed in DOS mode. It prints the message "This program cannot be run in DOS mode" and exits.
387 ///
388 /// ## Position in a modern PE file
389 ///
390 /// The [DosStub] is usually located immediately after the [DosHeader] and...
391 ///
392 /// * De facto, can be followed by a non-standard ["Rich header"](https://0xrick.github.io/win-internals/pe3/#rich-header).
393 /// * According to the standard, is followed by the [Header::signature] and then the [CoffHeader].
394 pub struct DosStub(pub [u8; 0x40]);
395 impl Default for DosStub {
396 fn default() -> Self {
397 // "This program cannot be run in DOS mode" error program
398 Self([
399 0x0E, 0x1F, 0xBA, 0x0E, 0x00, 0xB4, 0x09, 0xCD, 0x21, 0xB8, 0x01, 0x4C, 0xCD, 0x21,
400 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6F, 0x67, 0x72, 0x61, 0x6D, 0x20, 0x63,
401 0x61, 0x6E, 0x6E, 0x6F, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6E, 0x20, 0x69,
402 0x6E, 0x20, 0x44, 0x4F, 0x53, 0x20, 0x6D, 0x6F, 0x64, 0x65, 0x2E, 0x0D, 0x0D, 0x0A,
403 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
404 ])
405 }
406 }
407
408 /// In `winnt.h`, it's `IMAGE_FILE_HEADER`. COFF Header.
409 ///
410 /// Together with the [Header::signature] and the [Header::optional_header], it forms the
411 /// [`IMAGE_NT_HEADERS`](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_nt_headers32).
412 ///
413 /// ## Position in a modern PE file
414 ///
415 /// The COFF header is located after the [Header::signature], which in turn is located after the
416 /// non-standard ["Rich header"](https://0xrick.github.io/win-internals/pe3/#rich-header), if present,
417 /// and after the [DosStub], according to the standard.
418 ///
419 /// COFF header is followed by the [Header::optional_header].
420 #[repr(C)]
421 #[derive(Debug, PartialEq, Copy, Clone, Default, Pread, Pwrite, IOread, IOwrite, SizeWith)]
422 #[doc(alias("IMAGE_FILE_HEADER"))]
423 pub struct CoffHeader {
424 /// The architecture type of the computer. An image file can only be run
425 /// on the specified computer or a system that emulates the specified computer.
426 ///
427 /// Can be one of the following values:
428 ///
429 /// * [`COFF_MACHINE_UNKNOWN`],
430 /// * [`COFF_MACHINE_ALPHA`],
431 /// * [`COFF_MACHINE_ALPHA64`],
432 /// * [`COFF_MACHINE_AM33`],
433 /// * [`COFF_MACHINE_X86_64`],
434 /// * [`COFF_MACHINE_ARM`],
435 /// * [`COFF_MACHINE_ARM64`],
436 /// * [`COFF_MACHINE_ARMNT`],
437 /// * [`COFF_MACHINE_EBC`],
438 /// * [`COFF_MACHINE_X86`],
439 /// * [`COFF_MACHINE_IA64`],
440 /// * [`COFF_MACHINE_LOONGARCH32`],
441 /// * [`COFF_MACHINE_LOONGARCH64`],
442 /// * [`COFF_MACHINE_M32R`],
443 /// * [`COFF_MACHINE_MIPS16`],
444 /// * [`COFF_MACHINE_MIPSFPU`],
445 /// * [`COFF_MACHINE_MIPSFPU16`],
446 /// * [`COFF_MACHINE_POWERPC`],
447 /// * [`COFF_MACHINE_POWERPCFP`],
448 /// * [`COFF_MACHINE_R4000`],
449 /// * [`COFF_MACHINE_RISCV32`],
450 /// * [`COFF_MACHINE_RISCV64`],
451 /// * [`COFF_MACHINE_RISCV128`],
452 /// * [`COFF_MACHINE_SH3`],
453 /// * [`COFF_MACHINE_SH3DSP`],
454 /// * [`COFF_MACHINE_SH4`],
455 /// * [`COFF_MACHINE_SH5`],
456 /// * [`COFF_MACHINE_THUMB`],
457 /// * [`COFF_MACHINE_WCEMIPSV2`],
458 ///
459 /// or any other value that is not listed here.
460 ///
461 /// The constants above are sourced from <https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types>.
462 /// If there's a missing constant, please open an issue or a pull request.
463 // TODO: insert the values names with a macro
464 #[doc(alias("Machine"))]
465 pub machine: u16,
466 /// The number of sections. This indicates the size of the section table, which immediately follows the headers.
467 /// Note that the Windows loader limits the number of sections to 96.
468 /// [Source](https://learn.microsoft.com/en-us/windows/win32/api/winnt/ns-winnt-image_file_header).
469 #[doc(alias("NumberOfSections"))]
470 pub number_of_sections: u16,
471 /// The low 32 bits of the time stamp of the image. This represents the date and time the image was created by the linker.
472 /// The value is represented in the number of seconds elapsed since midnight (00:00:00), January 1, 1970, Universal
473 /// Coordinated Time, according to the system clock.
474 #[doc(alias("TimeDateStamp"))]
475 pub time_date_stamp: u32,
476 /// The offset of the symbol table, in bytes, or zero if no COFF symbol table exists.
477 ///
478 /// Typically, this field is set to 0 because COFF debugging information is deprecated.
479 /// [Source](https://0xrick.github.io/win-internals/pe4/#file-header-image_file_header).
480 // TODO: further explain the COFF symbol table. This seems to be a nuanced topic.
481 #[doc(alias("PointerToSymbolTable"))]
482 pub pointer_to_symbol_table: u32,
483 /// The number of symbols in the symbol table.
484 ///
485 /// Typically, this field is set to 0 because COFF debugging information is deprecated.
486 /// [Source](https://0xrick.github.io/win-internals/pe4/#file-header-image_file_header).
487 // Q (JohnScience): Why is the name `number_of_symbol_table` and not `number_of_symbols`?
488 #[doc(alias("NumberOfSymbols"))]
489 pub number_of_symbol_table: u32,
490 /// The size of the optional header, in bytes. This value should be zero for object files.
491 ///
492 /// The [`goblin::pe::optional_header::OptionalHeader`](crate::pe::optional_header::OptionalHeader) is meant to
493 /// represent either the 32-bit or the 64-bit optional header. The size of the optional header is used to determine
494 /// which one it is.
495 #[doc(alias("SizeOfOptionalHeader"))]
496 pub size_of_optional_header: u16,
497 /// The [characteristics](https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#characteristics) of the image.
498 ///
499 /// The constants for the characteristics are available in the [`goblin::pe::characteristic`](crate::pe::characteristic) module.
500 #[doc(alias("Characteristics"))]
501 pub characteristics: u16,
502 }
503
504 pub const SIZEOF_COFF_HEADER: usize = 20;
505 /// PE\0\0, little endian
506 pub const PE_MAGIC: u32 = 0x0000_4550;
507 pub const SIZEOF_PE_MAGIC: usize = 4;
508
509 // Q (JohnScience): doesn't it make sense to move all these constants to a dedicated module
510 // and then re-export them from here? This way, the module will be more organized.
511 //
512 // Also, don't we want to declare them in a macro to remove the boilerplate and make the implementation
513 // of `machine_to_str` more future-proof and concise? For example, addition of...
514 //
515 // * `IMAGE_FILE_MACHINE_LOONGARCH32`,
516 // * `IMAGE_FILE_MACHINE_LOONGARCH64`,
517 // * `IMAGE_FILE_MACHINE_ALPHA`,
518 // * `IMAGE_FILE_MACHINE_ALPHA64`
519 //
520 // didn't trigger the exhaustiveness check because there was a necessary default case.
521 //
522 // This way, we can also generate a test that would parse <https://learn.microsoft.com/en-us/windows/win32/debug/pe-format#machine-types>
523 // and check that there are no missing constants.
524
525 /// The contents of this field are assumed to be applicable to any machine type.
526 ///
527 /// One of the possible values for [`CoffHeader::machine`].
528 #[doc(alias("IMAGE_FILE_MACHINE_UNKNOWN"))]
529 pub const COFF_MACHINE_UNKNOWN: u16 = 0x0;
530
531 /// Alpha AXP, 32-bit address space.
532 ///
533 /// One of the possible values for [`CoffHeader::machine`].
534 #[doc(alias("IMAGE_FILE_MACHINE_ALPHA"))]
535 pub const COFF_MACHINE_ALPHA: u16 = 0x184;
536
537 /// Alpha AXP, 64-bit address space.
538 ///
539 /// One of the possible values for [`CoffHeader::machine`].
540 #[doc(alias("IMAGE_FILE_MACHINE_ALPHA64"))]
541 #[doc(alias("IMAGE_FILE_MACHINE_AXP64"))]
542 pub const COFF_MACHINE_ALPHA64: u16 = 0x284;
543
544 /// Matsushita AM33.
545 ///
546 /// One of the possible values for [`CoffHeader::machine`].
547 #[doc(alias("IMAGE_FILE_MACHINE_AM33"))]
548 pub const COFF_MACHINE_AM33: u16 = 0x1d3;
549
550 /// x64 aka amd64.
551 ///
552 /// One of the possible values for [`CoffHeader::machine`].
553 #[doc(alias("IMAGE_FILE_MACHINE_AMD64"))]
554 // Q (JohnScience): why is this `COFF_MACHINE_X86_64` and not `COFF_MACHINE_AMD64`?
555 // Should we deprecate the former and use the latter instead?
556 pub const COFF_MACHINE_X86_64: u16 = 0x8664;
557
558 /// ARM little endian.
559 ///
560 /// One of the possible values for [`CoffHeader::machine`].
561 #[doc(alias("IMAGE_FILE_MACHINE_ARM"))]
562 pub const COFF_MACHINE_ARM: u16 = 0x1c0;
563
564 /// ARM64 little endian.
565 ///
566 /// One of the possible values for [`CoffHeader::machine`].
567 #[doc(alias("IMAGE_FILE_MACHINE_ARM64"))]
568 pub const COFF_MACHINE_ARM64: u16 = 0xaa64;
569
570 /// ARM Thumb-2 little endian.
571 ///
572 /// One of the possible values for [`CoffHeader::machine`].
573 #[doc(alias("IMAGE_FILE_MACHINE_ARMNT"))]
574 pub const COFF_MACHINE_ARMNT: u16 = 0x1c4;
575
576 /// EFI byte code.
577 ///
578 /// One of the possible values for [`CoffHeader::machine`].
579 #[doc(alias("IMAGE_FILE_MACHINE_EBC"))]
580 pub const COFF_MACHINE_EBC: u16 = 0xebc;
581
582 /// Intel 386 or later processors and compatible processors.
583 ///
584 /// One of the possible values for [`CoffHeader::machine`].
585 // Q (JohnScience): why is this `COFF_MACHINE_X86` and not `COFF_MACHINE_I386`?
586 // Should we deprecate the former and use the latter instead?
587 #[doc(alias("IMAGE_FILE_MACHINE_I386"))]
588 pub const COFF_MACHINE_X86: u16 = 0x14c;
589
590 /// Intel Itanium processor family.
591 ///
592 /// One of the possible values for [`CoffHeader::machine`].
593 #[doc(alias("IMAGE_FILE_MACHINE_IA64"))]
594 pub const COFF_MACHINE_IA64: u16 = 0x200;
595
596 /// LoongArch 32-bit processor family.
597 ///
598 /// One of the possible values for [`CoffHeader::machine`].
599 #[doc(alias("IMAGE_FILE_MACHINE_LOONGARCH32"))]
600 pub const COFF_MACHINE_LOONGARCH32: u16 = 0x6232;
601
602 /// LoongArch 64-bit processor family.
603 ///
604 /// One of the possible values for [`CoffHeader::machine`].
605 #[doc(alias("IMAGE_FILE_MACHINE_LOONGARCH64"))]
606 pub const COFF_MACHINE_LOONGARCH64: u16 = 0x6264;
607
608 /// Mitsubishi M32R little endian.
609 ///
610 /// One of the possible values for [`CoffHeader::machine`].
611 #[doc(alias("IMAGE_FILE_MACHINE_M32R"))]
612 pub const COFF_MACHINE_M32R: u16 = 0x9041;
613
614 /// MIPS16.
615 ///
616 /// One of the possible values for [`CoffHeader::machine`].
617 #[doc(alias("IMAGE_FILE_MACHINE_MIPS16"))]
618 pub const COFF_MACHINE_MIPS16: u16 = 0x266;
619
620 /// MIPS with FPU.
621 ///
622 /// One of the possible values for [`CoffHeader::machine`].
623 #[doc(alias("IMAGE_FILE_MACHINE_MIPSFPU"))]
624 pub const COFF_MACHINE_MIPSFPU: u16 = 0x366;
625
626 /// MIPS16 with FPU.
627 ///
628 /// One of the possible values for [`CoffHeader::machine`].
629 #[doc(alias("IMAGE_FILE_MACHINE_MIPSFPU16"))]
630 pub const COFF_MACHINE_MIPSFPU16: u16 = 0x466;
631
632 /// Power PC little endian.
633 ///
634 /// One of the possible values for [`CoffHeader::machine`].
635 #[doc(alias("IMAGE_FILE_MACHINE_POWERPC"))]
636 pub const COFF_MACHINE_POWERPC: u16 = 0x1f0;
637
638 /// Power PC with floating point support.
639 ///
640 /// One of the possible values for [`CoffHeader::machine`].
641 #[doc(alias("IMAGE_FILE_MACHINE_POWERPCFP"))]
642 pub const COFF_MACHINE_POWERPCFP: u16 = 0x1f1;
643
644 /// MIPS little endian.
645 ///
646 /// One of the possible values for [`CoffHeader::machine`].
647 #[doc(alias("IMAGE_FILE_MACHINE_R4000"))]
648 pub const COFF_MACHINE_R4000: u16 = 0x166;
649
650 /// RISC-V 32-bit address space.
651 ///
652 /// One of the possible values for [`CoffHeader::machine`].
653 #[doc(alias("IMAGE_FILE_MACHINE_RISCV32"))]
654 pub const COFF_MACHINE_RISCV32: u16 = 0x5032;
655
656 /// RISC-V 64-bit address space.
657 ///
658 /// One of the possible values for [`CoffHeader::machine`].
659 #[doc(alias("IMAGE_FILE_MACHINE_RISCV64"))]
660 pub const COFF_MACHINE_RISCV64: u16 = 0x5064;
661
662 /// RISC-V 128-bit address space
663 ///
664 /// One of the possible values for [`CoffHeader::machine`].
665 #[doc(alias("IMAGE_FILE_MACHINE_RISCV128"))]
666 pub const COFF_MACHINE_RISCV128: u16 = 0x5128;
667
668 /// Hitachi SH3.
669 ///
670 /// One of the possible values for [`CoffHeader::machine`].
671 #[doc(alias("IMAGE_FILE_MACHINE_SH3"))]
672 pub const COFF_MACHINE_SH3: u16 = 0x1a2;
673
674 /// Hitachi SH3 DSP.
675 ///
676 /// One of the possible values for [`CoffHeader::machine`].
677 #[doc(alias("IMAGE_FILE_MACHINE_SH3DSP"))]
678 pub const COFF_MACHINE_SH3DSP: u16 = 0x1a3;
679
680 /// Hitachi SH4.
681 ///
682 /// One of the possible values for [`CoffHeader::machine`].
683 #[doc(alias("IMAGE_FILE_MACHINE_SH4"))]
684 pub const COFF_MACHINE_SH4: u16 = 0x1a6;
685
686 /// Hitachi SH5.
687 ///
688 /// One of the possible values for [`CoffHeader::machine`].
689 #[doc(alias("IMAGE_FILE_MACHINE_SH5"))]
690 pub const COFF_MACHINE_SH5: u16 = 0x1a8;
691
692 /// Thumb.
693 ///
694 /// One of the possible values for [`CoffHeader::machine`].
695 #[doc(alias("IMAGE_FILE_MACHINE_THUMB"))]
696 pub const COFF_MACHINE_THUMB: u16 = 0x1c2;
697
698 /// MIPS little-endian WCE v2.
699 ///
700 /// One of the possible values for [`CoffHeader::machine`].
701 #[doc(alias("IMAGE_FILE_MACHINE_WCEMIPSV2"))]
702 pub const COFF_MACHINE_WCEMIPSV2: u16 = 0x169;
703
704 impl CoffHeader {
705 pub fn parse(bytes: &[u8], offset: &mut usize) -> error::Result<Self> {
706 Ok(bytes.gread_with(offset, scroll::LE)?)
707 }
708
709 /// Parse the COFF section headers.
710 ///
711 /// For COFF, these immediately follow the COFF header. For PE, these immediately follow the
712 /// optional header.
713 pub fn sections(
714 &self,
715 bytes: &[u8],
716 offset: &mut usize,
717 ) -> error::Result<Vec<section_table::SectionTable>> {
718 let nsections = self.number_of_sections as usize;
719
720 // a section table is at least 40 bytes
721 if nsections > bytes.len() / 40 {
722 return Err(error::Error::BufferTooShort(nsections, "sections"));
723 }
724
725 let mut sections = Vec::with_capacity(nsections);
726 // Note that if we are handling a BigCoff, the size of the symbol will be different!
727 let string_table_offset = self.pointer_to_symbol_table as usize
728 + symbol::SymbolTable::size(self.number_of_symbol_table as usize);
729 for i in 0..nsections {
730 let section =
731 section_table::SectionTable::parse(bytes, offset, string_table_offset as usize)?;
732 debug!("({}) {:#?}", i, section);
733 sections.push(section);
734 }
735 Ok(sections)
736 }
737
738 /// Return the COFF symbol table.
739 pub fn symbols<'a>(&self, bytes: &'a [u8]) -> error::Result<Option<symbol::SymbolTable<'a>>> {
740 let offset = self.pointer_to_symbol_table as usize;
741 let number = self.number_of_symbol_table as usize;
742 if offset == 0 {
743 Ok(None)
744 } else {
745 symbol::SymbolTable::parse(bytes, offset, number).map(Some)
746 }
747 }
748
749 /// Return the COFF string table.
750 pub fn strings<'a>(&self, bytes: &'a [u8]) -> error::Result<Option<strtab::Strtab<'a>>> {
751 // > The file offset of the COFF symbol table, or zero if no COFF symbol table is present.
752 // > This value should be zero for an image because COFF debugging information is deprecated.
753 if self.pointer_to_symbol_table == 0 {
754 return Ok(None);
755 }
756
757 let mut offset = self.pointer_to_symbol_table as usize
758 + symbol::SymbolTable::size(self.number_of_symbol_table as usize);
759
760 let length_field_size = core::mem::size_of::<u32>();
761 let length = bytes.pread_with::<u32>(offset, scroll::LE)? as usize - length_field_size;
762
763 // The offset needs to be advanced in order to read the strings.
764 offset += length_field_size;
765
766 Ok(Some(strtab::Strtab::parse(bytes, offset, length, 0)?))
767 }
768 }
769
770 /// The PE header.
771 ///
772 /// ## Position in a modern PE file
773 ///
774 /// The PE header is located at the very beginning of the file and
775 /// is followed by the section table and sections.
776 #[derive(Debug, PartialEq, Copy, Clone, Default)]
777 pub struct Header {
778 pub dos_header: DosHeader,
779 /// DOS program for legacy loaders
780 pub dos_stub: DosStub,
781
782 // Q (JohnScience): should we care about the "rich header"?
783 // https://0xrick.github.io/win-internals/pe3/#rich-header
784 // Introducing it would be a breaking change because it would require a new field in the struct
785 // but it would be a good addition to the library.
786 //
787 /// PE Magic: PE\0\0, little endian
788 pub signature: u32,
789 pub coff_header: CoffHeader,
790 pub optional_header: Option<optional_header::OptionalHeader>,
791 }
792
793 impl Header {
794 fn parse_impl(bytes: &[u8], dos_header: DosHeader, dos_stub: DosStub) -> error::Result<Self> {
795 let mut offset = dos_header.pe_pointer as usize;
796 let signature = bytes.gread_with(&mut offset, scroll::LE).map_err(|_| {
797 error::Error::Malformed(format!("cannot parse PE signature (offset {:#x})", offset))
798 })?;
799 let coff_header = CoffHeader::parse(&bytes, &mut offset)?;
800 let optional_header = if coff_header.size_of_optional_header > 0 {
801 Some(bytes.pread::<optional_header::OptionalHeader>(offset)?)
802 } else {
803 None
804 };
805
806 Ok(Header {
807 dos_header,
808 dos_stub,
809 signature,
810 coff_header,
811 optional_header,
812 })
813 }
814
815 /// Parses PE header from the given bytes; this will fail if the DosHeader or DosStub is malformed or missing in some way
816 pub fn parse(bytes: &[u8]) -> error::Result<Self> {
817 let dos_header = DosHeader::parse(&bytes)?;
818 let dos_stub = bytes.pread(DOS_STUB_OFFSET as usize).map_err(|_| {
819 error::Error::Malformed(format!(
820 "cannot parse DOS stub (offset {:#x})",
821 DOS_STUB_OFFSET
822 ))
823 })?;
824
825 Header::parse_impl(bytes, dos_header, dos_stub)
826 }
827
828 /// Parses PE header from the given bytes, a default DosHeader and DosStub are generated, and any malformed header or stub is ignored
829 pub fn parse_without_dos(bytes: &[u8]) -> error::Result<Self> {
830 let dos_header = DosHeader::default();
831 Header::parse_impl(bytes, dos_header, DosStub::default())
832 }
833 }
834
835 impl ctx::TryIntoCtx<scroll::Endian> for Header {
836 type Error = error::Error;
837
838 fn try_into_ctx(self, bytes: &mut [u8], ctx: scroll::Endian) -> Result<usize, Self::Error> {
839 let offset = &mut 0;
840 bytes.gwrite_with(self.dos_header, offset, ctx)?;
841 bytes.gwrite_with(self.dos_stub, offset, ctx)?;
842 bytes.gwrite_with(self.signature, offset, scroll::LE)?;
843 bytes.gwrite_with(self.coff_header, offset, ctx)?;
844 if let Some(opt_header) = self.optional_header {
845 bytes.gwrite_with(opt_header, offset, ctx)?;
846 }
847 Ok(*offset)
848 }
849 }
850
851 /// The TE header is a reduced PE32/PE32+ header containing only fields
852 /// required for execution in the Platform Initialization
853 /// ([PI](https://uefi.org/specs/PI/1.8/V1_Introduction.html)) architecture.
854 /// The TE header is described in this specification:
855 /// <https://uefi.org/specs/PI/1.8/V1_TE_Image.html#te-header>
856 #[cfg(feature = "te")]
857 #[repr(C)]
858 #[derive(Debug, Default, PartialEq, Copy, Clone, Pread, Pwrite)]
859 pub struct TeHeader {
860 /// Te signature, always [TE_MAGIC]
861 pub signature: u16,
862 /// The machine type
863 pub machine: u16,
864 /// The number of sections
865 pub number_of_sections: u8,
866 /// The subsystem
867 pub subsystem: u8,
868 /// the amount of bytes stripped from the header when converting from a
869 /// PE32/PE32+ header to a TE header. Used to resolve addresses
870 pub stripped_size: u16,
871 /// The entry point of the binary
872 pub entry_point: u32,
873 /// The base of the code section
874 pub base_of_code: u32,
875 /// The image base
876 pub image_base: u64,
877 /// The size and address of the relocation directory
878 pub reloc_dir: data_directories::DataDirectory,
879 /// The size and address of the debug directory
880 pub debug_dir: data_directories::DataDirectory,
881 }
882
883 #[cfg(feature = "te")]
884 #[doc(alias("IMAGE_TE_SIGNATURE"))]
885 pub const TE_MAGIC: u16 = 0x5a56;
886
887 #[cfg(feature = "te")]
888 impl TeHeader {
889 /// Parse the TE header from the given bytes.
890 pub fn parse(bytes: &[u8], offset: &mut usize) -> error::Result<Self> {
891 let mut header: TeHeader = bytes.gread_with(offset, scroll::LE)?;
892 let adj_offset = header.stripped_size as u32 - core::mem::size_of::<TeHeader>() as u32;
893 header.fixup_header(adj_offset);
894 Ok(header)
895 }
896
897 /// Parse the sections from the TE header.
898 pub fn sections(
899 &self,
900 bytes: &[u8],
901 offset: &mut usize,
902 ) -> error::Result<Vec<section_table::SectionTable>> {
903 let adj_offset = self.stripped_size as u32 - core::mem::size_of::<TeHeader>() as u32;
904 let nsections = self.number_of_sections as usize;
905
906 // a section table is at least 40 bytes
907 if nsections > bytes.len() / 40 {
908 return Err(error::Error::BufferTooShort(nsections, "sections"));
909 }
910
911 let mut sections = Vec::with_capacity(nsections);
912 for i in 0..nsections {
913 let mut section = section_table::SectionTable::parse(bytes, offset, 0)?;
914 TeHeader::fixup_section(&mut section, adj_offset);
915 debug!("({}) {:#?}", i, section);
916 sections.push(section);
917 }
918 Ok(sections)
919 }
920
921 // Adjust addresses in the header to account for the stripped size
922 fn fixup_header(&mut self, adj_offset: u32) {
923 debug!(
924 "Entry point fixed up from: 0x{:x} to 0x{:X}",
925 self.entry_point,
926 self.entry_point.wrapping_sub(adj_offset)
927 );
928 self.entry_point = self.entry_point.wrapping_sub(adj_offset);
929
930 debug!(
931 "Base of code fixed up from: 0x{:x} to 0x{:X}",
932 self.base_of_code,
933 self.base_of_code.wrapping_sub(adj_offset)
934 );
935 self.base_of_code = self.base_of_code.wrapping_sub(adj_offset);
936
937 debug!(
938 "Relocation Directory fixed up from: 0x{:x} to 0x{:X}",
939 self.reloc_dir.virtual_address,
940 self.reloc_dir.virtual_address.wrapping_sub(adj_offset)
941 );
942 self.reloc_dir.virtual_address = self.reloc_dir.virtual_address.wrapping_sub(adj_offset);
943
944 debug!(
945 "Debug Directory fixed up from: 0x{:x} to 0x{:X}",
946 self.debug_dir.virtual_address,
947 self.debug_dir.virtual_address.wrapping_sub(adj_offset)
948 );
949 self.debug_dir.virtual_address = self.debug_dir.virtual_address.wrapping_sub(adj_offset);
950 }
951
952 // Adjust addresses in the section to account for the stripped size
953 fn fixup_section(section: &mut section_table::SectionTable, adj_offset: u32) {
954 debug!(
955 "Section virtual address fixed up from: 0x{:X} to 0x{:X}",
956 section.virtual_address,
957 section.virtual_address.wrapping_sub(adj_offset)
958 );
959 section.virtual_address = section.virtual_address.wrapping_sub(adj_offset);
960
961 if section.pointer_to_linenumbers > 0 {
962 debug!(
963 "Section pointer to line numbers fixed up from: 0x{:X} to 0x{:X}",
964 section.pointer_to_linenumbers,
965 section.pointer_to_linenumbers.wrapping_sub(adj_offset)
966 );
967 section.pointer_to_linenumbers =
968 section.pointer_to_linenumbers.wrapping_sub(adj_offset);
969 }
970
971 if section.pointer_to_raw_data > 0 {
972 debug!(
973 "Section pointer to raw data fixed up from: 0x{:X} to 0x{:X}",
974 section.pointer_to_raw_data,
975 section.pointer_to_raw_data.wrapping_sub(adj_offset)
976 );
977 section.pointer_to_raw_data = section.pointer_to_raw_data.wrapping_sub(adj_offset);
978 }
979
980 if section.pointer_to_relocations > 0 {
981 debug!(
982 "Section pointer to relocations fixed up from: 0x{:X} to 0x{:X}",
983 section.pointer_to_relocations,
984 section.pointer_to_relocations.wrapping_sub(adj_offset)
985 );
986 section.pointer_to_relocations =
987 section.pointer_to_relocations.wrapping_sub(adj_offset);
988 }
989 }
990 }
991
992 /// Convert machine to str representation. Any case of "COFF_UNKNOWN"
993 /// should be expected to change to a more specific value.
994 pub fn machine_to_str(machine: u16) -> &'static str {
995 // TODO: generate the branches with a macro
996 match machine {
997 COFF_MACHINE_UNKNOWN => "UNKNOWN",
998 COFF_MACHINE_ALPHA => "ALPHA",
999 COFF_MACHINE_ALPHA64 => "ALPHA64",
1000 COFF_MACHINE_AM33 => "AM33",
1001 // This is an outlier. In the C header, it's IMAGE_FILE_MACHINE_AMD64
1002 COFF_MACHINE_X86_64 => "X86_64",
1003 COFF_MACHINE_ARM => "ARM",
1004 COFF_MACHINE_ARM64 => "ARM64",
1005 COFF_MACHINE_ARMNT => "ARM_NT",
1006 COFF_MACHINE_EBC => "EBC",
1007 // This is an outlier. In the C header, it's IMAGE_FILE_MACHINE_I386
1008 COFF_MACHINE_X86 => "X86",
1009 COFF_MACHINE_IA64 => "IA64",
1010 COFF_MACHINE_LOONGARCH32 => "LOONGARCH32",
1011 COFF_MACHINE_LOONGARCH64 => "LOONGARCH64",
1012 COFF_MACHINE_M32R => "M32R",
1013 COFF_MACHINE_MIPS16 => "MIPS_16",
1014 COFF_MACHINE_MIPSFPU => "MIPS_FPU",
1015 COFF_MACHINE_MIPSFPU16 => "MIPS_FPU_16",
1016 COFF_MACHINE_POWERPC => "POWERPC",
1017 COFF_MACHINE_POWERPCFP => "POWERCFP",
1018 COFF_MACHINE_R4000 => "R4000",
1019 COFF_MACHINE_RISCV32 => "RISC-V_32",
1020 COFF_MACHINE_RISCV64 => "RISC-V_64",
1021 COFF_MACHINE_RISCV128 => "RISC-V_128",
1022 COFF_MACHINE_SH3 => "SH3",
1023 COFF_MACHINE_SH3DSP => "SH3DSP",
1024 COFF_MACHINE_SH4 => "SH4",
1025 COFF_MACHINE_SH5 => "SH5",
1026 COFF_MACHINE_THUMB => "THUMB",
1027 COFF_MACHINE_WCEMIPSV2 => "WCE_MIPS_V2",
1028 _ => "COFF_UNKNOWN",
1029 }
1030 }
1031
1032 #[cfg(test)]
1033 mod tests {
1034 use super::{machine_to_str, Header, COFF_MACHINE_X86, DOS_MAGIC, PE_MAGIC};
1035
1036 const CRSS_HEADER: [u8; 688] = [
1037 0x4d, 0x5a, 0x90, 0x00, 0x03, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0x00, 0xff, 0xff, 0x00,
1038 0x00, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00,
1039 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1040 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1041 0xd0, 0x00, 0x00, 0x00, 0x0e, 0x1f, 0xba, 0x0e, 0x00, 0xb4, 0x09, 0xcd, 0x21, 0xb8, 0x01,
1042 0x4c, 0xcd, 0x21, 0x54, 0x68, 0x69, 0x73, 0x20, 0x70, 0x72, 0x6f, 0x67, 0x72, 0x61, 0x6d,
1043 0x20, 0x63, 0x61, 0x6e, 0x6e, 0x6f, 0x74, 0x20, 0x62, 0x65, 0x20, 0x72, 0x75, 0x6e, 0x20,
1044 0x69, 0x6e, 0x20, 0x44, 0x4f, 0x53, 0x20, 0x6d, 0x6f, 0x64, 0x65, 0x2e, 0x0d, 0x0d, 0x0a,
1045 0x24, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xaa, 0x4a, 0xc3, 0xeb, 0xee, 0x2b, 0xad,
1046 0xb8, 0xee, 0x2b, 0xad, 0xb8, 0xee, 0x2b, 0xad, 0xb8, 0xee, 0x2b, 0xac, 0xb8, 0xfe, 0x2b,
1047 0xad, 0xb8, 0x33, 0xd4, 0x66, 0xb8, 0xeb, 0x2b, 0xad, 0xb8, 0x33, 0xd4, 0x63, 0xb8, 0xea,
1048 0x2b, 0xad, 0xb8, 0x33, 0xd4, 0x7a, 0xb8, 0xed, 0x2b, 0xad, 0xb8, 0x33, 0xd4, 0x64, 0xb8,
1049 0xef, 0x2b, 0xad, 0xb8, 0x33, 0xd4, 0x61, 0xb8, 0xef, 0x2b, 0xad, 0xb8, 0x52, 0x69, 0x63,
1050 0x68, 0xee, 0x2b, 0xad, 0xb8, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x50, 0x45,
1051 0x00, 0x00, 0x4c, 0x01, 0x05, 0x00, 0xd9, 0x8f, 0x15, 0x52, 0x00, 0x00, 0x00, 0x00, 0x00,
1052 0x00, 0x00, 0x00, 0xe0, 0x00, 0x02, 0x01, 0x0b, 0x01, 0x0b, 0x00, 0x00, 0x08, 0x00, 0x00,
1053 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x11, 0x00, 0x00, 0x00, 0x10, 0x00,
1054 0x00, 0x00, 0x20, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x02,
1055 0x00, 0x00, 0x06, 0x00, 0x03, 0x00, 0x06, 0x00, 0x03, 0x00, 0x06, 0x00, 0x03, 0x00, 0x00,
1056 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00, 0xe4, 0xab, 0x00, 0x00,
1057 0x01, 0x00, 0x40, 0x05, 0x00, 0x00, 0x04, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x10,
1058 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x00, 0x00,
1059 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c, 0x30, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00,
1060 0x40, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1061 0x00, 0x1a, 0x00, 0x00, 0xb8, 0x22, 0x00, 0x00, 0x00, 0x50, 0x00, 0x00, 0x38, 0x00, 0x00,
1062 0x00, 0x10, 0x10, 0x00, 0x00, 0x38, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1063 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1064 0x00, 0x00, 0x00, 0x68, 0x10, 0x00, 0x00, 0x5c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1065 0x00, 0x00, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x3c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1066 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1067 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x2e, 0x74, 0x65, 0x78, 0x74, 0x00, 0x00, 0x00, 0x24,
1068 0x06, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x04, 0x00, 0x00,
1069 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x20, 0x00, 0x00,
1070 0x60, 0x2e, 0x64, 0x61, 0x74, 0x61, 0x00, 0x00, 0x00, 0x3c, 0x03, 0x00, 0x00, 0x00, 0x20,
1071 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x0c, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1072 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0xc0, 0x2e, 0x69, 0x64, 0x61,
1073 0x74, 0x61, 0x00, 0x00, 0xf8, 0x01, 0x00, 0x00, 0x00, 0x30, 0x00, 0x00, 0x00, 0x02, 0x00,
1074 0x00, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1075 0x00, 0x00, 0x40, 0x00, 0x00, 0x40, 0x2e, 0x72, 0x73, 0x72, 0x63, 0x00, 0x00, 0x00, 0x00,
1076 0x08, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x08, 0x00, 0x00, 0x00, 0x10, 0x00, 0x00,
1077 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00,
1078 0x42, 0x2e, 0x72, 0x65, 0x6c, 0x6f, 0x63, 0x00, 0x00, 0x86, 0x01, 0x00, 0x00, 0x00, 0x50,
1079 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1080 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x42, 0x00, 0x00, 0x00, 0x00,
1081 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1082 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
1083 ];
1084
1085 #[test]
1086 fn crss_header() {
1087 let header = Header::parse(&&CRSS_HEADER[..]).unwrap();
1088 assert!(header.dos_header.signature == DOS_MAGIC);
1089 assert!(header.signature == PE_MAGIC);
1090 assert!(header.coff_header.machine == COFF_MACHINE_X86);
1091 assert!(machine_to_str(header.coff_header.machine) == "X86");
1092 println!("header: {:?}", &header);
1093 }
1094 }