winhook 0.1.1

x86_64 function hooking library for Windows and Wine
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
use std::{mem, ops::Neg, rc::Rc};

use closure_ffi_iced_x86::{
    BlockEncoder, BlockEncoderOptions, Code, Decoder, DecoderOptions, Encoder, FlowControl,
    Instruction, InstructionBlock, InstructionInfoFactory, InstructionInfoOptions, MemoryOperand,
    OpAccess, OpKind, Register,
};
use fxhash::FxHashMap;
use smallvec::{SmallVec, smallvec, smallvec_inline};

use crate::{
    address::AsAddress,
    cconv::{X64_CCONV_VOLATILE, X64_STACK_SCRATCH_SPACE},
};

pub trait InstructionIterator {
    fn instructions<A: AsAddress>(&self, ip: A) -> impl Iterator<Item = Instruction>;
}

trait InstructionExt {
    fn try_reverse(&self) -> Option<Instruction>;

    fn try_emulate_prologue(
        &self,
        info_factory: &mut InstructionInfoFactory,
        before: Rc<StackSnapshot>,
    ) -> Option<Rc<StackSnapshot>>;

    fn try_pic_encode(
        &self,
        info_factory: &mut InstructionInfoFactory,
        stack_snapshot: &StackSnapshot,
    ) -> Option<SmallVec<[Instruction; 1]>>;
}

trait OpAccessExt {
    fn is_write(&self) -> bool;
}

#[derive(Debug)]
pub struct PrologueProbe {
    instructions: Vec<Instruction>,
    stack_snapshots: Vec<Rc<StackSnapshot>>,
    pic_encoded: Vec<Instruction>,
    pic_index_map: Vec<usize>,
    called_with: &'static [Register],
}

#[derive(Clone, Debug)]
struct StackSnapshot {
    stack: Vec<Register>,
    stack_pointer: usize,
    stack_bottom_offset: usize,
    stack_pointer_aliases: FxHashMap<Register, isize>,
    saved_registers: FxHashMap<Register, Vec<usize>>,
}

impl PrologueProbe {
    pub fn new<S: AsRef<[u8]>, A: AsAddress>(
        bytes: S,
        ip: A,
        called_with: &'static [Register],
    ) -> Self {
        let mut info_factory = InstructionInfoFactory::new();
        let mut instructions = Vec::with_capacity(16);

        let mut all_usable = true;

        instructions.extend(bytes.instructions(ip).map_while(|instruction| {
            (all_usable && instruction.code() != Code::Call_rel32_64).then(|| {
                all_usable = !instruction.is_invalid()
                    && instruction.flow_control() == FlowControl::Next
                    && !instruction.is_ip_rel_memory_operand();
                instruction
            })
        }));

        let mut stack_snapshots = Vec::with_capacity(16);
        stack_snapshots.push(Rc::new(StackSnapshot::new(X64_STACK_SCRATCH_SPACE)));

        for (i, instruction) in instructions.iter().enumerate() {
            if let Some(snapshot) =
                instruction.try_emulate_prologue(&mut info_factory, stack_snapshots[i].clone())
            {
                stack_snapshots.push(snapshot);
            } else {
                break;
            }
        }

        let _ = stack_snapshots.remove(0);

        instructions.truncate(stack_snapshots.len() + 1);

        if instructions.iter().all(|instruction| {
            instruction.memory_base() != Register::RIP
                && !instruction.is_jmp_short_or_near()
                && !instruction.is_jcc_short_or_near()
        }) {
            return Self {
                instructions,
                stack_snapshots,
                pic_encoded: vec![],
                pic_index_map: vec![],
                called_with,
            };
        }

        let mut pic_encoded = Vec::with_capacity(instructions.len() + 6);
        let mut pic_index_map = Vec::with_capacity(instructions.len());

        for (i, instruction) in instructions.iter().enumerate() {
            if let Some(seq) = instruction.try_pic_encode(&mut info_factory, &stack_snapshots[i]) {
                pic_index_map.push(seq.len());
                pic_encoded.extend(seq);
            } else {
                instructions.truncate(i);
                stack_snapshots.truncate(i);
                break;
            }
        }

        for i in 1..pic_index_map.len() {
            pic_index_map[i] += pic_index_map[i - 1];
        }

        Self {
            instructions,
            stack_snapshots,
            pic_encoded,
            pic_index_map,
            called_with,
        }
    }

    pub fn encode_undo_sequence(&self, index: usize) -> Option<Vec<u8>> {
        if index == 0 {
            // Nothing to undo.
            return Some(vec![]);
        }

        let instructions_to_undo = &self.instructions[..index];
        let stack_snapshot = self
            .stack_snapshots
            .get(index - 1)
            .or_else(|| self.stack_snapshots.last())?;

        let mut info_factory = InstructionInfoFactory::new();
        let mut reversed_instructions = vec![];

        for instruction in instructions_to_undo.iter().rev() {
            let info =
                info_factory.info_options(instruction, InstructionInfoOptions::NO_MEMORY_USAGE);

            if let Some(used) = info.used_registers().iter().find(|used| {
                used.access().is_write()
                    && used.register() != Register::RSP
                    && (!X64_CCONV_VOLATILE.contains(&used.register())
                        || self.called_with.contains(&used.register()))
            }) {
                if let Some(sp_offset) = stack_snapshot.saved_register_sp_offset(used.register()) {
                    let memory_operand = MemoryOperand::new(
                        Register::RSP,
                        Register::None,
                        1,
                        sp_offset as i64,
                        1,
                        false,
                        Register::None,
                    );

                    let register = used.register();
                    let full_register = register.full_register();

                    let load_from_stack = if full_register.is_gpr() {
                        Instruction::with2(Code::Mov_r64_rm64, register, memory_operand).unwrap()
                    } else if full_register.is_zmm() {
                        let xmm = full_register - Register::ZMM0 as u32 + Register::XMM0 as u32;
                        Instruction::with2(Code::Movups_xmm_xmmm128, xmm, memory_operand).unwrap()
                    } else {
                        return None;
                    };

                    reversed_instructions.push(load_from_stack);
                } else if let Some(reversed_instruction) = instruction.try_reverse() {
                    reversed_instructions.push(reversed_instruction);
                } else {
                    return None;
                }
            }
        }

        let stack_size = stack_snapshot.stack_size();
        if stack_size != 0 {
            let realign_stack = if stack_size == 8 && index == 1 {
                // Optimization that can be done with one preceeding instruction to save space.
                // Since the previous instruction decremented RSP, it's sane to assume it didn't
                // also write to RAX.
                Instruction::with1(Code::Pop_r64, Register::RAX).unwrap()
            } else if stack_size <= i8::MAX as usize {
                Instruction::with2(Code::Add_rm64_imm8, Register::RSP, stack_size as i32).unwrap()
            } else if stack_size == i8::MIN as u8 as usize {
                // Niche optimization for `stack_size == 128`.
                Instruction::with2(
                    Code::Sub_rm64_imm8,
                    Register::RSP,
                    stack_size.wrapping_neg() as i32,
                )
                .unwrap()
            } else {
                Instruction::with2(Code::Add_rm64_imm32, Register::RSP, stack_size as i32).unwrap()
            };

            reversed_instructions.push(realign_stack);
        }

        let mut encoder = Encoder::new(64);

        for instruction in reversed_instructions {
            encoder.encode(&instruction, i64::MAX as u64).ok()?;
        }

        Some(encoder.take_buffer())
    }

    pub fn encode_trampoline(&self, index: usize) -> Option<Vec<u8>> {
        let mut buf = if let Some(pic_index) = self.pic_index_map.get(index) {
            BlockEncoder::encode(
                64,
                InstructionBlock::new(&self.pic_encoded[..*pic_index], i64::MAX as u64),
                BlockEncoderOptions::NONE,
            )
            .ok()?
            .code_buffer
        } else {
            let mut encoder = Encoder::new(64);
            for instruction in &self.instructions[..=index] {
                encoder.encode(instruction, !0).ok()?;
            }
            encoder.take_buffer()
        };

        buf.reserve_exact(14);

        let jmp_abs_rip0 = [0xff, 0x25, 0x00, 0x00, 0x00, 0x00];
        let next_ip = self.instructions[index].next_ip();

        buf.extend_from_slice(&jmp_abs_rip0);
        buf.extend_from_slice(&next_ip.to_le_bytes());

        Some(buf)
    }

    pub fn enumerate_instructions(&self) -> Vec<(usize, &Instruction)> {
        self.instructions.iter().enumerate().collect::<Vec<_>>()
    }

    pub fn enumerate_instructions_by_len(&self, desired_len: usize) -> Vec<(usize, &Instruction)> {
        let mut instructions = self.enumerate_instructions();

        // Stable sort that prioritizes instructions at least `desired_len` bytes long.
        instructions
            .sort_by_key(|(_, instruction)| std::cmp::Reverse(instruction.len().min(desired_len)));

        instructions
    }
}

impl StackSnapshot {
    fn new(stack_scratch_space: (usize, usize)) -> Self {
        let (high_bytes, low_bytes) = stack_scratch_space;

        // One extra for the return address.
        let stack_bottom_offset = high_bytes / 8 + 1;
        let stack_top_offset = low_bytes / 8;

        let stack = vec![Register::None; stack_bottom_offset + stack_top_offset];

        Self {
            stack,
            stack_pointer: stack_bottom_offset,
            stack_bottom_offset,
            stack_pointer_aliases: FxHashMap::default(),
            saved_registers: FxHashMap::default(),
        }
    }

    fn allocate(&mut self, bytes: usize) {
        let offset = bytes / 8;
        self.stack.resize(self.stack.len() + offset, Register::None);
        self.stack_pointer += offset;
    }

    fn push(&mut self, register: Register) {
        debug_assert!(register.is_gpr());

        if self.stack_pointer == self.stack.len() {
            self.stack.push(Register::None);
        }

        self.overwrite_stack_space(self.stack_pointer, register);

        self.stack_pointer += 1;
    }

    fn write(&mut self, sp_byte_offset: isize, register: Register) {
        if register == Register::None {
            return;
        }

        if let Some(index) = self
            .stack_pointer
            .checked_sub_signed(1 + sp_byte_offset / 8)
        {
            self.overwrite_stack_space(index, register);
        }
    }

    fn saved_register_sp_offset(&self, register: Register) -> Option<usize> {
        self.saved_registers
            .get(&register.full_register())
            .and_then(|saved| saved.first())
            .map(|index| (self.stack_pointer - index - 1) * 8)
    }

    fn stack_size(&self) -> usize {
        (self.stack_pointer - self.stack_bottom_offset) * 8
    }

    fn overwrite_stack_space(&mut self, index: usize, new: Register) {
        if let Some(space) = self.stack.get_mut(index) {
            let saved = self.saved_registers.entry(new.full_register()).or_default();

            if !saved.contains(&index) {
                saved.push(index);
            }

            let replaced = mem::replace(space, new);

            if replaced == Register::None {
                return;
            }

            let saved = self
                .saved_registers
                .get_mut(&replaced.full_register())
                .expect("BUG: register was not saved");

            let index = saved
                .iter()
                .position(|saved_index| *saved_index == index)
                .expect("BUG: register was not saved");

            saved.swap_remove(index);
        }
    }

    fn sp_alias_displacement(&self, register: Register) -> Option<isize> {
        match register {
            Register::RSP => Some(0),
            _ => self
                .stack_pointer_aliases
                .get(&register)
                .map(|disp| disp.wrapping_sub_unsigned(self.stack_size())),
        }
    }

    fn add_sp_alias(&mut self, register: Register, sp_byte_offset: isize) {
        if register != Register::RSP {
            self.stack_pointer_aliases.insert(
                register,
                sp_byte_offset.wrapping_add_unsigned(self.stack_size()),
            );
        }
    }

    fn clear_sp_alias(&mut self, register: Register) {
        if register != Register::RSP {
            self.stack_pointer_aliases.remove(&register);
        }
    }

    fn can_allocate_register(&self, reserved: &[Register]) -> Register {
        for saved in self.saved_registers.keys() {
            if saved.is_gpr() && !reserved.contains(saved) {
                return *saved;
            }
        }
        Register::None
    }

    fn can_push_register(&self, reserved: &[Register]) -> bool {
        !reserved.contains(&Register::RSP)
            && matches!(
                self.stack.get(self.stack_pointer),
                None | Some(Register::None)
            )
    }
}

impl<T: AsRef<[u8]> + ?Sized> InstructionIterator for T {
    #[inline]
    fn instructions<A: AsAddress>(&self, addr: A) -> impl Iterator<Item = Instruction> {
        let ip = addr.as_addr() as u64;
        let mut decoder = Decoder::with_ip(64, self.as_ref(), ip, DecoderOptions::NONE);
        let mut instruction = Instruction::new();

        std::iter::from_fn(move || {
            decoder.can_decode().then(|| {
                decoder.decode_out(&mut instruction);
                instruction
            })
        })
    }
}

impl InstructionExt for Instruction {
    fn try_reverse(&self) -> Option<Instruction> {
        let mut instruction = *self;
        let same_register = self.op0_register() == self.op1_register();

        use closure_ffi_iced_x86::Code as C;
        match self.code() {
            C::Add_rm8_r8 if !same_register => instruction.set_code(C::Sub_rm8_r8),
            C::Add_rm16_r16 if !same_register => instruction.set_code(C::Sub_rm16_r16),
            C::Add_rm32_r32 if !same_register => instruction.set_code(C::Sub_rm32_r32),
            C::Add_rm64_r64 if !same_register => instruction.set_code(C::Sub_rm64_r64),
            C::Add_r8_rm8 if !same_register => instruction.set_code(C::Sub_r8_rm8),
            C::Add_r16_rm16 if !same_register => instruction.set_code(C::Sub_r16_rm16),
            C::Add_r32_rm32 if !same_register => instruction.set_code(C::Sub_r32_rm32),
            C::Add_r64_rm64 if !same_register => instruction.set_code(C::Sub_r64_rm64),
            C::Add_AL_imm8 => instruction.set_code(C::Sub_AL_imm8),
            C::Add_AX_imm16 => instruction.set_code(C::Sub_AX_imm16),
            C::Add_EAX_imm32 => instruction.set_code(C::Sub_EAX_imm32),
            C::Add_RAX_imm32 => instruction.set_code(C::Sub_RAX_imm32),
            C::Sub_rm8_r8 if !same_register => instruction.set_code(C::Add_rm8_r8),
            C::Sub_rm16_r16 if !same_register => instruction.set_code(C::Add_rm16_r16),
            C::Sub_rm32_r32 if !same_register => instruction.set_code(C::Add_rm32_r32),
            C::Sub_rm64_r64 if !same_register => instruction.set_code(C::Add_rm64_r64),
            C::Sub_r8_rm8 if !same_register => instruction.set_code(C::Add_r8_rm8),
            C::Sub_r16_rm16 if !same_register => instruction.set_code(C::Add_r16_rm16),
            C::Sub_r32_rm32 if !same_register => instruction.set_code(C::Add_r32_rm32),
            C::Sub_r64_rm64 if !same_register => instruction.set_code(C::Add_r64_rm64),
            C::Sub_AL_imm8 => instruction.set_code(C::Add_AL_imm8),
            C::Sub_AX_imm16 => instruction.set_code(C::Add_AX_imm16),
            C::Sub_EAX_imm32 => instruction.set_code(C::Add_EAX_imm32),
            C::Sub_RAX_imm32 => instruction.set_code(C::Add_RAX_imm32),
            C::Xor_rm8_r8
            | C::Xor_rm16_r16
            | C::Xor_rm32_r32
            | C::Xor_rm64_r64
            | C::Xor_r8_rm8
            | C::Xor_r16_rm16
            | C::Xor_r32_rm32
            | C::Xor_r64_rm64
                if !same_register => {}
            C::Xor_AL_imm8 | C::Xor_AX_imm16 | C::Xor_EAX_imm32 | C::Xor_RAX_imm32 => {}
            C::Push_r64 | C::Pushq_imm32 | C::Pushq_imm8 | C::Push_rm64 | C::Pushfq => {
                instruction = Instruction::with2(C::Add_rm64_imm8, Register::RSP, 8).unwrap()
            }
            C::Pop_r64 | C::Pop_rm64 | C::Popfq => {
                instruction = Instruction::with2(C::Sub_rm64_imm8, Register::RSP, 8).unwrap()
            }
            C::Add_rm16_imm16 => instruction.set_code(C::Sub_rm16_imm16),
            C::Add_rm32_imm32 => instruction.set_code(C::Sub_rm32_imm32),
            C::Add_rm64_imm32 => instruction.set_code(C::Sub_rm64_imm32),
            C::Sub_rm16_imm16 => instruction.set_code(C::Add_rm16_imm16),
            C::Sub_rm32_imm32 => instruction.set_code(C::Add_rm32_imm32),
            C::Sub_rm64_imm32 => instruction.set_code(C::Add_rm64_imm32),
            C::Xor_rm16_imm16 | C::Xor_rm32_imm32 | C::Xor_rm64_imm32 => {}
            C::Add_rm16_imm8 => instruction.set_code(C::Sub_rm16_imm8),
            C::Add_rm32_imm8 => instruction.set_code(C::Sub_rm32_imm8),
            C::Add_rm64_imm8 => instruction.set_code(C::Sub_rm64_imm8),
            C::Sub_rm16_imm8 => instruction.set_code(C::Add_rm16_imm8),
            C::Sub_rm32_imm8 => instruction.set_code(C::Add_rm32_imm8),
            C::Sub_rm64_imm8 => instruction.set_code(C::Add_rm64_imm8),
            C::Xor_rm16_imm8 | C::Xor_rm32_imm8 | C::Xor_rm64_imm8 => {}
            C::Xchg_rm8_r8
            | C::Xchg_rm16_r16
            | C::Xchg_rm32_r32
            | C::Xchg_rm64_r64
            | C::Xchg_r16_AX
            | C::Xchg_r32_EAX
            | C::Xchg_r64_RAX => {}
            C::Not_rm8 | C::Not_rm16 | C::Not_rm32 | C::Not_rm64 => {}
            C::Neg_rm8 | C::Neg_rm16 | C::Neg_rm32 | C::Neg_rm64 => {}
            C::Inc_rm8 => instruction.set_code(C::Dec_rm8),
            C::Inc_rm16 => instruction.set_code(C::Dec_rm16),
            C::Inc_rm32 => instruction.set_code(C::Dec_rm32),
            C::Inc_rm64 => instruction.set_code(C::Dec_rm64),
            C::Dec_rm8 => instruction.set_code(C::Inc_rm8),
            C::Dec_rm16 => instruction.set_code(C::Inc_rm16),
            C::Dec_rm32 => instruction.set_code(C::Inc_rm32),
            C::Dec_rm64 => instruction.set_code(C::Inc_rm64),
            _ => return None,
        }

        Some(instruction)
    }

    fn try_emulate_prologue(
        &self,
        info_factory: &mut InstructionInfoFactory,
        before: Rc<StackSnapshot>,
    ) -> Option<Rc<StackSnapshot>> {
        let mut after = before;

        use closure_ffi_iced_x86::Code as C;
        match self.code() {
            C::Add_rm64_imm8 | C::Add_rm64_imm32 => {
                let immediate = if self.code() == C::Add_rm64_imm8 {
                    self.immediate8() as i8 as isize
                } else {
                    self.immediate32() as i32 as isize
                };

                if self.op0_register() == Register::RSP {
                    return (immediate <= 0).then(|| {
                        Rc::make_mut(&mut after).allocate(immediate.neg() as usize);
                        after
                    });
                } else if let Some(disp) = after.sp_alias_displacement(self.op0_register()) {
                    Rc::make_mut(&mut after).add_sp_alias(self.op0_register(), disp + immediate);
                }

                return Some(after);
            }
            C::Sub_rm64_imm8 | C::Sub_rm64_imm32 => {
                let immediate = if self.code() == C::Add_rm64_imm8 {
                    self.immediate8() as i8 as isize
                } else {
                    self.immediate32() as i32 as isize
                };

                if self.op0_register() == Register::RSP {
                    return (immediate >= 0).then(|| {
                        Rc::make_mut(&mut after).allocate(immediate as usize);
                        after
                    });
                } else if let Some(disp) = after.sp_alias_displacement(self.op0_register()) {
                    Rc::make_mut(&mut after).add_sp_alias(self.op0_register(), disp - immediate);
                }

                return Some(after);
            }
            _ => {}
        }

        match self.code() {
            C::Push_r64 | C::Push_rm64 if self.op0_kind() == OpKind::Register => {
                return self.op0_register().is_gpr().then(|| {
                    Rc::make_mut(&mut after).push(self.op0_register());
                    after
                });
            }
            C::Pushq_imm32 | C::Pushfq | C::Pushq_imm8 => {
                Rc::make_mut(&mut after).allocate(8);
                return Some(after);
            }
            C::Push_r16 | C::Pushw_imm8 | C::Push_rm16 | C::Pushfw => return None,
            C::Pop_r64 | C::Popfq | C::Pop_rm64 => return None,
            C::Pop_r16 | C::Popfw | C::Pop_rm16 => return None,
            _ => {}
        }

        let memory_base = self.memory_base();

        if memory_base != Register::None
            && self.op0_kind() == OpKind::Memory
            && let Some(disp) = after.sp_alias_displacement(memory_base)
        {
            return (self.memory_index() == Register::None).then(|| {
                Rc::make_mut(&mut after).write(
                    disp + self.memory_displacement64() as isize,
                    self.op1_register(),
                );
                after
            });
        }

        if after.sp_alias_displacement(self.op0_register()).is_some() {
            let info = info_factory.info_options(self, InstructionInfoOptions::NO_MEMORY_USAGE);

            if info.op0_access().is_write() {
                Rc::make_mut(&mut after).clear_sp_alias(self.op0_register());
            }
        }

        match self.code() {
            C::Mov_r64_rm64 | C::Mov_rm64_r64 => {
                if let Some(disp) = after.sp_alias_displacement(self.op1_register()) {
                    Rc::make_mut(&mut after).add_sp_alias(self.op0_register(), disp);
                }
            }
            C::Lea_r64_m => {
                if let Some(disp) = after.sp_alias_displacement(self.memory_base())
                    && self.memory_index() == Register::None
                {
                    Rc::make_mut(&mut after).add_sp_alias(
                        self.op0_register(),
                        disp + self.memory_displacement64() as isize,
                    );
                }
            }
            _ => {}
        }

        Some(after)
    }

    fn try_pic_encode(
        &self,
        info_factory: &mut InstructionInfoFactory,
        stack_snapshot: &StackSnapshot,
    ) -> Option<SmallVec<[Instruction; 1]>> {
        if self.memory_base() != Register::RIP
            || self.is_jmp_short_or_near()
            || self.is_jcc_short_or_near()
        {
            return Some(smallvec_inline![*self]);
        }

        let info = info_factory.info_options(self, InstructionInfoOptions::NO_MEMORY_USAGE);

        let mut reserved_registers = [Register::None; 5];
        let reserved_registers = &mut reserved_registers[..self.op_count() as usize];

        for (i, register) in reserved_registers.iter_mut().enumerate() {
            if info.op_access(i as u32).is_write() {
                *register = self.op_register(i as u32).full_register();
            }
        }

        match stack_snapshot.can_allocate_register(reserved_registers) {
            Register::None => {
                if !stack_snapshot.can_push_register(reserved_registers) {
                    return None;
                }

                let push = Instruction::with1(Code::Push_r64, Register::RAX).unwrap();

                let load = Instruction::with2(
                    Code::Mov_r64_imm64,
                    Register::RAX,
                    self.memory_displacement64(),
                )
                .unwrap();

                let mut instruction = *self;

                instruction.set_memory_base(Register::RAX);
                instruction.set_memory_index(Register::None);
                instruction.set_memory_index_scale(1);
                instruction.set_memory_displacement64(0);

                let pop = Instruction::with1(Code::Pop_r64, Register::RAX).unwrap();

                Some(smallvec![push, load, instruction, pop])
            }
            register => {
                let load =
                    Instruction::with2(Code::Mov_r64_imm64, register, self.memory_displacement64())
                        .unwrap();

                let mut instruction = *self;

                instruction.set_memory_base(register);
                instruction.set_memory_index(Register::None);
                instruction.set_memory_index_scale(1);
                instruction.set_memory_displacement64(0);

                let sp_offset = stack_snapshot
                    .saved_register_sp_offset(register)
                    .expect("BUG: register was not saved");

                let memory_operand = MemoryOperand::new(
                    Register::RSP,
                    Register::None,
                    1,
                    sp_offset as i64,
                    1,
                    false,
                    Register::None,
                );

                let reload =
                    Instruction::with2(Code::Mov_r64_rm64, register, memory_operand).unwrap();

                Some(smallvec![load, instruction, reload])
            }
        }
    }
}

impl OpAccessExt for OpAccess {
    fn is_write(&self) -> bool {
        matches!(
            self,
            OpAccess::Write | OpAccess::CondWrite | OpAccess::ReadWrite | OpAccess::ReadCondWrite
        )
    }
}