From 53bfbef762850e152f540e5f698a7ade3c0729f2 Mon Sep 17 00:00:00 2001
From: me-no-dev <hristo@espressif.com>
Date: Wed, 11 Aug 2021 13:25:41 +0300
Subject: [PATCH] Fix race in log_printf

Fixes: https://github.com/espressif/arduino-esp32/issues/5513

Can still race if Serial.begin() is not called in setup()
---
 cores/esp32/esp32-hal-uart.c | 14 ++++++++------
 1 file changed, 8 insertions(+), 6 deletions(-)

diff --git a/cores/esp32/esp32-hal-uart.c b/cores/esp32/esp32-hal-uart.c
index f670550ed45..840fc40eabf 100644
--- a/cores/esp32/esp32-hal-uart.c
+++ b/cores/esp32/esp32-hal-uart.c
@@ -648,17 +648,19 @@ int log_printf(const char *format, ...)
             return 0;
         }
     }
-    vsnprintf(temp, len+1, format, arg);
 #if !CONFIG_DISABLE_HAL_LOCKS
     if(s_uart_debug_nr != -1 && _uart_bus_array[s_uart_debug_nr].lock){
         xSemaphoreTake(_uart_bus_array[s_uart_debug_nr].lock, portMAX_DELAY);
-        ets_printf("%s", temp);
-        xSemaphoreGive(_uart_bus_array[s_uart_debug_nr].lock);
-    } else {
-        ets_printf("%s", temp);
     }
-#else
+#endif
+    
+    vsnprintf(temp, len+1, format, arg);
     ets_printf("%s", temp);
+
+#if !CONFIG_DISABLE_HAL_LOCKS
+    if(s_uart_debug_nr != -1 && _uart_bus_array[s_uart_debug_nr].lock){
+        xSemaphoreGive(_uart_bus_array[s_uart_debug_nr].lock);
+    }
 #endif
     va_end(arg);
     if(len >= sizeof(loc_buf)){