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  * The potential problem with wrap-around of cache generation counter is
25  * ignored for now. This will happen if someone happens to output more
26  * than 4 billion log entries, at which point wrap-around will not be
27  * the biggest problem.
28  *
29  */
30 
31 #include <stdbool.h>
32 #include <stdarg.h>
33 #include <stddef.h>
34 #include <string.h>
35 #include <stdlib.h>
36 #include <stdio.h>
37 #include <assert.h>
38 #include "esp_log.h"
39 #include "esp_log_private.h"
40 
41 #ifndef NDEBUG
42 // Enable built-in checks in queue.h in debug builds
43 #define INVARIANTS
44 // Enable consistency checks and cache statistics in this file.
45 #define LOG_BUILTIN_CHECKS
46 #endif
47 
48 #include "sys/queue.h"
49 
50 // Number of tags to be cached. Must be 2**n - 1, n >= 2.
51 #define TAG_CACHE_SIZE 31
52 
53 typedef struct {
54     const char *tag;
55     uint32_t level : 3;
56     uint32_t generation : 29;
57 } cached_tag_entry_t;
58 
59 typedef struct uncached_tag_entry_ {
60     SLIST_ENTRY(uncached_tag_entry_) entries;
61     uint8_t level;  // esp_log_level_t as uint8_t
62     char tag[0];    // beginning of a zero-terminated string
63 } uncached_tag_entry_t;
64 
65 esp_log_level_t esp_log_default_level = CONFIG_BOOTLOADER_LOG_LEVEL;
66 static SLIST_HEAD(log_tags_head, uncached_tag_entry_) s_log_tags = SLIST_HEAD_INITIALIZER(s_log_tags);
67 static cached_tag_entry_t s_log_cache[TAG_CACHE_SIZE];
68 static uint32_t s_log_cache_max_generation = 0;
69 static uint32_t s_log_cache_entry_count = 0;
70 static vprintf_like_t s_log_print_func = &vprintf;
71 
72 #ifdef LOG_BUILTIN_CHECKS
73 static uint32_t s_log_cache_misses = 0;
74 #endif
75 
76 extern size_t strlcpy(char*, const char*, size_t);
77 
78 static inline bool get_cached_log_level(const char *tag, esp_log_level_t *level);
79 static inline bool get_uncached_log_level(const char *tag, esp_log_level_t *level);
80 static inline void add_to_cache(const char *tag, esp_log_level_t level);
81 static void heap_bubble_down(int index);
82 static inline void heap_swap(int i, int j);
83 static inline bool should_output(esp_log_level_t level_for_message, esp_log_level_t level_for_tag);
84 static inline void clear_log_level_list(void);
85 
esp_log_set_vprintf(vprintf_like_t func)86 vprintf_like_t esp_log_set_vprintf(vprintf_like_t func)
87 {
88     esp_log_impl_lock();
89     vprintf_like_t orig_func = s_log_print_func;
90     s_log_print_func = func;
91     esp_log_impl_unlock();
92     return orig_func;
93 }
94 
esp_log_level_set(const char * tag,esp_log_level_t level)95 void esp_log_level_set(const char *tag, esp_log_level_t level)
96 {
97     esp_log_impl_lock();
98 
99     // for wildcard tag, remove all linked list items and clear the cache
100     if (strcmp(tag, "*") == 0) {
101         esp_log_default_level = level;
102         clear_log_level_list();
103         esp_log_impl_unlock();
104         return;
105     }
106 
107     // search for existing tag
108     uncached_tag_entry_t *it = NULL;
109     SLIST_FOREACH(it, &s_log_tags, entries) {
110         if (strcmp(it->tag, tag) == 0) {
111             // one tag in the linked list matched, update the level
112             it->level = level;
113             // quit with it != NULL
114             break;
115         }
116     }
117     // no existing tag, append new one
118     if (it == NULL) {
119         // allocate new linked list entry and append it to the head of the list
120         size_t tag_len = strlen(tag) + 1;
121         size_t entry_size = offsetof(uncached_tag_entry_t, tag) + tag_len;
122         uncached_tag_entry_t *new_entry = (uncached_tag_entry_t *) malloc(entry_size);
123         if (!new_entry) {
124             esp_log_impl_unlock();
125             return;
126         }
127         new_entry->level = (uint8_t) level;
128         memcpy(new_entry->tag, tag, tag_len); // we know the size and strncpy would trigger a compiler warning here
129         SLIST_INSERT_HEAD(&s_log_tags, new_entry, entries);
130     }
131 
132     // search in the cache and update the entry it if exists
133     for (uint32_t i = 0; i < s_log_cache_entry_count; ++i) {
134 #ifdef LOG_BUILTIN_CHECKS
135         assert(i == 0 || s_log_cache[(i - 1) / 2].generation < s_log_cache[i].generation);
136 #endif
137         if (strcmp(s_log_cache[i].tag, tag) == 0) {
138             s_log_cache[i].level = level;
139             break;
140         }
141     }
142     esp_log_impl_unlock();
143 }
144 
145 
146 /* Common code for getting the log level from cache, esp_log_impl_lock()
147    should be called before calling this function. The function unlocks,
148    as indicated in the name.
149 */
s_log_level_get_and_unlock(const char * tag)150 static esp_log_level_t s_log_level_get_and_unlock(const char *tag)
151 {
152     esp_log_level_t level_for_tag;
153     // Look for the tag in cache first, then in the linked list of all tags
154     if (!get_cached_log_level(tag, &level_for_tag)) {
155         if (!get_uncached_log_level(tag, &level_for_tag)) {
156             level_for_tag = esp_log_default_level;
157         }
158         add_to_cache(tag, level_for_tag);
159 #ifdef LOG_BUILTIN_CHECKS
160         ++s_log_cache_misses;
161 #endif
162     }
163     esp_log_impl_unlock();
164 
165     return level_for_tag;
166 }
167 
esp_log_level_get(const char * tag)168 esp_log_level_t esp_log_level_get(const char *tag)
169 {
170     esp_log_impl_lock();
171     return s_log_level_get_and_unlock(tag);
172 }
173 
clear_log_level_list(void)174 void clear_log_level_list(void)
175 {
176     uncached_tag_entry_t *it;
177     while ((it = SLIST_FIRST(&s_log_tags)) != NULL) {
178         SLIST_REMOVE_HEAD(&s_log_tags, entries);
179         free(it);
180     }
181     s_log_cache_entry_count = 0;
182     s_log_cache_max_generation = 0;
183 #ifdef LOG_BUILTIN_CHECKS
184     s_log_cache_misses = 0;
185 #endif
186 }
187 
esp_log_writev(esp_log_level_t level,const char * tag,const char * format,va_list args)188 void esp_log_writev(esp_log_level_t level,
189                    const char *tag,
190                    const char *format,
191                    va_list args)
192 {
193     if (!esp_log_impl_lock_timeout()) {
194         return;
195     }
196     esp_log_level_t level_for_tag = s_log_level_get_and_unlock(tag);
197     if (!should_output(level, level_for_tag)) {
198         return;
199     }
200 
201     (*s_log_print_func)(format, args);
202 
203 }
204 
esp_log_write(esp_log_level_t level,const char * tag,const char * format,...)205 void esp_log_write(esp_log_level_t level,
206                    const char *tag,
207                    const char *format, ...)
208 {
209     va_list list;
210     va_start(list, format);
211     esp_log_writev(level, tag, format, list);
212     va_end(list);
213 }
214 
get_cached_log_level(const char * tag,esp_log_level_t * level)215 static inline bool get_cached_log_level(const char *tag, esp_log_level_t *level)
216 {
217     // Look for `tag` in cache
218     uint32_t i;
219     for (i = 0; i < s_log_cache_entry_count; ++i) {
220 #ifdef LOG_BUILTIN_CHECKS
221         assert(i == 0 || s_log_cache[(i - 1) / 2].generation < s_log_cache[i].generation);
222 #endif
223         if (s_log_cache[i].tag == tag) {
224             break;
225         }
226     }
227     if (i == s_log_cache_entry_count) { // Not found in cache
228         return false;
229     }
230     // Return level from cache
231     *level = (esp_log_level_t) s_log_cache[i].level;
232     // If cache has been filled, start taking ordering into account
233     // (other options are: dynamically resize cache, add "dummy" entries
234     //  to the cache; this option was chosen because code is much simpler,
235     //  and the unfair behavior of cache will show it self at most once, when
236     //  it has just been filled)
237     if (s_log_cache_entry_count == TAG_CACHE_SIZE) {
238         // Update item generation
239         s_log_cache[i].generation = s_log_cache_max_generation++;
240         // Restore heap ordering
241         heap_bubble_down(i);
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         return;
260     }
261 
262     // Cache is full, so we replace the oldest entry (which is at index 0
263     // because this is a min-heap) with the new one, and do bubble-down
264     // operation to restore min-heap ordering.
265     s_log_cache[0] = (cached_tag_entry_t) {
266         .tag = tag,
267         .level = level,
268         .generation = generation
269     };
270     heap_bubble_down(0);
271 }
272 
get_uncached_log_level(const char * tag,esp_log_level_t * level)273 static inline bool get_uncached_log_level(const char *tag, esp_log_level_t *level)
274 {
275     // Walk the linked list of all tags and see if given tag is present in the list.
276     // This is slow because tags are compared as strings.
277     uncached_tag_entry_t *it;
278     SLIST_FOREACH(it, &s_log_tags, entries) {
279         if (strcmp(tag, it->tag) == 0) {
280             *level = it->level;
281             return true;
282         }
283     }
284     return false;
285 }
286 
should_output(esp_log_level_t level_for_message,esp_log_level_t level_for_tag)287 static inline bool should_output(esp_log_level_t level_for_message, esp_log_level_t level_for_tag)
288 {
289     return level_for_message <= level_for_tag;
290 }
291 
heap_bubble_down(int index)292 static void heap_bubble_down(int index)
293 {
294     while (index < TAG_CACHE_SIZE / 2) {
295         int left_index = index * 2 + 1;
296         int right_index = left_index + 1;
297         int next = (s_log_cache[left_index].generation < s_log_cache[right_index].generation) ? left_index : right_index;
298         heap_swap(index, next);
299         index = next;
300     }
301 }
302 
heap_swap(int i,int j)303 static inline void heap_swap(int i, int j)
304 {
305     cached_tag_entry_t tmp = s_log_cache[i];
306     s_log_cache[i] = s_log_cache[j];
307     s_log_cache[j] = tmp;
308 }
309