From a86f1219c3fc6a4cc56f3ea8df8151bfd053d767 Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Sun, 18 Oct 2026 04:34:07 -0500 Subject: [PATCH] fix(frame): follow 4.3.4's HookScript, so a hooked handler keeps its args HookScript's HookThunk was a C closure, which Frame::ScriptArgs treats as wanting no positional args, and it called the old handler with none - so a modern SetScript("OnShow", function(self) ... end) saw self == nil as soon as anything hooked it. It also padded the hook to 9 args and only detected OnEvent by exact case. Follow 4.3.4's FrameScript_Object::HookScript instead: - an unset script gets the hook itself, so GetScript returns it; - a set one gets the same wrapper hooksecurefunc installs (4.3.4 uses FrameScript_HookWrapper for both), exposed via HookSecureFunc.h: the old handler and the hook get the script's own args, and a hook error goes through the engine's script error handler. ScriptArgs' HandlerWantsArgs looks inside that wrapper (C function compare, upvalues at CClosure +0x10 per lua_pushcclosure), so a hooked script takes the positional path only when either side declares parameters. The usage error names the frame as the engine does: vtable+4 GetName, else its "". Verified in-game: old and hook both get self; OnEvent gets (self, event) with no padding; an unset script stores the hook; a three-deep chain; a hook error is reported after the old handler ran; both error texts. --- docs/API.md | 21 +++++---- src/HookSecureFunc.cpp | 14 +++++- src/HookSecureFunc.h | 32 ++++++++++++++ src/Offsets.h | 7 +++ src/frame/Modern.cpp | 93 ++++++++++++++++------------------------ src/frame/ScriptArgs.cpp | 64 +++++++++++++++++++-------- 6 files changed, 147 insertions(+), 84 deletions(-) create mode 100644 src/HookSecureFunc.h diff --git a/docs/API.md b/docs/API.md index 77b204d2..69698997 100644 --- a/docs/API.md +++ b/docs/API.md @@ -6239,14 +6239,19 @@ before they hook the scripts of a frame. ### `frame:HookScript(scriptType, handler)` -Adds `HookScript` to every frame. It chains: the previously-set handler -runs first, globals-style (no arguments — it reads the -`this`/`event`/`argN` globals like every handler), then `handler` is -invoked with positional arguments: `(frame, event, arg1..arg9)` for -`OnEvent` scripts and `(frame, arg1..arg9)` for everything else. So -handlers written as `function(self, ...) ... end` work unmodified. -Globals-style handlers passed to `HookScript` also keep working — the -globals are set as usual and extra arguments are simply ignored. +Adds `HookScript` to every frame. The previously-set handler runs first, +then `handler`. Both get the same arguments: `(self, event, ...)` for +`OnEvent` and `(self, ...)` for every other script, with every argument +the script has. Handlers that read the `this` / `event` / `argN` globals +keep working too. + +- When the script has no handler yet, `handler` becomes the handler, and + `GetScript` returns it. +- An error in `handler` is shown like any other script error, through the + error handler (`geterrorhandler()`). The previous handler still runs. +- Errors: `Usage: :HookScript("type", function)` for bad arguments + (`` for a frame with no name), and the same `doesn't have a + "" script` error as `SetScript` for an unknown script type. ```lua button:HookScript("OnEnter", function(self) diff --git a/src/HookSecureFunc.cpp b/src/HookSecureFunc.cpp index e1313e10..ac80feac 100644 --- a/src/HookSecureFunc.cpp +++ b/src/HookSecureFunc.cpp @@ -11,6 +11,8 @@ // You should have received a copy of the GNU General Public License along with // ClassicAPI. If not, see . +#include "HookSecureFunc.h" + #include "Game.h" #include "Offsets.h" @@ -51,6 +53,8 @@ bool IsUnhookable(const char *name) { return false; } +} // namespace + // Wrapper closure body — called when the hooked function is invoked. // Stack contains the wrapper's args (`[arg1..argN]`); the closure's // upvalues hold `(orig, callback)`. 4.3.4's FrameScript_HookWrapper, less @@ -64,7 +68,7 @@ bool IsUnhookable(const char *name) { // message handler as errfunc: a broken hook is REPORTED the way any // script error is (the error frame / geterrorhandler), and the // original's results still reach the caller. -int __fastcall HookWrapper(void *L) { +int __fastcall Wrapper(void *L) { const int nargs = Game::Lua::GetTop(L); // (1) Stack after: `[arg1..argN, res1..resM]`. @@ -101,6 +105,12 @@ int __fastcall HookWrapper(void *L) { return nresults; } +void PushWrapper(void *L) { + Game::Lua::PushCClosure(L, &Wrapper, 2); +} + +namespace { + // `hooksecurefunc([table,] "function", hookfunc)` — replaces // `table[name]` (default `_G`) with a wrapper that runs the original, then // `hookfunc` with the same args, and returns the original's results. @@ -148,7 +158,7 @@ int __fastcall Script_HookSecureFunc(void *L) { } Game::Lua::Insert(L, 3); // [t, name, orig, hookfunc] - Game::Lua::PushCClosure(L, &HookWrapper, 2); // [t, name, wrapper] + PushWrapper(L); // [t, name, wrapper] Game::Lua::RawSet(L, 1); // t[name] = wrapper return 0; } diff --git a/src/HookSecureFunc.h b/src/HookSecureFunc.h new file mode 100644 index 00000000..a73a569f --- /dev/null +++ b/src/HookSecureFunc.h @@ -0,0 +1,32 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU General Public License as published by the Free Software Foundation, either +// version 3 of the License, or (at your option) any later version. +// +// ClassicAPI is distributed in the hope that it will be useful, but WITHOUT ANY +// WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR +// PURPOSE. See the GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License along with +// ClassicAPI. If not, see . + +#pragma once + +// The one hook wrapper `hooksecurefunc` and `Frame:HookScript` both install — +// 4.3.4 uses its FrameScript_HookWrapper for both, so a hooked function and a +// hooked script behave the same way. +namespace HookSecureFunc { + +// The wrapper closure body. Upvalue 1 = the original, upvalue 2 = the hook. +// Runs the original with the wrapper's args (its errors propagate), then the +// hook with the same args under the engine's script error handler, and +// returns the original's results. Exposed so readers can recognize the +// closure by its C function. +int __fastcall Wrapper(void *L); + +// Pops the hook (top) and the original (below it) and pushes the wrapper +// closure over them. +void PushWrapper(void *L); + +} // namespace HookSecureFunc diff --git a/src/Offsets.h b/src/Offsets.h index b5e260eb..574b885d 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -1452,6 +1452,7 @@ enum Offsets { UNIT_EVENT_UNIT_COMBAT = 0xB6, VAR_STR_UNIT_COMBAT_FORMAT = 0x0084333C, // "%s%s%s%d%d" VAR_STR_EMPTY = 0x00882748, // "" + VAR_STR_UNNAMED = 0x0084C7F0, // "" — the display name of a frame with no name (see VTBL_SCRIPTOBJECT_GET_NAME) VAR_STR_COMBAT_CRITICAL = 0x00843370, VAR_STR_COMBAT_GLANCING = 0x00843364, VAR_STR_COMBAT_CRUSHING = 0x00843358, @@ -2954,6 +2955,12 @@ enum Offsets { OFF_FRAME_CHILD_LIST = 0x300, VTBL_FRAME_SET_FRAME_ALPHA = 0x28, VTBL_REGION_RECOLOR = 0x20, + // CScriptObject vtable+0x04 — `const char *__thiscall GetName()`, NULL for + // an unnamed object. The frame-script usage errors (Script_GetScript + // 0x00774780, Script_SetScript 0x007748D0, ~90 more sites) format the + // object as `GetName() ?: VAR_STR_UNNAMED` — 4.3.4's + // FrameScript_Object::GetDisplayName, inlined. + VTBL_SCRIPTOBJECT_GET_NAME = 0x04, FUN_FRAME_SET_FRAME_ALPHA = 0x0076A690, // CSimpleFrame::SetParent — `void __thiscall(frame, CSimpleFrame *parent)`, // `ret 4`; Script SetParent reaches it through vtable+0x14. No-op for the diff --git a/src/frame/Modern.cpp b/src/frame/Modern.cpp index f4d86cd9..7bff275c 100644 --- a/src/frame/Modern.cpp +++ b/src/frame/Modern.cpp @@ -38,8 +38,8 @@ // - `frame:SetResizeBounds(minW, minH [, maxW, maxH])` — the modern // rename of vanilla's SetMinResize/SetMaxResize pair. // - `frame:HookScript(scriptType, handler)` — absent in vanilla -// entirely. Chains after any existing handler and invokes `handler` -// with modern positional args (see the implementation comment). +// entirely. 4.3.4's: chains after any existing handler through the +// same wrapper `hooksecurefunc` installs. // - `frame:GetEffectiveAlpha()` — the alpha the frame is drawn with: // the byte at OFF_FRAME_ALPHA, which `Frame::Alpha` keeps at own × // the parent's drawn alpha. Frame-scoped (matches GetAlpha). @@ -52,10 +52,10 @@ // reshaping. #include "Game.h" +#include "HookSecureFunc.h" #include "Offsets.h" #include -#include namespace Frame::Modern { @@ -280,67 +280,50 @@ int __fastcall Script_SetResizeBounds(void *L) { // ---- HookScript (Frame) ---------------------------------------------------- -// `frame:HookScript(scriptType, handler)` — vanilla has no HookScript at -// all. Chains onto any existing handler: the old handler runs first, -// vanilla-style (no args — it reads the `this`/`event`/`argN` globals like -// every 1.12 handler), then `handler` is invoked MODERN-style with -// positional arguments `(frame, event, arg1..arg9)` for OnEvent and -// `(frame, arg1..arg9)` otherwise — mirroring the compat convention -// modern addon ports expect (and ship themselves when they detect a -// legacy client). The chain is a C closure over (handler, old, isOnEvent). +// `frame:HookScript("type", function)` — 4.3.4's +// FrameScript_Object::HookScript, less taint: +// * no script set: the hook becomes the script itself, so GetScript +// returns it; +// * otherwise the script becomes the hooksecurefunc wrapper over (old, +// hook) — 4.3.4 installs the same FrameScript_HookWrapper for both. The +// old handler runs first with the script's arguments, then the hook with +// the same arguments under the engine's script error handler. +// The arguments are whatever the dispatch passes. Frame::ScriptArgs looks +// inside the wrapper and passes positional args when either side declares +// parameters; the engine sets the this/event/argN globals for vanilla +// handlers either way. Script lookup, the unknown-script error and storage +// stay the engine's own GetScript / SetScript, whose texts match 4.3.4's. -// Pushes _G[name]. -void PushGlobal(void *L, const char *name) { - Game::Lua::PushString(L, name); - Game::Lua::GetTable(L, Game::Lua::GLOBALS_INDEX); -} - -// The chained handler the engine actually invokes (with no args, like any -// vanilla script handler). Upvalues: 1 = hook handler, 2 = old handler -// (or nil), 3 = isOnEvent (number). Errors inside lua_call propagate to -// the engine's own protected script dispatch. -int __fastcall HookThunk(void *L) { - if (Game::Lua::Type(L, Game::Lua::UpvalueIndex(2)) == - Game::Lua::TYPE_FUNCTION) { - Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(2)); - Game::Lua::Call(L, 0, 0); - } - const bool isOnEvent = - Game::Lua::ToNumber(L, Game::Lua::UpvalueIndex(3)) != 0; - Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(1)); - PushGlobal(L, "this"); - if (isOnEvent) - PushGlobal(L, "event"); - static const char *const kArgs[] = {"arg1", "arg2", "arg3", "arg4", - "arg5", "arg6", "arg7", "arg8", - "arg9"}; - for (const char *a : kArgs) - PushGlobal(L, a); - Game::Lua::Call(L, (isOnEvent ? 2 : 1) + 9, 0); - return 0; +// `GetName() ?: ""` — how the engine names an object in its +// frame-script usage errors (VTBL_SCRIPTOBJECT_GET_NAME). +const char *DisplayName(void *object) { + using GetName_t = const char *(__thiscall *)(void *); + const void *vtable = Game::Read(object, 0); + const char *name = Game::Read( + vtable, Offsets::VTBL_SCRIPTOBJECT_GET_NAME)(object); + return name != nullptr ? name + : reinterpret_cast(Offsets::VAR_STR_UNNAMED); } int __fastcall Script_HookScript(void *L) { + void *frame = Game::Lua::ResolveFrame(L); + if (frame == nullptr) + return 0; if (!Game::Lua::IsString(L, 2) || Game::Lua::Type(L, 3) != Game::Lua::TYPE_FUNCTION) { - Game::Lua::Error(L, "Usage: frame:HookScript(\"type\", function)"); + Game::Lua::Error(L, "Usage: %s:HookScript(\"type\", function)", + DisplayName(frame)); return 0; } - const char *scriptName = Game::Lua::ToString(L, 2); - const bool isOnEvent = - scriptName != nullptr && std::strcmp(scriptName, "OnEvent") == 0; - Game::Lua::SetTop(L, 3); // (self, name, handler) - // GetScript reads self/name at 1/2 and pushes the current handler - // (or nil) — extra stack entries above are ignored by its reads. - CallScript(Offsets::FUN_SCRIPT_FRAME_GETSCRIPT, L); // (.., old) - // Closure upvalues, in upvalue order: handler, old, isOnEvent. - Game::Lua::PushValue(L, 3); // handler - Game::Lua::PushValue(L, 4); // old - Game::Lua::PushNumber(L, isOnEvent ? 1.0 : 0.0); // flag - Game::Lua::PushCClosure(L, &HookThunk, 3); // (self,name,handler,old,closure) - Game::Lua::Remove(L, 4); // drop old - Game::Lua::Remove(L, 3); // drop handler → (self,name,closure) + Game::Lua::SetTop(L, 3); // (self, type, hook) + CallScript(Offsets::FUN_SCRIPT_FRAME_GETSCRIPT, L); // (.., old or nil) + if (Game::Lua::Type(L, 4) == Game::Lua::TYPE_FUNCTION) { + Game::Lua::Insert(L, 3); // (self, type, old, hook) + HookSecureFunc::PushWrapper(L); // (self, type, wrapper) + } else { + Game::Lua::SetTop(L, 3); // (self, type, hook) + } CallScript(Offsets::FUN_SCRIPT_FRAME_SETSCRIPT, L); return 0; } diff --git a/src/frame/ScriptArgs.cpp b/src/frame/ScriptArgs.cpp index ef196be3..dfc0dc6e 100644 --- a/src/frame/ScriptArgs.cpp +++ b/src/frame/ScriptArgs.cpp @@ -50,7 +50,7 @@ // // Convention: `(self, arg1..argN)` for every script, plus `event` inserted as // the first positional for OnEvent — `(self, event, arg1..argN)` — matching -// retail (and Frame::Modern's HookScript). An OnEvent dispatch is detected +// retail. An OnEvent dispatch is detected // structurally at the runner: the handler ref being invoked equals the frame's // OnEvent slot handler (frame+OFF_FRAME_ONEVENT_SLOT). This is exact — each // SetScript creates a distinct ref, so a function bound to two scripts still @@ -65,6 +65,7 @@ // (FUN_FRAME_RUN_SCRIPT_ARGS fires for every OnUpdate frame). #include "Game.h" +#include "HookSecureFunc.h" #include "Offsets.h" #include @@ -283,6 +284,8 @@ bool RunModern(int handlerRef, void *frame, const char *fmt, const void *vaPtr) // lua_State: top @ +0x08 (TValue *, next free slot) // TValue: tag @ +0x00 (int); GC/closure pointer @ +0x08 (16-byte TValue) // Closure: isC byte @ +0x06; union member (C func / Proto) @ +0x0C +// CClosure: C function @ +0x0C (same union slot); upvalue[i] (TValue) @ +// +0x10 + i*0x10 — lua_pushcclosure (0x006F3920) copies them there // Single-use here, so kept local (like the lua_State field offsets elsewhere). // The Proto fields this reads (numparams @ +0x45, is_vararg @ +0x46) are shared // with LuaSyntax::Upvalues and live in Offsets.h as OFF_LUA_PROTO_*. @@ -290,37 +293,60 @@ constexpr uintptr_t OFF_LUASTATE_TOP = 0x08; constexpr uintptr_t OFF_TVALUE_GC = 0x08; constexpr uintptr_t OFF_CLOSURE_ISC = 0x06; constexpr uintptr_t OFF_LCLOSURE_PROTO = 0x0C; +constexpr uintptr_t OFF_CCLOSURE_FN = 0x0C; +constexpr uintptr_t OFF_CCLOSURE_UPVALUES = 0x10; constexpr int kLuaTFunction = 6; constexpr uintptr_t kTValueSize = 0x10; +// A HookScript chain nests one wrapper per hook. Past this depth, answer +// "yes": positional args are harmless to a handler that ignores them, so +// erring that way costs only the slower path. +constexpr int kMaxWrapperDepth = 32; + +// Does the function in TValue `tv` observe positional args? A Lua closure +// does when it declares a parameter or is vararg — a modern +// `function(self, delta)` / `function(self, ...)`. The hook wrapper +// (`HookSecureFunc::Wrapper`, what HookScript installs) forwards its args to +// both functions it holds, so it does when either of them does. Any other C +// closure reads globals/upvalues, never positional args. +bool FunctionWantsArgs(const void *tv, int depth) { + if (Game::Read(tv, 0) != kLuaTFunction) + return false; + const void *cl = + reinterpret_cast(Game::Read(tv, OFF_TVALUE_GC)); + if (cl == nullptr) + return false; + if (Game::Read(cl, OFF_CLOSURE_ISC) == 0) { // Lua closure + const void *proto = reinterpret_cast( + Game::Read(cl, OFF_LCLOSURE_PROTO)); + return proto != nullptr && + (Game::Read(proto, Offsets::OFF_LUA_PROTO_NUMPARAMS) > 0 || + Game::Read(proto, Offsets::OFF_LUA_PROTO_IS_VARARG) != 0); + } + if (Game::Read(cl, OFF_CCLOSURE_FN) != + reinterpret_cast(&HookSecureFunc::Wrapper)) + return false; + if (depth >= kMaxWrapperDepth) + return true; + const auto *upvalues = static_cast(cl) + OFF_CCLOSURE_UPVALUES; + return FunctionWantsArgs(upvalues, depth + 1) || // original + FunctionWantsArgs(upvalues + kTValueSize, depth + 1); // hook +} + // Does this handler actually observe positional args? A vanilla handler reads // this/arg1 globals and declares NO parameters, so pushing positional args to // it is observably identical to vanilla — those route through the original // engine runner instead (exact vanilla, and off the hottest Lua path). Only a -// Lua closure that declares a parameter or is vararg — a modern -// `function(self, delta)` / `function(self, ...)` — takes the reimplemented -// positional path. A C-closure handler (HookScript's thunk, say) reads -// globals/upvalues, never positional args, so it counts as "no" too. +// handler FunctionWantsArgs accepts takes the reimplemented positional path. // -// Reads the handler's Proto directly (the engine exposes no arity via the C -// API); every read is bounded — a non-function ref, a C closure, or a null +// Reads the closures directly (the engine exposes no arity via the C API); +// every read is bounded — a non-function ref, a foreign C closure, or a null // Proto all fall through to "no". bool HandlerWantsArgs(void *L, int handlerRef) { RawGetI(L, Game::Lua::REGISTRY_INDEX, handlerRef); // push registry[handlerRef] - bool wants = false; const void *tv = reinterpret_cast( Game::Read(L, OFF_LUASTATE_TOP) - kTValueSize); - if (Game::Read(tv, 0) == kLuaTFunction) { - const void *cl = - reinterpret_cast(Game::Read(tv, OFF_TVALUE_GC)); - if (cl != nullptr && Game::Read(cl, OFF_CLOSURE_ISC) == 0) { // Lua closure - const void *proto = reinterpret_cast( - Game::Read(cl, OFF_LCLOSURE_PROTO)); - if (proto != nullptr) - wants = Game::Read(proto, Offsets::OFF_LUA_PROTO_NUMPARAMS) > 0 || - Game::Read(proto, Offsets::OFF_LUA_PROTO_IS_VARARG) != 0; - } - } + const bool wants = FunctionWantsArgs(tv, 0); Game::Lua::SetTop(L, -2); // pop the handler return wants; }