From c9606ba6685a2291abbe221baec2246396e1f24e Mon Sep 17 00:00:00 2001 From: Alastair Houghton Date: Fri, 27 Jun 2025 11:05:45 +0100 Subject: [PATCH] [Concurrency] Prevent negative sleeps from sleeping forever. Requests to sleep until a negative timestamp would result in sleeping until `UINT64_MAX` nanoseconds from the start of the relevant clock, which is about 585 years. rdar://154346018 --- stdlib/public/Concurrency/DispatchGlobalExecutor.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/stdlib/public/Concurrency/DispatchGlobalExecutor.cpp b/stdlib/public/Concurrency/DispatchGlobalExecutor.cpp index 049e565ff9ed1..b9a72e5ecab14 100644 --- a/stdlib/public/Concurrency/DispatchGlobalExecutor.cpp +++ b/stdlib/public/Concurrency/DispatchGlobalExecutor.cpp @@ -333,7 +333,9 @@ void swift_dispatchEnqueueWithDeadline(bool global, } uint64_t deadline; - if (__builtin_mul_overflow(sec, NSEC_PER_SEC, &deadline) + if (sec < 0 || sec == 0 && nsec < 0) + deadline = 0; + else if (__builtin_mul_overflow(sec, NSEC_PER_SEC, &deadline) || __builtin_add_overflow(nsec, deadline, &deadline)) { deadline = UINT64_MAX; } @@ -342,8 +344,10 @@ void swift_dispatchEnqueueWithDeadline(bool global, if (tnsec != -1) { uint64_t leeway; - if (__builtin_mul_overflow(tsec, NSEC_PER_SEC, &leeway) - || __builtin_add_overflow(tnsec, leeway, &leeway)) { + if (tsec < 0 || tsec == 0 && tnsec < 0) + leeway = 0; + else if (__builtin_mul_overflow(tsec, NSEC_PER_SEC, &leeway) + || __builtin_add_overflow(tnsec, leeway, &leeway)) { leeway = UINT64_MAX; }