git: 12f747e6ff67 - main - truss(1): detach more carefully

From: Konstantin Belousov <kib_at_FreeBSD.org>
Date: Wed, 12 Jan 2022 18:04:48 UTC
The branch main has been updated by kib:

URL: https://cgit.FreeBSD.org/src/commit/?id=12f747e6ff675edfc1f2f95f7fc435dc01e0c29c

commit 12f747e6ff675edfc1f2f95f7fc435dc01e0c29c
Author:     Konstantin Belousov <kib@FreeBSD.org>
AuthorDate: 2022-01-12 08:21:19 +0000
Commit:     Konstantin Belousov <kib@FreeBSD.org>
CommitDate: 2022-01-12 18:04:41 +0000

    truss(1): detach more carefully
    
    When detaching, truss(1) sends SIGSTOP to the traced process to ensure
    that it is detaching in the steady state.  But it is possible, for
    multithreaded process, that wait() call returns event other than our
    SIGSTOP notification.  As result, SIGSTOP might sit in some thread'
    sigqueue, which makes SIGCONT a nop.  Then, the process is stopped when
    the queued SIGSTOP is acted upon.
    
    To handle this, loop until we drain everything before SIGSTOP,
    and see that the process is stopped.
    
    Note that the earlier fix makes it safe to have some more debugging
    events longering after SIGSTOP is acted upon.  They will be ignored
    after PT_DETACH.
    
    Reviewed by:    markj
    Sponsored by:   The FreeBSD Foundation
    MFC after:      1 week
    Differential revision:  https://reviews.freebsd.org/D33861
---
 usr.bin/truss/setup.c | 19 ++++++++++++++++---
 1 file changed, 16 insertions(+), 3 deletions(-)

diff --git a/usr.bin/truss/setup.c b/usr.bin/truss/setup.c
index 00c0553b4c7c..b5a1d4e32d2b 100644
--- a/usr.bin/truss/setup.c
+++ b/usr.bin/truss/setup.c
@@ -205,11 +205,24 @@ restore_proc(int signo __unused)
 static void
 detach_proc(pid_t pid)
 {
+	int sig, status;
 
-	/* stop the child so that we can detach */
+	/*
+	 * Stop the child so that we can detach.  Filter out possible
+	 * lingering SIGTRAP events buffered in the threads.
+	 */
 	kill(pid, SIGSTOP);
-	if (waitpid(pid, NULL, 0) < 0)
-		err(1, "Unexpected stop in waitpid");
+	for (;;) {
+		if (waitpid(pid, &status, 0) < 0)
+			err(1, "Unexpected error in waitpid");
+		sig = WIFSTOPPED(status) ? WSTOPSIG(status) : 0;
+		if (sig == SIGSTOP)
+			break;
+		if (sig == SIGTRAP)
+			sig = 0;
+		if (ptrace(PT_CONTINUE, pid, (caddr_t)1, sig) < 0)
+			err(1, "Can not continue for detach");
+	}
 
 	if (ptrace(PT_DETACH, pid, (caddr_t)1, 0) < 0)
 		err(1, "Can not detach the process");