azathoth_core/os/windows/
structs.rs

1#![allow(non_snake_case, non_camel_case_types)]
2
3use core::ffi::{c_int, c_void};
4use crate::os::windows::types::USHORT;
5
6use super::types::{DWORD, LPSTR, PPS_POST_PROCESS_INIT_ROUTINE, ULONGLONG};
7
8/// Represents a 128-bit globally unique identifier (GUID).
9#[repr(C)]
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
11#[cfg_attr(feature = "std", derive(serde::Serialize, serde::Deserialize))]
12#[cfg_attr(feature = "std", serde(rename_all = "PascalCase"))]
13pub struct Guid {
14    /// First 32 bits of the GUID.
15    pub data1: u32,
16    /// Next 16 bits of the GUID.
17    pub data2: u16,
18    /// Next 16 bits of the GUID.
19    pub data3: u16,
20    /// Final 64 bits of the GUID as bytes.
21    pub data4: [u8; 8],
22}
23
24impl Guid {
25    /// Creates a new GUID from its four components.
26    pub const fn new(
27        data1: u32,
28        data2: u16,
29        data3: u16,
30        data4: [u8; 8],
31    ) -> Self {
32        Guid {
33            data1,
34            data2,
35            data3,
36            data4,
37        }
38    }
39
40    /// Converts a 128-bit integer to a GUID (big-endian order).
41    pub const fn from_u128(data: u128) -> Self {
42        let bytes = data.to_be_bytes();
43
44        Guid {
45            data1: u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]),
46            data2: u16::from_be_bytes([bytes[4], bytes[5]]),
47            data3: u16::from_be_bytes([bytes[6], bytes[7]]),
48            data4: [
49                bytes[8], bytes[9], bytes[10], bytes[11],
50                bytes[12], bytes[13], bytes[14], bytes[15],
51            ],
52        }
53    }
54}
55
56
57/// Thread Environment Block
58#[repr(C)]
59pub struct TEB {
60    Reserved1: [*mut c_void; 12],
61    /// Pointer to the Process Environment Block (PEB) of the current process.
62    ///
63    /// This field provides access to the process-wide data structure
64    /// that holds information such as loaded modules, process parameters,
65    /// and environment variables.
66    pub ProcessEnvironmentBlock: *mut PEB,
67    Reserved2: [*mut c_void; 399],
68    Reserved3: [u8; 1952],
69    TlsSlots: [*mut c_void; 64],
70    Reserved4: [u8; 8],
71    Reserved5: [*mut c_void; 26],
72    ReservedForOle: *mut c_void,
73    Reserved6: [*mut c_void; 4],
74    TlsExpansionSlots: *mut c_void,
75}
76
77/// Minimal Process Environment Block struct
78#[repr(C)]
79#[derive(Clone, Copy, Debug)]
80pub struct PEB {
81    Reserved1: [u8; 2],
82    BeingDebugged: u8,
83    Reserved2: [u8; 1],
84    Reserved3: [*mut c_void; 2],
85    /// Pointer to the loader data for this process.
86    ///
87    /// This points to a [`PEB_LDR_DATA`] structure containing a linked list
88    /// of all loaded modules for the process.
89    pub Ldr: *mut PEB_LDR_DATA,
90    /// User process parameters
91    pub ProcessParameters: *mut RTL_USER_PROCESS_PARAMETERS,
92    Reserved4: [*mut c_void; 3],
93    AtlThunkSListPtr: *mut c_void,
94    Reserved5: *mut c_void,
95    Reserved6: u32,
96    Reserved7: *mut c_void,
97    Reserved8: u32,
98    AtlThunkSListPtr32: u32,
99    Reserved9: [*mut c_void; 45],
100    Reserved10: [u8; 96],
101    PostProcessInitRoutine: PPS_POST_PROCESS_INIT_ROUTINE,
102    Reserved11: [u8; 128],
103    Reserved12: [*mut c_void; 1],
104    SessionId: u32,
105}
106
107/// User process parameters struct
108#[repr(C)]
109#[derive(Clone, Copy, Debug, PartialEq)]
110pub struct RTL_USER_PROCESS_PARAMETERS {
111    Reserved1: [u8; 16],
112    Reserved2: [*mut c_void; 10],
113    /// Unicode string containing the full path to the process's image file.
114    ///
115    /// This value represents the absolute file system path of the executable
116    /// that started the process.
117    pub ImagePathName: UNICODE_STRING,
118
119    /// Unicode string containing the command line arguments of the process.
120    ///
121    /// This value points to the full command line, excluding the executable
122    /// name in some cases, as passed to the process on creation.
123    pub CommandLine: UNICODE_STRING,
124
125    /// Pointer to the process's environment variables block.
126    ///
127    /// The environment is a sequence of null-terminated strings
128    /// (`KEY=VALUE` format) followed by an additional null terminator.
129    pub Environment: *mut u16,
130}
131impl Default for RTL_USER_PROCESS_PARAMETERS {
132    fn default() -> Self {
133        unsafe { core::mem::zeroed() }
134    }
135}
136
137/// Represents a counted, UTF-16 encoded Unicode string buffer
138#[repr(C)]
139#[derive(Clone, Copy, Debug, PartialEq)]
140pub struct UNICODE_STRING {
141    /// Length, in bytes, of the string stored in `Buffer`.
142    ///
143    /// This does **not** include the terminating null character.
144    pub Length: u16,
145
146    /// Maximum size, in bytes, allocated for `Buffer`.
147    ///
148    /// This value typically includes space for the terminating null character.
149    pub MaximumLength: u16,
150
151    /// Pointer to a wide-character string buffer (UTF-16 encoded).
152    pub Buffer: *mut u16,
153}
154
155/// Double linked list used internally by Windows to link list entries
156#[repr(C)]
157#[derive(Debug)]
158pub struct LIST_ENTRY {
159    /// Pointer to the next entry in the list (forward link).
160    pub flink: *mut LIST_ENTRY,
161    blink: *mut LIST_ENTRY,
162}
163/// Represents an entry in the process loader's module list.
164///
165/// Each loaded module (DLL or EXE) is represented by an `LDR_DATA_TABLE_ENTRY`
166/// in the loader's linked lists. This structure contains metadata about
167/// the loaded image, such as its base address, entry point, and name.
168#[repr(C)]
169#[derive(Debug)]
170pub struct LDR_DATA_TABLE_ENTRY {
171    InLoadOrderLinks: LIST_ENTRY,
172    InMemoryOrderLinks: LIST_ENTRY,
173    InInitializationOrderLinks: LIST_ENTRY,
174
175    /// Base address where the module is loaded in memory.
176    pub DllBase: *mut c_void,
177
178    /// Entry point address of the module.
179    pub EntryPoint: *mut c_void,
180
181    /// Size, in bytes, of the loaded module image.
182    pub SizeOfImage: u32,
183
184    FullDllName: UNICODE_STRING,
185
186    /// Unicode string containing the base name of the loaded module.
187    ///
188    /// This usually corresponds to the file name of the DLL or EXE
189    /// without the full path.
190    pub BaseDllName: UNICODE_STRING,
191}
192
193/// Contains information about the loaded modules for a process.
194///
195/// The `PEB_LDR_DATA` structure is referenced by the [`PEB`] and maintains
196/// multiple linked lists representing modules in their load, memory, and
197/// initialization order.
198#[repr(C)]
199#[derive(Debug)]
200pub struct PEB_LDR_DATA {
201    Length: u32,
202    Initialized: u8,
203    SsHandle: *mut c_void,
204
205    /// Head of a doubly linked list of [`LDR_DATA_TABLE_ENTRY`] structures
206    /// representing all loaded modules in their load order.
207    pub InLoadOrderModuleList: LIST_ENTRY,
208
209    InMemoryOrderModuleList: LIST_ENTRY,
210    InInitializationOrderModuleList: LIST_ENTRY,
211}
212
213/// Represents the MS-DOS header at the start of a PE (Portable Executable) file.
214///
215/// This is the first structure in a PE file, followed by a DOS stub and then the
216/// NT headers located at `e_lfanew`.
217#[repr(C)]
218#[derive(Debug, Clone, Copy)]
219pub struct IMAGE_DOS_HEADER {
220    /// Magic number identifying a DOS MZ executable ("MZ").
221    pub e_magic: u16,
222    e_cblp: u16,
223    e_cp: u16,
224    e_crlc: u16,
225    e_cparhdr: u16,
226    e_minalloc: u16,
227    e_maxalloc: u16,
228    e_ss: u16,
229    e_sp: u16,
230    e_csum: u16,
231    e_ip: u16,
232    e_cs: u16,
233    e_lfarlc: u16,
234    e_ovno: u16,
235    e_res: [u16; 4],
236    e_oemid: u16,
237    e_oeminfo: u16,
238    e_res2: [u16; 10],
239    /// Offset, in bytes, from the start of the file to the [`IMAGE_NT_HEADERS64`] structure.
240    pub e_lfanew: u32,
241}
242
243/// Represents the NT headers of a 64-bit PE image.
244///
245/// This structure contains the PE signature, file header, and optional header,
246/// describing the layout and characteristics of the executable image.
247#[repr(C)]
248#[derive(Debug, Clone, Copy)]
249pub struct IMAGE_NT_HEADERS64 {
250    /// PE file signature ("PE\0\0").
251    pub Signature: u32,
252
253    /// COFF file header containing general image characteristics.
254    pub FileHeader: IMAGE_FILE_HEADER,
255
256    /// Optional header containing additional information about the image,
257    /// including entry point, image base, and section alignment.
258    pub OptionalHeader: IMAGE_OPTIONAL_HEADER64,
259}
260
261/// Represents the COFF file header in a PE image.
262///
263/// This structure provides general information about the target machine,
264/// number of sections, symbol table, and characteristics of the executable.
265#[repr(C)]
266#[derive(Debug, Clone, Copy)]
267pub struct IMAGE_FILE_HEADER {
268    Machine: u16,
269
270    /// Number of sections in the PE image.
271    pub NumberOfSections: u16,
272
273    TimeDateStamp: u32,
274
275    /// File pointer to the COFF symbol table (deprecated in modern PE files).
276    pub PointerToSymbolTable: u32,
277
278    /// Number of symbols in the COFF symbol table (deprecated).
279    pub NumberOfSymbols: u32,
280
281    /// Size, in bytes, of the optional header following this structure.
282    pub SizeOfOptionalHeader: u16,
283
284    Characteristics: u16,
285}
286
287/// Represents the 64-bit PE Optional Header structure.
288///
289/// This structure provides essential information for loading and executing
290/// a PE image in memory, including entry point, image base, and data directories
291#[repr(C)]
292#[derive(Debug, Clone, Copy)]
293pub struct IMAGE_OPTIONAL_HEADER64 {
294    Magic: u16,
295    MajorLinkerVersion: u8,
296    MinorLinkerVersion: u8,
297    SizeOfCode: u32,
298    SizeOfInitializedData: u32,
299    SizeOfUninitializedData: u32,
300
301    /// RVA (Relative Virtual Address) of the image's entry point.
302    ///
303    /// This value represents the starting address where execution begins
304    /// relative to the image's base address.
305    pub AddressOfEntryPoint: u32,
306    BaseOfCode: u32,
307
308    /// Preferred base address of the image when loaded into memory.
309    pub ImageBase: u64,
310    SectionAlignment: u32,
311    FileAlignment: u32,
312    MajorOperatingSystemVersion: u16,
313    MinorOperatingSystemVersion: u16,
314    MajorImageVersion: u16,
315    MinorImageVersion: u16,
316    MajorSubsystemVersion: u16,
317    MinorSubsystemVersion: u16,
318    Win32VersionValue: u32,
319    /// Total size, in bytes, of the loaded image, including all headers
320    /// and sections, aligned to the specified section alignment.
321    pub SizeOfImage: u32,
322
323    /// Combined size, in bytes, of all headers in the PE file,
324    /// aligned to the specified file alignment.
325    pub SizeOfHeaders: u32,
326    CheckSum: u32,
327    Subsystem: u16,
328    DllCharacteristics: u16,
329    SizeOfStackReserve: u64,
330    SizeOfStackCommit: u64,
331    SizeOfHeapReserve: u64,
332    SizeOfHeapCommit: u64,
333    LoaderFlags: u32,
334    NumberOfRvaAndSizes: u32,
335
336    /// Array of data directory entries describing the locations
337    /// and sizes of various tables and resources within the image.
338    pub DataDirectory: [IMAGE_DATA_DIRECTORY; 16],
339}
340
341/// Represents a single data directory entry in the PE Optional Header.
342///
343/// Each entry specifies the RVA and size of a specific table or data structure
344/// (e.g., export table, import table, resource table).
345#[repr(C)]
346#[derive(Debug, Clone, Copy)]
347pub struct IMAGE_DATA_DIRECTORY {
348    /// Relative Virtual Address (RVA) of the data directory.
349    pub VirtualAddress: u32,
350
351    /// Size, in bytes, of the data directory.
352    pub Size: u32,
353}
354
355
356/// Contains information about exported functions of a PE image.
357///
358/// The `IMAGE_EXPORT_DIRECTORY` structure describes the export table,
359/// which holds function names, ordinals, and addresses available for
360/// external modules to import.
361#[repr(C)]
362#[derive(Debug, Clone, Copy)]
363pub struct IMAGE_EXPORT_DIRECTORY {
364    Characteristics: u32,
365    TimeDateStamp: u32,
366    MajorVersion: u16,
367    MinorVersion: u16,
368    Name: u32,
369    Base: u32,
370
371    /// Number of exported functions in the table.
372    pub NumberOfFunctions: u32,
373
374    /// Number of named entries in the export table.
375    pub NumberOfNames: u32,
376
377    /// RVA of the export address table, containing function entry points.
378    pub AddressOfFunctions: u32,
379
380    /// RVA of the name pointer table, containing function names.
381    pub AddressOfNames: u32,
382
383    /// RVA of the ordinal table, mapping names to function ordinals.
384    pub AddressOfNameOrdinals: u32,
385}
386
387/// Describes a single section of a PE image.
388///
389/// Each section contains code, data, or other resources loaded into memory.
390/// The `IMAGE_SECTION_HEADER` structure defines the size, location,
391/// and characteristics of each section.
392#[repr(C)]
393#[derive(Debug, Clone, Copy)]
394pub struct IMAGE_SECTION_HEADER {
395    /// ASCII name of the section (up to 8 bytes, null-padded).
396    pub Name: [u8; 8],
397
398    /// Total size of the section when loaded into memory.
399    pub VirtualSize: u32,
400
401    /// RVA of the first byte of the section when loaded.
402    pub VirtualAddress: u32,
403
404    /// Size, in bytes, of the section's data on disk.
405    pub SizeOfRawData: u32,
406
407    /// File pointer to the section's first byte of data.
408    pub PointerToRawData: u32,
409
410    PointerToRelocations: u32,
411    PointerToLinenumbers: u32,
412    NumberOfRelocations: u16,
413    NumberOfLinenumbers: u16,
414
415    /// Section flags describing memory characteristics
416    /// (e.g., executable, writable, readable).
417    pub Characteristics: u32,
418}
419
420/// Represents a single base relocation block in the PE image.
421///
422/// Each `IMAGE_BASE_RELOCATION` structure describes a block of addresses
423/// that require relocation when the image is loaded at a base address
424/// different from its preferred base.
425#[repr(C)]
426pub struct IMAGE_BASE_RELOCATION {
427    /// RVA (Relative Virtual Address) of the page where the relocations apply.
428    pub VirtualAddress: u32,
429
430    /// Total size of the relocation block, including the header and all entries.
431    pub SizeOfBlock: u32,
432}
433
434/// Describes a single import descriptor entry in the PE import table.
435///
436/// Each `IMAGE_IMPORT_DESCRIPTOR` structure provides information about
437/// an imported DLL and the functions or data imported from it.
438#[repr(C)]
439#[derive(Clone, Copy)]
440pub struct IMAGE_IMPORT_DESCRIPTOR {
441    /// Anonymous union containing the `OriginalFirstThunk` value.
442    pub Anonymous: IMAGE_IMPORT_DESCRIPTOR_0,
443
444    TimeDateStamp: u32,
445    ForwarderChain: u32,
446
447    /// RVA of the null-terminated ASCII string containing the name of the DLL.
448    pub Name: u32,
449
450    /// RVA of the Import Address Table (IAT) that holds
451    /// the resolved function pointers for this DLL.
452    pub FirstThunk: u32,
453}
454
455/// Anonymous union within `IMAGE_IMPORT_DESCRIPTOR`.
456///
457/// Holds either the `OriginalFirstThunk` value or other characteristics.
458#[repr(C)]
459#[derive(Clone, Copy)]
460pub union IMAGE_IMPORT_DESCRIPTOR_0 {
461    Characteristics: u32,
462
463    /// RVA of the Import Name Table (INT) containing
464    /// pointers to `IMAGE_IMPORT_BY_NAME` structures.
465    pub OriginalFirstThunk: u32,
466}
467
468/// Represents a single thunk entry in the import table for 64-bit images.
469///
470/// Each thunk entry can store an ordinal, a pointer to a hint/name structure,
471/// or a resolved function address.
472#[repr(C)]
473pub struct IMAGE_THUNK_DATA64 {
474    /// Anonymous union containing different possible thunk data representations.
475    pub u1: IMAGE_THUNK_DATA64_0,
476}
477
478/// Union representing different types of data that can be stored
479/// in an import thunk entry.
480#[repr(C)]
481pub union IMAGE_THUNK_DATA64_0 {
482    ForwarderString: u64,
483
484    /// Address of the imported function once resolved by the loader.
485    pub Function: u64,
486
487    /// Ordinal value of the imported function (if imported by ordinal).
488    pub Ordinal: u64,
489
490    /// RVA of an `IMAGE_IMPORT_BY_NAME` structure describing the imported symbol.
491    pub AddressOfData: u64,
492}
493
494/// Represents an import-by-name entry in the import table.
495///
496/// Each `IMAGE_IMPORT_BY_NAME` structure contains a hint and a symbol name
497/// for a function or variable imported by name from a DLL.
498#[repr(C)]
499pub struct IMAGE_IMPORT_BY_NAME {
500    Hint: u16,
501
502    /// Null-terminated ASCII string containing the name of the imported function or symbol.
503    pub Name: [i8; 1],
504}
505
506/// Represents the Thread Local Storage (TLS) directory for 64-bit images.
507///
508/// The `IMAGE_TLS_DIRECTORY64` structure defines the TLS template and callback information
509/// that the Windows loader uses to initialize TLS data for threads in a PE image.
510#[repr(C)]
511pub struct IMAGE_TLS_DIRECTORY64 {
512    /// Starting virtual address of the TLS template raw data.
513    pub StartAddressOfRawData: ULONGLONG,
514
515    /// Ending virtual address of the TLS template raw data.
516    pub EndAddressOfRawData: ULONGLONG,
517
518    /// Virtual address of the index variable used by the TLS runtime to access thread data.
519    pub AddressOfIndex: ULONGLONG,
520
521    /// Virtual address of an array of TLS callback functions executed by the loader
522    /// during process and thread initialization or termination.
523    pub AddressOfCallbacks: ULONGLONG,
524
525    /// Size of the zero-initialized TLS memory section, in bytes.
526    pub SizeOfZeroFill: DWORD,
527
528    Reserved0: DWORD,
529    Alignment: DWORD,
530    Reserved1: DWORD,
531}
532
533/// Describes the components of a parsed URL string.
534///
535/// The `URL_COMPONENTSA` structure is used with the Windows API function
536/// `InternetCrackUrlA` to retrieve individual parts of a URL.
537#[repr(C)]
538#[derive(Debug)]
539pub struct URL_COMPONENTSA {
540    /// Size of this structure, in bytes.
541    pub dwStructSize: DWORD,
542
543    /// Pointer to a buffer that receives the URL scheme (e.g., "http").
544    pub lpszScheme: LPSTR,
545
546    /// Length of the scheme string, in characters.
547    pub dwSchemeLength: DWORD,
548
549    /// Scheme type value as determined by the API.
550    pub nScheme: c_int,
551
552    /// Pointer to a buffer that receives the host name (e.g., "example.com").
553    pub lpszHostName: LPSTR,
554
555    /// Length of the host name string, in characters.
556    pub dwHostNameLength: DWORD,
557
558    /// Port number extracted from the URL.
559    pub nPort: USHORT,
560
561    /// Pointer to a buffer that receives the username, if present in the URL.
562    pub lpszUserName: LPSTR,
563
564    /// Length of the username string, in characters.
565    pub dwUserNameLength: DWORD,
566
567    /// Pointer to a buffer that receives the password, if present in the URL.
568    pub lpszPassword: LPSTR,
569
570    /// Length of the password string, in characters.
571    pub dwPasswordLength: DWORD,
572
573    /// Pointer to a buffer that receives the URL path (e.g., "/index.html").
574    pub lpszUrlPath: LPSTR,
575
576    /// Length of the URL path string, in characters.
577    pub dwUrlPathLength: DWORD,
578
579    /// Pointer to a buffer that receives any extra information or query parameters (e.g., "?id=1").
580    pub lpszExtraInfo: LPSTR,
581
582    /// Length of the extra info string, in characters.
583    pub dwExtraInfoLength: DWORD,
584}
585
586/// Represents an entry in the function table on 64-bit Windows.
587#[repr(C)]
588#[derive(Debug)]
589pub struct RUNTIME_FUNCTION {
590    /// The address of the start of the function.
591    pub BeginAddress: DWORD,
592    /// The address of the end of the function.
593    pub EndAddress: DWORD,
594    /// The address of the unwind information for the function.
595    pub UnwindData: DWORD,
596}