1 /*
2  * SPDX-FileCopyrightText: 2015-2021 Espressif Systems (Shanghai) CO LTD
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  */
6 
7 /*
8  * Log library implementation notes.
9  *
10  * Log library stores all tags provided to esp_log_level_set as a linked
11  * list. See uncached_tag_entry_t structure.
12  *
13  * To avoid looking up log level for given tag each time message is
14  * printed, this library caches pointers to tags. Because the suggested
15  * way of creating tags uses one 'TAG' constant per file, this caching
16  * should be effective. Cache is a binary min-heap of cached_tag_entry_t
17  * items, ordering is done on 'generation' member. In this context,
18  * generation is an integer which is incremented each time an operation
19  * with cache is performed. When cache is full, new item is inserted in
20  * place of an oldest item (that is, with smallest 'generation' value).
21  * After that, bubble-down operation is performed to fix ordering in the
22  * min-heap.
23  *
24  */
25 
26 #include <stdbool.h>
27 #include <stdarg.h>
28 #include <stddef.h>
29 #include <string.h>
30 #include <stdlib.h>
31 #include <stdio.h>
32 #include <assert.h>
33 #include "esp_log.h"
34 #include "esp_log_private.h"
35 
36 #ifndef NDEBUG
37 // Enable built-in checks in queue.h in debug builds
38 #define INVARIANTS
39 // Enable consistency checks and cache statistics in this file.
40 #define LOG_BUILTIN_CHECKS
41 #endif
42 
43 #include "sys/queue.h"
44 
45 // Number of tags to be cached. Must be 2**n - 1, n >= 2.
46 #define TAG_CACHE_SIZE 31
47 #define MAX_GENERATION ((1 << 29) - 1)
48 
49 typedef struct {
50     const char *tag;
51     uint32_t level : 3;
52     uint32_t generation : 29; // this size should be the same in MAX_GENERATION
53 } cached_tag_entry_t;
54 
55 typedef struct uncached_tag_entry_ {
56     SLIST_ENTRY(uncached_tag_entry_) entries;
57     uint8_t level;  // esp_log_level_t as uint8_t
58     char tag[0];    // beginning of a zero-terminated string
59 } uncached_tag_entry_t;
60 
61 esp_log_level_t esp_log_default_level = CONFIG_BOOTLOADER_LOG_LEVEL;
62 static SLIST_HEAD(log_tags_head, uncached_tag_entry_) s_log_tags = SLIST_HEAD_INITIALIZER(s_log_tags);
63 static cached_tag_entry_t s_log_cache[TAG_CACHE_SIZE];
64 static uint32_t s_log_cache_max_generation = 0;
65 static uint32_t s_log_cache_entry_count = 0;
66 static vprintf_like_t s_log_print_func = &vprintf;
67 
68 #ifdef LOG_BUILTIN_CHECKS
69 static uint32_t s_log_cache_misses = 0;
70 #endif
71 
72 
73 static inline bool get_cached_log_level(const char *tag, esp_log_level_t *level);
74 static inline bool get_uncached_log_level(const char *tag, esp_log_level_t *level);
75 static inline void add_to_cache(const char *tag, esp_log_level_t level);
76 static void heap_bubble_down(int index);
77 static inline void heap_swap(int i, int j);
78 static inline bool should_output(esp_log_level_t level_for_message, esp_log_level_t level_for_tag);
79 static inline void clear_log_level_list(void);
80 static void fix_cache_generation_overflow(void);
81 
esp_log_set_vprintf(vprintf_like_t func)82 vprintf_like_t esp_log_set_vprintf(vprintf_like_t func)
83 {
84     esp_log_impl_lock();
85     vprintf_like_t orig_func = s_log_print_func;
86     s_log_print_func = func;
87     esp_log_impl_unlock();
88     return orig_func;
89 }
90 
esp_log_level_set(const char * tag,esp_log_level_t level)91 void esp_log_level_set(const char *tag, esp_log_level_t level)
92 {
93     esp_log_impl_lock();
94 
95     // for wildcard tag, remove all linked list items and clear the cache
96     if (strcmp(tag, "*") == 0) {
97         esp_log_default_level = level;
98         clear_log_level_list();
99         esp_log_impl_unlock();
100         return;
101     }
102 
103     // search for existing tag
104     uncached_tag_entry_t *it = NULL;
105     SLIST_FOREACH(it, &s_log_tags, entries) {
106         if (strcmp(it->tag, tag) == 0) {
107             // one tag in the linked list matched, update the level
108             it->level = level;
109             // quit with it != NULL
110             break;
111         }
112     }
113     // no existing tag, append new one
114     if (it == NULL) {
115         // allocate new linked list entry and append it to the head of the list
116         size_t tag_len = strlen(tag) + 1;
117         size_t entry_size = offsetof(uncached_tag_entry_t, tag) + tag_len;
118         uncached_tag_entry_t *new_entry = (uncached_tag_entry_t *) malloc(entry_size);
119         if (!new_entry) {
120             esp_log_impl_unlock();
121             return;
122         }
123         new_entry->level = (uint8_t) level;
124         memcpy(new_entry->tag, tag, tag_len); // we know the size and strncpy would trigger a compiler warning here
125         SLIST_INSERT_HEAD(&s_log_tags, new_entry, entries);
126     }
127 
128     // search in the cache and update the entry it if exists
129     for (uint32_t i = 0; i < s_log_cache_entry_count; ++i) {
130 #ifdef LOG_BUILTIN_CHECKS
131         assert(i == 0 || s_log_cache[(i - 1) / 2].generation < s_log_cache[i].generation);
132 #endif
133         if (strcmp(s_log_cache[i].tag, tag) == 0) {
134             s_log_cache[i].level = level;
135             break;
136         }
137     }
138     esp_log_impl_unlock();
139 }
140 
141 
142 /* Common code for getting the log level from cache, esp_log_impl_lock()
143    should be called before calling this function. The function unlocks,
144    as indicated in the name.
145 */
s_log_level_get_and_unlock(const char * tag)146 static esp_log_level_t s_log_level_get_and_unlock(const char *tag)
147 {
148     esp_log_level_t level_for_tag;
149     // Look for the tag in cache first, then in the linked list of all tags
150     if (!get_cached_log_level(tag, &level_for_tag)) {
151         if (!get_uncached_log_level(tag, &level_for_tag)) {
152             level_for_tag = esp_log_default_level;
153         }
154         add_to_cache(tag, level_for_tag);
155 #ifdef LOG_BUILTIN_CHECKS
156         ++s_log_cache_misses;
157 #endif
158     }
159     esp_log_impl_unlock();
160 
161     return level_for_tag;
162 }
163 
esp_log_level_get(const char * tag)164 esp_log_level_t esp_log_level_get(const char *tag)
165 {
166     esp_log_impl_lock();
167     return s_log_level_get_and_unlock(tag);
168 }
169 
clear_log_level_list(void)170 void clear_log_level_list(void)
171 {
172     uncached_tag_entry_t *it;
173     while ((it = SLIST_FIRST(&s_log_tags)) != NULL) {
174         SLIST_REMOVE_HEAD(&s_log_tags, entries);
175         free(it);
176     }
177     s_log_cache_entry_count = 0;
178     s_log_cache_max_generation = 0;
179 #ifdef LOG_BUILTIN_CHECKS
180     s_log_cache_misses = 0;
181 #endif
182 }
183 
esp_log_writev(esp_log_level_t level,const char * tag,const char * format,va_list args)184 void esp_log_writev(esp_log_level_t level,
185                    const char *tag,
186                    const char *format,
187                    va_list args)
188 {
189     if (!esp_log_impl_lock_timeout()) {
190         return;
191     }
192     esp_log_level_t level_for_tag = s_log_level_get_and_unlock(tag);
193     if (!should_output(level, level_for_tag)) {
194         return;
195     }
196 
197     (*s_log_print_func)(format, args);
198 
199 }
200 
esp_log_write(esp_log_level_t level,const char * tag,const char * format,...)201 void esp_log_write(esp_log_level_t level,
202                    const char *tag,
203                    const char *format, ...)
204 {
205     va_list list;
206     va_start(list, format);
207     esp_log_writev(level, tag, format, list);
208     va_end(list);
209 }
210 
get_cached_log_level(const char * tag,esp_log_level_t * level)211 static inline bool get_cached_log_level(const char *tag, esp_log_level_t *level)
212 {
213     // Look for `tag` in cache
214     uint32_t i;
215     for (i = 0; i < s_log_cache_entry_count; ++i) {
216 #ifdef LOG_BUILTIN_CHECKS
217         assert(i == 0 || s_log_cache[(i - 1) / 2].generation < s_log_cache[i].generation);
218 #endif
219         if (s_log_cache[i].tag == tag) {
220             break;
221         }
222     }
223     if (i == s_log_cache_entry_count) { // Not found in cache
224         return false;
225     }
226     // Return level from cache
227     *level = (esp_log_level_t) s_log_cache[i].level;
228     // If cache has been filled, start taking ordering into account
229     // (other options are: dynamically resize cache, add "dummy" entries
230     //  to the cache; this option was chosen because code is much simpler,
231     //  and the unfair behavior of cache will show it self at most once, when
232     //  it has just been filled)
233     if (s_log_cache_entry_count == TAG_CACHE_SIZE) {
234         // Update item generation
235         s_log_cache[i].generation = s_log_cache_max_generation++;
236         // Restore heap ordering
237         heap_bubble_down(i);
238         // Check for generation count wrap and fix if necessary
239         if (s_log_cache_max_generation == MAX_GENERATION) {
240             fix_cache_generation_overflow();
241         }
242     }
243     return true;
244 }
245 
add_to_cache(const char * tag,esp_log_level_t level)246 static inline void add_to_cache(const char *tag, esp_log_level_t level)
247 {
248     uint32_t generation = s_log_cache_max_generation++;
249     // First consider the case when cache is not filled yet.
250     // In this case, just add new entry at the end.
251     // This happens to satisfy binary min-heap ordering.
252     if (s_log_cache_entry_count < TAG_CACHE_SIZE) {
253         s_log_cache[s_log_cache_entry_count] = (cached_tag_entry_t) {
254             .generation = generation,
255             .level = level,
256             .tag = tag
257         };
258         ++s_log_cache_entry_count;
259     } else {
260         // Cache is full, so we replace the oldest entry (which is at index 0
261         // because this is a min-heap) with the new one, and do bubble-down
262         // operation to restore min-heap ordering.
263         s_log_cache[0] = (cached_tag_entry_t) {
264             .tag = tag,
265             .level = level,
266             .generation = generation
267         };
268         heap_bubble_down(0);
269     }
270     // Check for generation count wrap and fix if necessary
271     if (s_log_cache_max_generation == MAX_GENERATION) {
272         fix_cache_generation_overflow();
273     }
274 }
275 
fix_cache_generation_overflow(void)276 static void fix_cache_generation_overflow(void)
277 {
278     // Fix generation count wrap
279     for (uint32_t i = 0; i < s_log_cache_entry_count; ++i) {
280         s_log_cache[i].generation = i;
281     }
282     s_log_cache_max_generation = s_log_cache_entry_count;
283 }
284 
get_uncached_log_level(const char * tag,esp_log_level_t * level)285 static inline bool get_uncached_log_level(const char *tag, esp_log_level_t *level)
286 {
287     // Walk the linked list of all tags and see if given tag is present in the list.
288     // This is slow because tags are compared as strings.
289     uncached_tag_entry_t *it;
290     SLIST_FOREACH(it, &s_log_tags, entries) {
291         if (strcmp(tag, it->tag) == 0) {
292             *level = it->level;
293             return true;
294         }
295     }
296     return false;
297 }
298 
should_output(esp_log_level_t level_for_message,esp_log_level_t level_for_tag)299 static inline bool should_output(esp_log_level_t level_for_message, esp_log_level_t level_for_tag)
300 {
301     return level_for_message <= level_for_tag;
302 }
303 
heap_bubble_down(int index)304 static void heap_bubble_down(int index)
305 {
306     while (index < TAG_CACHE_SIZE / 2) {
307         int left_index = index * 2 + 1;
308         int right_index = left_index + 1;
309         int next = (s_log_cache[left_index].generation < s_log_cache[right_index].generation) ? left_index : right_index;
310         heap_swap(index, next);
311         index = next;
312     }
313 }
314 
heap_swap(int i,int j)315 static inline void heap_swap(int i, int j)
316 {
317     cached_tag_entry_t tmp = s_log_cache[i];
318     s_log_cache[i] = s_log_cache[j];
319     s_log_cache[j] = tmp;
320 }
321