CrashTest.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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 <LibTest/CrashTest.h>
  9. #include <sys/wait.h>
  10. #include <unistd.h>
  11. namespace Test {
  12. Crash::Crash(String test_type, Function<Crash::Failure()> crash_function)
  13. : m_type(move(test_type))
  14. , m_crash_function(move(crash_function))
  15. {
  16. }
  17. bool Crash::run(RunType run_type)
  18. {
  19. printf("\x1B[33mTesting\x1B[0m: \"%s\"\n", m_type.characters());
  20. auto run_crash_and_print_if_error = [this]() -> bool {
  21. auto failure = m_crash_function();
  22. // If we got here something went wrong
  23. printf("\x1B[31mFAIL\x1B[0m: ");
  24. switch (failure) {
  25. case Failure::DidNotCrash:
  26. printf("Did not crash!\n");
  27. break;
  28. case Failure::UnexpectedError:
  29. printf("Unexpected error!\n");
  30. break;
  31. default:
  32. VERIFY_NOT_REACHED();
  33. }
  34. return false;
  35. };
  36. if (run_type == RunType::UsingCurrentProcess) {
  37. return run_crash_and_print_if_error();
  38. } else {
  39. // Run the test in a child process so that we do not crash the crash program :^)
  40. pid_t pid = fork();
  41. if (pid < 0) {
  42. perror("fork");
  43. VERIFY_NOT_REACHED();
  44. } else if (pid == 0) {
  45. run_crash_and_print_if_error();
  46. exit(0);
  47. }
  48. int status;
  49. waitpid(pid, &status, 0);
  50. if (WIFSIGNALED(status)) {
  51. printf("\x1B[32mPASS\x1B[0m: Terminated with signal %d\n", WTERMSIG(status));
  52. return true;
  53. }
  54. return false;
  55. }
  56. }
  57. }