2012-03-12 116 views
6

我已經多次說過,沒有辦法限制Lua腳本的內存使用,包括人們跳過箍環來防止Lua腳本創建函數和表。但考慮到lua_newstate允許你傳遞一個自定義分配器,難道不能用它來限制內存消耗嗎?在最壞的情況下,人們可以使用基於競技場的分配器,並且對硬盤分區可以使用的內存量進行限制。限制Lua腳本的內存使用情況?

我在這裏錯過了什麼嗎?

+1

「我多次看過它說」兩個字:需要引用。 – 2012-03-12 17:40:46

+0

沙盒上的Lua wiki頁面提到將內存用作可能的攻擊,但沒有提及限制它的方式:http://lua-users.org/wiki/SandBoxes。我想我誤解了這個頁面,它談論的是「Looah」而不是Lua:http://www.sk89q.com/2010/03/sandboxed-lua-via-php/ – 2012-03-17 15:46:27

+1

「他們總是試圖阻止創建函數或表。「那是因爲他們不希望他們創建表和函數。他們想要保持全球範圍。與防止內存被使用相比,這是一個不同的任務。 – 2012-03-17 18:06:39

回答

9
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); 

注:我沒有測試過的來源,但它應該工作。

+0

謝謝,雖然我想知道爲什麼我從來沒有見過任何人使用這種技術;他們總是試圖阻止創建函數或表。 – 2012-03-17 15:29:14

+0

現在我又看了一遍,看起來原因是人們正在嘗試從Lua內部的沙箱代碼。 – 2012-03-17 15:48:45

+1

我覺得int malloc真的想在使用之前歸零 – 2013-01-15 12:33:50