luat_malloc_air105.c 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 "heap"
  7. #include "luat_log.h"
  8. #include "FreeRTOS.h"
  9. #include "task.h"
  10. //------------------------------------------------
  11. // 管理系统内存
  12. void* luat_heap_malloc(size_t len) {
  13. return OS_Malloc(len);
  14. }
  15. void luat_heap_free(void* ptr) {
  16. OS_Free(ptr);
  17. }
  18. void* luat_heap_realloc(void* ptr, size_t len) {
  19. void* tmp = luat_heap_malloc(len);
  20. if (tmp && ptr) {
  21. memcpy(tmp, ptr, len);
  22. }
  23. return tmp;
  24. }
  25. void* luat_heap_calloc(size_t count, size_t _size) {
  26. void *ptr = luat_heap_malloc(count * _size);
  27. if (ptr) {
  28. memset(ptr, 0, _size);
  29. }
  30. return ptr;
  31. }
  32. //------------------------------------------------
  33. //------------------------------------------------
  34. // ---------- 管理 LuaVM所使用的内存----------------
  35. void* luat_heap_alloc(void *ud, void *ptr, size_t osize, size_t nsize) {
  36. // if (0) {
  37. // if (ptr) {
  38. // if (nsize) {
  39. // // 缩放内存块
  40. // LLOGD("realloc %p from %d to %d", ptr, osize, nsize);
  41. // }
  42. // else {
  43. // // 释放内存块
  44. // LLOGD("free %p ", ptr);
  45. // OS_Free(ptr);
  46. // return NULL;
  47. // }
  48. // }
  49. // else {
  50. // // 申请内存块
  51. // ptr = OS_Malloc(nsize);
  52. // LLOGD("malloc %p type=%d size=%d", ptr, osize, nsize);
  53. // return ptr;
  54. // }
  55. // }
  56. if (nsize)
  57. {
  58. void* ptmp = pvPortMalloc(nsize);
  59. if (ptmp)
  60. {
  61. if (osize > nsize)
  62. {
  63. memcpy(ptmp, ptr, nsize);
  64. }
  65. else
  66. {
  67. memcpy(ptmp, ptr, osize);
  68. }
  69. vPortFree(ptr);
  70. return ptmp;
  71. }
  72. else if (osize >= nsize)
  73. {
  74. return ptr;
  75. }
  76. }
  77. vPortFree(ptr);
  78. return NULL;
  79. }
  80. void luat_meminfo_luavm(size_t *total, size_t *used, size_t *max_used) {
  81. *used = configTOTAL_HEAP_SIZE - xPortGetFreeHeapSize();
  82. *max_used = configTOTAL_HEAP_SIZE - xPortGetMinimumEverFreeHeapSize();
  83. *total = configTOTAL_HEAP_SIZE;
  84. }
  85. void luat_meminfo_sys(size_t *total, size_t *used, size_t *max_used) {
  86. long curalloc, totfree, maxfree;
  87. unsigned long nget, nrel;
  88. bstats(&curalloc, &totfree, &maxfree, &nget, &nrel);
  89. *used = curalloc;
  90. *max_used = bstatsmaxget();
  91. *total = curalloc + totfree;
  92. }
  93. //-----------------------------------------------------------------------------