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