From 3a2c4768691ae0d90e2a907b00a9ae7f82037551 Mon Sep 17 00:00:00 2001 From: Tom Burdick Date: Tue, 27 Aug 2024 18:13:00 +0300 Subject: [PATCH] llext: flush logging before unloading extensions Extensions could have used logging, when log processing is deferred, the logging thread can run after the extension has been unloaded and thereby access invalid memory addresses. Make sure to flush all logs before unloading extensions. Signed-off-by: Guennadi Liakhovetski --- subsys/llext/llext.c | 47 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/subsys/llext/llext.c b/subsys/llext/llext.c index 831667f7c96c7fc..bc86d8991ca71ac 100644 --- a/subsys/llext/llext.c +++ b/subsys/llext/llext.c @@ -180,12 +180,59 @@ int llext_load(struct llext_loader *ldr, const char *name, struct llext **ext, return ret; } +#include + +extern struct k_thread logging_thread; + +static void llext_log_flush(void) +{ + int cur_prio = k_thread_priority_get(k_current_get()); + int log_prio = k_thread_priority_get(&logging_thread); + int target_prio; + bool adjust_cur, adjust_log; + + /* + * Our goal is to raise the logger thread priority above current, but if + * current has the highest possble priority, both need to be adjusted, + * particularly if the logger thread has the lowest possible priority + */ + if (log_prio < cur_prio) { + adjust_cur = false; + adjust_log = false; + target_prio = 0; + } else if (cur_prio == K_HIGHEST_THREAD_PRIO) { + adjust_cur = true; + adjust_log = true; + target_prio = cur_prio; + k_thread_priority_set(k_current_get(), cur_prio + 1); + } else { + adjust_cur = false; + adjust_log = true; + target_prio = cur_prio - 1; + } + + /* adjust logging thread priority if needed */ + if (adjust_log) + k_thread_priority_set(&logging_thread, target_prio); + + log_thread_trigger(); + k_yield(); + + if (adjust_log) + k_thread_priority_set(&logging_thread, log_prio); + if (adjust_cur) + k_thread_priority_set(&logging_thread, cur_prio); +} + int llext_unload(struct llext **ext) { __ASSERT(*ext, "Expected non-null extension"); struct llext *tmp = *ext; k_mutex_lock(&llext_lock, K_FOREVER); + + llext_log_flush(); + __ASSERT(tmp->use_count, "A valid LLEXT cannot have a zero use-count!"); if (tmp->use_count-- != 1) {