[WTF] Use Semaphore and BinarySemaphore instead of dispatch_semaphore_t
authoryusukesuzuki@slowstart.org <yusukesuzuki@slowstart.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Tue, 18 Sep 2018 05:47:33 +0000 (05:47 +0000)
committeryusukesuzuki@slowstart.org <yusukesuzuki@slowstart.org@268f45cc-cd09-0410-ab3c-d52691b4dbfc>
Tue, 18 Sep 2018 05:47:33 +0000 (05:47 +0000)
https://bugs.webkit.org/show_bug.cgi?id=185339

Patch by Yusuke Suzuki <utatane.tea@gmail.com> on 2018-09-17
Reviewed by Mark Lam.

Source/WebCore:

* fileapi/ThreadableBlobRegistry.cpp:
(WebCore::ThreadableBlobRegistry::blobSize):
* platform/cocoa/NetworkExtensionContentFilter.h:
* platform/cocoa/NetworkExtensionContentFilter.mm:
(WebCore::NetworkExtensionContentFilter::initialize):
(WebCore::NetworkExtensionContentFilter::willSendRequest):
(WebCore::NetworkExtensionContentFilter::responseReceived):
(WebCore::NetworkExtensionContentFilter::addData):
(WebCore::NetworkExtensionContentFilter::finishedAddingData):
(WebCore::NetworkExtensionContentFilter::handleDecision):
Use per-function BinarySemaphore instead of holding it in NetworkExtensionContentFilter's field.

* platform/glib/FileMonitorGLib.cpp:
(WebCore::FileMonitor::FileMonitor):
(WebCore::FileMonitor::~FileMonitor):
* platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h:
* platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:
(WebCore::MediaPlayerPrivateAVFoundationObjC::MediaPlayerPrivateAVFoundationObjC):
(WebCore::MediaPlayerPrivateAVFoundationObjC::~MediaPlayerPrivateAVFoundationObjC):
(WebCore::MediaPlayerPrivateAVFoundationObjC::waitForVideoOutputMediaDataWillChange):
(WebCore::MediaPlayerPrivateAVFoundationObjC::outputMediaDataWillChange):
Use BinarySemaphore. And remove unused dispatch_semaphore_t.

* platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.h:
* platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.mm:
(-[WebAVStreamDataParserListener streamDataParserWillProvideContentKeyRequestInitializationData:forTrackID:]):
(-[WebAVStreamDataParserListener streamDataParser:didProvideContentKeyRequestInitializationData:forTrackID:]):
(WebCore::SourceBufferPrivateAVFObjC::SourceBufferPrivateAVFObjC):
(WebCore::SourceBufferPrivateAVFObjC::~SourceBufferPrivateAVFObjC):
(WebCore::SourceBufferPrivateAVFObjC::didProvideContentKeyRequestInitializationDataForTrackID):
(WebCore::SourceBufferPrivateAVFObjC::abort):
(WebCore::SourceBufferPrivateAVFObjC::setCDMSession):
(WebCore::SourceBufferPrivateAVFObjC::setCDMInstance):
Use Box<Semaphore> and Box<BinarySemaphore>.

* platform/graphics/cocoa/WebCoreDecompressionSession.h:
* platform/graphics/cocoa/WebCoreDecompressionSession.mm:
(WebCore::WebCoreDecompressionSession::WebCoreDecompressionSession):
Remove unused dispatch_semaphore_t.

* platform/network/cf/ResourceHandleCFNet.cpp:
(WebCore::ResourceHandle::platformLoadResourceSynchronously):
* platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.cpp:
(WebCore::getRunLoop):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSendRequest):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::willCacheResponse):
(WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToProtectionSpace):
* platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.h:
* platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm:
(-[WebCoreResourceHandleAsOperationQueueDelegate initWithHandle:messageQueue:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate detachHandle]):
(-[WebCoreResourceHandleAsOperationQueueDelegate dealloc]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:willSendRequest:redirectResponse:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:canAuthenticateAgainstProtectionSpace:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:didReceiveResponse:]):
(-[WebCoreResourceHandleAsOperationQueueDelegate connection:willCacheResponse:]):
Use BinarySemaphore instead.

Source/WebKit:

* Platform/IPC/Connection.cpp:
(IPC::Connection::SyncMessageState::wait):
* Shared/mac/SecItemShim.cpp:
(WebKit::sendSecItemRequest):
Use BinarySemaphore.

* UIProcess/ResourceLoadStatisticsPersistentStorage.cpp:
(WebKit::ResourceLoadStatisticsPersistentStorage::finishAllPendingWorkSynchronously):
* UIProcess/WebStorage/StorageManager.cpp:
(WebKit::StorageManager::applicationWillTerminate):
* UIProcess/ios/WKActionSheetAssistant.mm:
(appLinkForURL):
Use BinarySemaphore to wait for async completion handler. We also fix memory leak
since the old code does not call dispatch_release for the used semaphore.

Source/WTF:

This patch adds WTF::Semaphore, which is based on WTF::Lock and WTF::Condition.

* WTF.xcodeproj/project.pbxproj:
* wtf/CMakeLists.txt:
* wtf/Semaphore.h: Added.
(WTF::Semaphore::Semaphore):
(WTF::Semaphore::signal):
(WTF::Semaphore::waitUntil):
(WTF::Semaphore::waitFor):
(WTF::Semaphore::wait):
* wtf/generic/WorkQueueGeneric.cpp:
(WorkQueue::platformInitialize):
* wtf/threads/BinarySemaphore.cpp:
(WTF::BinarySemaphore::waitUntil):
(WTF::BinarySemaphore::wait): Deleted.
* wtf/threads/BinarySemaphore.h:
(WTF::BinarySemaphore::waitFor):
(WTF::BinarySemaphore::wait):
Align the names of the functions to WTF::Condition.
Add BinarySemaphore::wait(), which is the same to waitUntil(WallTime::infinity()).

Tools:

* TestWebKitAPI/Tests/WTF/SynchronizedFixedQueue.cpp:
(TestWebKitAPI::ToUpperConverter::stopProducing):
(TestWebKitAPI::ToUpperConverter::stopConsuming):

git-svn-id: https://svn.webkit.org/repository/webkit/trunk@236101 268f45cc-cd09-0410-ab3c-d52691b4dbfc

29 files changed:
Source/WTF/ChangeLog
Source/WTF/WTF.xcodeproj/project.pbxproj
Source/WTF/wtf/CMakeLists.txt
Source/WTF/wtf/Semaphore.h [new file with mode: 0644]
Source/WTF/wtf/generic/WorkQueueGeneric.cpp
Source/WTF/wtf/threads/BinarySemaphore.cpp
Source/WTF/wtf/threads/BinarySemaphore.h
Source/WebCore/ChangeLog
Source/WebCore/fileapi/ThreadableBlobRegistry.cpp
Source/WebCore/platform/cocoa/NetworkExtensionContentFilter.h
Source/WebCore/platform/cocoa/NetworkExtensionContentFilter.mm
Source/WebCore/platform/glib/FileMonitorGLib.cpp
Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h
Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm
Source/WebCore/platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.h
Source/WebCore/platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.mm
Source/WebCore/platform/graphics/cocoa/WebCoreDecompressionSession.h
Source/WebCore/platform/graphics/cocoa/WebCoreDecompressionSession.mm
Source/WebCore/platform/network/cf/ResourceHandleCFNet.cpp
Source/WebCore/platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.cpp
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.h
Source/WebCore/platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm
Source/WebKit/ChangeLog
Source/WebKit/Platform/IPC/Connection.cpp
Source/WebKit/Shared/mac/SecItemShim.cpp
Source/WebKit/UIProcess/WebStorage/StorageManager.cpp
Source/WebKit/UIProcess/ios/WKActionSheetAssistant.mm
Tools/ChangeLog
Tools/TestWebKitAPI/Tests/WTF/SynchronizedFixedQueue.cpp

index e73d792..d308be1 100644 (file)
@@ -1,3 +1,31 @@
+2018-09-17  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        [WTF] Use Semaphore and BinarySemaphore instead of dispatch_semaphore_t
+        https://bugs.webkit.org/show_bug.cgi?id=185339
+
+        Reviewed by Mark Lam.
+
+        This patch adds WTF::Semaphore, which is based on WTF::Lock and WTF::Condition.
+
+        * WTF.xcodeproj/project.pbxproj:
+        * wtf/CMakeLists.txt:
+        * wtf/Semaphore.h: Added.
+        (WTF::Semaphore::Semaphore):
+        (WTF::Semaphore::signal):
+        (WTF::Semaphore::waitUntil):
+        (WTF::Semaphore::waitFor):
+        (WTF::Semaphore::wait):
+        * wtf/generic/WorkQueueGeneric.cpp:
+        (WorkQueue::platformInitialize):
+        * wtf/threads/BinarySemaphore.cpp:
+        (WTF::BinarySemaphore::waitUntil):
+        (WTF::BinarySemaphore::wait): Deleted.
+        * wtf/threads/BinarySemaphore.h:
+        (WTF::BinarySemaphore::waitFor):
+        (WTF::BinarySemaphore::wait):
+        Align the names of the functions to WTF::Condition.
+        Add BinarySemaphore::wait(), which is the same to waitUntil(WallTime::infinity()).
+
 2018-09-17  Jer Noble  <jer.noble@apple.com>
 
         Add support for HEVC codec types in Media Capabilities
index 0337fec..922bda0 100644 (file)
                E38D6E261F5522E300A75CC4 /* StringBuilderJSON.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = StringBuilderJSON.cpp; sourceTree = "<group>"; };
                E3A32BC21FC830E2007D7E76 /* JSValueMalloc.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = JSValueMalloc.cpp; sourceTree = "<group>"; };
                E3A32BC31FC830E2007D7E76 /* JSValueMalloc.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = JSValueMalloc.h; sourceTree = "<group>"; };
+               E3C21D8B209D5C70006CC078 /* Semaphore.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Semaphore.h; sourceTree = "<group>"; };
                E3CF76902115D6BA0091DE48 /* CompactPointerTuple.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = CompactPointerTuple.h; sourceTree = "<group>"; };
                E3E158251EADA53C004A079D /* SystemFree.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = SystemFree.h; sourceTree = "<group>"; };
                E431CC4A21187ADB000C8A07 /* DispatchSPI.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = DispatchSPI.h; sourceTree = "<group>"; };
                                0F66B2841DC97BAB004A1D3F /* Seconds.cpp */,
                                0F66B2851DC97BAB004A1D3F /* Seconds.h */,
                                A8A47306151A825B004123FF /* SegmentedVector.h */,
+                               E3C21D8B209D5C70006CC078 /* Semaphore.h */,
                                A8A47307151A825B004123FF /* SentinelLinkedList.h */,
                                A8A4731A151A825B004123FF /* SetForScope.h */,
                                A8A47308151A825B004123FF /* SHA1.cpp */,
index b172337..f8a2877 100644 (file)
@@ -197,6 +197,7 @@ set(WTF_PUBLIC_HEADERS
     ScopedLambda.h
     Seconds.h
     SegmentedVector.h
+    Semaphore.h
     SentinelLinkedList.h
     SetForScope.h
     SharedTask.h
diff --git a/Source/WTF/wtf/Semaphore.h b/Source/WTF/wtf/Semaphore.h
new file mode 100644 (file)
index 0000000..1ee5270
--- /dev/null
@@ -0,0 +1,81 @@
+/*
+ * Copyright (C) 2018 Yusuke Suzuki <utatane.tea@gmail.com>.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ * 1. Redistributions of source code must retain the above copyright
+ *    notice, this list of conditions and the following disclaimer.
+ * 2. Redistributions in binary form must reproduce the above copyright
+ *    notice, this list of conditions and the following disclaimer in the
+ *    documentation and/or other materials provided with the distribution.
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
+ * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+ * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL APPLE INC. OR
+ * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
+ * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
+ * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
+ * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
+ * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
+ * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#pragma once
+
+#include <wtf/Condition.h>
+#include <wtf/Lock.h>
+#include <wtf/Noncopyable.h>
+
+namespace WTF {
+
+class Semaphore {
+    WTF_MAKE_NONCOPYABLE(Semaphore);
+    WTF_MAKE_FAST_ALLOCATED;
+public:
+    constexpr Semaphore(unsigned value)
+        : m_value(value)
+    {
+    }
+
+    void signal()
+    {
+        auto locker = holdLock(m_lock);
+        m_value++;
+        m_condition.notifyOne();
+    }
+
+    bool waitUntil(const TimeWithDynamicClockType& timeout)
+    {
+        auto locker = holdLock(m_lock);
+        bool satisfied = m_condition.waitUntil(m_lock, timeout,
+            [&] {
+                return m_value;
+            });
+        if (satisfied)
+            --m_value;
+        return satisfied;
+    }
+
+    bool waitFor(Seconds relativeTimeout)
+    {
+        return waitUntil(MonotonicTime::now() + relativeTimeout);
+    }
+
+    void wait()
+    {
+        waitUntil(ParkingLot::Time::infinity());
+    }
+
+private:
+    unsigned m_value { 0 };
+    Lock m_lock;
+    Condition m_condition;
+};
+
+
+} // namespace WTF
+
+using WTF::Semaphore;
index e059164..3c0492f 100644 (file)
@@ -42,7 +42,7 @@ void WorkQueue::platformInitialize(const char* name, Type, QOS)
         semaphore.signal();
         m_runLoop->run();
     })->detach();
-    semaphore.wait(WallTime::infinity());
+    semaphore.wait();
 }
 
 void WorkQueue::platformInvalidate()
index e2f6ded..1805682 100644 (file)
@@ -35,7 +35,7 @@ void BinarySemaphore::signal()
     m_condition.notifyOne();
 }
 
-bool BinarySemaphore::wait(TimeWithDynamicClockType absoluteTime)
+bool BinarySemaphore::waitUntil(const TimeWithDynamicClockType& absoluteTime)
 {
     auto locker = holdLock(m_lock);
     bool satisfied = m_condition.waitUntil(m_lock, absoluteTime, [&] { return m_isSet; });
index fd59d5a..d5b738f 100644 (file)
@@ -35,11 +35,22 @@ namespace WTF {
 
 class BinarySemaphore {
     WTF_MAKE_NONCOPYABLE(BinarySemaphore);
+    WTF_MAKE_FAST_ALLOCATED;
 public:
-    BinarySemaphore() = default;
+    constexpr BinarySemaphore() = default;
 
     WTF_EXPORT_PRIVATE void signal();
-    WTF_EXPORT_PRIVATE bool wait(TimeWithDynamicClockType);
+    WTF_EXPORT_PRIVATE bool waitUntil(const TimeWithDynamicClockType&);
+
+    bool waitFor(Seconds relativeTimeout)
+    {
+        return waitUntil(MonotonicTime::now() + relativeTimeout);
+    }
+
+    void wait()
+    {
+        waitUntil(ParkingLot::Time::infinity());
+    }
 
 private:
     bool m_isSet { false };
index c336c14..0be1633 100644 (file)
@@ -1,3 +1,69 @@
+2018-09-17  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        [WTF] Use Semaphore and BinarySemaphore instead of dispatch_semaphore_t
+        https://bugs.webkit.org/show_bug.cgi?id=185339
+
+        Reviewed by Mark Lam.
+
+        * fileapi/ThreadableBlobRegistry.cpp:
+        (WebCore::ThreadableBlobRegistry::blobSize):
+        * platform/cocoa/NetworkExtensionContentFilter.h:
+        * platform/cocoa/NetworkExtensionContentFilter.mm:
+        (WebCore::NetworkExtensionContentFilter::initialize):
+        (WebCore::NetworkExtensionContentFilter::willSendRequest):
+        (WebCore::NetworkExtensionContentFilter::responseReceived):
+        (WebCore::NetworkExtensionContentFilter::addData):
+        (WebCore::NetworkExtensionContentFilter::finishedAddingData):
+        (WebCore::NetworkExtensionContentFilter::handleDecision):
+        Use per-function BinarySemaphore instead of holding it in NetworkExtensionContentFilter's field.
+
+        * platform/glib/FileMonitorGLib.cpp:
+        (WebCore::FileMonitor::FileMonitor):
+        (WebCore::FileMonitor::~FileMonitor):
+        * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.h:
+        * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::MediaPlayerPrivateAVFoundationObjC):
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::~MediaPlayerPrivateAVFoundationObjC):
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::waitForVideoOutputMediaDataWillChange):
+        (WebCore::MediaPlayerPrivateAVFoundationObjC::outputMediaDataWillChange):
+        Use BinarySemaphore. And remove unused dispatch_semaphore_t.
+
+        * platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.h:
+        * platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.mm:
+        (-[WebAVStreamDataParserListener streamDataParserWillProvideContentKeyRequestInitializationData:forTrackID:]):
+        (-[WebAVStreamDataParserListener streamDataParser:didProvideContentKeyRequestInitializationData:forTrackID:]):
+        (WebCore::SourceBufferPrivateAVFObjC::SourceBufferPrivateAVFObjC):
+        (WebCore::SourceBufferPrivateAVFObjC::~SourceBufferPrivateAVFObjC):
+        (WebCore::SourceBufferPrivateAVFObjC::didProvideContentKeyRequestInitializationDataForTrackID):
+        (WebCore::SourceBufferPrivateAVFObjC::abort):
+        (WebCore::SourceBufferPrivateAVFObjC::setCDMSession):
+        (WebCore::SourceBufferPrivateAVFObjC::setCDMInstance):
+        Use Box<Semaphore> and Box<BinarySemaphore>.
+
+        * platform/graphics/cocoa/WebCoreDecompressionSession.h:
+        * platform/graphics/cocoa/WebCoreDecompressionSession.mm:
+        (WebCore::WebCoreDecompressionSession::WebCoreDecompressionSession):
+        Remove unused dispatch_semaphore_t.
+
+        * platform/network/cf/ResourceHandleCFNet.cpp:
+        (WebCore::ResourceHandle::platformLoadResourceSynchronously):
+        * platform/network/cf/ResourceHandleCFURLConnectionDelegateWithOperationQueue.cpp:
+        (WebCore::getRunLoop):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSendRequest):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::willCacheResponse):
+        (WebCore::ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToProtectionSpace):
+        * platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.h:
+        * platform/network/mac/WebCoreResourceHandleAsOperationQueueDelegate.mm:
+        (-[WebCoreResourceHandleAsOperationQueueDelegate initWithHandle:messageQueue:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate detachHandle]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate dealloc]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:willSendRequest:redirectResponse:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:canAuthenticateAgainstProtectionSpace:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:didReceiveResponse:]):
+        (-[WebCoreResourceHandleAsOperationQueueDelegate connection:willCacheResponse:]):
+        Use BinarySemaphore instead.
+
 2018-09-17  Simon Fraser  <simon.fraser@apple.com>
 
         Many modern media control tests leak documents in testing
index b6c57a3..5bc9baf 100644 (file)
@@ -150,7 +150,7 @@ unsigned long long ThreadableBlobRegistry::blobSize(const URL& url)
             resultSize = blobRegistry().blobSize(url);
             semaphore.signal();
         });
-        semaphore.wait(WallTime::infinity());
+        semaphore.wait();
     }
     return resultSize;
 }
index 983b703..2106c2b 100644 (file)
@@ -64,7 +64,6 @@ private:
     void handleDecision(NEFilterSourceStatus, NSData *replacementData);
 
     OSObjectPtr<dispatch_queue_t> m_queue;
-    OSObjectPtr<dispatch_semaphore_t> m_semaphore;
     RetainPtr<NSData> m_replacementData;
     RetainPtr<NEFilterSource> m_neFilterSource;
 };
index 0d892ff..e9441ff 100644 (file)
@@ -38,6 +38,7 @@
 #import <objc/runtime.h>
 #import <pal/spi/cocoa/NEFilterSourceSPI.h>
 #import <wtf/SoftLinking.h>
+#import <wtf/threads/BinarySemaphore.h>
 
 SOFT_LINK_FRAMEWORK_OPTIONAL(NetworkExtension);
 SOFT_LINK_CLASS_OPTIONAL(NetworkExtension, NEFilterSource);
@@ -70,10 +71,8 @@ std::unique_ptr<NetworkExtensionContentFilter> NetworkExtensionContentFilter::cr
 void NetworkExtensionContentFilter::initialize(const URL* url)
 {
     ASSERT(!m_queue);
-    ASSERT(!m_semaphore);
     ASSERT(!m_neFilterSource);
     m_queue = adoptOSObject(dispatch_queue_create("WebKit NetworkExtension Filtering", DISPATCH_QUEUE_SERIAL));
-    m_semaphore = adoptOSObject(dispatch_semaphore_create(0));
     ASSERT_UNUSED(url, !url);
     m_neFilterSource = adoptNS([allocNEFilterSourceInstance() initWithDecisionQueue:m_queue.get()]);
 #if (PLATFORM(MAC) && __MAC_OS_X_VERSION_MIN_REQUIRED >= 101300) || (PLATFORM(IOS) && __IPHONE_OS_VERSION_MIN_REQUIRED >= 110000)
@@ -100,17 +99,19 @@ void NetworkExtensionContentFilter::willSendRequest(ResourceRequest& request, co
             return;
     }
 
+    BinarySemaphore semaphore;
     RetainPtr<NSString> modifiedRequestURLString;
-    [m_neFilterSource willSendRequest:request.nsURLRequest(DoNotUpdateHTTPBody) decisionHandler:[this, &modifiedRequestURLString](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
+    [m_neFilterSource willSendRequest:request.nsURLRequest(DoNotUpdateHTTPBody) decisionHandler:[this, &modifiedRequestURLString, &semaphore](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
         modifiedRequestURLString = decisionInfo[NEFilterSourceOptionsRedirectURL];
         ASSERT(!modifiedRequestURLString || [modifiedRequestURLString isKindOfClass:[NSString class]]);
         handleDecision(status, replacementDataFromDecisionInfo(decisionInfo));
+        semaphore.signal();
     }];
 
     // FIXME: We have to block here since DocumentLoader expects to have a
     // blocked/not blocked answer from the filter immediately after calling
     // addData(). We should find a way to make this asynchronous.
-    dispatch_semaphore_wait(m_semaphore.get(), DISPATCH_TIME_FOREVER);
+    semaphore.wait();
 
     if (!modifiedRequestURLString)
         return;
@@ -131,40 +132,46 @@ void NetworkExtensionContentFilter::responseReceived(const ResourceResponse& res
         return;
     }
 
-    [m_neFilterSource receivedResponse:response.nsURLResponse() decisionHandler:[this](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
+    BinarySemaphore semaphore;
+    [m_neFilterSource receivedResponse:response.nsURLResponse() decisionHandler:[this, &semaphore](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
         handleDecision(status, replacementDataFromDecisionInfo(decisionInfo));
+        semaphore.signal();
     }];
 
     // FIXME: We have to block here since DocumentLoader expects to have a
     // blocked/not blocked answer from the filter immediately after calling
     // addData(). We should find a way to make this asynchronous.
-    dispatch_semaphore_wait(m_semaphore.get(), DISPATCH_TIME_FOREVER);
+    semaphore.wait();
 }
 
 void NetworkExtensionContentFilter::addData(const char* data, int length)
 {
     RetainPtr<NSData> copiedData { [NSData dataWithBytes:(void*)data length:length] };
 
-    [m_neFilterSource receivedData:copiedData.get() decisionHandler:[this](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
+    BinarySemaphore semaphore;
+    [m_neFilterSource receivedData:copiedData.get() decisionHandler:[this, &semaphore](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
         handleDecision(status, replacementDataFromDecisionInfo(decisionInfo));
+        semaphore.signal();
     }];
 
     // FIXME: We have to block here since DocumentLoader expects to have a
     // blocked/not blocked answer from the filter immediately after calling
     // addData(). We should find a way to make this asynchronous.
-    dispatch_semaphore_wait(m_semaphore.get(), DISPATCH_TIME_FOREVER);
+    semaphore.wait();
 }
 
 void NetworkExtensionContentFilter::finishedAddingData()
 {
-    [m_neFilterSource finishedLoadingWithDecisionHandler:[this](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
+    BinarySemaphore semaphore;
+    [m_neFilterSource finishedLoadingWithDecisionHandler:[this, &semaphore](NEFilterSourceStatus status, NSDictionary *decisionInfo) {
         handleDecision(status, replacementDataFromDecisionInfo(decisionInfo));
+        semaphore.signal();
     }];
 
     // FIXME: We have to block here since DocumentLoader expects to have a
     // blocked/not blocked answer from the filter immediately after calling
     // finishedAddingData(). We should find a way to make this asynchronous.
-    dispatch_semaphore_wait(m_semaphore.get(), DISPATCH_TIME_FOREVER);
+    semaphore.wait();
 }
 
 Ref<SharedBuffer> NetworkExtensionContentFilter::replacementData() const
@@ -215,7 +222,6 @@ void NetworkExtensionContentFilter::handleDecision(NEFilterSourceStatus status,
     if (!needsMoreData())
         LOG(ContentFiltering, "NetworkExtensionContentFilter stopped buffering with status %zd and replacement data length %zu.\n", status, replacementData.length);
 #endif
-    dispatch_semaphore_signal(m_semaphore.get());
 }
 
 } // namespace WebCore
index bb695a9..463f327 100644 (file)
@@ -60,7 +60,7 @@ FileMonitor::FileMonitor(const String& path, Ref<WorkQueue>&& handlerQueue, WTF:
         createPlatformMonitor();
         semaphore.signal();
     });
-    semaphore.wait(WallTime::infinity());
+    semaphore.wait();
 }
 
 FileMonitor::~FileMonitor()
@@ -74,7 +74,7 @@ FileMonitor::~FileMonitor()
         m_platformMonitor = nullptr;
         semaphore.signal();
     });
-    semaphore.wait(WallTime::infinity());
+    semaphore.wait();
 }
 
 void FileMonitor::fileChangedCallback(GFileMonitor*, GFile*, GFile*, GFileMonitorEvent event, FileMonitor* monitor)
index 99be9fb..c545ae1 100644 (file)
@@ -31,6 +31,7 @@
 #include "MediaPlayerPrivateAVFoundation.h"
 #include <wtf/Function.h>
 #include <wtf/HashMap.h>
+#include <wtf/threads/BinarySemaphore.h>
 
 OBJC_CLASS AVAssetImageGenerator;
 OBJC_CLASS AVAssetResourceLoadingRequest;
@@ -347,7 +348,7 @@ private:
     RetainPtr<WebCoreAVFPullDelegate> m_videoOutputDelegate;
     RetainPtr<CVPixelBufferRef> m_lastPixelBuffer;
     RetainPtr<CGImageRef> m_lastImage;
-    dispatch_semaphore_t m_videoOutputSemaphore;
+    BinarySemaphore m_videoOutputSemaphore;
     std::unique_ptr<VideoTextureCopierCV> m_videoTextureCopier;
 #endif
 
index 0fb1308..f416d22 100644 (file)
@@ -363,7 +363,6 @@ enum MediaPlayerAVFoundationObservationContext {
 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
 @interface WebCoreAVFPullDelegate : NSObject<AVPlayerItemOutputPullDelegate> {
     MediaPlayerPrivateAVFoundationObjC *m_callback;
-    dispatch_semaphore_t m_semaphore;
 }
 - (id)initWithCallback:(MediaPlayerPrivateAVFoundationObjC *)callback;
 - (void)setCallback:(MediaPlayerPrivateAVFoundationObjC*)callback;
@@ -507,7 +506,6 @@ MediaPlayerPrivateAVFoundationObjC::MediaPlayerPrivateAVFoundationObjC(MediaPlay
     , m_haveCheckedPlayability(false)
 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
     , m_videoOutputDelegate(adoptNS([[WebCoreAVFPullDelegate alloc] initWithCallback:this]))
-    , m_videoOutputSemaphore(nullptr)
 #endif
 #if HAVE(AVFOUNDATION_LOADER_DELEGATE)
     , m_loaderDelegate(adoptNS([[WebCoreAVFLoaderDelegate alloc] initWithCallback:this]))
@@ -542,8 +540,6 @@ MediaPlayerPrivateAVFoundationObjC::~MediaPlayerPrivateAVFoundationObjC()
 #if HAVE(AVFOUNDATION_VIDEO_OUTPUT)
     [m_videoOutputDelegate setCallback:0];
     [m_videoOutput setDelegate:nil queue:0];
-    if (m_videoOutputSemaphore)
-        dispatch_release(m_videoOutputSemaphore);
 #endif
 
     if (m_videoLayer)
@@ -2391,21 +2387,17 @@ NativeImagePtr MediaPlayerPrivateAVFoundationObjC::nativeImageForCurrentTime()
 
 void MediaPlayerPrivateAVFoundationObjC::waitForVideoOutputMediaDataWillChange()
 {
-    if (!m_videoOutputSemaphore)
-        m_videoOutputSemaphore = dispatch_semaphore_create(0);
-
     [m_videoOutput requestNotificationOfMediaDataChangeWithAdvanceInterval:0];
 
     // Wait for 1 second.
-    long result = dispatch_semaphore_wait(m_videoOutputSemaphore, dispatch_time(0, 1 * NSEC_PER_SEC));
-
-    if (result)
+    bool satisfied = m_videoOutputSemaphore.waitFor(1_s);
+    if (!satisfied)
         ERROR_LOG(LOGIDENTIFIER, "timed out");
 }
 
 void MediaPlayerPrivateAVFoundationObjC::outputMediaDataWillChange(AVPlayerItemVideoOutputType *)
 {
-    dispatch_semaphore_signal(m_videoOutputSemaphore);
+    m_videoOutputSemaphore.signal();
 }
 
 #endif
index e2d2b56..293c60b 100644 (file)
@@ -29,7 +29,7 @@
 
 #include "SourceBufferPrivate.h"
 #include <dispatch/group.h>
-#include <dispatch/semaphore.h>
+#include <wtf/Box.h>
 #include <wtf/Deque.h>
 #include <wtf/HashMap.h>
 #include <wtf/MediaTime.h>
@@ -39,6 +39,7 @@
 #include <wtf/Vector.h>
 #include <wtf/WeakPtr.h>
 #include <wtf/text/AtomicString.h>
+#include <wtf/threads/BinarySemaphore.h>
 
 OBJC_CLASS AVAsset;
 OBJC_CLASS AVStreamDataParser;
@@ -88,7 +89,7 @@ public:
     void didProvideMediaDataForTrackID(int trackID, CMSampleBufferRef, const String& mediaType, unsigned flags);
     void didReachEndOfTrackWithTrackID(int trackID, const String& mediaType);
     void willProvideContentKeyRequestInitializationDataForTrackID(int trackID);
-    void didProvideContentKeyRequestInitializationDataForTrackID(NSData*, int trackID, OSObjectPtr<dispatch_semaphore_t>);
+    void didProvideContentKeyRequestInitializationDataForTrackID(NSData*, int trackID, Box<BinarySemaphore>);
 
     bool processCodedFrame(int trackID, CMSampleBufferRef, const String& mediaType);
 
@@ -170,7 +171,7 @@ private:
     RetainPtr<WebAVStreamDataParserListener> m_delegate;
     RetainPtr<WebAVSampleBufferErrorListener> m_errorListener;
     RetainPtr<NSError> m_hdcpError;
-    OSObjectPtr<dispatch_semaphore_t> m_hasSessionSemaphore;
+    Box<BinarySemaphore> m_hasSessionSemaphore;
     OSObjectPtr<dispatch_group_t> m_isAppendingGroup;
     RefPtr<WebCoreDecompressionSession> m_decompressionSession;
 
index 4cf2753..528e3ba 100644 (file)
@@ -55,6 +55,7 @@
 #import <wtf/BlockObjCExceptions.h>
 #import <wtf/HashCountedSet.h>
 #import <wtf/MainThread.h>
+#import <wtf/Semaphore.h>
 #import <wtf/SoftLinking.h>
 #import <wtf/WeakPtr.h>
 #import <wtf/text/AtomicString.h>
@@ -100,11 +101,11 @@ SOFT_LINK_CONSTANT(AVFoundation, AVSampleBufferDisplayLayerFailedToDecodeNotific
 
 @interface WebAVStreamDataParserListener : NSObject<AVStreamDataParserOutputHandling> {
     WeakPtr<WebCore::SourceBufferPrivateAVFObjC> _parent;
-    OSObjectPtr<dispatch_semaphore_t> _abortSemaphore;
+    Box<Semaphore> _abortSemaphore;
     AVStreamDataParser* _parser;
 }
 @property (assign) WeakPtr<WebCore::SourceBufferPrivateAVFObjC> parent;
-@property (assign) OSObjectPtr<dispatch_semaphore_t> abortSemaphore;
+@property (assign) Box<Semaphore> abortSemaphore;
 - (id)initWithParser:(AVStreamDataParser*)parser parent:(WeakPtr<WebCore::SourceBufferPrivateAVFObjC>)parent;
 @end
 
@@ -198,19 +199,19 @@ SOFT_LINK_CONSTANT(AVFoundation, AVSampleBufferDisplayLayerFailedToDecodeNotific
 
     // We must call synchronously to the main thread, as the AVStreamSession must be associated
     // with the streamDataParser before the delegate method returns.
-    OSObjectPtr<dispatch_semaphore_t> respondedSemaphore = adoptOSObject(dispatch_semaphore_create(0));
+    Box<BinarySemaphore> respondedSemaphore = Box<BinarySemaphore>::create();
     callOnMainThread([parent = _parent, trackID, respondedSemaphore]() {
         if (parent)
             parent->willProvideContentKeyRequestInitializationDataForTrackID(trackID);
-        dispatch_semaphore_signal(respondedSemaphore.get());
+        respondedSemaphore->signal();
     });
 
     while (true) {
-        if (!dispatch_semaphore_wait(respondedSemaphore.get(), dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_MSEC * 100)))
+        if (respondedSemaphore->waitFor(100_ms))
             return;
 
-        if (!dispatch_semaphore_wait(_abortSemaphore.get(), dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_MSEC * 100))) {
-            dispatch_semaphore_signal(_abortSemaphore.get());
+        if (_abortSemaphore->waitFor(100_ms)) {
+            _abortSemaphore->signal();
             return;
         }
     }
@@ -220,18 +221,18 @@ SOFT_LINK_CONSTANT(AVFoundation, AVSampleBufferDisplayLayerFailedToDecodeNotific
 {
     ASSERT_UNUSED(streamDataParser, streamDataParser == _parser);
 
-    OSObjectPtr<dispatch_semaphore_t> hasSessionSemaphore = adoptOSObject(dispatch_semaphore_create(0));
+    Box<BinarySemaphore> hasSessionSemaphore = Box<BinarySemaphore>::create();
     callOnMainThread([parent = _parent, protectedInitData = RetainPtr<NSData>(initData), trackID, hasSessionSemaphore] {
         if (parent)
             parent->didProvideContentKeyRequestInitializationDataForTrackID(protectedInitData.get(), trackID, hasSessionSemaphore);
     });
 
     while (true) {
-        if (!dispatch_semaphore_wait(hasSessionSemaphore.get(), dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_MSEC * 100)))
+        if (hasSessionSemaphore->waitFor(100_ms))
             return;
 
-        if (!dispatch_semaphore_wait(_abortSemaphore.get(), dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_MSEC * 100))) {
-            dispatch_semaphore_signal(_abortSemaphore.get());
+        if (_abortSemaphore->waitFor(100_ms)) {
+            _abortSemaphore->signal();
             return;
         }
     }
@@ -490,7 +491,7 @@ SourceBufferPrivateAVFObjC::SourceBufferPrivateAVFObjC(MediaSourcePrivateAVFObjC
     , m_mediaSource(parent)
 {
     CMNotificationCenterAddListener(CMNotificationCenterGetDefaultLocalCenter(), this, bufferWasConsumedCallback, kCMSampleBufferConsumerNotification_BufferConsumed, nullptr, 0);
-    m_delegate.get().abortSemaphore = adoptOSObject(dispatch_semaphore_create(0));
+    m_delegate.get().abortSemaphore = Box<Semaphore>::create(0);
 }
 
 SourceBufferPrivateAVFObjC::~SourceBufferPrivateAVFObjC()
@@ -502,7 +503,7 @@ SourceBufferPrivateAVFObjC::~SourceBufferPrivateAVFObjC()
     CMNotificationCenterRemoveListener(CMNotificationCenterGetDefaultLocalCenter(), this, bufferWasConsumedCallback, kCMSampleBufferConsumerNotification_BufferConsumed, nullptr);
 
     if (m_hasSessionSemaphore)
-        dispatch_semaphore_signal(m_hasSessionSemaphore.get());
+        m_hasSessionSemaphore->signal();
 }
 
 void SourceBufferPrivateAVFObjC::didParseStreamDataAsAsset(AVAsset* asset)
@@ -637,7 +638,7 @@ void SourceBufferPrivateAVFObjC::willProvideContentKeyRequestInitializationDataF
 #endif
 }
 
-void SourceBufferPrivateAVFObjC::didProvideContentKeyRequestInitializationDataForTrackID(NSData* initData, int trackID, OSObjectPtr<dispatch_semaphore_t> hasSessionSemaphore)
+void SourceBufferPrivateAVFObjC::didProvideContentKeyRequestInitializationDataForTrackID(NSData* initData, int trackID, Box<BinarySemaphore> hasSessionSemaphore)
 {
     if (!m_mediaSource)
         return;
@@ -650,10 +651,10 @@ void SourceBufferPrivateAVFObjC::didProvideContentKeyRequestInitializationDataFo
     m_mediaSource->sourceBufferKeyNeeded(this, initDataArray.get());
     if (auto session = m_mediaSource->player()->cdmSession()) {
         session->addParser(m_parser.get());
-        dispatch_semaphore_signal(hasSessionSemaphore.get());
+        hasSessionSemaphore->signal();
     } else {
         if (m_hasSessionSemaphore)
-            dispatch_semaphore_signal(m_hasSessionSemaphore.get());
+            m_hasSessionSemaphore->signal();
         m_hasSessionSemaphore = hasSessionSemaphore;
     }
 #endif
@@ -728,12 +729,12 @@ void SourceBufferPrivateAVFObjC::abort()
     // were asked to abort, and that cancels all outstanding append operations. Without cancelling this
     // semaphore, the m_isAppendingGroup wait operation will deadlock.
     if (m_hasSessionSemaphore)
-        dispatch_semaphore_signal(m_hasSessionSemaphore.get());
-    dispatch_semaphore_signal(m_delegate.get().abortSemaphore.get());
+        m_hasSessionSemaphore->signal();
+    m_delegate.get().abortSemaphore->signal();
     dispatch_group_wait(m_isAppendingGroup.get(), DISPATCH_TIME_FOREVER);
     m_appendWeakFactory.revokeAll();
     m_delegate.get().parent = m_appendWeakFactory.createWeakPtr(*this);
-    m_delegate.get().abortSemaphore = adoptOSObject(dispatch_semaphore_create(0));
+    m_delegate.get().abortSemaphore = Box<Semaphore>::create(0);
 }
 
 void SourceBufferPrivateAVFObjC::resetParserState()
@@ -882,7 +883,7 @@ void SourceBufferPrivateAVFObjC::setCDMSession(CDMSessionMediaSourceAVFObjC* ses
     if (m_session) {
         m_session->addSourceBuffer(this);
         if (m_hasSessionSemaphore) {
-            dispatch_semaphore_signal(m_hasSessionSemaphore.get());
+            m_hasSessionSemaphore->signal();
             m_hasSessionSemaphore = nullptr;
         }
 
@@ -917,7 +918,7 @@ void SourceBufferPrivateAVFObjC::setCDMInstance(CDMInstance* instance)
     if (m_cdmInstance) {
         [m_cdmInstance->contentKeySession() addContentKeyRecipient:m_parser.get()];
         if (m_hasSessionSemaphore) {
-            dispatch_semaphore_signal(m_hasSessionSemaphore.get());
+            m_hasSessionSemaphore->signal();
             m_hasSessionSemaphore = nullptr;
         }
     }
index e139481..3905580 100644 (file)
@@ -117,7 +117,6 @@ private:
     RetainPtr<CMTimebaseRef> m_timebase;
     OSObjectPtr<dispatch_queue_t> m_decompressionQueue;
     OSObjectPtr<dispatch_queue_t> m_enqueingQueue;
-    OSObjectPtr<dispatch_semaphore_t> m_hasAvailableImageSemaphore;
     OSObjectPtr<dispatch_source_t> m_timerSource;
     std::function<void()> m_notificationCallback;
     std::function<void()> m_hasAvailableFrameCallback;
index f0debc0..d79e5bf 100644 (file)
@@ -54,7 +54,6 @@ WebCoreDecompressionSession::WebCoreDecompressionSession(Mode mode)
     : m_mode(mode)
     , m_decompressionQueue(adoptOSObject(dispatch_queue_create("WebCoreDecompressionSession Decompression Queue", DISPATCH_QUEUE_SERIAL)))
     , m_enqueingQueue(adoptOSObject(dispatch_queue_create("WebCoreDecompressionSession Enqueueing Queue", DISPATCH_QUEUE_SERIAL)))
-    , m_hasAvailableImageSemaphore(adoptOSObject(dispatch_semaphore_create(0)))
 {
 }
 
index 5cbda5b..e047c7b 100644 (file)
@@ -583,7 +583,7 @@ void ResourceHandle::platformLoadResourceSynchronously(NetworkingContext* contex
             while (true)
                 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1E30, true);
         });
-        sem.wait(TimeWithDynamicClockType(WallTime::infinity()));
+        sem.wait();
     }
     CFURLConnectionScheduleWithRunLoop(handle->connection(), runLoop, kCFRunLoopDefaultMode);
     CFURLConnectionScheduleDownloadWithRunLoop(handle->connection(), runLoop, kCFRunLoopDefaultMode);
index 95e7ffd..dad9010 100644 (file)
@@ -119,7 +119,7 @@ static CFRunLoopRef getRunLoop()
             while (true)
                 CFRunLoopRunInMode(kCFRunLoopDefaultMode, 1E30, true);
         });
-        sem.wait(TimeWithDynamicClockType(WallTime::infinity()));
+        sem.wait();
     }
 
     return runLoop;
@@ -172,7 +172,7 @@ CFURLRequestRef ResourceHandleCFURLConnectionDelegateWithOperationQueue::willSen
         m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
     else
         callOnMainThread(WTFMove(work));
-    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    m_semaphore.wait();
 
     return m_requestResult.leakRef();
 }
@@ -210,7 +210,7 @@ void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveResponse
         m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
     else
         callOnMainThread(WTFMove(work));
-    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    m_semaphore.wait();
 }
 
 void ResourceHandleCFURLConnectionDelegateWithOperationQueue::didReceiveData(CFDataRef data, CFIndex originalLength)
@@ -314,7 +314,7 @@ CFCachedURLResponseRef ResourceHandleCFURLConnectionDelegateWithOperationQueue::
         m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
     else
         callOnMainThread(WTFMove(work));
-    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    m_semaphore.wait();
     return m_cachedResponseResult.leakRef();
 }
 
@@ -383,7 +383,7 @@ Boolean ResourceHandleCFURLConnectionDelegateWithOperationQueue::canRespondToPro
         m_messageQueue->append(std::make_unique<Function<void()>>(WTFMove(work)));
     else
         callOnMainThread(WTFMove(work));
-    m_semaphore.wait(TimeWithDynamicClockType(WallTime::infinity()));
+    m_semaphore.wait();
     return m_boolResult;
 }
 
index 4835426..3eda27e 100644 (file)
@@ -31,6 +31,7 @@
 #include <wtf/MessageQueue.h>
 #include <wtf/RetainPtr.h>
 #include <wtf/SchedulePair.h>
+#include <wtf/threads/BinarySemaphore.h>
 
 namespace WebCore {
 class ResourceHandle;
@@ -40,7 +41,7 @@ class ResourceHandle;
     WebCore::ResourceHandle* m_handle;
 
     // Synchronous delegates on operation queue wait until main thread sends an asynchronous response.
-    dispatch_semaphore_t m_semaphore;
+    BinarySemaphore m_semaphore;
     MessageQueue<Function<void()>>* m_messageQueue;
     RetainPtr<NSURLRequest> m_requestResult;
     Lock m_mutex;
index b3e907f..f99ab58 100644 (file)
@@ -90,7 +90,6 @@ static bool scheduledWithCustomRunLoopMode(const std::optional<SchedulePairHashS
         if (auto* pairs = m_handle->context()->scheduledRunLoopPairs())
             m_scheduledPairs = *pairs;
     }
-    m_semaphore = dispatch_semaphore_create(0);
     m_messageQueue = messageQueue;
 
     return self;
@@ -106,12 +105,11 @@ static bool scheduledWithCustomRunLoopMode(const std::optional<SchedulePairHashS
     m_requestResult = nullptr;
     m_cachedResponseResult = nullptr;
     m_boolResult = NO;
-    dispatch_semaphore_signal(m_semaphore); // OK to signal even if we are not waiting.
+    m_semaphore.signal(); // OK to signal even if we are not waiting.
 }
 
 - (void)dealloc
 {
-    dispatch_release(m_semaphore);
     [super dealloc];
 }
 
@@ -137,18 +135,18 @@ static bool scheduledWithCustomRunLoopMode(const std::optional<SchedulePairHashS
     auto work = [self, protectedSelf, newRequest = retainPtr(newRequest), redirectResponse = retainPtr(redirectResponse)] () mutable {
         if (!m_handle) {
             m_requestResult = nullptr;
-            dispatch_semaphore_signal(m_semaphore);
+            m_semaphore.signal();
             return;
         }
 
         m_handle->willSendRequest(newRequest.get(), redirectResponse.get(), [self, protectedSelf = WTFMove(protectedSelf)](ResourceRequest&& request) {
             m_requestResult = request.nsURLRequest(HTTPBodyUpdatePolicy::UpdateHTTPBody);
-            dispatch_semaphore_signal(m_semaphore);
+            m_semaphore.signal();
         });
     };
 
     [self callFunctionOnMainThread:WTFMove(work)];
-    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
+    m_semaphore.wait();
 
     LockHolder lock(m_mutex);
     if (!m_handle)
@@ -192,17 +190,17 @@ static bool scheduledWithCustomRunLoopMode(const std::optional<SchedulePairHashS
     auto work = [self, protectedSelf, protectionSpace = retainPtr(protectionSpace)] () mutable {
         if (!m_handle) {
             m_boolResult = NO;
-            dispatch_semaphore_signal(m_semaphore);
+            m_semaphore.signal();
             return;
         }
         m_handle->canAuthenticateAgainstProtectionSpace(ProtectionSpace(protectionSpace.get()), [self, protectedSelf = WTFMove(protectedSelf)] (bool result) mutable {
             m_boolResult = result;
-            dispatch_semaphore_signal(m_semaphore);
+            m_semaphore.signal();
         });
     };
 
     [self callFunctionOnMainThread:WTFMove(work)];
-    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
+    m_semaphore.wait();
 
     LockHolder lock(m_mutex);
     if (!m_handle)
@@ -227,7 +225,7 @@ static bool scheduledWithCustomRunLoopMode(const std::optional<SchedulePairHashS
     auto work = [self, protectedSelf, r = retainPtr(r), connection = retainPtr(connection)] () mutable {
         RefPtr<ResourceHandle> protectedHandle(m_handle);
         if (!m_handle || !m_handle->client()) {
-            dispatch_semaphore_signal(m_semaphore);
+            m_semaphore.signal();
             return;
         }
 
@@ -246,12 +244,12 @@ static bool scheduledWithCustomRunLoopMode(const std::optional<SchedulePairHashS
         ResourceHandle::getConnectionTimingData(connection.get(), resourceResponse.deprecatedNetworkLoadMetrics());
 
         m_handle->didReceiveResponse(WTFMove(resourceResponse), [self, protectedSelf = WTFMove(protectedSelf)] {
-            dispatch_semaphore_signal(m_semaphore);
+            m_semaphore.signal();
         });
     };
 
     [self callFunctionOnMainThread:WTFMove(work)];
-    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
+    m_semaphore.wait();
 
     // Make sure we get destroyed on the main thread.
     [self callFunctionOnMainThread:[protectedSelf = WTFMove(protectedSelf)] { }];
@@ -352,18 +350,18 @@ static bool scheduledWithCustomRunLoopMode(const std::optional<SchedulePairHashS
     auto work = [self, protectedSelf, cachedResponse = retainPtr(cachedResponse)] () mutable {
         if (!m_handle || !m_handle->client()) {
             m_cachedResponseResult = nullptr;
-            dispatch_semaphore_signal(m_semaphore);
+            m_semaphore.signal();
             return;
         }
 
         m_handle->client()->willCacheResponseAsync(m_handle, cachedResponse.get(), [self, protectedSelf = WTFMove(protectedSelf)] (NSCachedURLResponse * response) mutable {
             m_cachedResponseResult = response;
-            dispatch_semaphore_signal(m_semaphore);
+            m_semaphore.signal();
         });
     };
 
     [self callFunctionOnMainThread:WTFMove(work)];
-    dispatch_semaphore_wait(m_semaphore, DISPATCH_TIME_FOREVER);
+    m_semaphore.wait();
 
     LockHolder lock(m_mutex);
     if (!m_handle)
index 2b50c8f..1de0fa0 100644 (file)
@@ -1,3 +1,25 @@
+2018-09-17  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        [WTF] Use Semaphore and BinarySemaphore instead of dispatch_semaphore_t
+        https://bugs.webkit.org/show_bug.cgi?id=185339
+
+        Reviewed by Mark Lam.
+
+        * Platform/IPC/Connection.cpp:
+        (IPC::Connection::SyncMessageState::wait):
+        * Shared/mac/SecItemShim.cpp:
+        (WebKit::sendSecItemRequest):
+        Use BinarySemaphore.
+
+        * UIProcess/ResourceLoadStatisticsPersistentStorage.cpp:
+        (WebKit::ResourceLoadStatisticsPersistentStorage::finishAllPendingWorkSynchronously):
+        * UIProcess/WebStorage/StorageManager.cpp:
+        (WebKit::StorageManager::applicationWillTerminate):
+        * UIProcess/ios/WKActionSheetAssistant.mm:
+        (appLinkForURL):
+        Use BinarySemaphore to wait for async completion handler. We also fix memory leak
+        since the old code does not call dispatch_release for the used semaphore.
+
 2018-09-17  Simon Fraser  <simon.fraser@apple.com>
 
         Many modern media control tests leak documents in testing
index 3155c06..5e461b8 100644 (file)
@@ -87,7 +87,7 @@ public:
 
     bool wait(TimeWithDynamicClockType absoluteTime)
     {
-        return m_waitForSyncReplySemaphore.wait(absoluteTime);
+        return m_waitForSyncReplySemaphore.waitUntil(absoluteTime);
     }
 
     // Returns true if this message will be handled on a client thread that is currently
index 44533a6..14c9457 100644 (file)
@@ -39,6 +39,7 @@
 #include <dlfcn.h>
 #include <mutex>
 #include <wtf/ProcessPrivilege.h>
+#include <wtf/threads/BinarySemaphore.h>
 
 #if USE(APPLE_INTERNAL_SDK)
 #include <CFNetwork/CFURLConnectionPriv.h>
@@ -75,16 +76,16 @@ static std::optional<SecItemResponseData> sendSecItemRequest(SecItemRequestData:
 {
     std::optional<SecItemResponseData> response;
 
-    auto semaphore = adoptOSObject(dispatch_semaphore_create(0));
+    BinarySemaphore semaphore;
 
     sharedProcess->parentProcessConnection()->sendWithReply(Messages::SecItemShimProxy::SecItemRequest(SecItemRequestData(requestType, query, attributesToMatch)), 0, workQueue(), [&response, &semaphore](auto reply) {
         if (reply)
             response = WTFMove(std::get<0>(*reply));
 
-        dispatch_semaphore_signal(semaphore.get());
+        semaphore.signal();
     });
 
-    dispatch_semaphore_wait(semaphore.get(), DISPATCH_TIME_FOREVER);
+    semaphore.wait();
 
     return response;
 }
index 2152ed7..36b05f2 100644 (file)
@@ -849,7 +849,7 @@ void StorageManager::applicationWillTerminate()
 
         semaphore.signal();
     });
-    semaphore.wait(WallTime::infinity());
+    semaphore.wait();
 }
 
 StorageManager::StorageArea* StorageManager::findStorageArea(IPC::Connection& connection, uint64_t storageMapID) const
index 2018eae..bb66347 100644 (file)
@@ -46,6 +46,7 @@
 #import <wtf/WeakObjCPtr.h>
 #import <wtf/cocoa/Entitlements.h>
 #import <wtf/text/WTFString.h>
+#import <wtf/threads/BinarySemaphore.h>
 
 #if HAVE(APP_LINKS)
 #import <pal/spi/cocoa/LaunchServicesSPI.h>
@@ -70,14 +71,15 @@ static bool applicationHasAppLinkEntitlements()
 
 static LSAppLink *appLinkForURL(NSURL *url)
 {
+    BinarySemaphore semaphore;
     __block LSAppLink *syncAppLink = nil;
+    __block BinarySemaphore* semaphorePtr = &semaphore;
 
-    dispatch_semaphore_t semaphore = dispatch_semaphore_create(0);
     [LSAppLink getAppLinkWithURL:url completionHandler:^(LSAppLink *appLink, NSError *error) {
         syncAppLink = [appLink retain];
-        dispatch_semaphore_signal(semaphore);
+        semaphorePtr->signal();
     }];
-    dispatch_semaphore_wait(semaphore, DISPATCH_TIME_FOREVER);
+    semaphore.wait();
 
     return [syncAppLink autorelease];
 }
index 5bbbc26..4eddb3e 100644 (file)
@@ -1,3 +1,14 @@
+2018-09-17  Yusuke Suzuki  <utatane.tea@gmail.com>
+
+        [WTF] Use Semaphore and BinarySemaphore instead of dispatch_semaphore_t
+        https://bugs.webkit.org/show_bug.cgi?id=185339
+
+        Reviewed by Mark Lam.
+
+        * TestWebKitAPI/Tests/WTF/SynchronizedFixedQueue.cpp:
+        (TestWebKitAPI::ToUpperConverter::stopProducing):
+        (TestWebKitAPI::ToUpperConverter::stopConsuming):
+
 2018-09-17  Simon Fraser  <simon.fraser@apple.com>
 
         Many modern media control tests leak documents in testing
index 81bbc10..f7a48db 100644 (file)
@@ -123,7 +123,7 @@ public:
             return;
 
         m_lowerQueue->close();
-        m_produceCloseSemaphore.wait(WallTime::infinity());
+        m_produceCloseSemaphore.wait();
         m_produceQueue = nullptr;
     }
     
@@ -133,7 +133,7 @@ public:
             return;
 
         m_upperQueue->close();
-        m_consumeCloseSemaphore.wait(WallTime::infinity());
+        m_consumeCloseSemaphore.wait();
         m_consumeQueue = nullptr;
     }