Path: blob/main/sys/contrib/openzfs/module/lua/lmem.c
48383 views
// SPDX-License-Identifier: MIT1/*2** $Id: lmem.c,v 1.84.1.1 2013/04/12 18:48:47 roberto Exp $3** Interface to Memory Manager4** See Copyright Notice in lua.h5*/678#define lmem_c9#define LUA_CORE1011#include <sys/lua/lua.h>1213#include "ldebug.h"14#include "ldo.h"15#include "lgc.h"16#include "lmem.h"17#include "lobject.h"18#include "lstate.h"19202122/*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' (no28** 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 nothing33** (which is equivalent to free(NULL) in ANSI C)34**35** frealloc returns NULL if it cannot create or reallocate the area36** (any reallocation to an equal or smaller size cannot fail!)37*/38394041#define MINSIZEARRAY 4424344void *luaM_growaux_ (lua_State *L, void *block, int *size, size_t size_elems,45int limit, const char *what) {46void *newblock;47int newsize;48if (*size >= limit/2) { /* cannot double it? */49if (*size >= limit) /* cannot grow even a little? */50luaG_runerror(L, "too many %s (limit is %d)", what, limit);51newsize = limit; /* still have at least one free place */52}53else {54newsize = (*size)*2;55if (newsize < MINSIZEARRAY)56newsize = MINSIZEARRAY; /* minimum size */57}58newblock = luaM_reallocv(L, block, *size, newsize, size_elems);59*size = newsize; /* update only when everything else is OK */60return newblock;61}626364l_noret luaM_toobig (lua_State *L) {65luaG_runerror(L, "memory allocation error: block too big");66}67686970/*71** generic allocation routine.72*/73void *luaM_realloc_ (lua_State *L, void *block, size_t osize, size_t nsize) {74void *newblock;75global_State *g = G(L);76size_t realosize = (block) ? osize : 0;77lua_assert((realosize == 0) == (block == NULL));78#if defined(HARDMEMTESTS)79if (nsize > realosize && g->gcrunning)80luaC_fullgc(L, 1); /* force a GC whenever possible */81#endif82newblock = (*g->frealloc)(g->ud, block, osize, nsize);83if (newblock == NULL && nsize > 0) {84api_check(L, nsize > realosize,85"realloc cannot fail when shrinking a block");86if (g->gcrunning) {87luaC_fullgc(L, 1); /* try to free some memory... */88newblock = (*g->frealloc)(g->ud, block, osize, nsize); /* try again */89}90if (newblock == NULL)91luaD_throw(L, LUA_ERRMEM);92}93lua_assert((nsize == 0) == (newblock == NULL));94g->GCdebt = (g->GCdebt + nsize) - realosize;95return newblock;96}979899