gpt4 book ai didi

lua - 限制Lua脚本的内存使用?

转载 作者:行者123 更新时间:2023-12-01 17:40:45 25 4
gpt4 key购买 nike

我多次看到有人说没有办法限制 Lua 脚本的内存使用,包括人们千方百计阻止 Lua 脚本创建函数和表。但是考虑到 lua_newstate 允许您传递自定义分配器,难道不能用它来限制内存消耗吗?最坏的情况是,可以使用基于竞技场的分配器,甚至可以对碎片可以使用的内存量进行硬性限制。

我在这里遗漏了什么吗?

最佳答案

 static void *l_alloc_restricted (void *ud, void *ptr, size_t osize, size_t nsize)
{
const int MAX_SIZE = 1024; /* set limit here */
int *used = (int *)ud;

if(ptr == NULL) {
/*
* <http://www.lua.org/manual/5.2/manual.html#lua_Alloc>:
* When ptr is NULL, osize encodes the kind of object that Lua is
* allocating.
*
* Since we don’t care about that, just mark it as 0.
*/
osize = 0;
}

if (nsize == 0)
{
free(ptr);
*used -= osize; /* substract old size from used memory */
return NULL;
}
else
{
if (*used + (nsize - osize) > MAX_SIZE) /* too much memory in use */
return NULL;
ptr = realloc(ptr, nsize);
if (ptr) /* reallocation successful? */
*used += (nsize - osize);
return ptr;
}
}

要让 Lua 使用你的分配器,你可以使用

 int *ud = malloc(sizeof(int)); *ud = 0;
lua_State *L = lua_State *lua_newstate (l_alloc_restricted, ud);

注意:我尚未测试源代码,但它应该可以工作。

关于lua - 限制Lua脚本的内存使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9671793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com