assert.c 2.2 KB

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