memmgr.c 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  1. #include "memmgr.h"
  2. #include "common_defines.h"
  3. #include <string.h>
  4. #include <furi_hal_memory.h>
  5. extern void* pvPortMalloc(size_t xSize);
  6. extern void vPortFree(void* pv);
  7. extern size_t xPortGetFreeHeapSize(void);
  8. extern size_t xPortGetTotalHeapSize(void);
  9. extern size_t xPortGetMinimumEverFreeHeapSize(void);
  10. void* malloc(size_t size) {
  11. return pvPortMalloc(size);
  12. }
  13. void free(void* ptr) {
  14. vPortFree(ptr);
  15. }
  16. void* realloc(void* ptr, size_t size) {
  17. if(size == 0) {
  18. vPortFree(ptr);
  19. return NULL;
  20. }
  21. void* p = pvPortMalloc(size);
  22. if(ptr != NULL) {
  23. memcpy(p, ptr, size);
  24. vPortFree(ptr);
  25. }
  26. return p;
  27. }
  28. void* calloc(size_t count, size_t size) {
  29. return pvPortMalloc(count * size);
  30. }
  31. char* strdup(const char* s) {
  32. // arg s marked as non-null, so we need hack to check for NULL
  33. furi_check(((uint32_t)s << 2) != 0);
  34. size_t siz = strlen(s) + 1;
  35. char* y = pvPortMalloc(siz);
  36. memcpy(y, s, siz);
  37. return y;
  38. }
  39. size_t memmgr_get_free_heap(void) {
  40. return xPortGetFreeHeapSize();
  41. }
  42. size_t memmgr_get_total_heap(void) {
  43. return xPortGetTotalHeapSize();
  44. }
  45. size_t memmgr_get_minimum_free_heap(void) {
  46. return xPortGetMinimumEverFreeHeapSize();
  47. }
  48. void* __wrap__malloc_r(struct _reent* r, size_t size) {
  49. UNUSED(r);
  50. return pvPortMalloc(size);
  51. }
  52. void __wrap__free_r(struct _reent* r, void* ptr) {
  53. UNUSED(r);
  54. vPortFree(ptr);
  55. }
  56. void* __wrap__calloc_r(struct _reent* r, size_t count, size_t size) {
  57. UNUSED(r);
  58. return calloc(count, size);
  59. }
  60. void* __wrap__realloc_r(struct _reent* r, void* ptr, size_t size) {
  61. UNUSED(r);
  62. return realloc(ptr, size);
  63. }
  64. void* memmgr_alloc_from_pool(size_t size) {
  65. void* p = furi_hal_memory_alloc(size);
  66. if(p == NULL) p = malloc(size);
  67. return p;
  68. }
  69. size_t memmgr_pool_get_free(void) {
  70. return furi_hal_memory_get_free();
  71. }
  72. size_t memmgr_pool_get_max_block(void) {
  73. return furi_hal_memory_max_pool_block();
  74. }
  75. void* aligned_malloc(size_t size, size_t alignment) {
  76. void* p1; // original block
  77. void** p2; // aligned block
  78. int offset = alignment - 1 + sizeof(void*);
  79. if((p1 = (void*)malloc(size + offset)) == NULL) {
  80. return NULL;
  81. }
  82. p2 = (void**)(((size_t)(p1) + offset) & ~(alignment - 1));
  83. p2[-1] = p1;
  84. return p2;
  85. }
  86. void aligned_free(void* p) {
  87. free(((void**)p)[-1]);
  88. }