From 36f3661b98e7048ea3b2d65c4a558911639756a1 Mon Sep 17 00:00:00 2001 From: Brues <5278969+brues-code@users.noreply.github.com> Date: Sun, 1 Nov 2026 15:37:11 -0600 Subject: [PATCH] feat(lua): GetCallstackHeight, GetErrorCallstackHeight, SetErrorCallstackHeight Adds the three call stack heights an error handler uses to start its stack at the code that failed: debugstack(GetCallstackHeight() - (GetErrorCallstackHeight() - 1)) A height counts levels as lua_getstack (0x006FBAA0) does, and so as debugstack does: C functions and lost tail calls count, and level 1 is the caller. 1.12.1 records no error height, but every error report runs one C function, FrameScriptCallErrorHandler (0x00703B40, __fastcall(L)). It pushes the seterrorhandler function (registry ref 0x008722CC), moves it under the message and lua_calls it. Nothing calls it directly: state open pushes it as a C closure and refs it (0x008722C8). Every script pcall passes that closure as the errfunc, so Lua calls it at the point of the error before the stack unwinds; a chunk that fails to compile is reported by a pcall of it (0x00704AE0). ClassicAPI's securecall, hooksecurefunc and script runners pass the same ref. So while any handler runs, that closure's level sits directly above the code that failed. GetErrorCallstackHeight walks the levels with lua_getstack and lua_getinfo "f", finds the innermost one whose function is 0x00703B40 (lua_tocfunction, 0x006F3720) and answers the height below it, or nil when no error is being reported. There is no hook, and nothing is recorded, so a handler that fails part way leaves nothing behind. SetErrorCallstackHeight sets the height for a handler called with no error raised. It applies only while no 0x00703B40 level is on the stack, so a value left set by a failed handler cannot move a later error's stack. A new Lua state starts with no value set. Users: - The Lua error window takes its stack this way, so it starts at the failing code even when another addon wraps the handler. - CallErrorHandler and assertsafe set the height around their direct handler call, so they report from their caller. - Game::Lua gains GetStack, GetInfo and ToCFunction; SourceLocation uses them in place of its own copies. Docs: the xpcall and coroutine notes said error() returns without raising. Stock error (0x00702970) ends in lua_error (0x006F4440) and raises. pfUI replaces the global error with one that prints and returns, which is what those notes described. Tested in game: with seterrorhandler wrapping the old handler, a nil index in a local function f showed a stack that starts at f. --- README.md | 2 +- docs/API.md | 60 +++++-- src/Game.cpp | 3 + src/Game.h | 8 + src/Offsets.h | 12 ++ src/baselib/ErrorCallstack.cpp | 146 ++++++++++++++++++ .../FrameXML/ScriptErrorsFrame.lua | 25 +-- .../AddOns/!!!ClassicAPI/Util/ErrorUtil.lua | 9 +- src/frame/SourceLocation.cpp | 6 +- 9 files changed, 237 insertions(+), 34 deletions(-) create mode 100644 src/baselib/ErrorCallstack.cpp diff --git a/README.md b/README.md index 0ec405e5..61d95f7f 100644 --- a/README.md +++ b/README.md @@ -105,7 +105,7 @@ In the Frame rows, a name that starts with `:` is a method of the widget that th | [Loot](docs/API.md#loot) | `C_Loot.GetNearbyLootableUnits`, `C_Loot.GetLastScanResults`, `C_Loot.IsScanInProgress`, `C_Loot.LootAllCorpses`, `C_Loot.LootUnit`, `C_Loot.LootUnitItem`, `C_Loot.ScanNearbyLoot` | | [LootHistory](docs/API.md#loothistory) | `C_LootHistory.GetNumItems`, `C_LootHistory.GetItem`, `C_LootHistory.GetPlayerInfo`, `C_LootHistory.Clear` | | [LossOfControl](docs/API.md#lossofcontrol) | `C_LossOfControl.GetActiveLossOfControlData`, `C_LossOfControl.GetActiveLossOfControlDataCount`, `C_LossOfControl.GetSchoolLockout` | -| [Lua](docs/API.md#lua) | `collectgarbage` (5.1 options), `coroutine.create`, `coroutine.resume`, `coroutine.running`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `CreateFromMixins`, `math.fmod`, `math.huge`, `math.modf`, `Mixin`, `select`, `strcmputf8i`, `strconcat`, `string.concat`, `string.gmatch`, `string.gsub` (table replacement), `string.join`, `string.match`, `string.reverse`, `string.split`, `string.trim`, `strjoin`, `strlenutf8`, `strmatch`, `strreplace`, `strrev`, `strsplit`, `strsplittable`, `strtrim`, `table.count`, `table.maxn`, `table.wipe`, `unpack` (range args), `wipe`, `xpcall` (argument forwarding) | +| [Lua](docs/API.md#lua) | `collectgarbage` (5.1 options), `coroutine.create`, `coroutine.resume`, `coroutine.running`, `coroutine.status`, `coroutine.wrap`, `coroutine.yield`, `CreateFromMixins`, `GetCallstackHeight`, `GetErrorCallstackHeight`, `math.fmod`, `math.huge`, `math.modf`, `Mixin`, `select`, `SetErrorCallstackHeight`, `strcmputf8i`, `strconcat`, `string.concat`, `string.gmatch`, `string.gsub` (table replacement), `string.join`, `string.match`, `string.reverse`, `string.split`, `string.trim`, `strjoin`, `strlenutf8`, `strmatch`, `strreplace`, `strrev`, `strsplit`, `strsplittable`, `strtrim`, `table.count`, `table.maxn`, `table.wipe`, `unpack` (range args), `wipe`, `xpcall` (argument forwarding) | | [Macros](docs/API.md#macros) | `C_Macro.CreateMacro`, `C_Macro.EditMacro`, `C_Macro.SetMacroDisplay`, `DeleteMacro` / `EditMacro` / `GetMacroInfo` / `PickupMacro` by name, `GetLooseMacroIcons`, `GetLooseMacroItemIcons`, `GetMacroBody`, `GetMacroIcons`, `GetMacroItem`, `GetMacroItemIcons`, `GetMacroSpell`, `GetRunningMacro`, `GetRunningMacroButton`, `RunMacroText`, `SetMacroItem`, `SetMacroSpell`, `StopMacro` | | [Mail](docs/API.md#mail) | `GetInboxItemLink`, `GetSendMailItemLink` | | [Map](docs/API.md#map) | `C_Map.CanSetUserWaypointOnMap`, `C_Map.ClearUserWaypoint`, `C_Map.GetAreaInfo`, `C_Map.GetAreas`, `C_Map.GetAreaTriggerInfo`, `C_Map.GetAreaTriggers`, `C_Map.GetBestMapForUnit`, `C_Map.GetFallbackWorldMapID`, `C_Map.GetMapAreaIDs`, `C_Map.GetMapArtLayers`, `C_Map.GetMapArtLayerTextures`, `C_Map.GetMapChildrenInfo`, `C_Map.GetMapInfo`, `C_Map.GetMapInfoAtPosition`, `C_Map.GetMapOverlays`, `C_Map.GetMapPosFromWorldPos`, `C_Map.GetMapRectOnMap`, `C_Map.GetMapWorldSize`, `C_Map.GetPlayerMapPosition`, `C_Map.GetUserWaypoint`, `C_Map.GetUserWaypointFromHyperlink`, `C_Map.GetUserWaypointHyperlink`, `C_Map.GetUserWaypointPositionForMap`, `C_Map.GetWorldPosFromMapPos`, `C_Map.HasUserWaypoint`, `C_Map.MapHasArt`, `C_Map.SetUserWaypoint` | diff --git a/docs/API.md b/docs/API.md index cf76d123..f75de25e 100644 --- a/docs/API.md +++ b/docs/API.md @@ -654,6 +654,7 @@ build instructions. - [`select(index, ...)`](#selectindex-) - [`unpack(list [, i [, j]])`](#unpacklist--i--j) - [`xpcall(f, msgh [, arg1, ...])`](#xpcallf-msgh--arg1-) + - [`GetCallstackHeight()` / `GetErrorCallstackHeight()` / `SetErrorCallstackHeight([height])`](#getcallstackheight--geterrorcallstackheight--seterrorcallstackheightheight) - [`collectgarbage(opt [, arg])`](#collectgarbageopt--arg) - [`table.wipe(t)` / `wipe(t)`](#tablewipet--wipet) - [`table.count(tbl)`](#tablecounttbl) @@ -15366,12 +15367,42 @@ xpcall(function() return f(a, b) end, handler) Available to in-game addons and glue-screen code alike. -Note that `error("...")` does not reach the handler. WoW replaces Lua's -`error` with one that reports through `geterrorhandler()` and then returns -normally, so `f` looks like it finished and you get `true` with the message -printed to chat. Real runtime errors — indexing or calling nil, arithmetic -on a non-number — do reach the handler. To abort into it deliberately, cause -one of those: `(nil)()` is the shortest. +`error("...")` reaches the handler, the same as a runtime error. An addon +can replace the global `error` with a function that does not raise. For +example, pfUI's `error` prints the message to the chat frame and returns. +Then `f` continues, and `xpcall` returns `true`. + +### `GetCallstackHeight()` / `GetErrorCallstackHeight()` / `SetErrorCallstackHeight([height])` + +An error handler uses these functions to find the code that caused an +error. The handler can then show the stack from that code, and not from +the handler. + +- `GetCallstackHeight()` returns the number of call levels on the stack. + The function that calls `GetCallstackHeight` is level 1. C functions + count as levels, the same as in `debugstack`. +- `GetErrorCallstackHeight()` returns the stack height of the code that + caused the error, while the game reports an error to the error handler. + If code calls the error handler directly, `GetErrorCallstackHeight` + returns the value that `SetErrorCallstackHeight` set, or nil. +- `SetErrorCallstackHeight(height)` sets the height for an error handler + that code calls directly, with no error. `SetErrorCallstackHeight(nil)` + removes the value. `CallErrorHandler` and `assertsafe` use this function + to report from the code that called them. + +This function returns the stack from the code that caused the error: + +```lua +local function ErrorStack() + local errorHeight = GetErrorCallstackHeight() + if not errorHeight then + return debugstack(2) + end + return debugstack(GetCallstackHeight() - errorHeight + 1) +end +``` + +Works in the world and on the login screen. ### `collectgarbage(opt [, arg])` @@ -15757,21 +15788,18 @@ Returns: - The coroutine isn't suspended. `errMsg` is `"cannot resume coroutine"`, where `` is `running`, `normal` or `dead`. - - The body hit a Lua VM error. `errMsg` is the formatted error - string with file:line prefix. + - The body raised an error: a Lua VM error, or a call to `error`. + `errMsg` is the error message, usually with a file:line prefix. Passing more arguments, or getting back more results, than the stack can hold raises `too many arguments to resume` / `too many results to resume`. -**Caveat — `error()` doesn't propagate.** WoW replaces Lua's -`error()` global with a soft handler that calls -`geterrorhandler()(msg)` and returns normally instead of -longjmp'ing. So `error("msg")` inside a coroutine body looks like -a clean return to `resume` — the message gets printed to chat as -a side effect and `resume` returns `true` with no values. Real VM -errors (calling `nil`, indexing `nil`, etc.) still propagate -through the standard `false, msg` path. +**Caveat — an addon can change `error()`.** If an addon replaces +the global `error` with a function that does not raise, +`error("msg")` returns normally. pfUI does this: its `error` prints +the message to the chat frame. In a coroutine body, the body then +continues, and `resume` does not return `false`. #### `coroutine.yield(...)` diff --git a/src/Game.cpp b/src/Game.cpp index 9155071c..ea151b43 100644 --- a/src/Game.cpp +++ b/src/Game.cpp @@ -89,6 +89,9 @@ namespace Lua { F(ToPointer, lua_topointer, LUA_TO_POINTER) \ F(ToThread, lua_tothread, LUA_TO_THREAD) \ F(IsCFunction, lua_iscfunction, LUA_IS_C_FUNCTION)\ + F(ToCFunction, lua_tocfunction, LUA_TO_C_FUNCTION)\ + F(GetStack, lua_getstack, LUA_GET_STACK) \ + F(GetInfo, lua_getinfo, LUA_GET_INFO) \ F(XMove, lua_xmove, LUA_X_MOVE) \ F(NewThread, lua_newthread, LUA_NEW_THREAD) \ F(Resume, lua_resume, LUA_RESUME) \ diff --git a/src/Game.h b/src/Game.h index bba131b1..4a16efb8 100644 --- a/src/Game.h +++ b/src/Game.h @@ -298,6 +298,11 @@ using lua_error_t = void(__cdecl *)(void *L, const char *fmt, ...); using lua_topointer_t = const void *(__fastcall *)(void *L, int idx); using lua_tothread_t = void *(__fastcall *)(void *L, int idx); using lua_iscfunction_t = int(__fastcall *)(void *L, int idx); +using lua_tocfunction_t = CFunction(__fastcall *)(void *L, int idx); +// Fill a lua_Debug (Offsets::SIZEOF_LUA_DEBUG bytes) for a call level / +// with the fields `what` names. Level 0 is the running C function. +using lua_getstack_t = int(__fastcall *)(void *L, int level, void *ar); +using lua_getinfo_t = int(__fastcall *)(void *L, const char *what, void *ar); using lua_xmove_t = void(__fastcall *)(void *from, void *to, int n); // `lua_newthread` returns the new `lua_State *` in eax, but Ghidra // infers `void` because the inner call's value just flows through. @@ -370,6 +375,9 @@ extern const lua_error_t Error; extern const lua_topointer_t ToPointer; extern const lua_tothread_t ToThread; extern const lua_iscfunction_t IsCFunction; +extern const lua_tocfunction_t ToCFunction; +extern const lua_getstack_t GetStack; +extern const lua_getinfo_t GetInfo; extern const lua_xmove_t XMove; extern const lua_newthread_t NewThread; extern const lua_resume_t Resume; diff --git a/src/Offsets.h b/src/Offsets.h index 6f787f8e..7ad15da9 100644 --- a/src/Offsets.h +++ b/src/Offsets.h @@ -359,6 +359,13 @@ enum Offsets { // read as `*(int*)VAR_FRAMESCRIPT_ERROR_HANDLER_REF`, pushed via // lua_rawgeti(REGISTRY, ref). Set once at engine init. VAR_FRAMESCRIPT_ERROR_HANDLER_REF = 0x008722C8, + // The C function that ref holds (benilla FrameScriptCallErrorHandler), + // `int __fastcall(L)`: when the seterrorhandler ref (0x008722CC) is not + // -1 it pushes that function (lua_rawgeti REGISTRY), moves it under the + // message (lua_insert -2), lua_call(1, 1)s it and returns 1. No code + // calls it directly; state open pushes it as a C closure and refs it + // (0x00703A8C). Verified by disassembly. + FUN_FRAMESCRIPT_CALL_ERROR_HANDLER = 0x00703B40, // The base Frame script-name resolver — __thiscall(frame, const char *name) // -> int* slot, 0 for an unknown name. Maps the standard base-frame scripts // to their 8-byte {handler, context} slots on the frame (OnLoad@+0x118, @@ -8790,6 +8797,11 @@ enum Offsets { // otherwise. Used by `coroutine.create` to reject C functions // (Lua 5.0 only allows Lua-defined functions as coroutine bodies). LUA_IS_C_FUNCTION = 0x6F34A0, + // `lua_tocfunction(L, idx)` — the C function of a C closure, else null. + // `__fastcall(L, idx)`: index2adr (0x6F3410) on the same registers, tag + // 6, the C byte at closure+6, the function at closure+0xC (benilla-re + // bytes; the engine never calls it, so Ghidra has no function there). + LUA_TO_C_FUNCTION = 0x6F3720, // `lua_tothread(L, idx)` — returns the embedded `lua_State *` for // type-8 (LUA_TTHREAD) TValues, NULL for anything else. Used by // the `coroutine` library to extract the coroutine pointer from a diff --git a/src/baselib/ErrorCallstack.cpp b/src/baselib/ErrorCallstack.cpp new file mode 100644 index 00000000..b0678e61 --- /dev/null +++ b/src/baselib/ErrorCallstack.cpp @@ -0,0 +1,146 @@ +// 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 . + +// `GetCallstackHeight()`, `GetErrorCallstackHeight()` and +// `SetErrorCallstackHeight([height])` — retail's call stack heights. Its +// error handler turns them into the debugstack level of the code that +// failed, however many functions sit between that code and the handler: +// debugstack(GetCallstackHeight() - (GetErrorCallstackHeight() - 1)) +// A height counts call levels as lua_getstack does, and so as debugstack +// does: C functions and lost tail calls count, and level 1 is the caller of +// the C function that asks. +// +// 1.12 records no error height, and needs none. Every error report runs the +// engine's error function (FUN_FRAMESCRIPT_CALL_ERROR_HANDLER) as a C +// closure: each script pcall passes it as the errfunc, so Lua calls it at +// the point of the error before the stack unwinds, and a chunk that fails +// to compile is reported by a pcall of it (FUN_LUA_RUN_STRING). It calls the +// seterrorhandler function with lua_call. So while any handler runs, that +// closure's level is on the stack directly above the code that failed, and +// GetErrorCallstackHeight answers the height below the innermost one. +// Nothing is recorded, so a handler that fails part way leaves nothing +// behind, and a nested error finds its own level. +// +// SetErrorCallstackHeight is for a handler called directly, with no error +// raised (retail's CallErrorHandler and assertsafe): with no engine level on +// the stack, GetErrorCallstackHeight answers the value set. An engine level +// wins over it, so a value a failed handler left set does not move the +// stack of a later error. Retail's order between the two is not known; no +// retail code sets the value around a raised error. + +#include "Game.h" +#include "Offsets.h" + +#include +#include + +namespace BaseLib::ErrorCallstack { + +namespace { + +std::optional g_setHeight; + +// The number of call levels below the running C function. +int Height(void *L) { + alignas(4) uint8_t ar[Offsets::SIZEOF_LUA_DEBUG]; + int height = 0; + while (Game::Lua::GetStack(L, height + 1, ar)) + ++height; + return height; +} + +// The innermost level whose function is the engine's error function, or 0 +// when no error is being reported. +int ErrorFunctionLevel(void *L) { + const auto errorFunction = reinterpret_cast(Offsets::FUN_FRAMESCRIPT_CALL_ERROR_HANDLER); + alignas(4) uint8_t ar[Offsets::SIZEOF_LUA_DEBUG]; + for (int level = 1; Game::Lua::GetStack(L, level, ar); ++level) { + Game::Lua::GetInfo(L, "f", ar); // the level's function; nil for a lost tail call + const bool found = Game::Lua::ToCFunction(L, -1) == errorFunction; + Game::Lua::SetTop(L, -2); + if (found) + return level; + } + return 0; +} + +int __fastcall Script_GetCallstackHeight(void *L) { + Game::Lua::PushNumber(L, Height(L)); + return 1; +} + +int __fastcall Script_GetErrorCallstackHeight(void *L) { + const int level = ErrorFunctionLevel(L); + if (level > 0) + Game::Lua::PushNumber(L, Height(L) - level); + else if (g_setHeight) + Game::Lua::PushNumber(L, *g_setHeight); + else + Game::Lua::PushNil(L); + return 1; +} + +int __fastcall Script_SetErrorCallstackHeight(void *L) { + if (Game::Lua::Type(L, 1) <= Game::Lua::TYPE_NIL) + g_setHeight.reset(); + else if (Game::Lua::IsNumber(L, 1)) + g_setHeight = static_cast(Game::Lua::ToNumber(L, 1)); + else + Game::Lua::Error(L, "Usage: SetErrorCallstackHeight([height])"); + return 0; +} + +const Game::Doc::Field kHeightRets[] = { + Game::Doc::Req("height", "number", "The calling function's level and every level below it."), +}; +const Game::Doc::Field kErrorHeightRets[] = { + Game::Doc::Opt("height", "number", nullptr, "The stack height of the code that caused the error."), +}; +const Game::Doc::Field kSetArgs[] = { + Game::Doc::Opt("height", "number", nullptr, "The height to return, or nil to clear it."), +}; +const Game::Doc::Function kGetCallstackHeight{ + "Returns the number of call levels on the stack, counting the calling function as level 1.", + {}, kHeightRets, "FrameScriptGlobals"}; +const Game::Doc::Function kGetErrorCallstackHeight{ + "Returns the call stack height of the code that caused the error being handled, or nil when no error is being handled.", + {}, kErrorHeightRets, "FrameScriptGlobals"}; +const Game::Doc::Function kSetErrorCallstackHeight{ + "Sets the height that GetErrorCallstackHeight returns for an error handler called with no error raised.", + kSetArgs, {}, "FrameScriptGlobals"}; + +// A new Lua state starts with no height set. +void RegisterInGame() { + g_setHeight.reset(); + Game::Lua::RegisterGlobalFunction("GetCallstackHeight", &Script_GetCallstackHeight, &kGetCallstackHeight); + Game::Lua::RegisterGlobalFunction("GetErrorCallstackHeight", &Script_GetErrorCallstackHeight, + &kGetErrorCallstackHeight); + Game::Lua::RegisterGlobalFunction("SetErrorCallstackHeight", &Script_SetErrorCallstackHeight, + &kSetErrorCallstackHeight); +} + +void RegisterGlue() { + g_setHeight.reset(); + Game::Lua::RegisterGlueFunction("GetCallstackHeight", &Script_GetCallstackHeight, &kGetCallstackHeight); + Game::Lua::RegisterGlueFunction("GetErrorCallstackHeight", &Script_GetErrorCallstackHeight, + &kGetErrorCallstackHeight); + Game::Lua::RegisterGlueFunction("SetErrorCallstackHeight", &Script_SetErrorCallstackHeight, + &kSetErrorCallstackHeight); +} + +const Game::ModuleAutoRegister _autoreg{&RegisterInGame}; +const Game::GlueModuleAutoRegister _autoregGlue{&RegisterGlue}; + +} // namespace + +} // namespace BaseLib::ErrorCallstack diff --git a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ScriptErrorsFrame.lua b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ScriptErrorsFrame.lua index b85acf5e..c60d745f 100644 --- a/src/embed/AddOns/!!!ClassicAPI/FrameXML/ScriptErrorsFrame.lua +++ b/src/embed/AddOns/!!!ClassicAPI/FrameXML/ScriptErrorsFrame.lua @@ -23,18 +23,25 @@ -- - The text is a ScrollingEditBoxTemplate with a MinimalScrollBar, the -- ScrollBox pair retail uses for scrolling edit boxes, not retail's -- ScrollFrameTemplate, which ClassicAPI does not port. --- - The stack starts at a fixed level, as in 3.3.5; 1.12 has no --- GetErrorCallstackHeight. The engine's error function (0x703B40) is C --- and calls the handler, so from the SetText slot level 1 is the slot, --- 2 is _ERRORMESSAGE, 3 is that C function and 4 is the code that failed. --- !BugGrabber's GrabError reads level 4 from the same slot. A handler --- that chains to _ERRORMESSAGE adds one level on top. --- - No Locals section: 1.12 has no debuglocals. +-- - The stack is retail's GetErrorData without the locals, taken in the +-- SetText slot: GetErrorCallstackHeight finds the code that failed +-- however many handlers sit between it and the slot. 1.12 has no +-- debuglocals. -- - No scriptErrors cvar (1.12 always shows errors), no LUA_WARNING, no -- gamepad legend. -- - Lua 5.0: no `...` expression, no # operator. -DEBUGLOCALS_LEVEL = 4; +local function GetErrorStack() + -- Example of how debug stack level is calculated + -- Current stack: [1, 2, 3, 4, 5] (current function is at 1, total current height is 5) + -- Stack at time of error: [1, 2] (these are currently now index 4 and 5, but at the time of error the stack height is 2) + -- To calcuate the level to debug (4): curentStackHeight - (errorStackHeight - 1) = 5 - (2 - 1) = 4 + local currentStackHeight = GetCallstackHeight(); + local errorCallStackHeight = GetErrorCallstackHeight(); + local errorStackOffset = errorCallStackHeight and (errorCallStackHeight - 1); + local debugStackLevel = currentStackHeight - (errorStackOffset or 0); + return debugstack(debugStackLevel); +end local ERROR_FORMAT = "|cffffd200Message:|r|cffffffff %s|r\n" .. "|cffffd200Time:|r|cffffffff %s|r\n" @@ -61,7 +68,7 @@ function ScriptErrorsFrame_OnLoad(self) ScrollUtil.RegisterScrollBoxWithScrollBar(scrollBox, self.ScrollBar); ScriptErrors_Message.SetText = function(_, message) - ScriptErrorsFrame_OnError(message, debugstack(DEBUGLOCALS_LEVEL)); + ScriptErrorsFrame_OnError(message, GetErrorStack()); end ScriptErrors.Show = function() end end diff --git a/src/embed/AddOns/!!!ClassicAPI/Util/ErrorUtil.lua b/src/embed/AddOns/!!!ClassicAPI/Util/ErrorUtil.lua index ec35449a..95f1e810 100644 --- a/src/embed/AddOns/!!!ClassicAPI/Util/ErrorUtil.lua +++ b/src/embed/AddOns/!!!ClassicAPI/Util/ErrorUtil.lua @@ -1,13 +1,14 @@ -- Backport of retail's Blizzard_SharedXMLBase/ErrorUtil.lua. -- -- Implementation differences from the retail source: --- - 1.12 has no SetErrorCallstackHeight / GetCallstackHeight, so an --- error's stack starts at assertsafe rather than at its caller. -- - Lua 5.0 has no `...` as an expression and strings have no methods; -- varargs go through the implicit `arg` table and string.format. function CallErrorHandler(...) - return geterrorhandler()(unpack(arg)); + SetErrorCallstackHeight(GetCallstackHeight() - 1); -- report error from the previous function + local result = geterrorhandler()(unpack(arg)); + SetErrorCallstackHeight(nil); + return result; end function assertsafe(cond, msgStringOrFunction, ...) @@ -19,6 +20,7 @@ function assertsafe(cond, msgStringOrFunction, ...) error = msgStringOrFunction(unpack(arg)); end + SetErrorCallstackHeight(GetCallstackHeight() - 1); -- report error from the previous function if geterrorhandler() then geterrorhandler()(error); elseif ProcessExceptionClient then @@ -26,6 +28,7 @@ function assertsafe(cond, msgStringOrFunction, ...) ProcessExceptionClient(error, error, framesToSkip); end + SetErrorCallstackHeight(nil); end -- Parity with regular 'assert' which returns the input. diff --git a/src/frame/SourceLocation.cpp b/src/frame/SourceLocation.cpp index 7e88922a..d57bc0a2 100644 --- a/src/frame/SourceLocation.cpp +++ b/src/frame/SourceLocation.cpp @@ -68,8 +68,6 @@ namespace Frame::SourceLocation { namespace { -using GetStack_t = int(__fastcall *)(void *L, int level, void *ar); -using GetInfo_t = int(__fastcall *)(void *L, const char *what, void *ar); using ChunkId_t = void(__fastcall *)(char *out, const char *source, int bufflen); // Per-frame location, keyed by the frame object. @@ -103,11 +101,9 @@ bool Excluded(const char *source) { // "file:line" of the nearest Lua function above the running C function on // L's call stack that is not in an excluded file. False when there is none. bool CaptureCaller(void *L, char *out, size_t size) { - auto getStack = reinterpret_cast(Offsets::LUA_GET_STACK); - auto getInfo = reinterpret_cast(Offsets::LUA_GET_INFO); alignas(4) uint8_t ar[Offsets::SIZEOF_LUA_DEBUG]; for (int level = 1; level < 32; ++level) { - if (!getStack(L, level, ar) || !getInfo(L, "Sl", ar)) + if (!Game::Lua::GetStack(L, level, ar) || !Game::Lua::GetInfo(L, "Sl", ar)) return false; const int line = Game::Read(ar, Offsets::OFF_LUA_DEBUG_CURRENTLINE); if (line <= 0)