From c31b2008728babbc8738b88b593f2be40324369b Mon Sep 17 00:00:00 2001 From: Christopher Faulet Date: Mon, 3 May 2021 10:11:13 +0200 Subject: [PATCH] BUG/MINOR: hlua: Don't rely on top of the stack when using Lua buffers When the lua buffers are used, a variable number of stack slots may be used. Thus we cannot assume that we know where the top of the stack is. It was not an issue for lua < 5.4.3 (at least for small buffers). But 'socket:receive()' now fails with lua 5.4.3 because a light userdata is systematically pushed on the top of the stack when a buffer is initialized. To fix the bug, in hlua_socket_receive(), we save the index of the top of the stack before creating the buffer. This way, we can check the number of arguments, regardless anything was pushed on the stack or not. Note that the other buffer usages seem to be safe. This patch should solve the issue #1240. It should be backport to all stable branches. --- src/hlua.c | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/src/hlua.c b/src/hlua.c index e947370a9..2a6528f61 100644 --- a/src/hlua.c +++ b/src/hlua.c @@ -2130,7 +2130,7 @@ __LJMP static int hlua_socket_receive(struct lua_State *L) { int wanted = HLSR_READ_LINE; const char *pattern; - int type; + int lastarg, type; char *error; size_t len; struct hlua_socket *socket; @@ -2175,11 +2175,16 @@ __LJMP static int hlua_socket_receive(struct lua_State *L) if (lua_gettop(L) != 2) lua_replace(L, 2); + /* Save index of the top of the stack because since buffers are used, it + * may change + */ + lastarg = lua_gettop(L); + /* init buffer, and fill it with prefix. */ luaL_buffinit(L, &socket->b); /* Check prefix. */ - if (lua_gettop(L) >= 3) { + if (lastarg >= 3) { if (lua_type(L, 3) != LUA_TSTRING) WILL_LJMP(luaL_error(L, "Expect a 'string' for the prefix")); pattern = lua_tolstring(L, 3, &len);