styyx-util 1.0
Utility Header for SKSE Plugin development
Loading...
Searching...
No Matches
st-hooks.h
Go to the documentation of this file.
1//
2// Created by styyx on 09/03/2026.
3//
4
5#pragma once
6#include <xbyak/xbyak.h>
7
8namespace StyyxUtil
9{
10 namespace HookUtils
11 {
33 template <class T>
34 void WriteCall5(const REL::ID a_relID, const uint32_t a_offset)
35 {
36 static REL::Relocation<uintptr_t> targ {a_relID, a_offset};
37 auto& trampoline = SKSE::GetTrampoline();
38 T::func = trampoline.write_call<5>(targ.address(), T::Call);
39 }
40 template <class O, uint32_t table, uint32_t index, class T>
42 {
43 static REL::Relocation<uintptr_t> vtbl {O::VTABLE[table]};
44 T::func = vtbl.write_vfunc(index, T::Call);
45 }
46
47 template <typename Ret, typename... Args> static Ret GenericCall(REL::ID a_id, uint32_t a_offset, Args... args)
48 {
49 using func_t = Ret(*)(Args...);
50 static REL::Relocation<func_t> target{ a_id, a_offset };
51 return target(std::forward<Args>(args)...);
52 }
53 // copied from https://github.com/powerof3/PapyrusExtenderSSE/blob/0fbb355b634f2edcfd72bd364884e3ee5caadfc9/include/PCH.h#L140-L167
54 // MIT License
55 template <class T, std::size_t BYTES>
56 void hook_function_prologue(std::uintptr_t a_src)
57 {
58 struct Patch : Xbyak::CodeGenerator
59 {
60 Patch(std::uintptr_t a_originalFuncAddr, std::size_t a_originalByteLength)
61 {
62 // Hook returns here. Execute the restored bytes and jump back to the original function.
63 for (size_t i = 0; i < a_originalByteLength; ++i) {
64 db(*reinterpret_cast<std::uint8_t*>(a_originalFuncAddr + i));
65 }
66 jmp(ptr[rip]);
67 dq(a_originalFuncAddr + a_originalByteLength);
68 }
69 };
70
71 Patch p(a_src, BYTES);
72 p.ready();
73
74 auto& trampoline = SKSE::GetTrampoline();
75 trampoline.write_branch<5>(a_src, T::thunk);
76
77 auto alloc = trampoline.allocate(p.getSize());
78 std::memcpy(alloc, p.getCode(), p.getSize());
79
80 T::func = reinterpret_cast<std::uintptr_t>(alloc);
81 }
82 }
83}
Definition st-hooks.h:11
void WriteCall5(const REL::ID a_relID, const uint32_t a_offset)
Basic Call hook.
Definition st-hooks.h:34
static Ret GenericCall(REL::ID a_id, uint32_t a_offset, Args... args)
Definition st-hooks.h:47
void WriteVFunc()
Definition st-hooks.h:41
void hook_function_prologue(std::uintptr_t a_src)
Definition st-hooks.h:56
Definition st-actor.h:7