Bug 1360236 - make gSocketThread an internal implementation detail of nsSocketTransportService; r=mcmanus
authorNathan Froyd <froydnj@mozilla.com>
Thu, 27 Apr 2017 14:34:42 -0400
changeset 355469 3dc6e29a0128ede6af3f325239dfff97d8ec2cef
parent 355468 2cedd1aab52c76a8f39bc9bf57a3798c0129353c
child 355470 88c2a0b2dde53837f770d76050f35aaa18c03bbd
push id31727
push usercbook@mozilla.com
push dateFri, 28 Apr 2017 08:36:40 +0000
treeherdermozilla-central@8f2b930cd028 [default view] [failures only]
perfherder[talos] [build metrics] [platform microbench] (compared to previous push)
reviewersmcmanus
bugs1360236
milestone55.0a1
first release with
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
last release without
nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
Bug 1360236 - make gSocketThread an internal implementation detail of nsSocketTransportService; r=mcmanus This change makes the code a little cleaner and reduces the number of places we call PR_GetCurrentThread, which is important for Quantum DOM scheduling work. The conversion was largely automatic, via: find netwerk/ -name \*.cpp | \ xargs sed -i -e 's/MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread[^;]*/MOZ_ASSERT(OnSocketThread(), "not on socket thread")/' and related invocations, with a few manual tweaks at the end.
netwerk/base/EventTokenBucket.cpp
netwerk/base/NetworkActivityMonitor.cpp
netwerk/base/PollableEvent.cpp
netwerk/base/TLSServerSocket.cpp
netwerk/base/ThrottleQueue.cpp
netwerk/base/nsSocketTransport2.cpp
netwerk/base/nsSocketTransport2.h
netwerk/base/nsSocketTransportService2.cpp
netwerk/base/nsSocketTransportService2.h
netwerk/dns/mdns/libmdns/MDNSResponderOperator.cpp
netwerk/dns/mdns/libmdns/MDNSResponderReply.cpp
netwerk/protocol/http/ConnectionDiagnostics.cpp
netwerk/protocol/http/Http2Compression.cpp
netwerk/protocol/http/Http2Session.cpp
netwerk/protocol/http/Http2Stream.cpp
netwerk/protocol/http/TunnelUtils.cpp
netwerk/protocol/http/nsHttpConnection.cpp
netwerk/protocol/http/nsHttpConnectionMgr.cpp
netwerk/protocol/http/nsHttpHandler.cpp
netwerk/protocol/http/nsHttpHandler.h
netwerk/protocol/http/nsHttpTransaction.cpp
netwerk/protocol/websocket/WebSocketChannel.cpp
netwerk/protocol/websocket/WebSocketFrame.cpp
netwerk/socket/nsNamedPipeIOLayer.cpp
--- a/netwerk/base/EventTokenBucket.cpp
+++ b/netwerk/base/EventTokenBucket.cpp
@@ -50,17 +50,17 @@ NS_IMPL_ISUPPORTS(TokenBucketCancelable,
 TokenBucketCancelable::TokenBucketCancelable(ATokenBucketEvent *event)
   : mEvent(event)
 {
 }
 
 NS_IMETHODIMP
 TokenBucketCancelable::Cancel(nsresult reason)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   mEvent = nullptr;
   return NS_OK;
 }
 
 void
 TokenBucketCancelable::Fire()
 {
   if (!mEvent)
@@ -166,83 +166,83 @@ EventTokenBucket::SetRate(uint32_t event
   }
   mCredit = mMaxCredit;
   mLastUpdate = TimeStamp::Now();
 }
 
 void
 EventTokenBucket::ClearCredits()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   SOCKET_LOG(("EventTokenBucket::ClearCredits %p\n", this));
   mCredit = 0;
 }
 
 uint32_t
 EventTokenBucket::BurstEventsAvailable()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   return static_cast<uint32_t>(mCredit / mUnitCost);
 }
 
 uint32_t
 EventTokenBucket::QueuedEvents()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   return mEvents.GetSize();
 }
 
 void
 EventTokenBucket::Pause()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   SOCKET_LOG(("EventTokenBucket::Pause %p\n", this));
   if (mPaused || mStopped)
     return;
 
   mPaused = true;
   if (mTimerArmed) {
     mTimer->Cancel();
     mTimerArmed = false;
   }
 }
 
 void
 EventTokenBucket::UnPause()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   SOCKET_LOG(("EventTokenBucket::UnPause %p\n", this));
   if (!mPaused || mStopped)
     return;
 
   mPaused = false;
   DispatchEvents();
   UpdateTimer();
 }
 
 void
 EventTokenBucket::Stop()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   SOCKET_LOG(("EventTokenBucket::Stop %p armed=%d\n", this, mTimerArmed));
   mStopped = true;
   CleanupTimers();
 
   // Complete any queued events to prevent hangs
   while (mEvents.GetSize()) {
     RefPtr<TokenBucketCancelable> cancelable =
       dont_AddRef(static_cast<TokenBucketCancelable *>(mEvents.PopFront()));
     cancelable->Fire();
   }
 }
 
 nsresult
 EventTokenBucket::SubmitEvent(ATokenBucketEvent *event, nsICancelable **cancelable)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   SOCKET_LOG(("EventTokenBucket::SubmitEvent %p\n", this));
 
   if (mStopped || !mTimer)
     return NS_ERROR_FAILURE;
 
   UpdateCredits();
 
   RefPtr<TokenBucketCancelable> cancelEvent = new TokenBucketCancelable(event);
@@ -273,17 +273,17 @@ EventTokenBucket::TryImmediateDispatch(T
   mCredit -= mUnitCost;
   cancelable->Fire();
   return true;
 }
 
 void
 EventTokenBucket::DispatchEvents()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   SOCKET_LOG(("EventTokenBucket::DispatchEvents %p %d\n", this, mPaused));
   if (mPaused || mStopped)
     return;
 
   while (mEvents.GetSize() && mUnitCost <= mCredit) {
     RefPtr<TokenBucketCancelable> cancelable = 
       dont_AddRef(static_cast<TokenBucketCancelable *>(mEvents.PopFront()));
     if (cancelable->mEvent) {
@@ -299,17 +299,17 @@ EventTokenBucket::DispatchEvents()
   if (!mEvents.GetSize())
     WantNormalTimers();
 #endif
 }
  
 void
 EventTokenBucket::UpdateTimer()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   if (mTimerArmed || mPaused || mStopped || !mEvents.GetSize() || !mTimer)
     return;
 
   if (mCredit >= mUnitCost)
     return;
 
   // determine the time needed to wait to accumulate enough credits to admit
   // one more event and set the timer for that point. Always round it
@@ -332,17 +332,17 @@ EventTokenBucket::UpdateTimer()
   nsresult rv = mTimer->InitWithCallback(this, static_cast<uint32_t>(msecWait),
                                          nsITimer::TYPE_ONE_SHOT);
   mTimerArmed = NS_SUCCEEDED(rv);
 }
 
 NS_IMETHODIMP
 EventTokenBucket::Notify(nsITimer *timer)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
 #ifdef XP_WIN
   if (timer == mFineGrainResetTimer) {
     FineGrainResetTimerNotify();
     return NS_OK;
   }
 #endif
 
@@ -356,17 +356,17 @@ EventTokenBucket::Notify(nsITimer *timer
   UpdateTimer();
 
   return NS_OK;
 }
 
 void
 EventTokenBucket::UpdateCredits()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   TimeStamp now = TimeStamp::Now();
   TimeDuration elapsed = now - mLastUpdate;
   mLastUpdate = now;
 
   mCredit += static_cast<uint64_t>(elapsed.ToMicroseconds());
   if (mCredit > mMaxCredit)
     mCredit = mMaxCredit;
--- a/netwerk/base/NetworkActivityMonitor.cpp
+++ b/netwerk/base/NetworkActivityMonitor.cpp
@@ -273,17 +273,17 @@ NetworkActivityMonitor::AttachIOLayer(PR
   }
 
   return NS_OK;
 }
 
 nsresult
 NetworkActivityMonitor::DataInOut(Direction direction)
 {
-  NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (gInstance) {
     PRIntervalTime now = PR_IntervalNow();
     if ((now - gInstance->mLastNotificationTime[direction]) >
         gInstance->mBlipInterval) {
       gInstance->mLastNotificationTime[direction] = now;
       gInstance->PostNotification(direction);
     }
--- a/netwerk/base/PollableEvent.cpp
+++ b/netwerk/base/PollableEvent.cpp
@@ -26,17 +26,17 @@ namespace net {
 
 #ifndef USEPIPE
 static PRDescIdentity sPollableEventLayerIdentity;
 static PRIOMethods    sPollableEventLayerMethods;
 static PRIOMethods   *sPollableEventLayerMethodsPtr = nullptr;
 
 static void LazyInitSocket()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   if (sPollableEventLayerMethodsPtr) {
     return;
   }
   sPollableEventLayerIdentity = PR_GetUniqueIdentity("PollableEvent Layer");
   sPollableEventLayerMethods = *PR_GetDefaultIOMethods();
   sPollableEventLayerMethodsPtr = &sPollableEventLayerMethods;
 }
 
@@ -135,17 +135,17 @@ failed:
 #endif
 
 PollableEvent::PollableEvent()
   : mWriteFD(nullptr)
   , mReadFD(nullptr)
   , mSignaled(false)
 {
   MOZ_COUNT_CTOR(PollableEvent);
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   // create pair of prfiledesc that can be used as a poll()ble
   // signal. on windows use a localhost socket pair, and on
   // unix use a pipe.
 #ifdef USEPIPE
   SOCKET_LOG(("PollableEvent() using pipe\n"));
   if (PR_CreatePipe(&mReadFD, &mWriteFD) == PR_SUCCESS) {
     // make the pipe non blocking. NSPR asserts at
     // trying to use SockOpt here
@@ -252,17 +252,17 @@ PollableEvent::Signal()
     return false;
   }
 #ifndef XP_WIN
   // On windows poll can hang and this became worse when we introduced the
   // patch for bug 698882 (see also bug 1292181), therefore we reverted the
   // behavior on windows to be as before bug 698882, e.g. write to the socket
   // also if an event dispatch is on the socket thread and writing to the
   // socket for each event. See bug 1292181.
-  if (PR_GetCurrentThread() == gSocketThread) {
+  if (OnSocketThread()) {
     SOCKET_LOG(("PollableEvent::Signal OnSocketThread nop\n"));
     return true;
   }
 #endif
 
 #ifndef XP_WIN
   // To wake up the poll writing once is enough, but for Windows that can cause
   // hangs so we will write for every event.
@@ -282,17 +282,17 @@ PollableEvent::Signal()
   }
   return (status == 1);
 }
 
 bool
 PollableEvent::Clear()
 {
   // necessary because of the "dont signal on socket thread" optimization
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   SOCKET_LOG(("PollableEvent::Clear\n"));
   mSignaled = false;
   if (!mReadFD) {
     SOCKET_LOG(("PollableEvent::Clear mReadFD is null\n"));
     return false;
   }
   char buf[2048];
--- a/netwerk/base/TLSServerSocket.cpp
+++ b/netwerk/base/TLSServerSocket.cpp
@@ -64,17 +64,17 @@ TLSServerSocket::SetSocketDefaults()
 
   return NS_OK;
 }
 
 void
 TLSServerSocket::CreateClientTransport(PRFileDesc* aClientFD,
                                        const NetAddr& aClientAddr)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsresult rv;
 
   RefPtr<nsSocketTransport> trans = new nsSocketTransport;
   if (NS_WARN_IF(!trans)) {
     mCondition = NS_ERROR_OUT_OF_MEMORY;
     return;
   }
 
--- a/netwerk/base/ThrottleQueue.cpp
+++ b/netwerk/base/ThrottleQueue.cpp
@@ -259,29 +259,29 @@ ThrottleQueue::~ThrottleQueue()
     mTimer->Cancel();
   }
   mTimer = nullptr;
 }
 
 NS_IMETHODIMP
 ThrottleQueue::RecordRead(uint32_t aBytesRead)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   ThrottleEntry entry;
   entry.mTime = TimeStamp::Now();
   entry.mBytesRead = aBytesRead;
   mReadEvents.AppendElement(entry);
   mBytesProcessed += aBytesRead;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 ThrottleQueue::Available(uint32_t aRemaining, uint32_t* aAvailable)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   TimeStamp now = TimeStamp::Now();
   TimeStamp oneSecondAgo = now - TimeDuration::FromSeconds(1);
   size_t i;
 
   // Remove all stale events.
   for (i = 0; i < mReadEvents.Length(); ++i) {
     if (mReadEvents[i].mTime >= oneSecondAgo) {
       break;
@@ -333,17 +333,17 @@ ThrottleQueue::WrapStream(nsIInputStream
   nsCOMPtr<nsIAsyncInputStream> result = new ThrottleInputStream(aInputStream, this);
   result.forget(aResult);
   return NS_OK;
 }
 
 NS_IMETHODIMP
 ThrottleQueue::Notify(nsITimer* aTimer)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   // A notified reader may need to push itself back on the queue.
   // Swap out the list of readers so that this works properly.
   nsTArray<RefPtr<ThrottleInputStream>> events;
   events.SwapElements(mAsyncEvents);
 
   // Optimistically notify all the waiting readers, and then let them
   // requeue if there isn't enough bandwidth.
   for (size_t i = 0; i < events.Length(); ++i) {
@@ -352,17 +352,17 @@ ThrottleQueue::Notify(nsITimer* aTimer)
 
   mTimerArmed = false;
   return NS_OK;
 }
 
 void
 ThrottleQueue::QueueStream(ThrottleInputStream* aStream)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   if (mAsyncEvents.IndexOf(aStream) == mAsyncEvents.NoIndex) {
     mAsyncEvents.AppendElement(aStream);
 
     if (!mTimerArmed) {
       uint32_t ms = 1000;
       if (mReadEvents.Length() > 0) {
         TimeStamp t = mReadEvents[0].mTime + TimeDuration::FromSeconds(1);
         TimeStamp now = TimeStamp::Now();
@@ -379,14 +379,14 @@ ThrottleQueue::QueueStream(ThrottleInput
       }
     }
   }
 }
 
 void
 ThrottleQueue::DequeueStream(ThrottleInputStream* aStream)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   mAsyncEvents.RemoveElement(aStream);
 }
 
 }
 }
--- a/netwerk/base/nsSocketTransport2.cpp
+++ b/netwerk/base/nsSocketTransport2.cpp
@@ -265,17 +265,17 @@ nsSocketInputStream::~nsSocketInputStrea
 //   condition : failure code if socket has been closed
 //
 void
 nsSocketInputStream::OnSocketReady(nsresult condition)
 {
     SOCKET_LOG(("nsSocketInputStream::OnSocketReady [this=%p cond=%" PRIx32 "]\n",
                 this, static_cast<uint32_t>(condition)));
 
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsCOMPtr<nsIInputStreamCallback> callback;
     {
         MutexAutoLock lock(mTransport->mLock);
 
         // update condition, but be careful not to erase an already
         // existing error condition.
         if (NS_SUCCEEDED(mCondition))
@@ -529,17 +529,17 @@ nsSocketOutputStream::~nsSocketOutputStr
 //   condition : failure code if socket has been closed
 //
 void
 nsSocketOutputStream::OnSocketReady(nsresult condition)
 {
     SOCKET_LOG(("nsSocketOutputStream::OnSocketReady [this=%p cond=%" PRIx32 "]\n",
                 this, static_cast<uint32_t>(condition)));
 
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsCOMPtr<nsIOutputStreamCallback> callback;
     {
         MutexAutoLock lock(mTransport->mLock);
 
         // update condition, but be careful not to erase an already
         // existing error condition.
         if (NS_SUCCEEDED(mCondition))
@@ -932,17 +932,17 @@ nsSocketTransport::InitWithFilename(cons
 #else
     return NS_ERROR_SOCKET_ADDRESS_NOT_SUPPORTED;
 #endif
 }
 
 nsresult
 nsSocketTransport::InitWithConnectedSocket(PRFileDesc *fd, const NetAddr *addr)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     NS_ASSERTION(!mFD.IsInitialized(), "already initialized");
 
     char buf[kNetAddrMaxCStrBufSize];
     NetAddrToString(addr, buf, sizeof(buf));
     mHost.Assign(buf);
 
     uint16_t port;
     if (addr->raw.family == AF_INET)
@@ -1687,17 +1687,17 @@ nsSocketTransport::RecoverFromError()
 
 // called on the socket thread only
 void
 nsSocketTransport::OnMsgInputClosed(nsresult reason)
 {
     SOCKET_LOG(("nsSocketTransport::OnMsgInputClosed [this=%p reason=%" PRIx32 "]\n",
         this, static_cast<uint32_t>(reason)));
 
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     mInputClosed = true;
     // check if event should affect entire transport
     if (NS_FAILED(reason) && (reason != NS_BASE_STREAM_CLOSED))
         mCondition = reason;                // XXX except if NS_FAILED(mCondition), right??
     else if (mOutputClosed)
         mCondition = NS_BASE_STREAM_CLOSED; // XXX except if NS_FAILED(mCondition), right??
     else {
@@ -1709,17 +1709,17 @@ nsSocketTransport::OnMsgInputClosed(nsre
 
 // called on the socket thread only
 void
 nsSocketTransport::OnMsgOutputClosed(nsresult reason)
 {
     SOCKET_LOG(("nsSocketTransport::OnMsgOutputClosed [this=%p reason=%" PRIx32 "]\n",
         this, static_cast<uint32_t>(reason)));
 
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     mOutputClosed = true;
     // check if event should affect entire transport
     if (NS_FAILED(reason) && (reason != NS_BASE_STREAM_CLOSED))
         mCondition = reason;                // XXX except if NS_FAILED(mCondition), right??
     else if (mInputClosed)
         mCondition = NS_BASE_STREAM_CLOSED; // XXX except if NS_FAILED(mCondition), right??
     else {
@@ -1727,17 +1727,17 @@ nsSocketTransport::OnMsgOutputClosed(nsr
             mPollFlags &= ~PR_POLL_WRITE;
         mOutput.OnSocketReady(reason);
     }
 }
 
 void
 nsSocketTransport::OnSocketConnected()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     SOCKET_LOG(("  advancing to STATE_TRANSFERRING\n"));
 
     mPollFlags = (PR_POLL_READ | PR_POLL_WRITE | PR_POLL_EXCEPT);
     mPollTimeout = mTimeouts[TIMEOUT_READ_WRITE];
     mState = STATE_TRANSFERRING;
 
     // Set the m*AddrIsSet flags only when state has reached TRANSFERRING
     // because we need to make sure its value does not change due to failover
@@ -1763,17 +1763,17 @@ nsSocketTransport::OnSocketConnected()
     }
 
     SendStatus(NS_NET_STATUS_CONNECTED_TO);
 }
 
 void
 nsSocketTransport::SetSocketName(PRFileDesc *fd)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     if (mSelfAddrIsSet) {
         return;
     }
 
     PRNetAddr prAddr;
     memset(&prAddr, 0, sizeof(prAddr));
     if (PR_GetSockName(fd, &prAddr) == PR_SUCCESS) {
         PRNetAddrToNetAddr(&prAddr, &mSelfAddr);
@@ -1811,18 +1811,16 @@ private:
   PRFileDesc *mFD;
 };
 
 void
 STS_PRCloseOnSocketTransport(PRFileDesc *fd)
 {
   if (gSocketTransportService) {
     // Can't PR_Close() a socket off STS thread. Thunk it to STS to die
-    // FIX - Should use RUN_ON_THREAD once it's generally available
-    // RUN_ON_THREAD(gSocketThread,WrapRunnableNM(&PR_Close, mFD);
     gSocketTransportService->Dispatch(new ThunkPRClose(fd), NS_DISPATCH_NORMAL);
   } else {
     // something horrible has happened
     NS_ASSERTION(gSocketTransportService, "No STS service");
   }
 }
 
 void
@@ -1834,17 +1832,17 @@ nsSocketTransport::ReleaseFD_Locked(PRFi
     SOCKET_LOG(("JIMB: ReleaseFD_Locked: mFDref = %" PRIuPTR "\n", mFDref));
 
     if (--mFDref == 0) {
         if (gIOService->IsNetTearingDown() &&
             ((PR_IntervalNow() - gIOService->NetTearingDownStarted()) >
              gSocketTransportService->MaxTimeForPrClosePref())) {
           // If shutdown last to long, let the socket leak and do not close it.
           SOCKET_LOG(("Intentional leak"));
-        } else if (PR_GetCurrentThread() == gSocketThread) {
+        } else if (OnSocketThread()) {
             SOCKET_LOG(("nsSocketTransport: calling PR_Close [this=%p]\n", this));
             CloseSocket(mFD,
                 mSocketTransportService->IsTelemetryEnabledAndNotSleepPhase());
         } else {
             // Can't PR_Close() a socket off STS thread. Thunk it to STS to die
             STS_PRCloseOnSocketTransport(mFD);
         }
         mFD = nullptr;
@@ -2093,17 +2091,17 @@ nsSocketTransport::OnSocketReady(PRFileD
 
 // called on the socket thread only
 void
 nsSocketTransport::OnSocketDetached(PRFileDesc *fd)
 {
     SOCKET_LOG(("nsSocketTransport::OnSocketDetached [this=%p cond=%" PRIx32 "]\n",
                 this, static_cast<uint32_t>(mCondition)));
 
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // if we didn't initiate this detach, then be sure to pass an error
     // condition up to our consumers.  (e.g., STS is shutting down.)
     if (NS_SUCCEEDED(mCondition)) {
         if (gIOService->IsOffline()) {
           mCondition = NS_ERROR_OFFLINE;
         }
         else {
@@ -2400,25 +2398,25 @@ nsSocketTransport::GetPort(int32_t *port
 {
     *port = (int32_t) SocketPort();
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransport::GetNetworkInterfaceId(nsACString &aNetworkInterfaceId)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     aNetworkInterfaceId = mNetworkInterfaceId;
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransport::SetNetworkInterfaceId(const nsACString &aNetworkInterfaceId)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     mNetworkInterfaceId = aNetworkInterfaceId;
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransport::GetScriptableOriginAttributes(JSContext* aCx,
     JS::MutableHandle<JS::Value> aOriginAttributes)
 {
@@ -2751,17 +2749,17 @@ nsSocketTransport::SetConnectionFlags(ui
     mConnectionFlags = value;
     mIsPrivate = value & nsISocketTransport::NO_PERMANENT_STORAGE;
     return NS_OK;
 }
 
 void
 nsSocketTransport::OnKeepaliveEnabledPrefChange(bool aEnabled)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // The global pref toggles keepalive as a system feature; it only affects
     // an individual socket if keepalive has been specifically enabled for it.
     // So, ensure keepalive is configured correctly if previously enabled.
     if (mKeepaliveEnabled) {
         nsresult rv = SetKeepaliveEnabledInternal(aEnabled);
         if (NS_WARN_IF(NS_FAILED(rv))) {
             SOCKET_LOG(("  SetKeepaliveEnabledInternal [%s] failed rv[0x%" PRIx32 "]",
@@ -2841,17 +2839,17 @@ nsSocketTransport::EnsureKeepaliveValsAr
     }
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransport::SetKeepaliveEnabled(bool aEnable)
 {
 #if defined(XP_WIN) || defined(XP_UNIX) || defined(XP_MACOSX)
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (aEnable == mKeepaliveEnabled) {
         SOCKET_LOG(("nsSocketTransport::SetKeepaliveEnabled [%p] already %s.",
                     this, aEnable ? "enabled" : "disabled"));
         return NS_OK;
     }
 
     nsresult rv = NS_OK;
@@ -2892,17 +2890,17 @@ nsSocketTransport::SetKeepaliveEnabled(b
 #endif
 }
 
 NS_IMETHODIMP
 nsSocketTransport::SetKeepaliveVals(int32_t aIdleTime,
                                     int32_t aRetryInterval)
 {
 #if defined(XP_WIN) || defined(XP_UNIX) || defined(XP_MACOSX)
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     if (NS_WARN_IF(aIdleTime <= 0 || kMaxTCPKeepIdle < aIdleTime)) {
         return NS_ERROR_INVALID_ARG;
     }
     if (NS_WARN_IF(aRetryInterval <= 0 ||
                    kMaxTCPKeepIntvl < aRetryInterval)) {
         return NS_ERROR_INVALID_ARG;
     }
 
@@ -3043,17 +3041,17 @@ static void LogNSPRError(const char* aPr
                aPrefix ? aPrefix : "nsSocketTransport", aObjPtr, errCode,
                errLen > 0 ? errStr.BeginReading() : "<no error text>").get());
 #endif
 }
 
 nsresult
 nsSocketTransport::PRFileDescAutoLock::SetKeepaliveEnabled(bool aEnable)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(!(aEnable && !gSocketTransportService->IsKeepaliveEnabled()),
                "Cannot enable keepalive if global pref is disabled!");
     if (aEnable && !gSocketTransportService->IsKeepaliveEnabled()) {
         return NS_ERROR_ILLEGAL_VALUE;
     }
 
     PRSocketOptionData opt;
 
@@ -3066,17 +3064,17 @@ nsSocketTransport::PRFileDescAutoLock::S
         return ErrorAccordingToNSPR(PR_GetError());
     }
     return NS_OK;
 }
 
 static void LogOSError(const char *aPrefix, const void *aObjPtr)
 {
 #if defined(DEBUG)
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
 #ifdef XP_WIN
     DWORD errCode = WSAGetLastError();
     LPVOID errMessage;
     FormatMessage(FORMAT_MESSAGE_ALLOCATE_BUFFER |
                   FORMAT_MESSAGE_FROM_SYSTEM |
                   FORMAT_MESSAGE_IGNORE_INSERTS,
                   NULL,
@@ -3105,17 +3103,17 @@ static void LogOSError(const char *aPref
 
 nsresult
 nsSocketTransport::PRFileDescAutoLock::SetKeepaliveVals(bool aEnabled,
                                                         int aIdleTime,
                                                         int aRetryInterval,
                                                         int aProbeCount)
 {
 #if defined(XP_WIN) || defined(XP_UNIX) || defined(XP_MACOSX)
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     if (NS_WARN_IF(aIdleTime <= 0 || kMaxTCPKeepIdle < aIdleTime)) {
         return NS_ERROR_INVALID_ARG;
     }
     if (NS_WARN_IF(aRetryInterval <= 0 ||
                    kMaxTCPKeepIntvl < aRetryInterval)) {
         return NS_ERROR_INVALID_ARG;
     }
     if (NS_WARN_IF(aProbeCount <= 0 || kMaxTCPKeepCount < aProbeCount)) {
--- a/netwerk/base/nsSocketTransport2.h
+++ b/netwerk/base/nsSocketTransport2.h
@@ -408,41 +408,41 @@ private:
     void        ReleaseFD_Locked(PRFileDesc *fd);
 
     //
     // stream state changes (called outside mLock):
     //
     void OnInputClosed(nsresult reason)
     {
         // no need to post an event if called on the socket thread
-        if (PR_GetCurrentThread() == gSocketThread)
+        if (OnSocketThread())
             OnMsgInputClosed(reason);
         else
             PostEvent(MSG_INPUT_CLOSED, reason);
     }
     void OnInputPending()
     {
         // no need to post an event if called on the socket thread
-        if (PR_GetCurrentThread() == gSocketThread)
+        if (OnSocketThread())
             OnMsgInputPending();
         else
             PostEvent(MSG_INPUT_PENDING);
     }
     void OnOutputClosed(nsresult reason)
     {
         // no need to post an event if called on the socket thread
-        if (PR_GetCurrentThread() == gSocketThread)
+        if (OnSocketThread())
             OnMsgOutputClosed(reason); // XXX need to not be inside lock!
         else
             PostEvent(MSG_OUTPUT_CLOSED, reason);
     }
     void OnOutputPending()
     {
         // no need to post an event if called on the socket thread
-        if (PR_GetCurrentThread() == gSocketThread)
+        if (OnSocketThread())
             OnMsgOutputPending();
         else
             PostEvent(MSG_OUTPUT_PENDING);
     }
 
 #ifdef ENABLE_SOCKET_TRACING
     void TraceInBuf(const char *buf, int32_t n);
     void TraceOutBuf(const char *buf, int32_t n);
--- a/netwerk/base/nsSocketTransportService2.cpp
+++ b/netwerk/base/nsSocketTransportService2.cpp
@@ -36,17 +36,17 @@
 namespace mozilla {
 namespace net {
 
 LazyLogModule gSocketTransportLog("nsSocketTransport");
 LazyLogModule gUDPSocketLog("UDPSocket");
 LazyLogModule gTCPSocketLog("TCPSocket");
 
 nsSocketTransportService *gSocketTransportService = nullptr;
-Atomic<PRThread*, Relaxed> gSocketThread;
+static Atomic<PRThread*, Relaxed> gSocketThread;
 
 #define SEND_BUFFER_PREF "network.tcp.sendbuffer"
 #define KEEPALIVE_ENABLED_PREF "network.tcp.keepalive.enabled"
 #define KEEPALIVE_IDLE_TIME_PREF "network.tcp.keepalive.idle_time"
 #define KEEPALIVE_RETRY_INTERVAL_PREF "network.tcp.keepalive.retry_interval"
 #define KEEPALIVE_PROBE_COUNT_PREF "network.tcp.keepalive.probe_count"
 #define SOCKET_LIMIT_TARGET 1000U
 #define SOCKET_LIMIT_MIN      50U
@@ -55,16 +55,23 @@ Atomic<PRThread*, Relaxed> gSocketThread
 #define TELEMETRY_PREF "toolkit.telemetry.enabled"
 #define MAX_TIME_FOR_PR_CLOSE_DURING_SHUTDOWN "network.sts.max_time_for_pr_close_during_shutdown"
 
 #define REPAIR_POLLABLE_EVENT_TIME 10
 
 uint32_t nsSocketTransportService::gMaxCount;
 PRCallOnceType nsSocketTransportService::gMaxCountInitOnce;
 
+// Utility functions
+bool
+OnSocketThread()
+{
+  return PR_GetCurrentThread() == gSocketThread;
+}
+
 //-----------------------------------------------------------------------------
 // ctor/dtor (called on the main/UI thread by the service manager)
 
 nsSocketTransportService::nsSocketTransportService()
     : mThread(nullptr)
     , mLock("nsSocketTransportService::mLock")
     , mInitialized(false)
     , mShuttingDown(false)
@@ -169,33 +176,33 @@ nsSocketTransportService::IsOnCurrentThr
 //-----------------------------------------------------------------------------
 // socket api (socket thread only)
 
 NS_IMETHODIMP
 nsSocketTransportService::NotifyWhenCanAttachSocket(nsIRunnable *event)
 {
     SOCKET_LOG(("nsSocketTransportService::NotifyWhenCanAttachSocket\n"));
 
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (CanAttachSocket()) {
         return Dispatch(event, NS_DISPATCH_NORMAL);
     }
 
     auto *runnable = new LinkedRunnableEvent(event);
     mPendingSocketQueue.insertBack(runnable);
     return NS_OK;
 }
 
 NS_IMETHODIMP
 nsSocketTransportService::AttachSocket(PRFileDesc *fd, nsASocketHandler *handler)
 {
     SOCKET_LOG(("nsSocketTransportService::AttachSocket [handler=%p]\n", handler));
 
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (!CanAttachSocket()) {
         return NS_ERROR_NOT_AVAILABLE;
     }
 
     SocketContext sock;
     sock.mFD = fd;
     sock.mHandler = handler;
@@ -778,17 +785,17 @@ NS_IMETHODIMP
 nsSocketTransportService::OnDispatchedEvent(nsIThreadInternal *thread)
 {
 #ifndef XP_WIN
     // On windows poll can hang and this became worse when we introduced the
     // patch for bug 698882 (see also bug 1292181), therefore we reverted the
     // behavior on windows to be as before bug 698882, e.g. write to the socket
     // also if an event dispatch is on the socket thread and writing to the
     // socket for each event.
-    if (PR_GetCurrentThread() == gSocketThread) {
+    if (OnSocketThread()) {
         // this check is redundant to one done inside ::Signal(), but
         // we can do it here and skip obtaining the lock - given that
         // this is a relatively common occurance its worth the
         // redundant code
         SOCKET_LOG(("OnDispatchedEvent Same Thread Skip Signal\n"));
         return NS_OK;
     }
 #else
@@ -1283,17 +1290,17 @@ nsSocketTransportService::UpdatePrefs()
 
     return NS_OK;
 }
 
 void
 nsSocketTransportService::OnKeepaliveEnabledPrefChange()
 {
     // Dispatch to socket thread if we're not executing there.
-    if (PR_GetCurrentThread() != gSocketThread) {
+    if (!OnSocketThread()) {
         gSocketTransportService->Dispatch(
             NewRunnableMethod(
                 this, &nsSocketTransportService::OnKeepaliveEnabledPrefChange),
             NS_DISPATCH_NORMAL);
         return;
     }
 
     SOCKET_LOG(("nsSocketTransportService::OnKeepaliveEnabledPrefChange %s",
@@ -1424,17 +1431,17 @@ nsSocketTransportService::GetSendBufferS
 #include <sys/resource.h>
 #endif
 
 // Right now the only need to do this is on windows.
 #if defined(XP_WIN)
 void
 nsSocketTransportService::ProbeMaxCount()
 {
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mProbedMaxCount)
         return;
     mProbedMaxCount = true;
 
     // Allocate and test a PR_Poll up to the gMaxCount number of unconnected
     // sockets. See bug 692260 - windows should be able to handle 1000 sockets
     // in select() without a problem, but LSPs have been known to balk at lower
@@ -1576,17 +1583,17 @@ nsSocketTransportService::AnalyzeConnect
     SocketInfo info = { nsCString(host), sent, received, port, aActive, tcp };
 
     data->AppendElement(info);
 }
 
 void
 nsSocketTransportService::GetSocketConnections(nsTArray<SocketInfo> *data)
 {
-    NS_ASSERTION(PR_GetCurrentThread() == gSocketThread, "wrong thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     for (uint32_t i = 0; i < mActiveCount; i++)
         AnalyzeConnection(data, &mActiveList[i], true);
     for (uint32_t i = 0; i < mIdleCount; i++)
         AnalyzeConnection(data, &mIdleList[i], false);
 }
 
 #if defined(XP_WIN)
 void
--- a/netwerk/base/nsSocketTransportService2.h
+++ b/netwerk/base/nsSocketTransportService2.h
@@ -269,14 +269,14 @@ private:
     void StartPollWatchdog();
     void DoPollRepair();
     void StartPolling();
     void EndPolling();
 #endif
 };
 
 extern nsSocketTransportService *gSocketTransportService;
-extern Atomic<PRThread*, Relaxed> gSocketThread;
+bool OnSocketThread();
 
 } // namespace net
 } // namespace mozilla
 
 #endif // !nsSocketTransportService_h__
--- a/netwerk/dns/mdns/libmdns/MDNSResponderOperator.cpp
+++ b/netwerk/dns/mdns/libmdns/MDNSResponderOperator.cpp
@@ -40,34 +40,34 @@ class MDNSResponderOperator::ServiceWatc
   : public nsASocketHandler
 {
 public:
   NS_DECL_THREADSAFE_ISUPPORTS
 
   // nsASocketHandler methods
   virtual void OnSocketReady(PRFileDesc* fd, int16_t outFlags) override
   {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(fd == mFD);
 
     if (outFlags & (PR_POLL_ERR | PR_POLL_HUP | PR_POLL_NVAL)) {
       LOG_E("error polling on listening socket (%p)", fd);
       mCondition = NS_ERROR_UNEXPECTED;
     }
 
     if (!(outFlags & PR_POLL_READ)) {
       return;
     }
 
     DNSServiceProcessResult(mService);
   }
 
   virtual void OnSocketDetached(PRFileDesc *fd) override
   {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(mThread);
     MOZ_ASSERT(fd == mFD);
 
     if (!mFD) {
       return;
     }
 
     // Bug 1175387: do not double close the handle here.
@@ -102,17 +102,17 @@ public:
     {
       nsCOMPtr<nsISocketTransportService> sts =
         do_GetService(NS_SOCKETTRANSPORTSERVICE_CONTRACTID);
     }
   }
 
   nsresult Init()
   {
-    MOZ_ASSERT(PR_GetCurrentThread() != gSocketThread);
+    MOZ_ASSERT(!OnSocketThread(), "on socket thread");
     mThread = NS_GetCurrentThread();
 
     if (!mService) {
       return NS_OK;
     }
 
     if (!gSocketTransportService) {
       return NS_ERROR_FAILURE;
@@ -125,17 +125,17 @@ public:
     }
 
     mFD = PR_ImportFile(osfd);
     return PostEvent(&ServiceWatcher::OnMsgAttach);
   }
 
   void Close()
   {
-    MOZ_ASSERT(PR_GetCurrentThread() != gSocketThread);
+    MOZ_ASSERT(!OnSocketThread(), "on socket thread");
 
     if (!gSocketTransportService) {
       Deallocate();
       return;
     }
 
     PostEvent(&ServiceWatcher::OnMsgClose);
   }
@@ -155,17 +155,17 @@ private:
   nsresult PostEvent(void(ServiceWatcher::*func)(void))
   {
     return gSocketTransportService->Dispatch(NewRunnableMethod(this, func),
                                              NS_DISPATCH_NORMAL);
   }
 
   void OnMsgClose()
   {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (NS_FAILED(mCondition)) {
       return;
     }
 
     // tear down socket. this signals the STS to detach our socket handler.
     mCondition = NS_BINDING_ABORTED;
 
@@ -174,17 +174,17 @@ private:
     // (and thus close the socket) manually.
     if (!mAttached) {
       OnSocketDetached(mFD);
     }
   }
 
   void OnMsgAttach()
   {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (NS_FAILED(mCondition)) {
       return;
     }
 
     mCondition = TryAttach();
 
     // if we hit an error while trying to attach then bail...
@@ -192,17 +192,17 @@ private:
       NS_ASSERTION(!mAttached, "should not be attached already");
       OnSocketDetached(mFD);
     }
 
   }
 
   nsresult TryAttach()
   {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsresult rv;
 
     if (!gSocketTransportService) {
       return NS_ERROR_FAILURE;
     }
 
     //
--- a/netwerk/dns/mdns/libmdns/MDNSResponderReply.cpp
+++ b/netwerk/dns/mdns/libmdns/MDNSResponderReply.cpp
@@ -48,17 +48,17 @@ BrowseReplyRunnable::Reply(DNSServiceRef
                            DNSServiceFlags aFlags,
                            uint32_t aInterfaceIndex,
                            DNSServiceErrorType aErrorCode,
                            const char* aServiceName,
                            const char* aRegType,
                            const char* aReplyDomain,
                            void* aContext)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   BrowseOperator* obj(reinterpret_cast<BrowseOperator*>(aContext));
   if (!obj) {
     return;
   }
 
   nsCOMPtr<nsIThread> thread(obj->GetThread());
   if (!thread) {
@@ -111,17 +111,17 @@ void
 RegisterReplyRunnable::Reply(DNSServiceRef aSdRef,
                              DNSServiceFlags aFlags,
                              DNSServiceErrorType aErrorCode,
                              const char* aName,
                              const char* aRegType,
                              const char* domain,
                              void* aContext)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   RegisterOperator* obj(reinterpret_cast<RegisterOperator*>(aContext));
   if (!obj) {
     return;
   }
 
   nsCOMPtr<nsIThread> thread(obj->GetThread());
   if (!thread) {
@@ -191,17 +191,17 @@ ResolveReplyRunnable::Reply(DNSServiceRe
                             DNSServiceErrorType aErrorCode,
                             const char* aFullName,
                             const char* aHostTarget,
                             uint16_t aPort,
                             uint16_t aTxtLen,
                             const unsigned char* aTxtRecord,
                             void* aContext)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   ResolveOperator* obj(reinterpret_cast<ResolveOperator*>(aContext));
   if (!obj) {
     return;
   }
 
   nsCOMPtr<nsIThread> thread(obj->GetThread());
   if (!thread) {
@@ -263,17 +263,17 @@ GetAddrInfoReplyRunnable::Reply(DNSServi
                                 DNSServiceFlags aFlags,
                                 uint32_t aInterfaceIndex,
                                 DNSServiceErrorType aErrorCode,
                                 const char* aHostName,
                                 const struct sockaddr* aAddress,
                                 uint32_t aTTL,
                                 void* aContext)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   GetAddrInfoOperator* obj(reinterpret_cast<GetAddrInfoOperator*>(aContext));
   if (!obj) {
     return;
   }
 
   nsCOMPtr<nsIThread> thread(obj->GetThread());
   if (!thread) {
--- a/netwerk/protocol/http/ConnectionDiagnostics.cpp
+++ b/netwerk/protocol/http/ConnectionDiagnostics.cpp
@@ -30,17 +30,17 @@ nsHttpConnectionMgr::PrintDiagnostics()
     LOG(("nsHttpConnectionMgr::PrintDiagnostics\n"
          "  failed to post OnMsgPrintDiagnostics event"));
   }
 }
 
 void
 nsHttpConnectionMgr::OnMsgPrintDiagnostics(int32_t, ARefBase *)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   nsCOMPtr<nsIConsoleService> consoleService =
     do_GetService(NS_CONSOLESERVICE_CONTRACTID);
   if (!consoleService)
     return;
 
   mLogData.AppendPrintf("HTTP Connection Diagnostics\n---------------------\n");
   mLogData.AppendPrintf("IsSpdyEnabled() = %d\n", gHttpHandler->IsSpdyEnabled());
--- a/netwerk/protocol/http/Http2Compression.cpp
+++ b/netwerk/protocol/http/Http2Compression.cpp
@@ -108,17 +108,17 @@ static void
 AddStaticElement(const nsCString &name)
 {
   AddStaticElement(name, EmptyCString());
 }
 
 static void
 InitializeStaticHeaders()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   if (!gStaticHeaders) {
     gStaticHeaders = new nsDeque();
     gStaticReporter = new HpackStaticTableReporter();
     RegisterStrongMemoryReporter(gStaticReporter);
     AddStaticElement(NS_LITERAL_CSTRING(":authority"));
     AddStaticElement(NS_LITERAL_CSTRING(":method"), NS_LITERAL_CSTRING("GET"));
     AddStaticElement(NS_LITERAL_CSTRING(":method"), NS_LITERAL_CSTRING("POST"));
     AddStaticElement(NS_LITERAL_CSTRING(":path"), NS_LITERAL_CSTRING("/"));
--- a/netwerk/protocol/http/Http2Session.cpp
+++ b/netwerk/protocol/http/Http2Session.cpp
@@ -109,17 +109,17 @@ Http2Session::Http2Session(nsISocketTran
   , mPingSentEpoch(0)
   , mPreviousUsed(false)
   , mWaitingForSettingsAck(false)
   , mGoAwayOnPush(false)
   , mUseH2Deps(false)
   , mAttemptingEarlyData(attemptingEarlyData)
   , mOriginFrameActivated(false)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   static uint64_t sSerial;
   mSerial = ++sSerial;
 
   LOG3(("Http2Session::Http2Session %p serial=0x%" PRIX64 "\n", this, mSerial));
 
   mInputFrameBuffer = MakeUnique<char[]>(mInputFrameBufferSize);
   mOutputQueueBuffer = MakeUnique<char[]>(mOutputQueueSize);
@@ -229,17 +229,17 @@ static Http2ControlFx sControlFunctions[
   Http2Session::RecvAltSvc, // extension for type 0x0A
   Http2Session::RecvUnused, // 0x0B was BLOCKED still radioactive
   Http2Session::RecvOrigin  // extension for type 0x0C
 };
 
 bool
 Http2Session::RoomForMoreConcurrent()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   return (mConcurrent < mMaxConcurrent);
 }
 
 bool
 Http2Session::RoomForMoreStreams()
 {
   if (mNextStreamID + mStreamTransactionHash.Count() * 2 > kMaxStreamID)
     return false;
@@ -251,17 +251,17 @@ PRIntervalTime
 Http2Session::IdleTime()
 {
   return PR_IntervalNow() - mLastDataReadEpoch;
 }
 
 uint32_t
 Http2Session::ReadTimeoutTick(PRIntervalTime now)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   LOG3(("Http2Session::ReadTimeoutTick %p delta since last read %ds\n",
        this, PR_IntervalToSeconds(now - mLastReadEpoch)));
 
   if (!mPingThreshold)
     return UINT32_MAX;
 
   if ((now - mLastReadEpoch) < mPingThreshold) {
@@ -329,17 +329,17 @@ Http2Session::ReadTimeoutTick(PRInterval
   } while (deleteMe);
 
   return 1; // run the tick aggressively while ping is outstanding
 }
 
 uint32_t
 Http2Session::RegisterStreamID(Http2Stream *stream, uint32_t aNewID)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mNextStreamID < 0xfffffff0,
              "should have stopped admitting streams");
   MOZ_ASSERT(!(aNewID & 1),
              "0 for autoassign pull, otherwise explicit even push assignment");
 
   if (!aNewID) {
     // auto generate a new pull stream ID
     aNewID = mNextStreamID;
@@ -369,17 +369,17 @@ Http2Session::RegisterStreamID(Http2Stre
 }
 
 bool
 Http2Session::AddStream(nsAHttpTransaction *aHttpTransaction,
                         int32_t aPriority,
                         bool aUseTunnel,
                         nsIInterfaceRequestor *aCallbacks)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   // integrity check
   if (mStreamTransactionHash.Get(aHttpTransaction)) {
     LOG3(("   New transaction already present\n"));
     MOZ_ASSERT(false, "AddStream duplicate transaction pointer");
     return false;
   }
 
@@ -439,17 +439,17 @@ Http2Session::AddStream(nsAHttpTransacti
 
   return true;
 }
 
 void
 Http2Session::QueueStream(Http2Stream *stream)
 {
   // will be removed via processpending or a shutdown path
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(!stream->CountAsActive());
   MOZ_ASSERT(!stream->Queued());
 
   LOG3(("Http2Session::QueueStream %p stream %p queued.", this, stream));
 
 #ifdef DEBUG
   int32_t qsize = mQueuedStreams.GetSize();
   for (int32_t i = 0; i < qsize; i++) {
@@ -461,17 +461,17 @@ Http2Session::QueueStream(Http2Stream *s
 
   stream->SetQueued(true);
   mQueuedStreams.Push(stream);
 }
 
 void
 Http2Session::ProcessPending()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   Http2Stream*stream;
   while (RoomForMoreConcurrent() &&
          (stream = static_cast<Http2Stream *>(mQueuedStreams.PopFront()))) {
 
     LOG3(("Http2Session::ProcessPending %p stream %p woken from queue.",
           this, stream));
     MOZ_ASSERT(!stream->CountAsActive());
@@ -481,17 +481,17 @@ Http2Session::ProcessPending()
     SetWriteCallbacks();
   }
 }
 
 nsresult
 Http2Session::NetworkRead(nsAHttpSegmentWriter *writer, char *buf,
                           uint32_t count, uint32_t *countWritten)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (!count) {
     *countWritten = 0;
     return NS_OK;
   }
 
   nsresult rv = writer->OnWriteSegment(buf, count, countWritten);
   if (NS_SUCCEEDED(rv) && *countWritten > 0)
@@ -585,35 +585,35 @@ uint32_t
 Http2Session::SpdyVersion()
 {
   return HTTP_VERSION_2;
 }
 
 uint32_t
 Http2Session::GetWriteQueueSize()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   return mReadyForWrite.GetSize();
 }
 
 void
 Http2Session::ChangeDownstreamState(enum internalStateType newState)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   LOG3(("Http2Session::ChangeDownstreamState() %p from %X to %X",
         this, mDownstreamState, newState));
   mDownstreamState = newState;
 }
 
 void
 Http2Session::ResetDownstreamState()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   LOG3(("Http2Session::ResetDownstreamState() %p", this));
   ChangeDownstreamState(BUFFERING_FRAME_HEADER);
 
   if (mInputFrameFinal && mInputFrameDataStream) {
     mInputFrameFinal = false;
     LOG3(("  SetRecvdFin id=0x%x\n", mInputFrameDataStream->StreamID()));
     mInputFrameDataStream->SetRecvdFin(true);
@@ -644,17 +644,17 @@ Http2Session::TryToActivate(Http2Stream 
   LOG3(("Http2Session::TryToActivate %p stream=%p\n", this, aStream));
   IncrementConcurrent(aStream);
   return true;
 }
 
 void
 Http2Session::IncrementConcurrent(Http2Stream *stream)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(!stream->StreamID() || (stream->StreamID() & 1),
              "Do not activate pushed streams");
 
   nsAHttpTransaction *trans = stream->Transaction();
   if (!trans || !trans->IsNullTransaction() || trans->QuerySpdyConnectTransaction()) {
 
     MOZ_ASSERT(!stream->CountAsActive());
     stream->SetCountAsActive(true);
@@ -709,17 +709,17 @@ Http2Session::CreateFrameHeader(char *de
 template void
 Http2Session::CreateFrameHeader(uint8_t *dest, uint16_t frameLength,
                                 uint8_t frameType, uint8_t frameFlags,
                                 uint32_t streamID);
 
 void
 Http2Session::MaybeDecrementConcurrent(Http2Stream *aStream)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("MaybeDecrementConcurrent %p id=0x%X concurrent=%d active=%d\n",
         this, aStream->StreamID(), mConcurrent, aStream->CountAsActive()));
 
   if (!aStream->CountAsActive())
     return;
 
   MOZ_ASSERT(mConcurrent);
   aStream->SetCountAsActive(false);
@@ -745,17 +745,17 @@ Http2Session::UncompressAndDiscard(bool 
     return rv;
   }
   return NS_OK;
 }
 
 void
 Http2Session::GeneratePing(bool isAck)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::GeneratePing %p isAck=%d\n", this, isAck));
 
   char *packet = EnsureOutputBuffer(kFrameHeaderBytes + 8);
   mOutputQueueUsed += kFrameHeaderBytes + 8;
 
   if (isAck) {
     CreateFrameHeader(packet, 8, FRAME_TYPE_PING, kFlag_ACK, 0);
     memcpy(packet + kFrameHeaderBytes,
@@ -768,30 +768,30 @@ Http2Session::GeneratePing(bool isAck)
   LogIO(this, nullptr, "Generate Ping", packet, kFrameHeaderBytes + 8);
   FlushOutputQueue();
 }
 
 void
 Http2Session::GenerateSettingsAck()
 {
   // need to generate ack of this settings frame
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::GenerateSettingsAck %p\n", this));
 
   char *packet = EnsureOutputBuffer(kFrameHeaderBytes);
   mOutputQueueUsed += kFrameHeaderBytes;
   CreateFrameHeader(packet, 0, FRAME_TYPE_SETTINGS, kFlag_ACK, 0);
   LogIO(this, nullptr, "Generate Settings ACK", packet, kFrameHeaderBytes);
   FlushOutputQueue();
 }
 
 void
 Http2Session::GeneratePriority(uint32_t aID, uint8_t aPriorityWeight)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::GeneratePriority %p %X %X\n",
         this, aID, aPriorityWeight));
 
   uint32_t frameSize = kFrameHeaderBytes + 5;
   char *packet = EnsureOutputBuffer(frameSize);
   mOutputQueueUsed += frameSize;
 
   CreateFrameHeader(packet, 5, FRAME_TYPE_PRIORITY, 0, aID);
@@ -799,17 +799,17 @@ Http2Session::GeneratePriority(uint32_t 
   memcpy(packet + frameSize - 1, &aPriorityWeight, 1);
   LogIO(this, nullptr, "Generate Priority", packet, frameSize);
   FlushOutputQueue();
 }
 
 void
 Http2Session::GenerateRstStream(uint32_t aStatusCode, uint32_t aID)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   // make sure we don't do this twice for the same stream (at least if we
   // have a stream entry for it)
   Http2Stream *stream = mStreamIDHash.Get(aID);
   if (stream) {
     if (stream->SentReset())
       return;
     stream->SetSentReset(true);
@@ -826,17 +826,17 @@ Http2Session::GenerateRstStream(uint32_t
 
   LogIO(this, nullptr, "Generate Reset", packet, frameSize);
   FlushOutputQueue();
 }
 
 void
 Http2Session::GenerateGoAway(uint32_t aStatusCode)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::GenerateGoAway %p code=%X\n", this, aStatusCode));
 
   mClientGoAwayReason = aStatusCode;
   uint32_t frameSize = kFrameHeaderBytes + 8;
   char *packet = EnsureOutputBuffer(frameSize);
   mOutputQueueUsed += frameSize;
 
   CreateFrameHeader(packet, 8, FRAME_TYPE_GOAWAY, 0, 0);
@@ -857,17 +857,17 @@ Http2Session::GenerateGoAway(uint32_t aS
 // 2] a settings frame which sets a small flow control window for pushes
 // 3] a window update frame which creates a large session flow control window
 // 4] 5 priority frames for streams which will never be opened with headers
 //    these streams (3, 5, 7, 9, b) build a dependency tree that all other
 //    streams will be direct leaves of.
 void
 Http2Session::SendHello()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::SendHello %p\n", this));
 
   // sized for magic + 5 settings and a session window update and 5 priority frames
   // 24 magic, 33 for settings (9 header + 4 settings @6), 13 for window update,
   // 5 priority frames at 14 (9 + 5) each
   static const uint32_t maxSettings = 5;
   static const uint32_t prioritySize = 5 * (kFrameHeaderBytes + 5);
   static const uint32_t maxDataLen = 24 + kFrameHeaderBytes + maxSettings * 6 + 13 + prioritySize;
@@ -986,17 +986,17 @@ Http2Session::CreatePriorityNode(uint32_
 }
 
 // perform a bunch of integrity checks on the stream.
 // returns true if passed, false (plus LOG and ABORT) if failed.
 bool
 Http2Session::VerifyStream(Http2Stream *aStream, uint32_t aOptionalID = 0)
 {
   // This is annoying, but at least it is O(1)
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
 #ifndef DEBUG
   // Only do the real verification in debug builds
   return true;
 #endif
 
   if (!aStream)
     return true;
@@ -1043,17 +1043,17 @@ Http2Session::VerifyStream(Http2Stream *
   MOZ_ASSERT(false, "VerifyStream");
   return false;
 }
 
 void
 Http2Session::CleanupStream(Http2Stream *aStream, nsresult aResult,
                             errorType aResetCode)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::CleanupStream %p %p 0x%X %" PRIX32 "\n",
         this, aStream, aStream ? aStream->StreamID() : 0, static_cast<uint32_t>(aResult)));
   if (!aStream) {
     return;
   }
 
   if (aStream->DeferCleanup(aResult)) {
     LOG3(("Http2Session::CleanupStream 0x%X deferred\n", aStream->StreamID()));
@@ -1121,17 +1121,17 @@ Http2Session::CleanupStream(Http2Stream 
     pushSource->SetDeferCleanupOnSuccess(false);
     CleanupStream(pushSource, aResult, aResetCode);
   }
 }
 
 void
 Http2Session::CleanupStream(uint32_t aID, nsresult aResult, errorType aResetCode)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   Http2Stream *stream = mStreamIDHash.Get(aID);
   LOG3(("Http2Session::CleanupStream %p by ID 0x%X to stream %p\n",
         this, aID, stream));
   if (!stream) {
     return;
   }
   CleanupStream(stream, aResult, aResetCode);
 }
@@ -1153,17 +1153,17 @@ Http2Session::RemoveStreamFromQueues(Htt
   RemoveStreamFromQueue(aStream, mQueuedStreams);
   RemoveStreamFromQueue(aStream, mPushesReadyForRead);
   RemoveStreamFromQueue(aStream, mSlowConsumersReadyForRead);
 }
 
 void
 Http2Session::CloseStream(Http2Stream *aStream, nsresult aResult)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::CloseStream %p %p 0x%x %" PRIX32 "\n",
         this, aStream, aStream->StreamID(), static_cast<uint32_t>(aResult)));
 
   MaybeDecrementConcurrent(aStream);
 
   // Check if partial frame reader
   if (aStream == mInputFrameDataStream) {
     LOG3(("Stream had active partial read frame on close"));
@@ -2292,17 +2292,17 @@ Http2Session::RecvAltSvc(Http2Session *s
   NS_DispatchToMainThread(event);
   self->ResetDownstreamState();
   return NS_OK;
 }
 
 void
 Http2Session::Received421(nsHttpConnectionInfo *ci)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::Recevied421 %p %d\n", this, mOriginFrameActivated));
   if (!mOriginFrameActivated || !ci) {
     return;
   }
 
   nsAutoCString key(ci->GetOrigin());
   key.Append(':');
   key.AppendInt(ci->OriginPort());
@@ -2320,17 +2320,17 @@ Http2Session::RecvUnused(Http2Session *s
 }
 
 // defined as an http2 extension - origin
 // defines receipt of frame type 0x0b.. http://httpwg.org/http-extensions/origin-frame.html
 // as this is an extension, never generate protocol error - just ignore problems
 nsresult
 Http2Session::RecvOrigin(Http2Session *self)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(self->mInputFrameType == FRAME_TYPE_ORIGIN);
   LOG3(("Http2Session::RecvOrigin %p Flags 0x%X id 0x%X\n", self,
         self->mInputFrameFlags, self->mInputFrameID));
 
   if (self->mInputFrameFlags & 0x0F) {
     LOG3(("Http2Session::RecvOrigin %p leading flags must be 0", self));
     self->ResetDownstreamState();
     return NS_OK;
@@ -2412,17 +2412,17 @@ Http2Session::RecvOrigin(Http2Session *s
 // nsAHttpTransaction. It is expected that nsHttpConnection is the caller
 // of these methods
 //-----------------------------------------------------------------------------
 
 void
 Http2Session::OnTransportStatus(nsITransport* aTransport,
                                 nsresult aStatus, int64_t aProgress)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   switch (aStatus) {
     // These should appear only once, deliver to the first
     // transaction on the session.
   case NS_NET_STATUS_RESOLVING_HOST:
   case NS_NET_STATUS_RESOLVED_HOST:
   case NS_NET_STATUS_CONNECTING_TO:
   case NS_NET_STATUS_CONNECTED_TO:
@@ -2469,17 +2469,17 @@ Http2Session::OnTransportStatus(nsITrans
 // request data is pulled from the approriate transaction and
 // converted to http/2 data. Sometimes control data like window-update are
 // generated instead.
 
 nsresult
 Http2Session::ReadSegmentsAgain(nsAHttpSegmentReader *reader,
                                 uint32_t count, uint32_t *countRead, bool *again)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   MOZ_ASSERT(!mSegmentReader || !reader || (mSegmentReader == reader),
              "Inconsistent Write Function Callback");
 
   nsresult rv = ConfirmTLSProfile();
   if (NS_FAILED(rv)) {
     if (mGoAwayReason == INADEQUATE_SECURITY) {
       LOG3(("Http2Session::ReadSegments %p returning INADEQUATE_SECURITY %" PRIx32,
@@ -2705,17 +2705,17 @@ Http2Session::ReadyToProcessDataFrame(en
 // call stream->WriteSegments which can call this::OnWriteSegment to get the
 // data. It always gets full frames if they are part of the stream
 
 nsresult
 Http2Session::WriteSegmentsAgain(nsAHttpSegmentWriter *writer,
                                  uint32_t count, uint32_t *countWritten,
                                  bool *again)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   LOG3(("Http2Session::WriteSegments %p InternalState %X\n",
         this, mDownstreamState));
 
   *countWritten = 0;
 
   if (mClosed)
     return NS_ERROR_FAILURE;
@@ -3337,17 +3337,17 @@ Http2Session::UpdateLocalRwin(Http2Strea
   UpdateLocalStreamWindow(stream, bytes);
   UpdateLocalSessionWindow(bytes);
   FlushOutputQueue();
 }
 
 void
 Http2Session::Close(nsresult aReason)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (mClosed)
     return;
 
   LOG3(("Http2Session::Close %p %" PRIX32, this, static_cast<uint32_t>(aReason)));
 
   mClosed = true;
 
@@ -3381,17 +3381,17 @@ Http2Session::ConnectionInfo()
   GetConnectionInfo(getter_AddRefs(ci));
   return ci.get();
 }
 
 void
 Http2Session::CloseTransaction(nsAHttpTransaction *aTransaction,
                                nsresult aResult)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::CloseTransaction %p %p %" PRIx32, this, aTransaction,
         static_cast<uint32_t>(aResult)));
 
   // Generally this arrives as a cancel event from the connection manager.
 
   // need to find the stream and call CleanupStream() on it.
   Http2Stream *stream = mStreamTransactionHash.Get(aTransaction);
   if (!stream) {
@@ -3414,17 +3414,17 @@ Http2Session::CloseTransaction(nsAHttpTr
 //-----------------------------------------------------------------------------
 // nsAHttpSegmentReader
 //-----------------------------------------------------------------------------
 
 nsresult
 Http2Session::OnReadSegment(const char *buf,
                             uint32_t count, uint32_t *countRead)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsresult rv;
 
   // If we can release old queued data then we can try and write the new
   // data directly to the network without using the output queue at all
   if (mOutputQueueUsed)
     FlushOutputQueue();
 
   if (!mOutputQueueUsed && mSegmentReader) {
@@ -3509,17 +3509,17 @@ Http2Session::CommitToSegmentSize(uint32
 //-----------------------------------------------------------------------------
 // nsAHttpSegmentWriter
 //-----------------------------------------------------------------------------
 
 nsresult
 Http2Session::OnWriteSegment(char *buf,
                              uint32_t count, uint32_t *countWritten)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsresult rv;
 
   if (!mSegmentWriter) {
     // the only way this could happen would be if Close() were called on the
     // stack with WriteSegments()
     return NS_ERROR_FAILURE;
   }
 
@@ -3639,38 +3639,38 @@ Http2Session::ConnectSlowConsumer(Http2S
         this, stream->StreamID()));
   mSlowConsumersReadyForRead.Push(stream);
   Unused << ForceRecv();
 }
 
 uint32_t
 Http2Session::FindTunnelCount(nsHttpConnectionInfo *aConnInfo)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   uint32_t rv = 0;
   mTunnelHash.Get(aConnInfo->HashKey(), &rv);
   return rv;
 }
 
 void
 Http2Session::RegisterTunnel(Http2Stream *aTunnel)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsHttpConnectionInfo *ci = aTunnel->Transaction()->ConnectionInfo();
   uint32_t newcount = FindTunnelCount(ci) + 1;
   mTunnelHash.Remove(ci->HashKey());
   mTunnelHash.Put(ci->HashKey(), newcount);
   LOG3(("Http2Stream::RegisterTunnel %p stream=%p tunnels=%d [%s]",
         this, aTunnel, newcount, ci->HashKey().get()));
 }
 
 void
 Http2Session::UnRegisterTunnel(Http2Stream *aTunnel)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsHttpConnectionInfo *ci = aTunnel->Transaction()->ConnectionInfo();
   MOZ_ASSERT(FindTunnelCount(ci));
   uint32_t newcount = FindTunnelCount(ci) - 1;
   mTunnelHash.Remove(ci->HashKey());
   if (newcount) {
     mTunnelHash.Put(ci->HashKey(), newcount);
   }
   LOG3(("Http2Session::UnRegisterTunnel %p stream=%p tunnels=%d [%s]",
@@ -3695,17 +3695,17 @@ Http2Session::CreateTunnel(nsHttpTransac
   MOZ_ASSERT(tunnel);
   RegisterTunnel(tunnel);
 }
 
 void
 Http2Session::DispatchOnTunnel(nsAHttpTransaction *aHttpTransaction,
                                nsIInterfaceRequestor *aCallbacks)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsHttpTransaction *trans = aHttpTransaction->QueryHttpTransaction();
   nsHttpConnectionInfo *ci = aHttpTransaction->ConnectionInfo();
   MOZ_ASSERT(trans);
 
   LOG3(("Http2Session::DispatchOnTunnel %p trans=%p", this, trans));
 
   aHttpTransaction->SetConnection(nullptr);
 
@@ -3732,17 +3732,17 @@ Http2Session::DispatchOnTunnel(nsAHttpTr
     }
   }
 }
 
 // From ASpdySession
 bool
 Http2Session::MaybeReTunnel(nsAHttpTransaction *aHttpTransaction)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsHttpTransaction *trans = aHttpTransaction->QueryHttpTransaction();
   LOG(("Http2Session::MaybeReTunnel %p trans=%p\n", this, trans));
   if (!trans || trans->TunnelProvider() != this) {
     // this isn't really one of our transactions.
     return false;
   }
 
   if (mClosed || mShouldGoAway) {
@@ -3880,17 +3880,17 @@ Http2Session::ConfirmTLSProfile()
 
 //-----------------------------------------------------------------------------
 // Modified methods of nsAHttpConnection
 //-----------------------------------------------------------------------------
 
 void
 Http2Session::TransactionHasDataToWrite(nsAHttpTransaction *caller)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::TransactionHasDataToWrite %p trans=%p", this, caller));
 
   // a trapped signal from the http transaction to the connection that
   // it is no longer blocked on read.
 
   Http2Stream *stream = mStreamTransactionHash.Get(caller);
   if (!stream || !VerifyStream(stream)) {
     LOG3(("Http2Session::TransactionHasDataToWrite %p caller %p not found",
@@ -3913,17 +3913,17 @@ Http2Session::TransactionHasDataToWrite(
   // that are ready - so we can get into a deadlock waiting for the system IO
   // to come back here if we don't force the send loop manually.
   Unused << ForceSend();
 }
 
 void
 Http2Session::TransactionHasDataToRecv(nsAHttpTransaction *caller)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::TransactionHasDataToRecv %p trans=%p", this, caller));
 
   // a signal from the http transaction to the connection that it will consume more
   Http2Stream *stream = mStreamTransactionHash.Get(caller);
   if (!stream || !VerifyStream(stream)) {
     LOG3(("Http2Session::TransactionHasDataToRecv %p caller %p not found",
           this, caller));
     return;
@@ -3932,17 +3932,17 @@ Http2Session::TransactionHasDataToRecv(n
   LOG3(("Http2Session::TransactionHasDataToRecv %p ID is 0x%X\n",
         this, stream->StreamID()));
   ConnectSlowConsumer(stream);
 }
 
 void
 Http2Session::TransactionHasDataToWrite(Http2Stream *stream)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG3(("Http2Session::TransactionHasDataToWrite %p stream=%p ID=0x%x",
         this, stream, stream->StreamID()));
 
   mReadyForWrite.Push(stream);
   SetWriteCallbacks();
   Unused << ForceSend();
 }
 
@@ -4033,17 +4033,17 @@ Http2Session::Available()
 {
   MOZ_ASSERT(false, "Http2Session::Available()");
   return 0;
 }
 
 nsHttpRequestHead *
 Http2Session::RequestHead()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(false,
              "Http2Session::RequestHead() "
              "should not be called after http/2 is setup");
   return NULL;
 }
 
 uint32_t
 Http2Session::Http1xTransactionCount()
@@ -4077,17 +4077,17 @@ Http2Session::TakeSubTransactions(
 
 //-----------------------------------------------------------------------------
 // Pass through methods of nsAHttpConnection
 //-----------------------------------------------------------------------------
 
 nsAHttpConnection *
 Http2Session::Connection()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   return mConnection;
 }
 
 nsresult
 Http2Session::OnHeadersAvailable(nsAHttpTransaction *transaction,
                                  nsHttpRequestHead *requestHead,
                                  nsHttpResponseHead *responseHead, bool *reset)
 {
@@ -4107,17 +4107,17 @@ nsresult
 Http2Session::PushBack(const char *buf, uint32_t len)
 {
   return mConnection->PushBack(buf, len);
 }
 
 void
 Http2Session::SendPing()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (mPreviousUsed) {
     // alredy in progress, get out
     return;
   }
 
   mPingSentEpoch = PR_IntervalNow();
   if (!mPingSentEpoch) {
@@ -4131,17 +4131,17 @@ Http2Session::SendPing()
   }
   GeneratePing(false);
   Unused << ResumeRecv();
 }
 
 bool
 Http2Session::TestOriginFrame(const nsACString &hostname, int32_t port)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mOriginFrameActivated);
 
   nsAutoCString key(hostname);
   key.Append (':');
   key.AppendInt(port);
   bool rv = mOriginFrame.Get(key);
   LOG3(("TestOriginFrame() hash.get %p %s %d\n", this, key.get(), rv));
   if (!rv && ConnectionInfo()) {
--- a/netwerk/protocol/http/Http2Stream.cpp
+++ b/netwerk/protocol/http/Http2Stream.cpp
@@ -70,17 +70,17 @@ Http2Stream::Http2Stream(nsAHttpTransact
   , mBlockedOnRwin(false)
   , mTotalSent(0)
   , mTotalRead(0)
   , mPushSource(nullptr)
   , mAttempting0RTT(false)
   , mIsTunnel(false)
   , mPlainTextTunnel(false)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   LOG3(("Http2Stream::Http2Stream %p", this));
 
   mServerReceiveWindow = session->GetServerInitialStreamWindow();
   mClientReceiveWindow = session->PushAllowance();
 
   mTxInlineFrame = MakeUnique<uint8_t[]>(mTxInlineFrameSize);
 
@@ -116,17 +116,17 @@ Http2Stream::~Http2Stream()
 nsresult
 Http2Stream::ReadSegments(nsAHttpSegmentReader *reader,
                           uint32_t count,
                           uint32_t *countRead)
 {
   LOG3(("Http2Stream %p ReadSegments reader=%p count=%d state=%x",
         this, reader, count, mUpstreamState));
 
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   nsresult rv = NS_ERROR_UNEXPECTED;
   mRequestBlockedOnRead = 0;
 
   if (mRecvdFin || mRecvdReset) {
     // Don't transmit any request frames if the peer cannot respond
     LOG3(("Http2Stream %p ReadSegments request stream aborted due to"
           " response side closure\n", this));
@@ -283,17 +283,17 @@ Http2Stream::DeferCleanup(nsresult statu
 // just a call through to the associated nsHttpTransaction for this stream
 // for the remaining data bytes indicated by the current DATA frame.
 
 nsresult
 Http2Stream::WriteSegments(nsAHttpSegmentWriter *writer,
                            uint32_t count,
                            uint32_t *countWritten)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(!mSegmentWriter, "segment writer in progress");
 
   LOG3(("Http2Stream::WriteSegments %p count=%d state=%x",
         this, count, mUpstreamState));
 
   mSegmentWriter = writer;
   nsresult rv = mTransaction->WriteSegments(this, count, countWritten);
 
@@ -385,17 +385,17 @@ Http2Stream::CreatePushHashKey(const nsC
 nsresult
 Http2Stream::ParseHttpRequestHeaders(const char *buf,
                                      uint32_t avail,
                                      uint32_t *countUsed)
 {
   // Returns NS_OK even if the headers are incomplete
   // set mRequestHeadersDone flag if they are complete
 
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mUpstreamState == GENERATING_HEADERS);
   MOZ_ASSERT(!mRequestHeadersDone);
 
   LOG3(("Http2Stream::ParseHttpRequestHeaders %p avail=%d state=%x",
         this, avail, mUpstreamState));
 
   mFlatHttpRequestHeaders.Append(buf, avail);
   nsHttpRequestHead *head = mTransaction->RequestHead();
@@ -969,17 +969,17 @@ Http2Stream::ChangeState(enum upstreamSt
 }
 
 void
 Http2Stream::GenerateDataFrameHeader(uint32_t dataLength, bool lastFrame)
 {
   LOG3(("Http2Stream::GenerateDataFrameHeader %p len=%d last=%d",
         this, dataLength, lastFrame));
 
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(!mTxInlineFrameUsed, "inline frame not empty");
   MOZ_ASSERT(!mTxStreamFrameSize, "stream frame not empty");
 
   uint8_t frameFlags = 0;
   if (lastFrame) {
     frameFlags |= Http2Session::kFlag_END_STREAM;
     if (dataLength)
       SetSentFin(true);
@@ -1301,17 +1301,17 @@ Http2Stream::SetSentReset(bool aStatus)
 nsresult
 Http2Stream::OnReadSegment(const char *buf,
                            uint32_t count,
                            uint32_t *countRead)
 {
   LOG3(("Http2Stream::OnReadSegment %p count=%d state=%x",
         this, count, mUpstreamState));
 
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mSegmentReader, "OnReadSegment with null mSegmentReader");
 
   nsresult rv = NS_ERROR_UNEXPECTED;
   uint32_t dataLength;
 
   switch (mUpstreamState) {
   case GENERATING_HEADERS:
     // The buffer is the HTTP request stream, including at least part of the
@@ -1446,17 +1446,17 @@ Http2Stream::OnReadSegment(const char *b
 nsresult
 Http2Stream::OnWriteSegment(char *buf,
                             uint32_t count,
                             uint32_t *countWritten)
 {
   LOG3(("Http2Stream::OnWriteSegment %p count=%d state=%x 0x%X\n",
         this, count, mUpstreamState, mStreamID));
 
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mSegmentWriter);
 
   if (mPushSource) {
     nsresult rv;
     rv = mPushSource->GetBufferedData(buf, count, countWritten);
     if (NS_FAILED(rv))
       return rv;
 
@@ -1480,17 +1480,17 @@ Http2Stream::OnWriteSegment(char *buf,
   return mSegmentWriter->OnWriteSegment(buf, count, countWritten);
 }
 
 /// connect tunnels
 
 void
 Http2Stream::ClearTransactionsBlockedOnTunnel()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (!mIsTunnel) {
     return;
   }
   nsresult rv = gHttpHandler->ConnMgr()->ProcessPendingQ(mTransaction->ConnectionInfo());
   if (NS_FAILED(rv)) {
     LOG3(("Http2Stream::ClearTransactionsBlockedOnTunnel %p\n"
           "  ProcessPendingQ failed: %08x\n",
--- a/netwerk/protocol/http/TunnelUtils.cpp
+++ b/netwerk/protocol/http/TunnelUtils.cpp
@@ -18,16 +18,17 @@
 #include "nsISupportsPriority.h"
 #include "nsNetAddr.h"
 #include "prerror.h"
 #include "prio.h"
 #include "TunnelUtils.h"
 #include "nsNetCID.h"
 #include "nsServiceManagerUtils.h"
 #include "nsComponentManagerUtils.h"
+#include "nsSocketTransportService2.h"
 
 namespace mozilla {
 namespace net {
 
 static PRDescIdentity sLayerIdentity;
 static PRIOMethods sLayerMethods;
 static PRIOMethods *sLayerMethodsPtr = nullptr;
 
@@ -39,17 +40,17 @@ TLSFilterTransaction::TLSFilterTransacti
   : mTransaction(aWrapped)
   , mEncryptedTextUsed(0)
   , mEncryptedTextSize(0)
   , mSegmentReader(aReader)
   , mSegmentWriter(aWriter)
   , mForce(false)
   , mNudgeCounter(0)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG(("TLSFilterTransaction ctor %p\n", this));
 
   nsCOMPtr<nsISocketProvider> provider;
   nsCOMPtr<nsISocketProviderService> spserv =
     do_GetService(NS_SOCKETPROVIDERSERVICE_CONTRACTID);
 
   if (spserv) {
     spserv->GetSocketProvider("ssl", getter_AddRefs(provider));
@@ -252,17 +253,17 @@ TLSFilterTransaction::CommitToSegmentSiz
 }
 
 nsresult
 TLSFilterTransaction::OnWriteSegment(char *aData,
                                      uint32_t aCount,
                                      uint32_t *outCountRead)
 {
 
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mSegmentWriter);
   LOG(("TLSFilterTransaction::OnWriteSegment %p max=%d\n", this, aCount));
   if (!mSecInfo) {
     return NS_ERROR_FAILURE;
   }
 
   // this will call through to FilterInput to get data from the higher
   // level connection before removing the local TLS layer
@@ -286,17 +287,17 @@ TLSFilterTransaction::OnWriteSegment(cha
        "2 layers of ssl stripped to plaintext\n",
        this, static_cast<uint32_t>(mFilterReadCode), bytesRead));
   return mFilterReadCode;
 }
 
 int32_t
 TLSFilterTransaction::FilterInput(char *aBuf, int32_t aAmount)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mSegmentWriter);
   LOG(("TLSFilterTransaction::FilterInput max=%d\n", aAmount));
 
   uint32_t outCountRead = 0;
   mFilterReadCode = mSegmentWriter->OnWriteSegment(aBuf, aAmount, &outCountRead);
   if (NS_SUCCEEDED(mFilterReadCode) && outCountRead) {
     LOG(("TLSFilterTransaction::FilterInput rv=%" PRIx32 " read=%d input from net "
          "1 layer stripped, 1 still on\n",
@@ -311,17 +312,17 @@ TLSFilterTransaction::FilterInput(char *
   }
   return outCountRead;
 }
 
 nsresult
 TLSFilterTransaction::ReadSegments(nsAHttpSegmentReader *aReader,
                                    uint32_t aCount, uint32_t *outCountRead)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG(("TLSFilterTransaction::ReadSegments %p max=%d\n", this, aCount));
 
   if (!mTransaction) {
     return NS_ERROR_UNEXPECTED;
   }
 
   mReadSegmentBlocked = false;
   mSegmentReader = aReader;
@@ -337,17 +338,17 @@ TLSFilterTransaction::ReadSegments(nsAHt
 
   return rv;
 }
 
 nsresult
 TLSFilterTransaction::WriteSegments(nsAHttpSegmentWriter *aWriter,
                                     uint32_t aCount, uint32_t *outCountWritten)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG(("TLSFilterTransaction::WriteSegments %p max=%d\n", this, aCount));
 
   if (!mTransaction) {
     return NS_ERROR_UNEXPECTED;
   }
 
   mSegmentWriter = aWriter;
   nsresult rv = mTransaction->WriteSegments(this, aCount, outCountWritten);
@@ -373,17 +374,17 @@ TLSFilterTransaction::GetTransactionSecu
   nsCOMPtr<nsISupports> temp(mSecInfo);
   temp.forget(outSecInfo);
   return NS_OK;
 }
 
 nsresult
 TLSFilterTransaction::NudgeTunnel(NudgeTunnelCallback *aCallback)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG(("TLSFilterTransaction %p NudgeTunnel\n", this));
   mNudgeCallback = nullptr;
 
   if (!mSecInfo) {
     return NS_ERROR_FAILURE;
   }
 
   uint32_t notUsed;
@@ -429,17 +430,17 @@ TLSFilterTransaction::NudgeTunnel(NudgeT
 
   LOG(("TLSFilterTransaction %p NudgeTunnel timer started\n", this));
   return NS_OK;
 }
 
 NS_IMETHODIMP
 TLSFilterTransaction::Notify(nsITimer *timer)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG(("TLSFilterTransaction %p NudgeTunnel notify\n", this));
 
   if (timer != mTimer) {
     return NS_ERROR_UNEXPECTED;
   }
   DebugOnly<nsresult> rv = StartTimerCallback();
   MOZ_ASSERT(NS_SUCCEEDED(rv));
   return NS_OK;
@@ -979,17 +980,17 @@ SpdyConnectTransaction::~SpdyConnectTran
     Unused << gHttpHandler->InitiateTransaction(mDrivingTransaction,
                                                 mDrivingTransaction->Priority());
   }
 }
 
 void
 SpdyConnectTransaction::ForcePlainText()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(!mInputDataUsed && !mInputDataSize && !mInputDataOffset);
   MOZ_ASSERT(!mForcePlainText);
   MOZ_ASSERT(!mTunnelTransport, "call before mapstreamtohttpconnection");
 
   mForcePlainText = true;
   return;
 }
 
@@ -1039,17 +1040,17 @@ SpdyConnectTransaction::MapStreamToHttpC
   Unused << gHttpHandler->InitiateTransaction(
     mDrivingTransaction, nsISupportsPriority::PRIORITY_HIGHEST - 60);
   mDrivingTransaction = nullptr;
 }
 
 nsresult
 SpdyConnectTransaction::Flush(uint32_t count, uint32_t *countRead)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG(("SpdyConnectTransaction::Flush %p count %d avail %d\n",
        this, count, mOutputDataUsed - mOutputDataOffset));
 
   if (!mSegmentReader) {
     return NS_ERROR_UNEXPECTED;
   }
 
   *countRead = 0;
@@ -1083,17 +1084,17 @@ SpdyConnectTransaction::Flush(uint32_t c
   return NS_OK;
 }
 
 nsresult
 SpdyConnectTransaction::ReadSegments(nsAHttpSegmentReader *reader,
                                      uint32_t count,
                                      uint32_t *countRead)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG(("SpdyConnectTransaction::ReadSegments %p count %d conn %p\n",
        this, count, mTunneledConn.get()));
 
   mSegmentReader = reader;
 
   // spdy stream carrying tunnel is not setup yet.
   if (!mTunneledConn) {
     uint32_t toWrite = mConnectString.Length() - mConnectStringOffset;
@@ -1147,17 +1148,17 @@ SpdyConnectTransaction::ReadSegments(nsA
   rv = Flush(count, &subtotal);
   *countRead += subtotal;
   return rv;
 }
 
 void
 SpdyConnectTransaction::CreateShimError(nsresult code)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(NS_FAILED(code));
 
   if (mTunnelStreamOut && NS_SUCCEEDED(mTunnelStreamOut->mStatus)) {
     mTunnelStreamOut->mStatus = code;
   }
 
   if (mTunnelStreamIn && NS_SUCCEEDED(mTunnelStreamIn->mStatus)) {
     mTunnelStreamIn->mStatus = code;
@@ -1172,17 +1173,17 @@ SpdyConnectTransaction::CreateShimError(
   }
 }
 
 nsresult
 SpdyConnectTransaction::WriteSegments(nsAHttpSegmentWriter *writer,
                                       uint32_t count,
                                       uint32_t *countWritten)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   LOG(("SpdyConnectTransaction::WriteSegments %p max=%d cb=%p\n",
        this, count, mTunneledConn ? mTunnelStreamIn->mCallback : nullptr));
 
   // first call into the tunnel stream to get the demux'd data out of the
   // spdy session.
   EnsureBuffer(mInputData, mInputDataUsed + count, mInputDataUsed, mInputDataSize);
   nsresult rv = writer->OnWriteSegment(&mInputData[mInputDataUsed],
                                        count, countWritten);
@@ -1240,17 +1241,17 @@ SpdyConnectTransaction::Close(nsresult c
     CreateShimError(NS_BASE_STREAM_CLOSED);
   }
 }
 
 NS_IMETHODIMP
 OutputStreamShim::AsyncWait(nsIOutputStreamCallback *callback,
                             unsigned int, unsigned int, nsIEventTarget *target)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   bool currentThread;
 
   if (target &&
       (NS_FAILED(target->IsOnCurrentThread(&currentThread)) || !currentThread)) {
     return NS_ERROR_FAILURE;
   }
 
   LOG(("OutputStreamShim::AsyncWait %p callback %p\n", this, callback));
@@ -1317,17 +1318,17 @@ OutputStreamShim::Flush()
   LOG(("OutputStreamShim::Flush %p before %d after %d\n",
        this, count, trans->mOutputDataUsed - trans->mOutputDataOffset));
   return rv;
 }
 
 NS_IMETHODIMP
 OutputStreamShim::Write(const char * aBuf, uint32_t aCount, uint32_t *_retval)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (NS_FAILED(mStatus)) {
     return mStatus;
   }
 
   RefPtr<NullHttpTransaction> baseTrans(do_QueryReferent(mWeakTrans));
   if (!baseTrans) {
     return NS_ERROR_FAILURE;
@@ -1374,17 +1375,17 @@ OutputStreamShim::IsNonBlocking(bool *_r
   *_retval = true;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 InputStreamShim::AsyncWait(nsIInputStreamCallback *callback,
                            unsigned int, unsigned int, nsIEventTarget *target)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   bool currentThread;
 
   if (target &&
       (NS_FAILED(target->IsOnCurrentThread(&currentThread)) || !currentThread)) {
     return NS_ERROR_FAILURE;
   }
 
   LOG(("InputStreamShim::AsyncWait %p callback %p\n", this, callback));
@@ -1430,17 +1431,17 @@ InputStreamShim::Available(uint64_t *_re
 
   *_retval = trans->mInputDataUsed - trans->mInputDataOffset;
   return NS_OK;
 }
 
 NS_IMETHODIMP
 InputStreamShim::Read(char *aBuf, uint32_t aCount, uint32_t *_retval)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (NS_FAILED(mStatus)) {
     return mStatus;
   }
 
   RefPtr<NullHttpTransaction> baseTrans(do_QueryReferent(mWeakTrans));
   if (!baseTrans) {
     return NS_ERROR_FAILURE;
--- a/netwerk/protocol/http/nsHttpConnection.cpp
+++ b/netwerk/protocol/http/nsHttpConnection.cpp
@@ -551,30 +551,30 @@ npnComplete:
         mDid0RTTSpdy = false;
     }
     return true;
 }
 
 void
 nsHttpConnection::OnTunnelNudged(TLSFilterTransaction *trans)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnection::OnTunnelNudged %p\n", this));
     if (trans != mTLSFilter) {
         return;
     }
     LOG(("nsHttpConnection::OnTunnelNudged %p Calling OnSocketWritable\n", this));
     Unused << OnSocketWritable();
 }
 
 // called on the socket thread
 nsresult
 nsHttpConnection::Activate(nsAHttpTransaction *trans, uint32_t caps, int32_t pri)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnection::Activate [this=%p trans=%p caps=%x]\n",
          this, trans, caps));
 
     if (!trans->IsNullTransaction())
         mExperienced = true;
 
     mTransactionCaps = caps;
     mPriority = pri;
@@ -741,17 +741,17 @@ nsHttpConnection::SetupNPNList(nsISSLSoc
          this, static_cast<uint32_t>(rv)));
     return rv;
 }
 
 nsresult
 nsHttpConnection::AddTransaction(nsAHttpTransaction *httpTransaction,
                                  int32_t priority)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(mSpdySession && mUsingSpdyVersion,
                "AddTransaction to live http connection without spdy");
 
     // If this is a wild card nshttpconnection (i.e. a spdy proxy) then
     // it is important to start the stream using the specific connection
     // info of the transaction to ensure it is routed on the right tunnel
 
     nsHttpConnectionInfo *transCI = httpTransaction->ConnectionInfo();
@@ -776,17 +776,17 @@ nsHttpConnection::AddTransaction(nsAHttp
 }
 
 void
 nsHttpConnection::Close(nsresult reason, bool aIsShutdown)
 {
     LOG(("nsHttpConnection::Close [this=%p reason=%" PRIx32 "]\n",
          this, static_cast<uint32_t>(reason)));
 
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // Ensure TCP keepalive timer is stopped.
     if (mTCPKeepaliveTransitionTimer) {
         mTCPKeepaliveTransitionTimer->Cancel();
         mTCPKeepaliveTransitionTimer = nullptr;
     }
     if (mForceSendTimer) {
         mForceSendTimer->Cancel();
@@ -839,17 +839,17 @@ nsHttpConnection::Close(nsresult reason,
 }
 
 // called on the socket thread
 nsresult
 nsHttpConnection::InitSSLParams(bool connectingToProxy, bool proxyStartSSL)
 {
     LOG(("nsHttpConnection::InitSSLParams [this=%p] connectingToProxy=%d\n",
          this, connectingToProxy));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsresult rv;
     nsCOMPtr<nsISupports> securityInfo;
     GetSecurityInfo(getter_AddRefs(securityInfo));
     if (!securityInfo) {
         return NS_ERROR_FAILURE;
     }
 
@@ -1007,17 +1007,17 @@ nsresult
 nsHttpConnection::OnHeadersAvailable(nsAHttpTransaction *trans,
                                      nsHttpRequestHead *requestHead,
                                      nsHttpResponseHead *responseHead,
                                      bool *reset)
 {
     LOG(("nsHttpConnection::OnHeadersAvailable [this=%p trans=%p response-head=%p]\n",
         this, trans, responseHead));
 
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     NS_ENSURE_ARG_POINTER(trans);
     MOZ_ASSERT(responseHead, "No response head?");
 
     if (mInSpdyTunnel) {
         DebugOnly<nsresult> rv =
             responseHead->SetHeader(nsHttp::X_Firefox_Spdy_Proxy,
                                     NS_LITERAL_CSTRING("true"));
         MOZ_ASSERT(NS_SUCCEEDED(rv));
@@ -1256,17 +1256,17 @@ nsHttpConnection::TakeTransport(nsISocke
     mSocketOut.forget(aOutputStream);
 
     return NS_OK;
 }
 
 uint32_t
 nsHttpConnection::ReadTimeoutTick(PRIntervalTime now)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // make sure timer didn't tick before Activate()
     if (!mTransaction)
         return UINT32_MAX;
 
     // Spdy implements some timeout handling using the SPDY ping frame.
     if (mSpdySession) {
         return mSpdySession->ReadTimeoutTick(now);
@@ -1323,17 +1323,17 @@ nsHttpConnection::UpdateTCPKeepalive(nsI
              "StartLongLivedTCPKeepalives failed rv[0x%" PRIx32 "]",
              self, static_cast<uint32_t>(rv)));
     }
 }
 
 void
 nsHttpConnection::GetSecurityInfo(nsISupports **secinfo)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnection::GetSecurityInfo trans=%p tlsfilter=%p socket=%p\n",
          mTransaction.get(), mTLSFilter.get(), mSocketTransport.get()));
 
     if (mTransaction &&
         NS_SUCCEEDED(mTransaction->GetTransactionSecurityInfo(secinfo))) {
         return;
     }
 
@@ -1375,31 +1375,31 @@ nsHttpConnection::PushBack(const char *d
     return NS_OK;
 }
 
 nsresult
 nsHttpConnection::ResumeSend()
 {
     LOG(("nsHttpConnection::ResumeSend [this=%p]\n", this));
 
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mSocketOut)
         return mSocketOut->AsyncWait(this, 0, 0, nullptr);
 
     NS_NOTREACHED("no socket output stream");
     return NS_ERROR_UNEXPECTED;
 }
 
 nsresult
 nsHttpConnection::ResumeRecv()
 {
     LOG(("nsHttpConnection::ResumeRecv [this=%p]\n", this));
 
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // mResponseThrottled is an indication from above layers to stop reading
     // the socket.
     if (mResponseThrottled) {
         mResumeRecvOnUnthrottle = true;
 
         if (mSocketIn) {
             LOG(("  throttled, waiting for closure only"));
@@ -1432,17 +1432,17 @@ class HttpConnectionForceIO : public Run
 public:
   HttpConnectionForceIO(nsHttpConnection *aConn, bool doRecv)
      : mConn(aConn)
      , mDoRecv(doRecv)
     {}
 
     NS_IMETHOD Run() override
     {
-        MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+        MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
         if (mDoRecv) {
             if (!mConn->mSocketIn)
                 return NS_OK;
             return mConn->OnInputStreamReady(mConn->mSocketIn);
         }
 
         MOZ_ASSERT(mConn->mForceSendPending);
@@ -1455,27 +1455,27 @@ public:
 private:
     RefPtr<nsHttpConnection> mConn;
     bool mDoRecv;
 };
 
 void
 nsHttpConnection::ForceSendIO(nsITimer *aTimer, void *aClosure)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     nsHttpConnection *self = static_cast<nsHttpConnection *>(aClosure);
     MOZ_ASSERT(aTimer == self->mForceSendTimer);
     self->mForceSendTimer = nullptr;
     NS_DispatchToCurrentThread(new HttpConnectionForceIO(self, false));
 }
 
 nsresult
 nsHttpConnection::MaybeForceSendIO()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     // due to bug 1213084 sometimes real I/O events do not get serviced when
     // NSPR derived I/O events are ready and this can cause a deadlock with
     // https over https proxying. Normally we would expect the write callback to
     // be invoked before this timer goes off, but set it at the old windows
     // tick interval (kForceDelay) as a backup for those circumstances.
     static const uint32_t kForceDelay = 17; //ms
 
     if (mForceSendPending) {
@@ -1488,53 +1488,53 @@ nsHttpConnection::MaybeForceSendIO()
         nsHttpConnection::ForceSendIO, this, kForceDelay, nsITimer::TYPE_ONE_SHOT);
 }
 
 // trigger an asynchronous read
 nsresult
 nsHttpConnection::ForceRecv()
 {
     LOG(("nsHttpConnection::ForceRecv [this=%p]\n", this));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     return NS_DispatchToCurrentThread(new HttpConnectionForceIO(this, true));
 }
 
 // trigger an asynchronous write
 nsresult
 nsHttpConnection::ForceSend()
 {
     LOG(("nsHttpConnection::ForceSend [this=%p]\n", this));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mTLSFilter) {
         return mTLSFilter->NudgeTunnel(this);
     }
     return MaybeForceSendIO();
 }
 
 void
 nsHttpConnection::BeginIdleMonitoring()
 {
     LOG(("nsHttpConnection::BeginIdleMonitoring [this=%p]\n", this));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(!mTransaction, "BeginIdleMonitoring() while active");
     MOZ_ASSERT(!mUsingSpdyVersion, "Idle monitoring of spdy not allowed");
 
     LOG(("Entering Idle Monitoring Mode [this=%p]", this));
     mIdleMonitoring = true;
     if (mSocketIn)
         mSocketIn->AsyncWait(this, 0, 0, nullptr);
 }
 
 void
 nsHttpConnection::EndIdleMonitoring()
 {
     LOG(("nsHttpConnection::EndIdleMonitoring [this=%p]\n", this));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(!mTransaction, "EndIdleMonitoring() while active");
 
     if (mIdleMonitoring) {
         LOG(("Leaving Idle Monitoring Mode [this=%p]", this));
         mIdleMonitoring = false;
         if (mSocketIn)
             mSocketIn->AsyncWait(nullptr, 0, 0, nullptr);
     }
@@ -1554,17 +1554,17 @@ void
 nsHttpConnection::CloseTransaction(nsAHttpTransaction *trans, nsresult reason,
                                    bool aIsShutdown)
 {
     LOG(("nsHttpConnection::CloseTransaction[this=%p trans=%p reason=%" PRIx32 "]\n",
          this, trans, static_cast<uint32_t>(reason)));
 
     MOZ_ASSERT((trans == mTransaction) ||
                (mTLSFilter && mTLSFilter->Transaction() == trans));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mCurrentBytesRead > mMaxBytesRead)
         mMaxBytesRead = mCurrentBytesRead;
 
     // mask this error code because its not a real error.
     if (reason == NS_BASE_STREAM_CLOSED)
         reason = NS_OK;
 
@@ -1855,17 +1855,17 @@ nsHttpConnection::OnSocketReadable()
     } while (again && gHttpHandler->Active());
 
     return rv;
 }
 
 void
 nsHttpConnection::SetupSecondaryTLS()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(!mTLSFilter);
     LOG(("nsHttpConnection %p SetupSecondaryTLS %s %d\n",
          this, mConnInfo->Origin(), mConnInfo->OriginPort()));
 
     nsHttpConnectionInfo *ci = nullptr;
     if (mTransaction) {
         ci = mTransaction->ConnectionInfo();
     }
@@ -2103,17 +2103,17 @@ nsHttpConnection::DisableTCPKeepalives()
         mTCPKeepaliveTransitionTimer = nullptr;
     }
     return NS_OK;
 }
 
 void nsHttpConnection::ThrottleResponse(bool aThrottle)
 {
     LOG(("nsHttpConnection::ThrottleResponse this=%p, throttle=%d", this, aThrottle));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (aThrottle) {
         mResponseThrottled = true;
         return;
     }
 
     mResponseThrottled = false;
 
@@ -2156,17 +2156,17 @@ NS_INTERFACE_MAP_END
 // nsHttpConnection::nsIInputStreamCallback
 //-----------------------------------------------------------------------------
 
 // called on the socket transport thread
 NS_IMETHODIMP
 nsHttpConnection::OnInputStreamReady(nsIAsyncInputStream *in)
 {
     MOZ_ASSERT(in == mSocketIn, "unexpected stream");
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mIdleMonitoring) {
         MOZ_ASSERT(!mTransaction, "Idle Input Event While Active");
 
         // The only read event that is protocol compliant for an idle connection
         // is an EOF, which we check for with CanReuse(). If the data is
         // something else then just ignore it and suspend checking for EOF -
         // our normal timers or protocol stack are the place to deal with
@@ -2197,17 +2197,17 @@ nsHttpConnection::OnInputStreamReady(nsI
 
 //-----------------------------------------------------------------------------
 // nsHttpConnection::nsIOutputStreamCallback
 //-----------------------------------------------------------------------------
 
 NS_IMETHODIMP
 nsHttpConnection::OnOutputStreamReady(nsIAsyncOutputStream *out)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(out == mSocketOut, "unexpected socket");
     // if the transaction was dropped...
     if (!mTransaction) {
         LOG(("  no transaction; ignoring event\n"));
         return NS_OK;
     }
 
     nsresult rv = OnSocketWritable();
@@ -2244,17 +2244,17 @@ nsHttpConnection::GetInterface(const nsI
     //       the socket transport thread.  If that weren't the case, then we'd
     //       have to worry about the possibility of mTransaction going away
     //       part-way through this function call.  See CloseTransaction.
 
     // NOTE - there is a bug here, the call to getinterface is proxied off the
     // nss thread, not the ui thread as the above comment says. So there is
     // indeed a chance of mTransaction going away. bug 615342
 
-    MOZ_ASSERT(PR_GetCurrentThread() != gSocketThread);
+    MOZ_ASSERT(!OnSocketThread(), "on socket thread");
 
     nsCOMPtr<nsIInterfaceRequestor> callbacks;
     {
         MutexAutoLock lock(mCallbacksLock);
         callbacks = mCallbacks;
     }
     if (callbacks)
         return callbacks->GetInterface(iid, result);
--- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp
+++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp
@@ -548,17 +548,17 @@ nsHttpConnectionMgr::UpdateRequestTokenB
     // to post the new value to the socket thread.
     return PostEvent(&nsHttpConnectionMgr::OnMsgUpdateRequestTokenBucket,
                      0, aBucket);
 }
 
 nsresult
 nsHttpConnectionMgr::ClearConnectionHistory()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     for (auto iter = mCT.Iter(); !iter.Done(); iter.Next()) {
         nsAutoPtr<nsConnectionEntry>& ent = iter.Data();
         if (ent->mIdleConns.Length()    == 0 &&
             ent->mActiveConns.Length()  == 0 &&
             ent->mHalfOpens.Length()    == 0 &&
             ent->mUrgentStartQ.Length() == 0 &&
             ent->PendingQLength()       == 0) {
@@ -567,17 +567,17 @@ nsHttpConnectionMgr::ClearConnectionHist
     }
 
     return NS_OK;
 }
 
 nsresult
 nsHttpConnectionMgr::CloseIdleConnection(nsHttpConnection *conn)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::CloseIdleConnection %p conn=%p",
          this, conn));
 
     if (!conn->ConnectionInfo()) {
         return NS_ERROR_UNEXPECTED;
     }
 
     nsConnectionEntry *ent = mCT.Get(conn->ConnectionInfo()->HashKey());
@@ -590,17 +590,17 @@ nsHttpConnectionMgr::CloseIdleConnection
     mNumIdleConns--;
     ConditionallyStopPruneDeadConnectionsTimer();
     return NS_OK;
 }
 
 nsresult
 nsHttpConnectionMgr::RemoveIdleConnection(nsHttpConnection *conn)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     LOG(("nsHttpConnectionMgr::RemoveIdleConnection %p conn=%p",
          this, conn));
 
     if (!conn->ConnectionInfo()) {
         return NS_ERROR_UNEXPECTED;
     }
 
@@ -614,17 +614,17 @@ nsHttpConnectionMgr::RemoveIdleConnectio
     return NS_OK;
 }
 
 nsHttpConnection *
 nsHttpConnectionMgr::FindCoalescableConnectionByHashKey(nsConnectionEntry *ent,
                                                         const nsCString &key,
                                                         bool justKidding)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(ent->mConnInfo);
     nsHttpConnectionInfo *ci = ent->mConnInfo;
 
     nsTArray<nsWeakPtr> *listOfWeakConns =  mCoalescingHash.Get(key);
     if (!listOfWeakConns) {
         return nullptr;
     }
 
@@ -686,17 +686,17 @@ BuildOriginFrameHashKey(nsACString &newK
     newKey.Append(suffix);
     newKey.AppendLiteral("]viaORIGIN.FRAME");
 }
 
 nsHttpConnection *
 nsHttpConnectionMgr::FindCoalescableConnection(nsConnectionEntry *ent,
                                                bool justKidding)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(ent->mConnInfo);
     nsHttpConnectionInfo *ci = ent->mConnInfo;
     LOG(("FindCoalescableConnection %s\n", ci->HashKey().get()));
     // First try and look it up by origin frame
     nsCString newKey;
     BuildOriginFrameHashKey(newKey, ci, ci->GetOrigin(), ci->OriginPort());
     nsHttpConnection *conn =
         FindCoalescableConnectionByHashKey(ent, newKey, justKidding);
@@ -721,17 +721,17 @@ nsHttpConnectionMgr::FindCoalescableConn
     LOG(("FindCoalescableConnection(%s) no matching conn\n", ci->HashKey().get()));
     return nullptr;
 }
 
 void
 nsHttpConnectionMgr::UpdateCoalescingForNewConn(nsHttpConnection *newConn,
                                                 nsConnectionEntry *ent)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(newConn);
     MOZ_ASSERT(newConn->ConnectionInfo());
     MOZ_ASSERT(ent);
     MOZ_ASSERT(mCT.Get(newConn->ConnectionInfo()->HashKey()) == ent);
 
     nsHttpConnection *existingConn = FindCoalescableConnection(ent, true);
     if (existingConn) {
         LOG(("UpdateCoalescingForNewConn() found existing active conn that could have served newConn "
@@ -792,17 +792,17 @@ nsHttpConnectionMgr::UpdateCoalescingFor
 // the connection manager. The connection entry associated with the
 // connection is then updated to indicate whether or not we want to use
 // spdy with that host and update the coalescing hash
 // entries used for de-sharding hostsnames.
 void
 nsHttpConnectionMgr::ReportSpdyConnection(nsHttpConnection *conn,
                                           bool usingSpdy)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     if (!conn->ConnectionInfo()) {
         return;
     }
     nsConnectionEntry *ent = mCT.Get(conn->ConnectionInfo()->HashKey());
     if (!ent || !usingSpdy) {
         return;
     }
 
@@ -833,17 +833,17 @@ nsHttpConnectionMgr::ReportSpdyConnectio
 }
 
 //-----------------------------------------------------------------------------
 bool
 nsHttpConnectionMgr::DispatchPendingQ(nsTArray<RefPtr<nsHttpConnectionMgr::PendingTransactionInfo> > &pendingQ,
                                       nsConnectionEntry *ent,
                                       bool considerAll)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     PendingTransactionInfo *pendingTransInfo = nullptr;
     nsresult rv;
     bool dispatchedSuccessfully = false;
 
     // if !considerAll iterate the pending list until one is dispatched successfully.
     // Keep iterating afterwards only until a transaction fails to dispatch.
     // if considerAll == true then try and dispatch all items.
@@ -948,17 +948,17 @@ nsHttpConnectionMgr::MaxPersistConnectio
     }
 
     return static_cast<uint32_t>(mMaxPersistConnsPerHost);
 }
 
 bool
 nsHttpConnectionMgr::ProcessPendingQForEntry(nsConnectionEntry *ent, bool considerAll)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     LOG(("nsHttpConnectionMgr::ProcessPendingQForEntry "
          "[ci=%s ent=%p active=%" PRIuSIZE " idle=%" PRIuSIZE " urgent-start-queue=%" PRIuSIZE
          " queued=%" PRIuSIZE "]\n",
          ent->mConnInfo->HashKey().get(), ent, ent->mActiveConns.Length(),
          ent->mIdleConns.Length(), ent->mUrgentStartQ.Length(),
          ent->PendingQLength()));
 
@@ -1076,17 +1076,17 @@ nsHttpConnectionMgr::ProcessPendingQForE
     ent->RemoveEmptyPendingQ();
 
     return dispatchedSuccessfully;
 }
 
 bool
 nsHttpConnectionMgr::ProcessPendingQForEntry(nsHttpConnectionInfo *ci)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsConnectionEntry *ent = mCT.Get(ci->HashKey());
     if (ent)
         return ProcessPendingQForEntry(ent, false);
     return false;
 }
 
 // we're at the active connection limit if any one of the following conditions is true:
@@ -1150,17 +1150,17 @@ nsHttpConnectionMgr::ClosePersistentConn
     int32_t activeCount = ent->mActiveConns.Length();
     for (int32_t i=0; i < activeCount; i++)
         ent->mActiveConns[i]->DontReuse();
 }
 
 bool
 nsHttpConnectionMgr::RestrictConnections(nsConnectionEntry *ent)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (ent->AvailableForDispatchNow()) {
         // this might be a h2/spdy connection in this connection entry that
         // is able to be immediately muxxed, or it might be one that
         // was found in the same state through a coalescing hash
         LOG(("nsHttpConnectionMgr::RestrictConnections %p %s restricted due to active >=h2\n",
              ent, ent->mConnInfo->HashKey().get()));
         return true;
@@ -1212,17 +1212,17 @@ nsHttpConnectionMgr::RestrictConnections
 nsresult
 nsHttpConnectionMgr::MakeNewConnection(nsConnectionEntry *ent,
                                        PendingTransactionInfo *pendingTransInfo)
 {
     nsHttpTransaction *trans = pendingTransInfo->mTransaction;
 
     LOG(("nsHttpConnectionMgr::MakeNewConnection %p ent=%p trans=%p",
          this, ent, trans));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     uint32_t halfOpenLength = ent->mHalfOpens.Length();
     for (uint32_t i = 0; i < halfOpenLength; i++) {
         if (ent->mHalfOpens[i]->Claim()) {
             // We've found a speculative connection or a connection that
             // is free to be used in the half open list.
             // A free to be used connection is a connection that was
             // open for a concrete transaction, but that trunsaction
@@ -1349,17 +1349,17 @@ nsHttpConnectionMgr::MakeNewConnection(n
 //   should be queued until circumstances change
 // returns other ERROR when transaction has a hard failure and should
 //   not remain in the pending queue
 nsresult
 nsHttpConnectionMgr::TryDispatchTransaction(nsConnectionEntry *ent,
                                             bool onlyReusedConnection,
                                             PendingTransactionInfo *pendingTransInfo)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsHttpTransaction *trans = pendingTransInfo->mTransaction;
 
     LOG(("nsHttpConnectionMgr::TryDispatchTransaction without conn "
          "[trans=%p halfOpen=%p conn=%p ci=%p ci=%s caps=%x tunnelprovider=%p "
          "onlyreused=%d active=%" PRIuSIZE " idle=%" PRIuSIZE "]\n", trans,
          pendingTransInfo->mHalfOpen.get(),
          pendingTransInfo->mActiveConn.get(), ent->mConnInfo.get(),
@@ -1683,17 +1683,17 @@ nsHttpConnectionMgr::ReportProxyTelemetr
         Telemetry::Accumulate(Telemetry::HTTP_PROXY_TYPE, PROXY_HTTP);
     else
         Telemetry::Accumulate(Telemetry::HTTP_PROXY_TYPE, PROXY_SOCKS);
 }
 
 nsresult
 nsHttpConnectionMgr::ProcessNewTransaction(nsHttpTransaction *trans)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // since "adds" and "cancels" are processed asynchronously and because
     // various events might trigger an "add" directly on the socket thread,
     // we must take care to avoid dispatching a transaction that has already
     // been canceled (see bug 190001).
     if (NS_FAILED(trans->Status())) {
         LOG(("  transaction was canceled... dropping event!\n"));
         return NS_OK;
@@ -1847,17 +1847,17 @@ nsresult
 nsHttpConnectionMgr::CreateTransport(nsConnectionEntry *ent,
                                      nsAHttpTransaction *trans,
                                      uint32_t caps,
                                      bool speculative,
                                      bool isFromPredictor,
                                      bool allow1918,
                                      PendingTransactionInfo *pendingTransInfo)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT((speculative && !pendingTransInfo) ||
                (!speculative && pendingTransInfo));
 
     RefPtr<nsHalfOpenSocket> sock = new nsHalfOpenSocket(ent, trans, caps,
                                                          speculative,
                                                          isFromPredictor);
 
     if (speculative) {
@@ -1957,29 +1957,29 @@ nsHttpConnectionMgr::ProcessSpdyPendingQ
     for (const auto& transactionInfo : pendingQ) {
         ent->InsertTransaction(transactionInfo);
     }
 }
 
 void
 nsHttpConnectionMgr::OnMsgProcessAllSpdyPendingQ(int32_t, ARefBase *)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgProcessAllSpdyPendingQ\n"));
     for (auto iter = mCT.Iter(); !iter.Done(); iter.Next()) {
         ProcessSpdyPendingQ(iter.Data());
     }
 }
 
 // Given a connection entry, return an active h2 connection
 // that can be directly activated or null
 nsHttpConnection *
 nsHttpConnectionMgr::GetSpdyActiveConn(nsConnectionEntry *ent)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(ent);
 
     nsHttpConnection *experienced = nullptr;
     nsHttpConnection *noExperience = nullptr;
     uint32_t activeLen = ent->mActiveConns.Length();
     nsHttpConnectionInfo *ci = ent->mConnInfo;
     uint32_t index;
 
@@ -2033,17 +2033,17 @@ nsHttpConnectionMgr::GetSpdyActiveConn(n
     return nullptr;
 }
 
 //-----------------------------------------------------------------------------
 
 void
 nsHttpConnectionMgr::OnMsgShutdown(int32_t, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgShutdown\n"));
 
     gHttpHandler->StopRequestTokenBucket();
 
     for (auto iter = mCT.Iter(); !iter.Done(); iter.Next()) {
         nsAutoPtr<nsConnectionEntry>& ent = iter.Data();
 
         // Close all active connections.
@@ -2140,17 +2140,17 @@ nsHttpConnectionMgr::OnMsgNewTransaction
     nsresult rv = ProcessNewTransaction(trans);
     if (NS_FAILED(rv))
         trans->Close(rv); // for whatever its worth
 }
 
 void
 nsHttpConnectionMgr::OnMsgReschedTransaction(int32_t priority, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgReschedTransaction [trans=%p]\n", param));
 
     RefPtr<nsHttpTransaction> trans = static_cast<nsHttpTransaction *>(param);
     trans->SetPriority(priority);
 
     if (!trans->ConnectionInfo()) {
         return;
     }
@@ -2175,29 +2175,29 @@ nsHttpConnectionMgr::OnMsgReschedTransac
             pendingQ->RemoveElementAt(index);
             InsertTransactionSorted(*pendingQ, pendingTransInfo);
         }
     }
 }
 
 void nsHttpConnectionMgr::OnMsgThrottleTransaction(int32_t arg, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgThrottleTransaction [trans=%p]\n", param));
 
     bool throttle = static_cast<bool>(arg);
     nsHttpTransaction *trans = static_cast<nsHttpTransaction *>(param);
 
     trans->ThrottleResponse(throttle);
 }
 
 void
 nsHttpConnectionMgr::OnMsgCancelTransaction(int32_t reason, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgCancelTransaction [trans=%p]\n", param));
 
     nsresult closeCode = static_cast<nsresult>(reason);
 
     // caller holds a ref to param/trans on stack
     nsHttpTransaction *trans = static_cast<nsHttpTransaction *>(param);
 
     //
@@ -2271,17 +2271,17 @@ nsHttpConnectionMgr::OnMsgCancelTransact
             }
         }
     }
 }
 
 void
 nsHttpConnectionMgr::OnMsgProcessPendingQ(int32_t, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     nsHttpConnectionInfo *ci = static_cast<nsHttpConnectionInfo *>(param);
 
     if (!ci) {
         LOG(("nsHttpConnectionMgr::OnMsgProcessPendingQ [ci=nullptr]\n"));
         // Try and dispatch everything
         for (auto iter = mCT.Iter(); !iter.Done(); iter.Next()) {
             Unused << ProcessPendingQForEntry(iter.Data(), true);
         }
@@ -2348,17 +2348,17 @@ nsHttpConnectionMgr::OnMsgCancelTransact
         CancelTransactionsHelper(*it.UserData(), ci, ent, reason);
     }
     ent->mPendingTransactionTable.Clear();
 }
 
 void
 nsHttpConnectionMgr::OnMsgPruneDeadConnections(int32_t, ARefBase *)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgPruneDeadConnections\n"));
 
     // Reset mTimeOfNextWakeUp so that we can find a new shortest value.
     mTimeOfNextWakeUp = UINT64_MAX;
 
     // check canreuse() for all idle connections plus any active connections on
     // connection entries that are using spdy.
     if (mNumIdleConns || (mNumActiveConns && gHttpHandler->IsSpdyEnabled())) {
@@ -2445,17 +2445,17 @@ nsHttpConnectionMgr::OnMsgPruneDeadConne
             }
         }
     }
 }
 
 void
 nsHttpConnectionMgr::OnMsgPruneNoTraffic(int32_t, ARefBase *)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgPruneNoTraffic\n"));
 
     // Prune connections without traffic
     for (auto iter = mCT.Iter(); !iter.Done(); iter.Next()) {
 
         // Close the connections with no registered traffic.
         nsAutoPtr<nsConnectionEntry>& ent = iter.Data();
 
@@ -2479,17 +2479,17 @@ nsHttpConnectionMgr::OnMsgPruneNoTraffic
     }
 
     mPruningNoTraffic = false; // not pruning anymore
 }
 
 void
 nsHttpConnectionMgr::OnMsgVerifyTraffic(int32_t, ARefBase *)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgVerifyTraffic\n"));
 
     if (mPruningNoTraffic) {
       // Called in the time gap when the timeout to prune notraffic
       // connections has triggered but the pruning hasn't happened yet.
       return;
     }
 
@@ -2523,32 +2523,32 @@ nsHttpConnectionMgr::OnMsgVerifyTraffic(
         NS_WARNING("failed to create timer for VerifyTraffic!");
     }
 }
 
 void
 nsHttpConnectionMgr::OnMsgDoShiftReloadConnectionCleanup(int32_t, ARefBase *param)
 {
     LOG(("nsHttpConnectionMgr::OnMsgDoShiftReloadConnectionCleanup\n"));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsHttpConnectionInfo *ci = static_cast<nsHttpConnectionInfo *>(param);
 
     for (auto iter = mCT.Iter(); !iter.Done(); iter.Next()) {
         ClosePersistentConnections(iter.Data());
     }
 
     if (ci)
         ResetIPFamilyPreference(ci);
 }
 
 void
 nsHttpConnectionMgr::OnMsgReclaimConnection(int32_t, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::OnMsgReclaimConnection [conn=%p]\n", param));
 
     nsHttpConnection *conn = static_cast<nsHttpConnection *>(param);
 
     //
     // 1) remove the connection from the active list
     // 2) if keep-alive, add connection to idle list
     // 3) post event to process the pending transaction queue
@@ -2629,17 +2629,17 @@ nsHttpConnectionMgr::OnMsgReclaimConnect
     }
 
     OnMsgProcessPendingQ(0, ci);
 }
 
 void
 nsHttpConnectionMgr::OnMsgCompleteUpgrade(int32_t, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     nsCompleteUpgradeData *data = static_cast<nsCompleteUpgradeData *>(param);
     LOG(("nsHttpConnectionMgr::OnMsgCompleteUpgrade "
          "this=%p conn=%p listener=%p\n", this, data->mConn.get(),
          data->mUpgradeListener.get()));
 
     nsCOMPtr<nsISocketTransport> socketTransport;
     nsCOMPtr<nsIAsyncInputStream> socketIn;
     nsCOMPtr<nsIAsyncOutputStream> socketOut;
@@ -2695,17 +2695,17 @@ nsHttpConnectionMgr::nsConnectionEntry::
     MOZ_COUNT_DTOR(nsConnectionEntry);
 }
 
 // Read Timeout Tick handlers
 
 void
 nsHttpConnectionMgr::ActivateTimeoutTick()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     LOG(("nsHttpConnectionMgr::ActivateTimeoutTick() "
          "this=%p mTimeoutTick=%p\n", this, mTimeoutTick.get()));
 
     // The timer tick should be enabled if it is not already pending.
     // Upon running the tick will rearm itself if there are active
     // connections available.
 
     if (mTimeoutTick && mTimeoutTickArmed) {
@@ -2756,28 +2756,28 @@ nsHttpConnectionMgr::UpdateCurrentTopLev
         0,
         windowIdWrapper);
 }
 
 void
 nsHttpConnectionMgr::OnMsgUpdateCurrentTopLevelOuterContentWindowId(
     int32_t, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     mCurrentTopLevelOuterContentWindowId =
         static_cast<UINT64Wrapper*>(param)->GetValue();
     LOG(("nsHttpConnectionMgr::OnMsgUpdateCurrentTopLevelOuterContentWindowId"
          " id=%" PRIu64 "\n",
          mCurrentTopLevelOuterContentWindowId));
 }
 
 void
 nsHttpConnectionMgr::TimeoutTick()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(mTimeoutTick, "no readtimeout tick");
 
     LOG(("nsHttpConnectionMgr::TimeoutTick active=%d\n", mNumActiveConns));
     // The next tick will be between 1 second and 1 hr
     // Set it to the max value here, and the TimeoutTick()s can
     // reduce it to their local needs.
     mTimeoutTickNext = 3600; // 1hr
 
@@ -2904,17 +2904,17 @@ ConnectionHandle::TakeTransport(nsISocke
                                 nsIAsyncOutputStream **aOutputStream)
 {
     return mConn->TakeTransport(aTransport, aInputStream, aOutputStream);
 }
 
 void
 nsHttpConnectionMgr::OnMsgSpeculativeConnect(int32_t, ARefBase *param)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     SpeculativeConnectArgs *args = static_cast<SpeculativeConnectArgs *>(param);
 
     LOG(("nsHttpConnectionMgr::OnMsgSpeculativeConnect [ci=%s]\n",
          args->mTrans->ConnectionInfo()->HashKey().get()));
 
     nsConnectionEntry *ent =
         GetOrCreateConnectionEntry(args->mTrans->ConnectionInfo(), false);
@@ -3039,17 +3039,17 @@ nsHttpConnectionMgr::nsHalfOpenSocket::~
 
 nsresult
 nsHttpConnectionMgr::
 nsHalfOpenSocket::SetupStreams(nsISocketTransport **transport,
                                nsIAsyncInputStream **instream,
                                nsIAsyncOutputStream **outstream,
                                bool isBackup)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsresult rv;
     const char *socketTypes[1];
     uint32_t typeCount = 0;
     const nsHttpConnectionInfo *ci = mEnt->mConnInfo;
     if (ci->FirstHopSSL()) {
         socketTypes[typeCount++] = "ssl";
     } else {
@@ -3170,17 +3170,17 @@ nsHalfOpenSocket::SetupStreams(nsISocket
         gHttpHandler->ConnMgr()->StartedConnect();
 
     return rv;
 }
 
 nsresult
 nsHttpConnectionMgr::nsHalfOpenSocket::SetupPrimaryStreams()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     nsresult rv;
 
     mPrimarySynStarted = TimeStamp::Now();
     rv = SetupStreams(getter_AddRefs(mSocketTransport),
                       getter_AddRefs(mStreamIn),
                       getter_AddRefs(mStreamOut),
                       false);
@@ -3258,17 +3258,17 @@ nsHttpConnectionMgr::nsHalfOpenSocket::C
 void
 nsHttpConnectionMgr::nsHalfOpenSocket::Abandon()
 {
     LOG(("nsHalfOpenSocket::Abandon [this=%p ent=%s] %p %p %p %p",
          this, mEnt->mConnInfo->Origin(),
          mSocketTransport.get(), mBackupTransport.get(),
          mStreamOut.get(), mBackupStreamOut.get()));
 
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     RefPtr<nsHalfOpenSocket> deleteProtector(this);
 
     // Tell socket (and backup socket) to forget the half open socket.
     if (mSocketTransport) {
         mSocketTransport->SetEventSink(nullptr, nullptr);
         mSocketTransport->SetSecurityCallbacks(nullptr);
         mSocketTransport = nullptr;
@@ -3311,17 +3311,17 @@ nsHttpConnectionMgr::nsHalfOpenSocket::D
 
     return (epoch - mPrimarySynStarted).ToMilliseconds();
 }
 
 
 NS_IMETHODIMP // method for nsITimerCallback
 nsHttpConnectionMgr::nsHalfOpenSocket::Notify(nsITimer *timer)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(timer == mSynTimer, "wrong timer");
 
     DebugOnly<nsresult> rv = SetupBackupStreams();
     MOZ_ASSERT(NS_SUCCEEDED(rv));
 
     mSynTimer = nullptr;
     return NS_OK;
 }
@@ -3354,17 +3354,17 @@ nsHalfOpenSocket::FindTransactionHelper(
     return info.forget();
 }
 
 // method for nsIAsyncOutputStreamCallback
 NS_IMETHODIMP
 nsHttpConnectionMgr::
 nsHalfOpenSocket::OnOutputStreamReady(nsIAsyncOutputStream *out)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(out == mStreamOut || out == mBackupStreamOut,
                "stream mismatch");
     LOG(("nsHalfOpenSocket::OnOutputStreamReady [this=%p ent=%s %s]\n",
          this, mEnt->mConnInfo->Origin(),
          out == mStreamOut ? "primary" : "backup"));
     nsresult rv;
 
     gHttpHandler->ConnMgr()->RecvdConnect();
@@ -3520,17 +3520,17 @@ nsHalfOpenSocket::OnOutputStreamReady(ns
 
 // register a connection to receive CanJoinConnection() for particular
 // origin keys
 void
 nsHttpConnectionMgr::RegisterOriginCoalescingKey(nsHttpConnection *conn,
                                                  const nsACString &host,
                                                  int32_t port)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     nsHttpConnectionInfo *ci = conn ? conn->ConnectionInfo() : nullptr;
     if (!ci || !conn->CanDirectlyActivate()) {
         return;
     }
 
     nsCString newKey;
     BuildOriginFrameHashKey(newKey, ci, host, port);
     nsTArray<nsWeakPtr> *listOfWeakConns =  mCoalescingHash.Get(newKey);
@@ -3547,17 +3547,17 @@ nsHttpConnectionMgr::RegisterOriginCoale
 
 // method for nsITransportEventSink
 NS_IMETHODIMP
 nsHttpConnectionMgr::nsHalfOpenSocket::OnTransportStatus(nsITransport *trans,
                                                          nsresult status,
                                                          int64_t progress,
                                                          int64_t progressMax)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mTransaction) {
         RefPtr<PendingTransactionInfo> info = FindTransactionHelper(false);
         if ((trans == mSocketTransport) ||
             ((trans == mBackupTransport) && (status == NS_NET_STATUS_CONNECTED_TO) &&
             info)) {
             // Send this status event only if the transaction is still panding,
             // i.e. it has not found a free already connected socket.
@@ -3799,17 +3799,17 @@ nsHttpConnectionMgr::GetConnectionData(n
     }
 
     return true;
 }
 
 void
 nsHttpConnectionMgr::ResetIPFamilyPreference(nsHttpConnectionInfo *ci)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     nsConnectionEntry *ent = mCT.Get(ci->HashKey());
     if (ent) {
         ent->ResetIPFamilyPreference();
     }
 }
 
 uint32_t
 nsHttpConnectionMgr::
@@ -3987,17 +3987,17 @@ nsHttpConnectionMgr::nsConnectionEntry::
     }
 }
 
 void
 nsHttpConnectionMgr::MoveToWildCardConnEntry(nsHttpConnectionInfo *specificCI,
                                              nsHttpConnectionInfo *wildCardCI,
                                              nsHttpConnection *proxyConn)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     MOZ_ASSERT(specificCI->UsingHttpsProxy());
 
     LOG(("nsHttpConnectionMgr::MakeConnEntryWildCard conn %p has requested to "
          "change CI from %s to %s\n", proxyConn, specificCI->HashKey().get(),
          wildCardCI->HashKey().get()));
 
     nsConnectionEntry *ent = mCT.Get(specificCI->HashKey());
     LOG(("nsHttpConnectionMgr::MakeConnEntryWildCard conn %p using ent %p (spdy %d)\n",
--- a/netwerk/protocol/http/nsHttpHandler.cpp
+++ b/netwerk/protocol/http/nsHttpHandler.cpp
@@ -611,17 +611,17 @@ nsHttpHandler::GetThrottlingService()
 
     return mThrottlingService;
 }
 
 uint32_t
 nsHttpHandler::Get32BitsOfPseudoRandom()
 {
     // only confirm rand seeding on socket thread
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // rand() provides different amounts of PRNG on different platforms.
     // 15 or 31 bits are common amounts.
 
     static_assert(RAND_MAX >= 0xfff, "RAND_MAX should be >= 12 bits");
 
 #if RAND_MAX < 0xffffU
     return ((uint16_t) rand() << 20) |
--- a/netwerk/protocol/http/nsHttpHandler.h
+++ b/netwerk/protocol/http/nsHttpHandler.h
@@ -28,17 +28,17 @@ class nsIRequestContextService;
 class nsISiteSecurityService;
 class nsIStreamConverterService;
 class nsIThrottlingService;
 
 
 namespace mozilla {
 namespace net {
 
-extern Atomic<PRThread*, Relaxed> gSocketThread;
+bool OnSocketThread();
 
 class ATokenBucketEvent;
 class EventTokenBucket;
 class Tickler;
 class nsHttpConnection;
 class nsHttpConnectionInfo;
 class nsHttpTransaction;
 class AltSvcMapping;
@@ -588,33 +588,33 @@ private:
     void MakeNewRequestTokenBucket();
     RefPtr<EventTokenBucket> mRequestTokenBucket;
 
 public:
     // Socket thread only
     MOZ_MUST_USE nsresult SubmitPacedRequest(ATokenBucketEvent *event,
                                              nsICancelable **cancel)
     {
-        MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+        MOZ_ASSERT(OnSocketThread(), "not on socket thread");
         if (!mRequestTokenBucket) {
             return NS_ERROR_NOT_AVAILABLE;
         }
         return mRequestTokenBucket->SubmitEvent(event, cancel);
     }
 
     // Socket thread only
     void SetRequestTokenBucket(EventTokenBucket *aTokenBucket)
     {
-        MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+        MOZ_ASSERT(OnSocketThread(), "not on socket thread");
         mRequestTokenBucket = aTokenBucket;
     }
 
     void StopRequestTokenBucket()
     {
-        MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+        MOZ_ASSERT(OnSocketThread(), "not on socket thread");
         if (mRequestTokenBucket) {
             mRequestTokenBucket->Stop();
             mRequestTokenBucket = nullptr;
         }
     }
 
 private:
     RefPtr<Tickler> mWifiTickler;
--- a/netwerk/protocol/http/nsHttpTransaction.cpp
+++ b/netwerk/protocol/http/nsHttpTransaction.cpp
@@ -151,17 +151,17 @@ nsHttpTransaction::nsHttpTransaction()
     memset(&mPeerAddr, 0, sizeof(NetAddr));
 #endif
     mSelfAddr.raw.family = PR_AF_UNSPEC;
     mPeerAddr.raw.family = PR_AF_UNSPEC;
 }
 
 void nsHttpTransaction::ThrottleResponse(bool aThrottle)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // Just in case we suspend, get a connection, release a connection, get another connection.
     mThrottleResponse = aThrottle;
 
     if (mConnection) {
         mConnection->ThrottleResponse(aThrottle);
     }
 }
@@ -400,17 +400,17 @@ nsHttpTransaction::Init(uint32_t caps,
     tmp.forget(responseBody);
     return NS_OK;
 }
 
 // This method should only be used on the socket thread
 nsAHttpConnection *
 nsHttpTransaction::Connection()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     return mConnection.get();
 }
 
 already_AddRefed<nsAHttpConnection>
 nsHttpTransaction::GetConnectionReference()
 {
     MutexAutoLock lock(mLock);
     RefPtr<nsAHttpConnection> connection(mConnection);
@@ -547,17 +547,17 @@ nsHttpTransaction::OnTransportStatus(nsI
         } else if (status == NS_NET_STATUS_TLS_HANDSHAKE_ENDED) {
             SetConnectEnd(TimeStamp::Now(), false);
         }
     }
 
     if (!mTransportSink)
         return;
 
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // Need to do this before the STATUS_RECEIVING_FROM check below, to make
     // sure that the activity distributor gets told about all status events.
     if (mActivityDistributor) {
         // upon STATUS_WAITING_FOR; report request body sent
         if ((mHasRequestBody) &&
             (status == NS_NET_STATUS_WAITING_FOR)) {
             nsresult rv = mActivityDistributor->ObserveActivity(
@@ -686,17 +686,17 @@ nsHttpTransaction::ReadRequestSegment(ns
     trans->mSentData = true;
     return NS_OK;
 }
 
 nsresult
 nsHttpTransaction::ReadSegments(nsAHttpSegmentReader *reader,
                                 uint32_t count, uint32_t *countRead)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mTransactionDone) {
         *countRead = 0;
         return mStatus;
     }
 
     if (!mConnected && !m0RTTInProgress) {
         mConnected = true;
@@ -803,17 +803,17 @@ nsresult
 nsHttpTransaction::WriteSegments(nsAHttpSegmentWriter *writer,
                                  uint32_t count, uint32_t *countWritten)
 {
     static bool reentrantFlag = false;
     LOG(("nsHttpTransaction::WriteSegments %p reentrantFlag=%d",
          this, reentrantFlag));
     MOZ_DIAGNOSTIC_ASSERT(!reentrantFlag);
     reentrantFlag = true;
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mTransactionDone) {
         reentrantFlag = false;
         return NS_SUCCEEDED(mStatus) ? NS_BASE_STREAM_CLOSED : mStatus;
     }
 
     mWriter = writer;
 
@@ -861,17 +861,17 @@ nsHttpTransaction::WriteSegments(nsAHttp
 }
 
 void
 nsHttpTransaction::Close(nsresult reason)
 {
     LOG(("nsHttpTransaction::Close [this=%p reason=%" PRIx32 "]\n",
          this, static_cast<uint32_t>(reason)));
 
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     if (reason == NS_BINDING_RETARGETED) {
         LOG(("  close %p skipped due to ERETARGETED\n", this));
         return;
     }
 
     if (mClosed) {
         LOG(("  already closed\n"));
         return;
@@ -1109,17 +1109,17 @@ nsHttpTransaction::ResponseTimeoutEnable
 
 //-----------------------------------------------------------------------------
 // nsHttpTransaction <private>
 //-----------------------------------------------------------------------------
 
 nsresult
 nsHttpTransaction::Restart()
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     // limit the number of restart attempts - bug 92224
     if (++mRestartCount >= gHttpHandler->MaxRequestAttempts()) {
         LOG(("reached max request attempts, failing transaction @%p\n", this));
         return NS_ERROR_NET_RESET;
     }
 
     LOG(("restarting transaction @%p\n", this));
@@ -1428,17 +1428,17 @@ nsHttpTransaction::ParseHead(char *buf,
     }
     return NS_OK;
 }
 
 nsresult
 nsHttpTransaction::HandleContentStart()
 {
     LOG(("nsHttpTransaction::HandleContentStart [this=%p]\n", this));
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mResponseHead) {
         if (mEarlyDataDisposition == EARLY_ACCEPTED) {
             Unused << mResponseHead->SetHeader(nsHttp::X_Firefox_Early_Data, NS_LITERAL_CSTRING("accepted"));
         } else if (mEarlyDataDisposition == EARLY_SENT) {
             Unused << mResponseHead->SetHeader(nsHttp::X_Firefox_Early_Data, NS_LITERAL_CSTRING("sent"));
         } // no header on NONE case
 
@@ -1811,17 +1811,17 @@ nsHttpTransaction::DisableSpdy()
 
 void
 nsHttpTransaction::CheckForStickyAuthScheme()
 {
   LOG(("nsHttpTransaction::CheckForStickyAuthScheme this=%p", this));
 
   MOZ_ASSERT(mHaveAllHeaders);
   MOZ_ASSERT(mResponseHead);
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (mClosed) {
       LOG(("  closed, not checking"));
       return;
   }
 
   CheckForStickyAuthSchemeAt(nsHttp::WWW_Authenticate);
   CheckForStickyAuthSchemeAt(nsHttp::Proxy_Authenticate);
@@ -2099,17 +2099,17 @@ NS_IMPL_QUERY_INTERFACE(nsHttpTransactio
 //-----------------------------------------------------------------------------
 // nsHttpTransaction::nsIInputStreamCallback
 //-----------------------------------------------------------------------------
 
 // called on the socket thread
 NS_IMETHODIMP
 nsHttpTransaction::OnInputStreamReady(nsIAsyncInputStream *out)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     if (mConnection) {
         mConnection->TransactionHasDataToWrite(this);
         nsresult rv = mConnection->ResumeSend();
         if (NS_FAILED(rv))
             NS_ERROR("ResumeSend failed");
     }
     return NS_OK;
 }
@@ -2117,17 +2117,17 @@ nsHttpTransaction::OnInputStreamReady(ns
 //-----------------------------------------------------------------------------
 // nsHttpTransaction::nsIOutputStreamCallback
 //-----------------------------------------------------------------------------
 
 // called on the socket thread
 NS_IMETHODIMP
 nsHttpTransaction::OnOutputStreamReady(nsIAsyncOutputStream *out)
 {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
     mWaitingOnPipeOut = false;
     if (mConnection) {
         mConnection->TransactionHasDataToRecv(this);
         nsresult rv = mConnection->ResumeRecv();
         if (NS_FAILED(rv))
             NS_ERROR("ResumeRecv failed");
     }
     return NS_OK;
--- a/netwerk/protocol/websocket/WebSocketChannel.cpp
+++ b/netwerk/protocol/websocket/WebSocketChannel.cpp
@@ -1294,17 +1294,17 @@ WebSocketChannel::OnNetworkChanged()
       return NS_OK;
     }
 
     return mSocketThread->Dispatch(
       NewRunnableMethod(this, &WebSocketChannel::OnNetworkChanged),
       NS_DISPATCH_NORMAL);
   }
 
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "not socket thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   LOG(("WebSocketChannel::OnNetworkChanged() - on socket thread %p", this));
 
   if (mPingOutstanding) {
     // If there's an outstanding ping that's expected to get a pong back
     // we let that do its thing.
     LOG(("WebSocket: pong already pending"));
     return NS_OK;
@@ -1495,17 +1495,17 @@ WebSocketChannel::UpdateReadBuffer(uint8
 
   return true;
 }
 
 nsresult
 WebSocketChannel::ProcessInput(uint8_t *buffer, uint32_t count)
 {
   LOG(("WebSocketChannel::ProcessInput %p [%d %d]\n", this, count, mBuffered));
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "not socket thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   nsresult rv;
 
   // The purpose of ping/pong is to actively probe the peer so that an
   // unreachable peer is not mistaken for a period of idleness. This
   // implementation accepts any application level read activity as a sign of
   // life, it does not necessarily have to be a pong.
   ResetPingTimer();
@@ -2000,17 +2000,17 @@ WebSocketChannel::GeneratePong(uint8_t *
   EnqueueOutgoingMessage(mOutgoingPongMessages,
                          new OutboundMessage(kMsgTypePong, buf));
 }
 
 void
 WebSocketChannel::EnqueueOutgoingMessage(nsDeque &aQueue,
                                          OutboundMessage *aMsg)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "not socket thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   LOG(("WebSocketChannel::EnqueueOutgoingMessage %p "
        "queueing msg %p [type=%s len=%d]\n",
        this, aMsg, msgNames[aMsg->GetMsgType()], aMsg->Length()));
 
   aQueue.Push(aMsg);
   OnOutputStreamReady(mSocketOut);
 }
@@ -2034,17 +2034,17 @@ WebSocketChannel::ResultToCloseCode(nsre
       return CLOSE_PROTOCOL_ERROR;
   }
 }
 
 void
 WebSocketChannel::PrimeNewOutgoingMessage()
 {
   LOG(("WebSocketChannel::PrimeNewOutgoingMessage() %p\n", this));
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "not socket thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(!mCurrentOut, "Current message in progress");
 
   nsresult rv = NS_OK;
 
   mCurrentOut = (OutboundMessage *)mOutgoingPongMessages.PopFront();
   if (mCurrentOut) {
     MOZ_ASSERT(mCurrentOut->GetMsgType() == kMsgTypePong,
                "Not pong message!");
@@ -2500,17 +2500,17 @@ WebSocketChannel::AbortSession(nsresult 
 }
 
 // ReleaseSession is called on orderly shutdown
 void
 WebSocketChannel::ReleaseSession()
 {
   LOG(("WebSocketChannel::ReleaseSession() %p stopped = %d\n",
        this, !!mStopped));
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "not socket thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (mStopped)
     return;
   StopSession(NS_OK);
 }
 
 void
 WebSocketChannel::IncrementSessionCount()
@@ -2989,17 +2989,17 @@ WebSocketChannel::StartWebsocketData()
 
   return NS_OK;
 }
 
 nsresult
 WebSocketChannel::StartPinging()
 {
   LOG(("WebSocketChannel::StartPinging() %p", this));
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "not socket thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mPingInterval);
   MOZ_ASSERT(!mPingTimer);
 
   nsresult rv;
   mPingTimer = do_CreateInstance("@mozilla.org/timer;1", &rv);
   if (NS_FAILED(rv)) {
     NS_WARNING("unable to create ping timer. Carrying on.");
   } else {
@@ -3238,18 +3238,17 @@ WebSocketChannel::AsyncOnChannelRedirect
 
 NS_IMETHODIMP
 WebSocketChannel::Notify(nsITimer *timer)
 {
   LOG(("WebSocketChannel::Notify() %p [%p]\n", this, timer));
 
   if (timer == mCloseTimer) {
     MOZ_ASSERT(mClientClosed, "Close Timeout without local close");
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread,
-               "not socket thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     mCloseTimer = nullptr;
     if (mStopped || mServerClosed)                /* no longer relevant */
       return NS_OK;
 
     LOG(("WebSocketChannel:: Expecting Server Close - Timed Out\n"));
     AbortSession(NS_ERROR_NET_TIMEOUT);
   } else if (timer == mOpenTimer) {
@@ -3267,18 +3266,17 @@ WebSocketChannel::Notify(nsITimer *timer
     MOZ_ASSERT(mConnecting == CONNECTING_DELAYED,
                "woke up from delay w/o being delayed?");
     MOZ_ASSERT(NS_IsMainThread(), "not main thread");
 
     mReconnectDelayTimer = nullptr;
     LOG(("WebSocketChannel: connecting [this=%p] after reconnect delay", this));
     BeginOpen(false);
   } else if (timer == mPingTimer) {
-    MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread,
-               "not socket thread");
+    MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
     if (mClientClosed || mServerClosed || mRequestedClose) {
       // no point in worrying about ping now
       mPingTimer = nullptr;
       return NS_OK;
     }
 
     if (!mPingOutstanding) {
@@ -3939,17 +3937,17 @@ WebSocketChannel::OnStopRequest(nsIReque
 }
 
 // nsIInputStreamCallback
 
 NS_IMETHODIMP
 WebSocketChannel::OnInputStreamReady(nsIAsyncInputStream *aStream)
 {
   LOG(("WebSocketChannel::OnInputStreamReady() %p\n", this));
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "not socket thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (!mSocketIn) // did we we clean up the socket after scheduling InputReady?
     return NS_OK;
 
   // this is after the http upgrade - so we are speaking websockets
   char  buffer[2048];
   uint32_t count;
   nsresult rv;
@@ -3992,17 +3990,17 @@ WebSocketChannel::OnInputStreamReady(nsI
 
 
 // nsIOutputStreamCallback
 
 NS_IMETHODIMP
 WebSocketChannel::OnOutputStreamReady(nsIAsyncOutputStream *aStream)
 {
   LOG(("WebSocketChannel::OnOutputStreamReady() %p\n", this));
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread, "not socket thread");
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   nsresult rv;
 
   if (!mCurrentOut)
     PrimeNewOutgoingMessage();
 
   while (mCurrentOut && mSocketOut) {
     const char *sndBuf;
     uint32_t toSend;
--- a/netwerk/protocol/websocket/WebSocketFrame.cpp
+++ b/netwerk/protocol/websocket/WebSocketFrame.cpp
@@ -27,17 +27,17 @@ WebSocketFrame::WebSocketFrame(const Web
 {}
 
 WebSocketFrame::WebSocketFrame(bool aFinBit, bool aRsvBit1, bool aRsvBit2,
                                bool aRsvBit3, uint8_t aOpCode, bool aMaskBit,
                                uint32_t aMask, const nsCString& aPayload)
   : mData(PR_Now(), aFinBit, aRsvBit1, aRsvBit2, aRsvBit3, aOpCode, aMaskBit,
           aMask, aPayload)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   mData.mTimeStamp = PR_Now();
 }
 
 WebSocketFrame::~WebSocketFrame()
 {}
 
 #define WSF_GETTER( method, value , type )     \
 NS_IMETHODIMP                                  \
--- a/netwerk/socket/nsNamedPipeIOLayer.cpp
+++ b/netwerk/socket/nsNamedPipeIOLayer.cpp
@@ -235,17 +235,17 @@ NamedPipeInfo::OnError(uint32_t aError,
   return NS_OK;
 }
 
 // Named pipe operations
 
 nsresult
 NamedPipeInfo::Connect(const nsACString& aPath)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   HANDLE pipe;
   nsAutoCString path(aPath);
 
   pipe = CreateFileA(path.get(),
                      GENERIC_READ | GENERIC_WRITE,
                      FILE_SHARE_READ | FILE_SHARE_WRITE,
                      nullptr,
@@ -290,17 +290,17 @@ NamedPipeInfo::Connect(const nsACString&
   mReadOverlapped.hEvent = readEvent;
   mWriteOverlapped.hEvent = writeEvent;
   return NS_OK;
 }
 
 nsresult
 NamedPipeInfo::Disconnect()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   nsresult rv = mNamedPipeService->RemoveDataObserver(mPipe, this);
   NS_WARN_IF(NS_FAILED(rv));
   mPipe = nullptr;
 
   if (mReadOverlapped.hEvent &&
       mReadOverlapped.hEvent != INVALID_HANDLE_VALUE) {
     CloseHandle(mReadOverlapped.hEvent);
@@ -314,31 +314,31 @@ NamedPipeInfo::Disconnect()
   }
 
   return NS_OK;
 }
 
 int32_t
 NamedPipeInfo::Read(void* aBuffer, int32_t aSize)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   int32_t bytesRead = Peek(aBuffer, aSize);
 
   if (bytesRead > 0) {
     mReadBegin += bytesRead;
   }
 
   return bytesRead;
 }
 
 int32_t
 NamedPipeInfo::Write(const void* aBuffer, int32_t aSize)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mWriteBegin <= mWriteEnd);
 
   if (!IsConnected()) {
     // pipe unconnected
     PR_SetError(PR_NOT_CONNECTED_ERROR, 0);
     return -1;
   }
 
@@ -369,17 +369,17 @@ NamedPipeInfo::Write(const void* aBuffer
   GetPollFlags(PR_POLL_WRITE, &outFlag);
 
   return bytesToWrite;
 }
 
 uint32_t
 NamedPipeInfo::Peek(void* aBuffer, int32_t aSize)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mReadBegin <= mReadEnd);
 
   if (!IsConnected()) {
     // pipe unconnected
     PR_SetError(PR_NOT_CONNECTED_ERROR, 0);
     return -1;
   }
 
@@ -407,65 +407,65 @@ NamedPipeInfo::Peek(void* aBuffer, int32
   MOZ_ASSERT(mReadBegin + bytesRead <= mReadEnd);
   memcpy(aBuffer, &mReadBuffer[mReadBegin], bytesRead);
   return bytesRead;
 }
 
 int32_t
 NamedPipeInfo::Available() const
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mReadBegin <= mReadEnd);
   MOZ_ASSERT(mReadEnd - mReadBegin <= 0x7FFFFFFF); // no more than int32_max
   return mReadEnd - mReadBegin;
 }
 
 bool
 NamedPipeInfo::Sync(uint32_t aTimeout)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   if (!mHasPendingWrite) {
     return true;
   }
   return WaitForSingleObject(mWriteOverlapped.hEvent, aTimeout) == WAIT_OBJECT_0;
 }
 
 void
 NamedPipeInfo::SetNonblocking(bool nonblocking)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   mNonblocking = nonblocking;
 }
 
 bool
 NamedPipeInfo::IsConnected() const
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   return mPipe && mPipe != INVALID_HANDLE_VALUE;
 }
 
 bool
 NamedPipeInfo::IsNonblocking() const
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   return mNonblocking;
 }
 
 HANDLE
 NamedPipeInfo::GetHandle() const
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   return mPipe;
 }
 
 
 int16_t
 NamedPipeInfo::GetPollFlags(int16_t aInFlags, int16_t* aOutFlags)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   *aOutFlags = 0;
 
   if (aInFlags & PR_POLL_READ) {
     int32_t bytesToRead = 0;
     if (mReadBegin < mReadEnd) { // data in buffer and is ready to be read
       bytesToRead = Available();
     } else if (mHasPendingRead) { // nonblocking I/O and has pending task
@@ -502,17 +502,17 @@ NamedPipeInfo::GetPollFlags(int16_t aInF
 
   return *aOutFlags;
 }
 
 // @return: data has been read and is available
 int32_t
 NamedPipeInfo::DoRead()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(!mHasPendingRead);
   MOZ_ASSERT(mReadBegin == mReadEnd); // the buffer should be empty
 
   mReadBegin = 0;
   mReadEnd = 0;
 
   BOOL success = ReadFile(mPipe,
                           mReadBuffer,
@@ -542,17 +542,17 @@ NamedPipeInfo::DoRead()
   }
 
   return 0;
 }
 
 int32_t
 NamedPipeInfo::DoReadContinue()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mHasPendingRead);
   MOZ_ASSERT(mReadBegin == 0 && mReadEnd == 0);
 
   BOOL success;
   success = GetOverlappedResult(mPipe,
                                 &mReadOverlapped,
                                 &mReadEnd,
                                 FALSE);
@@ -585,17 +585,17 @@ NamedPipeInfo::DoReadContinue()
   }
 
   return 0;
 }
 
 int32_t
 NamedPipeInfo::DoWrite()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(!mHasPendingWrite);
   MOZ_ASSERT(mWriteBegin < mWriteEnd);
 
   DWORD bytesWritten = 0;
   BOOL success = WriteFile(mPipe,
                            &mWriteBuffer[mWriteBegin],
                            mWriteEnd - mWriteBegin,
                            &bytesWritten,
@@ -617,17 +617,17 @@ NamedPipeInfo::DoWrite()
   mHasPendingWrite = true;
 
   return 0;
 }
 
 int32_t
 NamedPipeInfo::DoWriteContinue()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_ASSERT(mHasPendingWrite);
 
   DWORD bytesWritten = 0;
   BOOL success = GetOverlappedResult(mPipe,
                                      &mWriteOverlapped,
                                      &bytesWritten,
                                      FALSE);
 
@@ -649,17 +649,17 @@ NamedPipeInfo::DoWriteContinue()
   mWriteBegin += bytesWritten;
   LOG_NPIO_DEBUG("[%s][%p] %d bytes written", __func__, this, bytesWritten);
   return bytesWritten;
 }
 
 static inline NamedPipeInfo*
 GetNamedPipeInfo(PRFileDesc* aFd)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   MOZ_DIAGNOSTIC_ASSERT(aFd);
   MOZ_DIAGNOSTIC_ASSERT(aFd->secret);
   MOZ_DIAGNOSTIC_ASSERT(PR_GetLayersIdentity(aFd) == nsNamedPipeLayerIdentity);
 
   if (!aFd ||
       !aFd->secret ||
       PR_GetLayersIdentity(aFd) != nsNamedPipeLayerIdentity) {
     LOG_NPIO_ERROR("cannot get named pipe info");
@@ -669,17 +669,17 @@ GetNamedPipeInfo(PRFileDesc* aFd)
   return reinterpret_cast<NamedPipeInfo*>(aFd->secret);
 }
 
 static PRStatus
 nsNamedPipeConnect(PRFileDesc* aFd,
                    const PRNetAddr* aAddr,
                    PRIntervalTime aTimeout)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return PR_FAILURE;
   }
 
   if (NS_WARN_IF(NS_FAILED(info->Connect(
@@ -688,25 +688,25 @@ nsNamedPipeConnect(PRFileDesc* aFd,
   }
 
   return PR_SUCCESS;
 }
 
 static PRStatus
 nsNamedPipeConnectContinue(PRFileDesc* aFd, PRInt16 aOutFlags)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   return PR_SUCCESS;
 }
 
 static PRStatus
 nsNamedPipeClose(PRFileDesc* aFd)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   if (aFd->secret && PR_GetLayersIdentity(aFd) == nsNamedPipeLayerIdentity) {
     RefPtr<NamedPipeInfo> info = dont_AddRef(GetNamedPipeInfo(aFd));
     info->Disconnect();
     aFd->secret = nullptr;
     aFd->identity = PR_INVALID_IO_LAYER;
   }
 
@@ -718,17 +718,17 @@ nsNamedPipeClose(PRFileDesc* aFd)
 
 static PRInt32
 nsNamedPipeSend(PRFileDesc* aFd,
                 const void* aBuffer,
                 PRInt32 aAmount,
                 PRIntn aFlags,
                 PRIntervalTime aTimeout)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   Unused << aFlags;
   Unused << aTimeout;
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return -1;
@@ -738,17 +738,17 @@ nsNamedPipeSend(PRFileDesc* aFd,
 
 static PRInt32
 nsNamedPipeRecv(PRFileDesc* aFd,
                 void* aBuffer,
                 PRInt32 aAmount,
                 PRIntn aFlags,
                 PRIntervalTime aTimeout)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   Unused << aTimeout;
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return -1;
   }
@@ -762,96 +762,96 @@ nsNamedPipeRecv(PRFileDesc* aFd,
   }
 
   return info->Read(aBuffer, aAmount);
 }
 
 static inline PRInt32
 nsNamedPipeRead(PRFileDesc* aFd, void* aBuffer, PRInt32 aAmount)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return -1;
   }
   return info->Read(aBuffer, aAmount);
 }
 
 static inline PRInt32
 nsNamedPipeWrite(PRFileDesc* aFd, const void* aBuffer, PRInt32 aAmount)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return -1;
   }
   return info->Write(aBuffer, aAmount);
 }
 
 static PRInt32
 nsNamedPipeAvailable(PRFileDesc* aFd)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return -1;
   }
   return static_cast<PRInt32>(info->Available());
 }
 
 static PRInt64
 nsNamedPipeAvailable64(PRFileDesc* aFd)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return -1;
   }
   return static_cast<PRInt64>(info->Available());
 }
 
 static PRStatus
 nsNamedPipeSync(PRFileDesc* aFd)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return PR_FAILURE;
   }
   return info->Sync(0) ? PR_SUCCESS : PR_FAILURE;
 }
 
 static PRInt16
 nsNamedPipePoll(PRFileDesc* aFd, PRInt16 aInFlags, PRInt16* aOutFlags)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   NamedPipeInfo* info = GetNamedPipeInfo(aFd);
   if (!info) {
     PR_SetError(PR_BAD_DESCRIPTOR_ERROR, 0);
     return 0;
   }
   return info->GetPollFlags(aInFlags, aOutFlags);
 }
 
 // FIXME: remove socket option functions?
 static PRStatus
 nsNamedPipeGetSocketOption(PRFileDesc* aFd, PRSocketOptionData* aData)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   MOZ_ASSERT(aFd);
   MOZ_ASSERT(aData);
 
   switch (aData->option) {
     case PR_SockOpt_Nonblocking:
       aData->value.non_blocking = GetNamedPipeInfo(aFd)->IsNonblocking()
                                   ? PR_TRUE
@@ -869,17 +869,17 @@ nsNamedPipeGetSocketOption(PRFileDesc* a
   }
 
   return PR_SUCCESS;
 }
 
 static PRStatus
 nsNamedPipeSetSocketOption(PRFileDesc* aFd, const PRSocketOptionData* aData)
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   MOZ_ASSERT(aFd);
   MOZ_ASSERT(aData);
 
   switch (aData->option) {
     case PR_SockOpt_Nonblocking:
       GetNamedPipeInfo(aFd)->SetNonblocking(aData->value.non_blocking);
       break;
@@ -892,17 +892,17 @@ nsNamedPipeSetSocketOption(PRFileDesc* a
   }
 
   return PR_SUCCESS;
 }
 
 static void
 Initialize()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
 
   static bool initialized = false;
   if (initialized) {
     return;
   }
 
   nsNamedPipeLayerIdentity = PR_GetUniqueIdentity("Named Pipe layer");
   nsNamedPipeLayerMethods = *PR_GetDefaultIOMethods();
@@ -927,17 +927,17 @@ bool
 IsNamedPipePath(const nsACString& aPath)
 {
   return StringBeginsWith(aPath, NS_LITERAL_CSTRING("\\\\.\\pipe\\"));
 }
 
 PRFileDesc*
 CreateNamedPipeLayer()
 {
-  MOZ_ASSERT(PR_GetCurrentThread() == gSocketThread);
+  MOZ_ASSERT(OnSocketThread(), "not on socket thread");
   Initialize();
 
   PRFileDesc* layer = PR_CreateIOLayerStub(nsNamedPipeLayerIdentity,
                                            &nsNamedPipeLayerMethods);
   if (NS_WARN_IF(!layer)) {
     LOG_NPIO_ERROR("CreateNamedPipeLayer() failed.");
     return nullptr;
   }