CrashTest.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2018-2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2019-2020, Shannon Booth <shannon.ml.booth@gmail.com>
  4. * Copyright (c) 2021, Brian Gianforcaro <bgianf@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/Platform.h>
  9. #include <LibTest/CrashTest.h>
  10. #include <sys/wait.h>
  11. #include <unistd.h>
  12. #ifndef AK_OS_MACOS
  13. # include <sys/prctl.h>
  14. #endif
  15. namespace Test {
  16. Crash::Crash(String test_type, Function<Crash::Failure()> crash_function)
  17. : m_type(move(test_type))
  18. , m_crash_function(move(crash_function))
  19. {
  20. }
  21. bool Crash::run(RunType run_type)
  22. {
  23. outln("\x1B[33mTesting\x1B[0m: \"{}\"", m_type);
  24. auto run_crash_and_print_if_error = [this]() -> bool {
  25. auto failure = m_crash_function();
  26. // If we got here something went wrong
  27. out("\x1B[31mFAIL\x1B[0m: ");
  28. switch (failure) {
  29. case Failure::DidNotCrash:
  30. outln("Did not crash!");
  31. break;
  32. case Failure::UnexpectedError:
  33. outln("Unexpected error!");
  34. break;
  35. default:
  36. VERIFY_NOT_REACHED();
  37. }
  38. return false;
  39. };
  40. if (run_type == RunType::UsingCurrentProcess) {
  41. return run_crash_and_print_if_error();
  42. } else {
  43. // Run the test in a child process so that we do not crash the crash program :^)
  44. pid_t pid = fork();
  45. if (pid < 0) {
  46. perror("fork");
  47. VERIFY_NOT_REACHED();
  48. } else if (pid == 0) {
  49. #ifndef AK_OS_MACOS
  50. if (prctl(PR_SET_DUMPABLE, 0, 0) < 0)
  51. perror("prctl(PR_SET_DUMPABLE)");
  52. #endif
  53. run_crash_and_print_if_error();
  54. exit(0);
  55. }
  56. int status;
  57. waitpid(pid, &status, 0);
  58. if (WIFSIGNALED(status)) {
  59. outln("\x1B[32mPASS\x1B[0m: Terminated with signal {}", WTERMSIG(status));
  60. return true;
  61. }
  62. return false;
  63. }
  64. }
  65. }