Hooks and code
Same ideas as tweaks, from code.
Finding things
Section titled “Finding things”addresses.resolve(text, names) takes the same address text tweaks do, and gives where it is now. names are extra names the text can use, often none.
import { Wraith } from "wraith";
const addresses = Wraith.addresses();
const takeDamage = addresses.resolve('sig("40 53 48 83 EC 20")', []);const player = addresses.resolve("[game.exe+0x2F00A0] + 0x10", []);local Wraith = require("wraith").Wraithlocal addresses, hooks, code = Wraith.addresses(), Wraith.hooks(), Wraith.code()
local take_damage = addresses:resolve('sig("40 53 48 83 EC 20")', {})local player = addresses:resolve("[game.exe+0x2F00A0] + 0x10", {})var addresses = Addresses.Instance;var takeDamage = addresses.Resolve("sig(\"40 53 48 83 EC 20\")", []);var player = addresses.Resolve("[game.exe+0x2F00A0] + 0x10", []);Your schemas’ functions and statics are found by name with schema().address, like TrailsHorizon::GameStateManager_spendMira_name.
auto addresses = wraith::api().addresses();
auto take_damage = addresses.resolve(R"(sig("40 53 48 83 EC 20"))", {});auto player = addresses.resolve("[game.exe+0x2F00A0] + 0x10", {});Your schemas’ functions and statics are found by name with schema().address, like schema::GAME_STATE_MANAGER_SPEND_MIRA_NAME.
let addresses = wraith::api().addresses();
let take_damage = addresses.resolve(r#"sig("40 53 48 83 EC 20")"#, &[]).ok()?;let player = addresses.resolve("[game.exe+0x2F00A0] + 0x10", &[]).ok()?;ctx.wraith.addresses().resolve works as in other languages. The SDK can also scan the game’s code itself, which is Zig only.
const text = try sdk.Module.main().text();const take_damage = text.scan("take_damage", "40 53 48 83 EC 20");The name shows up in the Workbench’s Names panel, which helps when one stops matching. A scan like that only reads the code as it is now. sdk.signatures.find goes through Wraith like a schema’s [Sig], so it’s listed, reused and finds hooked code too.
const found = try sdk.signatures.find(.{ .pattern = "40 53 48 83 EC 20", .first_match = true });// found.address, and found.source: .live, .snapshot or .diskYour schemas’ functions and statics are found by name with Wraith_Schema_address, like TrailsHorizon_GameStateManager_spendMira_name.
Wraith_Addresses addresses = Wraith_Api_addresses(w);
uintptr_t take_damage = 0, player = 0;Wraith_Addresses_resolve(addresses, SAL_STR("sig(\"40 53 48 83 EC 20\")"), (Slice_Wraith_Addresses_Name){ 0 }, &take_damage);Wraith_Addresses_resolve(addresses, SAL_STR("[game.exe+0x2F00A0] + 0x10"), (Slice_Wraith_Addresses_Name){ 0 }, &player);What your schemas declare doesn’t need any of this. Each struct’s addresses give where its methods and statics are, like GameStateManager.addresses.spendMira(), and your namespace’s give the top-level ones. Hooks take the function itself, see below.
If another mod hooked the function first, its bytes aren’t there anymore. Lookups then try the snapshot of the game’s code from when Wraith started, then the game’s exe on disk, as schemas do. addresses.find is addresses.resolve that also says which it was found in, as an address and a source. Anything but live means something changed those bytes, so a patch expecting them will fail.
addresses.setSources says which copies your plugin’s lookups use, its schemas’ [Sig]s too, with live, snapshot and disk each on or off. Till you call it, Wraith’s Find hooked code setting says.
Hook a function
Section titled “Hook a function”A hook sends calls to a game function to your handler instead. Declare the function in a schema and hook it by passing the function itself, so the hook is typed as declared. Wraith only needs to know where it is, so there’s no name to spell out. The examples here are from a plugin with the id trails_horizon, so its namespace is TrailsHorizon, with this schema:
[Instance("48 8B 0D ?? ?? ?? ?? 3D", Rip)]struct GameStateManager { [Sig("E8 ?? ?? ?? ?? 48 8B 0D ?? ?? ?? ?? F3 0F 10 36", Rip)] u32 spendMira(u32 amount);}The handler gets the game’s arguments, with self first for a method. It can also ask for two more things:
- The hook, whose
original()is the function as it was, typed like the declared one. Call it to run the game’s code. - The context, a number you set in the options. It’s handy when one handler serves several hooks.
How it asks depends on the language, see each tab. A [Virtual(n)] method works the same, and Wraith swaps its slot in the struct’s [VirtualTable] for you.
hookAt does the same for a function at an address of your own, typed like a declared one. That’s handy for a copy of a function the game has somewhere else.
Set disabled in the options to start a hook off, then enable() once it’s set up. disable() turns it off again and destroy() puts the code back. Wraith puts everything back when the plugin goes.
Pass the function from your namespace, like GameStateManager.spendMira. The handler’s parameters are matched by name. One named hook gets the hook, one named context gets the context, and the rest are the game’s arguments in order. TypeScript can’t type parameters by their names, so the typings put hook and context after the arguments. Write them last, and leave them off when you don’t need them.
import { Wraith, TrailsHorizon } from "wraith";
const { GameStateManager } = TrailsHorizon;const hooks = Wraith.hooks();
// Shops still take your Mira, just none of itconst freeShopping = hooks.hook(GameStateManager.spendMira, (self, _amount, hook) => hook.original()(self, 0), { disabled: true });freeShopping.enable();hook.original() is typed like GameStateManager.spendMira, so it takes the same arguments. The hook also has context, enable(), disable() and destroy().
With a context, one handler can serve several hooks:
// Half price with 2, a third with 3const discount = (by: number) => hooks.hook(GameStateManager.spendMira, (self, amount, hook, context) => hook.original()(self, Math.floor(amount / context)), { context: by, disabled: true });hooks.hookAt(address, target, handler, options) hooks your own address, typed like target:
const copy = Wraith.addresses().resolve('sig("40 53 48 89 5C 24 08")', []);hooks.hookAt(copy, GameStateManager.spendMira, (self, amount, hook) => hook.original()(self, amount * 2), {});Pass the function from your namespace, like game.GameStateManager.spendMira. The handler’s parameters are matched by name, wherever they are. One named hook gets the hook, one named context gets the context, and the rest are the game’s arguments in order. This one takes the hook first, like Zig does.
local wraith = require("wraith")local Wraith, game = wraith.Wraith, wraith.TrailsHorizonlocal hooks = Wraith.hooks()
-- Shops still take your Mira, just none of itlocal free_shopping = hooks:hook(game.GameStateManager.spendMira, function(hook, self, _) return hook.original()(self, 0)end, { disabled = true })free_shopping:enable()Inside the handler, hook.original() is the function as it was, and the hook also has hook.context, hook.enable(), hook.disable() and hook.destroy(). What hooks:hook gives is a plain hook, so it’s free_shopping:enable() with a colon.
With a context, one handler can serve several hooks:
-- Half price with 2, a third with 3local function discount(by) return hooks:hook(game.GameStateManager.spendMira, function(hook, context, self, amount) return hook.original()(self, amount // context) end, { context = by, disabled = true })endhooks:hookAt(address, target, handler, options) hooks your own address, typed like target:
local copy = Wraith.addresses():resolve('sig("40 53 48 89 5C 24 08")', {})hooks:hookAt(copy, game.GameStateManager.spendMira, function(hook, self, amount) return hook.original()(self, amount * 2)end, {})Each declared function has a value under its owner’s Fns, like GameStateManager.Fns.SpendMira. Top-level ones are under your namespace’s Schema.Fns. Give Hook a handler with just the arguments, or one with the hook first. hook.Original() is a typed function pointer to the function as it was, and hook.Context is the context. Calling a function pointer needs an unsafe class.
using Wraith;
namespace TrailsHorizon{ sealed unsafe class Main : WraithPlugin { Hook? freeShopping;
public override void Start(Context context) { // Shops still take your Mira, just none of it freeShopping = Hooks.Instance.Hook(GameStateManager.Fns.SpendMira, (hook, self, _) => hook.Original()(self, 0), new Hook.Options { Disabled = true }); freeShopping.Enable(); } }}With a context, one handler can serve several hooks:
// Half price with 2, a third with 3Hook Discount(nuint by) => Hooks.Instance.Hook(GameStateManager.Fns.SpendMira, (hook, self, amount) => hook.Original()(self, amount / (uint)hook.Context), new Hook.Options { Context = by, Disabled = true });Hooks.Instance.HookAt(address, GameStateManager.Fns.SpendMira, handler, options) hooks your own address, typed like the declared one.
Native code hooks with a function of its own. Find the declared function with schema().address, and give hooks().detourNative a function of the same type as its pointer type, like TrailsHorizon::GameStateManager_spendMira_fn. original() is an address, so call it through that type. hooks().context() gives the context inside the handler.
#include "schema.hpp"
using TrailsHorizon::GameStateManager;static Wraith::Hook free_shopping;
// Shops still take your Mira, just none of itstatic uint32_t spend_mira(GameStateManager* self, uint32_t) { return reinterpret_cast<TrailsHorizon::GameStateManager_spendMira_fn>(free_shopping.original())(self, 0);}
// in startif (auto at = wraith::api().schema().address(TrailsHorizon::GameStateManager_spendMira_name)) { if (auto made = wraith::api().hooks().detourNative(*at, reinterpret_cast<uintptr_t>(&spend_mira), {.disabled = true})) { free_shopping = *made; free_shopping.enable(); }}It starts off, so free_shopping is set before the game can call it. For an address of your own, pass that to detourNative instead.
Native code hooks with a function of its own. Find the declared function with schema().address, and give hooks().detour_native a function of the same type as its pointer type, like schema::GameStateManagerSpendMiraFn. original() is an address, so call it through that type. hooks().context() gives the context inside the handler.
use std::sync::atomic::{AtomicUsize, Ordering};
use schema::{GameStateManager, GameStateManagerSpendMiraFn};use wraith::HookOptions;
static ORIGINAL: AtomicUsize = AtomicUsize::new(0);
// Shops still take your Mira, just none of itunsafe extern "C" fn spend_mira(this: *mut GameStateManager, _amount: u32) -> u32 { let original: GameStateManagerSpendMiraFn = unsafe { std::mem::transmute(ORIGINAL.load(Ordering::Acquire)) }; unsafe { original(this, 0) }}
fn free_shopping() -> Option<()> { let api = wraith::api(); let at = api.schema().address(schema::GAME_STATE_MANAGER_SPEND_MIRA_NAME).ok()?; let hook = api.hooks().detour_native(at, spend_mira as usize, HookOptions { disabled: true, ..Default::default() }).ok()?; ORIGINAL.store(hook.original(), Ordering::Release); hook.enable().ok()?; Some(())}It starts off, so ORIGINAL is set before the game can call it. For an address of your own, pass that to detour_native instead.
sdk.hooks.hook takes the struct or namespace the function’s in, its name, a callback and a context, usually self. The callback can take the context and the hook first, in either order, or just one, or neither. They’re told apart by type. Then come the function’s arguments. The hook’s type is sdk.hooks.Hook(GameStateManager, .spendMira), and its original() is typed as declared.
const sdk = @import("wraith_sdk");const schema = @import("schema").TrailsHorizon;
const GameStateManager = schema.GameStateManager;const SpendHook = sdk.hooks.Hook(GameStateManager, .spendMira);
pub const Plugin = struct { spend_mira: SpendHook = undefined,
pub fn start(self: *Plugin, ctx: *sdk.Context) !void { _ = ctx; // Shops still take your Mira, just none of it self.spend_mira = try sdk.hooks.hook(GameStateManager, .spendMira, spendMira, self); try self.spend_mira.enable(); }
fn spendMira(_: *Plugin, hook: SpendHook, manager: *GameStateManager, _: u32) u32 { return hook.original()(manager, 0); }};These start off. Call enable() once it’s set up, or use sdk.hooks.hookWith with .{ .enabled = true }. A top-level function is in your namespace, like sdk.hooks.hook(schema, .update, update, self).
sdk.hooks.hookAt(GameStateManager, .spendMira, address, callback, context) hooks your own address, typed like the declared one, and hookAtWith takes options too.
Native code hooks with a function of its own. Find the declared function with Wraith_Schema_address, and give Wraith_Hooks_detourNative a function of the same type as its pointer type, like TrailsHorizon_GameStateManager_spendMira_fn. Wraith_Hook_original is an address, so call it through that type. Wraith_Hooks_context gives the context inside the handler.
#include "schema.h"
static Wraith_Hook free_shopping;
/* Shops still take your Mira, just none of it */static uint32_t spend_mira(TrailsHorizon_GameStateManager *self, uint32_t amount) { (void)amount; return ((TrailsHorizon_GameStateManager_spendMira_fn)Wraith_Hook_original(free_shopping))(self, 0);}
/* in start */uintptr_t at = 0;Wraith_Schema_address(Wraith_Api_schema(w), SAL_STR(TrailsHorizon_GameStateManager_spendMira_name), &at);Wraith_Hook_Options options = { .disabled = true };if (at && Wraith_Hooks_detourNative(Wraith_Api_hooks(w), at, (uintptr_t)&spend_mira, options, &free_shopping) == SAL_OK) { Wraith_Hook_enable(free_shopping);}It starts off, so free_shopping is set before the game can call it. For an address of your own, pass that to Wraith_Hooks_detourNative instead.
By hand
Section titled “By hand”The typed hooks above cover what your schemas declare. For a function that isn’t in a schema, or a quick experiment, hooks also take an address and a signature. Prefer the typed ones whenever you can.
hooks.detour(target, signature, handler, options)hooks the function attarget. The signature is like"fn i32 (i32 damage)".hooks.detourSlot(slot, signature, handler, options)swaps a function pointer, like one in a vtable.hooks.named(name, handler, options)hooks a declared function by its name as text, like"Player.heal".hooks.context()gives the running hook’s context from inside its handler.
Make the handler with fn from "salamander", and make the original callable with native. Both also take a declared function in place of a signature, like native(GameStateManager.spendMira, address), typed as declared.
import { Wraith } from "wraith";import { fn, native } from "salamander";
const sig = "fn i32 (i32 damage)";let original: (damage: number) => number;const hook = Wraith.hooks().detour(takeDamage, sig, fn(sig, (damage) => original(Math.floor(damage / 2))), {});original = native(sig, hook.original());Make the handler with sal.fn, and make the original callable with sal.native. Both also take a declared function in place of a signature, like sal.native(game.GameStateManager.spendMira, address).
local Wraith = require("wraith").Wraithlocal sal = require("salamander")
local sig = "fn i32 (i32 damage)"local originallocal hook = Wraith.hooks():detour(take_damage, sig, sal.fn(sig, function(damage) return original(damage // 2)end), {})original = sal.native(sig, hook:original())hooks.Named, hooks.Detour and hooks.DetourSlot want a handler from your schema with the same signature, like Schema.TakeDamageHandler(...), and Schema.TakeDamageAt(hook.Original()) makes the original callable.
Native code doesn’t need these. hooks().detourNative and detourSlotNative take a function of your own, as above.
Native code doesn’t need these. hooks().detour_native and detour_slot_native take a function of your own, as above.
sdk.hooks.createFn takes the function’s type, and createSlot hooks a function pointer. Their callbacks work like hook’s, and createFnWith and createSlotWith take options.
const TakeDamage = fn (i32) callconv(.c) i32;
fn onDamage(_: *Plugin, hook: sdk.hooks.FnHook(TakeDamage), damage: i32) i32 { return hook.original()(@divTrunc(damage, 2));}
// in startself.hook = try sdk.hooks.createFnWith(TakeDamage, take_damage, onDamage, self, .{ .enabled = true });Native code doesn’t need these. Wraith_Hooks_detourNative and Wraith_Hooks_detourSlotNative take a function of your own, as above.
Hook an instruction
Section titled “Hook an instruction”hooks.mid(target, options, handler) runs your handler right before an instruction, with the registers. Changes to them go back into the game. It’s for spots in the middle of a function, where there’s no function to hook.
expectchecks the bytes or asm there first, so it won’t hook a game that changed.sizeis how many bytes it takes over, ending between instructions. 0 means whatexpectcovers, or else the one instruction there. A mid hook can’t end inside an instruction, so giveexpectthe whole one.replacereplaces the code there rather than running before it.disabledstarts it off, like other hooks.
The address comes from your schema’s typed addresses, like any other spot. This one keeps part of each change to a gauge, so it fills slower. The game stores the new gauge from xmm7 into the struct rdi points at, so the schema has the spot and the struct:
[Sig("F3 0F 5F FE 0F 28 B4 24 ?? ?? ?? ?? F3 0F 11 BF", Offset(12))]static u8 tailing_gauge_store;
struct TailingState { [Offset(0xD4)] f32 gauge;}cpu.xmm7.f32x4[0] is the low float in xmm7.
import { Wraith, TrailsHorizon } from "wraith";
const { TailingState } = TrailsHorizon;let speed = 0.25;
const slowGauge = Wraith.hooks().mid(TrailsHorizon.addresses.tailing_gauge_store(), { expect: "F3 0F 11 BF D4 00 00 00", disabled: true }, (cpu) => { const state = TailingState.at(cpu.rdi); if (state) cpu.xmm7.f32x4[0] = state.gauge + (cpu.xmm7.f32x4[0] - state.gauge) * speed;});slowGauge.enable();cpu.xmm7.f32x4[1] is the low float in xmm7, since Lua counts from 1.
local wraith = require("wraith")local Wraith, game = wraith.Wraith, wraith.TrailsHorizonlocal speed = 0.25
local slow_gauge = Wraith.hooks():mid(game.addresses.tailing_gauge_store(), { expect = "F3 0F 11 BF D4 00 00 00", disabled = true }, function(cpu) local state = game.TailingState.at(cpu.rdi) if state then cpu.xmm7.f32x4[1] = state.gauge + (cpu.xmm7.f32x4[1] - state.gauge) * speed endend)slow_gauge:enable()cpu.Xmm7.F32x4[0] is the low float in xmm7. Reading rdi as a pointer needs an unsafe class.
float speed = 0.25f;
// in Startvar slowGauge = Hooks.Instance.Mid(Schema.Addresses.TailingGaugeStore(), new Hooks.MidOptions { Expect = "F3 0F 11 BF D4 00 00 00", Disabled = true }, (ref Cpu cpu) =>{ var state = (TailingState*)cpu.Rdi; cpu.Xmm7.F32x4[0] = state->Gauge + (cpu.Xmm7.F32x4[0] - state->Gauge) * speed;})!;slowGauge.Enable();cpu->xmm7.f32x4[0] is the low float in xmm7. The handler runs on the game’s thread, so share speed through an atomic.
#include <atomic>
#include "schema.hpp"
static std::atomic<float> speed = 0.25f;
// in startauto at = wraith::api().schema().address(TrailsHorizon::tailing_gauge_store_name);if (!at) return;auto slow_gauge = wraith::api().hooks().mid(*at, {.expect = sal::String::of("F3 0F 11 BF D4 00 00 00"), .disabled = true}, sal::keep<Wraith::Hooks::MidHandler>([](Wraith::Cpu* cpu) { auto* state = reinterpret_cast<TrailsHorizon::TailingState*>(cpu->rdi); float now = cpu->xmm7.f32x4[0]; cpu->xmm7.f32x4[0] = state->gauge + (now - state->gauge) * speed.load(); }));if (slow_gauge) slow_gauge->enable();cpu.xmm7.f32x4[0] is the low float in xmm7. The handler runs on the game’s thread, so share speed through an atomic.
use std::sync::atomic::{AtomicU32, Ordering};
use salamander::Str;use schema::TailingState;use wraith::{Cpu, HooksMidHandler, HooksMidOptions};
static SPEED: AtomicU32 = AtomicU32::new(0.25f32.to_bits());
fn slow_gauge() -> Option<()> { let api = wraith::api(); let at = api.schema().address(schema::TAILING_GAUGE_STORE_NAME).ok()?; let options = HooksMidOptions { expect: Str::new("F3 0F 11 BF D4 00 00 00"), disabled: true, ..Default::default() }; let hook = api .hooks() .mid(at, options, HooksMidHandler::keep(|cpu: *mut Cpu| { let cpu = unsafe { &mut *cpu }; let state = unsafe { &*(cpu.rdi as *const TailingState) }; let speed = f32::from_bits(SPEED.load(Ordering::Acquire)); unsafe { cpu.xmm7.f32x4[0] = state.gauge + (cpu.xmm7.f32x4[0] - state.gauge) * speed }; })) .ok()?; hook.enable().ok()?; Some(())}sdk.hooks.createMid is the SDK’s, and createMidWith takes the options. They start off unless .enabled is set. xmm7.scalarF32() is the low float, and setScalarF32 sets it. The handler runs on the game’s thread, so share speed through an atomic.
const schema = @import("schema").TrailsHorizon;
const SlowGauge = struct { hook: sdk.hooks.MidHook = undefined, speed: sdk.atomic.Value(f32) = .init(0.25),
fn store(self: *SlowGauge, cpu: *sdk.hooks.CpuContext) void { const state: *schema.TailingState = @ptrFromInt(cpu.rdi); const new = cpu.xmm7.scalarF32(); cpu.xmm7.setScalarF32(state.gauge + (new - state.gauge) * self.speed.load(.acquire)); }};
// in startself.slow_gauge.hook = try sdk.hooks.createMidWith(try schema.addresses.tailing_gauge_store(), SlowGauge.store, &self.slow_gauge, .{ .expect = "F3 0F 11 BF D4 00 00 00" });try self.slow_gauge.hook.enable();cpu->xmm7.f32x4[0] is the low float in xmm7. The handler runs on the game’s thread, so share speed through an atomic, or at least a volatile.
#include "schema.h"
static volatile float speed = 0.25f;
static void store(uintptr_t self, Wraith_Cpu *cpu) { (void)self; TrailsHorizon_TailingState *state = (TrailsHorizon_TailingState *)(uintptr_t)cpu->rdi; cpu->xmm7.f32x4[0] = state->gauge + (cpu->xmm7.f32x4[0] - state->gauge) * speed;}
static const Wraith_Hooks_MidHandler_table store_table = { SAL_TABLE(Wraith_Hooks_MidHandler), .call = store };
/* in start */uintptr_t at = 0;Wraith_Schema_address(Wraith_Api_schema(w), SAL_STR(TrailsHorizon_tailing_gauge_store_name), &at);Wraith_Hooks_MidOptions options = { .expect = SAL_STR("F3 0F 11 BF D4 00 00 00"), .disabled = true };Wraith_Hook slow_gauge;if (at && Wraith_Hooks_mid(Wraith_Api_hooks(w), at, options, (Wraith_Hooks_MidHandler){ 0, &store_table }, &slow_gauge) == SAL_OK) { Wraith_Hook_enable(slow_gauge);}A tweak with a speed field can turn it on and off and set the speed, as the examples that come with Wraith do.
Patch and inject
Section titled “Patch and inject”Asm, like in a tweak. code.patch(target, asm, options) replaces code, and code.inject(target, asm, options) runs asm before the instruction there. code.patchBytes writes exact bytes. They start on unless disabled is set, and give a patch with enable, disable and destroy. expect checks what’s there first.
import { Wraith } from "wraith";
const code = Wraith.code();
code.patch(target, "nop", { expect: "mov [rbx+0x98], eax" });code.inject(target, "mov eax, [rbx+0x98]", {});code.inject(target, `mov dword ptr [0x${player.toString(16)}], 100`, {});code:patch(target, "nop", { expect = "mov [rbx+0x98], eax" })code:inject(target, "mov eax, [rbx+0x98]", {})code:inject(target, string.format("mov dword ptr [0x%X], 100", player), {})var code = Code.Instance;code.Patch(target, "nop", new Patch.Options { Expect = "mov [rbx+0x98], eax" });code.Inject(target, "mov eax, [rbx+0x98]", new Patch.Options());code.Inject(target, $"mov dword ptr [0x{player:X}], 100", new Patch.Options());#include <format>
// in startauto code = wraith::api().code();
code.patch(target, "nop", {.expect = sal::String::of("mov [rbx+0x98], eax")});code.inject(target, "mov eax, [rbx+0x98]", {});code.inject(target, std::format("mov dword ptr [0x{:X}], 100", health), {});use salamander::Str;use wraith::PatchOptions;
let code = wraith::api().code();
code.patch(target, "nop", PatchOptions { expect: Str::new("mov [rbx+0x98], eax"), ..Default::default() }).ok()?;code.inject(target, "mov eax, [rbx+0x98]", PatchOptions::default()).ok()?;code.inject(target, &format!("mov dword ptr [0x{health:X}], 100"), PatchOptions::default()).ok()?;const code = ctx.wraith.code();_ = try code.patch(target, "nop", .{ .expect = "mov [rbx+0x98], eax" });_ = try code.inject(target, "mov eax, [rbx+0x98]", .{});Wraith_Code code = Wraith_Api_code(w);Wraith_Patch patch;
Wraith_Patch_Options nop = { .expect = SAL_STR("mov [rbx+0x98], eax") };Wraith_Code_patch(code, target, SAL_STR("nop"), nop, &patch);Wraith_Code_inject(code, target, SAL_STR("mov eax, [rbx+0x98]"), (Wraith_Patch_Options){ 0 }, &patch);
char text[64];int n = snprintf(text, sizeof text, "mov dword ptr [0x%llX], 100", (unsigned long long)health);Wraith_Code_inject(code, target, (sal_string){ text, n > 0 ? (uintptr_t)n : 0 }, (Wraith_Patch_Options){ 0 }, &patch);Read the code
Section titled “Read the code”code.disassemble(address, count) gives the instructions there, with their address, length, bytes and text. It stops at memory it can’t read. code.instructionLength(address) gives just one’s length.
import { Wraith } from "wraith";
const code = Wraith.code(), log = Wraith.log();for (const i of code.disassemble(target, 5)) log.info(`${i.address} ${i.text}`);const size = code.instructionLength(target);local Wraith = require("wraith").Wraith
for _, i in ipairs(code:disassemble(target, 5)) do Wraith.log():info(i.address .. " " .. i.text) endlocal size = code:instructionLength(target)var log = Log.Instance;foreach (var i in code.Disassemble(target, 5)) log.Info($"{i.Address:X} {i.Text}");var size = code.InstructionLength(target);#include <format>
// in startauto code = wraith::api().code();auto log = wraith::api().log();if (auto found = code.disassemble(target, 5)) { for (const auto& i : *found) log.info(std::format("{:x} {}", i.address, i.text.view()));}auto size = code.instructionLength(target);let code = wraith::api().code();for i in code.disassemble(target, 5).ok()? { wraith::api().log().info(&format!("{:x} {}", i.address, unsafe { i.text.get() }));}let size = code.instruction_length(target).ok()?;for (try code.disassemble(target, 5)) |i| log.info("0x{x} {s}", .{ i.address, i.text });const size = try code.instructionLength(target);Wraith_Code code = Wraith_Api_code(w);Slice_Wraith_Code_Instruction found;if (Wraith_Code_disassemble(code, target, 5, &found) == SAL_OK) { for (uintptr_t i = 0; i < found.len; i++) { char line[128]; int n = snprintf(line, sizeof line, "%llx %.*s", (unsigned long long)found.ptr[i].address, (int)found.ptr[i].text.len, found.ptr[i].text.ptr); Wraith_Log_info(Wraith_Api_log(w), (sal_string){ line, n > 0 ? (uintptr_t)n : 0 }); }}
uint32_t size;Wraith_Code_instructionLength(code, target, &size);Watches and breakpoints
Section titled “Watches and breakpoints”watches.add(address, length, kind, handler) uses one of the CPU’s four debug registers. write watches writes, access reads and writes, and execute with a length of 1 is a breakpoint. The game doesn’t stop, and hits come to your handler on the render thread at the start of the next frame, with a copy of the registers. To change the registers, use hooks.mid.
remove() stops it, or Wraith does when the plugin unloads.
import { Wraith } from "wraith";
const watch = Wraith.watches().add(health, 4, "write", (hit, cpu) => { Wraith.log().info(`written by ${hit.instruction}, rcx was ${cpu.rcx}`);});watch.remove();local Wraith = require("wraith").Wraith
local watch = Wraith.watches():add(health, 4, "write", function(hit, cpu) Wraith.log():info("written by " .. hit.instruction .. ", rcx was " .. cpu.rcx)end)watch:remove()var watch = Watches.Instance.Add(health, 4, Watch.Kind.Write, (hit, cpu) => Log.Instance.Info($"written by {hit.Instruction:X}, rcx was {cpu.Rcx}"))!;watch.Remove();#include <format>
// in startauto watch = wraith::api().watches().add(health, 4, Wraith::Watch::Kind::write, sal::keep<Wraith::Watch::Handler>([](Wraith::Watch::Hit hit, Wraith::Cpu cpu) { wraith::api().log().info(std::format("written by {:x}, rcx was {}", hit.instruction, cpu.rcx));}));if (watch) watch->remove();use wraith::{Cpu, WatchHandler, WatchHit, WatchKind};
let watch = wraith::api() .watches() .add(health, 4, WatchKind::WRITE, WatchHandler::keep(|hit: WatchHit, cpu: Cpu| { wraith::api().log().info(&format!("written by {:x}, rcx was {}", hit.instruction, cpu.rcx)); })) .ok()?;watch.remove();const W = sdk.api.wraith;
fn onWrite(self: *Plugin, hit: W.Watch.Hit, cpu: W.Cpu) void { _ = self; log.info("0x{x} wrote it, rcx was {d}", .{ hit.instruction, cpu.rcx });}
// in startself.watch = try ctx.wraith.watches().add(health, 4, .write, .init(self, onWrite));static void on_write(uintptr_t self, Wraith_Watch_Hit hit, Wraith_Cpu cpu) { (void)self; char line[96]; int n = snprintf(line, sizeof line, "written by %llx, rcx was %llu", (unsigned long long)hit.instruction, (unsigned long long)cpu.rcx); Wraith_Log_info(Wraith_Api_log(w), (sal_string){ line, n > 0 ? (uintptr_t)n : 0 });}
static const Wraith_Watch_Handler_table on_write_table = { SAL_TABLE(Wraith_Watch_Handler), .call = on_write };
/* in start */Wraith_Watch watch;Wraith_Watches_add(Wraith_Api_watches(w), health, 4, Wraith_Watch_Kind_write, (Wraith_Watch_Handler){ 0, &on_write_table }, &watch);Wraith_Watch_remove(watch);Threads
Section titled “Threads”Hook handlers run on whatever game thread called the function, which waits for them. Keep them short.
A script runs one thing at a time, so a hook that’s hit while the script’s busy is skipped, so it can miss calls.
A script runs one thing at a time, so a hook that’s hit while the script’s busy is skipped, so it can miss calls.
Several game threads can be in your handler at once. Use Interlocked, volatile or a lock for state you share with other threads.
Several game threads can be in your handler at once, and they often have little stack, so don’t block in a hook. Use std::atomic or a lock for state you share with other threads.
Several game threads can be in your handler at once, and they often have little stack, so don’t block in a hook. Use atomics or a Mutex for state you share with other threads.
The game’s threads often have little stack, so don’t block in a hook. Use sdk.atomic.Value for state you share with other threads, since it works in 32-bit games too.
Several game threads can be in your handler at once, and they often have little stack, so don’t block in a hook. Use C11 atomics or a lock for state you share with other threads.
wraith.io · Mods on the Hub · Get Wraith
Made with ♥ by Asgard
