assert.c 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. /*
  2. * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
  3. *
  4. * SPDX-License-Identifier: Apache-2.0
  5. */
  6. #include <string.h>
  7. #include <sys/param.h>
  8. #include "esp_system.h"
  9. #include "esp_spi_flash.h"
  10. #include "soc/soc_memory_layout.h"
  11. #define ASSERT_STR "assert failed: "
  12. #define CACHE_DISABLED_STR "<cached disabled>"
  13. #if __XTENSA__
  14. #define INST_LEN 3
  15. #elif __riscv
  16. #define INST_LEN 4
  17. #endif
  18. static inline void ra_to_str(char *addr)
  19. {
  20. addr[0] = '0';
  21. addr[1] = 'x';
  22. itoa((uint32_t)(__builtin_return_address(0) - INST_LEN), addr + 2, 16);
  23. }
  24. /* Overriding assert function so that whenever assert is called from critical section,
  25. * it does not lead to a crash of its own.
  26. */
  27. void __attribute__((noreturn)) __assert_func(const char *file, int line, const char *func, const char *expr)
  28. {
  29. #if CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT
  30. char buff[sizeof(ASSERT_STR) + 11 + 1] = ASSERT_STR;
  31. ra_to_str(&buff[sizeof(ASSERT_STR) - 1]);
  32. esp_system_abort(buff);
  33. #else
  34. char addr[11] = { 0 };
  35. char buff[200];
  36. char lbuf[5];
  37. uint32_t rem_len = sizeof(buff) - 1;
  38. uint32_t off = 0;
  39. itoa(line, lbuf, 10);
  40. if (!spi_flash_cache_enabled()) {
  41. if (esp_ptr_in_drom(file)) {
  42. file = CACHE_DISABLED_STR;
  43. }
  44. if (esp_ptr_in_drom(func)) {
  45. ra_to_str(addr);
  46. func = addr;
  47. }
  48. if (esp_ptr_in_drom(expr)) {
  49. expr = CACHE_DISABLED_STR;
  50. }
  51. }
  52. const char *str[] = {ASSERT_STR, func ? func : "\b", " ", file, ":", lbuf, " (", expr, ")"};
  53. for (int i = 0; i < sizeof(str) / sizeof(str[0]); i++) {
  54. uint32_t len = strlen(str[i]);
  55. uint32_t cpy_len = MIN(len, rem_len);
  56. memcpy(buff + off, str[i], cpy_len);
  57. rem_len -= cpy_len;
  58. off += cpy_len;
  59. if (rem_len == 0) {
  60. break;
  61. }
  62. }
  63. buff[off] = '\0';
  64. esp_system_abort(buff);
  65. #endif /* CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_SILENT */
  66. }
  67. void __attribute__((noreturn)) __assert(const char *file, int line, const char *failedexpr)
  68. {
  69. __assert_func(file, line, NULL, failedexpr);
  70. }
  71. /* No-op function, used to force linker to include these changes */
  72. void newlib_include_assert_impl(void)
  73. {
  74. }