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