Title: [236617] trunk
Revision
236617
Author
[email protected]
Date
2018-09-28 15:32:34 -0700 (Fri, 28 Sep 2018)

Log Message

[WTF] Make isMainThread more reliable
https://bugs.webkit.org/show_bug.cgi?id=189880

Reviewed by Mark Lam.

.:

* Source/cmake/OptionsCommon.cmake:

Source/WTF:

isMainThread() relied on Thread::current(). This API becomes broken in Windows
when the Thread is about to be destroyed since TLS is already cleared. This causes
a bug since `isMainThread()` is called in Thread::didExit in Windows.

This patch makes this `isMainThread` more reliable in all the platforms. In Windows,
we use `Thread::currentID()` instead of `Thread::current()` since `Thread::currentID`
uses Win32 GetCurrentThreadId directly. In the other system, we use `pthread_main_np`
or `pthread_self` instead.

We also move `holdLock` code inside `if (shouldRemoveThreadFromThreadGroup())`. If
the other thread takes a mutex and destroyed, this `holdLock` waits forever. This problem
only happens in Windows since Windows calls TLS destructor for the main thread.

* WTF.xcodeproj/project.pbxproj:
* wtf/MainThread.cpp:
(WTF::initializeMainThread):
(): Deleted.
(WTF::isMainThread): Deleted.
(WTF::isMainThreadIfInitialized): Deleted.
* wtf/Platform.h:
* wtf/PlatformMac.cmake:
* wtf/Threading.cpp:
(WTF::Thread::didExit):
* wtf/cocoa/MainThreadCocoa.mm: Renamed from Source/WTF/wtf/mac/MainThreadMac.mm.
* wtf/generic/MainThreadGeneric.cpp:
(WTF::initializeMainThreadPlatform):
(WTF::isMainThread):
(WTF::isMainThreadIfInitialized):
* wtf/win/MainThreadWin.cpp:
(WTF::initializeMainThreadPlatform):
(WTF::isMainThread):
(WTF::isMainThreadIfInitialized):

Modified Paths

Added Paths

Removed Paths

Diff

Modified: trunk/ChangeLog (236616 => 236617)


--- trunk/ChangeLog	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/ChangeLog	2018-09-28 22:32:34 UTC (rev 236617)
@@ -1,3 +1,12 @@
+2018-09-28  Yusuke Suzuki  <[email protected]>
+
+        [WTF] Make isMainThread more reliable
+        https://bugs.webkit.org/show_bug.cgi?id=189880
+
+        Reviewed by Mark Lam.
+
+        * Source/cmake/OptionsCommon.cmake:
+
 2018-09-21  Yusuke Suzuki  <[email protected]>
 
         [JSC] Enable LLInt ASM interpreter on X64 and ARM64 in non JIT configuration

Modified: trunk/Source/WTF/ChangeLog (236616 => 236617)


--- trunk/Source/WTF/ChangeLog	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/ChangeLog	2018-09-28 22:32:34 UTC (rev 236617)
@@ -1,3 +1,43 @@
+2018-09-28  Yusuke Suzuki  <[email protected]>
+
+        [WTF] Make isMainThread more reliable
+        https://bugs.webkit.org/show_bug.cgi?id=189880
+
+        Reviewed by Mark Lam.
+
+        isMainThread() relied on Thread::current(). This API becomes broken in Windows
+        when the Thread is about to be destroyed since TLS is already cleared. This causes
+        a bug since `isMainThread()` is called in Thread::didExit in Windows.
+
+        This patch makes this `isMainThread` more reliable in all the platforms. In Windows,
+        we use `Thread::currentID()` instead of `Thread::current()` since `Thread::currentID`
+        uses Win32 GetCurrentThreadId directly. In the other system, we use `pthread_main_np`
+        or `pthread_self` instead.
+
+        We also move `holdLock` code inside `if (shouldRemoveThreadFromThreadGroup())`. If
+        the other thread takes a mutex and destroyed, this `holdLock` waits forever. This problem
+        only happens in Windows since Windows calls TLS destructor for the main thread.
+
+        * WTF.xcodeproj/project.pbxproj:
+        * wtf/MainThread.cpp:
+        (WTF::initializeMainThread):
+        (): Deleted.
+        (WTF::isMainThread): Deleted.
+        (WTF::isMainThreadIfInitialized): Deleted.
+        * wtf/Platform.h:
+        * wtf/PlatformMac.cmake:
+        * wtf/Threading.cpp:
+        (WTF::Thread::didExit):
+        * wtf/cocoa/MainThreadCocoa.mm: Renamed from Source/WTF/wtf/mac/MainThreadMac.mm.
+        * wtf/generic/MainThreadGeneric.cpp:
+        (WTF::initializeMainThreadPlatform):
+        (WTF::isMainThread):
+        (WTF::isMainThreadIfInitialized):
+        * wtf/win/MainThreadWin.cpp:
+        (WTF::initializeMainThreadPlatform):
+        (WTF::isMainThread):
+        (WTF::isMainThreadIfInitialized):
+
 2018-09-28  Commit Queue  <[email protected]>
 
         Unreviewed, rolling out r236605.

Modified: trunk/Source/WTF/WTF.xcodeproj/project.pbxproj (236616 => 236617)


--- trunk/Source/WTF/WTF.xcodeproj/project.pbxproj	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/WTF.xcodeproj/project.pbxproj	2018-09-28 22:32:34 UTC (rev 236617)
@@ -113,7 +113,7 @@
 		A8A473BA151A825B004123FF /* dtoa.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A8A47297151A825A004123FF /* dtoa.cpp */; };
 		A8A473C3151A825B004123FF /* FastMalloc.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A8A472A1151A825A004123FF /* FastMalloc.cpp */; };
 		A8A473D8151A825B004123FF /* HashTable.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A8A472B8151A825A004123FF /* HashTable.cpp */; };
-		A8A473E4151A825B004123FF /* MainThreadMac.mm in Sources */ = {isa = PBXBuildFile; fileRef = A8A472C5151A825A004123FF /* MainThreadMac.mm */; };
+		A8A473E4151A825B004123FF /* MainThreadCocoa.mm in Sources */ = {isa = PBXBuildFile; fileRef = A8A472C5151A825A004123FF /* MainThreadCocoa.mm */; };
 		A8A473E5151A825B004123FF /* MainThread.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A8A472C6151A825A004123FF /* MainThread.cpp */; };
 		A8A473E9151A825B004123FF /* MD5.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A8A472CA151A825B004123FF /* MD5.cpp */; };
 		A8A473EC151A825B004123FF /* MetaAllocator.cpp in Sources */ = {isa = PBXBuildFile; fileRef = A8A472CD151A825B004123FF /* MetaAllocator.cpp */; };
@@ -505,7 +505,7 @@
 		A8A472BC151A825A004123FF /* InlineASM.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = InlineASM.h; sourceTree = "<group>"; };
 		A8A472C1151A825A004123FF /* ListHashSet.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ListHashSet.h; sourceTree = "<group>"; };
 		A8A472C3151A825A004123FF /* Locker.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Locker.h; sourceTree = "<group>"; };
-		A8A472C5151A825A004123FF /* MainThreadMac.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MainThreadMac.mm; sourceTree = "<group>"; };
+		A8A472C5151A825A004123FF /* MainThreadCocoa.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = MainThreadCocoa.mm; sourceTree = "<group>"; };
 		A8A472C6151A825A004123FF /* MainThread.cpp */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.cpp; path = MainThread.cpp; sourceTree = "<group>"; };
 		A8A472C7151A825B004123FF /* MainThread.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MainThread.h; sourceTree = "<group>"; };
 		A8A472C9151A825B004123FF /* MathExtras.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = MathExtras.h; sourceTree = "<group>"; };
@@ -1188,7 +1188,6 @@
 				1A428B8B1C8F89DD0051E9EB /* AppKitCompatibilityDeclarations.h */,
 				1ACADD821884480100D8B71D /* DeprecatedSymbolsUsedBySafari.mm */,
 				53534F291EC0E10E00141B2F /* MachExceptions.defs */,
-				A8A472C5151A825A004123FF /* MainThreadMac.mm */,
 			);
 			path = mac;
 			sourceTree = "<group>";
@@ -1352,6 +1351,7 @@
 				143DDE9720C8BE99007F76FA /* Entitlements.h */,
 				143DDE9520C8BC37007F76FA /* Entitlements.mm */,
 				7A6EBA3320746C34004F9C44 /* MachSendRight.cpp */,
+				A8A472C5151A825A004123FF /* MainThreadCocoa.mm */,
 				ADF2CE651E39F106006889DB /* MemoryFootprintCocoa.cpp */,
 				AD89B6B91E64150F0090707F /* MemoryPressureHandlerCocoa.mm */,
 				A30D412C1F0DE0BA00B71954 /* SoftLinking.h */,
@@ -1524,7 +1524,7 @@
 				53534F2A1EC0E10E00141B2F /* MachExceptions.defs in Sources */,
 				7A6EBA3420746C34004F9C44 /* MachSendRight.cpp in Sources */,
 				A8A473E5151A825B004123FF /* MainThread.cpp in Sources */,
-				A8A473E4151A825B004123FF /* MainThreadMac.mm in Sources */,
+				A8A473E4151A825B004123FF /* MainThreadCocoa.mm in Sources */,
 				A8A473E9151A825B004123FF /* MD5.cpp in Sources */,
 				CD5497AC15857D0300B5BC30 /* MediaTime.cpp in Sources */,
 				ADF2CE671E39F106006889DB /* MemoryFootprintCocoa.cpp in Sources */,

Modified: trunk/Source/WTF/wtf/MainThread.cpp (236616 => 236617)


--- trunk/Source/WTF/wtf/MainThread.cpp	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/wtf/MainThread.cpp	2018-09-28 22:32:34 UTC (rev 236617)
@@ -42,10 +42,6 @@
 namespace WTF {
 
 static bool callbacksPaused; // This global variable is only accessed from main thread.
-#if !PLATFORM(COCOA)
-static Thread* mainThread { nullptr };
-#endif
-
 static Lock mainThreadFunctionQueueMutex;
 
 static Deque<Function<void ()>>& functionQueue()
@@ -60,26 +56,11 @@
 {
     std::call_once(initializeKey, [] {
         initializeThreading();
-#if !PLATFORM(COCOA)
-        mainThread = &Thread::current();
-#endif
         initializeMainThreadPlatform();
         initializeGCThreads();
     });
 }
 
-#if !PLATFORM(COCOA)
-bool isMainThread()
-{
-    return mainThread == &Thread::current();
-}
-
-bool isMainThreadIfInitialized()
-{
-    return isMainThread();
-}
-#endif
-
 #if PLATFORM(COCOA)
 #if !USE(WEB_THREAD)
 void initializeMainThreadToProcessMainThread()

Modified: trunk/Source/WTF/wtf/Platform.h (236616 => 236617)


--- trunk/Source/WTF/wtf/Platform.h	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/wtf/Platform.h	2018-09-28 22:32:34 UTC (rev 236617)
@@ -655,6 +655,7 @@
 #define HAVE_TM_GMTOFF 1
 #define HAVE_TM_ZONE 1
 #define HAVE_TIMEGM 1
+#define HAVE_PTHREAD_MAIN_NP 1
 
 #if CPU(X86_64) || CPU(ARM64)
 #define HAVE_INT128_T 1

Modified: trunk/Source/WTF/wtf/PlatformMac.cmake (236616 => 236617)


--- trunk/Source/WTF/wtf/PlatformMac.cmake	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/wtf/PlatformMac.cmake	2018-09-28 22:32:34 UTC (rev 236617)
@@ -45,12 +45,12 @@
     cocoa/CPUTimeCocoa.cpp
     cocoa/Entitlements.cpp
     cocoa/MachSendRight.cpp
+    cocoa/MainThreadCocoa.mm
     cocoa/MemoryFootprintCocoa.cpp
     cocoa/MemoryPressureHandlerCocoa.mm
     cocoa/WorkQueueCocoa.cpp
 
     mac/DeprecatedSymbolsUsedBySafari.mm
-    mac/MainThreadMac.mm
 
     text/cf/AtomicStringImplCF.cpp
     text/cf/StringCF.cpp

Modified: trunk/Source/WTF/wtf/Threading.cpp (236616 => 236617)


--- trunk/Source/WTF/wtf/Threading.cpp	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/wtf/Threading.cpp	2018-09-28 22:32:34 UTC (rev 236617)
@@ -185,28 +185,30 @@
 void Thread::didExit()
 {
     if (shouldRemoveThreadFromThreadGroup()) {
-        Vector<std::shared_ptr<ThreadGroup>> threadGroups;
         {
-            auto locker = holdLock(m_mutex);
-            for (auto& threadGroup : m_threadGroups) {
-                // If ThreadGroup is just being destroyed,
-                // we do not need to perform unregistering.
-                if (auto retained = threadGroup.lock())
-                    threadGroups.append(WTFMove(retained));
+            Vector<std::shared_ptr<ThreadGroup>> threadGroups;
+            {
+                auto locker = holdLock(m_mutex);
+                for (auto& threadGroup : m_threadGroups) {
+                    // If ThreadGroup is just being destroyed,
+                    // we do not need to perform unregistering.
+                    if (auto retained = threadGroup.lock())
+                        threadGroups.append(WTFMove(retained));
+                }
+                m_isShuttingDown = true;
             }
-            m_isShuttingDown = true;
+            for (auto& threadGroup : threadGroups) {
+                auto threadGroupLocker = holdLock(threadGroup->getLock());
+                auto locker = holdLock(m_mutex);
+                threadGroup->m_threads.remove(*this);
+            }
         }
-        for (auto& threadGroup : threadGroups) {
-            auto threadGroupLocker = holdLock(threadGroup->getLock());
-            auto locker = holdLock(m_mutex);
-            threadGroup->m_threads.remove(*this);
-        }
+
+        // We would like to say "thread is exited" after unregistering threads from thread groups.
+        // So we need to separate m_isShuttingDown from m_didExit.
+        auto locker = holdLock(m_mutex);
+        m_didExit = true;
     }
-
-    // We would like to say "thread is exited" after unregistering threads from thread groups.
-    // So we need to separate m_isShuttingDown from m_didExit.
-    auto locker = holdLock(m_mutex);
-    m_didExit = true;
 }
 
 ThreadGroupAddResult Thread::addToThreadGroup(const AbstractLocker& threadGroupLocker, ThreadGroup& threadGroup)

Copied: trunk/Source/WTF/wtf/cocoa/MainThreadCocoa.mm (from rev 236616, trunk/Source/WTF/wtf/mac/MainThreadMac.mm) (0 => 236617)


--- trunk/Source/WTF/wtf/cocoa/MainThreadCocoa.mm	                        (rev 0)
+++ trunk/Source/WTF/wtf/cocoa/MainThreadCocoa.mm	2018-09-28 22:32:34 UTC (rev 236617)
@@ -0,0 +1,230 @@
+/*
+ * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions
+ * are met:
+ *
+ * 1.  Redistributions of source code must retain the above copyright
+ *     notice, this list of conditions and the following disclaimer. 
+ * 2.  Redistributions in binary form must reproduce the above copyright
+ *     notice, this list of conditions and the following disclaimer in the
+ *     documentation and/or other materials provided with the distribution. 
+ * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
+ *     its contributors may be used to endorse or promote products derived
+ *     from this software without specific prior written permission. 
+ *
+ * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
+ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+#import "config.h"
+#import "MainThread.h"
+
+#import <CoreFoundation/CoreFoundation.h>
+#import <Foundation/NSThread.h>
+#import <dispatch/dispatch.h>
+#import <stdio.h>
+#import <wtf/Assertions.h>
+#import <wtf/HashSet.h>
+#import <wtf/RetainPtr.h>
+#import <wtf/SchedulePair.h>
+#import <wtf/Threading.h>
+
+#if USE(WEB_THREAD)
+#include <wtf/ios/WebCoreThread.h>
+#endif
+
+@interface JSWTFMainThreadCaller : NSObject
+- (void)call;
+@end
+
+@implementation JSWTFMainThreadCaller
+
+- (void)call
+{
+    WTF::dispatchFunctionsFromMainThread();
+}
+
+@end
+
+namespace WTF {
+
+static JSWTFMainThreadCaller* staticMainThreadCaller;
+static bool isTimerPosted; // This is only accessed on the main thread.
+static bool mainThreadEstablishedAsPthreadMain { false };
+static pthread_t mainThreadPthread { nullptr };
+static NSThread* mainThreadNSThread { nullptr };
+
+#if USE(WEB_THREAD)
+static Thread* sApplicationUIThread;
+static Thread* sWebThread;
+#endif
+
+void initializeMainThreadPlatform()
+{
+    ASSERT(!staticMainThreadCaller);
+    staticMainThreadCaller = [[JSWTFMainThreadCaller alloc] init];
+
+#if !USE(WEB_THREAD)
+    mainThreadEstablishedAsPthreadMain = false;
+    mainThreadPthread = pthread_self();
+    mainThreadNSThread = [NSThread currentThread];
+#else
+    mainThreadEstablishedAsPthreadMain = true;
+    ASSERT(!mainThreadPthread);
+    ASSERT(!mainThreadNSThread);
+#endif
+}
+
+#if !USE(WEB_THREAD)
+void initializeMainThreadToProcessMainThreadPlatform()
+{
+    if (!pthread_main_np())
+        NSLog(@"WebKit Threading Violation - initial use of WebKit from a secondary thread.");
+
+    ASSERT(!staticMainThreadCaller);
+    staticMainThreadCaller = [[JSWTFMainThreadCaller alloc] init];
+
+    mainThreadEstablishedAsPthreadMain = true;
+    mainThreadPthread = 0;
+    mainThreadNSThread = nil;
+}
+#endif // !USE(WEB_THREAD)
+
+static void timerFired(CFRunLoopTimerRef timer, void*)
+{
+    CFRelease(timer);
+    isTimerPosted = false;
+
+    @autoreleasepool {
+        WTF::dispatchFunctionsFromMainThread();
+    }
+}
+
+static void postTimer()
+{
+    ASSERT(isMainThread());
+
+    if (isTimerPosted)
+        return;
+
+    isTimerPosted = true;
+    CFRunLoopAddTimer(CFRunLoopGetCurrent(), CFRunLoopTimerCreate(0, 0, 0, 0, 0, timerFired, 0), kCFRunLoopCommonModes);
+}
+
+void scheduleDispatchFunctionsOnMainThread()
+{
+    ASSERT(staticMainThreadCaller);
+
+    if (isWebThread()) {
+        postTimer();
+        return;
+    }
+    
+    if (mainThreadEstablishedAsPthreadMain) {
+        ASSERT(!mainThreadNSThread);
+        [staticMainThreadCaller performSelectorOnMainThread:@selector(call) withObject:nil waitUntilDone:NO];
+        return;
+    }
+
+    ASSERT(mainThreadNSThread);
+    [staticMainThreadCaller performSelector:@selector(call) onThread:mainThreadNSThread withObject:nil waitUntilDone:NO];
+}
+
+void callOnWebThreadOrDispatchAsyncOnMainThread(void (^block)())
+{
+#if USE(WEB_THREAD)
+    if (WebCoreWebThreadIsEnabled && WebCoreWebThreadIsEnabled()) {
+        WebCoreWebThreadRun(block);
+        return;
+    }
+#endif
+    dispatch_async(dispatch_get_main_queue(), block);
+}
+
+#if USE(WEB_THREAD)
+static bool webThreadIsUninitializedOrLockedOrDisabled()
+{
+    return !WebCoreWebThreadIsLockedOrDisabled || WebCoreWebThreadIsLockedOrDisabled();
+}
+
+bool isMainThread()
+{
+    return (isWebThread() || pthread_main_np()) && webThreadIsUninitializedOrLockedOrDisabled();
+}
+
+bool isMainThreadIfInitialized()
+{
+    return isMainThread();
+}
+
+bool isUIThread()
+{
+    return pthread_main_np();
+}
+
+// Keep in mind that isWebThread can be called even when destroying the current thread.
+bool isWebThread()
+{
+    return pthread_equal(pthread_self(), mainThreadPthread);
+}
+
+void initializeApplicationUIThread()
+{
+    ASSERT(pthread_main_np());
+    sApplicationUIThread = &Thread::current();
+}
+
+void initializeWebThreadPlatform()
+{
+    ASSERT(!pthread_main_np());
+
+    mainThreadEstablishedAsPthreadMain = false;
+    mainThreadPthread = pthread_self();
+    mainThreadNSThread = [NSThread currentThread];
+
+    sWebThread = &Thread::current();
+}
+
+bool canAccessThreadLocalDataForThread(Thread& thread)
+{
+    Thread& currentThread = Thread::current();
+    if (&thread == &currentThread)
+        return true;
+
+    if (&thread == sWebThread || &thread == sApplicationUIThread)
+        return (&currentThread == sWebThread || &currentThread == sApplicationUIThread) && webThreadIsUninitializedOrLockedOrDisabled();
+
+    return false;
+}
+#else
+bool isMainThread()
+{
+    if (mainThreadEstablishedAsPthreadMain) {
+        ASSERT(!mainThreadPthread);
+        return pthread_main_np();
+    }
+
+    ASSERT(mainThreadPthread);
+    return pthread_equal(pthread_self(), mainThreadPthread);
+}
+
+bool isMainThreadIfInitialized()
+{
+    if (mainThreadEstablishedAsPthreadMain)
+        return pthread_main_np();
+    return pthread_equal(pthread_self(), mainThreadPthread);
+}
+
+#endif // USE(WEB_THREAD)
+
+} // namespace WTF

Modified: trunk/Source/WTF/wtf/generic/MainThreadGeneric.cpp (236616 => 236617)


--- trunk/Source/WTF/wtf/generic/MainThreadGeneric.cpp	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/wtf/generic/MainThreadGeneric.cpp	2018-09-28 22:32:34 UTC (rev 236617)
@@ -30,7 +30,10 @@
  */
 
 #include "config.h"
-#include "MainThread.h"
+#include <pthread.h>
+#if HAVE(PTHREAD_NP_H)
+#include <pthread_np.h>
+#endif
 
 #include <wtf/RunLoop.h>
 #if USE(GLIB)
@@ -39,6 +42,10 @@
 
 namespace WTF {
 
+#if !HAVE(PTHREAD_MAIN_NP)
+static pthread_t mainThread;
+#endif
+
 class MainThreadDispatcher {
 public:
     MainThreadDispatcher()
@@ -65,8 +72,25 @@
 
 void initializeMainThreadPlatform()
 {
+#if !HAVE(PTHREAD_MAIN_NP)
+    mainThread = pthread_self();
+#endif
 }
 
+bool isMainThread()
+{
+#if HAVE(PTHREAD_MAIN_NP)
+    return pthread_main_np();
+#else
+    return pthread_equal(pthread_self(), mainThread);
+#endif
+}
+
+bool isMainThreadIfInitialized()
+{
+    return isMainThread();
+}
+
 void scheduleDispatchFunctionsOnMainThread()
 {
     // Use a RunLoop::Timer instead of RunLoop::dispatch() to be able to use a different priority and

Deleted: trunk/Source/WTF/wtf/mac/MainThreadMac.mm (236616 => 236617)


--- trunk/Source/WTF/wtf/mac/MainThreadMac.mm	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/wtf/mac/MainThreadMac.mm	2018-09-28 22:32:34 UTC (rev 236617)
@@ -1,230 +0,0 @@
-/*
- * Copyright (C) 2007, 2008 Apple Inc. All rights reserved.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions
- * are met:
- *
- * 1.  Redistributions of source code must retain the above copyright
- *     notice, this list of conditions and the following disclaimer. 
- * 2.  Redistributions in binary form must reproduce the above copyright
- *     notice, this list of conditions and the following disclaimer in the
- *     documentation and/or other materials provided with the distribution. 
- * 3.  Neither the name of Apple Inc. ("Apple") nor the names of
- *     its contributors may be used to endorse or promote products derived
- *     from this software without specific prior written permission. 
- *
- * THIS SOFTWARE IS PROVIDED BY APPLE AND ITS CONTRIBUTORS "AS IS" AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL APPLE OR ITS CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
- * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
- 
-#import "config.h"
-#import "MainThread.h"
-
-#import <CoreFoundation/CoreFoundation.h>
-#import <Foundation/NSThread.h>
-#import <dispatch/dispatch.h>
-#import <stdio.h>
-#import <wtf/Assertions.h>
-#import <wtf/HashSet.h>
-#import <wtf/RetainPtr.h>
-#import <wtf/SchedulePair.h>
-#import <wtf/Threading.h>
-
-#if USE(WEB_THREAD)
-#include <wtf/ios/WebCoreThread.h>
-#endif
-
-@interface JSWTFMainThreadCaller : NSObject
-- (void)call;
-@end
-
-@implementation JSWTFMainThreadCaller
-
-- (void)call
-{
-    WTF::dispatchFunctionsFromMainThread();
-}
-
-@end
-
-namespace WTF {
-
-static JSWTFMainThreadCaller* staticMainThreadCaller;
-static bool isTimerPosted; // This is only accessed on the main thread.
-static bool mainThreadEstablishedAsPthreadMain { false };
-static pthread_t mainThreadPthread { nullptr };
-static NSThread* mainThreadNSThread { nullptr };
-
-#if USE(WEB_THREAD)
-static Thread* sApplicationUIThread;
-static Thread* sWebThread;
-#endif
-
-void initializeMainThreadPlatform()
-{
-    ASSERT(!staticMainThreadCaller);
-    staticMainThreadCaller = [[JSWTFMainThreadCaller alloc] init];
-
-#if !USE(WEB_THREAD)
-    mainThreadEstablishedAsPthreadMain = false;
-    mainThreadPthread = pthread_self();
-    mainThreadNSThread = [NSThread currentThread];
-#else
-    mainThreadEstablishedAsPthreadMain = true;
-    ASSERT(!mainThreadPthread);
-    ASSERT(!mainThreadNSThread);
-#endif
-}
-
-#if !USE(WEB_THREAD)
-void initializeMainThreadToProcessMainThreadPlatform()
-{
-    if (!pthread_main_np())
-        NSLog(@"WebKit Threading Violation - initial use of WebKit from a secondary thread.");
-
-    ASSERT(!staticMainThreadCaller);
-    staticMainThreadCaller = [[JSWTFMainThreadCaller alloc] init];
-
-    mainThreadEstablishedAsPthreadMain = true;
-    mainThreadPthread = 0;
-    mainThreadNSThread = nil;
-}
-#endif // !USE(WEB_THREAD)
-
-static void timerFired(CFRunLoopTimerRef timer, void*)
-{
-    CFRelease(timer);
-    isTimerPosted = false;
-
-    @autoreleasepool {
-        WTF::dispatchFunctionsFromMainThread();
-    }
-}
-
-static void postTimer()
-{
-    ASSERT(isMainThread());
-
-    if (isTimerPosted)
-        return;
-
-    isTimerPosted = true;
-    CFRunLoopAddTimer(CFRunLoopGetCurrent(), CFRunLoopTimerCreate(0, 0, 0, 0, 0, timerFired, 0), kCFRunLoopCommonModes);
-}
-
-void scheduleDispatchFunctionsOnMainThread()
-{
-    ASSERT(staticMainThreadCaller);
-
-    if (isWebThread()) {
-        postTimer();
-        return;
-    }
-    
-    if (mainThreadEstablishedAsPthreadMain) {
-        ASSERT(!mainThreadNSThread);
-        [staticMainThreadCaller performSelectorOnMainThread:@selector(call) withObject:nil waitUntilDone:NO];
-        return;
-    }
-
-    ASSERT(mainThreadNSThread);
-    [staticMainThreadCaller performSelector:@selector(call) onThread:mainThreadNSThread withObject:nil waitUntilDone:NO];
-}
-
-void callOnWebThreadOrDispatchAsyncOnMainThread(void (^block)())
-{
-#if USE(WEB_THREAD)
-    if (WebCoreWebThreadIsEnabled && WebCoreWebThreadIsEnabled()) {
-        WebCoreWebThreadRun(block);
-        return;
-    }
-#endif
-    dispatch_async(dispatch_get_main_queue(), block);
-}
-
-#if USE(WEB_THREAD)
-static bool webThreadIsUninitializedOrLockedOrDisabled()
-{
-    return !WebCoreWebThreadIsLockedOrDisabled || WebCoreWebThreadIsLockedOrDisabled();
-}
-
-bool isMainThread()
-{
-    return (isWebThread() || pthread_main_np()) && webThreadIsUninitializedOrLockedOrDisabled();
-}
-
-bool isMainThreadIfInitialized()
-{
-    return isMainThread();
-}
-
-bool isUIThread()
-{
-    return pthread_main_np();
-}
-
-// Keep in mind that isWebThread can be called even when destroying the current thread.
-bool isWebThread()
-{
-    return pthread_equal(pthread_self(), mainThreadPthread);
-}
-
-void initializeApplicationUIThread()
-{
-    ASSERT(pthread_main_np());
-    sApplicationUIThread = &Thread::current();
-}
-
-void initializeWebThreadPlatform()
-{
-    ASSERT(!pthread_main_np());
-
-    mainThreadEstablishedAsPthreadMain = false;
-    mainThreadPthread = pthread_self();
-    mainThreadNSThread = [NSThread currentThread];
-
-    sWebThread = &Thread::current();
-}
-
-bool canAccessThreadLocalDataForThread(Thread& thread)
-{
-    Thread& currentThread = Thread::current();
-    if (&thread == &currentThread)
-        return true;
-
-    if (&thread == sWebThread || &thread == sApplicationUIThread)
-        return (&currentThread == sWebThread || &currentThread == sApplicationUIThread) && webThreadIsUninitializedOrLockedOrDisabled();
-
-    return false;
-}
-#else
-bool isMainThread()
-{
-    if (mainThreadEstablishedAsPthreadMain) {
-        ASSERT(!mainThreadPthread);
-        return pthread_main_np();
-    }
-
-    ASSERT(mainThreadPthread);
-    return pthread_equal(pthread_self(), mainThreadPthread);
-}
-
-bool isMainThreadIfInitialized()
-{
-    if (mainThreadEstablishedAsPthreadMain)
-        return pthread_main_np();
-    return pthread_equal(pthread_self(), mainThreadPthread);
-}
-
-#endif // USE(WEB_THREAD)
-
-} // namespace WTF

Modified: trunk/Source/WTF/wtf/win/MainThreadWin.cpp (236616 => 236617)


--- trunk/Source/WTF/wtf/win/MainThreadWin.cpp	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/WTF/wtf/win/MainThreadWin.cpp	2018-09-28 22:32:34 UTC (rev 236617)
@@ -39,6 +39,7 @@
 static HWND threadingWindowHandle;
 static UINT threadingFiredMessage;
 const LPCWSTR kThreadingWindowClassName = L"ThreadingWindowClass";
+static ThreadIdentifier mainThread { 0 };
 
 LRESULT CALLBACK ThreadingWindowWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
 {
@@ -64,9 +65,21 @@
         CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, HWND_MESSAGE, 0, 0, 0);
     threadingFiredMessage = RegisterWindowMessageW(L"com.apple.WebKit.MainThreadFired");
 
+    mainThread = Thread::currentID();
+
     Thread::initializeCurrentThreadInternal("Main Thread");
 }
 
+bool isMainThread()
+{
+    return mainThread == Thread::currentID();
+}
+
+bool isMainThreadIfInitialized()
+{
+    return isMainThread();
+}
+
 void scheduleDispatchFunctionsOnMainThread()
 {
     ASSERT(threadingWindowHandle);

Modified: trunk/Source/cmake/OptionsCommon.cmake (236616 => 236617)


--- trunk/Source/cmake/OptionsCommon.cmake	2018-09-28 22:12:07 UTC (rev 236616)
+++ trunk/Source/cmake/OptionsCommon.cmake	2018-09-28 22:32:34 UTC (rev 236617)
@@ -134,6 +134,7 @@
 
 # Check for symbols
 WEBKIT_CHECK_HAVE_SYMBOL(HAVE_REGEX_H regexec regex.h)
+WEBKIT_CHECK_HAVE_SYMBOL(HAVE_PTHREAD_MAIN_NP pthread_main_np pthread_np.h)
 # Windows has signal.h but is missing symbols that are used in calls to signal.
 WEBKIT_CHECK_HAVE_SYMBOL(HAVE_SIGNAL_H SIGTRAP signal.h)
 
_______________________________________________
webkit-changes mailing list
[email protected]
https://lists.webkit.org/mailman/listinfo/webkit-changes

Reply via email to