Path: blob/master/tools/testing/selftests/kvm/lib/assert.c
38237 views
// SPDX-License-Identifier: GPL-2.0-only1/*2* tools/testing/selftests/kvm/lib/assert.c3*4* Copyright (C) 2018, Google LLC.5*/6#include "test_util.h"78#include <execinfo.h>9#include <sys/syscall.h>1011#include "kselftest.h"1213/* Dumps the current stack trace to stderr. */14static void __attribute__((noinline)) test_dump_stack(void);15static void test_dump_stack(void)16{17/*18* Build and run this command:19*20* addr2line -s -e /proc/$PPID/exe -fpai {backtrace addresses} | \21* cat -n 1>&222*23* Note that the spacing is different and there's no newline.24*/25size_t i;26size_t n = 20;27void *stack[n];28const char *addr2line = "addr2line -s -e /proc/$PPID/exe -fpai";29const char *pipeline = "|cat -n 1>&2";30char cmd[strlen(addr2line) + strlen(pipeline) +31/* N bytes per addr * 2 digits per byte + 1 space per addr: */32n * (((sizeof(void *)) * 2) + 1) +33/* Null terminator: */341];35char *c = cmd;3637n = backtrace(stack, n);38/*39* Skip the first 2 frames, which should be test_dump_stack() and40* test_assert(); both of which are declared noinline. Bail if the41* resulting stack trace would be empty. Otherwise, addr2line will block42* waiting for addresses to be passed in via stdin.43*/44if (n <= 2) {45fputs(" (stack trace empty)\n", stderr);46return;47}4849c += sprintf(c, "%s", addr2line);50for (i = 2; i < n; i++)51c += sprintf(c, " %lx", ((unsigned long) stack[i]) - 1);5253c += sprintf(c, "%s", pipeline);54#pragma GCC diagnostic push55#pragma GCC diagnostic ignored "-Wunused-result"56system(cmd);57#pragma GCC diagnostic pop58}5960static pid_t _gettid(void)61{62return syscall(SYS_gettid);63}6465void __attribute__((noinline))66test_assert(bool exp, const char *exp_str,67const char *file, unsigned int line, const char *fmt, ...)68{69va_list ap;7071if (!(exp)) {72va_start(ap, fmt);7374fprintf(stderr, "==== Test Assertion Failure ====\n"75" %s:%u: %s\n"76" pid=%d tid=%d errno=%d - %s\n",77file, line, exp_str, getpid(), _gettid(),78errno, strerror(errno));79test_dump_stack();80if (fmt) {81fputs(" ", stderr);82vfprintf(stderr, fmt, ap);83fputs("\n", stderr);84}85va_end(ap);8687if (errno == EACCES) {88print_skip("Access denied - Exiting");89exit(KSFT_SKIP);90}91exit(254);92}9394return;95}969798