1 /*
2 ** $Id$
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 "lua.h"
12
13 #include "ldebug.h"
14 #include "ldo.h"
15 #include "lmem.h"
16 #include "lobject.h"
17 #include "lstate.h"
18
19
20
21 /*
22 ** About the realloc function:
23 ** void * frealloc (void *ud, void *ptr, size_t osize, size_t nsize);
24 ** (`osize' is the old size, `nsize' is the new size)
25 **
26 ** Lua ensures that (ptr == NULL) iff (osize == 0).
27 **
28 ** * frealloc(ud, NULL, 0, x) creates a new block of size `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
luaM_growaux_(lua_State * L,void * block,int * size,size_t size_elems,int limit,const char * errormsg)44 void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,
45 int limit, const char *errormsg) {
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, errormsg);
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
luaM_toobig(lua_State * L)64 void *luaM_toobig (lua_State *L) {
65 luaG_runerror(L, "memory allocation error: block too big");
66 return NULL; /* to avoid warnings */
67 }
68
69
70
71 /*
72 ** generic allocation routine.
73 */
luaM_realloc_(lua_State * L,void * block,size_t osize,size_t nsize)74 void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {
75 global_State *g = G(L);
76 lua_assert((osize == 0) == (block == NULL));
77 block = (*g->frealloc)(g->ud, block, osize, nsize);
78 if (block == NULL && nsize > 0)
79 luaD_throw(L, LUA_ERRMEM);
80 lua_assert((nsize == 0) == (block == NULL));
81 g->totalbytes = (g->totalbytes - osize) + nsize;
82 return block;
83 }
84