From 976ccdd0d0f090602e53ff73c171ea17b9b184ae Mon Sep 17 00:00:00 2001 From: Graeme Jenkinson Date: Thu, 24 Sep 2020 15:05:54 +0100 Subject: [PATCH] Scheduling tasks Int.max ns into future results in an obtuse fatal error (#1056) (#1642) Motivation: When scheduling a task too far into the future on a Darwin-kernel, a fatal error is produced. Whilst the error indicates that a parameter to the kevent syscall was invalid (EINVAL) it gives no further information as to the root cause. As the user's intent is to schedule an task far into the future, a fatal error should not result. Instead the time should be clamped to the maximum value that the Darwin-kernel supports. This ensures that , provided the system remains running, the task will eventually run (though this may be several yeasr into the future). Modifications: Duplicated the bounds checks from those in Darwin-kernel interval timer, clamping timespec values to the maximum value. Added an assert to check that the timespec tv_nsec field is valid (according to definition of the timespec datatype in ISO C11). And a precondition on the tv_sec field being > 0 (tasks schedule with times <= 0 should not result in a kevent being registered as they are scheduled immediately). Added note clarifying behaviour under Darwin-based OSes to the EventLoop scheduleTask() method. Added new unit test scheduling a task at the maximum value (which under any regression would crash). Result: Scheduled tasks where the timeout exceed the maximum value supported by Darwin-based OSes will be clamped to the maximum. Co-authored-by: Graeme Jenkinson Co-authored-by: Cory Benfield --- Sources/NIO/EventLoop.swift | 1 + Sources/NIO/Selector.swift | 19 ++++++++++++++++++- Tests/NIOTests/EventLoopTest+XCTest.swift | 1 + Tests/NIOTests/EventLoopTest.swift | 22 ++++++++++++++++++++++ 4 files changed, 42 insertions(+), 1 deletion(-) diff --git a/Sources/NIO/EventLoop.swift b/Sources/NIO/EventLoop.swift index 3f364551e..8da7614de 100644 --- a/Sources/NIO/EventLoop.swift +++ b/Sources/NIO/EventLoop.swift @@ -255,6 +255,7 @@ public protocol EventLoop: EventLoopGroup { /// on the completion of the task. /// /// - note: You can only cancel a task before it has started executing. + /// - note: The `in` value is clamped to a maximum when running on a Darwin-kernel. @discardableResult func scheduleTask(in: TimeAmount, _ task: @escaping () throws -> T) -> Scheduled diff --git a/Sources/NIO/Selector.swift b/Sources/NIO/Selector.swift index d6bb4d19b..3a2cbec7d 100644 --- a/Sources/NIO/Selector.swift +++ b/Sources/NIO/Selector.swift @@ -372,7 +372,24 @@ internal class Selector { case .now: return timespec(tv_sec: 0, tv_nsec: 0) case .blockUntilTimeout(let nanoseconds): - return timespec(timeAmount: nanoseconds) + // A scheduledTask() specified with a zero or negative timeAmount, will be scheduled immediately + // and therefore SHOULD NOT result in a kevent being created with a negative or zero timespec. + precondition(nanoseconds.nanoseconds > 0, "\(nanoseconds) is invalid (0 < nanoseconds)") + + var ts = timespec(timeAmount: nanoseconds) + // Check that the timespec tv_nsec field conforms to the definition in the C11 standard (ISO/IEC 9899:2011). + assert((0..<1_000_000_000).contains(ts.tv_nsec), "\(ts) is invalid (0 <= tv_nsec < 1_000_000_000)") + + // The maximum value in seconds supported by the Darwin-kernel interval timer (kern_time.c:itimerfix()) + // (note that - whilst unlikely - this value *could* change). + let sysIntervalTimerMaxSec = 100_000_000 + + // Clamp the timespec tv_sec value to the maximum supported by the Darwin-kernel. + // Whilst this schedules the event far into the future (several years) it will still be triggered provided + // the system stays up. + ts.tv_sec = min(ts.tv_sec, sysIntervalTimerMaxSec) + + return ts } } diff --git a/Tests/NIOTests/EventLoopTest+XCTest.swift b/Tests/NIOTests/EventLoopTest+XCTest.swift index 6570826f4..c4d1544e8 100644 --- a/Tests/NIOTests/EventLoopTest+XCTest.swift +++ b/Tests/NIOTests/EventLoopTest+XCTest.swift @@ -78,6 +78,7 @@ extension EventLoopTest { ("testWeFailOutstandingScheduledTasksOnELShutdown", testWeFailOutstandingScheduledTasksOnELShutdown), ("testSchedulingTaskOnFutureFailedByELShutdownDoesNotMakeUsExplode", testSchedulingTaskOnFutureFailedByELShutdownDoesNotMakeUsExplode), ("testEventLoopGroupProvider", testEventLoopGroupProvider), + ("testScheduleMaximum", testScheduleMaximum), ] } } diff --git a/Tests/NIOTests/EventLoopTest.swift b/Tests/NIOTests/EventLoopTest.swift index 9be329c2a..cc5d3a2cb 100644 --- a/Tests/NIOTests/EventLoopTest.swift +++ b/Tests/NIOTests/EventLoopTest.swift @@ -1295,4 +1295,26 @@ public final class EventLoopTest : XCTestCase { XCTFail("Not the same") } } + + // Test that scheduling a task at the maximum value doesn't crash. + // (Crashing resulted from an EINVAL/IOException thrown by the kevent + // syscall when the timeout value exceeded the maximum supported by + // the Darwin kernel #1056). + public func testScheduleMaximum() { + let eventLoop = EmbeddedEventLoop() + let maxAmount: TimeAmount = .nanoseconds(.max) + let scheduled = eventLoop.scheduleTask(in: maxAmount) { true } + + var result: Bool? + var error: Error? + scheduled.futureResult.whenSuccess { result = $0 } + scheduled.futureResult.whenFailure { error = $0 } + + scheduled.cancel() + + XCTAssertTrue(scheduled.futureResult.isFulfilled) + XCTAssertNil(result) + XCTAssertEqual(error as? EventLoopError, .cancelled) + } + }