Limiting memory usage of Lua script?

I saw how he said many times that there is no way to limit the use of Lua script memory, including people jumping through hoops so that Lua scripts cannot create functions and tables. But given that lua_newstate allows you to pass in a custom allocator, is it possible to use it to limit memory consumption? In the worst case scenario, you can use an arena-based allocator and set a hard limit even on the amount of memory that can be used by fragmentation.

Did I miss something?

+6
source share
1 answer
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; } } 

For Lua to use your dispenser, you can use

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

Note. I have not tested the source, but it should work.

+9
source

Source: https://habr.com/ru/post/910526/


All Articles