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 
77 static inline bool get_cached_log_level(const char *tag, esp_log_level_t *level);
78 static inline bool get_uncached_log_level(const char *tag, esp_log_level_t *level);
79 static inline void add_to_cache(const char *tag, esp_log_level_t level);
80 static void heap_bubble_down(int index);
81 static inline void heap_swap(int i, int j);
82 static inline bool should_output(esp_log_level_t level_for_message, esp_log_level_t level_for_tag);
83 static inline void clear_log_level_list(void);
84 
esp_log_set_vprintf(vprintf_like_t func)85 vprintf_like_t esp_log_set_vprintf(vprintf_like_t func)
86 {
87     esp_log_impl_lock();
88     vprintf_like_t orig_func = s_log_print_func;
89     s_log_print_func = func;
90     esp_log_impl_unlock();
91     return orig_func;
92 }
93 
esp_log_level_set(const char * tag,esp_log_level_t level)94 void esp_log_level_set(const char *tag, esp_log_level_t level)
95 {
96     esp_log_impl_lock();
97 
98     // for wildcard tag, remove all linked list items and clear the cache
99     if (strcmp(tag, "*") == 0) {
100         esp_log_default_level = level;
101         clear_log_level_list();
102         esp_log_impl_unlock();
103         return;
104     }
105 
106     // search for existing tag
107     uncached_tag_entry_t *it = NULL;
108     SLIST_FOREACH(it, &s_log_tags, entries) {
109         if (strcmp(it->tag, tag) == 0) {
110             // one tag in the linked list matched, update the level
111             it->level = level;
112             // quit with it != NULL
113             break;
114         }
115     }
116     // no existing tag, append new one
117     if (it == NULL) {
118         // allocate new linked list entry and append it to the head of the list
119         size_t tag_len = strlen(tag) + 1;
120         size_t entry_size = offsetof(uncached_tag_entry_t, tag) + tag_len;
121         uncached_tag_entry_t *new_entry = (uncached_tag_entry_t *) malloc(entry_size);
122         if (!new_entry) {
123             esp_log_impl_unlock();
124             return;
125         }
126         new_entry->level = (uint8_t) level;
127         memcpy(new_entry->tag, tag, tag_len); // we know the size and strncpy would trigger a compiler warning here
128         SLIST_INSERT_HEAD(&s_log_tags, new_entry, entries);
129     }
130 
131     // search in the cache and update the entry it if exists
132     for (uint32_t i = 0; i < s_log_cache_entry_count; ++i) {
133 #ifdef LOG_BUILTIN_CHECKS
134         assert(i == 0 || s_log_cache[(i - 1) / 2].generation < s_log_cache[i].generation);
135 #endif
136         if (strcmp(s_log_cache[i].tag, tag) == 0) {
137             s_log_cache[i].level = level;
138             break;
139         }
140     }
141     esp_log_impl_unlock();
142 }
143 
144 
145 /* Common code for getting the log level from cache, esp_log_impl_lock()
146    should be called before calling this function. The function unlocks,
147    as indicated in the name.
148 */
s_log_level_get_and_unlock(const char * tag)149 static esp_log_level_t s_log_level_get_and_unlock(const char *tag)
150 {
151     esp_log_level_t level_for_tag;
152     // Look for the tag in cache first, then in the linked list of all tags
153     if (!get_cached_log_level(tag, &level_for_tag)) {
154         if (!get_uncached_log_level(tag, &level_for_tag)) {
155             level_for_tag = esp_log_default_level;
156         }
157         add_to_cache(tag, level_for_tag);
158 #ifdef LOG_BUILTIN_CHECKS
159         ++s_log_cache_misses;
160 #endif
161     }
162     esp_log_impl_unlock();
163 
164     return level_for_tag;
165 }
166 
esp_log_level_get(const char * tag)167 esp_log_level_t esp_log_level_get(const char *tag)
168 {
169     esp_log_impl_lock();
170     return s_log_level_get_and_unlock(tag);
171 }
172 
clear_log_level_list(void)173 void clear_log_level_list(void)
174 {
175     uncached_tag_entry_t *it;
176     while ((it = SLIST_FIRST(&s_log_tags)) != NULL) {
177         SLIST_REMOVE_HEAD(&s_log_tags, entries);
178         free(it);
179     }
180     s_log_cache_entry_count = 0;
181     s_log_cache_max_generation = 0;
182 #ifdef LOG_BUILTIN_CHECKS
183     s_log_cache_misses = 0;
184 #endif
185 }
186 
esp_log_writev(esp_log_level_t level,const char * tag,const char * format,va_list args)187 void esp_log_writev(esp_log_level_t level,
188                    const char *tag,
189                    const char *format,
190                    va_list args)
191 {
192     if (!esp_log_impl_lock_timeout()) {
193         return;
194     }
195     esp_log_level_t level_for_tag = s_log_level_get_and_unlock(tag);
196     if (!should_output(level, level_for_tag)) {
197         return;
198     }
199 
200     (*s_log_print_func)(format, args);
201 
202 }
203 
esp_log_write(esp_log_level_t level,const char * tag,const char * format,...)204 void esp_log_write(esp_log_level_t level,
205                    const char *tag,
206                    const char *format, ...)
207 {
208     va_list list;
209     va_start(list, format);
210     esp_log_writev(level, tag, format, list);
211     va_end(list);
212 }
213 
get_cached_log_level(const char * tag,esp_log_level_t * level)214 static inline bool get_cached_log_level(const char *tag, esp_log_level_t *level)
215 {
216     // Look for `tag` in cache
217     uint32_t i;
218     for (i = 0; i < s_log_cache_entry_count; ++i) {
219 #ifdef LOG_BUILTIN_CHECKS
220         assert(i == 0 || s_log_cache[(i - 1) / 2].generation < s_log_cache[i].generation);
221 #endif
222         if (s_log_cache[i].tag == tag) {
223             break;
224         }
225     }
226     if (i == s_log_cache_entry_count) { // Not found in cache
227         return false;
228     }
229     // Return level from cache
230     *level = (esp_log_level_t) s_log_cache[i].level;
231     // If cache has been filled, start taking ordering into account
232     // (other options are: dynamically resize cache, add "dummy" entries
233     //  to the cache; this option was chosen because code is much simpler,
234     //  and the unfair behavior of cache will show it self at most once, when
235     //  it has just been filled)
236     if (s_log_cache_entry_count == TAG_CACHE_SIZE) {
237         // Update item generation
238         s_log_cache[i].generation = s_log_cache_max_generation++;
239         // Restore heap ordering
240         heap_bubble_down(i);
241     }
242     return true;
243 }
244 
add_to_cache(const char * tag,esp_log_level_t level)245 static inline void add_to_cache(const char *tag, esp_log_level_t level)
246 {
247     uint32_t generation = s_log_cache_max_generation++;
248     // First consider the case when cache is not filled yet.
249     // In this case, just add new entry at the end.
250     // This happens to satisfy binary min-heap ordering.
251     if (s_log_cache_entry_count < TAG_CACHE_SIZE) {
252         s_log_cache[s_log_cache_entry_count] = (cached_tag_entry_t) {
253             .generation = generation,
254             .level = level,
255             .tag = tag
256         };
257         ++s_log_cache_entry_count;
258         return;
259     }
260 
261     // Cache is full, so we replace the oldest entry (which is at index 0
262     // because this is a min-heap) with the new one, and do bubble-down
263     // operation to restore min-heap ordering.
264     s_log_cache[0] = (cached_tag_entry_t) {
265         .tag = tag,
266         .level = level,
267         .generation = generation
268     };
269     heap_bubble_down(0);
270 }
271 
get_uncached_log_level(const char * tag,esp_log_level_t * level)272 static inline bool get_uncached_log_level(const char *tag, esp_log_level_t *level)
273 {
274     // Walk the linked list of all tags and see if given tag is present in the list.
275     // This is slow because tags are compared as strings.
276     uncached_tag_entry_t *it;
277     SLIST_FOREACH(it, &s_log_tags, entries) {
278         if (strcmp(tag, it->tag) == 0) {
279             *level = it->level;
280             return true;
281         }
282     }
283     return false;
284 }
285 
should_output(esp_log_level_t level_for_message,esp_log_level_t level_for_tag)286 static inline bool should_output(esp_log_level_t level_for_message, esp_log_level_t level_for_tag)
287 {
288     return level_for_message <= level_for_tag;
289 }
290 
heap_bubble_down(int index)291 static void heap_bubble_down(int index)
292 {
293     while (index < TAG_CACHE_SIZE / 2) {
294         int left_index = index * 2 + 1;
295         int right_index = left_index + 1;
296         int next = (s_log_cache[left_index].generation < s_log_cache[right_index].generation) ? left_index : right_index;
297         heap_swap(index, next);
298         index = next;
299     }
300 }
301 
heap_swap(int i,int j)302 static inline void heap_swap(int i, int j)
303 {
304     cached_tag_entry_t tmp = s_log_cache[i];
305     s_log_cache[i] = s_log_cache[j];
306     s_log_cache[j] = tmp;
307 }
308