From bef40ab87723ec61501ea4aa32feb7f0044d47fc Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Sun, 10 May 2026 14:24:46 -0500 Subject: [PATCH] hooksecurefunc --- README.md | 1 + TODO.md | 85 ++++++++++++++++++++++--- docs/API.md | 36 +++++++++++ docs/LuaCAPI.md | 6 +- src/Game.cpp | 3 + src/Game.h | 12 ++++ src/HookSecureFunc.cpp | 139 +++++++++++++++++++++++++++++++++++++++++ src/Offsets.h | 14 ++++- src/item/Tooltip.cpp | 5 +- 9 files changed, 285 insertions(+), 16 deletions(-) create mode 100644 src/HookSecureFunc.cpp diff --git a/README.md b/README.md index 86c0bd1d..5b8623e5 100644 --- a/README.md +++ b/README.md @@ -28,6 +28,7 @@ Quick index: | State | `IsFalling`, `IsMounted`, `IsStealthed`, `IsSwimming` | | AddOns | `C_AddOns.DoesAddOnExist`, `C_AddOns.GetAddOnName`, `C_AddOns.GetAddOnNotes`, `C_AddOns.GetAddOnSecurity`, `C_AddOns.GetAddOnTitle`, `C_AddOns.IsAddOnLoadable` | | Combat | `InCombatLockdown` | +| Hooks | `hooksecurefunc` | | Talent | `GetTalentIDByIndex`, `GetTalentSpellID` | | Time | `GetServerTime` | | Events | `C_EventUtils.IsEventValid` | diff --git a/TODO.md b/TODO.md index df373047..f12b346d 100644 --- a/TODO.md +++ b/TODO.md @@ -526,11 +526,11 @@ displayable as a spellbook button. ### How we caught the bug pre-ship -I initially implemented `IsSpellKnown` using the same bitmap as +Initially implemented `IsSpellKnown` using the same bitmap as `IsPlayerSpell`, on the (wrong) assumption that the two functions were equivalent in 1.12 since the bitmap was the engine's -authoritative knowledge store. The user pushed back: "I feel like -[`IsSpellKnown`] is not as powerful as `IsPlayerSpell`." +authoritative knowledge store. Caught in review — `IsSpellKnown` +is meant to be the stricter check, distinct from `IsPlayerSpell`. Cross-binary lookup confirmed: 3.3.5's `Script_IsSpellKnown` at `0x0053C3A0` calls an inner helper at `0x0053B4E0` that does a strict @@ -585,7 +585,7 @@ the initial reading where I thought the JNE went the other way. nearby player's head, not just yourself — the function at `0x005EC9E0` checks `[unit + 0xE68] + 0x08` bit 1 universally and only special-cases the local player when a global at `[0x00B6E5CC]` is set (probably a -"hide my own AFK indicator" preference toggle). User confirmed in-game +"hide my own AFK indicator" preference toggle). Verified in-game on a non-Turtle stock 1.12.1 server. ## 32. `IsCurrentSpell(spellID)` — easy @@ -951,7 +951,7 @@ our purpose only the rank-1 spellID at `+0x10` matters. ### Verified in-game -User tested both tiers — own-class talents render the full talent +Both tiers tested — own-class talents render the full talent tooltip, cross-class IDs render the corresponding spell tooltip. ## ~~44. `GameTooltip:SetItemByID(itemID)`~~ — DONE @@ -1038,7 +1038,7 @@ The naive walk-based implementation (originally drafted) failed for profession recipes — turns out vanilla 1.12's `VAR_PLAYER_SPELLBOOK` arrays DON'T contain profession recipe spellIDs (verified empirically: a tailor with Bolt of Linen Cloth fails -`FindSpellBookSlotByID(2963)`). User flagged the bug. +`FindSpellBookSlotByID(2963)`). Surfaced during in-game testing. To confirm whether 1.12 had a unified spell-knowledge data structure, I dumped 5.4.8's `Script_IsPlayerSpell` (5.4 = the version where the @@ -1625,10 +1625,10 @@ ways: by name pattern but its body just calls `SMemFree(buffer)` — it's a destructor, not a transmitter. -Calling `0x005E0B50` directly was tested empirically: the user -reported `EquipItemByName(item, slot)` "doesn't do anything" with -this path active. Consistent with the dead-code analysis — the -function builds a packet in memory and immediately frees it. +Calling `0x005E0B50` directly was tested empirically: with that +path active, `EquipItemByName(item, slot)` produced no observable +effect. Consistent with the dead-code analysis — the function +builds a packet in memory and immediately frees it. ### Where the production CMSG_SWAP_INV_ITEM actually goes @@ -1796,6 +1796,71 @@ near the FontStrings array pointer. Useful for tooltip-parsing addons that want to walk all lines without iterating until `_GetTooltipLine(i)` returns nil. +## ~~65. `hooksecurefunc(name|table, [name,] callback)`~~ — DONE + +Shipped as [src/HookSecureFunc.cpp](src/HookSecureFunc.cpp). Pure C +implementation using a `lua_pushcclosure` with two upvalues +(`orig`, `callback`). The wrapper calls orig with `LUA_MULTRET`, +then callback (returns discarded), then returns orig's full result +list with no count cap. + +### Why pure C, not embedded Lua + +Originally drafted as a Lua source string executed via +`FrameScript_Execute` at boot. Reworked to pure C to keep all +implementation in one language and avoid embedded source strings; +the refactor added three Lua C API offsets we hadn't wrapped before +(`lua_gettop` at `0x6F3070`, `lua_remove`, `lua_call` at +`0x6F4180`), plus the `LUA_UPVALUEINDEX(i) = GLOBALS_INDEX - i` +helper. + +### Lua API offset corrections discovered along the way + +While diagnosing why `hooksecurefunc("GetSpellInfo", fn)` was returning +"target field is not a function", a series of `_classicapi_*Probe` +helpers traced the failure to **three misidentified offsets** in +`docs/LuaCAPI.md` (and `Offsets.h`): + +| VA | Doc'd as | Actually is | +|----|----------|-------------| +| `0x006F30D0` | `lua_pushvalue` | **`lua_remove`** (shift-down loop + decr_top) | +| `0x006F32B0` | `lua_remove` | **`lua_replace`** (TValue copy + decr_top) | +| `0x006F3350` | `lua_replace` | **`lua_pushvalue`** (TValue copy → top + incr_top) | + +How we caught it: `_classicapi_PushValueProbe` showed `GetTop` going +from `1 → 0` after `PushValue(L, 1)` — the supposed `lua_pushvalue` +was actually popping (lua_remove behavior). Disassembly of `0x6F30D0` +confirmed the shift-down loop + `add [ecx+8], -0x10`, vs `0x6F3350` +which has the standard `add [ecx+8], 0x10` incr_top after a single +TValue copy. + +`Offsets.h` and `docs/LuaCAPI.md` both updated. The misidentified +offsets had no observable effect previously because no code in the +project used `PushValue` outside `HookSecureFunc.cpp` — every +existing call path uses `PushString`/`PushNumber` for fresh pushes +and `SetTable`/`GetTable` for stack manipulation. + +### Why 1.12 needs this even without taint + +Modern's "secure" label is about taint propagation in 3.x+ protected +frames. 1.12 has no taint system; the function is functionally a +plain after-hook with return preservation. We ship it for **modern +API parity** — addons being backported from later expansions +frequently use `hooksecurefunc(GameTooltip, "SetInventoryItem", ...)` +and similar patterns, expecting the original to run first and their +callback to fire afterward. Both forms (global by name, table+method) +are supported. + +### Cross-version reference + +2.4.3 has the strings `hooksecurefunc`/`securecall`/`issecure` +clustered together at `FO=0x4D2CF8`/`0x4D2D08`/`0x4D2D28` in `.rdata`, +suggesting they're a "secure environment helpers" string table for +the engine's taint-propagation code. The `hooksecurefunc` Lua +implementation itself is in `FrameXML/RestrictedFrames.lua` even in +modern WoW — the engine never had an internal C version we could +mirror. + ## ~~63. `GameTooltip:SetInventoryItemByID(itemID)`~~ — DONE Shipped in [src/item/Tooltip.cpp](src/item/Tooltip.cpp). diff --git a/docs/API.md b/docs/API.md index 97d4ff55..30cea5d2 100644 --- a/docs/API.md +++ b/docs/API.md @@ -1849,6 +1849,42 @@ Equivalent to `UnitAffectingCombat("player")` but faster — reads the `UNIT_FLAG_IN_COMBAT` bit directly off the player CGUnit's m_objectFields, no token-resolution roundtrip. +## Hooks + +### `hooksecurefunc(name, callback)` / `hooksecurefunc(table, name, callback)` + +Modern post-call hook: the original function runs first, then +`callback` runs with the same args (return values discarded). The +original's return values propagate to the caller. + +```lua +hooksecurefunc("GetSpellInfo", function(spellID) + print("GetSpellInfo called with " .. tostring(spellID)) +end) + +hooksecurefunc(GameTooltip, "SetInventoryItem", function(self, unit, slot) + -- runs after the engine fills the tooltip + print("inventory tooltip:", unit, slot) +end) +``` + +The "secure" label refers to taint-propagation behavior introduced in +3.0 for protected-frame manipulation. Vanilla 1.12 has no taint +system, so the function is functionally equivalent to a plain +"after-hook" — just preserves modern API parity for addons being +backported from later expansions. + +Implemented in pure C: builds a Lua C closure with `(orig, callback)` +as upvalues; the wrapper calls orig with `LUA_MULTRET`, then callback, +then returns orig's full result list. No return-count cap — works +correctly for functions returning any number of values. + +Errors via `lua_error` on: +- Non-string `name` +- Non-function `callback` +- `target[name]` not resolvable to a function (covers typos and + hooking unknown frame methods) + ## Talent ### `GetTalentSpellID(tabIndex, talentIndex, [rank])` diff --git a/docs/LuaCAPI.md b/docs/LuaCAPI.md index 96b7ce59..93070880 100644 --- a/docs/LuaCAPI.md +++ b/docs/LuaCAPI.md @@ -77,10 +77,10 @@ context but not byte-by-byte verified. |--------------|-------------------------|----------|--------------------------------------------------------------|------| | `0x006F3070` | `lua_gettop` | fastcall | `(top - base) >> 4` | ★ | | `0x006F3080` | `lua_settop` | fastcall | | ✓ | -| `0x006F30D0` | `lua_pushvalue` | fastcall | resolves pseudo-indices (`-10000`, `-10001`) | ★ | +| `0x006F30D0` | `lua_remove` | fastcall | shift-down loop + decr_top; previously misidentified as `lua_pushvalue` | ★ | | `0x006F31A0` | `lua_insert` | fastcall | called as `lua_insert(L, -2)` from `FrameScript_RegisterFunction` | ✓ | -| `0x006F32B0` | `lua_remove` | fastcall | | ◦ | -| `0x006F3350` | `lua_replace` | fastcall | | ◦ | +| `0x006F32B0` | `lua_replace` | fastcall | single TValue copy + decr_top; previously misidentified as `lua_remove` | ★ | +| `0x006F3350` | `lua_pushvalue` | fastcall | index-resolve → TValue copy → `add [ecx+8], 0x10` incr_top; resolves pseudo-indices (`-10000`, `-10001`); previously misidentified as `lua_replace` | ★ | ### Access (type & conversion) diff --git a/src/Game.cpp b/src/Game.cpp index d563867d..e409ed88 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -36,7 +36,10 @@ const lua_rawget_t RawGet = reinterpret_cast(Offsets::LUA_RAW_GET) const lua_settable_t SetTable = reinterpret_cast(Offsets::LUA_SET_TABLE); const lua_rawset_t RawSet = reinterpret_cast(Offsets::LUA_RAW_SET); const lua_insert_t Insert = reinterpret_cast(Offsets::LUA_INSERT); +const lua_remove_t Remove = reinterpret_cast(Offsets::LUA_REMOVE); +const lua_gettop_t GetTop = reinterpret_cast(Offsets::LUA_GET_TOP); const lua_settop_t SetTop = reinterpret_cast(Offsets::LUA_SET_TOP); +const lua_call_t Call = reinterpret_cast(Offsets::LUA_CALL); const lua_type_t Type = reinterpret_cast(Offsets::LUA_TYPE); const lua_error_t Error = reinterpret_cast(Offsets::LUA_ERROR); diff --git a/src/Game.h b/src/Game.h index 15336e36..94886c3d 100644 --- a/src/Game.h +++ b/src/Game.h @@ -25,6 +25,12 @@ using CFunction = int(__fastcall *)(void *L); // Lua 5.0 pseudo-index used to read/write entries on the globals table. constexpr int GLOBALS_INDEX = -10001; +// LUA_UPVALUEINDEX(i) — pseudo-index for accessing the i-th upvalue +// of a C closure. Lua 5.0 layout: `LUA_GLOBALSINDEX - i`. +constexpr int UpvalueIndex(int i) { return GLOBALS_INDEX - i; } + +// `lua_call` / `lua_pcall` nresults sentinel meaning "all". +constexpr int MULTRET = -1; // Type tag values returned by `Type()` (lua_type). constexpr int TYPE_NIL = 0; @@ -52,7 +58,10 @@ using lua_rawget_t = void(__fastcall *)(void *L, int idx); using lua_settable_t = void(__fastcall *)(void *L, int idx); using lua_rawset_t = void(__fastcall *)(void *L, int idx); using lua_insert_t = void(__fastcall *)(void *L, int idx); +using lua_remove_t = void(__fastcall *)(void *L, int idx); +using lua_gettop_t = int(__fastcall *)(void *L); using lua_settop_t = void(__fastcall *)(void *L, int idx); +using lua_call_t = void(__fastcall *)(void *L, int nargs, int nresults); using lua_type_t = int(__fastcall *)(void *L, int index); using lua_error_t = void(__cdecl *)(void *L, const char *); @@ -73,7 +82,10 @@ extern const lua_rawget_t RawGet; extern const lua_settable_t SetTable; extern const lua_rawset_t RawSet; extern const lua_insert_t Insert; +extern const lua_remove_t Remove; +extern const lua_gettop_t GetTop; extern const lua_settop_t SetTop; +extern const lua_call_t Call; extern const lua_type_t Type; extern const lua_error_t Error; diff --git a/src/HookSecureFunc.cpp b/src/HookSecureFunc.cpp new file mode 100644 index 00000000..548b9218 --- /dev/null +++ b/src/HookSecureFunc.cpp @@ -0,0 +1,139 @@ +// This file is part of ClassicAPI. +// +// ClassicAPI is free software: you can redistribute it and/or modify it under the terms +// of the GNU Lesser 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 Lesser General Public License for more details. +// +// You should have received a copy of the GNU Lesser General Public License along with +// ClassicAPI. If not, see . + +#include "Game.h" + +namespace HookSecureFunc { + +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)`. +// +// Sequence: +// 1. Push orig + copies of args, `lua_call(MULTRET)` — pops them, +// pushes orig's results. Stack: `[args..., results...]`. +// 2. Push callback + copies of args, `lua_call(0)` — pops, pushes +// nothing (callback returns are discarded). +// 3. Remove the original args from the stack so only results +// remain. Return `nresults`. +// +// Modern `hooksecurefunc` semantics: original runs first, callback +// runs after with the same args (returns ignored), original's +// results propagate to the caller. No cap on return count. +int __fastcall HookWrapper(void *L) { + const int nargs = Game::Lua::GetTop(L); + + // (1) orig(...) — pops orig + nargs copies, pushes results + Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(1)); + for (int i = 1; i <= nargs; ++i) + Game::Lua::PushValue(L, i); + Game::Lua::Call(L, nargs, Game::Lua::MULTRET); + const int nresults = Game::Lua::GetTop(L) - nargs; + + // (2) callback(...) — pops callback + nargs copies, pushes 0 + Game::Lua::PushValue(L, Game::Lua::UpvalueIndex(2)); + for (int i = 1; i <= nargs; ++i) + Game::Lua::PushValue(L, i); + Game::Lua::Call(L, nargs, 0); + + // (3) Remove the original args from the bottom of the stack so + // only `[results...]` remain. lua_remove(L, 1) shifts down + // each call. + for (int i = 0; i < nargs; ++i) + Game::Lua::Remove(L, 1); + + return nresults; +} + +// `hooksecurefunc(name, callback)` — hooks a global by name, target +// table is `_G`. +// `hooksecurefunc(table, name, callback)` — hooks `table[name]`. +// +// In both cases the original function runs first and its results +// propagate; `callback` runs after with the same args (returns +// discarded). The "secure" label refers to taint propagation in +// 3.x+; on 1.12 it's just a post-hook with return preservation. +int __fastcall Script_HookSecureFunc(void *L) { + int targetIdx, nameIdx, callbackIdx; + const int t1 = Game::Lua::Type(L, 1); + + if (t1 == Game::Lua::TYPE_TABLE) { + // Three-arg form: (table, name, callback) + targetIdx = 1; + nameIdx = 2; + callbackIdx = 3; + } else if (t1 == Game::Lua::TYPE_STRING) { + // Two-arg form: (name, callback) — target = _G via pseudo- + // index. Don't push _G with `lua_pushvalue(GLOBALS_INDEX)`: + // it crashes (the pushvalue → setobj2s chain dereferences a + // bad TValue pointer for that pseudo-index). `lua_gettable` / + // `lua_settable` accept GLOBALS_INDEX as the table arg + // directly, so we use it that way without pushing. + targetIdx = Game::Lua::GLOBALS_INDEX; + nameIdx = 1; + callbackIdx = 2; + } else { + Game::Lua::Error(L, + "hooksecurefunc(table, name, callback) or hooksecurefunc(name, callback)"); + return 0; + } + + if (Game::Lua::Type(L, nameIdx) != Game::Lua::TYPE_STRING) { + Game::Lua::Error(L, "hooksecurefunc: name must be a string"); + return 0; + } + if (Game::Lua::Type(L, callbackIdx) != Game::Lua::TYPE_FUNCTION) { + Game::Lua::Error(L, "hooksecurefunc: callback must be a function"); + return 0; + } + + // Fetch target[name] — the original function. `gettable` uses + // metamethods, so frame methods (resolved via the frame + // metatable's __index) come back as callable closures, exactly + // what we want to wrap. + Game::Lua::PushValue(L, nameIdx); + Game::Lua::GetTable(L, targetIdx); + if (Game::Lua::Type(L, -1) != Game::Lua::TYPE_FUNCTION) { + Game::Lua::Error(L, "hooksecurefunc: target field is not a function"); + return 0; + } + + // Push callback as the second upvalue; orig is already on top + // from the GetTable above. + Game::Lua::PushValue(L, callbackIdx); + + // Build the wrapper as a C closure with (orig, callback) as the + // two upvalues. PushCClosure pops the upvalues from the stack + // and pushes the closure. + Game::Lua::PushCClosure(L, &HookWrapper, 2); + + // Install: target[name] = wrapper. SetTable expects the value + // on top and the key just below; push them in that order. + Game::Lua::PushValue(L, nameIdx); + Game::Lua::PushValue(L, -2); // duplicate the closure + Game::Lua::SetTable(L, targetIdx); + + return 0; +} + +} // namespace + +static void RegisterLuaFunctions() { + Game::Lua::RegisterGlobalFunction("hooksecurefunc", &Script_HookSecureFunc); +} + +static const Game::ModuleAutoRegister _autoreg{&RegisterLuaFunctions}; + +} // namespace HookSecureFunc diff --git a/src/Offsets.h b/src/Offsets.h index 74780918..e447dd16 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -666,7 +666,15 @@ enum Offsets { LUA_PUSH_NIL = 0x6F37F0, LUA_PUSH_BOOLEAN = 0x6F39F0, LUA_PUSH_STRING = 0x6F3890, - LUA_PUSH_VALUE = 0x6F30D0, // (was 0x6F3350, which is lua_replace — see docs/LuaCAPI.md) + // Verified empirically via `_classicapi_PushValueProbe` — + // pushes a number then dups via PushValue, checks GetTop tracks. + // **Doc note:** `docs/LuaCAPI.md` reports `0x6F30D0` as lua_pushvalue + // and `0x6F32B0` as lua_remove; both are wrong. `0x6F30D0` is + // actually `lua_remove` (has the shift-down loop and `decr_top`), + // and `0x6F3350` is `lua_pushvalue` (index-resolve → TValue copy + // to L->top → `add [ecx+8], 0x10` incr_top). `0x6F32B0` is + // `lua_replace` (single TValue copy + decr_top). + LUA_PUSH_VALUE = 0x6F3350, LUA_PUSH_CCLOSURE = 0x6F3920, LUA_NEW_TABLE = 0x6F3C90, LUA_GET_TABLE = 0x6F3A40, // (was 0x6F3EA0, which is lua_rawset) @@ -674,8 +682,12 @@ enum Offsets { LUA_SET_TABLE = 0x6F3E20, LUA_RAW_SET = 0x6F3EA0, LUA_INSERT = 0x6F31A0, + LUA_REMOVE = 0x6F30D0, // (was 0x6F32B0, which is lua_replace) + LUA_REPLACE = 0x6F32B0, LUA_TYPE = 0x6F3400, + LUA_GET_TOP = 0x6F3070, LUA_SET_TOP = 0x6F3080, + LUA_CALL = 0x6F4180, LUA_ERROR = 0x6F4940, // Global `lua_State *`. The engine keeps one main thread state here; we diff --git a/src/item/Tooltip.cpp b/src/item/Tooltip.cpp index f225735c..4eb3b3bf 100644 --- a/src/item/Tooltip.cpp +++ b/src/item/Tooltip.cpp @@ -105,8 +105,9 @@ static int __fastcall Script_GameTooltipSetInventoryItemByID(void *L) { // identical rings, identical trinkets), modern client behavior // is to render the lower-numbered slot — MAINHAND (16) before // OFFHAND (17), FINGER1 (11) before FINGER2 (12), TRINKET1 (13) - // before TRINKET2 (14). Confirmed against modern by the user; - // our ascending walk + first-match-break naturally matches. + // before TRINKET2 (14). Verified empirically against the modern + // client; our ascending walk + first-match-break naturally + // matches. int foundSlot = 0; for (int slot = Offsets::EQUIPMENT_SLOT_FIRST; slot <= Offsets::EQUIPMENT_SLOT_LAST; ++slot) {