test_realloc.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. /*
  2. * SPDX-FileCopyrightText: 2022-2023 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Unlicense OR CC0-1.0
  5. */
  6. /*
  7. Generic test for realloc
  8. */
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include "unity.h"
  12. #include "sdkconfig.h"
  13. #include "esp_heap_caps.h"
  14. #include "soc/soc_memory_layout.h"
  15. #ifndef CONFIG_HEAP_POISONING_COMPREHENSIVE
  16. /* (can't realloc in place if comprehensive is enabled) */
  17. TEST_CASE("realloc shrink buffer in place", "[heap]")
  18. {
  19. // pointers converted to int to avoid warning -Wuse-after-free
  20. int x = (int) malloc(64);
  21. TEST_ASSERT(x);
  22. int y = (int) realloc((void *) x, 48);
  23. TEST_ASSERT_EQUAL_UINT32((uint32_t) x, (uint32_t) y);
  24. }
  25. #endif
  26. #ifndef CONFIG_ESP_SYSTEM_MEMPROT_FEATURE
  27. TEST_CASE("realloc shrink buffer with EXEC CAPS", "[heap]")
  28. {
  29. const size_t buffer_size = 64;
  30. void *x = heap_caps_malloc(buffer_size, MALLOC_CAP_EXEC);
  31. TEST_ASSERT(x);
  32. void *y = heap_caps_realloc(x, buffer_size - 16, MALLOC_CAP_EXEC);
  33. TEST_ASSERT(y);
  34. //y needs to fall in a compatible memory area of IRAM:
  35. TEST_ASSERT(esp_ptr_executable(y)|| esp_ptr_in_iram(y) || esp_ptr_in_diram_iram(y));
  36. free(y);
  37. }
  38. TEST_CASE("realloc move data to a new heap type", "[heap]")
  39. {
  40. const char *test = "I am some test content to put in the heap";
  41. char buf[64];
  42. memset(buf, 0xEE, 64);
  43. strlcpy(buf, test, 64);
  44. char *a = malloc(64);
  45. memcpy(a, buf, 64);
  46. // move data from 'a' to IRAM
  47. char *b = heap_caps_realloc(a, 64, MALLOC_CAP_EXEC);
  48. TEST_ASSERT_NOT_NULL(b);
  49. TEST_ASSERT(heap_caps_check_integrity(MALLOC_CAP_INVALID, true));
  50. TEST_ASSERT_EQUAL_HEX32_ARRAY(buf, b, 64 / sizeof(uint32_t));
  51. // Move data back to DRAM
  52. char *c = heap_caps_realloc(b, 48, MALLOC_CAP_8BIT);
  53. TEST_ASSERT_NOT_NULL(c);
  54. TEST_ASSERT(heap_caps_check_integrity(MALLOC_CAP_INVALID, true));
  55. TEST_ASSERT_EQUAL_HEX8_ARRAY(buf, c, 48);
  56. free(c);
  57. }
  58. #endif // CONFIG_ESP_SYSTEM_MEMPROT_FEATURE