luat_malloc_mini.c 2.1 KB

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