xref: /linux/tools/testing/selftests/kvm/lib/assert.c (revision d0ee290071b475410476b4126c72da4bf6a2194c)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * tools/testing/selftests/kvm/lib/assert.c
4  *
5  * Copyright (C) 2018, Google LLC.
6  */
7 #include "test_util.h"
8 
9 
10 #include <sys/syscall.h>
11 
12 #include "kselftest.h"
13 
14 #ifdef __GLIBC__
15 #include <execinfo.h>
16 
17 /* Dumps the current stack trace to stderr. */
18 static void __attribute__((noinline)) test_dump_stack(void);
test_dump_stack(void)19 static void test_dump_stack(void)
20 {
21 	/*
22 	 * Build and run this command:
23 	 *
24 	 *	addr2line -s -e /proc/$PPID/exe -fpai {backtrace addresses} | \
25 	 *		cat -n 1>&2
26 	 *
27 	 * Note that the spacing is different and there's no newline.
28 	 */
29 	size_t i;
30 	size_t n = 20;
31 	void *stack[n];
32 	const char *addr2line = "addr2line -s -e /proc/$PPID/exe -fpai";
33 	const char *pipeline = "|cat -n 1>&2";
34 	char cmd[strlen(addr2line) + strlen(pipeline) +
35 		 /* N bytes per addr * 2 digits per byte + 1 space per addr: */
36 		 n * (((sizeof(void *)) * 2) + 1) +
37 		 /* Null terminator: */
38 		 1];
39 	char *c = cmd;
40 
41 	n = backtrace(stack, n);
42 	/*
43 	 * Skip the first 2 frames, which should be test_dump_stack() and
44 	 * test_assert(); both of which are declared noinline.  Bail if the
45 	 * resulting stack trace would be empty. Otherwise, addr2line will block
46 	 * waiting for addresses to be passed in via stdin.
47 	 */
48 	if (n <= 2) {
49 		fputs("  (stack trace empty)\n", stderr);
50 		return;
51 	}
52 
53 	c += sprintf(c, "%s", addr2line);
54 	for (i = 2; i < n; i++)
55 		c += sprintf(c, " %lx", ((unsigned long) stack[i]) - 1);
56 
57 	c += sprintf(c, "%s", pipeline);
58 #pragma GCC diagnostic push
59 #pragma GCC diagnostic ignored "-Wunused-result"
60 	system(cmd);
61 #pragma GCC diagnostic pop
62 }
63 #else
test_dump_stack(void)64 static void test_dump_stack(void) {}
65 #endif
66 
_gettid(void)67 static pid_t _gettid(void)
68 {
69 	return syscall(SYS_gettid);
70 }
71 
72 void __attribute__((noinline))
test_assert(bool exp,const char * exp_str,const char * file,unsigned int line,const char * fmt,...)73 test_assert(bool exp, const char *exp_str,
74 	const char *file, unsigned int line, const char *fmt, ...)
75 {
76 	va_list ap;
77 
78 	if (!(exp)) {
79 		va_start(ap, fmt);
80 
81 		fprintf(stderr, "==== Test Assertion Failure ====\n"
82 			"  %s:%u: %s\n"
83 			"  pid=%d tid=%d errno=%d - %s\n",
84 			file, line, exp_str, getpid(), _gettid(),
85 			errno, strerror(errno));
86 		test_dump_stack();
87 		if (fmt) {
88 			fputs("  ", stderr);
89 			vfprintf(stderr, fmt, ap);
90 			fputs("\n", stderr);
91 		}
92 		va_end(ap);
93 
94 		if (errno == EACCES) {
95 			print_skip("Access denied - Exiting");
96 			exit(KSFT_SKIP);
97 		}
98 		exit(254);
99 	}
100 
101 	return;
102 }
103