KVM: selftests: Gracefully handle empty stack traces
authorDavid Matlack <dmatlack@google.com>
Thu, 22 Sep 2022 23:17:23 +0000 (16:17 -0700)
committerPaolo Bonzini <pbonzini@redhat.com>
Fri, 30 Sep 2022 10:38:00 +0000 (06:38 -0400)
Bail out of test_dump_stack() if the stack trace is empty rather than
invoking addr2line with zero addresses. The problem with the latter is
that addr2line will block waiting for addresses to be passed in via
stdin, e.g. if running a selftest from an interactive terminal.

Opportunistically fix up the comment that mentions skipping 3 frames
since only 2 are skipped in the code.

Cc: Vipin Sharma <vipinsh@google.com>
Cc: Sean Christopherson <seanjc@google.com>
Signed-off-by: David Matlack <dmatlack@google.com>
Message-Id: <20220922231724.3560211-1-dmatlack@google.com>
[Small tweak to keep backtrace() call close to if(). - Paolo]
Signed-off-by: Paolo Bonzini <pbonzini@redhat.com>
tools/testing/selftests/kvm/lib/assert.c

index 71ade61..2bd25b1 100644 (file)
@@ -22,7 +22,7 @@ static void test_dump_stack(void)
         * Build and run this command:
         *
         *      addr2line -s -e /proc/$PPID/exe -fpai {backtrace addresses} | \
-        *              grep -v test_dump_stack | cat -n 1>&2
+        *              cat -n 1>&2
         *
         * Note that the spacing is different and there's no newline.
         */
@@ -36,18 +36,24 @@ static void test_dump_stack(void)
                 n * (((sizeof(void *)) * 2) + 1) +
                 /* Null terminator: */
                 1];
-       char *c;
+       char *c = cmd;
 
        n = backtrace(stack, n);
-       c = &cmd[0];
-       c += sprintf(c, "%s", addr2line);
        /*
-        * Skip the first 3 frames: backtrace, test_dump_stack, and
-        * test_assert. We hope that backtrace isn't inlined and the other two
-        * we've declared noinline.
+        * Skip the first 2 frames, which should be test_dump_stack() and
+        * test_assert(); both of which are declared noinline.  Bail if the
+        * resulting stack trace would be empty. Otherwise, addr2line will block
+        * waiting for addresses to be passed in via stdin.
         */
+       if (n <= 2) {
+               fputs("  (stack trace empty)\n", stderr);
+               return;
+       }
+
+       c += sprintf(c, "%s", addr2line);
        for (i = 2; i < n; i++)
                c += sprintf(c, " %lx", ((unsigned long) stack[i]) - 1);
+
        c += sprintf(c, "%s", pipeline);
 #pragma GCC diagnostic push
 #pragma GCC diagnostic ignored "-Wunused-result"