Changeset 201482 in webkit


Ignore:
Timestamp:
May 27, 2016 10:51:42 PM (8 years ago)
Author:
Chris Dumez
Message:

callOnMainThread() should not copy captured lambda variables
https://bugs.webkit.org/show_bug.cgi?id=158166

Reviewed by Brady Eidson.

Source/WebCore:

callOnMainThread() should not copy captured lambda variables. This
function is usually called cross-thread with a lambda and copying
the lambda (and its captured variables) can lead to thread-safety
issues.

This patch updates callOnMainThread() to take a NoncopyableFunction&&
in parameter instead of a std::function. The call sites of
callOnMainThread() have also been updated to use C++14's lambda
capture with initializer.

  • Modules/indexeddb/IDBTransaction.cpp:

(WebCore::IDBTransaction::putOrAddOnServer):

  • Modules/mediastream/MediaDevicesRequest.cpp:

(WebCore::MediaDevicesRequest::didCompletePermissionCheck):
(WebCore::MediaDevicesRequest::didCompleteTrackSourceInfoRequest):

  • Modules/mediastream/MediaEndpointPeerConnection.cpp:

(WebCore::MediaEndpointPeerConnection::runTask):

  • Modules/mediastream/MediaEndpointPeerConnection.h:
  • Modules/mediastream/UserMediaRequest.cpp:

(WebCore::UserMediaRequest::constraintsValidated):
(WebCore::UserMediaRequest::userMediaAccessGranted):

  • Modules/webaudio/AudioContext.cpp:

(WebCore::AudioContext::scheduleNodeDeletion):
(WebCore::AudioContext::isPlayingAudioDidChange):

  • dom/Document.cpp:

(WebCore::Document::postTask):
(WebCore::Document::pendingTasksTimerFired): Deleted.

  • dom/ScriptElement.cpp:

(WebCore::ScriptElement::requestScript):

  • fileapi/AsyncFileStream.cpp:

(WebCore::callOnFileThread):
(WebCore::AsyncFileStream::~AsyncFileStream):
(WebCore::AsyncFileStream::perform):

  • fileapi/AsyncFileStream.h:
  • fileapi/ThreadableBlobRegistry.cpp:

(WebCore::ThreadableBlobRegistry::registerFileBlobURL):
(WebCore::ThreadableBlobRegistry::registerBlobURL):
(WebCore::ThreadableBlobRegistry::registerBlobURLForSlice):
(WebCore::ThreadableBlobRegistry::blobSize):
(WebCore::ThreadableBlobRegistry::unregisterBlobURL):
(WebCore::ThreadableBlobRegistry::registerBlobURLOptionallyFileBacked): Deleted.

  • loader/icon/IconDatabase.cpp:

(WebCore::IconDatabase::dispatchDidImportIconURLForPageURLOnMainThread):
(WebCore::IconDatabase::dispatchDidImportIconDataForPageURLOnMainThread):

  • page/ResourceUsageThread.cpp:

(WebCore::ResourceUsageThread::notifyObservers):
(WebCore::ResourceUsageThread::threadBody):

  • page/ResourceUsageThread.h:
  • page/scrolling/ScrollingThread.cpp:

(WebCore::ScrollingThread::dispatch):
(WebCore::ScrollingThread::dispatchBarrier):
(WebCore::ScrollingThread::dispatchFunctionsFromScrollingThread):

  • page/scrolling/ScrollingThread.h:
  • page/scrolling/ios/ScrollingTreeIOS.cpp:

(WebCore::ScrollingTreeIOS::invalidate):
(WebCore::ScrollingTreeIOS::scrollingTreeNodeDidScroll):
(WebCore::ScrollingTreeIOS::currentSnapPointIndicesDidChange):
(WebCore::ScrollingTreeIOS::createScrollingTreeNode): Deleted.

  • page/scrolling/mac/ScrollingTreeFrameScrollingNodeMac.mm:

(WebCore::ScrollingTreeFrameScrollingNodeMac::releaseReferencesToScrollerImpsOnTheMainThread):

  • platform/MemoryPressureHandler.cpp:

(WebCore::MemoryPressureHandler::releaseMemory):

  • platform/audio/ios/MediaSessionManagerIOS.mm:

(-[WebMediaSessionHelper dealloc]):
(-[WebMediaSessionHelper startMonitoringAirPlayRoutes]):
(-[WebMediaSessionHelper stopMonitoringAirPlayRoutes]):

  • platform/graphics/avfoundation/AudioSourceProviderAVFObjC.mm:

(WebCore::AudioSourceProviderAVFObjC::prepare):

  • platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp:

(WebCore::MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification):
(WebCore::MediaPlayerPrivateAVFoundation::dispatchNotification):

  • platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.mm:

(-[WebCDMSessionAVFoundationObjCListener observeValueForKeyPath:ofObject:change:context:]):

  • platform/graphics/avfoundation/objc/MediaPlaybackTargetPickerMac.mm:

(-[WebAVOutputDeviceMenuControllerHelper observeValueForKeyPath:ofObject:change:context:]):

  • platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:

(WebCore::MediaPlayerPrivateAVFoundationObjC::createVideoLayer):
(-[WebCoreAVFMovieObserver legibleOutput:didOutputAttributedStrings:nativeSampleBuffers:forItemTime:]):
(-[WebCoreAVFMovieObserver outputSequenceWasFlushed:]):
(-[WebCoreAVFLoaderDelegate resourceLoader:shouldWaitForLoadingOfRequestedResource:]):
(-[WebCoreAVFLoaderDelegate resourceLoader:shouldWaitForResponseToAuthenticationChallenge:]):
(-[WebCoreAVFLoaderDelegate resourceLoader:didCancelLoadingRequest:]):

  • platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaSourceAVFObjC.mm:

(WebCore::CMTimebaseEffectiveRateChangedCallback):
(WebCore::MediaPlayerPrivateMediaSourceAVFObjC::play):
(WebCore::MediaPlayerPrivateMediaSourceAVFObjC::pause):

  • platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.h:
  • platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm:

(WebCore::MediaPlayerPrivateMediaStreamAVFObjC::scheduleDeferredTask):

  • platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.mm:

(-[WebAVStreamDataParserListener streamDataParser:didParseStreamDataAsAsset:]):
(-[WebAVStreamDataParserListener streamDataParser:didParseStreamDataAsAsset:withDiscontinuity:]):
(-[WebAVStreamDataParserListener streamDataParser:didFailToParseStreamDataWithError:]):
(-[WebAVStreamDataParserListener streamDataParser:didProvideMediaData:forTrackID:mediaType:flags:]):
(-[WebAVStreamDataParserListener streamDataParser:didReachEndOfTrackWithTrackID:mediaType:]):
(-[WebAVStreamDataParserListener streamDataParser:didProvideContentKeyRequestInitializationData:forTrackID:]):
(-[WebAVSampleBufferErrorListener observeValueForKeyPath:ofObject:change:context:]):
(-[WebAVSampleBufferErrorListener layerFailedToDecode:]):

  • platform/graphics/cg/GraphicsContextCG.cpp:

(WebCore::patternReleaseCallback):

  • platform/graphics/cg/PatternCG.cpp:

(WebCore::patternReleaseCallback):

  • platform/graphics/win/MediaPlayerPrivateMediaFoundation.cpp:

(WebCore::MediaPlayerPrivateMediaFoundation::endCreatedMediaSource):
(WebCore::MediaPlayerPrivateMediaFoundation::endGetEvent):
(WebCore::MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::processInputNotify):

  • platform/mediastream/MediaStreamPrivate.cpp:

(WebCore::MediaStreamPrivate::scheduleDeferredTask):

  • platform/mediastream/MediaStreamPrivate.h:
  • platform/mediastream/mac/AVMediaCaptureSource.h:
  • platform/mediastream/mac/AVMediaCaptureSource.mm:

(WebCore::AVMediaCaptureSource::scheduleDeferredTask):

  • platform/mediastream/mac/RealtimeMediaSourceCenterMac.cpp:

(WebCore::RealtimeMediaSourceCenterMac::getMediaStreamTrackSources):

  • platform/mediastream/mac/WebAudioSourceProviderAVFObjC.mm:

(WebCore::WebAudioSourceProviderAVFObjC::prepare):

  • platform/mock/MockRealtimeMediaSourceCenter.cpp:

(WebCore::MockRealtimeMediaSourceCenter::getMediaStreamTrackSources):

  • platform/network/BlobResourceHandle.cpp:

(WebCore::BlobResourceHandle::start):
(WebCore::BlobResourceHandle::notifyFinish):

  • platform/network/DataURLDecoder.cpp:

(WebCore::DataURLDecoder::decode):

  • platform/network/DataURLDecoder.h:
  • platform/network/cocoa/WebCoreNSURLSession.mm:

(-[WebCoreNSURLSession dealloc]):
(-[WebCoreNSURLSessionDataTask cancel]):
(-[WebCoreNSURLSessionDataTask suspend]):
(-[WebCoreNSURLSessionDataTask resume]):

  • platform/network/curl/CurlDownload.cpp:

(WebCore::CurlDownload::didReceiveHeader):
(WebCore::CurlDownload::didReceiveData): Deleted.

Source/WebKit:

callOnMainThread() should not copy captured lambda variables. This
function is usually called cross-thread with a lambda and copying
the lambda (and its captured variables) can lead to thread-safety
issues.

This patch updates callOnMainThread() to take a NoncopyableFunction&&
in parameter instead of a std::function. The call sites of
callOnMainThread() have also been updated to use C++14's lambda
capture with initializer.

  • Storage/StorageAreaSync.cpp:

(WebCore::StorageAreaSync::deleteEmptyDatabase):

  • Storage/StorageSyncManager.cpp:

(WebCore::StorageSyncManager::dispatch):

  • Storage/StorageSyncManager.h:
  • Storage/StorageThread.cpp:

(WebCore::StorageThread::dispatch):
(WebCore::StorageThread::terminate):
(WebCore::StorageThread::releaseFastMallocFreeMemoryInAllThreads):

  • Storage/StorageThread.h:
  • Storage/StorageTracker.cpp:

(WebCore::StorageTracker::syncFileSystemAndTrackerDatabase):
(WebCore::StorageTracker::setOriginDetails):

Source/WebKit/mac:

callOnMainThread() should not copy captured lambda variables. This
function is usually called cross-thread with a lambda and copying
the lambda (and its captured variables) can lead to thread-safety
issues.

This patch updates callOnMainThread() to take a NoncopyableFunction&&
in parameter instead of a std::function. The call sites of
callOnMainThread() have also been updated to use C++14's lambda
capture with initializer.

  • Storage/WebDatabaseManagerClient.mm:

(DidModifyOriginData::dispatchToMainThread):
(DidModifyOriginData::DidModifyOriginData): Deleted.

  • Storage/WebStorageTrackerClient.mm:

(WebStorageTrackerClient::dispatchDidModifyOrigin):

Source/WTF:

callOnMainThread() should not copy captured lambda variables. This
function is usually called cross-thread with a lambda and copying
the lambda (and its captured variables) can lead to thread-safety
issues.

This patch updates callOnMainThread() to take a NoncopyableFunction&&
in parameter instead of a std::function. The call sites of
callOnMainThread() have also been updated to use C++14's lambda
capture with initializer.

  • WTF.xcodeproj/project.pbxproj:
  • wtf/FunctionDispatcher.h:
  • wtf/NoncopyableFunction.h:
  • Moved NoncopyableFunction from FunctionDispatcher.h to NoncopyableFunction.h.
  • Add a new operator=(nullptr_t) operator to NoncopyableFunction to match std::function, as one of the call sites needed it.
  • wtf/MainThread.cpp:

(WTF::functionQueue):
(WTF::dispatchFunctionsFromMainThread):
(WTF::callOnMainThread):

  • wtf/MainThread.h:
Location:
trunk/Source
Files:
60 edited
1 copied

Legend:

Unmodified
Added
Removed
  • trunk/Source/WTF/ChangeLog

    r201479 r201482  
     12016-05-27  Chris Dumez  <cdumez@apple.com>
     2
     3        callOnMainThread() should not copy captured lambda variables
     4        https://bugs.webkit.org/show_bug.cgi?id=158166
     5
     6        Reviewed by Brady Eidson.
     7
     8        callOnMainThread() should not copy captured lambda variables. This
     9        function is usually called cross-thread with a lambda and copying
     10        the lambda (and its captured variables) can lead to thread-safety
     11        issues.
     12
     13        This patch updates callOnMainThread() to take a NoncopyableFunction&&
     14        in parameter instead of a std::function. The call sites of
     15        callOnMainThread() have also been updated to use C++14's lambda
     16        capture with initializer.
     17
     18        * WTF.xcodeproj/project.pbxproj:
     19
     20        * wtf/FunctionDispatcher.h:
     21        * wtf/NoncopyableFunction.h:
     22        - Moved NoncopyableFunction from FunctionDispatcher.h to
     23          NoncopyableFunction.h.
     24        - Add a new operator=(nullptr_t) operator to NoncopyableFunction to
     25          match std::function, as one of the call sites needed it.
     26
     27        * wtf/MainThread.cpp:
     28        (WTF::functionQueue):
     29        (WTF::dispatchFunctionsFromMainThread):
     30        (WTF::callOnMainThread):
     31        * wtf/MainThread.h:
     32
    1332016-05-27  Yusuke Suzuki  <utatane.tea@gmail.com>
    234
  • trunk/Source/WTF/WTF.xcodeproj/project.pbxproj

    r201406 r201482  
    115115                8134013815B092FD001FF0B8 /* Base64.cpp in Sources */ = {isa = PBXBuildFile; fileRef = 8134013615B092FD001FF0B8 /* Base64.cpp */; };
    116116                8134013915B092FD001FF0B8 /* Base64.h in Headers */ = {isa = PBXBuildFile; fileRef = 8134013715B092FD001FF0B8 /* Base64.h */; };
     117                83F2BADF1CF9524E003E99C3 /* NoncopyableFunction.h in Headers */ = {isa = PBXBuildFile; fileRef = 83F2BADE1CF9524E003E99C3 /* NoncopyableFunction.h */; };
    117118                83FBA93219DF459700F30ADB /* TypeCasts.h in Headers */ = {isa = PBXBuildFile; fileRef = 83FBA93119DF459700F30ADB /* TypeCasts.h */; };
    118119                86F46F611A2840EE00CCBF22 /* RefCounter.h in Headers */ = {isa = PBXBuildFile; fileRef = 86F46F5F1A2840EE00CCBF22 /* RefCounter.h */; };
     
    438439                8134013615B092FD001FF0B8 /* Base64.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = Base64.cpp; sourceTree = "<group>"; };
    439440                8134013715B092FD001FF0B8 /* Base64.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Base64.h; sourceTree = "<group>"; };
     441                83F2BADE1CF9524E003E99C3 /* NoncopyableFunction.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = NoncopyableFunction.h; sourceTree = "<group>"; };
    440442                83FBA93119DF459700F30ADB /* TypeCasts.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = TypeCasts.h; sourceTree = "<group>"; };
    441443                86F46F5F1A2840EE00CCBF22 /* RefCounter.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = RefCounter.h; sourceTree = "<group>"; };
     
    870872                                0F0D85B317234CB100338210 /* NoLock.h */,
    871873                                A8A472D0151A825B004123FF /* Noncopyable.h */,
     874                                83F2BADE1CF9524E003E99C3 /* NoncopyableFunction.h */,
    872875                                A8A472D5151A825B004123FF /* NumberOfCores.cpp */,
    873876                                A8A472D6151A825B004123FF /* NumberOfCores.h */,
     
    12321235                                A8A473DA151A825B004123FF /* HashTraits.h in Headers */,
    12331236                                A8A473DB151A825B004123FF /* HexNumber.h in Headers */,
     1237                                83F2BADF1CF9524E003E99C3 /* NoncopyableFunction.h in Headers */,
    12341238                                2684D4361C000D400081D663 /* IndexSparseSet.h in Headers */,
    12351239                                A8A473DC151A825B004123FF /* InlineASM.h in Headers */,
  • trunk/Source/WTF/wtf/FunctionDispatcher.h

    r201464 r201482  
    2828
    2929#include <functional>
     30#include <wtf/NoncopyableFunction.h>
    3031#include <wtf/ThreadSafeRefCounted.h>
    3132
    3233namespace WTF {
    33 
    34 // FIXME: Move this to its own header (e.g. Functional.h).
    35 // FIXME: We could make this templated to support other lambdas than void() and make this more reusable.
    36 class NoncopyableFunction {
    37 public:
    38     NoncopyableFunction() = default;
    39 
    40     template<typename CallableType, class = typename std::enable_if<std::is_rvalue_reference<CallableType&&>::value>::type>
    41     NoncopyableFunction(CallableType&& callable)
    42         : m_callableWrapper(std::make_unique<CallableWrapper<CallableType>>(WTFMove(callable)))
    43     {
    44     }
    45 
    46     void operator()() const
    47     {
    48         if (m_callableWrapper)
    49             m_callableWrapper->call();
    50     }
    51 
    52     explicit operator bool() const { return !!m_callableWrapper; }
    53 
    54     template<typename CallableType, class = typename std::enable_if<std::is_rvalue_reference<CallableType&&>::value>::type>
    55     NoncopyableFunction& operator=(CallableType&& callable)
    56     {
    57         m_callableWrapper = std::make_unique<CallableWrapper<CallableType>>(WTFMove(callable));
    58         return *this;
    59     }
    60 
    61 private:
    62     class CallableWrapperBase {
    63         WTF_MAKE_FAST_ALLOCATED;
    64     public:
    65         virtual ~CallableWrapperBase() { }
    66 
    67         virtual void call() = 0;
    68     };
    69 
    70     template<typename CallableType>
    71     class CallableWrapper final : public CallableWrapperBase {
    72     public:
    73         explicit CallableWrapper(CallableType&& callable)
    74             : m_callable(WTFMove(callable))
    75         {
    76         }
    77 
    78         CallableWrapper(const CallableWrapper&) = delete;
    79         CallableWrapper& operator=(const CallableWrapper&) = delete;
    80 
    81         void call() final { m_callable(); }
    82 
    83     private:
    84         CallableType m_callable;
    85     };
    86 
    87     std::unique_ptr<CallableWrapperBase> m_callableWrapper;
    88 };
    8934
    9035// FunctionDispatcher is an abstract representation of something that functions can be
     
    10449
    10550using WTF::FunctionDispatcher;
    106 using WTF::NoncopyableFunction;
    10751
    10852#endif // FunctionDispatcher_h
  • trunk/Source/WTF/wtf/MainThread.cpp

    r194496 r201482  
    4848static StaticLock mainThreadFunctionQueueMutex;
    4949
    50 static Deque<std::function<void ()>>& functionQueue()
    51 {
    52     static NeverDestroyed<Deque<std::function<void ()>>> functionQueue;
     50static Deque<NoncopyableFunction>& functionQueue()
     51{
     52    static NeverDestroyed<Deque<NoncopyableFunction>> functionQueue;
    5353    return functionQueue;
    5454}
     
    121121    auto startTime = std::chrono::steady_clock::now();
    122122
    123     std::function<void ()> function;
     123    NoncopyableFunction function;
    124124
    125125    while (true) {
     
    145145}
    146146
    147 void callOnMainThread(std::function<void ()> function)
     147void callOnMainThread(NoncopyableFunction&& function)
    148148{
    149149    ASSERT(function);
  • trunk/Source/WTF/wtf/MainThread.h

    r194318 r201482  
    3333#include <functional>
    3434#include <stdint.h>
     35#include <wtf/NoncopyableFunction.h>
    3536
    3637namespace WTF {
     
    4142WTF_EXPORT_PRIVATE void initializeMainThread();
    4243
    43 WTF_EXPORT_PRIVATE void callOnMainThread(std::function<void ()>);
     44WTF_EXPORT_PRIVATE void callOnMainThread(NoncopyableFunction&&);
    4445
    4546#if PLATFORM(COCOA)
  • trunk/Source/WTF/wtf/NoncopyableFunction.h

    r201481 r201482  
    11/*
    2  * Copyright (C) 2013 Apple Inc. All rights reserved.
     2 * Copyright (C) 2016 Apple Inc. All rights reserved.
    33 *
    44 * Redistribution and use in source and binary forms, with or without
     
    2424 */
    2525
    26 #ifndef FunctionDispatcher_h
    27 #define FunctionDispatcher_h
     26#pragma once
    2827
    29 #include <functional>
    30 #include <wtf/ThreadSafeRefCounted.h>
     28#include <memory>
    3129
    3230namespace WTF {
    3331
    34 // FIXME: Move this to its own header (e.g. Functional.h).
    3532// FIXME: We could make this templated to support other lambdas than void() and make this more reusable.
    3633class NoncopyableFunction {
     
    5653    {
    5754        m_callableWrapper = std::make_unique<CallableWrapper<CallableType>>(WTFMove(callable));
     55        return *this;
     56    }
     57
     58    NoncopyableFunction& operator=(std::nullptr_t)
     59    {
     60        m_callableWrapper = nullptr;
    5861        return *this;
    5962    }
     
    8891};
    8992
    90 // FunctionDispatcher is an abstract representation of something that functions can be
    91 // dispatched to. This can for example be a run loop or a work queue.
    92 
    93 class FunctionDispatcher : public ThreadSafeRefCounted<FunctionDispatcher> {
    94 public:
    95     WTF_EXPORT_PRIVATE virtual ~FunctionDispatcher();
    96 
    97     virtual void dispatch(NoncopyableFunction&&) = 0;
    98 
    99 protected:
    100     WTF_EXPORT_PRIVATE FunctionDispatcher();
    101 };
    102 
    10393} // namespace WTF
    10494
    105 using WTF::FunctionDispatcher;
    10695using WTF::NoncopyableFunction;
    107 
    108 #endif // FunctionDispatcher_h
  • trunk/Source/WebCore/ChangeLog

    r201478 r201482  
     12016-05-27  Chris Dumez  <cdumez@apple.com>
     2
     3        callOnMainThread() should not copy captured lambda variables
     4        https://bugs.webkit.org/show_bug.cgi?id=158166
     5
     6        Reviewed by Brady Eidson.
     7
     8        callOnMainThread() should not copy captured lambda variables. This
     9        function is usually called cross-thread with a lambda and copying
     10        the lambda (and its captured variables) can lead to thread-safety
     11        issues.
     12
     13        This patch updates callOnMainThread() to take a NoncopyableFunction&&
     14        in parameter instead of a std::function. The call sites of
     15        callOnMainThread() have also been updated to use C++14's lambda
     16        capture with initializer.
     17
     18        * Modules/indexeddb/IDBTransaction.cpp:
     19        (WebCore::IDBTransaction::putOrAddOnServer):
     20        * Modules/mediastream/MediaDevicesRequest.cpp:
     21        (WebCore::MediaDevicesRequest::didCompletePermissionCheck):
     22        (WebCore::MediaDevicesRequest::didCompleteTrackSourceInfoRequest):
     23        * Modules/mediastream/MediaEndpointPeerConnection.cpp:
     24        (WebCore::MediaEndpointPeerConnection::runTask):
     25        * Modules/mediastream/MediaEndpointPeerConnection.h:
     26        * Modules/mediastream/UserMediaRequest.cpp:
     27        (WebCore::UserMediaRequest::constraintsValidated):
     28        (WebCore::UserMediaRequest::userMediaAccessGranted):
     29        * Modules/webaudio/AudioContext.cpp:
     30        (WebCore::AudioContext::scheduleNodeDeletion):
     31        (WebCore::AudioContext::isPlayingAudioDidChange):
     32        * dom/Document.cpp:
     33        (WebCore::Document::postTask):
     34        (WebCore::Document::pendingTasksTimerFired): Deleted.
     35        * dom/ScriptElement.cpp:
     36        (WebCore::ScriptElement::requestScript):
     37        * fileapi/AsyncFileStream.cpp:
     38        (WebCore::callOnFileThread):
     39        (WebCore::AsyncFileStream::~AsyncFileStream):
     40        (WebCore::AsyncFileStream::perform):
     41        * fileapi/AsyncFileStream.h:
     42        * fileapi/ThreadableBlobRegistry.cpp:
     43        (WebCore::ThreadableBlobRegistry::registerFileBlobURL):
     44        (WebCore::ThreadableBlobRegistry::registerBlobURL):
     45        (WebCore::ThreadableBlobRegistry::registerBlobURLForSlice):
     46        (WebCore::ThreadableBlobRegistry::blobSize):
     47        (WebCore::ThreadableBlobRegistry::unregisterBlobURL):
     48        (WebCore::ThreadableBlobRegistry::registerBlobURLOptionallyFileBacked): Deleted.
     49        * loader/icon/IconDatabase.cpp:
     50        (WebCore::IconDatabase::dispatchDidImportIconURLForPageURLOnMainThread):
     51        (WebCore::IconDatabase::dispatchDidImportIconDataForPageURLOnMainThread):
     52        * page/ResourceUsageThread.cpp:
     53        (WebCore::ResourceUsageThread::notifyObservers):
     54        (WebCore::ResourceUsageThread::threadBody):
     55        * page/ResourceUsageThread.h:
     56        * page/scrolling/ScrollingThread.cpp:
     57        (WebCore::ScrollingThread::dispatch):
     58        (WebCore::ScrollingThread::dispatchBarrier):
     59        (WebCore::ScrollingThread::dispatchFunctionsFromScrollingThread):
     60        * page/scrolling/ScrollingThread.h:
     61        * page/scrolling/ios/ScrollingTreeIOS.cpp:
     62        (WebCore::ScrollingTreeIOS::invalidate):
     63        (WebCore::ScrollingTreeIOS::scrollingTreeNodeDidScroll):
     64        (WebCore::ScrollingTreeIOS::currentSnapPointIndicesDidChange):
     65        (WebCore::ScrollingTreeIOS::createScrollingTreeNode): Deleted.
     66        * page/scrolling/mac/ScrollingTreeFrameScrollingNodeMac.mm:
     67        (WebCore::ScrollingTreeFrameScrollingNodeMac::releaseReferencesToScrollerImpsOnTheMainThread):
     68        * platform/MemoryPressureHandler.cpp:
     69        (WebCore::MemoryPressureHandler::releaseMemory):
     70        * platform/audio/ios/MediaSessionManagerIOS.mm:
     71        (-[WebMediaSessionHelper dealloc]):
     72        (-[WebMediaSessionHelper startMonitoringAirPlayRoutes]):
     73        (-[WebMediaSessionHelper stopMonitoringAirPlayRoutes]):
     74        * platform/graphics/avfoundation/AudioSourceProviderAVFObjC.mm:
     75        (WebCore::AudioSourceProviderAVFObjC::prepare):
     76        * platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp:
     77        (WebCore::MediaPlayerPrivateAVFoundation::scheduleMainThreadNotification):
     78        (WebCore::MediaPlayerPrivateAVFoundation::dispatchNotification):
     79        * platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.mm:
     80        (-[WebCDMSessionAVFoundationObjCListener observeValueForKeyPath:ofObject:change:context:]):
     81        * platform/graphics/avfoundation/objc/MediaPlaybackTargetPickerMac.mm:
     82        (-[WebAVOutputDeviceMenuControllerHelper observeValueForKeyPath:ofObject:change:context:]):
     83        * platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm:
     84        (WebCore::MediaPlayerPrivateAVFoundationObjC::createVideoLayer):
     85        (-[WebCoreAVFMovieObserver legibleOutput:didOutputAttributedStrings:nativeSampleBuffers:forItemTime:]):
     86        (-[WebCoreAVFMovieObserver outputSequenceWasFlushed:]):
     87        (-[WebCoreAVFLoaderDelegate resourceLoader:shouldWaitForLoadingOfRequestedResource:]):
     88        (-[WebCoreAVFLoaderDelegate resourceLoader:shouldWaitForResponseToAuthenticationChallenge:]):
     89        (-[WebCoreAVFLoaderDelegate resourceLoader:didCancelLoadingRequest:]):
     90        * platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaSourceAVFObjC.mm:
     91        (WebCore::CMTimebaseEffectiveRateChangedCallback):
     92        (WebCore::MediaPlayerPrivateMediaSourceAVFObjC::play):
     93        (WebCore::MediaPlayerPrivateMediaSourceAVFObjC::pause):
     94        * platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.h:
     95        * platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm:
     96        (WebCore::MediaPlayerPrivateMediaStreamAVFObjC::scheduleDeferredTask):
     97        * platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.mm:
     98        (-[WebAVStreamDataParserListener streamDataParser:didParseStreamDataAsAsset:]):
     99        (-[WebAVStreamDataParserListener streamDataParser:didParseStreamDataAsAsset:withDiscontinuity:]):
     100        (-[WebAVStreamDataParserListener streamDataParser:didFailToParseStreamDataWithError:]):
     101        (-[WebAVStreamDataParserListener streamDataParser:didProvideMediaData:forTrackID:mediaType:flags:]):
     102        (-[WebAVStreamDataParserListener streamDataParser:didReachEndOfTrackWithTrackID:mediaType:]):
     103        (-[WebAVStreamDataParserListener streamDataParser:didProvideContentKeyRequestInitializationData:forTrackID:]):
     104        (-[WebAVSampleBufferErrorListener observeValueForKeyPath:ofObject:change:context:]):
     105        (-[WebAVSampleBufferErrorListener layerFailedToDecode:]):
     106        * platform/graphics/cg/GraphicsContextCG.cpp:
     107        (WebCore::patternReleaseCallback):
     108        * platform/graphics/cg/PatternCG.cpp:
     109        (WebCore::patternReleaseCallback):
     110        * platform/graphics/win/MediaPlayerPrivateMediaFoundation.cpp:
     111        (WebCore::MediaPlayerPrivateMediaFoundation::endCreatedMediaSource):
     112        (WebCore::MediaPlayerPrivateMediaFoundation::endGetEvent):
     113        (WebCore::MediaPlayerPrivateMediaFoundation::CustomVideoPresenter::processInputNotify):
     114        * platform/mediastream/MediaStreamPrivate.cpp:
     115        (WebCore::MediaStreamPrivate::scheduleDeferredTask):
     116        * platform/mediastream/MediaStreamPrivate.h:
     117        * platform/mediastream/mac/AVMediaCaptureSource.h:
     118        * platform/mediastream/mac/AVMediaCaptureSource.mm:
     119        (WebCore::AVMediaCaptureSource::scheduleDeferredTask):
     120        * platform/mediastream/mac/RealtimeMediaSourceCenterMac.cpp:
     121        (WebCore::RealtimeMediaSourceCenterMac::getMediaStreamTrackSources):
     122        * platform/mediastream/mac/WebAudioSourceProviderAVFObjC.mm:
     123        (WebCore::WebAudioSourceProviderAVFObjC::prepare):
     124        * platform/mock/MockRealtimeMediaSourceCenter.cpp:
     125        (WebCore::MockRealtimeMediaSourceCenter::getMediaStreamTrackSources):
     126        * platform/network/BlobResourceHandle.cpp:
     127        (WebCore::BlobResourceHandle::start):
     128        (WebCore::BlobResourceHandle::notifyFinish):
     129        * platform/network/DataURLDecoder.cpp:
     130        (WebCore::DataURLDecoder::decode):
     131        * platform/network/DataURLDecoder.h:
     132        * platform/network/cocoa/WebCoreNSURLSession.mm:
     133        (-[WebCoreNSURLSession dealloc]):
     134        (-[WebCoreNSURLSessionDataTask cancel]):
     135        (-[WebCoreNSURLSessionDataTask suspend]):
     136        (-[WebCoreNSURLSessionDataTask resume]):
     137        * platform/network/curl/CurlDownload.cpp:
     138        (WebCore::CurlDownload::didReceiveHeader):
     139        (WebCore::CurlDownload::didReceiveData): Deleted.
     140
    11412016-05-27  Tim Horton  <timothy_horton@apple.com>
    2142
  • trunk/Source/WebCore/Modules/indexeddb/IDBTransaction.cpp

    r201461 r201482  
    980980        // In that case, we cannot successfully store this record, so we callback with an error.
    981981        auto result = IDBResultData::error(protectedOperation->identifier(), { IDBDatabaseException::UnknownError, ASCIILiteral("Error preparing Blob/File data to be stored in object store") });
    982         callOnMainThread([protectedThis = WTFMove(protectedThis), this, protectedOperation = WTFMove(protectedOperation), result = WTFMove(result)]() {
     982        callOnMainThread([protectedThis = WTFMove(protectedThis), protectedOperation = WTFMove(protectedOperation), result = WTFMove(result)]() {
    983983            protectedOperation->completed(result);
    984984        });
  • trunk/Source/WebCore/Modules/mediastream/MediaDevicesRequest.cpp

    r200361 r201482  
    9393    m_havePersistentPermission = canAccess;
    9494
    95     callOnMainThread([this, permissionCheckProtector] {
     95    callOnMainThread([this, permissionCheckProtector = WTFMove(permissionCheckProtector)] {
    9696        RealtimeMediaSourceCenter::singleton().getMediaStreamTrackSources(this);
    9797    });
     
    161161    }
    162162
    163     RefPtr<MediaDevicesRequest> protectedThis(this);
    164     callOnMainThread([protectedThis, devices] {
     163    callOnMainThread([protectedThis = Ref<MediaDevicesRequest>(*this), devices = WTFMove(devices)]() mutable {
    165164        protectedThis->m_promise.resolve(devices);
    166165    });
  • trunk/Source/WebCore/Modules/mediastream/MediaEndpointPeerConnection.cpp

    r201420 r201482  
    9696}
    9797
    98 void MediaEndpointPeerConnection::runTask(std::function<void()> task)
     98void MediaEndpointPeerConnection::runTask(NoncopyableFunction&& task)
    9999{
    100100    if (m_dtlsFingerprint.isNull()) {
    101101        // Only one task needs to be deferred since it will hold off any others until completed.
    102102        ASSERT(!m_initialDeferredTask);
    103         m_initialDeferredTask = task;
     103        m_initialDeferredTask = WTFMove(task);
    104104    } else
    105         callOnMainThread(task);
     105        callOnMainThread(WTFMove(task));
    106106}
    107107
  • trunk/Source/WebCore/Modules/mediastream/MediaEndpointPeerConnection.h

    r198492 r201482  
    3838#include "PeerConnectionBackend.h"
    3939#include "RTCSessionDescription.h"
     40#include <wtf/NoncopyableFunction.h>
    4041#include <wtf/RefPtr.h>
    4142
     
    7879
    7980private:
    80     void runTask(std::function<void()>);
     81    void runTask(NoncopyableFunction&&);
    8182    void startRunningTasks();
    8283
     
    9293    std::unique_ptr<MediaEndpoint> m_mediaEndpoint;
    9394
    94     std::function<void()> m_initialDeferredTask;
     95    NoncopyableFunction m_initialDeferredTask;
    9596
    9697    std::unique_ptr<SDPProcessor> m_sdpProcessor;
  • trunk/Source/WebCore/Modules/mediastream/UserMediaRequest.cpp

    r201080 r201482  
    136136        m_videoDeviceUIDs.append(videoTrack->persistentID());
    137137
    138     RefPtr<UserMediaRequest> protectedThis(this);
    139     callOnMainThread([protectedThis] {
     138    callOnMainThread([protectedThis = Ref<UserMediaRequest>(*this)]() mutable {
    140139        // 2 - The constraints are valid, ask the user for access to media.
    141140        if (UserMediaController* controller = protectedThis->m_controller)
    142             controller->requestUserMediaAccess(*protectedThis.get());
     141            controller->requestUserMediaAccess(protectedThis.get());
    143142    });
    144143}
     
    149148    m_audioDeviceUIDAllowed = audioDeviceUID;
    150149
    151     RefPtr<UserMediaRequest> protectedThis(this);
    152     callOnMainThread([protectedThis, audioDeviceUID, videoDeviceUID] {
     150    callOnMainThread([protectedThis = Ref<UserMediaRequest>(*this), audioDeviceUID, videoDeviceUID]() mutable {
    153151        // 3 - the user granted access, ask platform to create the media stream descriptors.
    154         RealtimeMediaSourceCenter::singleton().createMediaStream(protectedThis.get(), audioDeviceUID, videoDeviceUID);
     152        RealtimeMediaSourceCenter::singleton().createMediaStream(protectedThis.ptr(), audioDeviceUID, videoDeviceUID);
    155153    });
    156154}
  • trunk/Source/WebCore/Modules/webaudio/AudioContext.cpp

    r200895 r201482  
    798798        m_isDeletionScheduled = true;
    799799
    800         RefPtr<AudioContext> protectedThis(this);
    801         callOnMainThread([protectedThis] {
     800        callOnMainThread([protectedThis = Ref<AudioContext>(*this)]() mutable {
    802801            protectedThis->deleteMarkedNodes();
    803802        });
     
    10031002    // Make sure to call Document::updateIsPlayingMedia() on the main thread, since
    10041003    // we could be on the audio I/O thread here and the call into WebCore could block.
    1005     RefPtr<AudioContext> protectedThis(this);
    1006     callOnMainThread([protectedThis] {
     1004    callOnMainThread([protectedThis = Ref<AudioContext>(*this)] {
    10071005        if (protectedThis->document())
    10081006            protectedThis->document()->updateIsPlayingMedia();
  • trunk/Source/WebCore/dom/Document.cpp

    r201471 r201482  
    53875387void Document::postTask(Task task)
    53885388{
    5389     Task* taskPtr = std::make_unique<Task>(WTFMove(task)).release();
    5390     WeakPtr<Document> documentReference(m_weakFactory.createWeakPtr());
    5391 
    5392     callOnMainThread([=] {
     5389    callOnMainThread([documentReference = m_weakFactory.createWeakPtr(), task = WTFMove(task)]() mutable {
    53935390        ASSERT(isMainThread());
    5394         std::unique_ptr<Task> task(taskPtr);
    53955391
    53965392        Document* document = documentReference.get();
     
    54005396        Page* page = document->page();
    54015397        if ((page && page->defersLoading() && document->activeDOMObjectsAreSuspended()) || !document->m_pendingTasks.isEmpty())
    5402             document->m_pendingTasks.append(WTFMove(*task.release()));
     5398            document->m_pendingTasks.append(WTFMove(task));
    54035399        else
    5404             task->performTask(*document);
     5400            task.performTask(*document);
    54055401    });
    54065402}
  • trunk/Source/WebCore/dom/ScriptElement.cpp

    r200327 r201482  
    281281        return true;
    282282
    283     RefPtr<Element> element = &m_element;
    284     callOnMainThread([this, element] {
     283    callOnMainThread([this, element = Ref<Element>(m_element)] {
    285284        dispatchErrorEvent();
    286285    });
  • trunk/Source/WebCore/fileapi/AsyncFileStream.cpp

    r201354 r201482  
    4040#include <wtf/MessageQueue.h>
    4141#include <wtf/NeverDestroyed.h>
     42#include <wtf/NoncopyableFunction.h>
    4243
    4344namespace WebCore {
     
    6465}
    6566
    66 static void callOnFileThread(std::function<void()>&& function)
     67static void callOnFileThread(NoncopyableFunction&& function)
    6768{
    6869    ASSERT(isMainThread());
    6970    ASSERT(function);
    7071
    71     static NeverDestroyed<MessageQueue<std::function<void()>>> queue;
     72    static NeverDestroyed<MessageQueue<NoncopyableFunction>> queue;
    7273
    7374    static std::once_flag createFileThreadOnce;
     
    9091    });
    9192
    92     queue.get().append(std::make_unique<std::function<void()>>(WTFMove(function)));
     93    queue.get().append(std::make_unique<NoncopyableFunction>(WTFMove(function)));
    9394}
    9495
     
    103104    ASSERT(isMainThread());
    104105
    105     // Release so that we can control the timing of deletion below.
    106     auto& internals = *m_internals.release();
    107 
    108106    // Set flag to prevent client callbacks and also prevent queued operations from starting.
    109     internals.destroyed = true;
     107    m_internals->destroyed = true;
    110108
    111109    // Call through file thread and back to main thread to make sure deletion happens
    112110    // after all file thread functions and all main thread functions called from them.
    113     callOnFileThread([&internals] {
    114         callOnMainThread([&internals] {
    115             delete &internals;
     111    callOnFileThread([internals = WTFMove(m_internals)]() mutable {
     112        callOnMainThread([internals = WTFMove(internals)] {
    116113        });
    117114    });
    118115}
    119116
    120 void AsyncFileStream::perform(std::function<std::function<void(FileStreamClient&)>(FileStream&)> operation)
     117void AsyncFileStream::perform(std::function<std::function<void(FileStreamClient&)>(FileStream&)>&& operation)
    121118{
    122119    auto& internals = *m_internals;
    123     callOnFileThread([&internals, operation] {
     120    callOnFileThread([&internals, operation = WTFMove(operation)] {
    124121        // Don't do the operation if stop was already called on the main thread. Note that there is
    125122        // a race here, but since skipping the operation is an optimization it's OK that we can't
     
    128125        if (internals.destroyed)
    129126            return;
    130         auto mainThreadWork = operation(internals.stream);
    131         callOnMainThread([&internals, mainThreadWork] {
     127        callOnMainThread([&internals, mainThreadWork = operation(internals.stream)] {
    132128            if (internals.destroyed)
    133129                return;
  • trunk/Source/WebCore/fileapi/AsyncFileStream.h

    r175782 r201482  
    5757private:
    5858    void start();
    59     void perform(std::function<std::function<void(FileStreamClient&)>(FileStream&)>);
     59    void perform(std::function<std::function<void(FileStreamClient&)>(FileStream&)>&&);
    6060
    6161    struct Internals;
  • trunk/Source/WebCore/fileapi/ThreadableBlobRegistry.cpp

    r199708 r201482  
    118118    else {
    119119        // BlobRegistryContext performs an isolated copy of data.
    120         BlobRegistryContext* context = new BlobRegistryContext(url, path, contentType);
    121         callOnMainThread([context] {
    122             std::unique_ptr<BlobRegistryContext> blobRegistryContext(context);
    123             blobRegistry().registerFileBlobURL(blobRegistryContext->url, BlobDataFileReference::create(blobRegistryContext->path), blobRegistryContext->contentType);
     120        callOnMainThread([context = std::make_unique<BlobRegistryContext>(url, path, contentType)] {
     121            blobRegistry().registerFileBlobURL(context->url, BlobDataFileReference::create(context->path), context->contentType);
    124122        });
    125123    }
     
    132130    else {
    133131        // BlobRegistryContext performs an isolated copy of data.
    134         BlobRegistryContext* context = new BlobRegistryContext(url, WTFMove(blobParts), contentType);
    135         callOnMainThread([context] {
    136             std::unique_ptr<BlobRegistryContext> blobRegistryContext(context);
    137             blobRegistry().registerBlobURL(blobRegistryContext->url, WTFMove(blobRegistryContext->blobParts), blobRegistryContext->contentType);
     132        callOnMainThread([context = std::make_unique<BlobRegistryContext>(url, WTFMove(blobParts), contentType)] {
     133            blobRegistry().registerBlobURL(context->url, WTFMove(context->blobParts), context->contentType);
    138134        });
    139135    }
     
    150146    else {
    151147        // BlobRegistryContext performs an isolated copy of data.
    152         BlobRegistryContext* context = new BlobRegistryContext(url, srcURL);
    153         callOnMainThread([context] {
    154             std::unique_ptr<BlobRegistryContext> blobRegistryContext(context);
    155             blobRegistry().registerBlobURL(blobRegistryContext->url, blobRegistryContext->srcURL);
     148        callOnMainThread([context = std::make_unique<BlobRegistryContext>(url, srcURL)] {
     149            blobRegistry().registerBlobURL(context->url, context->srcURL);
    156150        });
    157151    }
     
    179173    else {
    180174        // BlobRegistryContext performs an isolated copy of data.
    181         BlobRegistryContext* context = new BlobRegistryContext(newURL, srcURL);
    182         callOnMainThread([context, start, end] {
    183             std::unique_ptr<BlobRegistryContext> blobRegistryContext(context);
    184             blobRegistry().registerBlobURLForSlice(blobRegistryContext->url, blobRegistryContext->srcURL, start, end);
     175        callOnMainThread([context = std::make_unique<BlobRegistryContext>(newURL, srcURL), start, end] {
     176            blobRegistry().registerBlobURLForSlice(context->url, context->srcURL, start, end);
    185177        });
    186178    }
     
    194186    else {
    195187        // BlobRegistryContext performs an isolated copy of data.
    196         BlobRegistryContext* context = new BlobRegistryContext(url);
    197188        BinarySemaphore semaphore;
    198         callOnMainThread([context, &semaphore, &resultSize] {
    199             std::unique_ptr<BlobRegistryContext> blobRegistryContext(context);
    200             resultSize = blobRegistry().blobSize(blobRegistryContext->url);
     189        callOnMainThread([context = std::make_unique<BlobRegistryContext>(url), &semaphore, &resultSize] {
     190            resultSize = blobRegistry().blobSize(context->url);
    201191            semaphore.signal();
    202192        });
     
    215205    else {
    216206        // BlobRegistryContext performs an isolated copy of data.
    217         BlobRegistryContext* context = new BlobRegistryContext(url);
    218         callOnMainThread([context] {
    219             std::unique_ptr<BlobRegistryContext> blobRegistryContext(context);
    220             blobRegistry().unregisterBlobURL(blobRegistryContext->url);
     207        callOnMainThread([context = std::make_unique<BlobRegistryContext>(url)] {
     208            blobRegistry().unregisterBlobURL(context->url);
    221209        });
    222210    }
  • trunk/Source/WebCore/loader/icon/IconDatabase.cpp

    r198655 r201482  
    20912091    ++m_mainThreadCallbackCount;
    20922092
    2093     String pageURLCopy = pageURL.isolatedCopy();
    2094     callOnMainThread([this, pageURLCopy] {
     2093    callOnMainThread([this, pageURL = pageURL.isolatedCopy()] {
    20952094        if (m_client)
    2096             m_client->didImportIconURLForPageURL(pageURLCopy);
     2095            m_client->didImportIconURLForPageURL(pageURL);
    20972096        checkClosedAfterMainThreadCallback();
    20982097    });
     
    21042103    ++m_mainThreadCallbackCount;
    21052104
    2106     String pageURLCopy = pageURL.isolatedCopy();
    2107     callOnMainThread([this, pageURLCopy] {
     2105    callOnMainThread([this, pageURL = pageURL.isolatedCopy()] {
    21082106        if (m_client)
    2109             m_client->didImportIconDataForPageURL(pageURLCopy);
     2107            m_client->didImportIconDataForPageURL(pageURL);
    21102108        checkClosedAfterMainThreadCallback();
    21112109    });
  • trunk/Source/WebCore/page/ResourceUsageThread.cpp

    r195644 r201482  
    7878}
    7979
    80 void ResourceUsageThread::notifyObservers(ResourceUsageData& data)
     80void ResourceUsageThread::notifyObservers(ResourceUsageData&& data)
    8181{
    82     callOnMainThread([data]() mutable {
     82    callOnMainThread([data = WTFMove(data)]() mutable {
    8383        Vector<std::function<void (const ResourceUsageData&)>> functions;
    8484       
     
    118118        ResourceUsageData data;
    119119        platformThreadBody(m_vm, data);
    120         notifyObservers(data);
     120        notifyObservers(WTFMove(data));
    121121
    122122        auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::system_clock::now() - start);
  • trunk/Source/WebCore/page/ResourceUsageThread.h

    r196780 r201482  
    5757
    5858    void waitUntilObservers();
    59     void notifyObservers(ResourceUsageData&);
     59    void notifyObservers(ResourceUsageData&&);
    6060
    6161    void createThreadIfNeeded();
  • trunk/Source/WebCore/page/scrolling/ScrollingThread.cpp

    r200561 r201482  
    4646}
    4747
    48 void ScrollingThread::dispatch(std::function<void ()> function)
     48void ScrollingThread::dispatch(NoncopyableFunction&& function)
    4949{
    5050    auto& scrollingThread = ScrollingThread::singleton();
     
    5353    {
    5454        std::lock_guard<Lock> lock(scrollingThread.m_functionsMutex);
    55         scrollingThread.m_functions.append(function);
     55        scrollingThread.m_functions.append(WTFMove(function));
    5656    }
    5757
     
    5959}
    6060
    61 void ScrollingThread::dispatchBarrier(std::function<void ()> function)
     61void ScrollingThread::dispatchBarrier(NoncopyableFunction&& function)
    6262{
    63     dispatch([function]() mutable {
     63    dispatch([function = WTFMove(function)]() mutable {
    6464        callOnMainThread(WTFMove(function));
    6565    });
     
    105105    ASSERT(isCurrentThread());
    106106
    107     Vector<std::function<void ()>> functions;
     107    Vector<NoncopyableFunction> functions;
    108108   
    109109    {
  • trunk/Source/WebCore/page/scrolling/ScrollingThread.h

    r188642 r201482  
    3434#include <wtf/Lock.h>
    3535#include <wtf/Noncopyable.h>
     36#include <wtf/NoncopyableFunction.h>
    3637#include <wtf/Threading.h>
    3738#include <wtf/Vector.h>
     
    4849public:
    4950    static bool isCurrentThread();
    50     WEBCORE_EXPORT static void dispatch(std::function<void ()>);
     51    WEBCORE_EXPORT static void dispatch(NoncopyableFunction&&);
    5152
    5253    // Will dispatch the given function on the main thread once all pending functions
    5354    // on the scrolling thread have finished executing. Used for synchronization purposes.
    54     WEBCORE_EXPORT static void dispatchBarrier(std::function<void ()>);
     55    WEBCORE_EXPORT static void dispatchBarrier(NoncopyableFunction&&);
    5556
    5657private:
     
    8081
    8182    Lock m_functionsMutex;
    82     Vector<std::function<void ()>> m_functions;
     83    Vector<NoncopyableFunction> m_functions;
    8384
    8485#if PLATFORM(COCOA)
  • trunk/Source/WebCore/page/scrolling/ios/ScrollingTreeIOS.cpp

    r194496 r201482  
    6868    // we need to release it on the main thread since it has member variables (such as timers)
    6969    // that expect to be destroyed from the main thread.
    70     ScrollingCoordinator* scrollingCoordinator = m_scrollingCoordinator.release().leakRef();
    71     callOnMainThread([scrollingCoordinator] {
    72         scrollingCoordinator->deref();
     70    callOnMainThread([scrollingCoordinator = WTFMove(m_scrollingCoordinator)] {
    7371    });
    7472}
     
    8785        setMainFrameScrollPosition(scrollPosition);
    8886
    89     RefPtr<AsyncScrollingCoordinator> scrollingCoordinator = m_scrollingCoordinator;
    90     bool localIsHandlingProgrammaticScroll = isHandlingProgrammaticScroll();
    91 
    92     callOnMainThread([scrollingCoordinator, nodeID, scrollPosition, localIsHandlingProgrammaticScroll, scrollingLayerPositionAction] {
     87    callOnMainThread([scrollingCoordinator = m_scrollingCoordinator, nodeID, scrollPosition, localIsHandlingProgrammaticScroll = isHandlingProgrammaticScroll(), scrollingLayerPositionAction] {
    9388        scrollingCoordinator->scheduleUpdateScrollPositionAfterAsyncScroll(nodeID, scrollPosition, localIsHandlingProgrammaticScroll, scrollingLayerPositionAction);
    9489    });
     
    124119        return;
    125120   
    126     RefPtr<AsyncScrollingCoordinator> scrollingCoordinator = m_scrollingCoordinator;
    127     callOnMainThread([scrollingCoordinator, nodeID, horizontal, vertical] {
     121    callOnMainThread([scrollingCoordinator = m_scrollingCoordinator, nodeID, horizontal, vertical] {
    128122        scrollingCoordinator->setActiveScrollSnapIndices(nodeID, horizontal, vertical);
    129123    });
  • trunk/Source/WebCore/page/scrolling/mac/ScrollingTreeFrameScrollingNodeMac.mm

    r198078 r201482  
    7676        // FIXME: This is a workaround in place for the time being since NSScrollerImps cannot be deallocated
    7777        // on a non-main thread. rdar://problem/24535055
    78         NSScrollerImp *retainedVerticalScrollerImp = m_verticalScrollerImp.leakRef();
    79         NSScrollerImp *retainedHorizontalScrollerImp = m_horizontalScrollerImp.leakRef();
    80         WTF::callOnMainThread([retainedVerticalScrollerImp, retainedHorizontalScrollerImp] {
    81             [retainedVerticalScrollerImp release];
    82             [retainedHorizontalScrollerImp release];
     78        WTF::callOnMainThread([verticalScrollerImp = WTFMove(m_verticalScrollerImp), horizontalScrollerImp = WTFMove(m_horizontalScrollerImp)] {
    8379        });
    8480    }
  • trunk/Source/WebCore/platform/MemoryPressureHandler.cpp

    r201162 r201482  
    173173        WorkerThread::releaseFastMallocFreeMemoryInAllThreads();
    174174#if ENABLE(ASYNC_SCROLLING) && !PLATFORM(IOS)
    175         ScrollingThread::dispatch(WTF::releaseFastMallocFreeMemory);
     175        ScrollingThread::dispatch([]() {
     176            WTF::releaseFastMallocFreeMemory();
     177        });
    176178#endif
    177179        WTF::releaseFastMallocFreeMemory();
  • trunk/Source/WebCore/platform/audio/ios/MediaSessionManagerIOS.mm

    r200466 r201482  
    397397
    398398    if (!isMainThread()) {
    399         auto volumeView = WTFMove(_volumeView);
    400         auto routingController = WTFMove(_airPlayPresenceRoutingController);
    401 
    402         callOnMainThread([volumeView, routingController] () mutable {
     399        callOnMainThread([volumeView = WTFMove(_volumeView), routingController = WTFMove(_airPlayPresenceRoutingController)] () mutable {
    403400            LOG(Media, "-[WebMediaSessionHelper dealloc] - dipatched to MainThread");
    404401
     
    436433    LOG(Media, "-[WebMediaSessionHelper startMonitoringAirPlayRoutes]");
    437434
    438     RetainPtr<WebMediaSessionHelper> strongSelf = self;
    439     callOnMainThread([strongSelf] () {
     435    callOnMainThread([protectedSelf = RetainPtr<WebMediaSessionHelper>(self)] () {
    440436        LOG(Media, "-[WebMediaSessionHelper startMonitoringAirPlayRoutes] - dipatched to MainThread");
    441437
    442         if (strongSelf->_airPlayPresenceRoutingController)
    443             return;
    444 
    445         strongSelf->_airPlayPresenceRoutingController = adoptNS([allocMPAVRoutingControllerInstance() initWithName:@"WebCore - HTML media element checking for AirPlay route presence"]);
    446         [strongSelf->_airPlayPresenceRoutingController setDiscoveryMode:MPRouteDiscoveryModePresence];
     438        if (protectedSelf->_airPlayPresenceRoutingController)
     439            return;
     440
     441        protectedSelf->_airPlayPresenceRoutingController = adoptNS([allocMPAVRoutingControllerInstance() initWithName:@"WebCore - HTML media element checking for AirPlay route presence"]);
     442        [protectedSelf->_airPlayPresenceRoutingController setDiscoveryMode:MPRouteDiscoveryModePresence];
    447443    });
    448444}
     
    455451    LOG(Media, "-[WebMediaSessionHelper stopMonitoringAirPlayRoutes]");
    456452
    457     RetainPtr<WebMediaSessionHelper> strongSelf = self;
    458     callOnMainThread([strongSelf] () {
     453    callOnMainThread([protectedSelf = RetainPtr<WebMediaSessionHelper>(self)] () {
    459454        LOG(Media, "-[WebMediaSessionHelper stopMonitoringAirPlayRoutes] - dipatched to MainThread");
    460455
    461         if (!strongSelf->_airPlayPresenceRoutingController)
    462             return;
    463 
    464         [strongSelf->_airPlayPresenceRoutingController setDiscoveryMode:MPRouteDiscoveryModeDisabled];
    465         strongSelf->_airPlayPresenceRoutingController = nil;
     456        if (!protectedSelf->_airPlayPresenceRoutingController)
     457            return;
     458
     459        [protectedSelf->_airPlayPresenceRoutingController setDiscoveryMode:MPRouteDiscoveryModeDisabled];
     460        protectedSelf->_airPlayPresenceRoutingController = nil;
    466461    });
    467462}
  • trunk/Source/WebCore/platform/graphics/avfoundation/AudioSourceProviderAVFObjC.mm

    r198654 r201482  
    324324    m_list->mNumberBuffers = numberOfChannels;
    325325
    326     RefPtr<AudioSourceProviderAVFObjC> strongThis = this;
    327     callOnMainThread([strongThis, numberOfChannels, sampleRate] {
    328         strongThis->m_client->setFormat(numberOfChannels, sampleRate);
     326    callOnMainThread([protectedThis = Ref<AudioSourceProviderAVFObjC>(*this), numberOfChannels, sampleRate] {
     327        protectedThis->m_client->setFormat(numberOfChannels, sampleRate);
    329328    });
    330329}
  • trunk/Source/WebCore/platform/graphics/avfoundation/MediaPlayerPrivateAVFoundation.cpp

    r200675 r201482  
    807807        m_mainThreadCallPending = true;
    808808
    809         auto weakThis = createWeakPtr();
    810         callOnMainThread([weakThis] {
     809        callOnMainThread([weakThis = createWeakPtr()] {
    811810            if (!weakThis)
    812811                return;
     
    845844       
    846845        if (!m_queuedNotifications.isEmpty() && !m_mainThreadCallPending) {
    847             auto weakThis = createWeakPtr();
    848             callOnMainThread([weakThis] {
     846            callOnMainThread([weakThis = createWeakPtr()] {
    849847                if (!weakThis)
    850848                    return;
  • trunk/Source/WebCore/platform/graphics/avfoundation/objc/CDMSessionAVFoundationObjC.mm

    r199672 r201482  
    8585        if ([[change valueForKey:NSKeyValueChangeNewKey] intValue] == 1) {
    8686            RetainPtr<NSError> error = [NSError errorWithDomain:@"com.apple.WebKit" code:'HDCP' userInfo:nil];
    87             RetainPtr<WebCDMSessionAVFoundationObjCListener> strongSelf = { self };
    88             callOnMainThread([strongSelf, error] {
    89                 if (strongSelf->_parent)
    90                     strongSelf->_parent->playerDidReceiveError(error.get());
     87            RetainPtr<WebCDMSessionAVFoundationObjCListener> protectedSelf = { self };
     88            callOnMainThread([protectedSelf = WTFMove(protectedSelf), error = WTFMove(error)] {
     89                if (protectedSelf->_parent)
     90                    protectedSelf->_parent->playerDidReceiveError(error.get());
    9191            });
    9292        }
  • trunk/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlaybackTargetPickerMac.mm

    r199701 r201482  
    186186        return;
    187187
    188     RetainPtr<WebAVOutputDeviceMenuControllerHelper> strongSelf = self;
    189     RetainPtr<NSString> strongKeyPath = keyPath;
    190     callOnMainThread([strongSelf, strongKeyPath] {
    191         MediaPlaybackTargetPickerMac* callback = strongSelf->m_callback;
     188    RetainPtr<WebAVOutputDeviceMenuControllerHelper> protectedSelf = self;
     189    RetainPtr<NSString> protectedKeyPath = keyPath;
     190    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedKeyPath = WTFMove(protectedKeyPath)] {
     191        MediaPlaybackTargetPickerMac* callback = protectedSelf->m_callback;
    192192        if (!callback)
    193193            return;
    194194
    195         if ([strongKeyPath isEqualToString:externalOutputDeviceAvailableKeyName])
     195        if ([protectedKeyPath isEqualToString:externalOutputDeviceAvailableKeyName])
    196196            callback->availableDevicesDidChange();
    197         else if ([strongKeyPath isEqualToString:externalOutputDevicePickedKeyName])
     197        else if ([protectedKeyPath isEqualToString:externalOutputDevicePickedKeyName])
    198198            callback->currentDeviceDidChange();
    199199    });
  • trunk/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateAVFoundationObjC.mm

    r201474 r201482  
    702702        return;
    703703
    704     auto weakThis = createWeakPtr();
    705     callOnMainThread([this, weakThis] {
     704    callOnMainThread([this, weakThis = createWeakPtr()] {
    706705        if (!weakThis)
    707706            return;
     
    34423441        return;
    34433442
    3444     RetainPtr<WebCoreAVFMovieObserver> strongSelf = self;
    3445     RetainPtr<NSArray> strongStrings = strings;
    3446     RetainPtr<NSArray> strongSamples = nativeSamples;
    3447     callOnMainThread([strongSelf, strongStrings, strongSamples, itemTime] {
    3448         MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback;
     3443    RetainPtr<WebCoreAVFMovieObserver> protectedSelf = self;
     3444    RetainPtr<NSArray> protectedStrings = strings;
     3445    RetainPtr<NSArray> protectedNativeSamples = nativeSamples;
     3446    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedStrings = WTFMove(protectedStrings), protectedNativeSamples = WTFMove(protectedNativeSamples), itemTime] {
     3447        MediaPlayerPrivateAVFoundationObjC* callback = protectedSelf->m_callback;
    34493448        if (!callback)
    34503449            return;
    34513450        MediaTime time = std::max(toMediaTime(itemTime), MediaTime::zeroTime());
    3452         callback->processCue(strongStrings.get(), strongSamples.get(), time);
     3451        callback->processCue(protectedStrings.get(), protectedNativeSamples.get(), time);
    34533452    });
    34543453}
     
    34613460        return;
    34623461   
    3463     RetainPtr<WebCoreAVFMovieObserver> strongSelf = self;
    3464     callOnMainThread([strongSelf] {
    3465         if (MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback)
     3462    callOnMainThread([protectedSelf = RetainPtr<WebCoreAVFMovieObserver>(self)] {
     3463        if (MediaPlayerPrivateAVFoundationObjC* callback = protectedSelf->m_callback)
    34663464            callback->flushCues();
    34673465    });
     
    34893487        return NO;
    34903488
    3491     RetainPtr<WebCoreAVFLoaderDelegate> strongSelf = self;
    3492     RetainPtr<AVAssetResourceLoadingRequest> strongRequest = loadingRequest;
    3493     callOnMainThread([strongSelf, strongRequest] {
    3494         MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback;
     3489    RetainPtr<WebCoreAVFLoaderDelegate> protectedSelf = self;
     3490    RetainPtr<AVAssetResourceLoadingRequest> protectedLoadingRequest = loadingRequest;
     3491    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedLoadingRequest = WTFMove(protectedLoadingRequest)] {
     3492        MediaPlayerPrivateAVFoundationObjC* callback = protectedSelf->m_callback;
    34953493        if (!callback) {
    3496             [strongRequest finishLoadingWithError:nil];
     3494            [protectedLoadingRequest finishLoadingWithError:nil];
    34973495            return;
    34983496        }
    34993497
    3500         if (!callback->shouldWaitForLoadingOfResource(strongRequest.get()))
    3501             [strongRequest finishLoadingWithError:nil];
     3498        if (!callback->shouldWaitForLoadingOfResource(protectedLoadingRequest.get()))
     3499            [protectedLoadingRequest finishLoadingWithError:nil];
    35023500    });
    35033501
     
    35143512        return NO;
    35153513
    3516     RetainPtr<WebCoreAVFLoaderDelegate> strongSelf = self;
    3517     RetainPtr<NSURLAuthenticationChallenge> strongChallenge = challenge;
    3518     callOnMainThread([strongSelf, strongChallenge] {
    3519         MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback;
     3514    RetainPtr<WebCoreAVFLoaderDelegate> protectedSelf = self;
     3515    RetainPtr<NSURLAuthenticationChallenge> protectedChallenge = challenge;
     3516    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedChallenge = WTFMove(protectedChallenge)] {
     3517        MediaPlayerPrivateAVFoundationObjC* callback = protectedSelf->m_callback;
    35203518        if (!callback) {
    3521             [[strongChallenge sender] cancelAuthenticationChallenge:strongChallenge.get()];
     3519            [[protectedChallenge sender] cancelAuthenticationChallenge:protectedChallenge.get()];
    35223520            return;
    35233521        }
    35243522
    3525         if (!callback->shouldWaitForResponseToAuthenticationChallenge(strongChallenge.get()))
    3526             [[strongChallenge sender] cancelAuthenticationChallenge:strongChallenge.get()];
     3523        if (!callback->shouldWaitForResponseToAuthenticationChallenge(protectedChallenge.get()))
     3524            [[protectedChallenge sender] cancelAuthenticationChallenge:protectedChallenge.get()];
    35273525    });
    35283526
     
    35363534        return;
    35373535
    3538     RetainPtr<WebCoreAVFLoaderDelegate> strongSelf = self;
    3539     RetainPtr<AVAssetResourceLoadingRequest> strongRequest = loadingRequest;
    3540     callOnMainThread([strongSelf, strongRequest] {
    3541         MediaPlayerPrivateAVFoundationObjC* callback = strongSelf->m_callback;
     3536    RetainPtr<WebCoreAVFLoaderDelegate> protectedSelf = self;
     3537    RetainPtr<AVAssetResourceLoadingRequest> protectedLoadingRequest = loadingRequest;
     3538    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedLoadingRequest = WTFMove(protectedLoadingRequest)] {
     3539        MediaPlayerPrivateAVFoundationObjC* callback = protectedSelf->m_callback;
    35423540        if (callback)
    3543             callback->didCancelLoadingRequest(strongRequest.get());
     3541            callback->didCancelLoadingRequest(protectedLoadingRequest.get());
    35443542    });
    35453543}
  • trunk/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaSourceAVFObjC.mm

    r201474 r201482  
    130130{
    131131    MediaPlayerPrivateMediaSourceAVFObjC* player = (MediaPlayerPrivateMediaSourceAVFObjC*)listener;
    132     auto weakThis = player->createWeakPtr();
    133     callOnMainThread([weakThis]{
     132    callOnMainThread([weakThis = player->createWeakPtr()] {
    134133        if (!weakThis)
    135134            return;
     
    313312void MediaPlayerPrivateMediaSourceAVFObjC::play()
    314313{
    315     auto weakThis = createWeakPtr();
    316     callOnMainThread([weakThis]{
     314    callOnMainThread([weakThis = createWeakPtr()] {
    317315        if (!weakThis)
    318316            return;
     
    333331void MediaPlayerPrivateMediaSourceAVFObjC::pause()
    334332{
    335     auto weakThis = createWeakPtr();
    336     callOnMainThread([weakThis]{
     333    callOnMainThread([weakThis = createWeakPtr()] {
    337334        if (!weakThis)
    338335            return;
  • trunk/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.h

    r201474 r201482  
    3232#include "MediaStreamPrivate.h"
    3333#include <wtf/MediaTime.h>
     34#include <wtf/NoncopyableFunction.h>
    3435#include <wtf/Vector.h>
    3536#include <wtf/WeakPtr.h>
     
    143144    void renderingModeChanged();
    144145
    145     void scheduleDeferredTask(std::function<void()>);
     146    void scheduleDeferredTask(NoncopyableFunction&&);
    146147
    147148    enum DisplayMode {
  • trunk/Source/WebCore/platform/graphics/avfoundation/objc/MediaPlayerPrivateMediaStreamAVFObjC.mm

    r201474 r201482  
    625625}
    626626
    627 void MediaPlayerPrivateMediaStreamAVFObjC::scheduleDeferredTask(std::function<void()> function)
     627void MediaPlayerPrivateMediaStreamAVFObjC::scheduleDeferredTask(NoncopyableFunction&& function)
    628628{
    629629    ASSERT(function);
    630     auto weakThis = createWeakPtr();
    631     callOnMainThread([weakThis, function] {
     630    callOnMainThread([weakThis = createWeakPtr(), function = WTFMove(function)] {
    632631        if (!weakThis)
    633632            return;
  • trunk/Source/WebCore/platform/graphics/avfoundation/objc/SourceBufferPrivateAVFObjC.mm

    r201038 r201482  
    180180#endif
    181181    ASSERT(streamDataParser == _parser);
    182     RetainPtr<WebAVStreamDataParserListener> strongSelf = self;
    183 
    184     RetainPtr<AVAsset*> strongAsset = asset;
    185     callOnMainThread([strongSelf, strongAsset] {
    186         if (strongSelf->_parent)
    187             strongSelf->_parent->didParseStreamDataAsAsset(strongAsset.get());
     182    RetainPtr<WebAVStreamDataParserListener> protectedSelf = self;
     183
     184    RetainPtr<AVAsset*> protectedAsset = asset;
     185    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedAsset = WTFMove(protectedAsset)] {
     186        if (protectedSelf->_parent)
     187            protectedSelf->_parent->didParseStreamDataAsAsset(protectedAsset.get());
    188188    });
    189189}
     
    196196#endif
    197197    ASSERT(streamDataParser == _parser);
    198     RetainPtr<WebAVStreamDataParserListener> strongSelf = self;
    199 
    200     RetainPtr<AVAsset*> strongAsset = asset;
    201     callOnMainThread([strongSelf, strongAsset] {
    202         if (strongSelf->_parent)
    203             strongSelf->_parent->didParseStreamDataAsAsset(strongAsset.get());
     198    RetainPtr<WebAVStreamDataParserListener> protectedSelf = self;
     199
     200    RetainPtr<AVAsset*> protectedAsset = asset;
     201    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedAsset = WTFMove(protectedAsset)] {
     202        if (protectedSelf->_parent)
     203            protectedSelf->_parent->didParseStreamDataAsAsset(protectedAsset.get());
    204204    });
    205205}
     
    211211#endif
    212212    ASSERT(streamDataParser == _parser);
    213     RetainPtr<WebAVStreamDataParserListener> strongSelf = self;
    214 
    215     RetainPtr<NSError> strongError = error;
    216     callOnMainThread([strongSelf, strongError] {
    217         if (strongSelf->_parent)
    218             strongSelf->_parent->didFailToParseStreamDataWithError(strongError.get());
     213    RetainPtr<WebAVStreamDataParserListener> protectedSelf = self;
     214
     215    RetainPtr<NSError> protectedError = error;
     216    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedError = WTFMove(protectedError)] {
     217        if (protectedSelf->_parent)
     218            protectedSelf->_parent->didFailToParseStreamDataWithError(protectedError.get());
    219219    });
    220220}
     
    226226#endif
    227227    ASSERT(streamDataParser == _parser);
    228     RetainPtr<WebAVStreamDataParserListener> strongSelf = self;
    229 
    230     RetainPtr<CMSampleBufferRef> strongSample = sample;
     228    RetainPtr<WebAVStreamDataParserListener> protectedSelf = self;
     229
     230    RetainPtr<CMSampleBufferRef> protectedSample = sample;
    231231    String mediaType = nsMediaType;
    232     callOnMainThread([strongSelf, strongSample, trackID, mediaType, flags] {
    233         if (strongSelf->_parent)
    234             strongSelf->_parent->didProvideMediaDataForTrackID(trackID, strongSample.get(), mediaType, flags);
     232    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedSample = WTFMove(protectedSample), trackID, mediaType, flags] {
     233        if (protectedSelf->_parent)
     234            protectedSelf->_parent->didProvideMediaDataForTrackID(trackID, protectedSample.get(), mediaType, flags);
    235235    });
    236236}
     
    242242#endif
    243243    ASSERT(streamDataParser == _parser);
    244     RetainPtr<WebAVStreamDataParserListener> strongSelf = self;
     244    RetainPtr<WebAVStreamDataParserListener> protectedSelf = self;
    245245
    246246    String mediaType = nsMediaType;
    247     callOnMainThread([strongSelf, trackID, mediaType] {
    248         if (strongSelf->_parent)
    249             strongSelf->_parent->didReachEndOfTrackWithTrackID(trackID, mediaType);
     247    callOnMainThread([protectedSelf = WTFMove(protectedSelf), trackID, mediaType] {
     248        if (protectedSelf->_parent)
     249            protectedSelf->_parent->didReachEndOfTrackWithTrackID(trackID, mediaType);
    250250    });
    251251}
     
    273273#endif
    274274    ASSERT(streamDataParser == _parser);
    275     RetainPtr<WebAVStreamDataParserListener> strongSelf = self;
    276 
    277     RetainPtr<NSData> strongData = initData;
     275    RetainPtr<WebAVStreamDataParserListener> protectedSelf = self;
     276
    278277    OSObjectPtr<dispatch_semaphore_t> hasSessionSemaphore = adoptOSObject(dispatch_semaphore_create(0));
    279     callOnMainThread([strongSelf, strongData, trackID,  hasSessionSemaphore] {
    280         if (strongSelf->_parent)
    281             strongSelf->_parent->didProvideContentKeyRequestInitializationDataForTrackID(strongData.get(), trackID, hasSessionSemaphore);
     278    callOnMainThread([protectedSelf = WTFMove(protectedSelf), protectedInitData = RetainPtr<NSData>(initData), trackID, hasSessionSemaphore = WTFMove(hasSessionSemaphore)] {
     279        if (protectedSelf->_parent)
     280            protectedSelf->_parent->didProvideContentKeyRequestInitializationDataForTrackID(protectedInitData.get(), trackID, hasSessionSemaphore);
    282281    });
    283282    dispatch_semaphore_wait(hasSessionSemaphore.get(), DISPATCH_TIME_FOREVER);
     
    383382    ASSERT(_parent);
    384383
    385     RetainPtr<WebAVSampleBufferErrorListener> strongSelf = self;
     384    RetainPtr<WebAVSampleBufferErrorListener> protectedSelf = self;
    386385    if ([object isKindOfClass:getAVSampleBufferDisplayLayerClass()]) {
    387386        RetainPtr<AVSampleBufferDisplayLayer> layer = (AVSampleBufferDisplayLayer *)object;
     
    390389        if ([keyPath isEqualTo:@"error"]) {
    391390            RetainPtr<NSError> error = [change valueForKey:NSKeyValueChangeNewKey];
    392             callOnMainThread([strongSelf, layer, error] {
    393                 strongSelf->_parent->layerDidReceiveError(layer.get(), error.get());
     391            callOnMainThread([protectedSelf = WTFMove(protectedSelf), layer = WTFMove(layer), error = WTFMove(error)] {
     392                protectedSelf->_parent->layerDidReceiveError(layer.get(), error.get());
    394393            });
    395394        } else if ([keyPath isEqualTo:@"outputObscuredDueToInsufficientExternalProtection"]) {
    396395            if ([[change valueForKey:NSKeyValueChangeNewKey] boolValue]) {
    397396                RetainPtr<NSError> error = [NSError errorWithDomain:@"com.apple.WebKit" code:'HDCP' userInfo:nil];
    398                 callOnMainThread([strongSelf, layer, error] {
    399                     strongSelf->_parent->layerDidReceiveError(layer.get(), error.get());
     397                callOnMainThread([protectedSelf = WTFMove(protectedSelf), layer = WTFMove(layer), error = WTFMove(error)] {
     398                    protectedSelf->_parent->layerDidReceiveError(layer.get(), error.get());
    400399                });
    401400            }
     
    410409        ASSERT([keyPath isEqualTo:@"error"]);
    411410
    412         callOnMainThread([strongSelf, renderer, error] {
    413             strongSelf->_parent->rendererDidReceiveError(renderer.get(), error.get());
     411        callOnMainThread([protectedSelf = WTFMove(protectedSelf), renderer = WTFMove(renderer), error = WTFMove(error)] {
     412            protectedSelf->_parent->rendererDidReceiveError(renderer.get(), error.get());
    414413        });
    415414    } else
     
    422421    RetainPtr<NSError> error = [[note userInfo] valueForKey:AVSampleBufferDisplayLayerFailedToDecodeNotificationErrorKey];
    423422
    424     RetainPtr<WebAVSampleBufferErrorListener> strongSelf = self;
    425     callOnMainThread([strongSelf, layer, error] {
    426         if (!strongSelf->_parent || !strongSelf->_layers.contains(layer.get()))
     423    RetainPtr<WebAVSampleBufferErrorListener> protectedSelf = self;
     424    callOnMainThread([protectedSelf = WTFMove(protectedSelf), layer = WTFMove(layer), error = WTFMove(error)] {
     425        if (!protectedSelf->_parent || !protectedSelf->_layers.contains(layer.get()))
    427426            return;
    428         strongSelf->_parent->layerDidReceiveError(layer.get(), error.get());
     427        protectedSelf->_parent->layerDidReceiveError(layer.get(), error.get());
    429428    });
    430429}
  • trunk/Source/WebCore/platform/graphics/cg/GraphicsContextCG.cpp

    r200967 r201482  
    296296static void patternReleaseCallback(void* info)
    297297{
    298     auto image = static_cast<CGImageRef>(info);
    299     callOnMainThread([image] {
     298    callOnMainThread([image = static_cast<CGImageRef>(info)] {
    300299        CGImageRelease(image);
    301300    });
  • trunk/Source/WebCore/platform/graphics/cg/PatternCG.cpp

    r188772 r201482  
    5757static void patternReleaseCallback(void* info)
    5858{
    59     auto image = static_cast<CGImageRef>(info);
    60 
    61     callOnMainThread([image] {
     59    callOnMainThread([image = static_cast<CGImageRef>(info)] {
    6260        CGImageRelease(image);
    6361    });
  • trunk/Source/WebCore/platform/graphics/win/MediaPlayerPrivateMediaFoundation.cpp

    r199114 r201482  
    487487    m_loadingProgress = SUCCEEDED(hr);
    488488
    489     auto weakPtr = m_weakPtrFactory.createWeakPtr();
    490     callOnMainThread([weakPtr] {
     489    callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr()] {
    491490        if (!weakPtr)
    492491            return;
     
    517516    switch (mediaEventType) {
    518517    case MESessionTopologySet: {
    519         auto weakPtr = m_weakPtrFactory.createWeakPtr();
    520         callOnMainThread([weakPtr] {
     518        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr()] {
    521519            if (!weakPtr)
    522520                return;
     
    527525
    528526    case MEBufferingStarted: {
    529         auto weakPtr = m_weakPtrFactory.createWeakPtr();
    530         callOnMainThread([weakPtr] {
     527        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr()] {
    531528            if (!weakPtr)
    532529                return;
     
    537534
    538535    case MEBufferingStopped: {
    539         auto weakPtr = m_weakPtrFactory.createWeakPtr();
    540         callOnMainThread([weakPtr] {
     536        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr()] {
    541537            if (!weakPtr)
    542538                return;
     
    547543
    548544    case MESessionEnded: {
    549         auto weakPtr = m_weakPtrFactory.createWeakPtr();
    550         callOnMainThread([weakPtr] {
     545        callOnMainThread([weakPtr = m_weakPtrFactory.createWeakPtr()] {
    551546            if (!weakPtr)
    552547                return;
     
    16761671    // Invalidate the video area
    16771672    if (m_mediaPlayer) {
    1678         auto weakPtr = m_mediaPlayer->m_weakPtrFactory.createWeakPtr();
    1679         callOnMainThread([weakPtr] {
     1673        callOnMainThread([weakPtr = m_mediaPlayer->m_weakPtrFactory.createWeakPtr()] {
    16801674            if (weakPtr)
    16811675                weakPtr->invalidateFrameView();
  • trunk/Source/WebCore/platform/mediastream/MediaStreamPrivate.cpp

    r197929 r201482  
    300300}
    301301
    302 void MediaStreamPrivate::scheduleDeferredTask(std::function<void()> function)
     302void MediaStreamPrivate::scheduleDeferredTask(NoncopyableFunction&& function)
    303303{
    304304    ASSERT(function);
    305     auto weakThis = createWeakPtr();
    306     callOnMainThread([weakThis, function] {
     305    callOnMainThread([weakThis = createWeakPtr(), function = WTFMove(function)] {
    307306        if (!weakThis)
    308307            return;
  • trunk/Source/WebCore/platform/mediastream/MediaStreamPrivate.h

    r197929 r201482  
    4242#include <wtf/HashMap.h>
    4343#include <wtf/MediaTime.h>
     44#include <wtf/NoncopyableFunction.h>
    4445#include <wtf/RefCounted.h>
    4546#include <wtf/RefPtr.h>
     
    112113    void updateActiveVideoTrack();
    113114
    114     void scheduleDeferredTask(std::function<void()>);
     115    void scheduleDeferredTask(NoncopyableFunction&&);
    115116
    116117    WeakPtrFactory<MediaStreamPrivate> m_weakPtrFactory;
  • trunk/Source/WebCore/platform/mediastream/mac/AVMediaCaptureSource.h

    r192954 r201482  
    3232#include "RealtimeMediaSource.h"
    3333#include "Timer.h"
     34#include <wtf/NoncopyableFunction.h>
    3435#include <wtf/RetainPtr.h>
    3536#include <wtf/WeakPtr.h>
     
    8687    void setAudioSampleBufferDelegate(AVCaptureAudioDataOutput*);
    8788
    88     void scheduleDeferredTask(std::function<void ()>);
     89    void scheduleDeferredTask(NoncopyableFunction&&);
    8990
    9091private:
  • trunk/Source/WebCore/platform/mediastream/mac/AVMediaCaptureSource.mm

    r197929 r201482  
    241241}
    242242
    243 void AVMediaCaptureSource::scheduleDeferredTask(std::function<void ()> function)
     243void AVMediaCaptureSource::scheduleDeferredTask(NoncopyableFunction&& function)
    244244{
    245245    ASSERT(function);
    246 
    247     auto weakThis = createWeakPtr();
    248     callOnMainThread([weakThis, function] {
     246    callOnMainThread([weakThis = createWeakPtr(), function = WTFMove(function)] {
    249247        if (!weakThis)
    250248            return;
  • trunk/Source/WebCore/platform/mediastream/mac/RealtimeMediaSourceCenterMac.cpp

    r197114 r201482  
    164164{
    165165    RefPtr<MediaStreamTrackSourcesRequestClient> requestClient = prpClient;
    166 
    167166    TrackSourceInfoVector sources = AVCaptureDeviceManager::singleton().getSourcesInfo(requestClient->requestOrigin());
    168167
    169     callOnMainThread([this, requestClient, sources] {
     168    callOnMainThread([this, requestClient = WTFMove(requestClient), sources = WTFMove(sources)] {
    170169        requestClient->didCompleteTrackSourceInfoRequest(sources);
    171170    });
  • trunk/Source/WebCore/platform/mediastream/mac/WebAudioSourceProviderAVFObjC.mm

    r193389 r201482  
    215215    m_list->mNumberBuffers = numberOfChannels;
    216216
    217     RefPtr<WebAudioSourceProviderAVFObjC> strongThis = this;
    218     callOnMainThread([strongThis, numberOfChannels, sampleRate] {
    219         if (strongThis->m_client)
    220             strongThis->m_client->setFormat(numberOfChannels, sampleRate);
     217    RefPtr<WebAudioSourceProviderAVFObjC> protectedThis = this;
     218    callOnMainThread([protectedThis = WTFMove(protectedThis), numberOfChannels, sampleRate] {
     219        if (protectedThis->m_client)
     220            protectedThis->m_client->setFormat(numberOfChannels, sampleRate);
    221221    });
    222222}
  • trunk/Source/WebCore/platform/mock/MockRealtimeMediaSourceCenter.cpp

    r197114 r201482  
    160160    sources.append(MockRealtimeMediaSource::trackSourceWithUID(MockRealtimeMediaSource::mockVideoSourcePersistentID(), nullptr));
    161161
    162     callOnMainThread([this, requestClient, sources] {
     162    callOnMainThread([this, requestClient = WTFMove(requestClient), sources = WTFMove(sources)] {
    163163        requestClient->didCompleteTrackSourceInfoRequest(sources);
    164164    });
  • trunk/Source/WebCore/platform/network/BlobResourceHandle.cpp

    r200895 r201482  
    188188    }
    189189
    190     RefPtr<BlobResourceHandle> protectedThis(this);
    191 
    192190    // Finish this async call quickly and return.
    193     callOnMainThread([protectedThis] {
     191    callOnMainThread([protectedThis = Ref<BlobResourceHandle>(*this)]() mutable {
    194192        protectedThis->doStart();
    195193    });
     
    666664    // Schedule to notify the client from a standalone function because the client might dispose the handle immediately from the callback function
    667665    // while we still have BlobResourceHandle calls in the stack.
    668     RefPtr<BlobResourceHandle> protectedThis(this);
    669     callOnMainThread([protectedThis] {
    670         doNotifyFinish(*protectedThis);
     666    callOnMainThread([protectedThis = Ref<BlobResourceHandle>(*this)]() mutable {
     667        doNotifyFinish(protectedThis);
    671668    });
    672669
  • trunk/Source/WebCore/platform/network/DataURLDecoder.cpp

    r199735 r201482  
    169169}
    170170
    171 void decode(const URL& url, const ScheduleContext& scheduleContext, DecodeCompletionHandler completionHandler)
     171void decode(const URL& url, const ScheduleContext& scheduleContext, DecodeCompletionHandler&& completionHandler)
    172172{
    173173    ASSERT(url.protocolIsData());
    174174
    175175    auto decodeTask = createDecodeTask(url, scheduleContext, WTFMove(completionHandler));
    176     auto* decodeTaskPtr = decodeTask.release();
    177     decodeQueue().dispatch([decodeTaskPtr] {
    178         auto& decodeTask = *decodeTaskPtr;
    179 
    180         if (decodeTask.isBase64)
    181             decodeBase64(decodeTask);
     176    decodeQueue().dispatch([decodeTask = WTFMove(decodeTask)]() mutable {
     177        if (decodeTask->isBase64)
     178            decodeBase64(*decodeTask);
    182179        else
    183             decodeEscaped(decodeTask);
     180            decodeEscaped(*decodeTask);
    184181
    185182#if HAVE(RUNLOOP_TIMER)
    186         DecodingResultDispatcher::dispatch(std::unique_ptr<DecodeTask>(decodeTaskPtr));
     183        DecodingResultDispatcher::dispatch(WTFMove(decodeTask));
    187184#else
    188         callOnMainThread([decodeTaskPtr] {
    189             std::unique_ptr<DecodeTask> decodeTask(decodeTaskPtr);
     185        callOnMainThread([decodeTask = WTFMove(decodeTask)] {
    190186            if (!decodeTask->result.data) {
    191187                decodeTask->completionHandler({ });
  • trunk/Source/WebCore/platform/network/DataURLDecoder.h

    r191673 r201482  
    5656};
    5757
    58 void decode(const URL&, const ScheduleContext&, DecodeCompletionHandler);
     58void decode(const URL&, const ScheduleContext&, DecodeCompletionHandler&&);
    5959
    6060}
  • trunk/Source/WebCore/platform/network/cocoa/WebCoreNSURLSession.mm

    r200578 r201482  
    9393        task.get().session = nil;
    9494
    95     // FIXME(C++14): When we can move RefPtrs directly into blocks, replace this with a RefPtr&&:
    96     WebCore::PlatformMediaResourceLoader* loader = _loader.leakRef();
    97     callOnMainThread([loader] {
    98         loader->deref();
     95    callOnMainThread([loader = WTFMove(_loader)] {
    9996    });
    10097    [super dealloc];
     
    467464{
    468465    self.state = NSURLSessionTaskStateCanceling;
    469     RetainPtr<WebCoreNSURLSessionDataTask> strongSelf { self };
    470     callOnMainThread([strongSelf] {
    471         [strongSelf _cancel];
    472         [strongSelf _finish];
     466    callOnMainThread([protectedSelf = RetainPtr<WebCoreNSURLSessionDataTask>(self)] {
     467        [protectedSelf _cancel];
     468        [protectedSelf _finish];
    473469    });
    474470}
     
    476472- (void)suspend
    477473{
    478     RetainPtr<WebCoreNSURLSessionDataTask> strongSelf { self };
    479     callOnMainThread([strongSelf] {
     474    callOnMainThread([protectedSelf = RetainPtr<WebCoreNSURLSessionDataTask>(self)] {
    480475        // NSURLSessionDataTasks must start over after suspending, so while
    481476        // we could defer loading at this point, instead cancel and restart
    482477        // upon resume so as to adhere to NSURLSessionDataTask semantics.
    483         [strongSelf _cancel];
    484         strongSelf.get().state = NSURLSessionTaskStateSuspended;
     478        [protectedSelf _cancel];
     479        protectedSelf.get().state = NSURLSessionTaskStateSuspended;
    485480    });
    486481}
     
    488483- (void)resume
    489484{
    490     RetainPtr<WebCoreNSURLSessionDataTask> strongSelf { self };
    491     callOnMainThread([strongSelf] {
    492         if (strongSelf.get().state != NSURLSessionTaskStateSuspended)
     485    callOnMainThread([protectedSelf = RetainPtr<WebCoreNSURLSessionDataTask>(self)] {
     486        if (protectedSelf.get().state != NSURLSessionTaskStateSuspended)
    493487            return;
    494488
    495         [strongSelf _restart];
    496         strongSelf.get().state = NSURLSessionTaskStateRunning;
     489        [protectedSelf _restart];
     490        protectedSelf.get().state = NSURLSessionTaskStateRunning;
    497491    });
    498492}
  • trunk/Source/WebCore/platform/network/curl/CurlDownload.cpp

    r201354 r201482  
    403403
    404404        if (httpCode >= 200 && httpCode < 300) {
    405             URLCapture capturedUrl(getCurlEffectiveURL(m_curlHandle));
    406             RefPtr<CurlDownload> protectedThis(this);
    407 
    408             callOnMainThread([this, capturedUrl, protectedThis] {
    409                 m_response.setURL(capturedUrl.url());
     405            URL url = getCurlEffectiveURL(m_curlHandle);
     406            callOnMainThread([this, url = url.isolatedCopy(), protectedThis = Ref<CurlDownload>(*this)] {
     407                m_response.setURL(url);
    410408                m_response.setMimeType(extractMIMETypeFromMediaType(m_response.httpHeaderField(HTTPHeaderName::ContentType)));
    411409                m_response.setTextEncodingName(extractCharsetFromMediaType(m_response.httpHeaderField(HTTPHeaderName::ContentType)));
     
    415413        }
    416414    } else {
    417         StringCapture capturedHeader(header);
    418 
    419         RefPtr<CurlDownload> protectedThis(this);
    420 
    421         callOnMainThread([this, capturedHeader, protectedThis] {
    422             int splitPos = capturedHeader.string().find(":");
     415        callOnMainThread([this, header = header.isolatedCopy(), protectedThis = Ref<CurlDownload>(*this)] {
     416            int splitPos = header.string().find(":");
    423417            if (splitPos != -1)
    424                 m_response.setHTTPHeaderField(capturedHeader.string().left(splitPos), capturedHeader.string().substring(splitPos + 1).stripWhiteSpace());
     418                m_response.setHTTPHeaderField(header.string().left(splitPos), header.string().substring(splitPos + 1).stripWhiteSpace());
    425419        });
    426420    }
  • trunk/Source/WebKit/ChangeLog

    r201398 r201482  
     12016-05-27  Chris Dumez  <cdumez@apple.com>
     2
     3        callOnMainThread() should not copy captured lambda variables
     4        https://bugs.webkit.org/show_bug.cgi?id=158166
     5
     6        Reviewed by Brady Eidson.
     7
     8        callOnMainThread() should not copy captured lambda variables. This
     9        function is usually called cross-thread with a lambda and copying
     10        the lambda (and its captured variables) can lead to thread-safety
     11        issues.
     12
     13        This patch updates callOnMainThread() to take a NoncopyableFunction&&
     14        in parameter instead of a std::function. The call sites of
     15        callOnMainThread() have also been updated to use C++14's lambda
     16        capture with initializer.
     17
     18        * Storage/StorageAreaSync.cpp:
     19        (WebCore::StorageAreaSync::deleteEmptyDatabase):
     20        * Storage/StorageSyncManager.cpp:
     21        (WebCore::StorageSyncManager::dispatch):
     22        * Storage/StorageSyncManager.h:
     23        * Storage/StorageThread.cpp:
     24        (WebCore::StorageThread::dispatch):
     25        (WebCore::StorageThread::terminate):
     26        (WebCore::StorageThread::releaseFastMallocFreeMemoryInAllThreads):
     27        * Storage/StorageThread.h:
     28        * Storage/StorageTracker.cpp:
     29        (WebCore::StorageTracker::syncFileSystemAndTrackerDatabase):
     30        (WebCore::StorageTracker::setOriginDetails):
     31
    1322016-05-25  Alex Christensen  <achristensen@webkit.org>
    233
  • trunk/Source/WebKit/Storage/StorageAreaSync.cpp

    r188594 r201482  
    515515        m_database.close();
    516516        if (StorageTracker::tracker().isActive()) {
    517             StringImpl* databaseIdentifierCopy = &m_databaseIdentifier.impl()->isolatedCopy().leakRef();
    518             callOnMainThread([databaseIdentifierCopy] {
    519                 StorageTracker::tracker().deleteOriginWithIdentifier(databaseIdentifierCopy);
    520                 databaseIdentifierCopy->deref();
     517            callOnMainThread([databaseIdentifier = m_databaseIdentifier.isolatedCopy()] {
     518                StorageTracker::tracker().deleteOriginWithIdentifier(databaseIdentifier);
    521519            });
    522520        } else {
  • trunk/Source/WebKit/Storage/StorageSyncManager.cpp

    r177813 r201482  
    6464}
    6565
    66 void StorageSyncManager::dispatch(const std::function<void ()>& function)
     66void StorageSyncManager::dispatch(NoncopyableFunction&& function)
    6767{
    6868    ASSERT(isMainThread());
     
    7070
    7171    if (m_thread)
    72         m_thread->dispatch(function);
     72        m_thread->dispatch(WTFMove(function));
    7373}
    7474
  • trunk/Source/WebKit/Storage/StorageSyncManager.h

    r177813 r201482  
    2929#include <functional>
    3030#include <wtf/Forward.h>
     31#include <wtf/NoncopyableFunction.h>
    3132#include <wtf/PassRefPtr.h>
    3233#include <wtf/RefCounted.h>
     
    4344    ~StorageSyncManager();
    4445
    45     void dispatch(const std::function<void ()>&);
     46    void dispatch(NoncopyableFunction&&);
    4647    void close();
    4748
  • trunk/Source/WebKit/Storage/StorageThread.cpp

    r194987 r201482  
    7575}
    7676
    77 void StorageThread::dispatch(const std::function<void ()>& function)
     77void StorageThread::dispatch(NoncopyableFunction&& function)
    7878{
    7979    ASSERT(isMainThread());
    8080    ASSERT(!m_queue.killed() && m_threadID);
    81     m_queue.append(std::make_unique<std::function<void ()>>(function));
     81    m_queue.append(std::make_unique<NoncopyableFunction>(WTFMove(function)));
    8282}
    8383
     
    9191        return;
    9292
    93     m_queue.append(std::make_unique<std::function<void ()>>([this] {
     93    m_queue.append(std::make_unique<NoncopyableFunction>([this] {
    9494        performTerminate();
    9595    }));
     
    109109    HashSet<StorageThread*>& threads = activeStorageThreads();
    110110
    111     for (HashSet<StorageThread*>::iterator it = threads.begin(), end = threads.end(); it != end; ++it)
    112         (*it)->dispatch(WTF::releaseFastMallocFreeMemory);
     111    for (HashSet<StorageThread*>::iterator it = threads.begin(), end = threads.end(); it != end; ++it) {
     112        (*it)->dispatch([]() {
     113            WTF::releaseFastMallocFreeMemory();
     114        });
     115    }
    113116}
    114117
  • trunk/Source/WebKit/Storage/StorageThread.h

    r177813 r201482  
    3030#include <wtf/HashSet.h>
    3131#include <wtf/MessageQueue.h>
    32 #include <wtf/PassRefPtr.h>
     32#include <wtf/NoncopyableFunction.h>
    3333#include <wtf/Threading.h>
    3434
     
    4747    void terminate();
    4848
    49     void dispatch(const std::function<void()>&);
     49    void dispatch(NoncopyableFunction&&);
    5050
    5151    static void releaseFastMallocFreeMemoryInAllThreads();
     
    6060
    6161    ThreadIdentifier m_threadID;
    62     MessageQueue<std::function<void()>> m_queue;
     62    MessageQueue<NoncopyableFunction> m_queue;
    6363};
    6464
  • trunk/Source/WebKit/Storage/StorageTracker.cpp

    r195452 r201482  
    294294            continue;
    295295
    296         String originIdentifierCopy = originIdentifier.isolatedCopy();
    297         callOnMainThread([this, originIdentifierCopy] {
    298             deleteOriginWithIdentifier(originIdentifierCopy);
     296        callOnMainThread([this, originIdentifier = originIdentifier.isolatedCopy()] {
     297            deleteOriginWithIdentifier(originIdentifier);
    299298        });
    300299    }
     
    315314    }
    316315
    317     String originIdentifierCopy = originIdentifier.isolatedCopy();
    318     String databaseFileCopy = databaseFile.isolatedCopy();
    319     auto function = [this, originIdentifierCopy, databaseFileCopy] {
    320         syncSetOriginDetails(originIdentifierCopy, databaseFileCopy);
     316    auto function = [this, originIdentifier = originIdentifier.isolatedCopy(), databaseFile = databaseFile.isolatedCopy()] {
     317        syncSetOriginDetails(originIdentifier, databaseFile);
    321318    };
    322319
    323320    if (isMainThread()) {
    324321        ASSERT(m_thread);
    325         m_thread->dispatch(function);
     322        m_thread->dispatch(WTFMove(function));
    326323    } else {
    327324        // FIXME: This weird ping-ponging was done to fix a deadlock. We should figure out a cleaner way to avoid it instead.
    328         callOnMainThread([this, function] {
    329             m_thread->dispatch(function);
     325        callOnMainThread([this, function = WTFMove(function)]() mutable {
     326            m_thread->dispatch(WTFMove(function));
    330327        });
    331328    }
  • trunk/Source/WebKit/mac/ChangeLog

    r201481 r201482  
     12016-05-27  Chris Dumez  <cdumez@apple.com>
     2
     3        callOnMainThread() should not copy captured lambda variables
     4        https://bugs.webkit.org/show_bug.cgi?id=158166
     5
     6        Reviewed by Brady Eidson.
     7
     8        callOnMainThread() should not copy captured lambda variables. This
     9        function is usually called cross-thread with a lambda and copying
     10        the lambda (and its captured variables) can lead to thread-safety
     11        issues.
     12
     13        This patch updates callOnMainThread() to take a NoncopyableFunction&&
     14        in parameter instead of a std::function. The call sites of
     15        callOnMainThread() have also been updated to use C++14's lambda
     16        capture with initializer.
     17
     18        * Storage/WebDatabaseManagerClient.mm:
     19        (DidModifyOriginData::dispatchToMainThread):
     20        (DidModifyOriginData::DidModifyOriginData): Deleted.
     21        * Storage/WebStorageTrackerClient.mm:
     22        (WebStorageTrackerClient::dispatchDidModifyOrigin):
     23
    1242016-05-27  Caitlin Potter  <caitp@igalia.com>
    225
  • trunk/Source/WebKit/mac/Storage/WebDatabaseManagerClient.mm

    r188772 r201482  
    104104    static void dispatchToMainThread(WebDatabaseManagerClient* client, SecurityOrigin* origin)
    105105    {
    106         DidModifyOriginData* context = new DidModifyOriginData(client, origin->isolatedCopy());
    107         callOnMainThread([context] {
     106        auto context = std::make_unique<DidModifyOriginData>(client, origin->isolatedCopy());
     107        callOnMainThread([context = WTFMove(context)] {
    108108            context->client->dispatchDidModifyOrigin(context->origin.get());
    109             delete context;
    110109        });
    111110    }
    112111
    113 private:
    114112    DidModifyOriginData(WebDatabaseManagerClient* client, PassRefPtr<SecurityOrigin> origin)
    115113        : client(client)
     
    118116    }
    119117
     118private:
    120119    WebDatabaseManagerClient* client;
    121120    RefPtr<SecurityOrigin> origin;
  • trunk/Source/WebKit/mac/Storage/WebStorageTrackerClient.mm

    r188772 r201482  
    5959void WebStorageTrackerClient::dispatchDidModifyOrigin(const String& originIdentifier)
    6060{
    61     RefPtr<SecurityOrigin> origin = SecurityOrigin::createFromDatabaseIdentifier(originIdentifier);
     61    auto origin = SecurityOrigin::createFromDatabaseIdentifier(originIdentifier);
    6262
    6363    if (isMainThread()) {
    64         dispatchDidModifyOrigin(origin);
     64        dispatchDidModifyOrigin(WTFMove(origin));
    6565        return;
    6666    }
    6767
    68     callOnMainThread([origin] {
    69         WebStorageTrackerClient::sharedWebStorageTrackerClient()->dispatchDidModifyOrigin(origin.get());
     68    callOnMainThread([origin = WTFMove(origin)]() mutable {
     69        WebStorageTrackerClient::sharedWebStorageTrackerClient()->dispatchDidModifyOrigin(WTFMove(origin));
    7070    });
    7171}
Note: See TracChangeset for help on using the changeset viewer.