uwd 0.3.5

Call Stack Spoofing for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
use alloc::{string::String, vec::Vec};
use core::ffi::c_void;

use anyhow::{Context, Result, bail};
use obfstr::obfstring as s;
use dinvk::module::{get_module_address, get_proc_address};
use dinvk::types::IMAGE_RUNTIME_FUNCTION;
use dinvk::hash::murmur3;
use dinvk::helper::PE;

#[cfg(feature = "desync")]
use crate::util::find_base_thread_return_address;
use crate::util::{find_gadget, shuffle, find_valid_instruction_offset};
use crate::types::{Config, Registers, UNWIND_OP_CODES::{self, *}};
use crate::types::{UNW_FLAG_CHAININFO, UNW_FLAG_EHANDLER};
use crate::types::{UNWIND_CODE, UNWIND_INFO};
use crate::types::Unwind;

#[cfg(feature = "desync")]
unsafe extern "C" {
    /// Function responsible for Call Stack Spoofing (Desync)
    fn Spoof(config: &mut Config) -> *mut c_void;
}

#[cfg(not(feature = "desync"))]
unsafe extern "C" {
    /// Function responsible for Call Stack Spoofing (Synthetic)
    fn SpoofSynthetic(config: &mut Config) -> *mut c_void;
}

/// Invokes a function using a synthetic spoofed call stack.
///
/// # Examples
///
/// ```
/// use core::ptr;
/// use dinvk::module::{get_module_address, get_proc_address};
/// use uwd::spoof;
///
/// let kernel32 = get_module_address("kernel32.dll", None);
/// let virtual_alloc = get_proc_address(kernel32, "VirtualAlloc", None);
///
/// let addr = spoof!(
///     virtual_alloc,
///     ptr::null_mut::<core::ffi::c_void>(),
///     1 << 12,
///     0x3000,
///     0x04
/// ).unwrap();
///
/// assert!(!addr.is_null());
/// ```
#[macro_export]
macro_rules! spoof {
    ($addr:expr, $($arg:expr),+ $(,)?) => {
        unsafe {
            $crate::__private::spoof(
                $addr,
                &[$(::core::mem::transmute($arg as usize)),*],
                $crate::SpoofKind::Function,
            )
        }
    };
}

/// Invokes a Windows native syscall using a spoofed stack.
///
/// # Examples
/// 
/// ```
/// use core::ptr;
/// use uwd::{AsPointer, syscall};
///
/// let mut addr = ptr::null_mut::<core::ffi::c_void>();
/// let mut size = (1 << 12) as usize;
///
/// let status = syscall!(
///     "NtAllocateVirtualMemory",
///     -1isize,
///     addr.as_ptr_mut(),
///     0,
///     size.as_ptr_mut(),
///     0x3000,
///     0x04
/// ).unwrap() as i32;
///
/// assert_eq!(status, 0);
/// ```
#[macro_export]
macro_rules! syscall {
    ($name:expr, $($arg:expr),* $(,)?) => {
        unsafe {
            $crate::__private::spoof(
                core::ptr::null_mut(),
                &[$(::core::mem::transmute($arg as usize)),*],
                $crate::SpoofKind::Syscall($name),
            )
        }
    };
}

#[doc(hidden)]
pub mod __private {
    use core::ffi::c_void;
    use super::*;

    /// Performs call stack spoofing in `synthetic` mode.
    #[cfg(not(feature = "desync"))]
    pub fn spoof(addr: *mut c_void, args: &[*const c_void], kind: SpoofKind) -> Result<*mut c_void> {
        // Max 11 args
        if args.len() > 11 {
            bail!(s!("too many arguments"));
        }

        // Function pointer must be valid unless syscall spoof
        if let SpoofKind::Function = kind && addr.is_null() {
            bail!(s!("null function address"));
        }

        let mut config = Config::default();

        // Resolve kernelbase
        let kernelbase = get_module_address(2737729883u32, Some(murmur3));

        // Parse unwind table
        let pe_kernelbase = Unwind::new(PE::parse(kernelbase));
        let tables = pe_kernelbase
            .entries()
            .context(s!(
                "failed to read IMAGE_RUNTIME_FUNCTION entries from .pdata section"
            ))?;

        // Resolve APIs
        let ntdll = get_module_address(2788516083u32, Some(murmur3));
        if ntdll.is_null() {
            bail!(s!("ntdll.dll not found"));
        }

        let kernel32 = get_module_address(2808682670u32, Some(murmur3));
        let rlt_user_addr = get_proc_address(ntdll, 1578834099u32, Some(murmur3));
        let base_thread_addr = get_proc_address(kernel32, 4083630997u32, Some(murmur3));

        config.rtl_user_addr = rlt_user_addr;
        config.base_thread_addr = base_thread_addr;

        // Unwind lookup
        let pe_ntdll = Unwind::new(PE::parse(ntdll));
        let rtl_user_runtime = pe_ntdll
            .function_by_offset(rlt_user_addr as u32 - ntdll as u32)
            .context(s!("RtlUserThreadStart unwind info not found"))?;

        let pe_kernel32 = Unwind::new(PE::parse(kernel32));
        let base_thread_runtime = pe_kernel32
            .function_by_offset(base_thread_addr as u32 - kernel32 as u32)
            .context(s!("BaseThreadInitThunk unwind info not found"))?;

        // Stack sizes
        let rtl_user_size = ignoring_set_fpreg(ntdll, rtl_user_runtime)
            .context(s!("RtlUserThreadStart stack size not found"))?;
        
        let base_thread_size = ignoring_set_fpreg(kernel32, base_thread_runtime)
            .context(s!("BaseThreadInitThunk stack size not found"))?;

        config.rtl_user_thread_size = rtl_user_size as u64;
        config.base_thread_size = base_thread_size as u64;

        // First prologue
        let first_prolog = Prolog::find_prolog(kernelbase, tables)
            .context(s!("first prolog not found"))?;
        
        config.first_frame_fp = (first_prolog.frame + first_prolog.offset as u64) as *const c_void;
        config.first_frame_size = first_prolog.stack_size as u64;

        // Second prologue
        let second_prolog = Prolog::find_push_rbp(kernelbase, tables)
            .context(s!("second prolog not found"))?;
        
        config.second_frame_fp = (second_prolog.frame + second_prolog.offset as u64) as *const c_void;
        config.second_frame_size = second_prolog.stack_size as u64;
        config.rbp_stack_offset = second_prolog.rbp_offset as u64;

        // Gadget: `add rsp, 0x58; ret`
        let (add_rsp_addr, size) = find_gadget(kernelbase, &[0x48, 0x83, 0xC4, 0x58, 0xC3], tables)
            .context(s!("add rsp gadget not found"))?;
        
        config.add_rsp_gadget = add_rsp_addr as *const c_void;
        config.add_rsp_frame_size = size as u64;

        // Gadget: `jmp rbx`
        let (jmp_rbx_addr, size) = find_gadget(kernelbase, &[0xFF, 0x23], tables)
            .context(s!("jmp rbx gadget not found"))?;
        
        config.jmp_rbx_gadget = jmp_rbx_addr as *const c_void;
        config.jmp_rbx_frame_size = size as u64;

        // Prepare arguments
        let len = args.len();
        config.number_args = len as u32;
        
        for (i, &arg) in args.iter().take(len).enumerate() {
            match i {
                0 => config.arg01 = arg,
                1 => config.arg02 = arg,
                2 => config.arg03 = arg,
                3 => config.arg04 = arg,
                4 => config.arg05 = arg,
                5 => config.arg06 = arg,
                6 => config.arg07 = arg,
                7 => config.arg08 = arg,
                8 => config.arg09 = arg,
                9 => config.arg10 = arg,
                10 => config.arg11 = arg,
                _ => break,
            }
        }

        // Handle syscall spoofing
        match kind {
            SpoofKind::Function => config.spoof_function = addr,
            SpoofKind::Syscall(name) => {
                let addr = get_proc_address(ntdll, name, None);
                if addr.is_null() {
                    bail!(s!("get_proc_address returned null"));
                }

                config.is_syscall = true as u32;
                config.ssn = dinvk::ssn(name, ntdll).context(s!("ssn not found"))?;
                config.spoof_function = dinvk::get_syscall_address(addr)
                    .context(s!("syscall address not found"))? as *const c_void;
            }
        }

        Ok(unsafe { SpoofSynthetic(&mut config) })
    }

    /// Performs call stack spoofing in `desync` mode.
    #[cfg(feature = "desync")]
    pub fn spoof(addr: *mut c_void, args: &[*const c_void], kind: SpoofKind) -> Result<*mut c_void> {
        // Max 11 args
        if args.len() > 11 {
            bail!(s!("too many arguments"));
        }

        // Function pointer must be valid unless syscall spoof
        if let SpoofKind::Function = kind && addr.is_null() {
            bail!(s!("null function address"));
        }

        let mut config = Config::default();

        // Resolve kernelbase
        let kernelbase = get_module_address(2737729883u32, Some(murmur3));

        // Parse unwind table
        let pe = Unwind::new(PE::parse(kernelbase));
        let tables = pe
            .entries()
            .context(s!(
                "failed to read IMAGE_RUNTIME_FUNCTION entries from .pdata section"
            ))?;

        // Locate a return address from BaseThreadInitThunk on the current stack
        config.return_address = find_base_thread_return_address()
            .context(s!("return address not found"))? as *const c_void;

        // First prologue
        let first_prolog = Prolog::find_prolog(kernelbase, tables)
            .context(s!("first prolog not found"))?;
        
        config.first_frame_fp = (first_prolog.frame + first_prolog.offset as u64) as *const c_void;
        config.first_frame_size = first_prolog.stack_size as u64;

        // Second prologue
        let second_prolog = Prolog::find_push_rbp(kernelbase, tables)
            .context(s!("second prolog not found"))?;
        
        config.second_frame_fp = (second_prolog.frame + second_prolog.offset as u64) as *const c_void;
        config.second_frame_size = second_prolog.stack_size as u64;
        config.rbp_stack_offset = second_prolog.rbp_offset as u64;

        // Gadget: `add rsp, 0x58; ret`
        let (add_rsp_addr, size) = find_gadget(kernelbase, &[0x48, 0x83, 0xC4, 0x58, 0xC3], tables)
            .context(s!("add rsp gadget not found"))?;

        config.add_rsp_gadget = add_rsp_addr as *const c_void;
        config.add_rsp_frame_size = size as u64;

        // Gadget: `jmp rbx`
        let (jmp_rbx_addr, size) = find_gadget(kernelbase, &[0xFF, 0x23], tables)
            .context(s!("jmp rbx gadget not found"))?;

        config.jmp_rbx_gadget = jmp_rbx_addr as *const c_void;
        config.jmp_rbx_frame_size = size as u64;

        // Prepare arguments
        let len = args.len();
        config.number_args = len as u32;
        
        for (i, &arg) in args.iter().take(len).enumerate() {
            match i {
                0 => config.arg01 = arg,
                1 => config.arg02 = arg,
                2 => config.arg03 = arg,
                3 => config.arg04 = arg,
                4 => config.arg05 = arg,
                5 => config.arg06 = arg,
                6 => config.arg07 = arg,
                7 => config.arg08 = arg,
                8 => config.arg09 = arg,
                9 => config.arg10 = arg,
                10 => config.arg11 = arg,
                _ => break,
            }
        }

        // Handle syscall spoofing
        match kind {
            SpoofKind::Function => config.spoof_function = addr,
            SpoofKind::Syscall(name) => {
                let ntdll = get_module_address(2788516083u32, Some(murmur3));
                if ntdll.is_null() {
                    bail!(s!("ntdll.dll not found"));
                }

                let addr = get_proc_address(ntdll, name, None);
                if addr.is_null() {
                    bail!(s!("get_proc_address returned null"));
                }

                config.is_syscall = true as u32;
                config.ssn = dinvk::ssn(name, ntdll).context(s!("ssn not found"))?;
                config.spoof_function = dinvk::get_syscall_address(addr)
                    .context(s!("syscall address not found"))? as *const c_void;
            }
        }

        Ok(unsafe { Spoof(&mut config) })
    }
}

/// Metadata extracted from a function prologue that is suitable for spoofing.
#[derive(Copy, Clone, Default)]
struct Prolog {
    /// Address of the selected function frame.
    frame: u64,

    /// Total stack space reserved by the function.
    stack_size: u32,

    /// Offset inside the function where a valid instruction pattern was found.
    offset: u32,

    /// Offset in the stack where `rbp` is pushed or saved.
    rbp_offset: u32,
}

impl Prolog {
    /// Finds the first prologue in the unwind table that looks safe for spoofing.
    ///
    /// This scans the RUNTIME_FUNCTION entries for a function that:
    /// - Allocates a stack frame.
    /// - Has a predictable prologue layout.
    fn find_prolog(module_base: *mut c_void, runtime_table: &[IMAGE_RUNTIME_FUNCTION]) -> Option<Self> {
        let mut prologs = runtime_table
            .iter()
            .filter_map(|runtime| {
                let (is_valid, stack_size) = stack_frame(module_base, runtime)?;
                if !is_valid {
                    return None;
                }

                let offset = find_valid_instruction_offset(module_base, runtime)?;
                let frame = module_base as u64 + runtime.BeginAddress as u64;
                Some(Self {
                    frame,
                    stack_size,
                    offset,
                    ..Default::default()
                })
            })
            .collect::<Vec<Self>>();

        if prologs.is_empty() {
            return None;
        }

        // Shuffle to reduce pattern predictability.
        shuffle(&mut prologs);

        prologs.first().copied()
    }

    /// Finds a prologue that uses `push rbp` and an RBP-based frame.
    ///
    /// This is useful when spoofing techniques rely on classic frame-pointer
    /// based layouts rather than purely RSP-based stack frames.
    fn find_push_rbp(module_base: *mut c_void, runtime_table: &[IMAGE_RUNTIME_FUNCTION]) -> Option<Self> {
        let mut prologs = runtime_table
            .iter()
            .filter_map(|runtime| {
                let (rbp_offset, stack_size) = rbp_offset(module_base, runtime)?;
                if rbp_offset == 0 || stack_size == 0 || stack_size <= rbp_offset {
                    return None;
                }

                let offset = find_valid_instruction_offset(module_base, runtime)?;
                let frame = module_base as u64 + runtime.BeginAddress as u64;
                Some(
                    Self {
                        frame,
                        stack_size,
                        offset,
                        rbp_offset,
                    }
                )
            })
            .collect::<Vec<Self>>();

        if prologs.is_empty() {
            return None;
        }

        // The first frame is often not suitable on many Windows versions.
        prologs.remove(0);

        // Shuffle to reduce pattern predictability.
        shuffle(&mut prologs);

        prologs.first().copied()
    }
}

/// Determines whether RBP is pushed or saved in a spoof-compatible manner and
/// computes the total stack size for a function.
///
/// This inspects the unwind codes associated with the `IMAGE_RUNTIME_FUNCTION`
/// entry to determine if the function frame uses a layout suitable for
/// call stack spoofing.
pub fn rbp_offset(module: *mut c_void, runtime: &IMAGE_RUNTIME_FUNCTION) -> Option<(u32, u32)> {
    unsafe {
        let unwind_info = (module as usize + runtime.UnwindData as usize) as *mut UNWIND_INFO;
        let unwind_code = (unwind_info as *mut u8).add(4) as *mut UNWIND_CODE;
        let flag = (*unwind_info).VersionFlags.Flags();

        let mut i = 0usize;
        let mut total_stack = 0u32;
        let mut rbp_pushed = false;
        let mut stack_offset = 0;

        while i < (*unwind_info).CountOfCodes as usize {
            // Accessing `UNWIND_CODE` based on the index
            let unwind_code = unwind_code.add(i);

            // Information used in operation codes
            let op_info = (*unwind_code).Anonymous.OpInfo() as usize;
            let unwind_op = (*unwind_code).Anonymous.UnwindOp();

            match UNWIND_OP_CODES::try_from(unwind_op) {
                // Saves a non-volatile register on the stack.
                //
                // Example: push <reg>
                Ok(UWOP_PUSH_NONVOL) => {
                    if Registers::Rsp == op_info {
                        return None;
                    }

                    if Registers::Rbp == op_info {
                        if rbp_pushed {
                            return None;
                        }

                        rbp_pushed = true;
                        stack_offset = total_stack;
                    }

                    total_stack += 8;
                    i += 1;
                }

                // Allocates large space on the stack.
                // - OpInfo == 0: The next slot contains the /8 size of the allocation (maximum 512 KB - 8).
                // - OpInfo == 1: The next two slots contain the full size of the allocation (up to 4 GB - 8).
                //
                // Example (OpInfo == 0): sub rsp, 0x100 ; Allocates 256 bytes
                // Example (OpInfo == 1): sub rsp, 0x10000 ; Allocates 65536 bytes (two slots used)
                Ok(UWOP_ALLOC_LARGE) => {
                    if (*unwind_code).Anonymous.OpInfo() == 0 {
                        // Case 1: OpInfo == 0 (Size in 1 slot, divided by 8)
                        // Multiplies by 8 to the actual value

                        let frame_offset = ((*unwind_code.add(1)).FrameOffset as i32) * 8;
                        total_stack += frame_offset as u32;

                        // Consumes 2 slots (1 for the instruction, 1 for the size divided by 8)
                        i += 2
                    } else {
                        // Case 2: OpInfo == 1 (Size in 2 slots, 32 bits)
                        let frame_offset = *(unwind_code.add(1) as *mut i32);
                        total_stack += frame_offset as u32;

                        // Consumes 3 slots (1 for the instruction, 2 for the full size)
                        i += 3
                    }
                }

                // Allocates small space in the stack.
                //
                // Example (OpInfo = 3): sub rsp, 0x20  ; Aloca 32 bytes (OpInfo + 1) * 8
                Ok(UWOP_ALLOC_SMALL) => {
                    total_stack += ((op_info + 1) * 8) as u32;
                    i += 1;
                }

                // UWOP_SAVE_NONVOL: Saves the contents of a non-volatile register in a specific position on the stack.
                // - Reg: Name of the saved register.
                // - FrameOffset: Offset indicating where the value of the register is saved.
                //
                // Example: mov [rsp + 0x40], rsi ; Saves the contents of RSI in RSP + 0x40
                Ok(UWOP_SAVE_NONVOL) => {
                    if Registers::Rsp == op_info {
                        return None;
                    }

                    if Registers::Rbp == op_info {
                        if rbp_pushed {
                            return None;
                        }

                        let offset = (*unwind_code.add(1)).FrameOffset * 8;
                        stack_offset = total_stack + offset as u32;
                        rbp_pushed = true;
                    }

                    i += 2;
                }

                // Saves a non-volatile register to a stack address with a long offset.
                // - Reg: Name of the saved register.
                // - FrameOffset: Long offset indicating where the value of the register is saved.
                //
                // Example: mov [rsp + 0x1040], rsi ; Saves the contents of RSI in RSP + 0x1040.
                Ok(UWOP_SAVE_NONVOL_BIG) => {
                    if Registers::Rsp == op_info {
                        return None;
                    }

                    if Registers::Rbp == op_info {
                        if rbp_pushed {
                            return None;
                        }

                        let offset = *(unwind_code.add(1) as *mut u32);
                        stack_offset = total_stack + offset;
                        rbp_pushed = true;
                    }

                    i += 3;
                }

                // Return
                Ok(UWOP_SET_FPREG) => return None,

                // - Reg: Name of the saved XMM register.
                // - FrameOffset: Offset indicating where the value of the register is saved.
                Ok(UWOP_SAVE_XMM128) => i += 2,

                // UWOP_SAVE_XMM128BIG: Saves the contents of a non-volatile XMM register to a stack address with a long offset.
                // - Reg: Name of the saved XMM register.
                // - FrameOffset: Long offset indicating where the value of the register is saved.
                //
                // Example: movaps [rsp + 0x1040], xmm6 ; Saves the contents of XMM6 in RSP + 0x1040.
                Ok(UWOP_SAVE_XMM128BIG) => i += 3,

                // Reserved code, not currently used.
                Ok(UWOP_EPILOG) | Ok(UWOP_SPARE_CODE) => i += 1,

                // Push a machine frame. This unwind code is used to record the effect of a hardware interrupt or exception.
                Ok(UWOP_PUSH_MACH_FRAME) => {
                    total_stack += if op_info == 0 { 0x40 } else { 0x48 };
                    i += 1
                }

                _ => {}
            }
        }

        // If there is a chain unwind structure, it too must be processed
        // recursively and included in the stack size calculation.
        if (flag & UNW_FLAG_CHAININFO) != 0 {
            let count = (*unwind_info).CountOfCodes as usize;
            let index = if count & 1 == 1 { count + 1 } else { count };
            let runtime = unwind_code.add(index) as *const IMAGE_RUNTIME_FUNCTION;
            if let Some((_, child_total)) = rbp_offset(module, &*runtime) {
                total_stack += child_total;
            } else {
                return None;
            }
        }

        Some((stack_offset, total_stack))
    }
}

/// Computes stack frame metadata while rejecting `setfp` frames.
///
/// Used when locating suitable prologues for spoofed call frames.
pub fn stack_frame(module: *mut c_void, runtime: &IMAGE_RUNTIME_FUNCTION) -> Option<(bool, u32)> {
    unsafe {
        let unwind_info = (module as usize + runtime.UnwindData as usize) as *mut UNWIND_INFO;
        let unwind_code = (unwind_info as *mut u8).add(4) as *mut UNWIND_CODE;
        let flag = (*unwind_info).VersionFlags.Flags();

        let mut i = 0usize;
        let mut set_fpreg_hit = false;
        let mut total_stack = 0i32;
        while i < (*unwind_info).CountOfCodes as usize {
            // Accessing `UNWIND_CODE` based on the index
            let unwind_code = unwind_code.add(i);

            // Information used in operation codes
            let op_info = (*unwind_code).Anonymous.OpInfo() as usize;
            let unwind_op = (*unwind_code).Anonymous.UnwindOp();

            match UNWIND_OP_CODES::try_from(unwind_op) {
                // Saves a non-volatile register on the stack.
                //
                // Example: push <reg>
                Ok(UWOP_PUSH_NONVOL) => {
                    if Registers::Rsp == op_info && !set_fpreg_hit {
                        return None;
                    }

                    total_stack += 8;
                    i += 1;
                }

                // Allocates small space in the stack.
                //
                // Example (OpInfo = 3): sub rsp, 0x20  ; Aloca 32 bytes (OpInfo + 1) * 8
                Ok(UWOP_ALLOC_SMALL) => {
                    total_stack += ((op_info + 1) * 8) as i32;
                    i += 1;
                }

                // Allocates large space on the stack.
                // - OpInfo == 0: The next slot contains the /8 size of the allocation (maximum 512 KB - 8).
                // - OpInfo == 1: The next two slots contain the full size of the allocation (up to 4 GB - 8).
                //
                // Example (OpInfo == 0): sub rsp, 0x100 ; Allocates 256 bytes
                // Example (OpInfo == 1): sub rsp, 0x10000 ; Allocates 65536 bytes (two slots used)
                Ok(UWOP_ALLOC_LARGE) => {
                    if (*unwind_code).Anonymous.OpInfo() == 0 {
                        // Case 1: OpInfo == 0 (Size in 1 slot, divided by 8)
                        // Multiplies by 8 to the actual value

                        let frame_offset = ((*unwind_code.add(1)).FrameOffset as i32) * 8;
                        total_stack += frame_offset;

                        // Consumes 2 slots (1 for the instruction, 1 for the size divided by 8)
                        i += 2
                    } else {
                        // Case 2: OpInfo == 1 (Size in 2 slots, 32 bits)
                        let frame_offset = *(unwind_code.add(1) as *mut i32);
                        total_stack += frame_offset;

                        // Consumes 3 slots (1 for the instruction, 2 for the full size)
                        i += 3
                    }
                }

                // UWOP_SAVE_NONVOL: Saves the contents of a non-volatile register in a specific position on the stack.
                // - Reg: Name of the saved register.
                // - FrameOffset: Offset indicating where the value of the register is saved.
                //
                // Example: mov [rsp + 0x40], rsi ; Saves the contents of RSI in RSP + 0x40
                Ok(UWOP_SAVE_NONVOL) => {
                    if Registers::Rsp == op_info || Registers::Rbp == op_info {
                        return None;
                    }

                    i += 2;
                }

                // Saves a non-volatile register to a stack address with a long offset.
                // - Reg: Name of the saved register.
                // - FrameOffset: Long offset indicating where the value of the register is saved.
                //
                // Example: mov [rsp + 0x1040], rsi ; Saves the contents of RSI in RSP + 0x1040.
                Ok(UWOP_SAVE_NONVOL_BIG) => {
                    if Registers::Rsp == op_info || Registers::Rbp == op_info {
                        return None;
                    }

                    i += 3;
                }

                // Saves the contents of a non-volatile XMM register on the stack.
                // - Reg: Name of the saved XMM register.
                // - FrameOffset: Offset indicating where the value of the register is saved.
                //
                // Example: movaps [rsp + 0x20], xmm6 ; Saves the contents of XMM6 in RSP + 0x20.
                Ok(UWOP_SAVE_XMM128) => i += 2,

                // UWOP_SAVE_XMM128BIG: Saves the contents of a non-volatile XMM register to a stack address with a long offset.
                // - Reg: Name of the saved XMM register.
                // - FrameOffset: Long offset indicating where the value of the register is saved.
                //
                // Example: movaps [rsp + 0x1040], xmm6 ; Saves the contents of XMM6 in RSP + 0x1040.
                Ok(UWOP_SAVE_XMM128BIG) => i += 3,

                // UWOP_SET_FPREG: Marks use of register as stack base (e.g. RBP).
                // Ignore if not RBP, has EH handler or chained unwind.
                // Subtract `FrameOffset << 4` from the stack total.
                Ok(UWOP_SET_FPREG) => {
                    if (flag & UNW_FLAG_EHANDLER) != 0 && (flag & UNW_FLAG_CHAININFO) != 0 {
                        return None;
                    }

                    if (*unwind_info).FrameInfo.FrameRegister() != Registers::Rbp as u8 {
                        return None;
                    }

                    set_fpreg_hit = true;
                    let offset = ((*unwind_info).FrameInfo.FrameOffset() as i32) << 4;
                    total_stack -= offset;
                    i += 1
                }

                // Reserved code, not currently used.
                Ok(UWOP_EPILOG) | Ok(UWOP_SPARE_CODE) => i += 1,

                // Push a machine frame. This unwind code is used to record the effect of a hardware interrupt or exception.
                Ok(UWOP_PUSH_MACH_FRAME) => {
                    total_stack += if op_info == 0 { 0x40 } else { 0x48 };
                    i += 1
                }
                _ => {}
            }
        }

        // If there is a chain unwind structure, it too must be processed
        // recursively and included in the stack size calculation.
        if (flag & UNW_FLAG_CHAININFO) != 0 {
            let count = (*unwind_info).CountOfCodes as usize;
            let index = if count & 1 == 1 { count + 1 } else { count };
            let runtime = unwind_code.add(index) as *const IMAGE_RUNTIME_FUNCTION;
            if let Some((chained_fpreg_hit, chained_stack)) = stack_frame(module, &*runtime) {
                total_stack += chained_stack as i32;
                set_fpreg_hit |= chained_fpreg_hit;
            } else {
                return None;
            }
        }

        Some((set_fpreg_hit, total_stack as u32))
    }
}

/// Computes the total stack frame size of a function while ignoring any `setfp` frames. 
/// Useful for identifying spoof-compatible RUNTIME_FUNCTION entries.
pub fn ignoring_set_fpreg(module: *mut c_void, runtime: &IMAGE_RUNTIME_FUNCTION) -> Option<u32> {
    unsafe {
        let unwind_info = (module as usize + runtime.UnwindData as usize) as *mut UNWIND_INFO;
        let unwind_code = (unwind_info as *mut u8).add(4) as *mut UNWIND_CODE;
        let flag = (*unwind_info).VersionFlags.Flags();

        let mut i = 0usize;
        let mut total_stack = 0u32;
        while i < (*unwind_info).CountOfCodes as usize {
            // Accessing `UNWIND_CODE` based on the index
            let unwind_code = unwind_code.add(i);

            // Information used in operation codes
            let op_info = (*unwind_code).Anonymous.OpInfo() as usize;
            let unwind_op = (*unwind_code).Anonymous.UnwindOp();

            match UNWIND_OP_CODES::try_from(unwind_op) {
                // Saves a non-volatile register on the stack.
                //
                // Example: push <reg>
                Ok(UWOP_PUSH_NONVOL) => {
                    if Registers::Rsp == op_info {
                        return None;
                    }

                    total_stack += 8;
                    i += 1;
                }

                // Allocates small space in the stack.
                //
                // Example (OpInfo = 3): sub rsp, 0x20  ; Aloca 32 bytes (OpInfo + 1) * 8
                Ok(UWOP_ALLOC_SMALL) => {
                    total_stack += ((op_info + 1) * 8) as u32;
                    i += 1;
                }

                // Allocates large space on the stack.
                // - OpInfo == 0: The next slot contains the /8 size of the allocation (maximum 512 KB - 8).
                // - OpInfo == 1: The next two slots contain the full size of the allocation (up to 4 GB - 8).
                //
                // Example (OpInfo == 0): sub rsp, 0x100 ; Allocates 256 bytes
                // Example (OpInfo == 1): sub rsp, 0x10000 ; Allocates 65536 bytes (two slots used)
                Ok(UWOP_ALLOC_LARGE) => {
                    if (*unwind_code).Anonymous.OpInfo() == 0 {
                        // Case 1: OpInfo == 0 (Size in 1 slot, divided by 8)
                        // Multiplies by 8 to the actual value

                        let frame_offset = ((*unwind_code.add(1)).FrameOffset as i32) * 8;
                        total_stack += frame_offset as u32;

                        // Consumes 2 slots (1 for the instruction, 1 for the size divided by 8)
                        i += 2
                    } else {
                        // Case 2: OpInfo == 1 (Size in 2 slots, 32 bits)
                        let frame_offset = *(unwind_code.add(1) as *mut i32);
                        total_stack += frame_offset as u32;

                        // Consumes 3 slots (1 for the instruction, 2 for the full size)
                        i += 3
                    }
                }

                // UWOP_SAVE_NONVOL: Saves the contents of a non-volatile register in a specific position on the stack.
                // - Reg: Name of the saved register.
                // - FrameOffset: Offset indicating where the value of the register is saved.
                //
                // Example: mov [rsp + 0x40], rsi ; Saves the contents of RSI in RSP + 0x40
                Ok(UWOP_SAVE_NONVOL) => {
                    if Registers::Rsp == op_info {
                        return None;
                    }

                    i += 2;
                }

                // Saves a non-volatile register to a stack address with a long offset.
                // - Reg: Name of the saved register.
                // - FrameOffset: Long offset indicating where the value of the register is saved.
                //
                // Example: mov [rsp + 0x1040], rsi ; Saves the contents of RSI in RSP + 0x1040.
                Ok(UWOP_SAVE_NONVOL_BIG) => {
                    if Registers::Rsp == op_info {
                        return None;
                    }

                    i += 3;
                }

                // Saves the contents of a non-volatile XMM register on the stack.
                // - Reg: Name of the saved XMM register.
                // - FrameOffset: Offset indicating where the value of the register is saved.
                //
                // Example: movaps [rsp + 0x20], xmm6 ; Saves the contents of XMM6 in RSP + 0x20.
                Ok(UWOP_SAVE_XMM128) => i += 2,

                // UWOP_SAVE_XMM128BIG: Saves the contents of a non-volatile XMM register to a stack address with a long offset.
                // - Reg: Name of the saved XMM register.
                // - FrameOffset: Long offset indicating where the value of the register is saved.
                //
                // Example: movaps [rsp + 0x1040], xmm6 ; Saves the contents of XMM6 in RSP + 0x1040.
                Ok(UWOP_SAVE_XMM128BIG) => i += 3,

                // Ignoring.
                Ok(UWOP_SET_FPREG) => i += 1,

                // Reserved code, not currently used.
                Ok(UWOP_EPILOG) | Ok(UWOP_SPARE_CODE) => i += 1,

                // Push a machine frame. This unwind code is used to record the effect of a hardware interrupt or exception.
                Ok(UWOP_PUSH_MACH_FRAME) => {
                    total_stack += if op_info == 0 { 0x40 } else { 0x48 };
                    i += 1
                }
                _ => {}
            }
        }

        // If there is a chain unwind structure, it too must be processed
        // recursively and included in the stack size calculation.
        if (flag & UNW_FLAG_CHAININFO) != 0 {
            let count = (*unwind_info).CountOfCodes as usize;
            let index = if count & 1 == 1 { count + 1 } else { count };
            let runtime = unwind_code.add(index) as *const IMAGE_RUNTIME_FUNCTION;
            if let Some(chained_stack) = ignoring_set_fpreg(module, &*runtime) {
                total_stack += chained_stack;
            } else {
                return None;
            }
        }

        Some(total_stack)
    }
}

/// Trait for safely converting any reference or mutable reference into a raw
/// pointer usable in spoofing routines.
pub trait AsPointer {
    /// Returns a raw immutable pointer to `self`.
    fn as_ptr_const(&self) -> *const c_void;

    /// Returns a raw mutable pointer to `self`.
    fn as_ptr_mut(&mut self) -> *mut c_void;
}

impl<T> AsPointer for T {
    #[inline(always)]
    fn as_ptr_const(&self) -> *const c_void {
        self as *const _ as *const c_void
    }

    #[inline(always)]
    fn as_ptr_mut(&mut self) -> *mut c_void {
        self as *mut _ as *mut c_void
    }
}

/// Specifies the spoofing mode used by the engine.
pub enum SpoofKind<'a> {
    /// Spoofs a direct function call.
    Function,

    /// Spoofs a syscall using its name.
    Syscall(&'a str),
}

#[cfg(test)]
mod tests {
    use core::ptr;
    use alloc::boxed::Box;
    use super::*;

    #[test]
    fn test_spoof() -> Result<(), Box<dyn core::error::Error>> {
        let kernel32 = get_module_address("kernel32.dll", None);
        let virtual_alloc = get_proc_address(kernel32, "VirtualAlloc", None);   
        let addr = spoof!(virtual_alloc, ptr::null_mut::<c_void>(), 1 << 12, 0x3000, 0x04)?;
        assert_ne!(addr, ptr::null_mut());

        Ok(())
    }

    #[test]
    fn test_syscall() -> Result<(), Box<dyn core::error::Error>> {
        let mut addr = ptr::null_mut::<c_void>();
        let mut size = (1 << 12) as usize;
        let status = syscall!("NtAllocateVirtualMemory", -1isize, addr.as_ptr_mut(), 0, size.as_ptr_mut(), 0x3000, 0x04)? as i32;
        assert_eq!(status, 0);

        Ok(())
    }
}