TestKernelAlarm.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /*
  2. * Copyright (c) 2021, Brian Gianforcaro <bgianf@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Atomic.h>
  7. #include <AK/Time.h>
  8. #include <LibCore/ElapsedTimer.h>
  9. #include <LibTest/TestCase.h>
  10. #include <signal.h>
  11. #include <signal_numbers.h>
  12. #include <unistd.h>
  13. class SuccessContext {
  14. public:
  15. static Atomic<bool> alarm_fired;
  16. static Core::ElapsedTimer signal_timer;
  17. static constexpr auto timer_value = Time::from_seconds(1);
  18. static void test_signal_handler(int signal)
  19. {
  20. auto actual_duration = Time::from_milliseconds(SuccessContext::signal_timer.elapsed());
  21. auto expected_duration = SuccessContext::timer_value;
  22. // Add a small buffer to allow for latency on the system.
  23. constexpr auto buffer_duration = Time::from_milliseconds(50);
  24. dbgln("Signal Times - Actual: {} Expected: {}", actual_duration.to_milliseconds(), expected_duration.to_milliseconds());
  25. EXPECT(actual_duration >= expected_duration);
  26. EXPECT(actual_duration < expected_duration + buffer_duration);
  27. EXPECT_EQ(signal, SIGALRM);
  28. SuccessContext::alarm_fired = true;
  29. }
  30. };
  31. Atomic<bool> SuccessContext::alarm_fired { false };
  32. Core::ElapsedTimer SuccessContext::signal_timer {};
  33. TEST_CASE(success_case)
  34. {
  35. signal(SIGALRM, SuccessContext::test_signal_handler);
  36. SuccessContext::signal_timer.start();
  37. auto previous_time = alarm(SuccessContext::timer_value.to_seconds());
  38. EXPECT_EQ(previous_time, 0u);
  39. auto sleep_time = SuccessContext::timer_value + Time::from_seconds(1);
  40. sleep(sleep_time.to_seconds());
  41. EXPECT(SuccessContext::alarm_fired);
  42. }
  43. // Regression test for issues #9071
  44. // See: https://github.com/SerenityOS/serenity/issues/9071
  45. TEST_CASE(regression_inifinite_loop)
  46. {
  47. constexpr auto hour_long_timer_value = Time::from_seconds(60 * 60);
  48. // Create an alarm timer significantly far into the future.
  49. auto previous_time = alarm(hour_long_timer_value.to_seconds());
  50. EXPECT_EQ(previous_time, 0u);
  51. // Update the alarm with a zero value before the previous timer expires.
  52. previous_time = alarm(0);
  53. EXPECT_EQ(previous_time, hour_long_timer_value.to_seconds());
  54. // Update the alarm with a zero value again, this shouldn't get stuck
  55. // in an infinite loop trying to cancel the previous timer in the kernel.
  56. previous_time = alarm(0);
  57. EXPECT_EQ(previous_time, 0u);
  58. }