Skip to content

Hooks and code

Same ideas as tweaks, typed.

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.

Describe the function’s type, then give a callback. The callback gets your context, the hook and the arguments.

const TakeDamage = fn (i32) callconv(.c) i32;
fn onDamage(self: *Plugin, hook: *sdk.hooks.FnHook(TakeDamage), damage: i32) i32 {
_ = self;
return hook.original()(@divTrunc(damage, 2));
}
// in start
self.hook = try sdk.hooks.createFn(TakeDamage, take_damage, onDamage, self);
try self.hook.enable();

Hooks start off. Call enable() once it’s set up.

createMid runs before an instruction, with the registers.

fn beforeWrite(self: *Plugin, cpu: *sdk.CpuContext) void {
_ = self;
cpu.rax = 999;
}
const mid = try sdk.hooks.createMid(target, beforeWrite, self);
try mid.enable();

Asm, like in a tweak. These start on unless you pass .enabled = false.

_ = try sdk.code.patch(target, "nop", .{ .expect = "mov [rbx+0x98], eax" });
_ = try sdk.code.inject(target, "mov eax, [rbx+0x98]", .{});

sdk.code.decode reads one instruction without faulting. It fails with error.Unreadable when the memory isn’t there.

const insn = try sdk.code.decode(target);
std.log.info("{s} ({d} bytes)", .{ insn.text(), insn.len });
const size = try sdk.code.instructionLength(target);

sdk.watches.add uses one of the CPU’s four debug registers. Use .write, .access or .execute with a length of 1 for a breakpoint. The game doesn’t stop, and hits come to your callback at the start of the next frame, with a copy of the registers.

fn onWrite(self: *Plugin, hit: sdk.watches.Hit, cpu: *const sdk.CpuContext) void {
_ = self;
std.log.info("0x{x} wrote it, rcx was {d}", .{ hit.instruction, cpu.rcx });
}
// in start
self.watch = try sdk.watches.add(health, 4, .write, self, onWrite);

self.watch.remove() stops it, or Wraith does when the plugin unloads.

Hook callbacks run on whatever game thread called the function, often with little stack. Keep them short and don’t block. Use sdk.atomic.Value for shared state, since it works in 32-bit games too.

Made with ♥ by Asgard