关于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要放到后面执行。

相关推荐
钟智强6 天前
CVE-2025-49844高危预警:Redis Lua脚本引擎UAF漏洞深度剖析与POC实战
数据库·redis·web安全·junit·lua
闲人编程7 天前
聚合管道与复杂查询
开发语言·oracle·lua·match·查询·聚合·lookup
会周易的程序员8 天前
cNetgate物联网网关内存数据表和数据视图模块架构
c语言·c++·物联网·架构·lua·iot
会周易的程序员9 天前
cNetgate插件架构设计详解 动态库 脚本二开lua, python, javascript
javascript·c++·python·物联网·lua·iot
白太岁12 天前
Redis:(3) Lua 与 Redis、基于连接池的 Facade 模式封装
数据库·c++·redis·lua·外观模式
Maguyusi17 天前
go 批量生成c++和lua proto文件
c++·golang·lua·protobuf
foxsen_xia18 天前
Kamailio通过Lua写路由
开发语言·lua·信息与通信
码农周20 天前
nginx + Lua 实现域名访问日志统计
nginx·lua
難釋懷21 天前
Lua脚本解决多条命令原子性问题
开发语言·lua
AI_567824 天前
Postman接口测试提速技巧:批量请求+智能断言实践
测试工具·lua·postman