From 09a98a4e45e55b554a0ecbd9dd939ce77ec5fe91 Mon Sep 17 00:00:00 2001 From: Matthew Wild Date: Thu, 14 Nov 2024 16:09:43 +0000 Subject: [PATCH] luv_cfpcall: Fix stack balancing after an uncaught error The default error handling code for printing uncaught errors uses luaL_tolstring(). This returns the resulting string, but also pushes it onto the stack. After we have printed it, it is safe to pop from the stack. Leaving it on the stack causes the stack to be unbalanced. Fixes https://github.com/luvit/luv/issues/735 (where a test case can be found) --- src/luv.c | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/luv.c b/src/luv.c index 9d602c46..7ae7e861 100644 --- a/src/luv.c +++ b/src/luv.c @@ -715,9 +715,11 @@ LUALIB_API int luv_cfpcall(lua_State* L, int nargs, int nresult, int flags) { case LUA_OK: break; case LUA_ERRMEM: - if ((flags & LUVF_CALLBACK_NOERRMSG) == 0) + if ((flags & LUVF_CALLBACK_NOERRMSG) == 0) { fprintf(stderr, "System Error: %s\n", luaL_tolstring(L, lua_absindex(L, -1), NULL)); + lua_pop(L, 1); // Remove error string pushed by luaL_tolstring() + } if ((flags & LUVF_CALLBACK_NOEXIT) == 0) exit(-1); lua_pop(L, 1); @@ -726,9 +728,11 @@ LUALIB_API int luv_cfpcall(lua_State* L, int nargs, int nresult, int flags) { case LUA_ERRRUN: case LUA_ERRERR: default: - if ((flags & LUVF_CALLBACK_NOERRMSG) == 0) + if ((flags & LUVF_CALLBACK_NOERRMSG) == 0) { fprintf(stderr, "Uncaught Error: %s\n", luaL_tolstring(L, lua_absindex(L, -1), NULL)); + lua_pop(L, 1); // Remove error string pushed by luaL_tolstring() + } if ((flags & LUVF_CALLBACK_NOEXIT) == 0) exit(-1); lua_pop(L, 1);