all repos — gemini-redirect @ 35426b2cb8e686689d194a1b9e0f7cc394d0b5e4

content/blog/woce-5.md (view raw)

  1+++
  2title = "Writing our own Cheat Engine: Code finder"
  3date = 2021-03-06
  4updated = 2021-03-06
  5[taxonomies]
  6category = ["sw"]
  7tags = ["windows", "rust", "hacking"]
  8+++
  9
 10This is part 5 on the *Writing our own Cheat Engine* series:
 11
 12* [Part 1: Introduction](/blog/woce-1) (start here if you're new to the series!)
 13* [Part 2: Exact Value scanning](/blog/woce-2)
 14* [Part 3: Unknown initial value](/blog/woce-3)
 15* [Part 4: Floating points](/blog/woce-4)
 16* Part 5: Code finder
 17
 18In part 4 we spent a good deal of time trying to make our scans generic, and now we have something that works[^1]! Now that the scanning is fairly powerful and all covered, the Cheat Engine tutorial shifts focus into slightly more advanced techniques that you will most certainly need in anything bigger than a toy program.
 19
 20It's time to write our very own **debugger** in Rust!
 21
 22## Code finder
 23
 24<details open><summary>Cheat Engine Tutorial: Step 5</summary>
 25
 26> Sometimes the location something is stored at changes when you restart the game, or even while you're playing… In that case you can use 2 things to still make a table that works. In this step I'll try to describe how to use the Code Finder function.
 27>
 28> The value down here will be at a different location each time you start the tutorial, so a normal entry in the address list wouldn't work. First try to find the address. (You've got to this point so I assume you know how to.)
 29>
 30> When you've found the address, right-click the address in Cheat Engine and choose "Find out what writes to this address". A window will pop up with an empty list.
 31>
 32> Then click on the Change value button in this tutorial, and go back to Cheat Engine. If everything went right there should be an address with assembler code there now.
 33>
 34> Click it and choose the replace option to replace it with code that does nothing. That will also add the code address to the code list in the advanced options window. (Which gets saved if you save your table.)
 35>
 36> Click on stop, so the game will start running normal again, and close to close the window. Now, click on Change value, and if everything went right the Next button should become enabled.
 37>
 38> Note: When you're freezing the address with a high enough speed it may happen that next becomes visible anyhow
 39
 40</details>
 41
 42## Baby steps to debugging
 43
 44Although I have used debuggers before, I have never had a need to write one myself so it's time for some research.
 45
 46Searching on DuckDuckGo, I can find entire series to [Writing a Debugger][debug-series]. We would be done by now if only that series wasn't written for Linux. The Windows documentation contains a section called [Creating a Basic Debugger][win-basic-dbg], but as far as I can tell, it only teaches you the [functions][dbg-func] needed to configure the debugging loop. Which mind you, we will need, but in due time.
 47
 48According to [Writing your own windows debugger in C][dbg-c], the steps needed to write a debugger are:
 49
 50* [`SuspendThread(proc)`][suspend-thread]. It makes sense that we need to pause all the threads[^2] before messing around with the code the program is executing, or things are very prone to go wrong.
 51* [`GetThreadContext(proc)`][thread-ctx]. This function retrieves the appropriate context of the specified thread and is highly processor specific. It basically takes a snapshot of all the registers. Think of registers like extremely fast, but also extremely limited, memory the processor uses.
 52* [`DebugBreakProcess`][dbg-break]. Essentially [writes out the 0xCC opcode][0xcc], `int 3` in assembly, also known as software breakpoint. It's written wherever the Register Instruction Pointer (RIP[^3]) currently points to, so in essence, when the thread resumes, it will immediately [trigger the breakpoint][how-c-brk].
 53* [`ContinueDebugEvent`][cont-dbg]. Presumably continues debugging.
 54
 55There are pages documenting [all of the debug events][dbg-events] that our debugger will be able to handle.
 56
 57Okay, nice! Software breakpoints seem to be done by writing out memory to the region where the program is reading instructions from. We know how to write memory, as that's what all the previous posts have been doing to complete the corresponding tutorial steps. After the breakpoint is executed, all we need to do is [restore the original memory back][how-int3] so that the next time the program executes the code it sees no difference.
 58
 59But a software breakpoint will halt execution when the code executes the interrupt instruction. This step of the tutorial wants us to find *what writes to a memory location*. Where should we place the breakpoint to detect such location? Writing out the instruction to the memory we want to break in won't do; it's not an instruction, it's just data.
 60
 61The name may have given it away. If we're talking about software breakpoints, it makes sense that there would exist such a thing as [*hardware* breakpoints][hw-brk]. Because they're tied to the hardware, they're highly processor-specific, but luckily for us, the processor on your usual desktop computer probably has them! Even the [cortex-m] does. The wikipedia page also tells us the name of the thing we're looking for, watchpoints:
 62
 63> Other kinds of conditions can also be used, such as the reading, writing, or modification of a specific location in an area of memory. This is often referred to as a conditional breakpoint, a data breakpoint, or a watchpoint.
 64
 65A breakpoint that triggers when a specific memory location is written to is exactly what we need, and [x86 has debug registers D0 to D3 to track memory addresses][x86-dbg-reg]. As far as I can tell, there is no API in specific to mess with the registers. But we don't need any of that! We can just go ahead and [write some assembly by hand][asm-macro] to access these registers. At the time of writing, inline assembly is unstable, so we need a nightly compiler. Run `rustup toolchain install nightly` if you haven't yet, and execute the following code with `cargo +nightly run`:
 66
 67```rust
 68#![feature(asm)] // top of the file
 69
 70fn main() {
 71    let x: u64 = 123;
 72    unsafe {
 73        asm!("mov dr7, {}", in(reg) x);
 74    }
 75}
 76
 77```
 78
 79`dr7` stands is the [debug control register][dbg-reg], and running this we get…
 80
 81```
 82>cargo +nightly run
 83   Compiling memo v0.1.0
 84    Finished dev [unoptimized + debuginfo] target(s) in 0.74s
 85     Running `target\debug\memo.exe`
 86error: process didn't exit successfully: `target\debug\memo.exe` (exit code: 0xc0000096, STATUS_PRIVILEGED_INSTRUCTION)
 87```
 88
 89…an exception! In all fairness, I have no idea what that code would have done. So maybe the `STATUS_PRIVILEGED_INSTRUCTION` is just trying to protect us. Can we read from the register instead, and see it's default value?
 90
 91```rust
 92let x: u64;
 93unsafe {
 94    asm!("mov {}, dr7", out(reg) x);
 95}
 96assert_eq!(x, 5);
 97```
 98
 99```
100>cargo +nightly run
101...
102error: process didn't exit successfully: `target\debug\memo.exe` (exit code: 0xc0000096, STATUS_PRIVILEGED_INSTRUCTION)
103```
104
105Nope. Okay, it seems directly reading from or writing to the debug register is a ring-0 thing. Surely there's a way around this. But first we should figure out how to enumerate and pause all the threads.
106
107## Pausing all the threads
108
109It seems there is no straightforward way to enumerate the threads. One has to [create a "toolhelp"][toolhelp] and poll the entries. I won't bore you with the details. Let's add `tlhelp32` to the crate features of `winapi` and try it out:
110
111```rust
112
113#[derive(Debug)]
114pub struct Toolhelp {
115    handle: winapi::um::winnt::HANDLE,
116}
117
118impl Drop for Toolhelp {
119    fn drop(&mut self) {
120        unsafe { winapi::um::handleapi::CloseHandle(self.handle) };
121    }
122}
123
124pub fn enum_threads(pid: u32) -> io::Result<Vec<u32>> {
125    const ENTRY_SIZE: u32 = mem::size_of::<winapi::um::tlhelp32::THREADENTRY32>() as u32;
126
127    // size_of(dwSize + cntUsage + th32ThreadID + th32OwnerProcessID)
128    const NEEDED_ENTRY_SIZE: u32 = 4 * mem::size_of::<DWORD>() as u32;
129
130    // SAFETY: it is always safe to attempt to call this function.
131    let handle = unsafe {
132        winapi::um::tlhelp32::CreateToolhelp32Snapshot(winapi::um::tlhelp32::TH32CS_SNAPTHREAD, 0)
133    };
134    if handle == winapi::um::handleapi::INVALID_HANDLE_VALUE {
135        return Err(io::Error::last_os_error());
136    }
137    let toolhelp = Toolhelp { handle };
138
139    let mut result = Vec::new();
140    let mut entry = winapi::um::tlhelp32::THREADENTRY32 {
141        dwSize: ENTRY_SIZE,
142        cntUsage: 0,
143        th32ThreadID: 0,
144        th32OwnerProcessID: 0,
145        tpBasePri: 0,
146        tpDeltaPri: 0,
147        dwFlags: 0,
148    };
149
150    // SAFETY: we have a valid handle, and point to memory we own with the right size.
151    if unsafe { winapi::um::tlhelp32::Thread32First(toolhelp.handle, &mut entry) } != FALSE {
152        loop {
153            if entry.dwSize >= NEEDED_ENTRY_SIZE && entry.th32OwnerProcessID == pid {
154                result.push(entry.th32ThreadID);
155            }
156
157            entry.dwSize = ENTRY_SIZE;
158            // SAFETY: we have a valid handle, and point to memory we own with the right size.
159            if unsafe { winapi::um::tlhelp32::Thread32Next(toolhelp.handle, &mut entry) } == FALSE {
160                break;
161            }
162        }
163    }
164
165    Ok(result)
166}
167```
168
169Annoyingly, invalid handles returned by [`CreateToolhelp32Snapshot`][create-snapshot], are `INVALID_HANDLE_VALUE` (which is -1), not null. But that's not a big deal, we simply can't use `NonNull` here. The function ignores the process identifier when using `TH32CS_SNAPTHREAD`, used to include all threads, and we need to compare the process identifier ourselves.
170
171In summary, we create a "toolhelp" (wrapped in a helper `struct` so that whatever happens, `Drop` will clean it up), initialize a thread enntry (with everything but the structure size to zero) and call `Thread32First` the first time, `Thread32Next` subsequent times. It seems to work all fine!
172
173```rust
174dbg!(process::enum_threads(pid));
175```
176
177```
178[src\main.rs:46] process::enum_threads(pid) = Ok(
179    [
180        10560,
181    ],
182)
183```
184
185According to this, the Cheat Engine tutorial is only using one thread. Good to know. Much like processes, threads need to be opened before we can use them, with [`OpenThread`][open-thread]:
186
187```rust
188pub struct Thread {
189    tid: u32,
190    handle: NonNull<c_void>,
191}
192
193impl Thread {
194    pub fn open(tid: u32) -> io::Result<Self> {
195        // SAFETY: the call doesn't have dangerous side-effects
196        NonNull::new(unsafe {
197            winapi::um::processthreadsapi::OpenThread(
198                winapi::um::winnt::THREAD_SUSPEND_RESUME,
199                FALSE,
200                tid,
201            )
202        })
203        .map(|handle| Self { tid, handle })
204        .ok_or_else(io::Error::last_os_error)
205    }
206
207    pub fn tid(&self) -> u32 {
208        self.tid
209    }
210}
211
212impl Drop for Thread {
213    fn drop(&mut self) {
214        unsafe { winapi::um::handleapi::CloseHandle(self.handle.as_mut()) };
215    }
216}
217```
218
219Just your usual RAII pattern. The thread is opened with permission to suspend and resume it. Let's try to pause the handles with [`SuspendThread`][suspend-thread] to make sure that this thread is actually the one we're looking for:
220
221```rust
222pub fn suspend(&mut self) -> io::Result<usize> {
223    // SAFETY: the handle is valid.
224    let ret = unsafe {
225        winapi::um::processthreadsapi::SuspendThread(self.handle.as_ptr())
226    };
227    if ret == -1i32 as u32 {
228        Err(io::Error::last_os_error())
229    } else {
230        Ok(ret as usize)
231    }
232}
233
234pub fn resume(&mut self) -> io::Result<usize> {
235    // SAFETY: the handle is valid.
236    let ret = unsafe {
237        winapi::um::processthreadsapi::ResumeThread(self.handle.as_ptr())
238    };
239    if ret == -1i32 as u32 {
240        Err(io::Error::last_os_error())
241    } else {
242        Ok(ret as usize)
243    }
244}
245```
246
247Both suspend and resume return the previous "suspend count". It's kind of like a barrier or semaphore where the thread only runs if the suspend count is zero. Trying it out:
248
249```rust
250let mut threads = thread::enum_threads(pid)
251    .unwrap()
252    .into_iter()
253    .map(Thread::open)
254    .collect::<Result<Vec<_>, _>>()
255    .unwrap();
256
257threads
258    .iter_mut()
259    .for_each(|thread| {
260        println!("Pausing thread {} for 10 seconds…", thread.tid());
261        thread.suspend().unwrap();
262
263        std::thread::sleep(std::time::Duration::from_secs(10));
264
265        println!("Wake up, {}!", thread.tid());
266        thread.resume().unwrap();
267    });
268```
269
270If you run this code with the process ID of the Cheat Engine tutorial, you will see that the tutorial window freezes for ten seconds! Because the main and only thread is paused, it cannot process any window events, so it becomes unresponsive. It is now "safe" to mess around with the thread context.
271
272## Setting hardware breakpoints
273
274I'm definitely not the first person to wonder [How to set a hardware breakpoint?][howto-hw-brk]. This is great, because it means I don't need to ask that question myself. It appears we need to change the debug register *via the thread context*.
275
276One has to be careful to use the right context structure. Confusingly enough, [`WOW64_CONTEXT`][wow64-ctx] is 32 bits, not 64. `CONTEXT` alone seems to be the right one:
277
278```rust
279pub fn get_context(&self) -> io::Result<winapi::um::winnt::CONTEXT> {
280    let context = MaybeUninit::<winapi::um::winnt::CONTEXT>::zeroed();
281    // SAFETY: it's a C struct, and all-zero is a valid bit-pattern for the type.
282    let mut context = unsafe { context.assume_init() };
283    context.ContextFlags = winapi::um::winnt::CONTEXT_ALL;
284
285    // SAFETY: the handle is valid and structure points to valid memory.
286    if unsafe {
287        winapi::um::processthreadsapi::GetThreadContext(self.handle.as_ptr(), &mut context)
288    } == FALSE
289    {
290        Err(io::Error::last_os_error())
291    } else {
292        Ok(context)
293    }
294}
295```
296
297Trying it out:
298
299```rust
300thread.suspend().unwrap();
301
302let context = thread.get_context().unwrap();
303println!("Dr0: {:016x}", context.Dr0);
304println!("Dr7: {:016x}", context.Dr7);
305println!("Dr6: {:016x}", context.Dr6);
306println!("Rax: {:016x}", context.Rax);
307println!("Rbx: {:016x}", context.Rbx);
308println!("Rcx: {:016x}", context.Rcx);
309println!("Rip: {:016x}", context.Rip);
310```
311
312```
313Dr0: 0000000000000000
314Dr7: 0000000000000000
315Dr6: 0000000000000000
316Rax: 0000000000001446
317Rbx: 0000000000000000
318Rcx: 0000000000000000
319Rip: 00007ffda4259904
320```
321
322Looks about right! Hm, I wonder what happens if I use Cheat Engine to add the watchpoint on the memory location we care about?
323
324```
325Dr0: 000000000157e650
326Dr7: 00000000000d0001
327```
328
329Look at that! The debug registers changed! DR0 contains the location we want to watch for writes, and the debug control register DR7 changed. Cheat Engine sets the same values on all threads (for some reason I now see more than one thread printed for the tutorial, not sure what's up with that; maybe the single-thread is the weird one out).
330
331Hmm, what happens if I watch for access instead of write?
332
333```
334Dr0: 000000000157e650
335Dr7: 00000000000f0001
336```
337
338What if I set both?
339
340```
341Dr0: 000000000157e650
342Dr7: 0000000000fd0005
343```
344
345Most intriguing! This was done by telling Cheat Engine to find "what writes" to the address, then "what accesses" the address. I wonder if the order matters?
346
347```
348Dr0: 000000000157e650
349Dr7: 0000000000df0005
350```
351
352"What accesses" and then "what writes" does change it. Very well! We're only concerned in a single breakpoint, so we won't worry about this, but it's good to know that we can inspect what Cheat Engine is doing. It's also interesting to see how Cheat Engine is using hardware breakpoints and not software breakpoints.
353
354For simplicity, our code is going to assume that we're the only ones messing around with the debug registers, and that there will only be a single debug register in use. Make sure to add `THREAD_SET_CONTEXT` to the permissions when opening the thread handle:
355
356```rust
357pub fn set_context(&self, context: &winapi::um::winnt::CONTEXT) -> io::Result<()> {
358    // SAFETY: the handle is valid and structure points to valid memory.
359    if unsafe {
360        winapi::um::processthreadsapi::SetThreadContext(self.handle.as_ptr(), context)
361    } == FALSE
362    {
363        Err(io::Error::last_os_error())
364    } else {
365        Ok(())
366    }
367}
368
369pub fn watch_memory_write(&self, addr: usize) -> io::Result<()> {
370    let mut context = self.get_context()?;
371    context.Dr0 = addr as u64;
372    context.Dr7 = 0x00000000000d0001;
373    self.set_context(&context)?;
374    todo!()
375}
376```
377
378If we do this (and temporarily get rid of the `todo!()`), trying to change the value in the Cheat Engine tutorial will greet us with a warm message:
379
380> **Tutorial-x86_64**
381>
382> External exception 80000004.
383>
384> Press OK to ignore and risk data corruption.\
385> Press Abort to kill the program.
386>
387> <kbd>OK</kbd> <kbd>Abort</kbd>
388
389There is no debugger attached yet that could possibly handle this exception, so the exception just propagates. Let's fix that.
390
391## Handling debug events
392
393Now that we've succeeded on setting breakpoints, we can actually follow the steps described in [Creating a Basic Debugger][win-basic-dbg]. It starts by saying that we should use [`DebugActiveProcess`][dbg-active] to attach our processor, the debugger, to the process we want to debug, the debuggee. This function lives under the `debugapi` header, so add it to `winapi` features:
394
395```rust
396pub struct DebugToken {
397    pid: u32,
398}
399
400pub fn debug(pid: u32) -> io::Result<DebugToken> {
401    if unsafe { winapi::um::debugapi::DebugActiveProcess(pid) } == FALSE {
402        return Err(io::Error::last_os_error());
403    };
404    let token = DebugToken { pid };
405    if unsafe { winapi::um::winbase::DebugSetProcessKillOnExit(FALSE) } == FALSE {
406        return Err(io::Error::last_os_error());
407    };
408    Ok(token)
409}
410
411impl Drop for DebugToken {
412    fn drop(&mut self) {
413        unsafe { winapi::um::debugapi::DebugActiveProcessStop(self.pid) };
414    }
415}
416```
417
418Once again, we create a wrapper `struct` with `Drop` to stop debugging the process once the token is dropped. The call to `DebugSetProcessKillOnExit` in our `debug` method ensures that, if our process (the debugger) dies, the process we're debugging (the debuggee) stays alive. We don't want to be restarting the entire Cheat Engine tutorial every time our Rust code crashes!
419
420With the debugger attached, we can wait for debug events. We will put this method inside of `impl DebugToken`, so that the only way you can call it is if you successfully attached to another process:
421
422```rust
423impl DebugToken {
424    pub fn wait_event(
425        &self,
426        timeout: Option<Duration>,
427    ) -> io::Result<winapi::um::minwinbase::DEBUG_EVENT> {
428        let mut result = MaybeUninit::uninit();
429        let timeout = timeout
430            .map(|d| d.as_millis().try_into().ok())
431            .flatten()
432            .unwrap_or(winapi::um::winbase::INFINITE);
433
434        // SAFETY: can only wait for events with a token, so the debugger is active.
435        if unsafe { winapi::um::debugapi::WaitForDebugEvent(result.as_mut_ptr(), timeout) } == FALSE
436        {
437            Err(io::Error::last_os_error())
438        } else {
439            // SAFETY: the call returned non-zero, so the structure is initialized.
440            Ok(unsafe { result.assume_init() })
441        }
442    }
443}
444```
445
446`WaitForDebugEvent` wants a timeout in milliseconds, so our function lets the user pass the more Rusty `Duration` type. `None` will indicate "there is no timeout", i.e., it's infinite. If the duration is too large to fit in the `u32` (`try_into` fails), it will also be infinite.
447
448If we attach the debugger, set the hardware watchpoint, and modify the memory location from the tutorial, an event with `dwDebugEventCode = 3` will be returned! Now, back to the page with the [Debugging Events][dbg-events]… Gah! It only has the name of the constants, not the values. Well, good thing [docs.rs] has a source view! We can just check the values in the [source code for `winapi`][winapi-dbg-event-src]:
449
450```rust
451pub const EXCEPTION_DEBUG_EVENT: DWORD = 1;
452pub const CREATE_THREAD_DEBUG_EVENT: DWORD = 2;
453pub const CREATE_PROCESS_DEBUG_EVENT: DWORD = 3;
454pub const EXIT_THREAD_DEBUG_EVENT: DWORD = 4;
455pub const EXIT_PROCESS_DEBUG_EVENT: DWORD = 5;
456pub const LOAD_DLL_DEBUG_EVENT: DWORD = 6;
457pub const UNLOAD_DLL_DEBUG_EVENT: DWORD = 7;
458pub const OUTPUT_DEBUG_STRING_EVENT: DWORD = 8;
459pub const RIP_EVENT: DWORD = 9;
460```
461
462So, we've got a `CREATE_PROCESS_DEBUG_EVENT`:
463
464> Generated whenever a new process is created in a process being debugged or whenever the debugger begins debugging an already active process. The system generates this debugging event before the process begins to execute in user mode and before the system generates any other debugging events for the new process.
465
466It makes sense that this is our first event. By the way, if you were trying this out with a `sleep` lying around in your code, you may have noticed that the window froze until the debugger terminated. That's because:
467
468> When the system notifies the debugger of a debugging event, it also suspends all threads in the affected process. The threads do not resume execution until the debugger continues the debugging event by using [`ContinueDebugEvent`][cont-dbg].
469
470Let's call `ContinueDebugMethod` but also wait on more than one event and see what happens:
471
472```rust
473for _ in 0..10 {
474    let event = debugger.wait_event(None).unwrap();
475    println!("Got {}", event.dwDebugEventCode);
476    debugger.cont(event, true).unwrap();
477}
478```
479
480```
481Got 3
482Got 6
483Got 6
484Got 6
485Got 6
486Got 6
487Got 6
488Got 6
489Got 6
490Got 6
491```
492
493That's a lot of `LOAD_DLL_DEBUG_EVENT`. Pumping it up to one hundred and also showing the index we get the following:
494
495```
4960. Got 3
4971. Got 6
498...
49940. Got 6
50041. Got 2
50142. Got 1
50243. Got 4
503```
504
505In order, we got:
506
507* One `CREATE_PROCESS_DEBUG_EVENT`.
508* Forty `LOAD_DLL_DEBUG_EVENT`.
509* One `CREATE_THREAD_DEBUG_EVENT`.
510* One `EXCEPTION_DEBUG_EVENT`.
511* One `EXIT_THREAD_DEBUG_EVENT`.
512
513And, if after all this, you change the value in the Cheat Engine tutorial (thus triggering our watch point), we get `EXCEPTION_DEBUG_EVENT`!
514
515> Generated whenever an exception occurs in the process being debugged. Possible exceptions include attempting to access inaccessible memory, executing breakpoint instructions, attempting to divide by zero, or any other exception noted in Structured Exception Handling.
516
517If we print out all the fields in the [`EXCEPTION_DEBUG_INFO`][exc-dbg-info] structure:
518
519```
520Watching writes to 10e3a0 for 10s
521First chance: 1
522ExceptionCode: 2147483652
523ExceptionFlags: 0
524ExceptionRecord: 0x0
525ExceptionAddress: 0x10002c5ba
526NumberParameters: 0
527ExceptionInformation: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
528```
529
530The `ExceptionCode`, which is `0x80000004`, corresponds with `EXCEPTION_SINGLE_STEP`:
531
532> A trace trap or other single-instruction mechanism signaled that one instruction has been executed.
533
534The `ExceptionAddress` is supposed to be "the address where the exception occurred". Very well! I have already completed this step of the tutorial, and I know the instruction is `mov [rax],edx` (or, as Cheat Engine shows, the bytes `89 10` in hexadecimal). The opcode for the `nop` instruction is `90` in hexadecimal, so if we replace two bytes at this address, we should be able to complete the tutorial.
535
536Note that we also need to flush the instruction cache, as noted in the Windows documentation:
537
538> Debuggers frequently read the memory of the process being debugged and write the memory that contains instructions to the instruction cache. After the instructions are written, the debugger calls the [`FlushInstructionCache`][flush-ins] function to execute the cached instructions.
539
540So we add a new method to `impl Process`:
541
542```rust
543/// Flushes the instruction cache.
544///
545/// Should be called when writing to memory regions that contain code.
546pub fn flush_instruction_cache(&self) -> io::Result<()> {
547    // SAFETY: the call doesn't have dangerous side-effects.
548    if unsafe {
549        winapi::um::processthreadsapi::FlushInstructionCache(
550            self.handle.as_ptr(),
551            ptr::null(),
552            0,
553        )
554    } == FALSE
555    {
556        Err(io::Error::last_os_error())
557    } else {
558        Ok(())
559    }
560}
561```
562
563And write some quick and dirty code to get this done:
564
565```rust
566let addr = ...;
567println!("Watching writes to {:x} for 10s", addr);
568threads.iter_mut().for_each(|thread| {
569    thread.watch_memory_write(addr).unwrap();
570});
571loop {
572    let event = debugger.wait_event(None).unwrap();
573    if event.dwDebugEventCode == 1 {
574        let exc = unsafe { event.u.Exception() };
575        if exc.ExceptionRecord.ExceptionCode == 2147483652 {
576            let addr = exc.ExceptionRecord.ExceptionAddress as usize;
577            match process.write_memory(addr, &[0x90, 0x90]) {
578                Ok(_) => eprintln!("Patched [{:x}] with NOP", addr),
579                Err(e) => eprintln!("Failed to patch [{:x}] with NOP: {}", addr, e),
580            };
581            process.flush_instruction_cache().unwrap();
582            debugger.cont(event, true).unwrap();
583            break;
584        }
585    }
586    debugger.cont(event, true).unwrap();
587}
588```
589
590Although it seems to work:
591
592```
593Watching writes to 15103f0 for 10s
594Patched [10002c5ba] with NOP
595```
596
597It really doesn't:
598
599> **Tutorial-x86_64**
600>
601> Access violation.
602>
603> Press OK to ignore and risk data corruption.\
604> Press Abort to kill the program.
605>
606> <kbd>OK</kbd> <kbd>Abort</kbd>
607
608Did we write memory somewhere we shouldn't? The documentation does mention "segment-relative" and "linear virtual addresses":
609
610> `GetThreadSelectorEntry` returns the descriptor table entry for a specified selector and thread. Debuggers use the descriptor table entry to convert a segment-relative address to a linear virtual address. The `ReadProcessMemory` and `WriteProcessMemory` functions require linear virtual addresses.
611
612But nope! This isn't the problem. The problem is that the `ExceptionRecord.ExceptionAddress` is *after* the execution happened, so it's already 2 bytes beyond where it should be. We were accidentally writing out the first half of the next instruction, which, yeah, could not end good.
613
614So does it work if I do this instead?:
615
616```rust
617process.write_memory(addr - 2, &[0x90, 0x90])
618//                        ^^^ new
619```
620
621This totally does work. Step 5: complete 🎉
622
623## Properly patching instructions
624
625You may not be satisfied at all with our solution. Not only are we hardcoding some magic constants to set hardware watchpoints, we're also relying on knowledge specific to the Cheat Engine tutorial (insofar that we're replacing two bytes worth of instruction with NOPs).
626
627Properly supporting more than one hardware breakpoint, along with supporting different types of breakpoints, is definitely doable. The meaning of the bits for the debug registers is well defined, and you can definitely study that to come up with [something more sophisticated][cpp-many-brk] and support multiple different breakpoints. But for now, that's out of the scope of this series. The tutorial only wants us to use an on-write watchpoint, and our solution is fine and portable for that use case.
628
629However, relying on the size of the instructions is pretty bad. The instructions x86 executes are of variable length, so we can't possibly just look back until we find the previous instruction, or even naively determine its length. A lot of unrelated sequences of bytes are very likely instructions themselves. We need a disassembler. No, we're not writing our own.
630
631Searching on [crates.io] for "disassembler" yields a few results, and the first one I've found is [iced-x86]. I like the name, it has a decent amount of GitHub stars, and it was last updated less than a month ago. I don't know about you, but I think we've just hit a jackpot!
632
633It's quite heavy though, so I will add it behind a feature gate, and users that want it may opt into it:
634
635```toml
636[features]
637patch-nops = ["iced-x86"]
638
639[dependencies]
640iced-x86 = { version = "1.10.3", optional = true }
641```
642
643You can make use of it with `cargo run --features=patch-nops`. I don't want to turn this blog post into a tutorial for `iced-x86`, but in essence, we need to make use of its `Decoder`. Here's the plan:
644
6451. Find the memory region corresponding to the address we want to patch.
6462. Read the entire region.
6473. Decode the read bytes until the instruction pointer reaches our address.
6484. Because we just parsed the previous instruction, we know its length, and can be replaced with NOPs.
649
650```rust
651#[cfg(feature = "patch-nops")]
652pub fn nop_last_instruction(&self, addr: usize) -> io::Result<()> {
653    use iced_x86::{Decoder, DecoderOptions, Formatter, Instruction, NasmFormatter};
654
655    let region = self
656        .memory_regions()
657        .into_iter()
658        .find(|region| {
659            let base = region.BaseAddress as usize;
660            base <= addr && addr < base + region.RegionSize
661        })
662        .ok_or_else(|| io::Error::new(io::ErrorKind::Other, "no matching region found"))?;
663
664    let bytes = self.read_memory(region.BaseAddress as usize, region.RegionSize)?;
665
666    let mut decoder = Decoder::new(64, &bytes, DecoderOptions::NONE);
667    decoder.set_ip(region.BaseAddress as _);
668
669    let mut instruction = Instruction::default();
670    while decoder.can_decode() {
671        decoder.decode_out(&mut instruction);
672        if instruction.next_ip() as usize == addr {
673            return self
674                .write_memory(instruction.ip() as usize, &vec![0x90; instruction.len()])
675                .map(drop);
676        }
677    }
678
679    Err(io::Error::new(
680        io::ErrorKind::Other,
681        "no matching instruction found",
682    ))
683}
684```
685
686Pretty straightforward! We can set the "instruction pointer" of the decoder so that it matches with the address we're reading from. The `next_ip` method comes in really handy. Overall, it's a bit inefficient, because we could reuse the regions retrieved previously, but other than that, there is not much room for improvement.
687
688With this, we are no longer hardcoding the instruction size or guessing which instruction is doing what. You may wonder, what if the region does not start with valid executable code? It could be possible that the instructions are in some memory region with garbage except for a very specific location with real code. I don't know how Cheat Engine handles this, but I think it's reasonable to assume that the region starts with valid code. If you can think of any more reliable way to figure out the instruction right before a given address, please let me know!
689
690## Finale
691
692That was quite a deep dive! We have learnt about the existence of the various breakpoint types (software, hardware, and even behaviour, such as watchpoints), how to debug a separate process, and how to correctly update the code other process is running on-the-fly. The [code for this post][code] is available over at my GitHub. You can run `git checkout step5` after cloning the repository to get the right version of the code.
693
694Although we've only talked about *setting* breakpoints, there are of course [ways of detecting them][detect-brk]. There's [entire guides about it][detect-brk-guide]. Again, we currently hardcode the fact we want to add a single watchpoint using the first debug register. A proper solution here would be to actually calculate the needs that need to be set, as well as keeping track of how many breakpoints have been added so far.
695
696Hardware breakpoints are also limited, since they're simply a bunch of registers, and our machine does not have infinite registers. How are other debuggers like `gdb` able to create a seemingly unlimited amount of breakpoints? Well, the GDB wiki actually has a page on [Internals Watchpoints][gdb-watchpoints], and it's really interesting! `gdb` essentially single-steps through the entire program and tests the expressions after every instruction:
697
698> Software watchpoints are very slow, since GDB needs to single-step the program being debugged and test the value of the watched expression(s) after each instruction.
699
700However, that's not the only way. One could [change the protection level][change-prot] of the region of interest (for example, remove the write permission), and when the program tries to write there, it will fail! In any case, the GDB wiki is actually a pretty nice resource. It also has a section on [Breakpoint Handling][gdb-breakpoints], which contains some additional insight.
701
702With regards to code improvements, `DebugToken::wait_event` could definitely be both nicer and safer to use, with a custom `enum`, so the user does not need to rely on magic constants or having to resort to `unsafe` access to get the right `union` variant.
703
704In the next post, we'll tackle the sixth step of the tutorial: Pointers. It reuses the debugging techniques presented here to backtrack where the pointer for our desired value is coming from, so here we will need to actually *understand* what the instructions are doing, not just patching them out!
705
706### Footnotes
707
708[^1]: I'm not super happy about the design of it all, but we won't actually need anything beyond scanning for integers for the rest of the steps so it doesn't really matter.
709
710[^2]: There seems to be a way to pause the entire process in one go, with the [undocumented `NtSuspendProcess`] function!
711
712[^3]: It really is called that. The naming went from "IP" (instruction pointer, 16 bits), to "EIP" (extended instruction pointer, 32 bits) and currently "RIP" (64 bits). The naming convention for upgraded registers is the same (RAX, RBX, RCX, and so on). The [OS Dev wiki][osdev-wiki] is a great resource for this kind of stuff.
713
714[debug-series]: http://system.joekain.com/debugger/
715[win-basic-dbg]: https://docs.microsoft.com/en-us/windows/win32/debug/creating-a-basic-debugger
716[dbg-func]: https://docs.microsoft.com/en-us/windows/win32/debug/debugging-functions
717[dbg-c]: https://www.gironsec.com/blog/2013/12/writing-your-own-debugger-windows-in-c/
718[suspend-thread]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-suspendthread
719[thread-ctx]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-getthreadcontext
720[dbg-break]: https://docs.microsoft.com/en-us/windows/win32/api/winbase/nf-winbase-debugbreakprocess
721[0xcc]: https://docs.microsoft.com/en-us/windows-hardware/drivers/debugger/x86-instructions#miscellaneous
722[how-c-brk]: https://stackoverflow.com/q/3915511/
723[cont-dbg]: https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-continuedebugevent
724[dbg-events]: https://docs.microsoft.com/en-us/windows/win32/debug/debugging-events
725[how-int3]: https://stackoverflow.com/q/3747852/
726[hw-brk]: https://en.wikipedia.org/wiki/Breakpoint#Hardware
727[cortex-m]: https://interrupt.memfault.com/blog/cortex-m-breakpoints
728[x86-dbg-reg]: https://stackoverflow.com/a/19109153/
729[asm-macro]: https://doc.rust-lang.org/stable/unstable-book/library-features/asm.html
730[dbg-reg]: https://en.wikipedia.org/wiki/X86_debug_register
731[toolhelp]: https://stackoverflow.com/a/1206915/
732[create-snapshot]: https://docs.microsoft.com/en-us/windows/win32/api/tlhelp32/nf-tlhelp32-createtoolhelp32snapshot
733[open-thread]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-openthread
734[howto-hw-brk]: https://social.msdn.microsoft.com/Forums/en-US/0cb3360d-3747-42a7-bc0e-668c5d9ee1ee/how-to-set-a-hardware-breakpoint
735[wow64-ctx]: https://stackoverflow.com/q/17504174/
736[dbg-active]: https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-debugactiveprocess
737[docs.rs]: https://docs.rs/
738[winapi-dbg-event-src]: https://docs.rs/winapi/0.3.9/src/winapi/um/minwinbase.rs.html#203-211
739[cont-dbg]: https://docs.microsoft.com/en-us/windows/win32/api/debugapi/nf-debugapi-continuedebugevent
740[exc-dbg-info]: https://docs.microsoft.com/en-us/windows/win32/api/minwinbase/ns-minwinbase-exception_debug_info
741[flush-ins]: https://docs.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-flushinstructioncache
742[crates.io]: https://crates.io
743[iced-x86]: https://crates.io/crates/iced-x86
744[detect-brk]: https://reverseengineering.stackexchange.com/a/16547
745[detect-brk-guide]: https://www.codeproject.com/Articles/30815/An-Anti-Reverse-Engineering-Guide
746[gdb-watchpoints]: https://sourceware.org/gdb/wiki/Internals%20Watchpoints
747[gdb-breakpoints]: https://sourceware.org/gdb/wiki/Internals/Breakpoint%20Handling
748[cpp-many-brk]: https://github.com/mmorearty/hardware-breakpoints
749[change-prot]: https://stackoverflow.com/a/7805842/
750[suspend-proc]: https://stackoverflow.com/a/4062698/
751[osdev-wiki]: https://wiki.osdev.org/CPU_Registers_x86_64
752[code]: https://github.com/lonami/memo