100 satır
2.6 KiB

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