1 /* 2 Tests for registering new heap memory at runtime 3 */ 4 5 #include <stdio.h> 6 #include "unity.h" 7 #include "esp_heap_caps_init.h" 8 #include "esp_system.h" 9 #include <stdlib.h> 10 11 12 /* NOTE: This is not a well-formed unit test, it leaks memory */ 13 TEST_CASE("Allocate new heap at runtime", "[heap][ignore]") 14 { 15 const size_t BUF_SZ = 1000; 16 const size_t HEAP_OVERHEAD_MAX = 200; 17 void *buffer = malloc(BUF_SZ); 18 TEST_ASSERT_NOT_NULL(buffer); 19 uint32_t before_free = esp_get_free_heap_size(); 20 TEST_ESP_OK( heap_caps_add_region((intptr_t)buffer, (intptr_t)buffer + BUF_SZ) ); 21 uint32_t after_free = esp_get_free_heap_size(); 22 printf("Before %u after %u\n", before_free, after_free); 23 /* allow for some 'heap overhead' from accounting structures */ 24 TEST_ASSERT(after_free >= before_free + BUF_SZ - HEAP_OVERHEAD_MAX); 25 } 26 27 /* NOTE: This is not a well-formed unit test, it leaks memory and 28 may fail if run twice in a row without a reset. 29 */ 30 TEST_CASE("Allocate new heap with new capability", "[heap][ignore]") 31 { 32 const size_t BUF_SZ = 100; 33 #ifdef CONFIG_ESP_SYSTEM_MEMPROT_FEATURE 34 const size_t ALLOC_SZ = 32; 35 #else 36 const size_t ALLOC_SZ = 64; // More than half of BUF_SZ 37 #endif 38 const uint32_t MALLOC_CAP_INVENTED = (1 << 30); /* this must be unused in esp_heap_caps.h */ 39 40 /* no memory exists to provide this capability */ 41 TEST_ASSERT_NULL( heap_caps_malloc(ALLOC_SZ, MALLOC_CAP_INVENTED) ); 42 43 void *buffer = malloc(BUF_SZ); 44 TEST_ASSERT_NOT_NULL(buffer); 45 uint32_t caps[SOC_MEMORY_TYPE_NO_PRIOS] = { MALLOC_CAP_INVENTED }; 46 TEST_ESP_OK( heap_caps_add_region_with_caps(caps, (intptr_t)buffer, (intptr_t)buffer + BUF_SZ) ); 47 48 /* ta-da, it's now possible! */ 49 TEST_ASSERT_NOT_NULL( heap_caps_malloc(ALLOC_SZ, MALLOC_CAP_INVENTED) ); 50 } 51 52 /* NOTE: This is not a well-formed unit test. 53 * If run twice without a reset, it will failed. 54 */ 55 56 TEST_CASE("Add .bss memory to heap region runtime", "[heap][ignore]") 57 { 58 #define BUF_SZ 1000 59 #define HEAP_OVERHEAD_MAX 200 60 static uint8_t s_buffer[BUF_SZ]; 61 62 printf("s_buffer start %08x end %08x\n", (intptr_t)s_buffer, (intptr_t)s_buffer + BUF_SZ); 63 uint32_t before_free = esp_get_free_heap_size(); 64 TEST_ESP_OK( heap_caps_add_region((intptr_t)s_buffer, (intptr_t)s_buffer + BUF_SZ) ); 65 uint32_t after_free = esp_get_free_heap_size(); 66 printf("Before %u after %u\n", before_free, after_free); 67 /* allow for some 'heap overhead' from accounting structures */ 68 TEST_ASSERT(after_free >= before_free + BUF_SZ - HEAP_OVERHEAD_MAX); 69 70 /* Twice add must be failed */ 71 TEST_ASSERT( (heap_caps_add_region((intptr_t)s_buffer, (intptr_t)s_buffer + BUF_SZ) != ESP_OK) ); 72 } 73