CrashTest.cpp 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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(test_type)
  14. , m_crash_function(move(crash_function))
  15. {
  16. }
  17. void Crash::run(RunType run_type = RunType::UsingChildProcess)
  18. {
  19. printf("\x1B[33mTesting\x1B[0m: \"%s\"\n", m_type.characters());
  20. auto run_crash_and_print_if_error = [this]() {
  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. };
  35. if (run_type == RunType::UsingCurrentProcess) {
  36. run_crash_and_print_if_error();
  37. } else {
  38. // Run the test in a child process so that we do not crash the crash program :^)
  39. pid_t pid = fork();
  40. if (pid < 0) {
  41. perror("fork");
  42. VERIFY_NOT_REACHED();
  43. } else if (pid == 0) {
  44. run_crash_and_print_if_error();
  45. exit(0);
  46. }
  47. int status;
  48. waitpid(pid, &status, 0);
  49. if (WIFSIGNALED(status))
  50. printf("\x1B[32mPASS\x1B[0m: Terminated with signal %d\n", WTERMSIG(status));
  51. }
  52. }
  53. }