Hpmason / retour-rs

A cross-platform detour library written in Rust
Other
99 stars 18 forks source link
# `retour` (a `detour` Fork) [![Crates.io][crates-badge]][crates-url] [![docs.rs][docs-badge]][docs-url] [![Lcense][license-badge]][license-url] [![Cargo Check/Tests][actions-badge]][actions-url]

(Fork of original detour-rs that works on nightly after nightly-2022-11-07)

This is a cross-platform detour library developed in Rust. Beyond the basic functionality, this library handles branch redirects, RIP-relative instructions, hot-patching, NOP-padded functions, and allows the original function to be called using a trampoline whilst hooked.

This is one of few cross-platform detour libraries that exists, and to maintain this feature, not all desired functionality can be supported due to lack of cross-platform APIs. Therefore EIP relocation is not supported.

NOTE: Nightly is currently required for static_detour! and is enabled with the static-detour feature flag.

Platforms

This library provides CI for these targets:

Installation

Add this to your Cargo.toml:

[dependencies]
# `static-detour` feature requires nightly
retour = { version = "0.3", features = ["static-detour"] }

Supported Versions

This crate, with default features, will support the MSRV in Cargo.toml (currently 1.60.0). Certain features may require newer versions of the compiler, which will be documented here and in the docs. Any features that require the nightly compiler will always target the newest version.

Feature versions:

Example

use std::error::Error;
use retour::static_detour;

static_detour! {
  static Test: /* extern "X" */ fn(i32) -> i32;
}

fn add5(val: i32) -> i32 {
  val + 5
}

fn add10(val: i32) -> i32 {
  val + 10
}

fn main() -> Result<(), Box<dyn Error>> {
  // Reroute the 'add5' function to 'add10' (can also be a closure)
  unsafe { Test.initialize(add5, add10)? };

  assert_eq!(add5(1), 6);
  assert_eq!(Test.call(1), 6);

  // Hooks must be enabled to take effect
  unsafe { Test.enable()? };

  // The original function is detoured to 'add10'
  assert_eq!(add5(1), 11);

  // The original function can still be invoked using 'call'
  assert_eq!(Test.call(1), 6);

  // It is also possible to change the detour whilst hooked
  Test.set_detour(|val| val - 5);
  assert_eq!(add5(5), 0);

  unsafe { Test.disable()? };

  assert_eq!(add5(1), 6);
  Ok(())
}

Mentions

This is fork of the original detour-rs creator darfink that put so much work into the original crate.

Part of the library's external user interface was inspired by minhook-rs, created by Jascha-N, and it contains derivative code of his work.

Injection Methods

This crate provides the ability to hook functions in other applications, but does not provide the utilities necessary for injecting/attaching to another process. If you're looking for ways to inject your hooking library here are some approaches you can look into:

Appendix