Changeset 208415 in webkit


Ignore:
Timestamp:
Nov 4, 2016 8:02:39 PM (7 years ago)
Author:
fpizlo@apple.com
Message:

WTF::ParkingLot should stop using std::chrono because std::chrono::duration casts are prone to overflows
https://bugs.webkit.org/show_bug.cgi?id=152045

Reviewed by Andy Estes.
Source/JavaScriptCore:


Probably the nicest example of why this patch is a good idea is the change in
AtomicsObject.cpp.

  • jit/ICStats.cpp:

(JSC::ICStats::ICStats):

  • runtime/AtomicsObject.cpp:

(JSC::atomicsFuncWait):

Source/WebCore:

No new layout tests because no new behavior. The new WTF time classes have some unit tests
in TestWebKitAPI.

  • fileapi/ThreadableBlobRegistry.cpp:

(WebCore::ThreadableBlobRegistry::blobSize):

  • platform/MainThreadSharedTimer.h:
  • platform/SharedTimer.h:
  • platform/ThreadTimers.cpp:

(WebCore::ThreadTimers::updateSharedTimer):

  • platform/cf/MainThreadSharedTimerCF.cpp:

(WebCore::MainThreadSharedTimer::setFireInterval):

  • platform/efl/MainThreadSharedTimerEfl.cpp:

(WebCore::MainThreadSharedTimer::setFireInterval):

  • platform/glib/MainThreadSharedTimerGLib.cpp:

(WebCore::MainThreadSharedTimer::setFireInterval):

  • platform/win/MainThreadSharedTimerWin.cpp:

(WebCore::MainThreadSharedTimer::setFireInterval):

  • workers/WorkerRunLoop.cpp:

(WebCore::WorkerRunLoop::runInMode):

Source/WebKit2:

  • Platform/IPC/Connection.cpp:

(IPC::Connection::SyncMessageState::wait):
(IPC::Connection::sendMessage):
(IPC::Connection::timeoutRespectingIgnoreTimeoutsForTesting):
(IPC::Connection::waitForMessage):
(IPC::Connection::sendSyncMessage):
(IPC::Connection::waitForSyncReply):

  • Platform/IPC/Connection.h:

(IPC::Connection::sendSync):
(IPC::Connection::waitForAndDispatchImmediately):

  • Platform/IPC/MessageSender.h:

(IPC::MessageSender::sendSync):

  • UIProcess/ChildProcessProxy.h:

(WebKit::ChildProcessProxy::sendSync):

  • UIProcess/Network/NetworkProcessProxy.cpp:

(WebKit::NetworkProcessProxy::sendProcessWillSuspendImminently):

  • UIProcess/Storage/StorageManager.cpp:

(WebKit::StorageManager::applicationWillTerminate):

  • UIProcess/WebProcessProxy.cpp:

(WebKit::WebProcessProxy::sendProcessWillSuspendImminently):

  • UIProcess/WebResourceLoadStatisticsStore.cpp:

(WebKit::WebResourceLoadStatisticsStore::applicationWillTerminate):

  • UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.h:
  • UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.mm:

(-[WKOneShotDisplayLinkHandler displayLinkFired:]):
(WebKit::RemoteLayerTreeDrawingAreaProxy::commitLayerTree):
(WebKit::RemoteLayerTreeDrawingAreaProxy::didRefreshDisplay):
(WebKit::RemoteLayerTreeDrawingAreaProxy::waitForDidUpdateActivityState):

  • UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm:

(WebKit::TiledCoreAnimationDrawingAreaProxy::waitForDidUpdateActivityState):

  • UIProcess/mac/WKImmediateActionController.mm:

(-[WKImmediateActionController immediateActionRecognizerWillBeginAnimation:]):

  • UIProcess/mac/WebPageProxyMac.mm:

(WebKit::WebPageProxy::stringSelectionForPasteboard):
(WebKit::WebPageProxy::dataSelectionForPasteboard):
(WebKit::WebPageProxy::readSelectionFromPasteboard):
(WebKit::WebPageProxy::shouldDelayWindowOrderingForEvent):
(WebKit::WebPageProxy::acceptsFirstMouse):

  • WebProcess/WebCoreSupport/WebChromeClient.cpp:

(WebKit::WebChromeClient::runBeforeUnloadConfirmPanel):
(WebKit::WebChromeClient::runJavaScriptAlert):
(WebKit::WebChromeClient::runJavaScriptConfirm):
(WebKit::WebChromeClient::runJavaScriptPrompt):
(WebKit::WebChromeClient::print):
(WebKit::WebChromeClient::exceededDatabaseQuota):
(WebKit::WebChromeClient::reachedApplicationCacheOriginQuota):

  • WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp:

(WebKit::WebFrameLoaderClient::dispatchDecidePolicyForResponse):

  • WebProcess/WebPage/WebPage.cpp:

(WebKit::WebPage::postSynchronousMessageForTesting):

Source/WTF:


We used to use 'double' for all time measurements. Sometimes it was milliseconds,
sometimes it was seconds. Sometimes we measured a span of time, sometimes we spoke of time
since some epoch. When we spoke of time since epoch, we either used a monotonic clock or
a wall clock. The type - always 'double' - never told us what kind of time we had, even
though there were roughly six of them (sec interval, ms interval, sec since epoch on wall,
ms since epoch on wall, sec since epoch monotonic, ms since epoch monotonic).

At some point, we thought that it would be a good idea to replace these doubles with
std::chrono. But since replacing some things with std::chrono, we found it to be terribly
inconvenient:

  • Outrageous API. I never want to say std::chrono::milliseconds(blah). I never want to say std::chrono::steady_clock::timepoint. The syntax for duration_cast is ugly, and ideally duration_cast would not even be a thing.


  • No overflow protection. std::chrono uses integers by default and using anything else is clumsy. But the integer math is done without regard for the rough edges of integer math, so any cast between std::chrono types risks overflow. Any comparison risks overflow because it may do conversions silently. We have even found bugs where some C++ implementations had more overflows than others, which ends up being a special kind of hell. In many cases, the overflow also has nasal demons.


It's an error to represent time using integers. It would have been excusable back when
floating point math was not guaranteed to be supported on all platforms, but that would
have been a long time ago. Time is a continuous, infinite concept and it's a perfect fit
for floating point:

  • Floating point preserves precision under multiplication in all but extreme cases, so using floating point for time means that unit conversions are almost completely lossless. This means that we don't have to think very hard about what units to use. In this patch, we use seconds almost everywhere. We only convert at boundaries, like an API boundary that wants something other than seconds.


  • Floating point makes it easy to reason about infinity, which is something that time code wants to do a lot. Example: when would you like to timeout? Infinity please! This is the most elegant way of having an API support both a timeout variant and a no-timeout variant.
  • Floating point does well-understood things when math goes wrong, and these things are pretty well optimized to match what a mathematician would do when computing with real numbers represented using scientific notation with a finite number of significant digits. This means that time math under floating point looks like normal math. On the other hand, std::chrono time math looks like garbage because you have to always check for multiple possible UB corners whenever you touch large integers. Integers that represent time are very likely to be large and you don't have to do much to overflow them. At this time, based on the number of bugs we have already seen due to chrono overflows, I am not certain that we even understand what are all of the corner cases that we should even check for.


This patch introduces a new set of timekeeping classes that are all based on double, and
all internally use seconds. These classes support algebraic typing. The classes are:

  • Seconds: this is for measuring a duration.
  • WallTime: time since epoch according to a wall clock (aka real time clock).
  • MonotonicTime: time since epoch according to a monotonic clock.
  • ClockType: enum that says either Wall or Monotonic.
  • TimeWithDynamicClockType: a tuple of double and ClockType, which represents either a wall time or a monotonic time.


All of these classes behave like C++ values and are cheap to copy around since they are
very nearly POD. This supports comprehensive conversions between the various time types.
Most of this is by way of algebra. Here are just some of the rules we recognize:

WallTime = WallTime + Seconds
Seconds = WallTime - WallTime
MonotonicTime = MonotonicTime + Seconds
etc...

We support negative, infinite, and NaN times because math.

We support conversions between MonotonicTime and WallTime, like:

WallTime wt = mt.approximateWallTime()

This is called this "approximate" because the only way to do it is to get the current time
on both clocks and convert relative to that.

Many of our APIs would be happy using whatever notion of time the user wanted to use. For
those APIs, which includes Condition and ParkingLot, we have TimeWithDynamicClockType. You
can automatically convert WallTime or MonotonicTime to TimeWithDynamicClockType. This
means that if you use a WallTime with Condition::waitUntil, then Condition's internal
logic for when it should wake up makes its decision based on the current WallTime - but if
you use MonotonicTime then waitUntil will make its decision based on current
MonotonicTime. This is a greater level of flexibility than chrono allowed, since chrono
did not have the concept of a dynamic clock type.

This patch does not include conversions between std::chrono and these new time classes,
because past experience shows that we're quite bad at getting conversions between
std::chrono and anything else right. Also, I didn't need such conversion code because this
patch only converts code that transitively touches ParkingLot and Condition. It was easy
to get all of that code onto the new time classes.

  • WTF.xcodeproj/project.pbxproj:
  • wtf/AutomaticThread.cpp:

(WTF::AutomaticThread::start):

  • wtf/CMakeLists.txt:
  • wtf/ClockType.cpp: Added.

(WTF::printInternal):

  • wtf/ClockType.h: Added.
  • wtf/Condition.h:

(WTF::ConditionBase::waitUntil):
(WTF::ConditionBase::waitFor):
(WTF::ConditionBase::wait):
(WTF::ConditionBase::waitUntilWallClockSeconds): Deleted.
(WTF::ConditionBase::waitUntilMonotonicClockSeconds): Deleted.
(WTF::ConditionBase::waitForSeconds): Deleted.
(WTF::ConditionBase::waitForSecondsImpl): Deleted.
(WTF::ConditionBase::waitForImpl): Deleted.
(WTF::ConditionBase::absoluteFromRelative): Deleted.

  • wtf/CrossThreadQueue.h:

(WTF::CrossThreadQueue<DataType>::waitForMessage):

  • wtf/CurrentTime.cpp:

(WTF::sleep):

  • wtf/MessageQueue.h:

(WTF::MessageQueue::infiniteTime): Deleted.

  • wtf/MonotonicTime.cpp: Added.

(WTF::MonotonicTime::now):
(WTF::MonotonicTime::approximateWallTime):
(WTF::MonotonicTime::dump):
(WTF::MonotonicTime::sleep):

  • wtf/MonotonicTime.h: Added.

(WTF::MonotonicTime::MonotonicTime):
(WTF::MonotonicTime::fromRawDouble):
(WTF::MonotonicTime::infinity):
(WTF::MonotonicTime::secondsSinceEpoch):
(WTF::MonotonicTime::approximateMonotonicTime):
(WTF::MonotonicTime::operator bool):
(WTF::MonotonicTime::operator+):
(WTF::MonotonicTime::operator-):
(WTF::MonotonicTime::operator+=):
(WTF::MonotonicTime::operator-=):
(WTF::MonotonicTime::operator==):
(WTF::MonotonicTime::operator!=):
(WTF::MonotonicTime::operator<):
(WTF::MonotonicTime::operator>):
(WTF::MonotonicTime::operator<=):
(WTF::MonotonicTime::operator>=):

  • wtf/ParkingLot.cpp:

(WTF::ParkingLot::parkConditionallyImpl):
(WTF::ParkingLot::unparkOne):
(WTF::ParkingLot::unparkOneImpl):
(WTF::ParkingLot::unparkCount):

  • wtf/ParkingLot.h:

(WTF::ParkingLot::parkConditionally):
(WTF::ParkingLot::compareAndPark):

  • wtf/Seconds.cpp: Added.

(WTF::Seconds::operator+):
(WTF::Seconds::operator-):
(WTF::Seconds::dump):
(WTF::Seconds::sleep):

  • wtf/Seconds.h: Added.

(WTF::Seconds::Seconds):
(WTF::Seconds::value):
(WTF::Seconds::seconds):
(WTF::Seconds::milliseconds):
(WTF::Seconds::microseconds):
(WTF::Seconds::nanoseconds):
(WTF::Seconds::fromMilliseconds):
(WTF::Seconds::fromMicroseconds):
(WTF::Seconds::fromNanoseconds):
(WTF::Seconds::infinity):
(WTF::Seconds::operator bool):
(WTF::Seconds::operator+):
(WTF::Seconds::operator-):
(WTF::Seconds::operator*):
(WTF::Seconds::operator/):
(WTF::Seconds::operator+=):
(WTF::Seconds::operator-=):
(WTF::Seconds::operator*=):
(WTF::Seconds::operator/=):
(WTF::Seconds::operator==):
(WTF::Seconds::operator!=):
(WTF::Seconds::operator<):
(WTF::Seconds::operator>):
(WTF::Seconds::operator<=):
(WTF::Seconds::operator>=):

  • wtf/TimeWithDynamicClockType.cpp: Added.

(WTF::TimeWithDynamicClockType::now):
(WTF::TimeWithDynamicClockType::nowWithSameClock):
(WTF::TimeWithDynamicClockType::wallTime):
(WTF::TimeWithDynamicClockType::monotonicTime):
(WTF::TimeWithDynamicClockType::approximateWallTime):
(WTF::TimeWithDynamicClockType::approximateMonotonicTime):
(WTF::TimeWithDynamicClockType::operator-):
(WTF::TimeWithDynamicClockType::operator<):
(WTF::TimeWithDynamicClockType::operator>):
(WTF::TimeWithDynamicClockType::operator<=):
(WTF::TimeWithDynamicClockType::operator>=):
(WTF::TimeWithDynamicClockType::dump):
(WTF::TimeWithDynamicClockType::sleep):

  • wtf/TimeWithDynamicClockType.h: Added.

(WTF::TimeWithDynamicClockType::TimeWithDynamicClockType):
(WTF::TimeWithDynamicClockType::fromRawDouble):
(WTF::TimeWithDynamicClockType::secondsSinceEpoch):
(WTF::TimeWithDynamicClockType::clockType):
(WTF::TimeWithDynamicClockType::withSameClockAndRawDouble):
(WTF::TimeWithDynamicClockType::operator bool):
(WTF::TimeWithDynamicClockType::operator+):
(WTF::TimeWithDynamicClockType::operator-):
(WTF::TimeWithDynamicClockType::operator+=):
(WTF::TimeWithDynamicClockType::operator-=):
(WTF::TimeWithDynamicClockType::operator==):
(WTF::TimeWithDynamicClockType::operator!=):

  • wtf/WallTime.cpp: Added.

(WTF::WallTime::now):
(WTF::WallTime::approximateMonotonicTime):
(WTF::WallTime::dump):
(WTF::WallTime::sleep):

  • wtf/WallTime.h: Added.

(WTF::WallTime::WallTime):
(WTF::WallTime::fromRawDouble):
(WTF::WallTime::infinity):
(WTF::WallTime::secondsSinceEpoch):
(WTF::WallTime::approximateWallTime):
(WTF::WallTime::operator bool):
(WTF::WallTime::operator+):
(WTF::WallTime::operator-):
(WTF::WallTime::operator+=):
(WTF::WallTime::operator-=):
(WTF::WallTime::operator==):
(WTF::WallTime::operator!=):
(WTF::WallTime::operator<):
(WTF::WallTime::operator>):
(WTF::WallTime::operator<=):
(WTF::WallTime::operator>=):

  • wtf/threads/BinarySemaphore.cpp:

(WTF::BinarySemaphore::wait):

  • wtf/threads/BinarySemaphore.h:

Tools:

  • TestWebKitAPI/CMakeLists.txt:
  • TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
  • TestWebKitAPI/Tests/WTF/Condition.cpp:

(TestWebKitAPI::TEST):

  • TestWebKitAPI/Tests/WTF/SynchronizedFixedQueue.cpp:

(TestWebKitAPI::ToUpperConverter::stopProducing):
(TestWebKitAPI::ToUpperConverter::stopConsuming):

  • TestWebKitAPI/Tests/WTF/Time.cpp: Added.

(WTF::operator<<):
(TestWebKitAPI::TEST):

Location:
trunk
Files:
11 added
52 edited

Legend:

Unmodified
Added
Removed
  • trunk/Source/JavaScriptCore/ChangeLog

    r208413 r208415  
     12016-11-04  Filip Pizlo  <fpizlo@apple.com>
     2
     3        WTF::ParkingLot should stop using std::chrono because std::chrono::duration casts are prone to overflows
     4        https://bugs.webkit.org/show_bug.cgi?id=152045
     5
     6        Reviewed by Andy Estes.
     7       
     8        Probably the nicest example of why this patch is a good idea is the change in
     9        AtomicsObject.cpp.
     10
     11        * jit/ICStats.cpp:
     12        (JSC::ICStats::ICStats):
     13        * runtime/AtomicsObject.cpp:
     14        (JSC::atomicsFuncWait):
     15
    1162016-11-04  JF Bastien  <jfbastien@apple.com>
    217
  • trunk/Source/JavaScriptCore/jit/ICStats.cpp

    r199140 r208415  
    6464            LockHolder locker(m_lock);
    6565            for (;;) {
    66                 m_condition.waitForSeconds(m_lock, 1, [this] () -> bool { return m_shouldStop; });
     66                m_condition.waitFor(
     67                    m_lock, Seconds(1), [this] () -> bool { return m_shouldStop; });
    6768                if (m_shouldStop)
    6869                    break;
  • trunk/Source/JavaScriptCore/runtime/AtomicsObject.cpp

    r208306 r208415  
    305305    }
    306306   
    307     double timeoutInNanoseconds = timeoutInMilliseconds * 1000 * 1000;
     307    Seconds timeout = Seconds::fromMilliseconds(timeoutInMilliseconds);
    308308
    309309    // This covers the proposed rule:
     
    315315    // exec->argument(3) returns undefined if it's not provided and ToNumber(undefined) returns NaN,
    316316    // so NaN is the only special case.
    317     if (timeoutInNanoseconds == timeoutInNanoseconds)
    318         timeoutInNanoseconds = std::max(0., timeoutInNanoseconds);
     317    if (timeout == timeout)
     318        timeout = std::max(Seconds(0), timeout);
    319319    else
    320         timeoutInNanoseconds = std::numeric_limits<double>::infinity();
    321    
    322     // What happens next is a pile of nonsense, but it's all needed because of corner cases
    323     // inside std::chrono.
    324     // FIXME: Stop using std::chrono.
    325    
    326     ParkingLot::Clock::time_point timeout;
    327     if (timeoutInNanoseconds > static_cast<double>(std::numeric_limits<int64_t>::max()))
    328         timeout = ParkingLot::Clock::time_point::max();
    329     else {
    330         std::chrono::nanoseconds relativeTimeout =
    331             std::chrono::nanoseconds(static_cast<int64_t>(timeoutInNanoseconds));
    332         if (relativeTimeout < std::chrono::nanoseconds::zero())
    333             timeout = ParkingLot::Clock::now();
    334         else if (relativeTimeout > ParkingLot::Clock::duration::max())
    335             timeout = ParkingLot::Clock::time_point::max();
    336         else {
    337             ParkingLot::Clock::duration myRelativeTimeout =
    338                 std::chrono::duration_cast<ParkingLot::Clock::duration>(relativeTimeout);
    339             timeout = ParkingLot::Clock::now() + myRelativeTimeout;
    340         }
    341     }
     320        timeout = Seconds::infinity();
    342321   
    343322    bool didPassValidation = false;
     
    352331            },
    353332            [] () { },
    354             timeout);
     333            MonotonicTime::now() + timeout);
    355334    }
    356335    const char* resultString;
  • trunk/Source/WTF/ChangeLog

    r208373 r208415  
     12016-11-04  Filip Pizlo  <fpizlo@apple.com>
     2
     3        WTF::ParkingLot should stop using std::chrono because std::chrono::duration casts are prone to overflows
     4        https://bugs.webkit.org/show_bug.cgi?id=152045
     5
     6        Reviewed by Andy Estes.
     7       
     8        We used to use 'double' for all time measurements. Sometimes it was milliseconds,
     9        sometimes it was seconds. Sometimes we measured a span of time, sometimes we spoke of time
     10        since some epoch. When we spoke of time since epoch, we either used a monotonic clock or
     11        a wall clock. The type - always 'double' - never told us what kind of time we had, even
     12        though there were roughly six of them (sec interval, ms interval, sec since epoch on wall,
     13        ms since epoch on wall, sec since epoch monotonic, ms since epoch monotonic).
     14       
     15        At some point, we thought that it would be a good idea to replace these doubles with
     16        std::chrono. But since replacing some things with std::chrono, we found it to be terribly
     17        inconvenient:
     18       
     19        - Outrageous API. I never want to say std::chrono::milliseconds(blah). I never want to say
     20          std::chrono::steady_clock::timepoint. The syntax for duration_cast is ugly, and ideally
     21          duration_cast would not even be a thing.
     22       
     23        - No overflow protection. std::chrono uses integers by default and using anything else is
     24          clumsy. But the integer math is done without regard for the rough edges of integer math,
     25          so any cast between std::chrono types risks overflow. Any comparison risks overflow
     26          because it may do conversions silently. We have even found bugs where some C++
     27          implementations had more overflows than others, which ends up being a special kind of
     28          hell. In many cases, the overflow also has nasal demons.
     29       
     30        It's an error to represent time using integers. It would have been excusable back when
     31        floating point math was not guaranteed to be supported on all platforms, but that would
     32        have been a long time ago. Time is a continuous, infinite concept and it's a perfect fit
     33        for floating point:
     34       
     35        - Floating point preserves precision under multiplication in all but extreme cases, so
     36          using floating point for time means that unit conversions are almost completely
     37          lossless. This means that we don't have to think very hard about what units to use. In
     38          this patch, we use seconds almost everywhere. We only convert at boundaries, like an API
     39          boundary that wants something other than seconds.
     40       
     41        - Floating point makes it easy to reason about infinity, which is something that time code
     42          wants to do a lot. Example: when would you like to timeout? Infinity please! This is the
     43          most elegant way of having an API support both a timeout variant and a no-timeout
     44          variant.
     45
     46        - Floating point does well-understood things when math goes wrong, and these things are
     47          pretty well optimized to match what a mathematician would do when computing with real
     48          numbers represented using scientific notation with a finite number of significant
     49          digits. This means that time math under floating point looks like normal math. On the
     50          other hand, std::chrono time math looks like garbage because you have to always check
     51          for multiple possible UB corners whenever you touch large integers. Integers that
     52          represent time are very likely to be large and you don't have to do much to overflow
     53          them. At this time, based on the number of bugs we have already seen due to chrono
     54          overflows, I am not certain that we even understand what are all of the corner cases
     55          that we should even check for.
     56       
     57        This patch introduces a new set of timekeeping classes that are all based on double, and
     58        all internally use seconds. These classes support algebraic typing. The classes are:
     59       
     60        - Seconds: this is for measuring a duration.
     61        - WallTime: time since epoch according to a wall clock (aka real time clock).
     62        - MonotonicTime: time since epoch according to a monotonic clock.
     63        - ClockType: enum that says either Wall or Monotonic.
     64        - TimeWithDynamicClockType: a tuple of double and ClockType, which represents either a
     65          wall time or a monotonic time.
     66       
     67        All of these classes behave like C++ values and are cheap to copy around since they are
     68        very nearly POD. This supports comprehensive conversions between the various time types.
     69        Most of this is by way of algebra. Here are just some of the rules we recognize:
     70       
     71        WallTime = WallTime + Seconds
     72        Seconds = WallTime - WallTime
     73        MonotonicTime = MonotonicTime + Seconds
     74        etc...
     75       
     76        We support negative, infinite, and NaN times because math.
     77       
     78        We support conversions between MonotonicTime and WallTime, like:
     79       
     80        WallTime wt = mt.approximateWallTime()
     81       
     82        This is called this "approximate" because the only way to do it is to get the current time
     83        on both clocks and convert relative to that.
     84       
     85        Many of our APIs would be happy using whatever notion of time the user wanted to use. For
     86        those APIs, which includes Condition and ParkingLot, we have TimeWithDynamicClockType. You
     87        can automatically convert WallTime or MonotonicTime to TimeWithDynamicClockType. This
     88        means that if you use a WallTime with Condition::waitUntil, then Condition's internal
     89        logic for when it should wake up makes its decision based on the current WallTime - but if
     90        you use MonotonicTime then waitUntil will make its decision based on current
     91        MonotonicTime. This is a greater level of flexibility than chrono allowed, since chrono
     92        did not have the concept of a dynamic clock type.
     93       
     94        This patch does not include conversions between std::chrono and these new time classes,
     95        because past experience shows that we're quite bad at getting conversions between
     96        std::chrono and anything else right. Also, I didn't need such conversion code because this
     97        patch only converts code that transitively touches ParkingLot and Condition. It was easy
     98        to get all of that code onto the new time classes.
     99
     100        * WTF.xcodeproj/project.pbxproj:
     101        * wtf/AutomaticThread.cpp:
     102        (WTF::AutomaticThread::start):
     103        * wtf/CMakeLists.txt:
     104        * wtf/ClockType.cpp: Added.
     105        (WTF::printInternal):
     106        * wtf/ClockType.h: Added.
     107        * wtf/Condition.h:
     108        (WTF::ConditionBase::waitUntil):
     109        (WTF::ConditionBase::waitFor):
     110        (WTF::ConditionBase::wait):
     111        (WTF::ConditionBase::waitUntilWallClockSeconds): Deleted.
     112        (WTF::ConditionBase::waitUntilMonotonicClockSeconds): Deleted.
     113        (WTF::ConditionBase::waitForSeconds): Deleted.
     114        (WTF::ConditionBase::waitForSecondsImpl): Deleted.
     115        (WTF::ConditionBase::waitForImpl): Deleted.
     116        (WTF::ConditionBase::absoluteFromRelative): Deleted.
     117        * wtf/CrossThreadQueue.h:
     118        (WTF::CrossThreadQueue<DataType>::waitForMessage):
     119        * wtf/CurrentTime.cpp:
     120        (WTF::sleep):
     121        * wtf/MessageQueue.h:
     122        (WTF::MessageQueue::infiniteTime): Deleted.
     123        * wtf/MonotonicTime.cpp: Added.
     124        (WTF::MonotonicTime::now):
     125        (WTF::MonotonicTime::approximateWallTime):
     126        (WTF::MonotonicTime::dump):
     127        (WTF::MonotonicTime::sleep):
     128        * wtf/MonotonicTime.h: Added.
     129        (WTF::MonotonicTime::MonotonicTime):
     130        (WTF::MonotonicTime::fromRawDouble):
     131        (WTF::MonotonicTime::infinity):
     132        (WTF::MonotonicTime::secondsSinceEpoch):
     133        (WTF::MonotonicTime::approximateMonotonicTime):
     134        (WTF::MonotonicTime::operator bool):
     135        (WTF::MonotonicTime::operator+):
     136        (WTF::MonotonicTime::operator-):
     137        (WTF::MonotonicTime::operator+=):
     138        (WTF::MonotonicTime::operator-=):
     139        (WTF::MonotonicTime::operator==):
     140        (WTF::MonotonicTime::operator!=):
     141        (WTF::MonotonicTime::operator<):
     142        (WTF::MonotonicTime::operator>):
     143        (WTF::MonotonicTime::operator<=):
     144        (WTF::MonotonicTime::operator>=):
     145        * wtf/ParkingLot.cpp:
     146        (WTF::ParkingLot::parkConditionallyImpl):
     147        (WTF::ParkingLot::unparkOne):
     148        (WTF::ParkingLot::unparkOneImpl):
     149        (WTF::ParkingLot::unparkCount):
     150        * wtf/ParkingLot.h:
     151        (WTF::ParkingLot::parkConditionally):
     152        (WTF::ParkingLot::compareAndPark):
     153        * wtf/Seconds.cpp: Added.
     154        (WTF::Seconds::operator+):
     155        (WTF::Seconds::operator-):
     156        (WTF::Seconds::dump):
     157        (WTF::Seconds::sleep):
     158        * wtf/Seconds.h: Added.
     159        (WTF::Seconds::Seconds):
     160        (WTF::Seconds::value):
     161        (WTF::Seconds::seconds):
     162        (WTF::Seconds::milliseconds):
     163        (WTF::Seconds::microseconds):
     164        (WTF::Seconds::nanoseconds):
     165        (WTF::Seconds::fromMilliseconds):
     166        (WTF::Seconds::fromMicroseconds):
     167        (WTF::Seconds::fromNanoseconds):
     168        (WTF::Seconds::infinity):
     169        (WTF::Seconds::operator bool):
     170        (WTF::Seconds::operator+):
     171        (WTF::Seconds::operator-):
     172        (WTF::Seconds::operator*):
     173        (WTF::Seconds::operator/):
     174        (WTF::Seconds::operator+=):
     175        (WTF::Seconds::operator-=):
     176        (WTF::Seconds::operator*=):
     177        (WTF::Seconds::operator/=):
     178        (WTF::Seconds::operator==):
     179        (WTF::Seconds::operator!=):
     180        (WTF::Seconds::operator<):
     181        (WTF::Seconds::operator>):
     182        (WTF::Seconds::operator<=):
     183        (WTF::Seconds::operator>=):
     184        * wtf/TimeWithDynamicClockType.cpp: Added.
     185        (WTF::TimeWithDynamicClockType::now):
     186        (WTF::TimeWithDynamicClockType::nowWithSameClock):
     187        (WTF::TimeWithDynamicClockType::wallTime):
     188        (WTF::TimeWithDynamicClockType::monotonicTime):
     189        (WTF::TimeWithDynamicClockType::approximateWallTime):
     190        (WTF::TimeWithDynamicClockType::approximateMonotonicTime):
     191        (WTF::TimeWithDynamicClockType::operator-):
     192        (WTF::TimeWithDynamicClockType::operator<):
     193        (WTF::TimeWithDynamicClockType::operator>):
     194        (WTF::TimeWithDynamicClockType::operator<=):
     195        (WTF::TimeWithDynamicClockType::operator>=):
     196        (WTF::TimeWithDynamicClockType::dump):
     197        (WTF::TimeWithDynamicClockType::sleep):
     198        * wtf/TimeWithDynamicClockType.h: Added.
     199        (WTF::TimeWithDynamicClockType::TimeWithDynamicClockType):
     200        (WTF::TimeWithDynamicClockType::fromRawDouble):
     201        (WTF::TimeWithDynamicClockType::secondsSinceEpoch):
     202        (WTF::TimeWithDynamicClockType::clockType):
     203        (WTF::TimeWithDynamicClockType::withSameClockAndRawDouble):
     204        (WTF::TimeWithDynamicClockType::operator bool):
     205        (WTF::TimeWithDynamicClockType::operator+):
     206        (WTF::TimeWithDynamicClockType::operator-):
     207        (WTF::TimeWithDynamicClockType::operator+=):
     208        (WTF::TimeWithDynamicClockType::operator-=):
     209        (WTF::TimeWithDynamicClockType::operator==):
     210        (WTF::TimeWithDynamicClockType::operator!=):
     211        * wtf/WallTime.cpp: Added.
     212        (WTF::WallTime::now):
     213        (WTF::WallTime::approximateMonotonicTime):
     214        (WTF::WallTime::dump):
     215        (WTF::WallTime::sleep):
     216        * wtf/WallTime.h: Added.
     217        (WTF::WallTime::WallTime):
     218        (WTF::WallTime::fromRawDouble):
     219        (WTF::WallTime::infinity):
     220        (WTF::WallTime::secondsSinceEpoch):
     221        (WTF::WallTime::approximateWallTime):
     222        (WTF::WallTime::operator bool):
     223        (WTF::WallTime::operator+):
     224        (WTF::WallTime::operator-):
     225        (WTF::WallTime::operator+=):
     226        (WTF::WallTime::operator-=):
     227        (WTF::WallTime::operator==):
     228        (WTF::WallTime::operator!=):
     229        (WTF::WallTime::operator<):
     230        (WTF::WallTime::operator>):
     231        (WTF::WallTime::operator<=):
     232        (WTF::WallTime::operator>=):
     233        * wtf/threads/BinarySemaphore.cpp:
     234        (WTF::BinarySemaphore::wait):
     235        * wtf/threads/BinarySemaphore.h:
     236
    12372016-11-03  Filip Pizlo  <fpizlo@apple.com>
    2238
  • trunk/Source/WTF/WTF.xcodeproj/project.pbxproj

    r207480 r208415  
    3030                0F4570431BE5B58F0062A629 /* Dominators.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F4570421BE5B58F0062A629 /* Dominators.h */; };
    3131                0F4570451BE834410062A629 /* BubbleSort.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F4570441BE834410062A629 /* BubbleSort.h */; };
     32                0F66B28A1DC97BAB004A1D3F /* ClockType.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F66B2801DC97BAB004A1D3F /* ClockType.cpp */; };
     33                0F66B28B1DC97BAB004A1D3F /* ClockType.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F66B2811DC97BAB004A1D3F /* ClockType.h */; };
     34                0F66B28C1DC97BAB004A1D3F /* MonotonicTime.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F66B2821DC97BAB004A1D3F /* MonotonicTime.cpp */; };
     35                0F66B28D1DC97BAB004A1D3F /* MonotonicTime.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F66B2831DC97BAB004A1D3F /* MonotonicTime.h */; };
     36                0F66B28E1DC97BAB004A1D3F /* Seconds.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F66B2841DC97BAB004A1D3F /* Seconds.cpp */; };
     37                0F66B28F1DC97BAB004A1D3F /* Seconds.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F66B2851DC97BAB004A1D3F /* Seconds.h */; };
     38                0F66B2901DC97BAB004A1D3F /* TimeWithDynamicClockType.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F66B2861DC97BAB004A1D3F /* TimeWithDynamicClockType.cpp */; };
     39                0F66B2911DC97BAB004A1D3F /* TimeWithDynamicClockType.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F66B2871DC97BAB004A1D3F /* TimeWithDynamicClockType.h */; };
     40                0F66B2921DC97BAB004A1D3F /* WallTime.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F66B2881DC97BAB004A1D3F /* WallTime.cpp */; };
     41                0F66B2931DC97BAB004A1D3F /* WallTime.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F66B2891DC97BAB004A1D3F /* WallTime.h */; };
    3242                0F725CAC1C50461600AD943A /* RangeSet.h in Headers */ = {isa = PBXBuildFile; fileRef = 0F725CAB1C50461600AD943A /* RangeSet.h */; };
    3343                0F7C5FB61D885CF20044F5E2 /* FastBitVector.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F7C5FB51D885CF20044F5E2 /* FastBitVector.cpp */; };
     
    373383                0F4570421BE5B58F0062A629 /* Dominators.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Dominators.h; sourceTree = "<group>"; };
    374384                0F4570441BE834410062A629 /* BubbleSort.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = BubbleSort.h; sourceTree = "<group>"; };
     385                0F66B2801DC97BAB004A1D3F /* ClockType.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = ClockType.cpp; sourceTree = "<group>"; };
     386                0F66B2811DC97BAB004A1D3F /* ClockType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ClockType.h; sourceTree = "<group>"; };
     387                0F66B2821DC97BAB004A1D3F /* MonotonicTime.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MonotonicTime.cpp; sourceTree = "<group>"; };
     388                0F66B2831DC97BAB004A1D3F /* MonotonicTime.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MonotonicTime.h; sourceTree = "<group>"; };
     389                0F66B2841DC97BAB004A1D3F /* Seconds.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Seconds.cpp; sourceTree = "<group>"; };
     390                0F66B2851DC97BAB004A1D3F /* Seconds.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Seconds.h; sourceTree = "<group>"; };
     391                0F66B2861DC97BAB004A1D3F /* TimeWithDynamicClockType.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = TimeWithDynamicClockType.cpp; sourceTree = "<group>"; };
     392                0F66B2871DC97BAB004A1D3F /* TimeWithDynamicClockType.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TimeWithDynamicClockType.h; sourceTree = "<group>"; };
     393                0F66B2881DC97BAB004A1D3F /* WallTime.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WallTime.cpp; sourceTree = "<group>"; };
     394                0F66B2891DC97BAB004A1D3F /* WallTime.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = WallTime.h; sourceTree = "<group>"; };
    375395                0F725CAB1C50461600AD943A /* RangeSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RangeSet.h; sourceTree = "<group>"; };
    376396                0F7C5FB51D885CF20044F5E2 /* FastBitVector.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = FastBitVector.cpp; sourceTree = "<group>"; };
     
    864884                                A8A4726A151A825A004123FF /* CheckedArithmetic.h */,
    865885                                A8A4726B151A825A004123FF /* CheckedBoolean.h */,
     886                                0F66B2801DC97BAB004A1D3F /* ClockType.cpp */,
     887                                0F66B2811DC97BAB004A1D3F /* ClockType.h */,
    866888                                0FC4EDE51696149600F65041 /* CommaPrinter.h */,
    867889                                0F8F2B8F172E00F0007DBDA5 /* CompilationThread.cpp */,
     
    947969                                A8A472CE151A825B004123FF /* MetaAllocator.h */,
    948970                                A8A472CF151A825B004123FF /* MetaAllocatorHandle.h */,
     971                                0F66B2821DC97BAB004A1D3F /* MonotonicTime.cpp */,
     972                                0F66B2831DC97BAB004A1D3F /* MonotonicTime.h */,
    949973                                FE8225301B2A1E5B00BA68FD /* NakedPtr.h */,
    950974                                1A3F6BE6174ADA2100B2EEA7 /* NeverDestroyed.h */,
     
    10081032                                1A3524AA1D63A2FF0031729B /* Scope.h */,
    10091033                                0FEC84B01BDACD390080FF74 /* ScopedLambda.h */,
     1034                                0F66B2841DC97BAB004A1D3F /* Seconds.cpp */,
     1035                                0F66B2851DC97BAB004A1D3F /* Seconds.h */,
    10101036                                A8A47306151A825B004123FF /* SegmentedVector.h */,
    10111037                                A8A47307151A825B004123FF /* SentinelLinkedList.h */,
     
    10441070                                A8A4733E151A825B004123FF /* ThreadSafeRefCounted.h */,
    10451071                                A8A4733F151A825B004123FF /* ThreadSpecific.h */,
     1072                                0F66B2861DC97BAB004A1D3F /* TimeWithDynamicClockType.cpp */,
     1073                                0F66B2871DC97BAB004A1D3F /* TimeWithDynamicClockType.h */,
    10461074                                553071C91C40427200384898 /* TinyLRUCache.h */,
    10471075                                0FED67B51B22D4D80066CE15 /* TinyPtrSet.h */,
     
    10551083                                A8A47371151A825B004123FF /* VectorTraits.h */,
    10561084                                A8A47372151A825B004123FF /* VMTags.h */,
     1085                                0F66B2881DC97BAB004A1D3F /* WallTime.cpp */,
     1086                                0F66B2891DC97BAB004A1D3F /* WallTime.h */,
    10571087                                974CFC8D16A4F327006D5404 /* WeakPtr.h */,
    10581088                                0F3501631BB258C800F0A2A3 /* WeakRandom.h */,
     
    12601290                                0FB14E1B1810E1DC009B6B4D /* BagToHashMap.h in Headers */,
    12611291                                8134013915B092FD001FF0B8 /* Base64.h in Headers */,
     1292                                0F66B28F1DC97BAB004A1D3F /* Seconds.h in Headers */,
    12621293                                A8A473A9151A825B004123FF /* bignum-dtoa.h in Headers */,
     1294                                0F66B2911DC97BAB004A1D3F /* TimeWithDynamicClockType.h in Headers */,
    12631295                                A8A473AB151A825B004123FF /* bignum.h in Headers */,
    12641296                                A8A47452151A825B004123FF /* BinarySemaphore.h in Headers */,
     
    13411373                                539EB0631D55284200C82EF7 /* LEBDecoder.h in Headers */,
    13421374                                A70DA0851799F04D00529A9B /* ListDump.h in Headers */,
     1375                                0F66B2931DC97BAB004A1D3F /* WallTime.h in Headers */,
    13431376                                A8A473E1151A825B004123FF /* ListHashSet.h in Headers */,
    13441377                                0FE1646B1B6FFC9600400E7C /* Lock.h in Headers */,
     
    14001433                                1469419616EAAFF80024E146 /* SchedulePair.h in Headers */,
    14011434                                1A3524AB1D63A2FF0031729B /* Scope.h in Headers */,
     1435                                0F66B28D1DC97BAB004A1D3F /* MonotonicTime.h in Headers */,
    14021436                                0FEC84B11BDACD390080FF74 /* ScopedLambda.h in Headers */,
    14031437                                A5098B021C16A4F900087797 /* SecuritySPI.h in Headers */,
     
    14671501                                A8A47446151A825B004123FF /* WTFString.h in Headers */,
    14681502                                A8A47487151A825B004123FF /* WTFThreadData.h in Headers */,
     1503                                0F66B28B1DC97BAB004A1D3F /* ClockType.h in Headers */,
    14691504                                CE73E02519DCB7AB00580D5C /* XPCSPI.h in Headers */,
    14701505                                C8B0E1A1E01A486EB95E0D11 /* IndexSet.h in Headers */,
     
    15821617                                A8A47451151A825B004123FF /* BinarySemaphore.cpp in Sources */,
    15831618                                A8A4738B151A825B004123FF /* BitVector.cpp in Sources */,
     1619                                0F66B2901DC97BAB004A1D3F /* TimeWithDynamicClockType.cpp in Sources */,
    15841620                                DCEE22011CEA7551000C2396 /* BlockObjCExceptions.mm in Sources */,
    15851621                                A8A473AC151A825B004123FF /* cached-powers.cc in Sources */,
     
    16421678                                0FDDBFA71666DFA300C55FEF /* StringPrintStream.cpp in Sources */,
    16431679                                A8A47443151A825B004123FF /* StringStatics.cpp in Sources */,
     1680                                0F66B28A1DC97BAB004A1D3F /* ClockType.cpp in Sources */,
     1681                                0F66B2921DC97BAB004A1D3F /* WallTime.cpp in Sources */,
     1682                                0F66B28E1DC97BAB004A1D3F /* Seconds.cpp in Sources */,
    16441683                                0F43D8F11DB5ADDC00108FB6 /* AutomaticThread.cpp in Sources */,
    16451684                                93F1993E19D7958D00C2390B /* StringView.cpp in Sources */,
     
    16531692                                A8A4744A151A825B004123FF /* Threading.cpp in Sources */,
    16541693                                A8A4744E151A825B004123FF /* ThreadingPthreads.cpp in Sources */,
     1694                                0F66B28C1DC97BAB004A1D3F /* MonotonicTime.cpp in Sources */,
    16551695                                1C181C8F1D307AB800F5FA16 /* UTextProvider.cpp in Sources */,
    16561696                                1C181C911D307AB800F5FA16 /* UTextProviderLatin1.cpp in Sources */,
  • trunk/Source/WTF/wtf/AutomaticThread.cpp

    r208306 r208415  
    181181                        RELEASE_ASSERT(result == PollResult::Wait);
    182182                        // Shut the thread down after one second.
    183                         double timeout = monotonicallyIncreasingTime() + 1;
    184183                        bool awokenByNotify =
    185                             m_condition->m_condition.waitUntilMonotonicClockSeconds(*m_lock, timeout);
     184                            m_condition->m_condition.waitFor(*m_lock, Seconds(1));
    186185                        if (!awokenByNotify) {
    187186                            if (verbose)
  • trunk/Source/WTF/wtf/CMakeLists.txt

    r207480 r208415  
    1313    BumpPointerAllocator.h
    1414    ByteOrder.h
     15    ClockType.h
    1516    CompilationThread.h
    1617    Compiler.h
     
    6566    MetaAllocator.h
    6667    MetaAllocatorHandle.h
     68    MonotonicTime.h
    6769    Noncopyable.h
    6870    NumberOfCores.h
     
    102104    SaturatedArithmetic.h
    103105    ScopedLambda.h
     106    Seconds.h
    104107    SegmentedVector.h
    105108    SmallPtrSet.h
     
    117120    Threading.h
    118121    ThreadingPrimitives.h
     122    TimeWithDynamicClockType.h
    119123    TinyPtrSet.h
    120124    UniqueRef.h
     
    125129    VectorTraits.h
    126130    WTFThreadData.h
     131    WallTime.h
    127132    WeakPtr.h
    128133    WordLock.h
     
    177182    AutomaticThread.cpp
    178183    BitVector.cpp
     184    ClockType.cpp
    179185    CompilationThread.cpp
    180186    CrossThreadCopier.cpp
     
    196202    MediaTime.cpp
    197203    MetaAllocator.cpp
     204    MonotonicTime.cpp
    198205    NumberOfCores.cpp
    199206    OSRandomSource.cpp
     
    208215    RunLoop.cpp
    209216    SHA1.cpp
     217    Seconds.cpp
    210218    SixCharacterHash.cpp
    211219    StackBounds.cpp
     
    213221    StringPrintStream.cpp
    214222    Threading.cpp
     223    TimeWithDynamicClockType.cpp
    215224    WTFThreadData.cpp
     225    WallTime.cpp
    216226    WordLock.cpp
    217227    WorkQueue.cpp
  • trunk/Source/WTF/wtf/Condition.h

    r207545 r208415  
    11/*
    2  * Copyright (C) 2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2015-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2727#define WTF_Condition_h
    2828
    29 #include <chrono>
    3029#include <functional>
    3130#include <wtf/CurrentTime.h>
    3231#include <wtf/Noncopyable.h>
    3332#include <wtf/ParkingLot.h>
     33#include <wtf/TimeWithDynamicClockType.h>
    3434
    3535namespace WTF {
     
    4747// Use Lock in instance variables.
    4848struct ConditionBase {
    49     typedef ParkingLot::Clock Clock;
     49    // Condition will accept any kind of time and convert it internally, but this typedef tells
     50    // you what kind of time Condition would be able to use without conversions. However, if you
     51    // are unlikely to be affected by the cost of conversions, it is better to use MonotonicTime.
     52    typedef ParkingLot::Time Time;
    5053   
    5154    // Wait on a parking queue while releasing the given lock. It will unlock the lock just before
     
    6568    // documentation for timedwait().
    6669    template<typename LockType>
    67     bool waitUntil(LockType& lock, Clock::time_point timeout)
     70    bool waitUntil(LockType& lock, const TimeWithDynamicClockType& timeout)
    6871    {
    6972        bool result;
    70         if (timeout < Clock::now()) {
     73        if (timeout < timeout.nowWithSameClock()) {
    7174            lock.unlock();
    7275            result = false;
     
    9093    // May return early due to timeout.
    9194    template<typename LockType, typename Functor>
    92     bool waitUntil(LockType& lock, Clock::time_point timeout, const Functor& predicate)
     95    bool waitUntil(
     96        LockType& lock, const TimeWithDynamicClockType& timeout, const Functor& predicate)
    9397    {
    9498        while (!predicate()) {
     
    101105    // Wait until the given predicate is satisfied. Returns true if it is satisfied in the end.
    102106    // May return early due to timeout.
    103     template<typename LockType, typename DurationType, typename Functor>
     107    template<typename LockType, typename Functor>
    104108    bool waitFor(
    105         LockType& lock, const DurationType& relativeTimeout, const Functor& predicate)
     109        LockType& lock, Seconds relativeTimeout, const Functor& predicate)
    106110    {
    107         return waitUntil(lock, absoluteFromRelative(relativeTimeout), predicate);
     111        return waitUntil(lock, MonotonicTime::now() + relativeTimeout, predicate);
     112    }
     113   
     114    template<typename LockType>
     115    bool waitFor(LockType& lock, Seconds relativeTimeout)
     116    {
     117        return waitUntil(lock, MonotonicTime::now() + relativeTimeout);
    108118    }
    109119
     
    111121    void wait(LockType& lock)
    112122    {
    113         waitUntil(lock, Clock::time_point::max());
     123        waitUntil(lock, Time::infinity());
    114124    }
    115125
     
    119129        while (!predicate())
    120130            wait(lock);
    121     }
    122 
    123     template<typename LockType, typename TimeType>
    124     bool waitUntil(LockType& lock, const TimeType& timeout)
    125     {
    126         if (timeout == TimeType::max()) {
    127             wait(lock);
    128             return true;
    129         }
    130         return waitForImpl(lock, timeout - TimeType::clock::now());
    131     }
    132 
    133     template<typename LockType>
    134     bool waitUntilWallClockSeconds(LockType& lock, double absoluteTimeoutSeconds)
    135     {
    136         return waitForSecondsImpl(lock, absoluteTimeoutSeconds - currentTime());
    137     }
    138 
    139     template<typename LockType>
    140     bool waitUntilMonotonicClockSeconds(LockType& lock, double absoluteTimeoutSeconds)
    141     {
    142         return waitForSecondsImpl(lock, absoluteTimeoutSeconds - monotonicallyIncreasingTime());
    143     }
    144    
    145     template<typename LockType, typename Functor>
    146     bool waitForSeconds(LockType& lock, double relativeTimeoutSeconds, const Functor& predicate)
    147     {
    148         double relativeTimeoutNanoseconds = relativeTimeoutSeconds * (1000.0 * 1000.0 * 1000.0);
    149        
    150         if (!(relativeTimeoutNanoseconds > 0)) {
    151             // This handles insta-timeouts as well as NaN.
    152             lock.unlock();
    153             lock.lock();
    154             return false;
    155         }
    156 
    157         if (relativeTimeoutNanoseconds > static_cast<double>(std::numeric_limits<int64_t>::max())) {
    158             // If the timeout in nanoseconds cannot be expressed using a 64-bit integer, then we
    159             // might as well wait forever.
    160             wait(lock, predicate);
    161             return true;
    162         }
    163        
    164         auto relativeTimeout =
    165             std::chrono::nanoseconds(static_cast<int64_t>(relativeTimeoutNanoseconds));
    166 
    167         return waitFor(lock, relativeTimeout, predicate);
    168131    }
    169132
     
    208171   
    209172protected:
    210     template<typename LockType>
    211     bool waitForSecondsImpl(LockType& lock, double relativeTimeoutSeconds)
    212     {
    213         double relativeTimeoutNanoseconds = relativeTimeoutSeconds * (1000.0 * 1000.0 * 1000.0);
    214        
    215         if (!(relativeTimeoutNanoseconds > 0)) {
    216             // This handles insta-timeouts as well as NaN.
    217             lock.unlock();
    218             lock.lock();
    219             return false;
    220         }
    221 
    222         if (relativeTimeoutNanoseconds > static_cast<double>(std::numeric_limits<int64_t>::max())) {
    223             // If the timeout in nanoseconds cannot be expressed using a 64-bit integer, then we
    224             // might as well wait forever.
    225             wait(lock);
    226             return true;
    227         }
    228        
    229         auto relativeTimeout =
    230             std::chrono::nanoseconds(static_cast<int64_t>(relativeTimeoutNanoseconds));
    231 
    232         return waitForImpl(lock, relativeTimeout);
    233     }
    234    
    235     template<typename LockType, typename DurationType>
    236     bool waitForImpl(LockType& lock, const DurationType& relativeTimeout)
    237     {
    238         return waitUntil(lock, absoluteFromRelative(relativeTimeout));
    239     }
    240 
    241     template<typename DurationType>
    242     Clock::time_point absoluteFromRelative(const DurationType& relativeTimeout)
    243     {
    244         if (relativeTimeout < DurationType::zero())
    245             return Clock::time_point::min();
    246 
    247         if (relativeTimeout > Clock::duration::max()) {
    248             // This is highly unlikely. But if it happens, we want to not do anything dumb. Sleeping
    249             // without a timeout seems sensible when the timeout duration is greater than what can be
    250             // expressed using steady_clock.
    251             return Clock::time_point::max();
    252         }
    253        
    254         Clock::duration myRelativeTimeout =
    255             std::chrono::duration_cast<Clock::duration>(relativeTimeout);
    256 
    257         return Clock::now() + myRelativeTimeout;
    258     }
    259 
    260173    Atomic<bool> m_hasWaiters;
    261 };   
     174};
    262175
    263176class Condition : public ConditionBase {
  • trunk/Source/WTF/wtf/CrossThreadQueue.h

    r201518 r208415  
    7575            break;
    7676
    77         static const double infiniteTime = std::numeric_limits<double>::max();
    78         m_condition.waitUntilWallClockSeconds(m_lock, infiniteTime);
     77        m_condition.wait(m_lock);
    7978    }
    8079
  • trunk/Source/WTF/wtf/CurrentTime.cpp

    r198364 r208415  
    11/*
    2  * Copyright (C) 2006, 2008, 2009, 2010 Apple Inc. All rights reserved.
     2 * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
    33 * Copyright (C) 2008 Google Inc. All rights reserved.
    44 * Copyright (C) 2007-2009 Torch Mobile, Inc.
     
    341341    Condition fakeCondition;
    342342    LockHolder fakeLocker(fakeLock);
    343     fakeCondition.waitUntilMonotonicClockSeconds(fakeLock, monotonicallyIncreasingTime() + value);
     343    fakeCondition.waitFor(fakeLock, Seconds(value));
    344344}
    345345
  • trunk/Source/WTF/wtf/MessageQueue.h

    r194496 r208415  
    11/*
    2  * Copyright (C) 2008, 2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2008, 2015-2016 Apple Inc. All rights reserved.
    33 * Copyright (C) 2009 Google Inc. All rights reserved.
    44 *
     
    3838#include <wtf/Noncopyable.h>
    3939#include <wtf/Threading.h>
     40#include <wtf/WallTime.h>
    4041
    4142namespace WTF {
     
    6667        std::unique_ptr<DataType> tryGetMessageIgnoringKilled();
    6768        template<typename Predicate>
    68         std::unique_ptr<DataType> waitForMessageFilteredWithTimeout(MessageQueueWaitResult&, Predicate&&, double absoluteTime);
     69        std::unique_ptr<DataType> waitForMessageFilteredWithTimeout(MessageQueueWaitResult&, Predicate&&, WallTime absoluteTime);
    6970
    7071        template<typename Predicate>
     
    7677        // The result of isEmpty() is only valid if no other thread is manipulating the queue at the same time.
    7778        bool isEmpty();
    78 
    79         static double infiniteTime() { return std::numeric_limits<double>::max(); }
    8079
    8180    private:
     
    131130    {
    132131        MessageQueueWaitResult exitReason;
    133         std::unique_ptr<DataType> result = waitForMessageFilteredWithTimeout(exitReason, [](const DataType&) { return true; }, infiniteTime());
     132        std::unique_ptr<DataType> result = waitForMessageFilteredWithTimeout(exitReason, [](const DataType&) { return true; }, WallTime::infinity());
    134133        ASSERT(exitReason == MessageQueueTerminated || exitReason == MessageQueueMessageReceived);
    135134        return result;
     
    138137    template<typename DataType>
    139138    template<typename Predicate>
    140     inline auto MessageQueue<DataType>::waitForMessageFilteredWithTimeout(MessageQueueWaitResult& result, Predicate&& predicate, double absoluteTime) -> std::unique_ptr<DataType>
     139    inline auto MessageQueue<DataType>::waitForMessageFilteredWithTimeout(MessageQueueWaitResult& result, Predicate&& predicate, WallTime absoluteTime) -> std::unique_ptr<DataType>
    141140    {
    142141        LockHolder lock(m_mutex);
     
    152151                break;
    153152
    154             timedOut = !m_condition.waitUntilWallClockSeconds(m_mutex, absoluteTime);
    155         }
    156 
    157         ASSERT(!timedOut || absoluteTime != infiniteTime());
     153            timedOut = !m_condition.waitUntil(m_mutex, absoluteTime);
     154        }
     155
     156        ASSERT(!timedOut || absoluteTime != WallTime::infinity());
    158157
    159158        if (m_killed) {
  • trunk/Source/WTF/wtf/ParkingLot.cpp

    r208306 r208415  
    5555    ThreadIdentifier threadIdentifier;
    5656   
    57     std::mutex parkingLock;
    58     std::condition_variable parkingCondition;
     57    Mutex parkingLock;
     58    ThreadCondition parkingCondition;
    5959
    6060    const void* address { nullptr };
     
    565565    const ScopedLambda<bool()>& validation,
    566566    const ScopedLambda<void()>& beforeSleep,
    567     Clock::time_point timeout)
     567    const TimeWithDynamicClockType& timeout)
    568568{
    569569    if (verbose)
     
    593593    bool didGetDequeued;
    594594    {
    595         std::unique_lock<std::mutex> locker(me->parkingLock);
    596         while (me->address && Clock::now() < timeout) {
    597             // Falling back to wait() works around a bug in libstdc++ implementation of std::condition_variable. See:
    598             // - https://bugs.webkit.org/show_bug.cgi?id=148027
    599             // - https://gcc.gnu.org/bugzilla/show_bug.cgi?id=58931
    600             if (timeout == Clock::time_point::max())
    601                 me->parkingCondition.wait(locker);
    602             else
    603                 me->parkingCondition.wait_until(locker, timeout);
     595        MutexLocker locker(me->parkingLock);
     596        while (me->address && timeout.nowWithSameClock() < timeout) {
     597            me->parkingCondition.timedWait(
     598                me->parkingLock, timeout.approximateWallTime().secondsSinceEpoch().value());
    604599           
    605             // Because of the above, we do this thing, which is hilariously awful, but ensures that the worst case is
    606             // a CPU-eating spin but not a deadlock.
    607             locker.unlock();
    608             locker.lock();
     600            // It's possible for the OS to decide not to wait. If it does that then it will also
     601            // decide not to release the lock. If there's a bug in the time math, then this could
     602            // result in a deadlock. Flashing the lock means that at worst it's just a CPU-eating
     603            // spin.
     604            me->parkingLock.unlock();
     605            me->parkingLock.lock();
    609606        }
    610607        ASSERT(!me->address || me->address == address);
     
    641638    // Make sure that no matter what, me->address is null after this point.
    642639    {
    643         std::unique_lock<std::mutex> locker(me->parkingLock);
     640        MutexLocker locker(me->parkingLock);
    644641        if (!didDequeue) {
    645642            // If we did not dequeue ourselves, then someone else did. They will set our address to
     
    648645            // other things.
    649646            while (me->address)
    650                 me->parkingCondition.wait(locker);
     647                me->parkingCondition.wait(me->parkingLock);
    651648        }
    652649        me->address = nullptr;
     
    696693   
    697694    {
    698         std::unique_lock<std::mutex> locker(threadData->parkingLock);
     695        MutexLocker locker(threadData->parkingLock);
    699696        threadData->address = nullptr;
    700697        threadData->token = 0;
    701698    }
    702     threadData->parkingCondition.notify_one();
     699    threadData->parkingCondition.signal();
    703700
    704701    return result;
     
    742739   
    743740    {
    744         std::unique_lock<std::mutex> locker(threadData->parkingLock);
     741        MutexLocker locker(threadData->parkingLock);
    745742        threadData->address = nullptr;
    746743    }
    747744    // At this point, the threadData may die. Good thing we have a RefPtr<> on it.
    748     threadData->parkingCondition.notify_one();
     745    threadData->parkingCondition.signal();
    749746}
    750747
     
    780777        ASSERT(threadData->address);
    781778        {
    782             std::unique_lock<std::mutex> locker(threadData->parkingLock);
     779            MutexLocker locker(threadData->parkingLock);
    783780            threadData->address = nullptr;
    784781        }
    785         threadData->parkingCondition.notify_one();
     782        threadData->parkingCondition.signal();
    786783    }
    787784
  • trunk/Source/WTF/wtf/ParkingLot.h

    r208209 r208415  
    2727#define WTF_ParkingLot_h
    2828
    29 #include <chrono>
    3029#include <functional>
    3130#include <wtf/Atomics.h>
    3231#include <wtf/ScopedLambda.h>
    3332#include <wtf/Threading.h>
     33#include <wtf/TimeWithDynamicClockType.h>
    3434
    3535namespace WTF {
     
    4040
    4141public:
    42     typedef std::chrono::steady_clock Clock;
     42    // ParkingLot will accept any kind of time and convert it internally, but this typedef tells
     43    // you what kind of time ParkingLot would be able to use without conversions. It's sad that
     44    // this is WallTime not MonotonicTime, but that's just how OS wait functions work. However,
     45    // because ParkingLot evaluates whether it should wait by checking if your time has passed
     46    // using whatever clock you used, specifying timeouts in MonotonicTime is semantically better.
     47    // For example, if the user sets his computer's clock back during the time that you wanted to
     48    // wait for one second, and you specified the timeout using the MonotonicTime, then ParkingLot
     49    // will be smart enough to know that your one second has elapsed.
     50    typedef WallTime Time;
    4351   
    4452    // Parks the thread in a queue associated with the given address, which cannot be null. The
     
    6977        const ValidationFunctor& validation,
    7078        const BeforeSleepFunctor& beforeSleep,
    71         Clock::time_point timeout)
     79        const TimeWithDynamicClockType& timeout)
    7280    {
    7381        return parkConditionallyImpl(
     
    9098            },
    9199            [] () { },
    92             Clock::time_point::max());
     100            Time::infinity());
    93101    }
    94102
     
    159167        const ScopedLambda<bool()>& validation,
    160168        const ScopedLambda<void()>& beforeSleep,
    161         Clock::time_point timeout);
     169        const TimeWithDynamicClockType& timeout);
    162170   
    163171    WTF_EXPORT_PRIVATE static void unparkOneImpl(
  • trunk/Source/WTF/wtf/threads/BinarySemaphore.cpp

    r188002 r208415  
    11/*
    2  * Copyright (C) 2010 Apple Inc. All rights reserved.
     2 * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    4646}
    4747
    48 bool BinarySemaphore::wait(double absoluteTime)
     48bool BinarySemaphore::wait(TimeWithDynamicClockType absoluteTime)
    4949{
    5050    MutexLocker locker(m_mutex);
     
    5252    bool timedOut = false;
    5353    while (!m_isSet) {
    54         timedOut = !m_condition.timedWait(m_mutex, absoluteTime);
     54        timedOut = !m_condition.timedWait(
     55            m_mutex, absoluteTime.approximateWallTime().secondsSinceEpoch().value());
    5556        if (timedOut)
    5657            return false;
  • trunk/Source/WTF/wtf/threads/BinarySemaphore.h

    r188002 r208415  
    11/*
    2  * Copyright (C) 2010, 2011 Apple Inc. All rights reserved.
     2 * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2929#include <wtf/Noncopyable.h>
    3030#include <wtf/ThreadingPrimitives.h>
     31#include <wtf/TimeWithDynamicClockType.h>
    3132
    3233namespace WTF {
     
    4041
    4142    WTF_EXPORT_PRIVATE void signal();
    42     WTF_EXPORT_PRIVATE bool wait(double absoluteTime);
     43    WTF_EXPORT_PRIVATE bool wait(TimeWithDynamicClockType);
    4344
    4445private:
  • trunk/Source/WebCore/ChangeLog

    r208414 r208415  
     12016-11-04  Filip Pizlo  <fpizlo@apple.com>
     2
     3        WTF::ParkingLot should stop using std::chrono because std::chrono::duration casts are prone to overflows
     4        https://bugs.webkit.org/show_bug.cgi?id=152045
     5
     6        Reviewed by Andy Estes.
     7
     8        No new layout tests because no new behavior. The new WTF time classes have some unit tests
     9        in TestWebKitAPI.
     10
     11        * fileapi/ThreadableBlobRegistry.cpp:
     12        (WebCore::ThreadableBlobRegistry::blobSize):
     13        * platform/MainThreadSharedTimer.h:
     14        * platform/SharedTimer.h:
     15        * platform/ThreadTimers.cpp:
     16        (WebCore::ThreadTimers::updateSharedTimer):
     17        * platform/cf/MainThreadSharedTimerCF.cpp:
     18        (WebCore::MainThreadSharedTimer::setFireInterval):
     19        * platform/efl/MainThreadSharedTimerEfl.cpp:
     20        (WebCore::MainThreadSharedTimer::setFireInterval):
     21        * platform/glib/MainThreadSharedTimerGLib.cpp:
     22        (WebCore::MainThreadSharedTimer::setFireInterval):
     23        * platform/win/MainThreadSharedTimerWin.cpp:
     24        (WebCore::MainThreadSharedTimer::setFireInterval):
     25        * workers/WorkerRunLoop.cpp:
     26        (WebCore::WorkerRunLoop::runInMode):
     27
    1282016-11-04  Zalan Bujtas  <zalan@apple.com>
    229
  • trunk/Source/WebCore/fileapi/ThreadableBlobRegistry.cpp

    r204466 r208415  
    151151            semaphore.signal();
    152152        });
    153         semaphore.wait(std::numeric_limits<double>::max());
     153        semaphore.wait(WallTime::infinity());
    154154    }
    155155    return resultSize;
  • trunk/Source/WebCore/platform/MainThreadSharedTimer.h

    r202611 r208415  
    11/*
    22 * Copyright (C) 2015 Igalia S.L.
    3  * Copyright (C) 2006 Apple Inc.  All rights reserved.
     3 * Copyright (C) 2006-2016 Apple Inc.  All rights reserved.
    44 *
    55 * Redistribution and use in source and binary forms, with or without
     
    4343
    4444    void setFiredFunction(std::function<void()>&&) override;
    45     void setFireInterval(double) override;
     45    void setFireInterval(Seconds) override;
    4646    void stop() override;
    4747    void invalidate() override;
  • trunk/Source/WebCore/platform/SharedTimer.h

    r191789 r208415  
    11/*
    2  * Copyright (C) 2006 Apple Inc.  All rights reserved.
     2 * Copyright (C) 2006-2016 Apple Inc.  All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    3030#include <wtf/FastMalloc.h>
    3131#include <wtf/Noncopyable.h>
     32#include <wtf/Seconds.h>
    3233
    3334namespace WebCore {
     
    4445
    4546    // The fire interval is in seconds relative to the current monotonic clock time.
    46     virtual void setFireInterval(double) = 0;
     47    virtual void setFireInterval(Seconds) = 0;
    4748    virtual void stop() = 0;
    4849
  • trunk/Source/WebCore/platform/ThreadTimers.cpp

    r191789 r208415  
    11/*
    2  * Copyright (C) 2006, 2008 Apple Inc. All rights reserved.
     2 * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
    33 * Copyright (C) 2009 Google Inc. All rights reserved.
    44 *
     
    9393        }
    9494        m_pendingSharedTimerFireTime = nextFireTime;
    95         m_sharedTimer->setFireInterval(std::max(nextFireTime - currentMonotonicTime, 0.0));
     95        m_sharedTimer->setFireInterval(Seconds(std::max(nextFireTime - currentMonotonicTime, 0.0)));
    9696    }
    9797}
  • trunk/Source/WebCore/platform/cf/MainThreadSharedTimerCF.cpp

    r191789 r208415  
    11/*
    2  * Copyright (C) 2006, 2010, 2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2006-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    9494}
    9595
    96 void MainThreadSharedTimer::setFireInterval(double interval)
     96void MainThreadSharedTimer::setFireInterval(Seconds interval)
    9797{
    9898    ASSERT(m_firedFunction);
    9999
    100     CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent() + interval;
     100    CFAbsoluteTime fireDate = CFAbsoluteTimeGetCurrent() + interval.value();
    101101    if (!sharedTimer) {
    102102        sharedTimer = CFRunLoopTimerCreate(nullptr, fireDate, kCFTimeIntervalDistantFuture, 0, 0, timerFired, nullptr);
  • trunk/Source/WebCore/platform/efl/MainThreadSharedTimerEfl.cpp

    r191789 r208415  
    44 *           (C) 2009-2010 ProFUSION embedded systems
    55 *           (C) 2009-2010 Samsung Electronics
     6 * Copyright (C) 2016 Apple Inc. All rights reserved.
    67 *
    78 * Redistribution and use in source and binary forms, with or without
     
    5455}
    5556
    56 void MainThreadSharedTimer::setFireInterval(double interval)
     57void MainThreadSharedTimer::setFireInterval(Seconds interval)
    5758{
    5859    stop();
    59     sharedTimer = ecore_timer_loop_add(interval, timerEvent, nullptr);
     60    sharedTimer = ecore_timer_loop_add(interval.value(), timerEvent, nullptr);
    6061}
    6162
  • trunk/Source/WebCore/platform/glib/MainThreadSharedTimerGLib.cpp

    r202611 r208415  
    11/*
    2  * Copyright (C) 2006 Apple Inc.  All rights reserved.
     2 * Copyright (C) 2006-2016 Apple Inc.  All rights reserved.
    33 * Copyright (C) 2006 Michael Emmel mike.emmel@gmail.com
    44 * All rights reserved.
     
    4040}
    4141
    42 void MainThreadSharedTimer::setFireInterval(double interval)
     42void MainThreadSharedTimer::setFireInterval(Seconds interval)
    4343{
    4444    ASSERT(m_firedFunction);
    45     m_timer.startOneShot(interval);
     45    m_timer.startOneShot(interval.value());
    4646}
    4747
  • trunk/Source/WebCore/platform/win/MainThreadSharedTimerWin.cpp

    r191789 r208415  
    11/*
    2  * Copyright (C) 2006 Apple Inc.  All rights reserved.
     2 * Copyright (C) 2006-2016 Apple Inc.  All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    122122}
    123123
    124 void MainThreadSharedTimer::setFireInterval(double interval)
     124void MainThreadSharedTimer::setFireInterval(Seconds intervalInSeconds)
    125125{
    126126    ASSERT(m_firedFunction);
    127127
     128    double interval = intervalInSeconds.milliseconds();
    128129    unsigned intervalInMS;
    129     interval *= 1000;
    130130    if (interval > USER_TIMER_MAXIMUM)
    131131        intervalInMS = USER_TIMER_MAXIMUM;
  • trunk/Source/WebCore/workers/WorkerRunLoop.cpp

    r208306 r208415  
    11/*
    22 * Copyright (C) 2009 Google Inc. All rights reserved.
     3 * Copyright (C) 2016 Apple Inc.  All rights reserved.
    34 *
    45 * Redistribution and use in source and binary forms, with or without
     
    5051    // SharedTimer interface.
    5152    void setFiredFunction(std::function<void()>&& function) override { m_sharedTimerFunction = WTFMove(function); }
    52     void setFireInterval(double interval) override { m_nextFireTime = interval + currentTime(); }
    53     void stop() override { m_nextFireTime = 0; }
     53    void setFireInterval(Seconds interval) override { m_nextFireTime = interval + WallTime::now(); }
     54    void stop() override { m_nextFireTime = WallTime(); }
    5455
    5556    bool isActive() { return m_sharedTimerFunction && m_nextFireTime; }
    56     double fireTime() { return m_nextFireTime; }
     57    WallTime fireTime() { return m_nextFireTime; }
    5758    void fire() { m_sharedTimerFunction(); }
    5859
    5960private:
    6061    std::function<void()> m_sharedTimerFunction;
    61     double m_nextFireTime { 0 };
     62    WallTime m_nextFireTime;
    6263};
    6364
     
    158159#endif
    159160
    160     double deadline = MessageQueue<Task>::infiniteTime();
     161    WallTime deadline = WallTime::infinity();
    161162
    162163#if USE(CF)
    163164    CFAbsoluteTime nextCFRunLoopTimerFireDate = CFRunLoopGetNextTimerFireDate(CFRunLoopGetCurrent(), kCFRunLoopDefaultMode);
    164165    double timeUntilNextCFRunLoopTimerInSeconds = nextCFRunLoopTimerFireDate - CFAbsoluteTimeGetCurrent();
    165     deadline = currentTime() + std::max(0.0, timeUntilNextCFRunLoopTimerInSeconds);
    166 #endif
    167 
    168     double absoluteTime = 0.0;
     166    deadline = WallTime::now() + std::max(
     167        Seconds(0), Seconds(timeUntilNextCFRunLoopTimerInSeconds));
     168#endif
     169
     170    WallTime absoluteTime;
    169171    if (waitMode == WaitForMessage) {
    170172        if (predicate.isDefaultMode() && m_sharedTimer->isActive())
  • trunk/Source/WebKit2/ChangeLog

    r208406 r208415  
     12016-11-04  Filip Pizlo  <fpizlo@apple.com>
     2
     3        WTF::ParkingLot should stop using std::chrono because std::chrono::duration casts are prone to overflows
     4        https://bugs.webkit.org/show_bug.cgi?id=152045
     5
     6        Reviewed by Andy Estes.
     7
     8        * Platform/IPC/Connection.cpp:
     9        (IPC::Connection::SyncMessageState::wait):
     10        (IPC::Connection::sendMessage):
     11        (IPC::Connection::timeoutRespectingIgnoreTimeoutsForTesting):
     12        (IPC::Connection::waitForMessage):
     13        (IPC::Connection::sendSyncMessage):
     14        (IPC::Connection::waitForSyncReply):
     15        * Platform/IPC/Connection.h:
     16        (IPC::Connection::sendSync):
     17        (IPC::Connection::waitForAndDispatchImmediately):
     18        * Platform/IPC/MessageSender.h:
     19        (IPC::MessageSender::sendSync):
     20        * UIProcess/ChildProcessProxy.h:
     21        (WebKit::ChildProcessProxy::sendSync):
     22        * UIProcess/Network/NetworkProcessProxy.cpp:
     23        (WebKit::NetworkProcessProxy::sendProcessWillSuspendImminently):
     24        * UIProcess/Storage/StorageManager.cpp:
     25        (WebKit::StorageManager::applicationWillTerminate):
     26        * UIProcess/WebProcessProxy.cpp:
     27        (WebKit::WebProcessProxy::sendProcessWillSuspendImminently):
     28        * UIProcess/WebResourceLoadStatisticsStore.cpp:
     29        (WebKit::WebResourceLoadStatisticsStore::applicationWillTerminate):
     30        * UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.h:
     31        * UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.mm:
     32        (-[WKOneShotDisplayLinkHandler displayLinkFired:]):
     33        (WebKit::RemoteLayerTreeDrawingAreaProxy::commitLayerTree):
     34        (WebKit::RemoteLayerTreeDrawingAreaProxy::didRefreshDisplay):
     35        (WebKit::RemoteLayerTreeDrawingAreaProxy::waitForDidUpdateActivityState):
     36        * UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm:
     37        (WebKit::TiledCoreAnimationDrawingAreaProxy::waitForDidUpdateActivityState):
     38        * UIProcess/mac/WKImmediateActionController.mm:
     39        (-[WKImmediateActionController immediateActionRecognizerWillBeginAnimation:]):
     40        * UIProcess/mac/WebPageProxyMac.mm:
     41        (WebKit::WebPageProxy::stringSelectionForPasteboard):
     42        (WebKit::WebPageProxy::dataSelectionForPasteboard):
     43        (WebKit::WebPageProxy::readSelectionFromPasteboard):
     44        (WebKit::WebPageProxy::shouldDelayWindowOrderingForEvent):
     45        (WebKit::WebPageProxy::acceptsFirstMouse):
     46        * WebProcess/WebCoreSupport/WebChromeClient.cpp:
     47        (WebKit::WebChromeClient::runBeforeUnloadConfirmPanel):
     48        (WebKit::WebChromeClient::runJavaScriptAlert):
     49        (WebKit::WebChromeClient::runJavaScriptConfirm):
     50        (WebKit::WebChromeClient::runJavaScriptPrompt):
     51        (WebKit::WebChromeClient::print):
     52        (WebKit::WebChromeClient::exceededDatabaseQuota):
     53        (WebKit::WebChromeClient::reachedApplicationCacheOriginQuota):
     54        * WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp:
     55        (WebKit::WebFrameLoaderClient::dispatchDecidePolicyForResponse):
     56        * WebProcess/WebPage/WebPage.cpp:
     57        (WebKit::WebPage::postSynchronousMessageForTesting):
     58
    1592016-11-04  Wenson Hsieh  <wenson_hsieh@apple.com>
    260
  • trunk/Source/WebKit2/Platform/IPC/Connection.cpp

    r205275 r208415  
    11/*
    2  * Copyright (C) 2010 Apple Inc. All rights reserved.
     2 * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    7474    }
    7575
    76     bool wait(double absoluteTime)
     76    bool wait(TimeWithDynamicClockType absoluteTime)
    7777    {
    7878        return m_waitForSyncReplySemaphore.wait(absoluteTime);
     
    377377        wrappedMessage->setFullySynchronousModeForTesting();
    378378        wrappedMessage->wrapForTesting(WTFMove(encoder));
    379         return static_cast<bool>(sendSyncMessage(syncRequestID, WTFMove(wrappedMessage), std::chrono::milliseconds::max(), { }));
     379        return static_cast<bool>(sendSyncMessage(syncRequestID, WTFMove(wrappedMessage), Seconds::infinity(), { }));
    380380    }
    381381
     
    421421}
    422422
    423 std::chrono::milliseconds Connection::timeoutRespectingIgnoreTimeoutsForTesting(std::chrono::milliseconds timeout) const
    424 {
    425     return m_ignoreTimeoutsForTesting ? std::chrono::milliseconds::max() : timeout;
    426 }
    427 
    428 std::unique_ptr<Decoder> Connection::waitForMessage(StringReference messageReceiverName, StringReference messageName, uint64_t destinationID, std::chrono::milliseconds timeout, OptionSet<WaitForOption> waitForOptions)
     423Seconds Connection::timeoutRespectingIgnoreTimeoutsForTesting(Seconds timeout) const
     424{
     425    return m_ignoreTimeoutsForTesting ? Seconds::infinity() : timeout;
     426}
     427
     428std::unique_ptr<Decoder> Connection::waitForMessage(StringReference messageReceiverName, StringReference messageName, uint64_t destinationID, Seconds timeout, OptionSet<WaitForOption> waitForOptions)
    429429{
    430430    ASSERT(RunLoop::isMain());
     
    470470    }
    471471
    472     // Clamp the timeout to however much time is remaining on our clock.
    473     auto now = Condition::Clock::now();
    474     auto remainingClockTime = std::chrono::duration_cast<std::chrono::milliseconds>(Condition::Clock::time_point::max() - now);
    475     auto absoluteTimeout = now + std::min(remainingClockTime, timeout);
     472    MonotonicTime absoluteTimeout = MonotonicTime::now() + timeout;
    476473
    477474    // Now wait for it to be set.
     
    497494}
    498495
    499 std::unique_ptr<Decoder> Connection::sendSyncMessage(uint64_t syncRequestID, std::unique_ptr<Encoder> encoder, std::chrono::milliseconds timeout, OptionSet<SendSyncOption> sendSyncOptions)
     496std::unique_ptr<Decoder> Connection::sendSyncMessage(uint64_t syncRequestID, std::unique_ptr<Encoder> encoder, Seconds timeout, OptionSet<SendSyncOption> sendSyncOptions)
    500497{
    501498    ASSERT(RunLoop::isMain());
     
    542539}
    543540
    544 std::unique_ptr<Decoder> Connection::waitForSyncReply(uint64_t syncRequestID, std::chrono::milliseconds timeout, OptionSet<SendSyncOption> sendSyncOptions)
     541std::unique_ptr<Decoder> Connection::waitForSyncReply(uint64_t syncRequestID, Seconds timeout, OptionSet<SendSyncOption> sendSyncOptions)
    545542{
    546543    timeout = timeoutRespectingIgnoreTimeoutsForTesting(timeout);
    547     double absoluteTime = currentTime() + (timeout.count() / 1000.0);
     544    WallTime absoluteTime = WallTime::now() + timeout;
    548545
    549546    willSendSyncMessage(sendSyncOptions);
  • trunk/Source/WebKit2/Platform/IPC/Connection.h

    r205207 r208415  
    11/*
    2  * Copyright (C) 2010 Apple Inc. All rights reserved.
     2 * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
    33 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies)
    44 * Portions Copyright (c) 2010 Motorola Mobility, Inc.  All rights reserved.
     
    167167    template<typename T> bool send(T&& message, uint64_t destinationID, OptionSet<SendOption> sendOptions = { });
    168168    template<typename T> void sendWithReply(T&& message, uint64_t destinationID, FunctionDispatcher& replyDispatcher, Function<void (Optional<typename CodingType<typename T::Reply>::Type>)>&& replyHandler);
    169     template<typename T> bool sendSync(T&& message, typename T::Reply&& reply, uint64_t destinationID, std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), OptionSet<SendSyncOption> sendSyncOptions = { });
    170     template<typename T> bool waitForAndDispatchImmediately(uint64_t destinationID, std::chrono::milliseconds timeout, OptionSet<WaitForOption> waitForOptions = { });
     169    template<typename T> bool sendSync(T&& message, typename T::Reply&& reply, uint64_t destinationID, Seconds timeout = Seconds::infinity(), OptionSet<SendSyncOption> sendSyncOptions = { });
     170    template<typename T> bool waitForAndDispatchImmediately(uint64_t destinationID, Seconds timeout, OptionSet<WaitForOption> waitForOptions = { });
    171171
    172172    bool sendMessage(std::unique_ptr<Encoder>, OptionSet<SendOption> sendOptions);
    173173    void sendMessageWithReply(uint64_t requestID, std::unique_ptr<Encoder>, FunctionDispatcher& replyDispatcher, Function<void (std::unique_ptr<Decoder>)>&& replyHandler);
    174174    std::unique_ptr<Encoder> createSyncMessageEncoder(StringReference messageReceiverName, StringReference messageName, uint64_t destinationID, uint64_t& syncRequestID);
    175     std::unique_ptr<Decoder> sendSyncMessage(uint64_t syncRequestID, std::unique_ptr<Encoder>, std::chrono::milliseconds timeout, OptionSet<SendSyncOption> sendSyncOptions);
     175    std::unique_ptr<Decoder> sendSyncMessage(uint64_t syncRequestID, std::unique_ptr<Encoder>, Seconds timeout, OptionSet<SendSyncOption> sendSyncOptions);
    176176    bool sendSyncReply(std::unique_ptr<Encoder>);
    177177
     
    209209    void platformInvalidate();
    210210   
    211     std::unique_ptr<Decoder> waitForMessage(StringReference messageReceiverName, StringReference messageName, uint64_t destinationID, std::chrono::milliseconds timeout, OptionSet<WaitForOption>);
    212    
    213     std::unique_ptr<Decoder> waitForSyncReply(uint64_t syncRequestID, std::chrono::milliseconds timeout, OptionSet<SendSyncOption>);
     211    std::unique_ptr<Decoder> waitForMessage(StringReference messageReceiverName, StringReference messageName, uint64_t destinationID, Seconds timeout, OptionSet<WaitForOption>);
     212   
     213    std::unique_ptr<Decoder> waitForSyncReply(uint64_t syncRequestID, Seconds timeout, OptionSet<SendSyncOption>);
    214214
    215215    // Called on the connection work queue.
     
    239239    void didReceiveSyncReply(OptionSet<SendSyncOption>);
    240240
    241     std::chrono::milliseconds timeoutRespectingIgnoreTimeoutsForTesting(std::chrono::milliseconds) const;
     241    Seconds timeoutRespectingIgnoreTimeoutsForTesting(Seconds) const;
    242242   
    243243    Client& m_client;
     
    366366}
    367367
    368 template<typename T> bool Connection::sendSync(T&& message, typename T::Reply&& reply, uint64_t destinationID, std::chrono::milliseconds timeout, OptionSet<SendSyncOption> sendSyncOptions)
     368template<typename T> bool Connection::sendSync(T&& message, typename T::Reply&& reply, uint64_t destinationID, Seconds timeout, OptionSet<SendSyncOption> sendSyncOptions)
    369369{
    370370    COMPILE_ASSERT(T::isSync, SyncMessageExpected);
     
    390390}
    391391
    392 template<typename T> bool Connection::waitForAndDispatchImmediately(uint64_t destinationID, std::chrono::milliseconds timeout, OptionSet<WaitForOption> waitForOptions)
     392template<typename T> bool Connection::waitForAndDispatchImmediately(uint64_t destinationID, Seconds timeout, OptionSet<WaitForOption> waitForOptions)
    393393{
    394394    std::unique_ptr<Decoder> decoder = waitForMessage(T::receiverName(), T::name(), destinationID, timeout, waitForOptions);
  • trunk/Source/WebKit2/Platform/IPC/MessageSender.h

    r204996 r208415  
    11/*
    2  * Copyright (C) 2010 Apple Inc. All rights reserved.
     2 * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    5151
    5252    template<typename T>
    53     bool sendSync(T&& message, typename T::Reply&& reply, std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), OptionSet<SendSyncOption> sendSyncOptions = { })
     53    bool sendSync(T&& message, typename T::Reply&& reply, Seconds timeout = Seconds::infinity(), OptionSet<SendSyncOption> sendSyncOptions = { })
    5454    {
    5555        static_assert(T::isSync, "Message is not sync!");
     
    5959
    6060    template<typename T>
    61     bool sendSync(T&& message, typename T::Reply&& reply, uint64_t destinationID, std::chrono::milliseconds timeout = std::chrono::milliseconds::max(), OptionSet<SendSyncOption> sendSyncOptions = { })
     61    bool sendSync(T&& message, typename T::Reply&& reply, uint64_t destinationID, Seconds timeout = Seconds::infinity(), OptionSet<SendSyncOption> sendSyncOptions = { })
    6262    {
    6363        ASSERT(messageSenderConnection());
  • trunk/Source/WebKit2/UIProcess/AcceleratedDrawingAreaProxy.cpp

    r207658 r208415  
    237237
    238238    // The timeout, in seconds, we use when waiting for a DidUpdateBackingStoreState message when we're asked to paint.
    239     m_webPageProxy.process().connection()->waitForAndDispatchImmediately<Messages::DrawingAreaProxy::DidUpdateBackingStoreState>(m_webPageProxy.pageID(), std::chrono::milliseconds(500));
     239    m_webPageProxy.process().connection()->waitForAndDispatchImmediately<Messages::DrawingAreaProxy::DidUpdateBackingStoreState>(m_webPageProxy.pageID(), Seconds::fromMilliseconds(500));
    240240}
    241241
  • trunk/Source/WebKit2/UIProcess/ChildProcessProxy.h

    r205159 r208415  
    11/*
    2  * Copyright (C) 2012 Apple Inc. All rights reserved.
     2 * Copyright (C) 2012-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    4545
    4646    template<typename T> bool send(T&& message, uint64_t destinationID, OptionSet<IPC::SendOption> sendOptions = { });
    47     template<typename T> bool sendSync(T&& message, typename T::Reply&&, uint64_t destinationID, std::chrono::milliseconds timeout = std::chrono::seconds(1), OptionSet<IPC::SendSyncOption> sendSyncOptions = { });
     47    template<typename T> bool sendSync(T&& message, typename T::Reply&&, uint64_t destinationID, Seconds timeout = Seconds(1), OptionSet<IPC::SendSyncOption> sendSyncOptions = { });
    4848
    4949    IPC::Connection* connection() const
     
    103103
    104104template<typename U>
    105 bool ChildProcessProxy::sendSync(U&& message, typename U::Reply&& reply, uint64_t destinationID, std::chrono::milliseconds timeout, OptionSet<IPC::SendSyncOption> sendSyncOptions)
     105bool ChildProcessProxy::sendSync(U&& message, typename U::Reply&& reply, uint64_t destinationID, Seconds timeout, OptionSet<IPC::SendSyncOption> sendSyncOptions)
    106106{
    107107    COMPILE_ASSERT(U::isSync, SyncMessageExpected);
  • trunk/Source/WebKit2/UIProcess/DrawingAreaProxy.h

    r208225 r208415  
    7272
    7373    // The timeout we use when waiting for a DidUpdateGeometry message.
    74     static constexpr std::chrono::milliseconds didUpdateBackingStoreStateTimeout() { return std::chrono::milliseconds(500); }
     74    static constexpr Seconds didUpdateBackingStoreStateTimeout() { return Seconds::fromMilliseconds(500); }
    7575
    76     virtual void waitForPossibleGeometryUpdate(std::chrono::milliseconds = didUpdateBackingStoreStateTimeout()) { }
     76    virtual void waitForPossibleGeometryUpdate(Seconds = didUpdateBackingStoreStateTimeout()) { }
    7777
    7878    virtual void colorSpaceDidChange() { }
  • trunk/Source/WebKit2/UIProcess/Network/NetworkProcessProxy.cpp

    r207346 r208415  
    11/*
    2  * Copyright (C) 2012 Apple Inc. All rights reserved.
     2 * Copyright (C) 2012-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    370370
    371371    bool handled = false;
    372     sendSync(Messages::NetworkProcess::ProcessWillSuspendImminently(), Messages::NetworkProcess::ProcessWillSuspendImminently::Reply(handled), 0, std::chrono::seconds(1));
     372    sendSync(Messages::NetworkProcess::ProcessWillSuspendImminently(), Messages::NetworkProcess::ProcessWillSuspendImminently::Reply(handled), 0, Seconds(1));
    373373}
    374374   
  • trunk/Source/WebKit2/UIProcess/Storage/StorageManager.cpp

    r203303 r208415  
    11/*
    2  * Copyright (C) 2013 Apple Inc. All rights reserved.
     2 * Copyright (C) 2013-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    844844        semaphore.signal();
    845845    });
    846     semaphore.wait(std::numeric_limits<double>::max());
     846    semaphore.wait(WallTime::infinity());
    847847}
    848848
  • trunk/Source/WebKit2/UIProcess/WebProcessProxy.cpp

    r208225 r208415  
    907907
    908908    bool handled = false;
    909     sendSync(Messages::WebProcess::ProcessWillSuspendImminently(), Messages::WebProcess::ProcessWillSuspendImminently::Reply(handled), 0, std::chrono::seconds(1));
     909    sendSync(Messages::WebProcess::ProcessWillSuspendImminently(), Messages::WebProcess::ProcessWillSuspendImminently::Reply(handled), 0, Seconds(1));
    910910}
    911911
  • trunk/Source/WebKit2/UIProcess/WebResourceLoadStatisticsStore.cpp

    r206869 r208415  
    214214        semaphore.signal();
    215215    });
    216     semaphore.wait(std::numeric_limits<double>::max());
     216    semaphore.wait(WallTime::infinity());
    217217}
    218218
  • trunk/Source/WebKit2/UIProcess/ios/WKContentView.mm

    r208371 r208415  
    679679{
    680680    if (_isPrintingToPDF) {
    681         if (!_page->process().connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DrawToPDFCallback>(_page->pageID(), std::chrono::milliseconds::max())) {
     681        if (!_page->process().connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DrawToPDFCallback>(_page->pageID(), Seconds::infinity())) {
    682682            ASSERT_NOT_REACHED();
    683683            return nullptr;
  • trunk/Source/WebKit2/UIProcess/ios/WebPageProxyIOS.mm

    r208361 r208415  
    296296        FloatPoint newScrollPosition;
    297297        uint64_t nextValidLayerTreeTransactionID;
    298         if (m_process->sendSync(Messages::WebPage::SynchronizeDynamicViewportUpdate(), Messages::WebPage::SynchronizeDynamicViewportUpdate::Reply(newScale, newScrollPosition, nextValidLayerTreeTransactionID), m_pageID, std::chrono::seconds(2))) {
     298        if (m_process->sendSync(Messages::WebPage::SynchronizeDynamicViewportUpdate(), Messages::WebPage::SynchronizeDynamicViewportUpdate::Reply(newScale, newScrollPosition, nextValidLayerTreeTransactionID), m_pageID, Seconds(2))) {
    299299            m_dynamicViewportSizeUpdateWaitingForTarget = false;
    300300            m_dynamicViewportSizeUpdateLayerTreeTransactionID = nextValidLayerTreeTransactionID;
  • trunk/Source/WebKit2/UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.h

    r208225 r208415  
    11/*
    2  * Copyright (C) 2012-2014 Apple Inc. All rights reserved.
     2 * Copyright (C) 2012-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    5353    uint64_t lastCommittedLayerTreeTransactionID() const { return m_transactionIDForPendingCACommit; }
    5454
    55     void didRefreshDisplay(double timestamp);
     55    void didRefreshDisplay();
    5656
    5757private:
  • trunk/Source/WebKit2/UIProcess/mac/RemoteLayerTreeDrawingAreaProxy.mm

    r208395 r208415  
    11/*
    2  * Copyright (C) 2012-2014 Apple Inc. All rights reserved.
     2 * Copyright (C) 2012-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    8282{
    8383    ASSERT(isUIThread());
    84     _drawingAreaProxy->didRefreshDisplay(sender.timestamp);
     84    _drawingAreaProxy->didRefreshDisplay();
    8585}
    8686
     
    229229#if PLATFORM(IOS)
    230230    if (std::exchange(m_didUpdateMessageState, NeedsDidUpdate) == MissedCommit)
    231         didRefreshDisplay(monotonicallyIncreasingTime());
     231        didRefreshDisplay();
    232232    [m_displayLinkHandler schedule];
    233233#else
    234234    m_didUpdateMessageState = NeedsDidUpdate;
    235     didRefreshDisplay(monotonicallyIncreasingTime());
     235    didRefreshDisplay();
    236236#endif
    237237
     
    395395}
    396396
    397 void RemoteLayerTreeDrawingAreaProxy::didRefreshDisplay(double)
     397void RemoteLayerTreeDrawingAreaProxy::didRefreshDisplay()
    398398{
    399399    if (!m_webPageProxy.isValid())
     
    427427    // we can be guaranteed that the next commit won't come until after the waitForAndDispatchImmediately times out.
    428428    if (m_didUpdateMessageState != DoesNotNeedDidUpdate)
    429         didRefreshDisplay(monotonicallyIncreasingTime());
    430 
    431     static std::chrono::milliseconds activityStateUpdateTimeout = [] {
     429        didRefreshDisplay();
     430
     431    static Seconds activityStateUpdateTimeout = [] {
    432432        if (id value = [[NSUserDefaults standardUserDefaults] objectForKey:@"WebKitOverrideActivityStateUpdateTimeout"])
    433             return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::duration<double>([value doubleValue]));
    434 
    435 #if PLATFORM(IOS)
    436         return std::chrono::milliseconds(500);
     433            return Seconds([value doubleValue]);
     434
     435#if PLATFORM(IOS)
     436        return Seconds::fromMilliseconds(500);
    437437#else
    438         return std::chrono::milliseconds(250);
     438        return Seconds::fromMilliseconds(250);
    439439#endif
    440440    }();
  • trunk/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.h

    r208225 r208415  
    4242    void deviceScaleFactorDidChange() override;
    4343    void sizeDidChange() override;
    44     void waitForPossibleGeometryUpdate(std::chrono::milliseconds timeout = didUpdateBackingStoreStateTimeout()) override;
     44    void waitForPossibleGeometryUpdate(Seconds timeout = didUpdateBackingStoreStateTimeout()) override;
    4545    void colorSpaceDidChange() override;
    4646    void minimumLayoutSizeDidChange() override;
  • trunk/Source/WebKit2/UIProcess/mac/TiledCoreAnimationDrawingAreaProxy.mm

    r208225 r208415  
    11/*
    2  * Copyright (C) 2011 Apple Inc. All rights reserved.
     2 * Copyright (C) 2011-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    7171}
    7272
    73 void TiledCoreAnimationDrawingAreaProxy::waitForPossibleGeometryUpdate(std::chrono::milliseconds timeout)
     73void TiledCoreAnimationDrawingAreaProxy::waitForPossibleGeometryUpdate(Seconds timeout)
    7474{
    7575#if !HAVE(COREANIMATION_FENCES)
     
    134134void TiledCoreAnimationDrawingAreaProxy::waitForDidUpdateActivityState()
    135135{
    136     auto activityStateUpdateTimeout = std::chrono::milliseconds(250);
     136    Seconds activityStateUpdateTimeout = Seconds::fromMilliseconds(250);
    137137    m_webPageProxy.process().connection()->waitForAndDispatchImmediately<Messages::WebPageProxy::DidUpdateActivityState>(m_webPageProxy.pageID(), activityStateUpdateTimeout, IPC::WaitForOption::InterruptWaitingIfSyncMessageArrives);
    138138}
  • trunk/Source/WebKit2/UIProcess/mac/WKImmediateActionController.mm

    r208342 r208415  
    11/*
    2  * Copyright (C) 2014 Apple Inc. All rights reserved.
     2 * Copyright (C) 2014-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    197197    if (_state == ImmediateActionState::Pending) {
    198198        if (auto* connection = _page->process().connection()) {
    199             bool receivedReply = connection->waitForAndDispatchImmediately<Messages::WebPageProxy::DidPerformImmediateActionHitTest>(_page->pageID(), std::chrono::milliseconds(500));
     199            bool receivedReply = connection->waitForAndDispatchImmediately<Messages::WebPageProxy::DidPerformImmediateActionHitTest>(_page->pageID(), Seconds::fromMilliseconds(500));
    200200            if (!receivedReply)
    201201                _state = ImmediateActionState::TimedOut;
  • trunk/Source/WebKit2/UIProcess/mac/WebPageProxyMac.mm

    r208361 r208415  
    11/*
    2  * Copyright (C) 2010, 2011, 2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    231231        return value;
    232232   
    233     const auto messageTimeout = std::chrono::seconds(20);
     233    const Seconds messageTimeout(20);
    234234    process().sendSync(Messages::WebPage::GetStringSelectionForPasteboard(), Messages::WebPage::GetStringSelectionForPasteboard::Reply(value), m_pageID, messageTimeout);
    235235    return value;
     
    242242    SharedMemory::Handle handle;
    243243    uint64_t size = 0;
    244     const auto messageTimeout = std::chrono::seconds(20);
     244    const Seconds messageTimeout(20);
    245245    process().sendSync(Messages::WebPage::GetDataSelectionForPasteboard(pasteboardType),
    246246                                                Messages::WebPage::GetDataSelectionForPasteboard::Reply(handle, size), m_pageID, messageTimeout);
     
    257257
    258258    bool result = false;
    259     const auto messageTimeout = std::chrono::seconds(20);
     259    const Seconds messageTimeout(20);
    260260    process().sendSync(Messages::WebPage::ReadSelectionFromPasteboard(pasteboardName), Messages::WebPage::ReadSelectionFromPasteboard::Reply(result), m_pageID, messageTimeout);
    261261    return result;
     
    410410
    411411    bool result = false;
    412     const auto messageTimeout = std::chrono::seconds(3);
     412    const Seconds messageTimeout(3);
    413413    process().sendSync(Messages::WebPage::ShouldDelayWindowOrderingEvent(event), Messages::WebPage::ShouldDelayWindowOrderingEvent::Reply(result), m_pageID, messageTimeout);
    414414    return result;
     
    421421
    422422    bool result = false;
    423     const auto messageTimeout = std::chrono::seconds(3);
     423    const Seconds messageTimeout(3);
    424424    process().sendSync(Messages::WebPage::AcceptsFirstMouse(eventNumber, event), Messages::WebPage::AcceptsFirstMouse::Reply(result), m_pageID, messageTimeout);
    425425    return result;
  • trunk/Source/WebKit2/WebProcess/WebCoreSupport/WebChromeClient.cpp

    r207706 r208415  
    355355    HangDetectionDisabler hangDetectionDisabler;
    356356
    357     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunBeforeUnloadConfirmPanel(message, webFrame->frameID()), Messages::WebPageProxy::RunBeforeUnloadConfirmPanel::Reply(shouldClose), m_page->pageID(), std::chrono::milliseconds::max(), IPC::SendSyncOption::InformPlatformProcessWillSuspend))
     357    if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunBeforeUnloadConfirmPanel(message, webFrame->frameID()), Messages::WebPageProxy::RunBeforeUnloadConfirmPanel::Reply(shouldClose), m_page->pageID(), Seconds::infinity(), IPC::SendSyncOption::InformPlatformProcessWillSuspend))
    358358        return false;
    359359
     
    401401    HangDetectionDisabler hangDetectionDisabler;
    402402
    403     WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptAlert(webFrame->frameID(), SecurityOriginData::fromFrame(frame), alertText), Messages::WebPageProxy::RunJavaScriptAlert::Reply(), m_page->pageID(), std::chrono::milliseconds::max(), IPC::SendSyncOption::InformPlatformProcessWillSuspend);
     403    WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptAlert(webFrame->frameID(), SecurityOriginData::fromFrame(frame), alertText), Messages::WebPageProxy::RunJavaScriptAlert::Reply(), m_page->pageID(), Seconds::infinity(), IPC::SendSyncOption::InformPlatformProcessWillSuspend);
    404404}
    405405
     
    418418
    419419    bool result = false;
    420     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptConfirm(webFrame->frameID(), SecurityOriginData::fromFrame(frame), message), Messages::WebPageProxy::RunJavaScriptConfirm::Reply(result), m_page->pageID(), std::chrono::milliseconds::max(), IPC::SendSyncOption::InformPlatformProcessWillSuspend))
     420    if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptConfirm(webFrame->frameID(), SecurityOriginData::fromFrame(frame), message), Messages::WebPageProxy::RunJavaScriptConfirm::Reply(result), m_page->pageID(), Seconds::infinity(), IPC::SendSyncOption::InformPlatformProcessWillSuspend))
    421421        return false;
    422422
     
    437437    HangDetectionDisabler hangDetectionDisabler;
    438438
    439     if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptPrompt(webFrame->frameID(), SecurityOriginData::fromFrame(frame), message, defaultValue), Messages::WebPageProxy::RunJavaScriptPrompt::Reply(result), m_page->pageID(), std::chrono::milliseconds::max(), IPC::SendSyncOption::InformPlatformProcessWillSuspend))
     439    if (!WebProcess::singleton().parentProcessConnection()->sendSync(Messages::WebPageProxy::RunJavaScriptPrompt(webFrame->frameID(), SecurityOriginData::fromFrame(frame), message, defaultValue), Messages::WebPageProxy::RunJavaScriptPrompt::Reply(result), m_page->pageID(), Seconds::infinity(), IPC::SendSyncOption::InformPlatformProcessWillSuspend))
    440440        return false;
    441441
     
    669669#endif
    670670
    671     m_page->sendSync(Messages::WebPageProxy::PrintFrame(webFrame->frameID()), Messages::WebPageProxy::PrintFrame::Reply(), std::chrono::milliseconds::max(), IPC::SendSyncOption::InformPlatformProcessWillSuspend);
     671    m_page->sendSync(Messages::WebPageProxy::PrintFrame(webFrame->frameID()), Messages::WebPageProxy::PrintFrame::Reply(), Seconds::infinity(), IPC::SendSyncOption::InformPlatformProcessWillSuspend);
    672672}
    673673
     
    689689        WebProcess::singleton().parentProcessConnection()->sendSync(
    690690            Messages::WebPageProxy::ExceededDatabaseQuota(webFrame->frameID(), origin->databaseIdentifier(), databaseName, details.displayName(), currentQuota, currentOriginUsage, details.currentUsage(), details.expectedUsage()),
    691             Messages::WebPageProxy::ExceededDatabaseQuota::Reply(newQuota), m_page->pageID(), std::chrono::milliseconds::max(), IPC::SendSyncOption::InformPlatformProcessWillSuspend);
     691            Messages::WebPageProxy::ExceededDatabaseQuota::Reply(newQuota), m_page->pageID(), Seconds::infinity(), IPC::SendSyncOption::InformPlatformProcessWillSuspend);
    692692    }
    693693
     
    714714    WebProcess::singleton().parentProcessConnection()->sendSync(
    715715        Messages::WebPageProxy::ReachedApplicationCacheOriginQuota(origin->databaseIdentifier(), currentQuota, totalBytesNeeded),
    716         Messages::WebPageProxy::ReachedApplicationCacheOriginQuota::Reply(newQuota), m_page->pageID(), std::chrono::milliseconds::max(), IPC::SendSyncOption::InformPlatformProcessWillSuspend);
     716        Messages::WebPageProxy::ReachedApplicationCacheOriginQuota::Reply(newQuota), m_page->pageID(), Seconds::infinity(), IPC::SendSyncOption::InformPlatformProcessWillSuspend);
    717717
    718718    cacheStorage.storeUpdatedQuotaForOrigin(origin, newQuota);
  • trunk/Source/WebKit2/WebProcess/WebCoreSupport/WebFrameLoaderClient.cpp

    r207484 r208415  
    691691    Ref<WebFrame> protect(*m_frame);
    692692    WebCore::Frame* coreFrame = m_frame->coreFrame();
    693     if (!webPage->sendSync(Messages::WebPageProxy::DecidePolicyForResponseSync(m_frame->frameID(), SecurityOriginData::fromFrame(coreFrame), response, request, canShowMIMEType, listenerID, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())), Messages::WebPageProxy::DecidePolicyForResponseSync::Reply(receivedPolicyAction, policyAction, downloadID), std::chrono::milliseconds::max(), IPC::SendSyncOption::InformPlatformProcessWillSuspend)) {
     693    if (!webPage->sendSync(Messages::WebPageProxy::DecidePolicyForResponseSync(m_frame->frameID(), SecurityOriginData::fromFrame(coreFrame), response, request, canShowMIMEType, listenerID, UserData(WebProcess::singleton().transformObjectsToHandles(userData.get()).get())), Messages::WebPageProxy::DecidePolicyForResponseSync::Reply(receivedPolicyAction, policyAction, downloadID), Seconds::infinity(), IPC::SendSyncOption::InformPlatformProcessWillSuspend)) {
    694694        m_frame->didReceivePolicyDecision(listenerID, PolicyIgnore, 0, { });
    695695        return;
  • trunk/Source/WebKit2/WebProcess/WebPage/WebPage.cpp

    r208406 r208415  
    1 
    21/*
    32 * Copyright (C) 2010-2016 Apple Inc. All rights reserved.
     
    55495548
    55505549    auto& webProcess = WebProcess::singleton();
    5551     if (!sendSync(Messages::WebPageProxy::HandleSynchronousMessage(messageName, UserData(webProcess.transformObjectsToHandles(messageBody))), Messages::WebPageProxy::HandleSynchronousMessage::Reply(returnUserData), std::chrono::milliseconds::max(), IPC::SendSyncOption::UseFullySynchronousModeForTesting))
     5550    if (!sendSync(Messages::WebPageProxy::HandleSynchronousMessage(messageName, UserData(webProcess.transformObjectsToHandles(messageBody))), Messages::WebPageProxy::HandleSynchronousMessage::Reply(returnUserData), Seconds::infinity(), IPC::SendSyncOption::UseFullySynchronousModeForTesting))
    55525551        returnData = nullptr;
    55535552    else
  • trunk/Tools/ChangeLog

    r208400 r208415  
     12016-11-04  Filip Pizlo  <fpizlo@apple.com>
     2
     3        WTF::ParkingLot should stop using std::chrono because std::chrono::duration casts are prone to overflows
     4        https://bugs.webkit.org/show_bug.cgi?id=152045
     5
     6        Reviewed by Andy Estes.
     7
     8        * TestWebKitAPI/CMakeLists.txt:
     9        * TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj:
     10        * TestWebKitAPI/Tests/WTF/Condition.cpp:
     11        (TestWebKitAPI::TEST):
     12        * TestWebKitAPI/Tests/WTF/SynchronizedFixedQueue.cpp:
     13        (TestWebKitAPI::ToUpperConverter::stopProducing):
     14        (TestWebKitAPI::ToUpperConverter::stopConsuming):
     15        * TestWebKitAPI/Tests/WTF/Time.cpp: Added.
     16        (WTF::operator<<):
     17        (TestWebKitAPI::TEST):
     18
    1192016-11-04  Alex Christensen  <achristensen@webkit.org>
    220
  • trunk/Tools/TestWebKitAPI/CMakeLists.txt

    r207325 r208415  
    7979    ${TESTWEBKITAPI_DIR}/Tests/WTF/StringView.cpp
    8080    ${TESTWEBKITAPI_DIR}/Tests/WTF/TemporaryChange.cpp
     81    ${TESTWEBKITAPI_DIR}/Tests/WTF/Time.cpp
    8182    ${TESTWEBKITAPI_DIR}/Tests/WTF/UniqueRef.cpp
    8283    ${TESTWEBKITAPI_DIR}/Tests/WTF/Variant.cpp
  • trunk/Tools/TestWebKitAPI/TestWebKitAPI.xcodeproj/project.pbxproj

    r208340 r208415  
    2626                0F139E781A423A6B00F590F5 /* PlatformUtilitiesCocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = 0F139E721A423A2B00F590F5 /* PlatformUtilitiesCocoa.mm */; };
    2727                0F139E791A42457000F590F5 /* PlatformUtilitiesCocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = 0F139E721A423A2B00F590F5 /* PlatformUtilitiesCocoa.mm */; };
     28                0F2C20B81DCD545000542D9E /* Time.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 0F2C20B71DCD544800542D9E /* Time.cpp */; };
    2829                0F3B94A71A77267400DE3272 /* WKWebViewEvaluateJavaScript.mm in Sources */ = {isa = PBXBuildFile; fileRef = 0F3B94A51A77266C00DE3272 /* WKWebViewEvaluateJavaScript.mm */; };
    2930                1A02C870125D4CFD00E3F4BD /* find.html in Copy Resources */ = {isa = PBXBuildFile; fileRef = 1A02C84B125D4A5E00E3F4BD /* find.html */; };
     
    723724                0F139E751A423A5300F590F5 /* WeakObjCPtr.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; name = WeakObjCPtr.mm; path = cocoa/WeakObjCPtr.mm; sourceTree = "<group>"; };
    724725                0F17BBD415AF6C4D007AB753 /* WebCoreStatisticsWithNoWebProcess.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = WebCoreStatisticsWithNoWebProcess.cpp; sourceTree = "<group>"; };
     726                0F2C20B71DCD544800542D9E /* Time.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Time.cpp; sourceTree = "<group>"; };
    725727                0F3B94A51A77266C00DE3272 /* WKWebViewEvaluateJavaScript.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = WKWebViewEvaluateJavaScript.mm; sourceTree = "<group>"; };
    726728                0FC6C4CB141027E0005B7F0C /* RedBlackTree.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = RedBlackTree.cpp; sourceTree = "<group>"; };
     
    18261828                                5597F8341D9596C80066BC21 /* SynchronizedFixedQueue.cpp */,
    18271829                                0BCD85691485C98B00EA2003 /* TemporaryChange.cpp */,
     1830                                0F2C20B71DCD544800542D9E /* Time.cpp */,
    18281831                                5C5E633D1D0B67940085A025 /* UniqueRef.cpp */,
    18291832                                7CD0D5AA1D5534DE000CC9E1 /* Variant.cpp */,
     
    22882291                                1A77BAA31D9AFFFC005FC568 /* OptionSet.cpp in Sources */,
    22892292                                7C83DEC31D0A590C00FEBCF3 /* Condition.cpp in Sources */,
     2293                                0F2C20B81DCD545000542D9E /* Time.cpp in Sources */,
    22902294                                1A3524AE1D63A4FB0031729B /* Scope.cpp in Sources */,
    22912295                                7C83DEA61D0A590C00FEBCF3 /* Counters.cpp in Sources */,
  • trunk/Tools/TestWebKitAPI/Tests/WTF/Condition.cpp

    r188618 r208415  
    11/*
    2  * Copyright (C) 2015 Apple Inc. All rights reserved.
     2 * Copyright (C) 2015-2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    4949
    5050template<typename Functor>
    51 void wait(Condition& condition, std::unique_lock<Lock>& locker, const Functor& predicate, std::chrono::microseconds timeout)
    52 {
    53     if (timeout == std::chrono::microseconds::max())
     51void wait(Condition& condition, std::unique_lock<Lock>& locker, const Functor& predicate, Seconds timeout)
     52{
     53    if (timeout == Seconds::infinity())
    5454        condition.wait(locker, predicate);
    5555    else {
     
    8181    unsigned numMessagesPerProducer,
    8282    NotifyStyle notifyStyle,
    83     std::chrono::microseconds timeout = std::chrono::microseconds::max(),
    84     std::chrono::microseconds delay = std::chrono::microseconds::zero())
     83    Seconds timeout = Seconds::infinity(),
     84    Seconds delay = Seconds(0))
    8585{
    8686    Deque<unsigned> queue;
     
    129129    }
    130130
    131     std::this_thread::sleep_for(delay);
     131    sleep(delay);
    132132
    133133    for (unsigned i = numProducers; i--;) {
     
    187187    runTest(
    188188        1, 1, 1, 100000, TacticallyNotifyAll,
    189         std::chrono::microseconds(10000),
    190         std::chrono::microseconds(1000000));
     189        Seconds::fromMilliseconds(10),
     190        Seconds(1));
    191191}
    192192
     
    248248    lock.lock();
    249249    bool result = condition.waitFor(
    250         lock, std::chrono::microseconds(10000), [] () -> bool { return false; });
     250        lock, Seconds::fromMilliseconds(10), [] () -> bool { return false; });
    251251    lock.unlock();
    252252
  • trunk/Tools/TestWebKitAPI/Tests/WTF/SynchronizedFixedQueue.cpp

    r207156 r208415  
    117117
    118118        m_lowerQueue.close();
    119         m_produceCloseSemaphore.wait(std::numeric_limits<double>::max());
     119        m_produceCloseSemaphore.wait(WallTime::infinity());
    120120        m_produceQueue = nullptr;
    121121    }
     
    127127
    128128        m_upperQueue.close();
    129         m_consumeCloseSemaphore.wait(std::numeric_limits<double>::max());
     129        m_consumeCloseSemaphore.wait(WallTime::infinity());
    130130        m_consumeQueue = nullptr;
    131131    }
Note: See TracChangeset for help on using the changeset viewer.