1 /*
2  * SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 #include <sdkconfig.h>
7 
8 #define HEAP_TRACE_SRCFILE /* don't warn on inclusion here */
9 #include "esp_heap_trace.h"
10 #undef HEAP_TRACE_SRCFILE
11 
12 #if CONFIG_APPTRACE_SV_ENABLE
13 #include "esp_app_trace.h"
14 #include "esp_sysview_trace.h"
15 #endif
16 
17 #define STACK_DEPTH CONFIG_HEAP_TRACING_STACK_DEPTH
18 
19 #ifdef CONFIG_HEAP_TRACING_TOHOST
20 
21 #if !CONFIG_APPTRACE_SV_ENABLE
22 #error None of the heap tracing backends is enabled! You must enable SystemView compatible tracing to use this feature.
23 #endif
24 
25 static bool s_tracing;
26 
heap_trace_init_tohost(void)27 esp_err_t heap_trace_init_tohost(void)
28 {
29     if (s_tracing) {
30         return ESP_ERR_INVALID_STATE;
31     }
32     return ESP_OK;
33 }
34 
heap_trace_start(heap_trace_mode_t mode_param)35 esp_err_t heap_trace_start(heap_trace_mode_t mode_param)
36 {
37 #if CONFIG_APPTRACE_SV_ENABLE
38     esp_err_t ret = esp_sysview_heap_trace_start((uint32_t)-1);
39     if (ret != ESP_OK) {
40         return ret;
41     }
42 #endif
43     s_tracing = true;
44     return ESP_OK;
45 }
46 
heap_trace_stop(void)47 esp_err_t heap_trace_stop(void)
48 {
49     esp_err_t ret = ESP_ERR_NOT_SUPPORTED;
50 #if CONFIG_APPTRACE_SV_ENABLE
51     ret = esp_sysview_heap_trace_stop();
52 #endif
53     s_tracing = false;
54     return ret;
55 }
56 
heap_trace_resume(void)57 esp_err_t heap_trace_resume(void)
58 {
59     return heap_trace_start(HEAP_TRACE_ALL);
60 }
61 
heap_trace_get_count(void)62 size_t heap_trace_get_count(void)
63 {
64     return 0;
65 }
66 
heap_trace_get(size_t index,heap_trace_record_t * record)67 esp_err_t heap_trace_get(size_t index, heap_trace_record_t *record)
68 {
69     return ESP_ERR_NOT_SUPPORTED;
70 }
71 
heap_trace_dump(void)72 void heap_trace_dump(void)
73 {
74     return;
75 }
76 
77 /* Add a new allocation to the heap trace records */
record_allocation(const heap_trace_record_t * record)78 static IRAM_ATTR void record_allocation(const heap_trace_record_t *record)
79 {
80     if (!s_tracing) {
81         return;
82     }
83 #if CONFIG_APPTRACE_SV_ENABLE
84     esp_sysview_heap_trace_alloc(record->address, record->size, record->alloced_by);
85 #endif
86 }
87 
88 /* record a free event in the heap trace log
89 
90    For HEAP_TRACE_ALL, this means filling in the freed_by pointer.
91    For HEAP_TRACE_LEAKS, this means removing the record from the log.
92 */
record_free(void * p,void ** callers)93 static IRAM_ATTR void record_free(void *p, void **callers)
94 {
95     if (!s_tracing) {
96         return;
97     }
98 #if CONFIG_APPTRACE_SV_ENABLE
99     esp_sysview_heap_trace_free(p, callers);
100 #endif
101 }
102 
103 #include "heap_trace.inc"
104 
105 #endif /*CONFIG_HEAP_TRACING_TOHOST*/
106