1 /* 2 ** $Id: lmem.c,v 1.84.1.1 2013/04/12 18:48:47 roberto Exp $ 3 ** Interface to Memory Manager 4 ** See Copyright Notice in lua.h 5 */ 6 7 8 #define lmem_c 9 #define LUA_CORE 10 11 #include <sys/lua/lua.h> 12 13 #include "ldebug.h" 14 #include "ldo.h" 15 #include "lgc.h" 16 #include "lmem.h" 17 #include "lobject.h" 18 #include "lstate.h" 19 20 21 22 /* 23 ** About the realloc function: 24 ** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize); 25 ** (`osize' is the old size, `nsize' is the new size) 26 ** 27 ** * frealloc(ud, NULL, x, s) creates a new block of size `s' (no 28 ** matter 'x'). 29 ** 30 ** * frealloc(ud, p, x, 0) frees the block `p' 31 ** (in this specific case, frealloc must return NULL); 32 ** particularly, frealloc(ud, NULL, 0, 0) does nothing 33 ** (which is equivalent to free(NULL) in ANSI C) 34 ** 35 ** frealloc returns NULL if it cannot create or reallocate the area 36 ** (any reallocation to an equal or smaller size cannot fail!) 37 */ 38 39 40 41 #define MINSIZEARRAY 4 42 43 44 void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems, 45 int limit, const char *what) { 46 void *newblock; 47 int newsize; 48 if (*size >= limit/2) { /* cannot double it? */ 49 if (*size >= limit) /* cannot grow even a little? */ 50 luaG_runerror(L, "too many %s (limit is %d)", what, limit); 51 newsize = limit; /* still have at least one free place */ 52 } 53 else { 54 newsize = (*size)*2; 55 if (newsize < MINSIZEARRAY) 56 newsize = MINSIZEARRAY; /* minimum size */ 57 } 58 newblock = luaM_reallocv(L, block, *size, newsize, size_elems); 59 *size = newsize; /* update only when everything else is OK */ 60 return newblock; 61 } 62 63 64 l_noret luaM_toobig (lua_State *L) { 65 luaG_runerror(L, "memory allocation error: block too big"); 66 } 67 68 69 70 /* 71 ** generic allocation routine. 72 */ 73 void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) { 74 void *newblock; 75 global_State *g = G(L); 76 size_t realosize = (block) ? osize : 0; 77 lua_assert((realosize == 0) == (block == NULL)); 78 #if defined(HARDMEMTESTS) 79 if (nsize > realosize && g->gcrunning) 80 luaC_fullgc(L, 1); /* force a GC whenever possible */ 81 #endif 82 newblock = (*g->frealloc)(g->ud, block, osize, nsize); 83 if (newblock == NULL && nsize > 0) { 84 api_check(L, nsize > realosize, 85 "realloc cannot fail when shrinking a block"); 86 if (g->gcrunning) { 87 luaC_fullgc(L, 1); /* try to free some memory... */ 88 newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */ 89 } 90 if (newblock == NULL) 91 luaD_throw(L, LUA_ERRMEM); 92 } 93 lua_assert((nsize == 0) == (newblock == NULL)); 94 g->GCdebt = (g->GCdebt + nsize) - realosize; 95 return newblock; 96 } 97