From a04d8957c2120abb1187a0d4fa4b97f10307a8b0 Mon Sep 17 00:00:00 2001 From: Jakub Rzeszutko Date: Wed, 21 Jan 2026 15:28:31 +0100 Subject: [PATCH] shell: fix race condition between prompt print and RX buffer flush Move z_shell_backend_rx_buffer_flush() before state_set() in shell_start() to prevent a race condition where incoming shell commands could be lost. Previously, the sequence was: 1. state_set() - prints the prompt 2. z_shell_backend_rx_buffer_flush() - flushes RX buffer If the shell thread was preempted after printing the prompt, the host could see the prompt and send commands. When the thread resumed, z_shell_backend_rx_buffer_flush() would discard those commands. By flushing the RX buffer before printing the prompt, any commands received after the prompt is visible will not be affected by the flush operation. Fixes #99674 Signed-off-by: Jakub Rzeszutko --- subsys/shell/shell.c | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/subsys/shell/shell.c b/subsys/shell/shell.c index a331464ba09..9596ae1b2ff 100644 --- a/subsys/shell/shell.c +++ b/subsys/shell/shell.c @@ -1449,12 +1449,6 @@ int shell_start(const struct shell *sh) z_shell_vt100_color_set(sh, SHELL_NORMAL); } - /* print new line before printing the prompt to clear the line - * vt100 are not used here for compatibility reasons - */ - z_cursor_next_line_move(sh); - state_set(sh, SHELL_STATE_ACTIVE); - /* * If the shell is stopped with the shell_stop function, its backend remains active * and continues to buffer incoming data. As a result, when the shell is resumed, @@ -1463,6 +1457,12 @@ int shell_start(const struct shell *sh) */ z_shell_backend_rx_buffer_flush(sh); + /* print new line before printing the prompt to clear the line + * vt100 are not used here for compatibility reasons + */ + z_cursor_next_line_move(sh); + state_set(sh, SHELL_STATE_ACTIVE); + z_shell_unlock(sh); return 0;