assert.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. /* Dumps the current stack trace to stderr. */
  13. static void __attribute__((noinline)) test_dump_stack(void);
  14. static void test_dump_stack(void)
  15. {
  16. /*
  17. * Build and run this command:
  18. *
  19. * addr2line -s -e /proc/$PPID/exe -fpai {backtrace addresses} | \
  20. * grep -v test_dump_stack | cat -n 1>&2
  21. *
  22. * Note that the spacing is different and there's no newline.
  23. */
  24. size_t i;
  25. size_t n = 20;
  26. void *stack[n];
  27. const char *addr2line = "addr2line -s -e /proc/$PPID/exe -fpai";
  28. const char *pipeline = "|cat -n 1>&2";
  29. char cmd[strlen(addr2line) + strlen(pipeline) +
  30. /* N bytes per addr * 2 digits per byte + 1 space per addr: */
  31. n * (((sizeof(void *)) * 2) + 1) +
  32. /* Null terminator: */
  33. 1];
  34. char *c;
  35. n = backtrace(stack, n);
  36. c = &cmd[0];
  37. c += sprintf(c, "%s", addr2line);
  38. /*
  39. * Skip the first 3 frames: backtrace, test_dump_stack, and
  40. * test_assert. We hope that backtrace isn't inlined and the other two
  41. * we've declared noinline.
  42. */
  43. for (i = 2; i < n; i++)
  44. c += sprintf(c, " %lx", ((unsigned long) stack[i]) - 1);
  45. c += sprintf(c, "%s", pipeline);
  46. #pragma GCC diagnostic push
  47. #pragma GCC diagnostic ignored "-Wunused-result"
  48. system(cmd);
  49. #pragma GCC diagnostic pop
  50. }
  51. static pid_t gettid(void)
  52. {
  53. return syscall(SYS_gettid);
  54. }
  55. void __attribute__((noinline))
  56. test_assert(bool exp, const char *exp_str,
  57. const char *file, unsigned int line, const char *fmt, ...)
  58. {
  59. va_list ap;
  60. if (!(exp)) {
  61. va_start(ap, fmt);
  62. fprintf(stderr, "==== Test Assertion Failure ====\n"
  63. " %s:%u: %s\n"
  64. " pid=%d tid=%d\n",
  65. file, line, exp_str, getpid(), gettid());
  66. test_dump_stack();
  67. if (fmt) {
  68. fputs(" ", stderr);
  69. vfprintf(stderr, fmt, ap);
  70. fputs("\n", stderr);
  71. }
  72. va_end(ap);
  73. exit(254);
  74. }
  75. return;
  76. }