关于lua源代码中的EXTRA_STACK宏

EXTRA_STACK是给栈额外预留的空间:

c 复制代码
/* extra stack space to handle TM calls and some other extras */
#define EXTRA_STACK 5

这样top之上的几个位置就可以先用,后面再增加栈空间:

c 复制代码
static void callTM (lua_State *L, const TValue *f, const TValue *p1,
                    const TValue *p2, const TValue *p3) {
  setobj2s(L, L->top, f);  /* push function */
  setobj2s(L, L->top+1, p1);  /* 1st argument */
  setobj2s(L, L->top+2, p2);  /* 2nd argument */
  setobj2s(L, L->top+3, p3);  /* 3th argument */
  luaD_checkstack(L, 4);
  L->top += 4;
  luaD_call(L, L->top - 4, 0);
}

我看到这里就想,干嘛不提前luaD_checkstack(L, 4);

c 复制代码
static void callTM (lua_State *L, const TValue *f, const TValue *p1,
                    const TValue *p2, const TValue *p3) {
  setobj2s(L, L->top, f); /* push function */
  setobj2s(L, L->top+1, p1); /* 1st argument */
  setobj2s(L, L->top+2, p2); /* 2nd argument */
  setobj2s(L, L->top+3, p3); /* 3th argument */
  luaD_checkstack(L, 4);
  L->top += 4;
  luaD_call(L, L->top - 4, 0);
}

但是用AddressSanitizer工具测试发现,在执行源码自带的trace-globals.lua时,setobj2s(L, L->top+3, p3);会报使用已free内存。

经过查看代码发现,p3可能是栈上的数据,luaD_checkstack中可能会调用luaD_reallocstack导致p3不可用。

所以luaD_checkstack要放到后面执行。

相关推荐
镜水灵动1 天前
redisTemplate执行lua脚本报错‘for‘ initial value must be a number
lua·springboot
IMPYLH2 天前
Lua 的 Coroutine(协程)模块
开发语言·笔记·后端·中间件·游戏引擎·lua
IMPYLH3 天前
Lua 的 xpcall 函数
开发语言·笔记·后端·游戏引擎·lua
一帘忧梦4 天前
linux 系统rcs脚本启动
linux·运维·lua
IMPYLH4 天前
Lua 的 warn 函数
java·开发语言·笔记·junit·lua
石头wang4 天前
postman如何设置鉴权authorization header(怎么只设置一次,统一管理,不要每个request重复设置)
测试工具·lua·postman
qq_348231855 天前
Redis 事务(MULTI/EXEC)与 Lua 脚本的核心区别
数据库·redis·lua
没有腰的嘟嘟嘟5 天前
从 0 到 1:我如何用 Spring Boot 3 + Redis 打造一个生产级通用幂等与防重中间件(含图解 + 代码 + 案例)
spring boot·redis·中间件·lua
小雨下雨的雨6 天前
第5篇:Redis事务与Lua脚本
redis·junit·lua
BuHuaX6 天前
Lua入门
开发语言·unity·junit·c#·游戏引擎·lua