luat_malloc_weak.c 2.0 KB

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