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 <jakub.rzeszutko@verkada.com>
This commit is contained in:
Jakub Rzeszutko
2026-01-21 15:28:31 +01:00
committed by Maureen Helm
parent f87fff19a7
commit a04d8957c2

View File

@@ -1449,12 +1449,6 @@ int shell_start(const struct shell *sh)
z_shell_vt100_color_set(sh, SHELL_NORMAL); 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 * 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, * 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); 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); z_shell_unlock(sh);
return 0; return 0;