assert.c 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * tools/testing/selftests/kvm/lib/assert.c
  3. *
  4. * Copyright (C) 2018, Google LLC.
  5. *
  6. * This work is licensed under the terms of the GNU GPL, version 2.
  7. */
  8. #define _GNU_SOURCE /* for getline(3) and strchrnul(3)*/
  9. #include "test_util.h"
  10. #include <execinfo.h>
  11. #include <sys/syscall.h>
  12. #include "../../kselftest.h"
  13. /* Dumps the current stack trace to stderr. */
  14. static void __attribute__((noinline)) test_dump_stack(void);
  15. static 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. * grep -v test_dump_stack | cat -n 1>&2
  22. *
  23. * Note that the spacing is different and there's no newline.
  24. */
  25. size_t i;
  26. size_t n = 20;
  27. void *stack[n];
  28. const char *addr2line = "addr2line -s -e /proc/$PPID/exe -fpai";
  29. const char *pipeline = "|cat -n 1>&2";
  30. char cmd[strlen(addr2line) + strlen(pipeline) +
  31. /* N bytes per addr * 2 digits per byte + 1 space per addr: */
  32. n * (((sizeof(void *)) * 2) + 1) +
  33. /* Null terminator: */
  34. 1];
  35. char *c;
  36. n = backtrace(stack, n);
  37. c = &cmd[0];
  38. c += sprintf(c, "%s", addr2line);
  39. /*
  40. * Skip the first 3 frames: backtrace, test_dump_stack, and
  41. * test_assert. We hope that backtrace isn't inlined and the other two
  42. * we've declared noinline.
  43. */
  44. for (i = 2; i < n; i++)
  45. c += sprintf(c, " %lx", ((unsigned long) stack[i]) - 1);
  46. c += sprintf(c, "%s", pipeline);
  47. #pragma GCC diagnostic push
  48. #pragma GCC diagnostic ignored "-Wunused-result"
  49. system(cmd);
  50. #pragma GCC diagnostic pop
  51. }
  52. static pid_t _gettid(void)
  53. {
  54. return syscall(SYS_gettid);
  55. }
  56. void __attribute__((noinline))
  57. test_assert(bool exp, const char *exp_str,
  58. const char *file, unsigned int line, const char *fmt, ...)
  59. {
  60. va_list ap;
  61. if (!(exp)) {
  62. va_start(ap, fmt);
  63. fprintf(stderr, "==== Test Assertion Failure ====\n"
  64. " %s:%u: %s\n"
  65. " pid=%d tid=%d - %s\n",
  66. file, line, exp_str, getpid(), _gettid(),
  67. strerror(errno));
  68. test_dump_stack();
  69. if (fmt) {
  70. fputs(" ", stderr);
  71. vfprintf(stderr, fmt, ap);
  72. fputs("\n", stderr);
  73. }
  74. va_end(ap);
  75. if (errno == EACCES)
  76. ksft_exit_skip("Access denied - Exiting.\n");
  77. exit(254);
  78. }
  79. return;
  80. }