]> www.infradead.org Git - users/dwmw2/linux.git/commit
selftests/bpf: Fix stdout race condition in traffic monitor
authorAmery Hung <ameryhung@gmail.com>
Thu, 13 Feb 2025 23:32:17 +0000 (15:32 -0800)
committerMartin KaFai Lau <martin.lau@kernel.org>
Fri, 14 Feb 2025 01:06:25 +0000 (17:06 -0800)
commitb99f27e90268b1a814c13f8bd72ea1db448ea257
treef61906409a29596d4f7911d94da984e56a85deb0
parentc83e2d970bae8616b94c40caa43d85f2f2c7d81e
selftests/bpf: Fix stdout race condition in traffic monitor

Fix a race condition between the main test_progs thread and the traffic
monitoring thread. The traffic monitor thread tries to print a line
using multiple printf and use flockfile() to prevent the line from being
torn apart. Meanwhile, the main thread doing io redirection can reassign
or close stdout when going through tests. A deadlock as shown below can
happen.

       main                      traffic_monitor_thread
       ====                      ======================
                                 show_transport()
                                 -> flockfile(stdout)

stdio_hijack_init()
-> stdout = open_memstream(log_buf, log_cnt);
   ...
   env.subtest_state->stdout_saved = stdout;

                                    ...
                                    funlockfile(stdout)
stdio_restore_cleanup()
-> fclose(env.subtest_state->stdout_saved);

After the traffic monitor thread lock stdout, A new memstream can be
assigned to stdout by the main thread. Therefore, the traffic monitor
thread later will not be able to unlock the original stdout. As the
main thread tries to access the old stdout, it will hang indefinitely
as it is still locked by the traffic monitor thread.

The deadlock can be reproduced by running test_progs repeatedly with
traffic monitor enabled:

for ((i=1;i<=100;i++)); do
  ./test_progs -a flow_dissector_skb* -m '*'
done

Fix this by only calling printf once and remove flockfile()/funlockfile().

Signed-off-by: Amery Hung <ameryhung@gmail.com>
Signed-off-by: Martin KaFai Lau <martin.lau@kernel.org>
Link: https://patch.msgid.link/20250213233217.553258-1-ameryhung@gmail.com
tools/testing/selftests/bpf/network_helpers.c