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

相关推荐
weixin_471383035 小时前
Node.js + Express 入门实战笔记-01-基础
node.js·lua·express
闪电悠米6 小时前
黑马点评-Redis ZSet-实现关注 Feed 流
服务器·网络·数据库·redis·缓存·junit·lua
Chris-zz1 天前
lua流程控制
开发语言·lua
多彩电脑1 天前
Lua基础入门
开发语言·lua
ellis19702 天前
Lua的module和require
unity·lua
塵觴葉2 天前
基于Lua协程的简单任务管理
开发语言·lua
我是一颗柠檬3 天前
【Java项目技术亮点】Redis Lua脚本原子化操作:高并发场景下的终极武器
java·redis·lua
笑虾4 天前
Frida Hook Cocos2dx lua 3.15 的 lua 脚本
lua·cocos2d
IT策士4 天前
Redis 从入门到精通:事务与 Lua 脚本
redis·junit·lua