Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
MinHook-rs
A Rust implementation of the MinHook library for Windows x64 function hooking.
Features
- Precise instruction decoder - Custom x64 disassembler optimized for hook creation
- Thread-safe operations - All APIs are thread-safe with proper synchronization
- Memory efficient - Minimal memory footprint with optimized data structures
- Comprehensive error handling - Detailed error reporting for all edge cases
- Production ready - Extensively tested with multiple hook scenarios
- Zero-copy design - Efficient instruction processing without unnecessary allocations
Quick Start
Add to your Cargo.toml:
[]
= "1.2.0"
= { = "0.60", = ["Win32_UI_WindowsAndMessaging"] }
Basic usage:
use *;
use c_void;
use ptr;
// Define original function type
type MessageBoxAFn = unsafe extern "system" fn ;
static mut ORIGINAL_MESSAGEBOX: = None;
// Your hook function
unsafe extern "system"
Examples
Basic Hook Example
Run our comprehensive example that demonstrates all MinHook-rs features:
This example includes:
- Basic hook functionality with MessageBoxA interception
- Multiple simultaneous hooks (MessageBoxA + GetTickCount)
- Dynamic enable/disable cycles for stress testing
- Queued operations with batch application
- Comprehensive error handling and edge cases
- Recursive call handling and safety verification
- High-frequency performance testing with 1000+ calls
- Memory safety verification under stress conditions
The example runs 12 test phases covering all functionality aspects with detailed output and performance metrics.
MessageBox Hook Examples
The examples/messagebox/ directory contains comprehensive MessageBox hooking examples:
simple_messagebox_hook.rs: DLL that hooks MessageBoxA to replace all message contentsimple_injector.rs: Generic DLL injector for testing hooksmessagebox_test.rs: Test program that displays multiple MessageBox dialogs
Build and test:
# Build all components
# Start test program
&
# Find PID and inject DLL
|
Notepad Hook Examples
The examples/notepad/ directory demonstrates real-world application hooking:
notepad_hook_dll.rs: Hooks Notepad's exit confirmation dialognotepad_injector.rs: Specialized injector for Notepad processes
Build and test:
# Build and inject into Notepad
&
|
x86_64 Instruction Format and Disassembler
Understanding x86_64 instruction encoding is crucial for reliable function hooking. MinHook-rs includes a custom instruction decoder designed specifically for hook creation.
Instruction Structure
x86_64 instructions use variable-length encoding with up to 7 components:
[Prefixes] [REX] [Opcode] [ModR/M] [SIB] [Displacement] [Immediate]
0-4 0-1 1-3 0-1 0-1 0-8 0-8
Components:
- Prefixes: Operation size, segment, repeat behavior overrides
- REX Prefix: 64-bit extensions for registers and operand size
- Opcode: 1-3 bytes defining the instruction operation
- ModR/M: Addressing mode and register selection
- SIB: Scale-Index-Base for complex memory addressing
- Displacement: Memory offset values (8/16/32-bit)
- Immediate: Constant operand data (8/16/32/64-bit)
Hook-Critical Instructions
RIP-Relative Addressing:
mov rax, [rip + 0x12345678] ; Requires address relocation in trampolines
lea rax, [rip + 0x1000] ; PC-relative memory references
call [rip + offset] ; Indirect calls through memory
Control Flow Instructions:
call relative_addr ; Direct relative calls
jmp short_offset ; Short jumps (8-bit offset)
jcc long_offset ; Conditional jumps (32-bit offset)
ret ; Return instructions
Complex Addressing:
mov rax, [rbp + rsi*2 + 8] ; Scale-index-base with displacement
mov [rsp + 0x100], rbx ; Stack operations with large offsets
Decoder Features
MinHook-rs provides a specialized decoder optimized for hooking:
Key Methods:
is_rip_relative()- Detect instructions requiring address relocationis_call(),is_jmp(),is_conditional()- Control flow classificationimmediate_size()- Calculate immediate field length for relocationmodrm_reg()- Extract register fields for indirect jump detection
HDE64 Compatibility
The decoder maintains full compatibility with the proven HDE64 algorithm:
- Table-driven approach: Uses comprehensive opcode lookup tables
- Multi-stage parsing: Prefix → REX → Opcode → ModR/M → Operands
- Error handling: Graceful handling of malformed instructions
- Length accuracy: 100% accurate instruction length calculation
API Reference
Core Functions
| Function | Description |
|---|---|
initialize() |
Initialize the library |
uninitialize() |
Cleanup and uninitialize |
create_hook(target, detour) |
Create a hook for a function |
create_hook_api(module, func, detour) |
Create a hook by module/function name |
enable_hook(target) |
Enable a hook |
disable_hook(target) |
Disable a hook |
remove_hook(target) |
Remove a hook |
Batch Operations
| Function | Description |
|---|---|
enable_hook(ALL_HOOKS) |
Enable all hooks |
disable_hook(ALL_HOOKS) |
Disable all hooks |
queue_enable_hook(target) |
Queue hook for enable |
queue_disable_hook(target) |
Queue hook for disable |
apply_queued() |
Apply all queued operations |
Disassembler API
| Function | Description |
|---|---|
decode_instruction(code) |
Decode a single instruction |
can_hook_safely(code, len) |
Check if code region can be safely hooked |
Utility Functions
| Function | Description |
|---|---|
is_supported() |
Check if current platform is supported |
status_to_string(error) |
Convert error to string description |
Error Handling
MinHook-rs provides comprehensive error handling:
Architecture
MinHook-rs works by patching target functions and redirecting execution:
Original: [Target Function] → [Function Body] → [Return]
Hooked: [Target Function] → [Hook Function] → [Trampoline] → [Original Body] → [Return]
Hook Installation Process:
- Analysis: Decode instructions at target address for safe hook points
- Trampoline: Allocate nearby memory and copy original instructions
- Relocation: Fix RIP-relative addresses for new trampoline location
- Installation: Replace target function start with jump to detour
- Execution: Detour function calls original via trampoline
Platform Support
- Windows x64: Full support
- Windows x86: Not supported
- Linux/macOS: Windows-specific
Performance
MinHook-rs is optimized for production use:
- Low overhead: Minimal impact on hooked function performance
- Fast decoding: Optimized instruction parsing with table lookups
- Memory efficient: Small trampoline footprint and optimized data structures
- Thread safety: Lock-free operations where possible
Benchmarks show excellent performance characteristics:
- Hook creation: Sub-millisecond trampoline generation
- Runtime overhead: Near-zero impact on function execution
- Memory usage: Minimal footprint with efficient instruction decoding
Best Practices
Hook Function Design
// Always match the exact signature of the target function
type TargetFn = unsafe extern "system" fn ;
static mut ORIGINAL: = None;
unsafe extern "system"
Error Handling
// Handle all possible error conditions
match create_hook_api
Cleanup
// Always cleanup in reverse order
disable_hook?;
remove_hook?;
uninitialize?;
License
MIT License - see LICENSE file.