luat_malloc_weak.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // 这个文件包含 系统heap和lua heap的默认实现
  2. #include "luat_base.h"
  3. #include <stdlib.h>
  4. #include "luat_mem.h"
  5. #ifdef __LUATOS__
  6. #include "bget.h"
  7. #endif
  8. #define LUAT_LOG_TAG "vmheap"
  9. #include "luat_log.h"
  10. //------------------------------------------------
  11. // 管理系统内存
  12. LUAT_WEAK void luat_heap_init(void){}
  13. LUAT_WEAK void* luat_heap_malloc(size_t len) {
  14. return malloc(len);
  15. }
  16. LUAT_WEAK void luat_heap_free(void* ptr) {
  17. free(ptr);
  18. }
  19. LUAT_WEAK void* luat_heap_realloc(void* ptr, size_t len) {
  20. return realloc(ptr, len);
  21. }
  22. LUAT_WEAK void* luat_heap_calloc(size_t count, size_t _size) {
  23. void *ptr = luat_heap_malloc(count * _size);
  24. if (ptr) {
  25. memset(ptr, 0, count * _size);
  26. }
  27. return ptr;
  28. }
  29. LUAT_WEAK void* luat_heap_zalloc(size_t _size) {
  30. void *ptr = luat_heap_malloc(_size);
  31. if (ptr) {
  32. memset(ptr, 0, _size);
  33. }
  34. return ptr;
  35. }
  36. //------------------------------------------------
  37. //------------------------------------------------
  38. // ---------- 管理 LuaVM所使用的内存----------------
  39. #ifdef __LUATOS__
  40. LUAT_WEAK void* luat_heap_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {
  41. if (0) {
  42. if (ptr) {
  43. if (nsize) {
  44. // 缩放内存块
  45. LLOGD("realloc %p from %d to %d", ptr, osize, nsize);
  46. }
  47. else {
  48. // 释放内存块
  49. LLOGD("free %p ", ptr);
  50. brel(ptr);
  51. return NULL;
  52. }
  53. }
  54. else {
  55. // 申请内存块
  56. ptr = bget(nsize);
  57. LLOGD("malloc %p type=%d size=%d", ptr, osize, nsize);
  58. return ptr;
  59. }
  60. }
  61. if (nsize)
  62. {
  63. void* ptmp = bgetr(ptr, nsize);
  64. if(ptmp == NULL && osize >= nsize)
  65. {
  66. return ptr;
  67. }
  68. return ptmp;
  69. }
  70. brel(ptr);
  71. return NULL;
  72. }
  73. LUAT_WEAK void luat_meminfo_luavm(size_t *total, size_t *used, size_t *max_used) {
  74. long curalloc, totfree, maxfree;
  75. unsigned long nget, nrel;
  76. bstats(&curalloc, &totfree, &maxfree, &nget, &nrel);
  77. *used = curalloc;
  78. *max_used = bstatsmaxget();
  79. *total = curalloc + totfree;
  80. }
  81. #endif
  82. //-----------------------------------------------------------------------------