diff --git a/content/media/nsBuiltinDecoderReader.h b/content/media/nsBuiltinDecoderReader.h index 93fa60ab170..a9673d8abb8 100644 --- a/content/media/nsBuiltinDecoderReader.h +++ b/content/media/nsBuiltinDecoderReader.h @@ -42,7 +42,6 @@ #include #include "Layers.h" #include "ImageLayers.h" -#include "nsAutoLock.h" #include "nsClassHashtable.h" #include "mozilla/TimeStamp.h" #include "nsSize.h" diff --git a/content/media/nsMediaCache.cpp b/content/media/nsMediaCache.cpp index a3aed28f5a8..19c53790df1 100644 --- a/content/media/nsMediaCache.cpp +++ b/content/media/nsMediaCache.cpp @@ -36,10 +36,10 @@ * * ***** END LICENSE BLOCK ***** */ +#include "mozilla/Monitor.h" #include "mozilla/XPCOM.h" #include "nsMediaCache.h" -#include "nsAutoLock.h" #include "nsContentUtils.h" #include "nsDirectoryServiceUtils.h" #include "nsDirectoryServiceDefs.h" @@ -51,6 +51,8 @@ #include "prlog.h" #include "nsIPrivateBrowsingService.h" +using namespace mozilla; + #ifdef PR_LOGGING PRLogModuleInfo* gMediaCacheLog; #define LOG(type, msg) PR_LOG(gMediaCacheLog, type, msg) @@ -77,9 +79,6 @@ static const PRUint32 REPLAY_DELAY = 30; // can. static const PRUint32 FREE_BLOCK_SCAN_LIMIT = 16; -using mozilla::TimeStamp; -using mozilla::TimeDuration; - #ifdef DEBUG // Turn this on to do very expensive cache state validation // #define DEBUG_VERIFY_CACHE @@ -135,7 +134,7 @@ public: }; nsMediaCache() : mNextResourceID(1), - mMonitor(nsAutoMonitor::NewMonitor("media.cache")), + mMonitor("nsMediaCache.mMonitor"), mFD(nsnull), mFDCurrentPos(0), mUpdateQueued(PR_FALSE) #ifdef DEBUG , mInUpdate(PR_FALSE) @@ -150,9 +149,6 @@ public: if (mFD) { PR_Close(mFD); } - if (mMonitor) { - nsAutoMonitor::DestroyMonitor(mMonitor); - } MOZ_COUNT_DTOR(nsMediaCache); } @@ -231,7 +227,7 @@ public: void Verify() {} #endif - PRMonitor* Monitor() { return mMonitor; } + Monitor& GetMonitor() { return mMonitor; } /** * An iterator that makes it easy to iterate through all streams that @@ -354,7 +350,7 @@ protected: // The monitor protects all the data members here. Also, off-main-thread // readers that need to block will Wait() on this monitor. When new // data becomes available in the cache, we NotifyAll() on this monitor. - PRMonitor* mMonitor; + Monitor mMonitor; // The Blocks describing the cache entries. nsTArray mIndex; // The file descriptor of the cache file. The file will be deleted @@ -549,11 +545,6 @@ nsMediaCache::Init() NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); NS_ASSERTION(!mFD, "Cache file already open?"); - if (!mMonitor) { - // the constructor failed - return NS_ERROR_OUT_OF_MEMORY; - } - nsCOMPtr tmp; nsresult rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tmp)); NS_ENSURE_SUCCESS(rv,rv); @@ -617,7 +608,7 @@ nsMediaCache::Flush() void nsMediaCache::FlushInternal() { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); for (PRUint32 blockIndex = 0; blockIndex < mIndex.Length(); ++blockIndex) { FreeBlock(blockIndex); @@ -672,7 +663,7 @@ nsresult nsMediaCache::ReadCacheFile(PRInt64 aOffset, void* aData, PRInt32 aLength, PRInt32* aBytes) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); if (!mFD) return NS_ERROR_FAILURE; @@ -694,7 +685,7 @@ nsMediaCache::ReadCacheFile(PRInt64 aOffset, void* aData, PRInt32 aLength, nsresult nsMediaCache::ReadCacheFileAllBytes(PRInt64 aOffset, void* aData, PRInt32 aLength) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); PRInt64 offset = aOffset; PRInt32 count = aLength; @@ -717,7 +708,7 @@ nsMediaCache::ReadCacheFileAllBytes(PRInt64 aOffset, void* aData, PRInt32 aLengt nsresult nsMediaCache::WriteCacheFile(PRInt64 aOffset, const void* aData, PRInt32 aLength) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); if (!mFD) return NS_ERROR_FAILURE; @@ -758,7 +749,7 @@ PRInt32 nsMediaCache::FindBlockForIncomingData(TimeStamp aNow, nsMediaCacheStream* aStream) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); PRInt32 blockIndex = FindReusableBlock(aNow, aStream, aStream->mChannelOffset/BLOCK_SIZE, PR_INT32_MAX); @@ -801,7 +792,7 @@ nsMediaCache::AppendMostReusableBlock(BlockList* aBlockList, nsTArray* aResult, PRInt32 aBlockIndexLimit) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); PRInt32 blockIndex = aBlockList->GetLastBlock(); if (blockIndex < 0) @@ -825,7 +816,7 @@ nsMediaCache::FindReusableBlock(TimeStamp aNow, PRInt32 aForStreamBlock, PRInt32 aMaxSearchBlockIndex) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); PRUint32 length = PR_MIN(PRUint32(aMaxSearchBlockIndex), mIndex.Length()); @@ -919,7 +910,7 @@ nsMediaCache::GetBlockOwner(PRInt32 aBlockIndex, nsMediaCacheStream* aStream) void nsMediaCache::SwapBlocks(PRInt32 aBlockIndex1, PRInt32 aBlockIndex2) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); Block* block1 = &mIndex[aBlockIndex1]; Block* block2 = &mIndex[aBlockIndex2]; @@ -999,7 +990,7 @@ nsMediaCache::AddBlockOwnerAsReadahead(PRInt32 aBlockIndex, void nsMediaCache::FreeBlock(PRInt32 aBlock) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); Block* block = &mIndex[aBlock]; if (block->mOwners.IsEmpty()) { @@ -1022,7 +1013,7 @@ nsMediaCache::FreeBlock(PRInt32 aBlock) TimeDuration nsMediaCache::PredictNextUse(TimeStamp aNow, PRInt32 aBlock) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); NS_ASSERTION(!IsBlockFree(aBlock), "aBlock is free"); Block* block = &mIndex[aBlock]; @@ -1072,7 +1063,7 @@ nsMediaCache::PredictNextUse(TimeStamp aNow, PRInt32 aBlock) TimeDuration nsMediaCache::PredictNextUseForIncomingData(nsMediaCacheStream* aStream) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); PRInt64 bytesAhead = aStream->mChannelOffset - aStream->mStreamOffset; if (bytesAhead <= -BLOCK_SIZE) { @@ -1100,7 +1091,7 @@ nsMediaCache::Update() nsAutoTArray actions; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mUpdateQueued = PR_FALSE; #ifdef DEBUG mInUpdate = PR_TRUE; @@ -1382,8 +1373,8 @@ nsMediaCache::Update() // Close the streams that failed due to error. This will cause all // client Read and Seek operations on those streams to fail. Blocked // Reads will also be woken up. - nsAutoMonitor mon(mMonitor); - stream->CloseInternal(&mon); + MonitorAutoEnter mon(mMonitor); + stream->CloseInternal(mon); } } } @@ -1403,7 +1394,7 @@ public: void nsMediaCache::QueueUpdate() { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); // Queuing an update while we're in an update raises a high risk of // triggering endless events @@ -1420,7 +1411,7 @@ nsMediaCache::QueueUpdate() void nsMediaCache::Verify() { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); mFreeBlocks.Verify(); for (PRUint32 i = 0; i < mStreams.Length(); ++i) { @@ -1452,7 +1443,7 @@ void nsMediaCache::InsertReadaheadBlock(BlockOwner* aBlockOwner, PRInt32 aBlockIndex) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); // Find the last block whose stream block is before aBlockIndex's // stream block, and insert after it @@ -1478,7 +1469,7 @@ void nsMediaCache::AllocateAndWriteBlock(nsMediaCacheStream* aStream, const void* aData, nsMediaCacheStream::ReadMode aMode) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); PRInt32 streamBlockIndex = aStream->mChannelOffset/BLOCK_SIZE; @@ -1556,7 +1547,7 @@ nsMediaCache::OpenStream(nsMediaCacheStream* aStream) { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); LOG(PR_LOG_DEBUG, ("Stream %p opened", aStream)); mStreams.AppendElement(aStream); aStream->mResourceID = mNextResourceID++; @@ -1570,7 +1561,7 @@ nsMediaCache::ReleaseStream(nsMediaCacheStream* aStream) { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); LOG(PR_LOG_DEBUG, ("Stream %p closed", aStream)); mStreams.RemoveElement(aStream); } @@ -1578,7 +1569,7 @@ nsMediaCache::ReleaseStream(nsMediaCacheStream* aStream) void nsMediaCache::ReleaseStreamBlocks(nsMediaCacheStream* aStream) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); // XXX scanning the entire stream doesn't seem great, if not much of it // is cached, but the only easy alternative is to scan the entire cache @@ -1618,7 +1609,7 @@ nsMediaCache::NoteBlockUsage(nsMediaCacheStream* aStream, PRInt32 aBlockIndex, nsMediaCacheStream::ReadMode aMode, TimeStamp aNow) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); if (aBlockIndex < 0) { // this block is not in the cache yet @@ -1650,7 +1641,7 @@ nsMediaCache::NoteBlockUsage(nsMediaCacheStream* aStream, PRInt32 aBlockIndex, void nsMediaCache::NoteSeek(nsMediaCacheStream* aStream, PRInt64 aOldOffset) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); if (aOldOffset < aStream->mStreamOffset) { // We seeked forward. Convert blocks from readahead to played. @@ -1706,7 +1697,7 @@ nsMediaCacheStream::NotifyDataLength(PRInt64 aLength) { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); mStreamLength = aLength; } @@ -1715,7 +1706,7 @@ nsMediaCacheStream::NotifyDataStarted(PRInt64 aOffset) { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); NS_WARN_IF_FALSE(aOffset == mChannelOffset, "Server is giving us unexpected offset"); mChannelOffset = aOffset; @@ -1766,7 +1757,7 @@ nsMediaCacheStream::NotifyDataReceived(PRInt64 aSize, const char* aData, { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); PRInt64 size = aSize; const char* data = aData; @@ -1835,7 +1826,7 @@ nsMediaCacheStream::NotifyDataEnded(nsresult aStatus) { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); PRInt32 blockOffset = PRInt32(mChannelOffset%BLOCK_SIZE); if (blockOffset > 0) { @@ -1873,7 +1864,7 @@ nsMediaCacheStream::~nsMediaCacheStream() void nsMediaCacheStream::SetSeekable(PRBool aIsSeekable) { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); NS_ASSERTION(mIsSeekable || aIsSeekable || mChannelOffset == 0, "channel offset must be zero when we become non-seekable"); mIsSeekable = aIsSeekable; @@ -1885,7 +1876,7 @@ nsMediaCacheStream::SetSeekable(PRBool aIsSeekable) PRBool nsMediaCacheStream::IsSeekable() { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); return mIsSeekable; } @@ -1894,8 +1885,8 @@ nsMediaCacheStream::Close() { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - nsAutoMonitor mon(gMediaCache->Monitor()); - CloseInternal(&mon); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); + CloseInternal(mon); // Queue an Update since we may have created more free space. Don't do // it from CloseInternal since that gets called by Update() itself // sometimes, and we try to not to queue updates from Update(). @@ -1903,7 +1894,7 @@ nsMediaCacheStream::Close() } void -nsMediaCacheStream::CloseInternal(nsAutoMonitor* aMonitor) +nsMediaCacheStream::CloseInternal(MonitorAutoEnter& aMonitor) { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); @@ -1912,13 +1903,13 @@ nsMediaCacheStream::CloseInternal(nsAutoMonitor* aMonitor) mClosed = PR_TRUE; gMediaCache->ReleaseStreamBlocks(this); // Wake up any blocked readers - aMonitor->NotifyAll(); + aMonitor.NotifyAll(); } void nsMediaCacheStream::Pin() { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); ++mPinCount; // Queue an Update since we may no longer want to read more into the // cache, if this stream's block have become non-evictable @@ -1928,7 +1919,7 @@ nsMediaCacheStream::Pin() void nsMediaCacheStream::Unpin() { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); NS_ASSERTION(mPinCount > 0, "Unbalanced Unpin"); --mPinCount; // Queue an Update since we may be able to read more into the @@ -1939,28 +1930,28 @@ nsMediaCacheStream::Unpin() PRInt64 nsMediaCacheStream::GetLength() { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); return mStreamLength; } PRInt64 nsMediaCacheStream::GetNextCachedData(PRInt64 aOffset) { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); return GetNextCachedDataInternal(aOffset); } PRInt64 nsMediaCacheStream::GetCachedDataEnd(PRInt64 aOffset) { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); return GetCachedDataEndInternal(aOffset); } PRBool nsMediaCacheStream::IsDataCachedToEndOfStream(PRInt64 aOffset) { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); if (mStreamLength < 0) return PR_FALSE; return GetCachedDataEndInternal(aOffset) >= mStreamLength; @@ -1969,7 +1960,7 @@ nsMediaCacheStream::IsDataCachedToEndOfStream(PRInt64 aOffset) PRInt64 nsMediaCacheStream::GetCachedDataEndInternal(PRInt64 aOffset) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(gMediaCache->Monitor()); + gMediaCache->GetMonitor().AssertCurrentThreadIn(); PRUint32 startBlockIndex = aOffset/BLOCK_SIZE; PRUint32 blockIndex = startBlockIndex; while (blockIndex < mBlocks.Length() && mBlocks[blockIndex] != -1) { @@ -1992,7 +1983,7 @@ nsMediaCacheStream::GetCachedDataEndInternal(PRInt64 aOffset) PRInt64 nsMediaCacheStream::GetNextCachedDataInternal(PRInt64 aOffset) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(gMediaCache->Monitor()); + gMediaCache->GetMonitor().AssertCurrentThreadIn(); if (aOffset == mStreamLength) return -1; @@ -2039,7 +2030,7 @@ nsMediaCacheStream::GetNextCachedDataInternal(PRInt64 aOffset) void nsMediaCacheStream::SetReadMode(ReadMode aMode) { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); if (aMode == mCurrentMode) return; mCurrentMode = aMode; @@ -2050,7 +2041,7 @@ void nsMediaCacheStream::SetPlaybackRate(PRUint32 aBytesPerSecond) { NS_ASSERTION(aBytesPerSecond > 0, "Zero playback rate not allowed"); - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); if (aBytesPerSecond == mPlaybackBytesPerSecond) return; mPlaybackBytesPerSecond = aBytesPerSecond; @@ -2062,7 +2053,7 @@ nsMediaCacheStream::Seek(PRInt32 aWhence, PRInt64 aOffset) { NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread"); - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); if (mClosed) return NS_ERROR_FAILURE; @@ -2096,7 +2087,7 @@ nsMediaCacheStream::Tell() { NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread"); - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); return mStreamOffset; } @@ -2105,7 +2096,7 @@ nsMediaCacheStream::Read(char* aBuffer, PRUint32 aCount, PRUint32* aBytes) { NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread"); - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); if (mClosed) return NS_ERROR_FAILURE; @@ -2190,7 +2181,7 @@ nsMediaCacheStream::ReadFromCache(char* aBuffer, PRInt64 aOffset, PRInt64 aCount) { - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); if (mClosed) return NS_ERROR_FAILURE; @@ -2268,7 +2259,7 @@ nsMediaCacheStream::InitAsClone(nsMediaCacheStream* aOriginal) mResourceID = aOriginal->mResourceID; // Grab cache blocks from aOriginal as readahead blocks for our stream - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); mPrincipal = aOriginal->mPrincipal; mStreamLength = aOriginal->mStreamLength; @@ -2298,7 +2289,7 @@ nsresult nsMediaCacheStream::GetCachedRanges(nsTArray& aRanges) { // Take the monitor, so that the cached data ranges can't grow while we're // trying to loop over them. - nsAutoMonitor mon(gMediaCache->Monitor()); + MonitorAutoEnter mon(gMediaCache->GetMonitor()); // We must be pinned while running this, otherwise the cached data ranges may // shrink while we're trying to loop over them. diff --git a/content/media/nsMediaCache.h b/content/media/nsMediaCache.h index 00b0426a82b..35ea9ce5d7d 100644 --- a/content/media/nsMediaCache.h +++ b/content/media/nsMediaCache.h @@ -40,11 +40,13 @@ #define nsMediaCache_h_ #include "nsTArray.h" -#include "nsAutoLock.h" #include "nsIPrincipal.h" #include "nsCOMPtr.h" class nsByteRange; +namespace mozilla { +class MonitorAutoEnter; +} /** * Media applications want fast, "on demand" random access to media data, @@ -209,6 +211,8 @@ class nsMediaChannelStream; * This class can be directly embedded as a value. */ class nsMediaCacheStream { + typedef mozilla::MonitorAutoEnter MonitorAutoEnter; + public: enum { // This needs to be a power of two @@ -429,7 +433,7 @@ private: // aMonitor is the nsAutoMonitor wrapper holding the cache monitor. // This is used to NotifyAll to wake up threads that might be // blocked on reading from this stream. - void CloseInternal(nsAutoMonitor* aMonitor); + void CloseInternal(MonitorAutoEnter& aMonitor); // Update mPrincipal given that data has been received from aPrincipal void UpdatePrincipal(nsIPrincipal* aPrincipal); diff --git a/content/media/nsMediaDecoder.cpp b/content/media/nsMediaDecoder.cpp index 71928d8a520..38234daeb86 100644 --- a/content/media/nsMediaDecoder.cpp +++ b/content/media/nsMediaDecoder.cpp @@ -47,7 +47,6 @@ #include "nsIDOMHTMLMediaElement.h" #include "nsNetUtil.h" #include "nsHTMLMediaElement.h" -#include "nsAutoLock.h" #include "nsIRenderingContext.h" #include "gfxContext.h" #include "nsPresContext.h" @@ -57,6 +56,8 @@ #include "nsSVGEffects.h" #endif +using namespace mozilla; + // Number of milliseconds between progress events as defined by spec #define PROGRESS_MS 350 @@ -75,7 +76,7 @@ nsMediaDecoder::nsMediaDecoder() : mElement(0), mRGBWidth(-1), mRGBHeight(-1), - mVideoUpdateLock(nsnull), + mVideoUpdateLock("nsMediaDecoder.mVideoUpdateLock"), mPixelAspectRatio(1.0), mFrameBufferLength(0), mPinnedForSeek(PR_FALSE), @@ -88,19 +89,13 @@ nsMediaDecoder::nsMediaDecoder() : nsMediaDecoder::~nsMediaDecoder() { - if (mVideoUpdateLock) { - nsAutoLock::DestroyLock(mVideoUpdateLock); - mVideoUpdateLock = nsnull; - } MOZ_COUNT_DTOR(nsMediaDecoder); } PRBool nsMediaDecoder::Init(nsHTMLMediaElement* aElement) { mElement = aElement; - mVideoUpdateLock = nsAutoLock::NewLock("nsMediaDecoder::mVideoUpdateLock"); - - return mVideoUpdateLock != nsnull; + return PR_TRUE; } void nsMediaDecoder::Shutdown() @@ -142,7 +137,7 @@ void nsMediaDecoder::Invalidate() PRBool invalidateFrame = PR_FALSE; { - nsAutoLock lock(mVideoUpdateLock); + MutexAutoLock lock(mVideoUpdateLock); // Get mImageContainerSizeChanged while holding the lock. invalidateFrame = mImageContainerSizeChanged; @@ -258,7 +253,7 @@ void nsMediaDecoder::SetVideoData(const gfxIntSize& aSize, Image* aImage, TimeStamp aTarget) { - nsAutoLock lock(mVideoUpdateLock); + MutexAutoLock lock(mVideoUpdateLock); if (mRGBWidth != aSize.width || mRGBHeight != aSize.height || mPixelAspectRatio != aPixelAspectRatio) { @@ -287,7 +282,7 @@ void nsMediaDecoder::SetVideoData(const gfxIntSize& aSize, double nsMediaDecoder::GetFrameDelay() { - nsAutoLock lock(mVideoUpdateLock); + MutexAutoLock lock(mVideoUpdateLock); return mPaintDelay.ToSeconds(); } diff --git a/content/media/nsMediaDecoder.h b/content/media/nsMediaDecoder.h index d654957523c..6e2d7cefdb9 100644 --- a/content/media/nsMediaDecoder.h +++ b/content/media/nsMediaDecoder.h @@ -48,6 +48,7 @@ #include "nsITimer.h" #include "ImageLayers.h" #include "mozilla/Monitor.h" +#include "mozilla/Mutex.h" class nsHTMLMediaElement; class nsMediaStream; @@ -89,6 +90,7 @@ public: typedef mozilla::layers::ImageContainer ImageContainer; typedef mozilla::layers::Image Image; typedef mozilla::Monitor Monitor; + typedef mozilla::Mutex Mutex; nsMediaDecoder(); virtual ~nsMediaDecoder(); @@ -441,7 +443,7 @@ protected: // to the RGB buffer must obtain this lock first to ensure that // the video element does not use video data or sizes that are // in the midst of being changed. - PRLock* mVideoUpdateLock; + Mutex mVideoUpdateLock; // Pixel aspect ratio (ratio of the pixel width to pixel height) float mPixelAspectRatio; diff --git a/content/media/nsMediaStream.cpp b/content/media/nsMediaStream.cpp index e78c2b96854..e31eb620159 100644 --- a/content/media/nsMediaStream.cpp +++ b/content/media/nsMediaStream.cpp @@ -35,11 +35,11 @@ * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ +#include "mozilla/Mutex.h" #include "nsDebug.h" #include "nsMediaStream.h" #include "nsMediaDecoder.h" #include "nsNetUtil.h" -#include "nsAutoLock.h" #include "nsThreadUtils.h" #include "nsIFile.h" #include "nsIFileChannel.h" @@ -61,7 +61,7 @@ #define HTTP_OK_CODE 200 #define HTTP_PARTIAL_RESPONSE_CODE 206 -using mozilla::TimeStamp; +using namespace mozilla; nsMediaChannelStream::nsMediaChannelStream(nsMediaDecoder* aDecoder, nsIChannel* aChannel, nsIURI* aURI) @@ -69,7 +69,7 @@ nsMediaChannelStream::nsMediaChannelStream(nsMediaDecoder* aDecoder, mOffset(0), mSuspendCount(0), mReopenOnError(PR_FALSE), mIgnoreClose(PR_FALSE), mCacheStream(this), - mLock(nsAutoLock::NewLock("media.channel.stream")), + mLock("nsMediaChannelStream.mLock"), mCacheSuspendCount(0) { } @@ -80,9 +80,6 @@ nsMediaChannelStream::~nsMediaChannelStream() // Kill its reference to us since we're going away mListener->Revoke(); } - if (mLock) { - nsAutoLock::DestroyLock(mLock); - } } // nsMediaChannelStream::Listener just observes the channel and @@ -271,7 +268,7 @@ nsMediaChannelStream::OnStartRequest(nsIRequest* aRequest) } { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mChannelStatistics.Start(TimeStamp::Now()); } @@ -297,7 +294,7 @@ nsMediaChannelStream::OnStopRequest(nsIRequest* aRequest, nsresult aStatus) "How can OnStopRequest fire while we're suspended?"); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mChannelStatistics.Stop(TimeStamp::Now()); } @@ -383,7 +380,7 @@ nsMediaChannelStream::OnDataAvailable(nsIRequest* aRequest, NS_ASSERTION(mChannel.get() == aRequest, "Wrong channel!"); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mChannelStatistics.AddBytes(aCount); } @@ -412,8 +409,6 @@ nsresult nsMediaChannelStream::Open(nsIStreamListener **aStreamListener) { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; nsresult rv = mCacheStream.Init(); if (NS_FAILED(rv)) return rv; @@ -549,7 +544,7 @@ void nsMediaChannelStream::CloseChannel() NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mChannelStatistics.Stop(TimeStamp::Now()); } @@ -628,7 +623,7 @@ void nsMediaChannelStream::Suspend(PRBool aCloseImmediately) element->DownloadSuspended(); } else if (mSuspendCount == 0) { { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mChannelStatistics.Stop(TimeStamp::Now()); } mChannel->Suspend(); @@ -656,7 +651,7 @@ void nsMediaChannelStream::Resume() if (mChannel) { // Just wake up our existing channel { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mChannelStatistics.Start(TimeStamp::Now()); } // if an error occurs after Resume, assume it's because the server @@ -762,7 +757,7 @@ nsMediaChannelStream::CacheClientSeek(PRInt64 aOffset, PRBool aResume) // No need to mess with the channel, since we're making a new one --mSuspendCount; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(mCacheSuspendCount > 0, "CacheClientSeek(aResume=true) without previous CacheClientSuspend!"); --mCacheSuspendCount; } @@ -780,7 +775,7 @@ nsresult nsMediaChannelStream::CacheClientSuspend() { { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); ++mCacheSuspendCount; } Suspend(PR_FALSE); @@ -794,7 +789,7 @@ nsMediaChannelStream::CacheClientResume() { Resume(); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(mCacheSuspendCount > 0, "CacheClientResume without previous CacheClientSuspend!"); --mCacheSuspendCount; } @@ -824,14 +819,14 @@ nsMediaChannelStream::IsDataCachedToEndOfStream(PRInt64 aOffset) PRBool nsMediaChannelStream::IsSuspendedByCache() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return mCacheSuspendCount > 0; } PRBool nsMediaChannelStream::IsSuspended() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return mSuspendCount > 0; } @@ -862,7 +857,7 @@ nsMediaChannelStream::Unpin() double nsMediaChannelStream::GetDownloadRate(PRPackedBool* aIsReliable) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return mChannelStatistics.GetRate(TimeStamp::Now(), aIsReliable); } @@ -877,14 +872,11 @@ class nsMediaFileStream : public nsMediaStream public: nsMediaFileStream(nsMediaDecoder* aDecoder, nsIChannel* aChannel, nsIURI* aURI) : nsMediaStream(aDecoder, aChannel, aURI), mSize(-1), - mLock(nsAutoLock::NewLock("media.file.stream")) + mLock("nsMediaFileStream.mLock") { } ~nsMediaFileStream() { - if (mLock) { - nsAutoLock::DestroyLock(mLock); - } } // Main thread @@ -935,7 +927,7 @@ private: // Read or Seek is in progress since it resets various internal // values to null. // This lock protects mSeekable and mInput. - PRLock* mLock; + Mutex mLock; // Seekable stream interface to file. This can be used from any // thread. @@ -1041,7 +1033,7 @@ nsresult nsMediaFileStream::Close() { NS_ASSERTION(NS_IsMainThread(), "Only call on main thread"); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mChannel) { mChannel->Cancel(NS_ERROR_PARSED_DATA_CACHED); mChannel = nsnull; @@ -1087,7 +1079,7 @@ nsMediaStream* nsMediaFileStream::CloneData(nsMediaDecoder* aDecoder) nsresult nsMediaFileStream::ReadFromCache(char* aBuffer, PRInt64 aOffset, PRUint32 aCount) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mInput || !mSeekable) return NS_ERROR_FAILURE; PRInt64 offset = 0; @@ -1116,7 +1108,7 @@ nsresult nsMediaFileStream::ReadFromCache(char* aBuffer, PRInt64 aOffset, PRUint nsresult nsMediaFileStream::Read(char* aBuffer, PRUint32 aCount, PRUint32* aBytes) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mInput) return NS_ERROR_FAILURE; return mInput->Read(aBuffer, aCount, aBytes); @@ -1126,7 +1118,7 @@ nsresult nsMediaFileStream::Seek(PRInt32 aWhence, PRInt64 aOffset) { NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread"); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mSeekable) return NS_ERROR_FAILURE; return mSeekable->Seek(aWhence, aOffset); @@ -1136,7 +1128,7 @@ PRInt64 nsMediaFileStream::Tell() { NS_ASSERTION(!NS_IsMainThread(), "Don't call on main thread"); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mSeekable) return 0; diff --git a/content/media/nsMediaStream.h b/content/media/nsMediaStream.h index 3ef36b516de..4c4632cfc48 100644 --- a/content/media/nsMediaStream.h +++ b/content/media/nsMediaStream.h @@ -38,6 +38,7 @@ #if !defined(nsMediaStream_h_) #define nsMediaStream_h_ +#include "mozilla/Mutex.h" #include "mozilla/XPCOM.h" #include "nsIChannel.h" #include "nsIPrincipal.h" @@ -45,7 +46,6 @@ #include "nsIStreamListener.h" #include "nsIChannelEventSink.h" #include "nsIInterfaceRequestor.h" -#include "prlock.h" #include "nsMediaCache.h" // For HTTP seeking, if number of bytes needing to be @@ -344,6 +344,8 @@ protected: */ class nsMediaChannelStream : public nsMediaStream { + typedef mozilla::Mutex Mutex; + public: nsMediaChannelStream(nsMediaDecoder* aDecoder, nsIChannel* aChannel, nsIURI* aURI); ~nsMediaChannelStream(); @@ -468,7 +470,7 @@ protected: nsMediaCacheStream mCacheStream; // This lock protects mChannelStatistics and mCacheSuspendCount - PRLock* mLock; + Mutex mLock; nsChannelStatistics mChannelStatistics; PRUint32 mCacheSuspendCount; }; diff --git a/dom/src/threads/nsDOMThreadService.cpp b/dom/src/threads/nsDOMThreadService.cpp index 19f8004a205..950c19edd64 100644 --- a/dom/src/threads/nsDOMThreadService.cpp +++ b/dom/src/threads/nsDOMThreadService.cpp @@ -59,7 +59,6 @@ #include "nsPIDOMWindow.h" // Other includes -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsContentUtils.h" #include "nsDeque.h" @@ -82,6 +81,8 @@ #include "nsDOMWorkerSecurityManager.h" #include "nsDOMWorkerTimeout.h" +using namespace mozilla; + #ifdef PR_LOGGING PRLogModuleInfo *gDOMThreadsLog = nsnull; #endif @@ -372,7 +373,7 @@ public: PRBool aClearQueue) { NS_ASSERTION(aRunnable, "Null pointer!"); - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(gDOMThreadService->mMonitor); + gDOMThreadService->mMonitor.AssertCurrentThreadIn(); if (NS_LIKELY(!aTimeoutInterval)) { NS_ADDREF(aRunnable); @@ -465,7 +466,7 @@ public: JS_SetContextPrivate(cx, NULL); } - nsAutoMonitor mon(gDOMThreadService->mMonitor); + MonitorAutoEnter mon(gDOMThreadService->mMonitor); killWorkerWhenDone = mKillWorkerWhenDone; gDOMThreadService->WorkerComplete(this); mon.NotifyAll(); @@ -495,7 +496,7 @@ protected: while (1) { nsCOMPtr runnable; { - nsAutoMonitor mon(gDOMThreadService->mMonitor); + MonitorAutoEnter mon(gDOMThreadService->mMonitor); runnable = dont_AddRef((nsIRunnable*)mRunnables.PopFront()); @@ -572,7 +573,7 @@ DOMWorkerOperationCallback(JSContext* aCx) JS_FlushCaches(aCx); for (;;) { - nsAutoMonitor mon(worker->Pool()->Monitor()); + MonitorAutoEnter mon(worker->Pool()->GetMonitor()); // There's a small chance that the worker was canceled after our check // above in which case we shouldn't wait here. We're guaranteed not to @@ -728,7 +729,7 @@ DOMWorkerErrorReporter(JSContext* aCx, */ nsDOMThreadService::nsDOMThreadService() -: mMonitor(nsnull), +: mMonitor("nsDOMThreadServer.mMonitor"), mNavigatorStringsLoaded(PR_FALSE) { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); @@ -747,10 +748,6 @@ nsDOMThreadService::~nsDOMThreadService() NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); Cleanup(); - - if (mMonitor) { - nsAutoMonitor::DestroyMonitor(mMonitor); - } } NS_IMPL_THREADSAFE_ISUPPORTS3(nsDOMThreadService, nsIEventTarget, @@ -787,9 +784,6 @@ nsDOMThreadService::Init() rv = mThreadPool->SetIdleThreadLimit(THREADPOOL_IDLE_THREADS); NS_ENSURE_SUCCESS(rv, rv); - mMonitor = nsAutoMonitor::NewMonitor("nsDOMThreadService::mMonitor"); - NS_ENSURE_TRUE(mMonitor, NS_ERROR_OUT_OF_MEMORY); - PRBool success = mWorkersInProgress.Init(); NS_ENSURE_TRUE(success, NS_ERROR_OUT_OF_MEMORY); @@ -890,7 +884,7 @@ nsDOMThreadService::Cleanup() CancelWorkersForGlobal(nsnull); { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); NS_ASSERTION(!mPools.Count(), "Live workers left!"); mPools.Clear(); @@ -955,7 +949,7 @@ nsDOMThreadService::Dispatch(nsDOMWorker* aWorker, nsRefPtr workerRunnable; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); if (mWorkersInProgress.Get(aWorker, getter_AddRefs(workerRunnable))) { workerRunnable->PutRunnable(aRunnable, aTimeoutInterval, aClearQueue); @@ -978,7 +972,7 @@ nsDOMThreadService::Dispatch(nsDOMWorker* aWorker, if (NS_FAILED(rv)) { NS_WARNING("Failed to dispatch runnable to thread pool!"); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); // We exited the monitor after inserting the runnable into the table so make // sure we're removing the right one! @@ -1006,7 +1000,7 @@ nsDOMThreadService::SetWorkerTimeout(nsDOMWorker* aWorker, NS_ASSERTION(mThreadPool, "Dispatch called after 'xpcom-shutdown'!"); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); nsRefPtr workerRunnable; if (mWorkersInProgress.Get(aWorker, getter_AddRefs(workerRunnable))) { @@ -1017,7 +1011,7 @@ nsDOMThreadService::SetWorkerTimeout(nsDOMWorker* aWorker, void nsDOMThreadService::WorkerComplete(nsDOMWorkerRunnable* aRunnable) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); #ifdef DEBUG nsRefPtr& debugWorker = aRunnable->mWorker; @@ -1034,7 +1028,7 @@ nsDOMThreadService::WorkerComplete(nsDOMWorkerRunnable* aRunnable) PRBool nsDOMThreadService::QueueSuspendedWorker(nsDOMWorkerRunnable* aRunnable) { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); #ifdef DEBUG { @@ -1091,7 +1085,7 @@ already_AddRefed nsDOMThreadService::GetPoolForGlobal(nsIScriptGlobalObject* aGlobalObject, PRBool aRemove) { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); nsRefPtr pool; mPools.Get(aGlobalObject, getter_AddRefs(pool)); @@ -1106,7 +1100,7 @@ nsDOMThreadService::GetPoolForGlobal(nsIScriptGlobalObject* aGlobalObject, void nsDOMThreadService::TriggerOperationCallbackForPool(nsDOMWorkerPool* aPool) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); // See if we need to trigger the operation callback on any currently running // contexts. @@ -1123,7 +1117,7 @@ nsDOMThreadService::TriggerOperationCallbackForPool(nsDOMWorkerPool* aPool) void nsDOMThreadService::RescheduleSuspendedWorkerForPool(nsDOMWorkerPool* aPool) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); PRUint32 count = mSuspendedWorkers.Length(); if (!count) { @@ -1167,7 +1161,7 @@ nsDOMThreadService::CancelWorkersForGlobal(nsIScriptGlobalObject* aGlobalObject) if (pool) { pool->Cancel(); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); TriggerOperationCallbackForPool(pool); RescheduleSuspendedWorkerForPool(pool); @@ -1183,7 +1177,7 @@ nsDOMThreadService::SuspendWorkersForGlobal(nsIScriptGlobalObject* aGlobalObject if (pool) { pool->Suspend(); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); TriggerOperationCallbackForPool(pool); } } @@ -1197,7 +1191,7 @@ nsDOMThreadService::ResumeWorkersForGlobal(nsIScriptGlobalObject* aGlobalObject) if (pool) { pool->Resume(); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); TriggerOperationCallbackForPool(pool); RescheduleSuspendedWorkerForPool(pool); @@ -1209,7 +1203,7 @@ nsDOMThreadService::NoteEmptyPool(nsDOMWorkerPool* aPool) { NS_ASSERTION(aPool, "Null pointer!"); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mPools.Remove(aPool->ScriptGlobalObject()); } @@ -1228,7 +1222,7 @@ nsDOMThreadService::ChangeThreadPoolMaxThreads(PRInt16 aDelta) { NS_ENSURE_ARG(aDelta == 1 || aDelta == -1); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); PRUint32 currentThreadCount; nsresult rv = mThreadPool->GetThreadLimit(¤tThreadCount); @@ -1266,7 +1260,7 @@ nsDOMThreadService::NoteThreadsafeContractId(const nsACString& aContractId, { NS_ASSERTION(!aContractId.IsEmpty(), "Empty contract id!"); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); #ifdef DEBUG { @@ -1287,7 +1281,7 @@ nsDOMThreadService::GetContractIdThreadsafeStatus(const nsACString& aContractId) { NS_ASSERTION(!aContractId.IsEmpty(), "Empty contract id!"); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); PRBool isThreadsafe; if (mThreadsafeContractIDs.Get(aContractId, &isThreadsafe)) { @@ -1398,7 +1392,7 @@ nsDOMThreadService::OnThreadCreated() return NS_ERROR_FAILURE; } - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); #ifdef DEBUG JSContext** newContext = @@ -1427,7 +1421,7 @@ nsDOMThreadService::OnThreadShuttingDown() NS_WARN_IF_FALSE(cx, "Thread died with no context?"); if (cx) { { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mJSContexts.RemoveElement(cx); } @@ -1473,7 +1467,7 @@ nsDOMThreadService::RegisterWorker(nsDOMWorker* aWorker, nsRefPtr pool; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); if (!mThreadPool) { // Shutting down! @@ -1522,7 +1516,7 @@ nsDOMThreadService::RegisterWorker(nsDOMWorker* aWorker, rv = pool->Init(); NS_ENSURE_SUCCESS(rv, rv); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); PRBool success = mPools.Put(aGlobalObject, pool); NS_ENSURE_TRUE(success, NS_ERROR_OUT_OF_MEMORY); diff --git a/dom/src/threads/nsDOMThreadService.h b/dom/src/threads/nsDOMThreadService.h index d4dadd1643e..85ade5595a4 100644 --- a/dom/src/threads/nsDOMThreadService.h +++ b/dom/src/threads/nsDOMThreadService.h @@ -47,13 +47,13 @@ // Other includes #include "jsapi.h" +#include "mozilla/Monitor.h" #include "nsAutoPtr.h" #include "nsCOMPtr.h" #include "nsDataHashtable.h" #include "nsRefPtrHashtable.h" #include "nsStringGlue.h" #include "nsTPtrArray.h" -#include "prmon.h" #include "prlog.h" #ifdef PR_LOGGING @@ -185,7 +185,7 @@ private: // mMonitor protects all access to mWorkersInProgress and // mCreationsInProgress. - PRMonitor* mMonitor; + mozilla::Monitor mMonitor; // A map from nsDOMWorkerThread to nsDOMWorkerRunnable. nsRefPtrHashtable mWorkersInProgress; diff --git a/dom/src/threads/nsDOMWorker.cpp b/dom/src/threads/nsDOMWorker.cpp index d2ebee23802..357e3d8de76 100644 --- a/dom/src/threads/nsDOMWorker.cpp +++ b/dom/src/threads/nsDOMWorker.cpp @@ -48,7 +48,6 @@ #include "jsdbgapi.h" #endif #include "nsAtomicRefcnt.h" -#include "nsAutoLock.h" #include "nsAXPCNativeCallContext.h" #include "nsContentUtils.h" #include "nsDOMClassInfo.h" @@ -70,6 +69,8 @@ #include "nsDOMWorkerTimeout.h" #include "nsDOMWorkerXHR.h" +using namespace mozilla; + class TestComponentThreadsafetyRunnable : public nsIRunnable { public: @@ -1351,7 +1352,7 @@ nsDOMWorker::nsDOMWorker(nsDOMWorker* aParent, : mParent(aParent), mParentWN(aParentWN), mPrivilegeModel(aPrivilegeModel), - mLock(nsnull), + mLock("nsDOMWorker.mLock"), mInnerScope(nsnull), mGlobal(NULL), mNextTimeoutId(0), @@ -1375,10 +1376,6 @@ nsDOMWorker::~nsDOMWorker() mPool->NoteDyingWorker(this); } - if (mLock) { - nsAutoLock::DestroyLock(mLock); - } - NS_ASSERTION(!mFeatures.Length(), "Live features!"); NS_ASSERTION(!mQueuedRunnables.Length(), "Events that never ran!"); @@ -1500,7 +1497,7 @@ nsDOMWorker::PostCreate(nsIXPConnectWrappedNative* aWrapper, JSContext* /* aCx */, JSObject* /* aObj */) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mWrappedNative = aWrapper; return NS_OK; } @@ -1514,7 +1511,7 @@ nsDOMWorker::Trace(nsIXPConnectWrappedNative* /* aWrapper */, PRBool canceled = PR_FALSE; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); canceled = mStatus == eKilled; } @@ -1537,7 +1534,7 @@ nsDOMWorker::Finalize(nsIXPConnectWrappedNative* /* aWrapper */, // Clear our wrapped native now that it has died. { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mWrappedNative = nsnull; } @@ -1672,9 +1669,6 @@ nsDOMWorker::InitializeInternal(nsIScriptGlobalObject* aOwner, NS_ASSERTION(mPrincipal, "Should have set the principal!"); } - mLock = nsAutoLock::NewLock("nsDOMWorker::mLock"); - NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY); - NS_ASSERTION(!mGlobal, "Already got a global?!"); nsCOMPtr thisWrapped; @@ -1733,7 +1727,7 @@ nsDOMWorker::Cancel() PRBool enforceTimeout = PR_FALSE; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(mStatus != eCanceled, "Canceled more than once?!"); @@ -1795,7 +1789,7 @@ nsDOMWorker::Kill() PRUint32 count, index; nsAutoTArray, 20> features; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mStatus == eKilled) { NS_ASSERTION(mFeatures.Length() == 0, "Features added after killed!"); @@ -1844,7 +1838,7 @@ nsDOMWorker::Suspend() PRBool shouldSuspendFeatures; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(!mSuspended, "Suspended more than once!"); shouldSuspendFeatures = !mSuspended; mSuspended = PR_TRUE; @@ -1862,7 +1856,7 @@ nsDOMWorker::Resume() PRBool shouldResumeFeatures; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); #ifdef DEBUG // Should only have a mismatch if GC or Cancel happened while suspended. if (!mSuspended) { @@ -1890,7 +1884,7 @@ nsDOMWorker::Resume() PRBool nsDOMWorker::IsCanceled() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return IsCanceledNoLock(); } @@ -1924,14 +1918,14 @@ nsDOMWorker::IsCanceledNoLock() PRBool nsDOMWorker::IsClosing() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return mStatus != eRunning; } PRBool nsDOMWorker::IsSuspended() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return mSuspended; } @@ -2203,7 +2197,7 @@ nsDOMWorker::GetWrappedNative() { nsCOMPtr wrappedNative; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); wrappedNative = mWrappedNative; } return wrappedNative.forget(); @@ -2220,7 +2214,7 @@ nsDOMWorker::AddFeature(nsDOMWorkerFeature* aFeature, // aCx may be null. JSAutoSuspendRequest asr(aCx); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mStatus == eKilled) { // No features may be added after we've been canceled. Sorry. @@ -2253,7 +2247,7 @@ nsDOMWorker::RemoveFeature(nsDOMWorkerFeature* aFeature, // aCx may be null. JSAutoSuspendRequest asr(aCx); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); #ifdef DEBUG PRBool removed = @@ -2270,7 +2264,7 @@ nsDOMWorker::CancelTimeoutWithId(PRUint32 aId) { nsRefPtr foundFeature; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); PRUint32 count = mFeatures.Length(); for (PRUint32 index = 0; index < count; index++) { nsDOMWorkerFeature*& feature = mFeatures[index]; @@ -2293,7 +2287,7 @@ nsDOMWorker::SuspendFeatures() { nsAutoTArray, 20> features; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // We don't really have to worry about overflow here because the only way // to do this is through recursive script loading, which uses the stack. We @@ -2322,7 +2316,7 @@ nsDOMWorker::ResumeFeatures() { nsAutoTArray, 20> features; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(mFeatureSuspendDepth > 0, "Shouldn't happen!"); if (--mFeatureSuspendDepth != 0) { @@ -2383,7 +2377,7 @@ nsDOMWorker::FireCloseRunnable(PRIntervalTime aTimeoutInterval, // to do is unblock the waiting thread. PRBool wakeUp; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(mExpirationTime == 0, "Close runnable should not be scheduled already!"); @@ -2396,7 +2390,7 @@ nsDOMWorker::FireCloseRunnable(PRIntervalTime aTimeoutInterval, } if (wakeUp) { - nsAutoMonitor mon(mPool->Monitor()); + MonitorAutoEnter mon(mPool->GetMonitor()); mon.NotifyAll(); } @@ -2430,7 +2424,7 @@ nsresult nsDOMWorker::Close() { { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(mStatus != eKilled, "This should be impossible!"); if (mStatus != eRunning) { return NS_OK; @@ -2448,7 +2442,7 @@ nsresult nsDOMWorker::TerminateInternal(PRBool aFromFinalize) { { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); #ifdef DEBUG if (!aFromFinalize) { NS_ASSERTION(mStatus != eCanceled, "Shouldn't be able to get here!"); @@ -2495,7 +2489,7 @@ void nsDOMWorker::SetExpirationTime(PRIntervalTime aExpirationTime) { { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(mStatus != eRunning && mStatus != eKilled, "Bad status!"); NS_ASSERTION(!mExpirationTime || mExpirationTime == PR_INTERVAL_NO_TIMEOUT, @@ -2509,7 +2503,7 @@ nsDOMWorker::SetExpirationTime(PRIntervalTime aExpirationTime) PRIntervalTime nsDOMWorker::GetExpirationTime() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return mExpirationTime; } #endif @@ -2594,7 +2588,7 @@ nsDOMWorker::DispatchEvent(nsIDOMEvent* aEvent, PRBool* _retval) { { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (IsCanceledNoLock()) { return NS_OK; } @@ -2635,7 +2629,7 @@ NS_IMETHODIMP nsDOMWorker::PostMessage(/* JSObject aMessage */) { { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // There's no reason to dispatch this message after the close handler has // been triggered since it will never be allowed to run. if (mStatus != eRunning) { diff --git a/dom/src/threads/nsDOMWorker.h b/dom/src/threads/nsDOMWorker.h index a22c34a22fc..e9f08e5fb77 100644 --- a/dom/src/threads/nsDOMWorker.h +++ b/dom/src/threads/nsDOMWorker.h @@ -48,10 +48,10 @@ #include "nsIXPCScriptable.h" #include "jsapi.h" +#include "mozilla/Mutex.h" #include "nsAutoPtr.h" #include "nsCOMPtr.h" #include "nsTPtrArray.h" -#include "prlock.h" #include "nsDOMWorkerMessageHandler.h" @@ -143,6 +143,8 @@ class nsDOMWorker : public nsDOMWorkerMessageHandler, public nsIJSNativeInitializer, public nsIXPCScriptable { + typedef mozilla::Mutex Mutex; + friend class nsDOMWorkerFeature; friend class nsDOMWorkerFunctions; friend class nsDOMWorkerScope; @@ -214,7 +216,7 @@ public: return mPool; } - PRLock* Lock() { + Mutex& GetLock() { return mLock; } @@ -352,7 +354,7 @@ private: // worker is created. WorkerPrivilegeModel mPrivilegeModel; - PRLock* mLock; + Mutex mLock; nsRefPtr mPool; diff --git a/dom/src/threads/nsDOMWorkerPool.cpp b/dom/src/threads/nsDOMWorkerPool.cpp index 775589e2683..8e1230d9481 100644 --- a/dom/src/threads/nsDOMWorkerPool.cpp +++ b/dom/src/threads/nsDOMWorkerPool.cpp @@ -50,7 +50,6 @@ #include "nsPIDOMWindow.h" // Other includes -#include "nsAutoLock.h" #include "nsContentUtils.h" #include "nsDOMJSUtils.h" #include "nsProxyRelease.h" @@ -60,13 +59,15 @@ #include "nsDOMThreadService.h" #include "nsDOMWorker.h" +using namespace mozilla; + #define LOG(_args) PR_LOG(gDOMThreadsLog, PR_LOG_DEBUG, _args) nsDOMWorkerPool::nsDOMWorkerPool(nsIScriptGlobalObject* aGlobalObject, nsIDocument* aDocument) : mParentGlobal(aGlobalObject), mParentDocument(aDocument), - mMonitor(nsnull), + mMonitor("nsDOMWorkerPool.mMonitor"), mCanceled(PR_FALSE), mSuspended(PR_FALSE), mWindowID(aDocument ? aDocument->OuterWindowID() : 0) @@ -89,10 +90,6 @@ nsDOMWorkerPool::~nsDOMWorkerPool() if (document) { NS_ProxyRelease(mainThread, document, PR_FALSE); } - - if (mMonitor) { - nsAutoMonitor::DestroyMonitor(mMonitor); - } } NS_IMPL_THREADSAFE_ADDREF(nsDOMWorkerPool) @@ -102,10 +99,6 @@ nsresult nsDOMWorkerPool::Init() { NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); - - mMonitor = nsAutoMonitor::NewMonitor("nsDOMWorkerPool::mMonitor"); - NS_ENSURE_TRUE(mMonitor, NS_ERROR_OUT_OF_MEMORY); - return NS_OK; } @@ -117,7 +110,7 @@ nsDOMWorkerPool::NoteWorker(nsDOMWorker* aWorker) PRBool suspendWorker; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); if (mCanceled) { return NS_ERROR_ABORT; @@ -144,7 +137,7 @@ nsDOMWorkerPool::NoteDyingWorker(nsDOMWorker* aWorker) PRBool removeFromThreadService = PR_FALSE; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); NS_ASSERTION(mWorkers.Contains(aWorker), "Worker from a different pool?!"); mWorkers.RemoveElement(aWorker); @@ -163,7 +156,7 @@ nsDOMWorkerPool::NoteDyingWorker(nsDOMWorker* aWorker) void nsDOMWorkerPool::GetWorkers(nsTArray& aArray) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMonitor); + mMonitor.AssertCurrentThreadIn(); NS_ASSERTION(!aArray.Length(), "Should be empty!"); #ifdef DEBUG @@ -181,7 +174,7 @@ nsDOMWorkerPool::Cancel() nsAutoTArray workers; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mCanceled = PR_TRUE; @@ -193,7 +186,7 @@ nsDOMWorkerPool::Cancel() for (PRUint32 index = 0; index < count; index++) { workers[index]->Cancel(); } - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mon.NotifyAll(); } } @@ -205,7 +198,7 @@ nsDOMWorkerPool::Suspend() nsAutoTArray workers; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); NS_ASSERTION(!mSuspended, "Suspended more than once!"); mSuspended = PR_TRUE; @@ -226,7 +219,7 @@ nsDOMWorkerPool::Resume() nsAutoTArray workers; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); NS_ASSERTION(mSuspended, "Not suspended!"); mSuspended = PR_FALSE; @@ -239,7 +232,7 @@ nsDOMWorkerPool::Resume() for (PRUint32 index = 0; index < count; index++) { workers[index]->Resume(); } - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mon.NotifyAll(); } } diff --git a/dom/src/threads/nsDOMWorkerPool.h b/dom/src/threads/nsDOMWorkerPool.h index e97d7700326..a12396140dd 100644 --- a/dom/src/threads/nsDOMWorkerPool.h +++ b/dom/src/threads/nsDOMWorkerPool.h @@ -42,10 +42,10 @@ // Other includes #include "jsapi.h" +#include "mozilla/Monitor.h" #include "nsCOMPtr.h" #include "nsStringGlue.h" #include "nsTArray.h" -#include "prmon.h" class nsDOMWorker; class nsIDocument; @@ -55,6 +55,8 @@ class nsIScriptGlobalObject; class nsDOMWorkerPool { + typedef mozilla::Monitor Monitor; + public: nsDOMWorkerPool(nsIScriptGlobalObject* aGlobalObject, nsIDocument* aDocument); @@ -79,7 +81,7 @@ public: nsresult NoteWorker(nsDOMWorker* aWorker); void NoteDyingWorker(nsDOMWorker* aWorker); - PRMonitor* Monitor() { + Monitor& GetMonitor() { return mMonitor; } @@ -105,7 +107,7 @@ private: nsTArray mWorkers; // Monitor for suspending and resuming workers. - PRMonitor* mMonitor; + Monitor mMonitor; PRPackedBool mCanceled; PRPackedBool mSuspended; diff --git a/dom/src/threads/nsDOMWorkerScriptLoader.cpp b/dom/src/threads/nsDOMWorkerScriptLoader.cpp index 61f5ea8b55d..e1353ea6f96 100644 --- a/dom/src/threads/nsDOMWorkerScriptLoader.cpp +++ b/dom/src/threads/nsDOMWorkerScriptLoader.cpp @@ -49,7 +49,6 @@ #include "nsIStreamLoader.h" // Other includes -#include "nsAutoLock.h" #include "nsContentErrors.h" #include "nsContentPolicyUtils.h" #include "nsContentUtils.h" @@ -70,6 +69,8 @@ #include "nsDOMThreadService.h" #include "nsDOMWorkerTimeout.h" +using namespace mozilla; + #define LOG(_args) PR_LOG(gDOMThreadsLog, PR_LOG_DEBUG, _args) nsDOMWorkerScriptLoader::nsDOMWorkerScriptLoader(nsDOMWorker* aWorker) @@ -303,7 +304,7 @@ nsDOMWorkerScriptLoader::Cancel() nsAutoTArray runnables; { - nsAutoLock lock(mWorker->Lock()); + MutexAutoLock lock(mWorker->GetLock()); runnables.AppendElements(mPendingRunnables); mPendingRunnables.Clear(); } @@ -753,7 +754,7 @@ ScriptLoaderRunnable::ScriptLoaderRunnable(nsDOMWorkerScriptLoader* aLoader) : mRevoked(PR_FALSE), mLoader(aLoader) { - nsAutoLock lock(aLoader->Lock()); + MutexAutoLock lock(aLoader->GetLock()); #ifdef DEBUG nsDOMWorkerScriptLoader::ScriptLoaderRunnable** added = #endif @@ -765,7 +766,7 @@ nsDOMWorkerScriptLoader:: ScriptLoaderRunnable::~ScriptLoaderRunnable() { if (!mRevoked) { - nsAutoLock lock(mLoader->Lock()); + MutexAutoLock lock(mLoader->GetLock()); #ifdef DEBUG PRBool removed = #endif diff --git a/dom/src/threads/nsDOMWorkerScriptLoader.h b/dom/src/threads/nsDOMWorkerScriptLoader.h index e5e36df16f2..4332958d537 100644 --- a/dom/src/threads/nsDOMWorkerScriptLoader.h +++ b/dom/src/threads/nsDOMWorkerScriptLoader.h @@ -54,7 +54,6 @@ #include "nsCOMPtr.h" #include "nsStringGlue.h" #include "nsTArray.h" -#include "prlock.h" #include "nsDOMWorker.h" @@ -91,6 +90,8 @@ class nsDOMWorkerScriptLoader : public nsDOMWorkerFeature, public nsIRunnable, public nsIStreamLoaderObserver { + typedef mozilla::Mutex Mutex; + friend class AutoSuspendWorkerEvents; friend class ScriptLoaderRunnable; @@ -132,8 +133,8 @@ private: void SuspendWorkerEvents(); void ResumeWorkerEvents(); - PRLock* Lock() { - return mWorker->Lock(); + Mutex& GetLock() { + return mWorker->GetLock(); } class ScriptLoaderRunnable : public nsIRunnable diff --git a/dom/src/threads/nsDOMWorkerXHR.cpp b/dom/src/threads/nsDOMWorkerXHR.cpp index dbbe2052af8..dd02f50187b 100644 --- a/dom/src/threads/nsDOMWorkerXHR.cpp +++ b/dom/src/threads/nsDOMWorkerXHR.cpp @@ -45,7 +45,6 @@ #include "nsIXPConnect.h" // Other includes -#include "nsAutoLock.h" #include "nsAXPCNativeCallContext.h" #include "nsComponentManagerUtils.h" #include "nsContentUtils.h" @@ -59,6 +58,8 @@ #include "nsDOMWorkerPool.h" #include "nsDOMWorkerXHRProxy.h" +using namespace mozilla; + // The list of event types that we support. This list and the defines based on // it determine the sizes of the listener arrays in nsDOMWorkerXHRProxy. Make // sure that any event types shared by both the XHR and Upload objects are @@ -493,7 +494,7 @@ nsDOMWorkerXHR::Cancel() { // This lock is here to prevent a race between Cancel and GetUpload, not to // protect mCanceled. - nsAutoLock lock(mWorker->Lock()); + MutexAutoLock lock(mWorker->GetLock()); mCanceled = PR_TRUE; mUpload = nsnull; @@ -829,7 +830,7 @@ nsDOMWorkerXHR::GetUpload(nsIXMLHttpRequestUpload** aUpload) return NS_ERROR_ABORT; } - nsAutoLock lock(worker->Lock()); + MutexAutoLock lock(worker->GetLock()); if (mCanceled) { return NS_ERROR_ABORT; diff --git a/dom/src/threads/nsDOMWorkerXHR.h b/dom/src/threads/nsDOMWorkerXHR.h index 60193bae389..a3d0a748f38 100644 --- a/dom/src/threads/nsDOMWorkerXHR.h +++ b/dom/src/threads/nsDOMWorkerXHR.h @@ -48,7 +48,6 @@ #include "nsAutoPtr.h" #include "nsCOMPtr.h" #include "nsTArray.h" -#include "prlock.h" // DOMWorker includes #include "nsDOMWorker.h" @@ -92,6 +91,8 @@ class nsDOMWorkerXHR : public nsDOMWorkerFeature, public nsIXMLHttpRequest, public nsIXPCScriptable { + typedef mozilla::Mutex Mutex; + friend class nsDOMWorkerXHREvent; friend class nsDOMWorkerXHRLastProgressOrLoadEvent; friend class nsDOMWorkerXHRProxy; @@ -116,8 +117,8 @@ public: private: virtual ~nsDOMWorkerXHR(); - PRLock* Lock() { - return mWorker->Lock(); + Mutex& GetLock() { + return mWorker->GetLock(); } already_AddRefed GetWrappedNative() { diff --git a/dom/src/threads/nsDOMWorkerXHRProxy.cpp b/dom/src/threads/nsDOMWorkerXHRProxy.cpp index b9379a252db..caef07b0c2e 100644 --- a/dom/src/threads/nsDOMWorkerXHRProxy.cpp +++ b/dom/src/threads/nsDOMWorkerXHRProxy.cpp @@ -49,7 +49,6 @@ #include "nsIXMLHttpRequest.h" // Other includes -#include "nsAutoLock.h" #include "nsComponentManagerUtils.h" #include "nsIClassInfoImpl.h" #include "nsThreadUtils.h" @@ -66,6 +65,8 @@ #include "nsDOMWorkerXHR.h" #include "nsDOMWorkerXHRProxiedFunctions.h" +using namespace mozilla; + #define MAX_XHR_LISTENER_TYPE nsDOMWorkerXHREventTarget::sMaxXHREventTypes #define MAX_UPLOAD_LISTENER_TYPE nsDOMWorkerXHREventTarget::sMaxUploadEventTypes @@ -181,7 +182,7 @@ public: nsRefPtr lastProgressOrLoadEvent; if (!mProxy->mCanceled) { - nsAutoLock lock(mProxy->mWorkerXHR->Lock()); + MutexAutoLock lock(mProxy->mWorkerXHR->GetLock()); mProxy->mLastProgressOrLoadEvent.swap(lastProgressOrLoadEvent); if (mProxy->mCanceled) { return NS_ERROR_ABORT; @@ -375,7 +376,7 @@ nsDOMWorkerXHRProxy::Destroy() NS_ASSERTION(NS_IsMainThread(), "Wrong thread!"); { - nsAutoLock lock(mWorkerXHR->Lock()); + MutexAutoLock lock(mWorkerXHR->GetLock()); mCanceled = PR_TRUE; @@ -465,7 +466,7 @@ nsDOMWorkerXHRProxy::DestroyInternal() // necko has fired its OnStartRequest notification. Guard against that here. nsRefPtr syncFinishedRunnable; { - nsAutoLock lock(mWorkerXHR->Lock()); + MutexAutoLock lock(mWorkerXHR->GetLock()); mSyncFinishedRunnable.swap(syncFinishedRunnable); } @@ -580,7 +581,7 @@ nsDOMWorkerXHRProxy::HandleWorkerEvent(nsDOMWorkerXHREvent* aEvent, NS_ASSERTION(aEvent, "Should not be null!"); { - nsAutoLock lock(mWorkerXHR->Lock()); + MutexAutoLock lock(mWorkerXHR->GetLock()); if (mCanceled || (aEvent->mChannelID != -1 && aEvent->mChannelID != mChannelID)) { @@ -605,7 +606,7 @@ nsDOMWorkerXHRProxy::HandleWorkerEvent(nsDOMWorkerXHREvent* aEvent, progressInfo = nsnull; // Dummy memory barrier. - nsAutoLock lock(mWorkerXHR->Lock()); + MutexAutoLock lock(mWorkerXHR->GetLock()); } nsIDOMEventTarget* target = aUploadEvent ? @@ -769,7 +770,7 @@ nsDOMWorkerXHRProxy::HandleEvent(nsIDOMEvent* aEvent) NS_ASSERTION(!syncFinishedRunnable, "This shouldn't be set!"); - nsAutoLock lock(mWorkerXHR->Lock()); + MutexAutoLock lock(mWorkerXHR->GetLock()); mSyncFinishedRunnable.swap(syncFinishedRunnable); } else { @@ -811,7 +812,7 @@ nsDOMWorkerXHRProxy::HandleEvent(nsIDOMEvent* aEvent) NS_ENSURE_TRUE(runnable, NS_ERROR_OUT_OF_MEMORY); { - nsAutoLock lock(mWorkerXHR->Lock()); + MutexAutoLock lock(mWorkerXHR->GetLock()); if (mCanceled) { return NS_ERROR_ABORT; @@ -957,7 +958,7 @@ nsDOMWorkerXHRProxy::Send(nsIVariant* aBody) mSyncXHRThread = NS_GetCurrentThread(); NS_ENSURE_TRUE(mSyncXHRThread, NS_ERROR_FAILURE); - nsAutoLock lock(mWorkerXHR->Lock()); + MutexAutoLock lock(mWorkerXHR->GetLock()); if (mCanceled) { return NS_ERROR_ABORT; @@ -982,7 +983,7 @@ nsDOMWorkerXHRProxy::SendAsBinary(const nsAString& aBody) mSyncXHRThread = NS_GetCurrentThread(); NS_ENSURE_TRUE(mSyncXHRThread, NS_ERROR_FAILURE); - nsAutoLock lock(mWorkerXHR->Lock()); + MutexAutoLock lock(mWorkerXHR->GetLock()); if (mCanceled) { return NS_ERROR_ABORT; diff --git a/editor/txmgr/tests/TestTXMgr.cpp b/editor/txmgr/tests/TestTXMgr.cpp index 7d7afba11ca..e6b150258f9 100644 --- a/editor/txmgr/tests/TestTXMgr.cpp +++ b/editor/txmgr/tests/TestTXMgr.cpp @@ -4623,10 +4623,17 @@ simple_stress_test() SimpleTransactionFactory factory; + PRInt32 iterations = +#ifdef DEBUG + 10 +#else // // 1500 iterations sends 1,125,750 transactions through the system!! // - return stress_test(&factory, 1500); + 1500 +#endif + ; + return stress_test(&factory, iterations); } nsresult @@ -4652,10 +4659,17 @@ aggregation_stress_test() AggregateTransactionFactory factory(3, 4); + PRInt32 iterations = +#ifdef DEBUG + 10 +#else // // 500 iterations sends 2,630,250 transactions through the system!! // - return stress_test(&factory, 500); + 500 +#endif + ; + return stress_test(&factory, iterations); } nsresult @@ -4681,10 +4695,17 @@ aggregation_batch_stress_test() AggregateTransactionFactory factory(3, 4, BATCH_FLAG); + PRInt32 iterations = +#ifdef DEBUG + 10 +#else // // 500 iterations sends 2,630,250 transactions through the system!! // - return stress_test(&factory, 500); + iterations = 500 +#endif + ; + return stress_test(&factory, iterations); } int diff --git a/embedding/components/windowwatcher/src/nsWindowWatcher.cpp b/embedding/components/windowwatcher/src/nsWindowWatcher.cpp index 2ae7af28305..f8831ecc1ad 100644 --- a/embedding/components/windowwatcher/src/nsWindowWatcher.cpp +++ b/embedding/components/windowwatcher/src/nsWindowWatcher.cpp @@ -42,7 +42,6 @@ #include "nsWindowWatcher.h" #include "nsAutoWindowStateHelper.h" -#include "nsAutoLock.h" #include "nsCRT.h" #include "nsNetUtil.h" #include "nsWWJSUtils.h" @@ -101,6 +100,8 @@ #include "nsIWeakReference.h" #endif +using namespace mozilla; + static const char *sJSStackContractID="@mozilla.org/js/xpc/ContextStack;1"; /**************************************************************** @@ -338,7 +339,7 @@ NS_IMPL_QUERY_INTERFACE3(nsWindowWatcher, nsWindowWatcher::nsWindowWatcher() : mEnumeratorList(), mOldestWindow(0), - mListLock(0) + mListLock("nsWindowWatcher.mListLock") { } @@ -347,17 +348,11 @@ nsWindowWatcher::~nsWindowWatcher() // delete data while (mOldestWindow) RemoveWindow(mOldestWindow); - - if (mListLock) - nsAutoLock::DestroyLock(mListLock); } nsresult nsWindowWatcher::Init() { - mListLock = nsAutoLock::NewLock("nsWindowWatcher::mListLock"); - if (!mListLock) - return NS_ERROR_OUT_OF_MEMORY; return NS_OK; } @@ -1073,7 +1068,7 @@ nsWindowWatcher::GetWindowEnumerator(nsISimpleEnumerator** _retval) if (!_retval) return NS_ERROR_INVALID_ARG; - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsWatcherWindowEnumerator *enumerator = new nsWatcherWindowEnumerator(this); if (enumerator) return CallQueryInterface(enumerator, _retval); @@ -1169,7 +1164,7 @@ nsWindowWatcher::AddWindow(nsIDOMWindow *aWindow, nsIWebBrowserChrome *aChrome) { nsWatcherWindowEntry *info; - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); // if we already have an entry for this window, adjust // its chrome mapping and return @@ -1269,7 +1264,7 @@ nsresult nsWindowWatcher::RemoveWindow(nsWatcherWindowEntry *inInfo) { // notify the enumerators - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); for (ctr = 0; ctr < count; ++ctr) mEnumeratorList[ctr]->WindowRemoved(inInfo); @@ -1305,7 +1300,7 @@ nsWindowWatcher::GetChromeForWindow(nsIDOMWindow *aWindow, nsIWebBrowserChrome * return NS_ERROR_INVALID_ARG; *_retval = 0; - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsWatcherWindowEntry *info = FindWindowEntry(aWindow); if (info) { if (info->mChromeWeak != nsnull) { diff --git a/embedding/components/windowwatcher/src/nsWindowWatcher.h b/embedding/components/windowwatcher/src/nsWindowWatcher.h index 0928ff4f34a..90e6f84d3d8 100644 --- a/embedding/components/windowwatcher/src/nsWindowWatcher.h +++ b/embedding/components/windowwatcher/src/nsWindowWatcher.h @@ -44,6 +44,7 @@ #include "nsCOMPtr.h" #include "jspubtd.h" +#include "mozilla/Mutex.h" #include "nsIWindowCreator.h" // for stupid compilers #include "nsIWindowWatcher.h" #include "nsIPromptFactory.h" @@ -61,7 +62,6 @@ class nsPromptService; struct JSContext; struct JSObject; struct nsWatcherWindowEntry; -struct PRLock; struct SizeSpec; class nsWindowWatcher : @@ -145,7 +145,7 @@ protected: nsTArray mEnumeratorList; nsWatcherWindowEntry *mOldestWindow; - PRLock *mListLock; + mozilla::Mutex mListLock; nsCOMPtr mWindowCreator; }; diff --git a/gfx/src/nsRegion.cpp b/gfx/src/nsRegion.cpp index fe801ada38a..d25533f484d 100644 --- a/gfx/src/nsRegion.cpp +++ b/gfx/src/nsRegion.cpp @@ -34,7 +34,6 @@ * * ***** END LICENSE BLOCK ***** */ -#include "prlock.h" #include "nsRegion.h" #include "nsISupportsImpl.h" #include "nsTArray.h" @@ -109,14 +108,7 @@ class RgnRectMemoryAllocator nsRegion::RgnRect* mFreeListHead; PRUint32 mFreeEntries; void* mChunkListHead; -#if 0 - PRLock* mLock; - - void InitLock () { mLock = PR_NewLock (); } - void DestroyLock () { PR_DestroyLock (mLock); } - void Lock () { PR_Lock (mLock); } - void Unlock () { PR_Unlock (mLock); } -#elif defined (DEBUG) +#if defined (DEBUG) NS_DECL_OWNINGTHREAD void InitLock () { NS_ASSERT_OWNINGTHREAD (RgnRectMemoryAllocator); } diff --git a/intl/strres/src/nsStringBundle.cpp b/intl/strres/src/nsStringBundle.cpp index 9db96373f0b..51ad859566e 100644 --- a/intl/strres/src/nsStringBundle.cpp +++ b/intl/strres/src/nsStringBundle.cpp @@ -59,7 +59,6 @@ #include "pratom.h" #include "prmem.h" #include "nsCOMArray.h" -#include "nsAutoLock.h" #include "nsTextFormatter.h" #include "nsIErrorService.h" #include "nsITimelineService.h" @@ -75,20 +74,20 @@ #include "prenv.h" #include "nsCRT.h" +using namespace mozilla; + static NS_DEFINE_CID(kErrorServiceCID, NS_ERRORSERVICE_CID); static NS_DEFINE_CID(kPersistentPropertiesCID, NS_IPERSISTENTPROPERTIES_CID); nsStringBundle::~nsStringBundle() { - if (mMonitor) - nsAutoMonitor::DestroyMonitor(mMonitor); } nsStringBundle::nsStringBundle(const char* aURLSpec, nsIStringBundleOverride* aOverrideStrings) : mPropertiesURL(aURLSpec), mOverrideStrings(aOverrideStrings), - mMonitor(0), + mMonitor("nsStringBundle.mMonitor"), mAttemptedLoad(PR_FALSE), mLoaded(PR_FALSE) { @@ -112,10 +111,6 @@ nsStringBundle::LoadProperties() nsresult rv; - mMonitor = nsAutoMonitor::NewMonitor("StringBundle monitor"); - if (!mMonitor) - return NS_ERROR_OUT_OF_MEMORY; - // do it synchronously nsCOMPtr uri; rv = NS_NewURI(getter_AddRefs(uri), mPropertiesURL); @@ -153,7 +148,7 @@ nsStringBundle::LoadProperties() nsresult nsStringBundle::GetStringFromID(PRInt32 aID, nsAString& aResult) { - nsAutoMonitor automon(mMonitor); + MonitorAutoEnter automon(mMonitor); nsCAutoString name; name.AppendInt(aID, 10); @@ -274,7 +269,7 @@ nsStringBundle::GetStringFromName(const PRUnichar *aName, PRUnichar **aResult) rv = LoadProperties(); if (NS_FAILED(rv)) return rv; - nsAutoMonitor automon(mMonitor); + MonitorAutoEnter automon(mMonitor); *aResult = nsnull; nsAutoString tmpstr; rv = GetStringFromName(nsDependentString(aName), tmpstr); diff --git a/intl/strres/src/nsStringBundle.h b/intl/strres/src/nsStringBundle.h index e9d4c6efa62..a344043cd07 100644 --- a/intl/strres/src/nsStringBundle.h +++ b/intl/strres/src/nsStringBundle.h @@ -38,13 +38,13 @@ #ifndef nsStringBundle_h__ #define nsStringBundle_h__ +#include "mozilla/Monitor.h" #include "nsIStringBundle.h" #include "nsCOMPtr.h" #include "nsIPersistentProperties2.h" #include "nsString.h" #include "nsCOMArray.h" #include "nsIStringBundleOverride.h" -#include "nsAutoLock.h" class nsStringBundle : public nsIStringBundle { @@ -71,7 +71,7 @@ protected: private: nsCString mPropertiesURL; nsCOMPtr mOverrideStrings; - PRMonitor* mMonitor; + mozilla::Monitor mMonitor; PRPackedBool mAttemptedLoad; PRPackedBool mLoaded; diff --git a/intl/uconv/src/nsUNIXCharset.cpp b/intl/uconv/src/nsUNIXCharset.cpp index ee2664404cf..79edede3c2d 100644 --- a/intl/uconv/src/nsUNIXCharset.cpp +++ b/intl/uconv/src/nsUNIXCharset.cpp @@ -59,7 +59,6 @@ #include #endif #include "nsPlatformCharset.h" -#include "nsAutoLock.h" #include "prinit.h" #include "nsUnicharUtils.h" diff --git a/js/src/xpconnect/src/xpcjsruntime.cpp b/js/src/xpconnect/src/xpcjsruntime.cpp index e1b0f4b21a5..c8b2a19eef6 100644 --- a/js/src/xpconnect/src/xpcjsruntime.cpp +++ b/js/src/xpconnect/src/xpcjsruntime.cpp @@ -49,6 +49,8 @@ #include "mozilla/FunctionTimer.h" #include "prsystem.h" +using namespace mozilla; + /***************************************************************************/ const char* XPCJSRuntime::mStrings[] = { @@ -339,10 +341,10 @@ void XPCJSRuntime::TraceJS(JSTracer* trc, void* data) // bad locking problems with the thread iteration otherwise. if(!self->GetXPConnect()->IsShuttingDown()) { - PRLock* threadLock = XPCPerThreadData::GetLock(); + Mutex* threadLock = XPCPerThreadData::GetLock(); if(threadLock) { // scoped lock - nsAutoLock lock(threadLock); + MutexAutoLock lock(*threadLock); XPCPerThreadData* iterp = nsnull; XPCPerThreadData* thread; @@ -757,10 +759,10 @@ JSBool XPCJSRuntime::GCCallback(JSContext *cx, JSGCStatus status) // bad locking problems with the thread iteration otherwise. if(!self->GetXPConnect()->IsShuttingDown()) { - PRLock* threadLock = XPCPerThreadData::GetLock(); + Mutex* threadLock = XPCPerThreadData::GetLock(); if(threadLock) { // scoped lock - nsAutoLock lock(threadLock); + MutexAutoLock lock(*threadLock); XPCPerThreadData* iterp = nsnull; XPCPerThreadData* thread; @@ -851,13 +853,13 @@ JSBool XPCJSRuntime::GCCallback(JSContext *cx, JSGCStatus status) // bad locking problems with the thread iteration otherwise. if(!self->GetXPConnect()->IsShuttingDown()) { - PRLock* threadLock = XPCPerThreadData::GetLock(); + Mutex* threadLock = XPCPerThreadData::GetLock(); if(threadLock) { // Do the marking... { // scoped lock - nsAutoLock lock(threadLock); + MutexAutoLock lock(*threadLock); XPCPerThreadData* iterp = nsnull; XPCPerThreadData* thread; diff --git a/js/src/xpconnect/src/xpcprivate.h b/js/src/xpconnect/src/xpcprivate.h index eaeeeb4889a..68a47966db2 100644 --- a/js/src/xpconnect/src/xpcprivate.h +++ b/js/src/xpconnect/src/xpcprivate.h @@ -81,7 +81,6 @@ #include "nsIJSRuntimeService.h" #include "nsWeakReference.h" #include "nsCOMPtr.h" -#include "nsAutoLock.h" #include "nsXPTCUtils.h" #include "xptinfo.h" #include "xpcforwards.h" @@ -98,6 +97,8 @@ #include "nsXPIDLString.h" #include "nsAutoJSValHolder.h" #include "mozilla/AutoRestore.h" +#include "mozilla/Monitor.h" +#include "mozilla/Mutex.h" #include "nsDataHashtable.h" #include "nsThreadUtils.h" @@ -350,26 +351,18 @@ typedef nsDataHashtable XPCCompart #pragma warning(disable : 4355) // OK to pass "this" in member initializer #endif -typedef PRMonitor XPCLock; +typedef mozilla::Monitor XPCLock; static inline void xpc_Wait(XPCLock* lock) { NS_ASSERTION(lock, "xpc_Wait called with null lock!"); -#ifdef DEBUG - PRStatus result = -#endif - PR_Wait(lock, PR_INTERVAL_NO_TIMEOUT); - NS_ASSERTION(PR_SUCCESS == result, "bad result from PR_Wait!"); + lock->Wait(); } static inline void xpc_NotifyAll(XPCLock* lock) { NS_ASSERTION(lock, "xpc_NotifyAll called with null lock!"); -#ifdef DEBUG - PRStatus result = -#endif - PR_NotifyAll(lock); - NS_ASSERTION(PR_SUCCESS == result, "bad result from PR_NotifyAll!"); + lock->NotifyAll(); } // This is a cloned subset of nsAutoMonitor. We want the use of a monitor - @@ -382,36 +375,27 @@ static inline void xpc_NotifyAll(XPCLock* lock) // Note that xpconnect only makes *one* monitor and *mostly* holds it locked // only through very small critical sections. -class NS_STACK_CLASS XPCAutoLock : public nsAutoLockBase { +class NS_STACK_CLASS XPCAutoLock { public: static XPCLock* NewLock(const char* name) - {return nsAutoMonitor::NewMonitor(name);} + {return new mozilla::Monitor(name);} static void DestroyLock(XPCLock* lock) - {nsAutoMonitor::DestroyMonitor(lock);} + {delete lock;} XPCAutoLock(XPCLock* lock MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM) -#ifdef DEBUG_jband - : nsAutoLockBase(lock ? (void*) lock : (void*) this, eAutoMonitor), -#else - : nsAutoLockBase(lock, eAutoMonitor), -#endif - mLock(lock) + : mLock(lock) { MOZILLA_GUARD_OBJECT_NOTIFIER_INIT; if(mLock) - PR_EnterMonitor(mLock); + mLock->Enter(); } ~XPCAutoLock() { if(mLock) { -#ifdef DEBUG - PRStatus status = -#endif - PR_ExitMonitor(mLock); - NS_ASSERTION(status == PR_SUCCESS, "PR_ExitMonitor failed"); + mLock->Exit(); } } @@ -437,27 +421,22 @@ private: /************************************************/ -class NS_STACK_CLASS XPCAutoUnlock : public nsAutoUnlockBase { +class NS_STACK_CLASS XPCAutoUnlock { public: XPCAutoUnlock(XPCLock* lock MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM) - : nsAutoUnlockBase(lock), - mLock(lock) + : mLock(lock) { MOZILLA_GUARD_OBJECT_NOTIFIER_INIT; if(mLock) { -#ifdef DEBUG - PRStatus status = -#endif - PR_ExitMonitor(mLock); - NS_ASSERTION(status == PR_SUCCESS, "PR_ExitMonitor failed"); + mLock->Exit(); } } ~XPCAutoUnlock() { if(mLock) - PR_EnterMonitor(mLock); + mLock->Enter(); } private: @@ -3673,6 +3652,8 @@ private: class XPCPerThreadData { + typedef mozilla::Mutex Mutex; + public: // Get the instance of this object for the current thread static inline XPCPerThreadData* GetData(JSContext *cx) @@ -3763,7 +3744,7 @@ public: PRBool IsValid() const {return mJSContextStack != nsnull;} - static PRLock* GetLock() {return gLock;} + static Mutex* GetLock() {return gLock;} // Must be called with the threads locked. static XPCPerThreadData* IterateThreads(XPCPerThreadData** iteratorp); @@ -3809,7 +3790,7 @@ private: #endif PRThread* mThread; - static PRLock* gLock; + static Mutex* gLock; static XPCPerThreadData* gThreads; static PRUintn gTLSIndex; diff --git a/js/src/xpconnect/src/xpcthreadcontext.cpp b/js/src/xpconnect/src/xpcthreadcontext.cpp index ef072ee3f17..9f25eb153b5 100644 --- a/js/src/xpconnect/src/xpcthreadcontext.cpp +++ b/js/src/xpconnect/src/xpcthreadcontext.cpp @@ -43,10 +43,13 @@ #include "xpcprivate.h" #include "XPCWrapper.h" +#include "mozilla/Mutex.h" #include "nsDOMJSUtils.h" #include "nsIScriptGlobalObject.h" #include "nsNullPrincipal.h" +using namespace mozilla; + /***************************************************************************/ XPCJSContextStack::XPCJSContextStack() @@ -341,7 +344,7 @@ XPCJSContextStack::SetSafeJSContext(JSContext * aSafeJSContext) /***************************************************************************/ PRUintn XPCPerThreadData::gTLSIndex = BAD_TLS_INDEX; -PRLock* XPCPerThreadData::gLock = nsnull; +Mutex* XPCPerThreadData::gLock = nsnull; XPCPerThreadData* XPCPerThreadData::gThreads = nsnull; XPCPerThreadData *XPCPerThreadData::sMainThreadData = nsnull; void * XPCPerThreadData::sMainJSThread = nsnull; @@ -363,7 +366,7 @@ XPCPerThreadData::XPCPerThreadData() MOZ_COUNT_CTOR(xpcPerThreadData); if(gLock) { - nsAutoLock lock(gLock); + MutexAutoLock lock(*gLock); mNextThread = gThreads; gThreads = this; } @@ -397,7 +400,7 @@ XPCPerThreadData::~XPCPerThreadData() // Unlink 'this' from the list of threads. if(gLock) { - nsAutoLock lock(gLock); + MutexAutoLock lock(*gLock); if(gThreads == this) gThreads = mNextThread; else @@ -419,7 +422,7 @@ XPCPerThreadData::~XPCPerThreadData() if(gLock && doDestroyLock) { - nsAutoLock::DestroyLock(gLock); + delete gLock; gLock = nsnull; } } @@ -465,14 +468,12 @@ XPCPerThreadData::GetDataImpl(JSContext *cx) if(!gLock) { - gLock = nsAutoLock::NewLock("XPCPerThreadData::gLock"); - if(!gLock) - return nsnull; + gLock = new Mutex("XPCPerThreadData.gLock"); } if(gTLSIndex == BAD_TLS_INDEX) { - nsAutoLock lock(gLock); + MutexAutoLock lock(*gLock); // check again now that we have the lock... if(gTLSIndex == BAD_TLS_INDEX) { @@ -533,7 +534,7 @@ XPCPerThreadData::CleanupAllThreads() if(gLock) { - nsAutoLock lock(gLock); + MutexAutoLock lock(*gLock); for(XPCPerThreadData* cur = gThreads; cur; cur = cur->mNextThread) count++; diff --git a/modules/libjar/nsJAR.cpp b/modules/libjar/nsJAR.cpp index 6abaf1c61f9..a2cc5dce1c2 100644 --- a/modules/libjar/nsJAR.cpp +++ b/modules/libjar/nsJAR.cpp @@ -55,6 +55,8 @@ #include #endif +using namespace mozilla; + //---------------------------------------------- // nsJARManifestItem declaration //---------------------------------------------- @@ -123,8 +125,9 @@ nsJAR::nsJAR(): mZip(new nsZipArchive()), mGlobalStatus(JAR_MANIFEST_NOT_PARSED), mReleaseTime(PR_INTERVAL_NO_TIMEOUT), mCache(nsnull), - mLock(nsnull), - mTotalItemsInManifest(0) + mLock("nsJAR::mLock"), + mTotalItemsInManifest(0), + mOpened(PR_FALSE) { } @@ -168,13 +171,11 @@ NS_IMETHODIMP nsJAR::Open(nsIFile* zipFile) { NS_ENSURE_ARG_POINTER(zipFile); - if (mLock) return NS_ERROR_FAILURE; // Already open! + if (mOpened) return NS_ERROR_FAILURE; // Already open! mZipFile = zipFile; mOuterZipEntry.Truncate(); - - mLock = nsAutoLock::NewLock("nsJAR::mLock"); - NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY); + mOpened = PR_TRUE; #ifdef MOZ_OMNIJAR // The omnijar is special, it is opened early on and closed late @@ -194,7 +195,7 @@ nsJAR::OpenInner(nsIZipReader *aZipReader, const char *aZipEntry) { NS_ENSURE_ARG_POINTER(aZipReader); NS_ENSURE_ARG_POINTER(aZipEntry); - if (mLock) return NS_ERROR_FAILURE; // Already open! + if (mOpened) return NS_ERROR_FAILURE; // Already open! PRBool exist; nsresult rv = aZipReader->HasEntry(nsDependentCString(aZipEntry), &exist); @@ -204,8 +205,7 @@ nsJAR::OpenInner(nsIZipReader *aZipReader, const char *aZipEntry) rv = aZipReader->GetFile(getter_AddRefs(mZipFile)); NS_ENSURE_SUCCESS(rv, rv); - mLock = nsAutoLock::NewLock("nsJAR::mLock"); - NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY); + mOpened = PR_TRUE; mOuterZipEntry.Assign(aZipEntry); @@ -229,11 +229,7 @@ nsJAR::GetFile(nsIFile* *result) NS_IMETHODIMP nsJAR::Close() { - if (mLock) { - nsAutoLock::DestroyLock(mLock); - mLock = nsnull; - } - + mOpened = PR_FALSE; mParsedManifest = PR_FALSE; mManifestData.Reset(); mGlobalStatus = JAR_MANIFEST_NOT_PARSED; @@ -260,7 +256,7 @@ nsJAR::Extract(const char *zipEntry, nsIFile* outFile) { // nsZipArchive and zlib are not thread safe // we need to use a lock to prevent bug #51267 - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsresult rv; nsCOMPtr localFile = do_QueryInterface(outFile, &rv); @@ -1060,7 +1056,7 @@ nsJARItem::GetLastModifiedTime(PRTime* aLastModTime) NS_IMPL_THREADSAFE_ISUPPORTS3(nsZipReaderCache, nsIZipReaderCache, nsIObserver, nsISupportsWeakReference) nsZipReaderCache::nsZipReaderCache() - : mLock(nsnull) + : mLock("nsZipReaderCache.mLock") , mZips(16) #ifdef ZIP_CACHE_HIT_RATE , @@ -1088,8 +1084,7 @@ nsZipReaderCache::Init(PRUint32 cacheSize) } // ignore failure of the observer registration. - mLock = nsAutoLock::NewLock("nsZipReaderCache::mLock"); - return mLock ? NS_OK : NS_ERROR_OUT_OF_MEMORY; + return NS_OK; } static PRBool @@ -1102,8 +1097,6 @@ DropZipReaderCache(nsHashKey *aKey, void *aData, void* closure) nsZipReaderCache::~nsZipReaderCache() { - if (mLock) - nsAutoLock::DestroyLock(mLock); mZips.Enumerate(DropZipReaderCache, nsnull); #ifdef ZIP_CACHE_HIT_RATE @@ -1120,7 +1113,7 @@ nsZipReaderCache::GetZip(nsIFile* zipFile, nsIZipReader* *result) NS_ENSURE_ARG_POINTER(zipFile); nsresult rv; nsCOMPtr antiLockZipGrip; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); #ifdef ZIP_CACHE_HIT_RATE mZipCacheLookups++; @@ -1247,7 +1240,7 @@ nsresult nsZipReaderCache::ReleaseZip(nsJAR* zip) { nsresult rv; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // It is possible that two thread compete for this zip. The dangerous // case is where one thread Releases the zip and discovers that the ref @@ -1336,7 +1329,7 @@ nsZipReaderCache::Observe(nsISupports *aSubject, const PRUnichar *aSomeData) { if (strcmp(aTopic, "memory-pressure") == 0) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); while (PR_TRUE) { nsHashKey* flushable = nsnull; mZips.Enumerate(FindFlushableZip, &flushable); @@ -1369,7 +1362,7 @@ nsZipReaderCache::Observe(nsISupports *aSubject, uri.Insert(NS_LITERAL_CSTRING("file:"), 0); nsCStringKey key(uri); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsJAR* zip = static_cast(static_cast(mZips.Get(&key))); if (!zip) return NS_OK; diff --git a/modules/libjar/nsJAR.h b/modules/libjar/nsJAR.h index 2fe5593b964..a4bd6b8edf2 100644 --- a/modules/libjar/nsJAR.h +++ b/modules/libjar/nsJAR.h @@ -52,13 +52,13 @@ #include "prtypes.h" #include "prinrval.h" +#include "mozilla/Mutex.h" #include "nsIComponentManager.h" #include "nsCOMPtr.h" #include "nsString.h" #include "nsIFile.h" #include "nsStringEnumerator.h" #include "nsHashtable.h" -#include "nsAutoLock.h" #include "nsIZipReader.h" #include "nsZipArchive.h" #include "nsIPrincipal.h" @@ -140,10 +140,11 @@ class nsJAR : public nsIZipReader PRInt16 mGlobalStatus; // Global signature verification status PRIntervalTime mReleaseTime; // used by nsZipReaderCache for flushing entries nsZipReaderCache* mCache; // if cached, this points to the cache it's contained in - PRLock* mLock; + mozilla::Mutex mLock; PRInt64 mMtime; PRInt32 mTotalItemsInManifest; - + PRBool mOpened; + nsresult ParseManifest(); void ReportError(const char* aFilename, PRInt16 errorCode); nsresult LoadEntry(const char* aFilename, char** aBuf, @@ -229,7 +230,7 @@ public: nsresult ReleaseZip(nsJAR* reader); protected: - PRLock* mLock; + mozilla::Mutex mLock; PRInt32 mCacheSize; nsSupportsHashtable mZips; diff --git a/modules/plugin/base/src/nsNPAPIPlugin.cpp b/modules/plugin/base/src/nsNPAPIPlugin.cpp index 33b51aaa806..ea3933a17d6 100644 --- a/modules/plugin/base/src/nsNPAPIPlugin.cpp +++ b/modules/plugin/base/src/nsNPAPIPlugin.cpp @@ -51,7 +51,6 @@ #include "jscntxt.h" -#include "nsAutoLock.h" #include "nsNPAPIPlugin.h" #include "nsNPAPIPluginInstance.h" #include "nsNPAPIPluginStreamListener.h" @@ -108,6 +107,7 @@ #include "nsNetUtil.h" +#include "mozilla/Mutex.h" #include "mozilla/PluginLibrary.h" using mozilla::PluginLibrary; @@ -127,6 +127,7 @@ using mozilla::plugins::PluginModuleParent; #include #endif +using namespace mozilla; using namespace mozilla::plugins::parent; // We should make this const... @@ -190,7 +191,7 @@ static NPNetscapeFuncs sBrowserFuncs = { _urlredirectresponse }; -static PRLock *sPluginThreadAsyncCallLock = nsnull; +static Mutex *sPluginThreadAsyncCallLock = nsnull; static PRCList sPendingAsyncCalls = PR_INIT_STATIC_CLIST(&sPendingAsyncCalls); // POST/GET stream type @@ -229,7 +230,7 @@ static void CheckClassInitialized() return; if (!sPluginThreadAsyncCallLock) - sPluginThreadAsyncCallLock = nsAutoLock::NewLock("sPluginThreadAsyncCallLock"); + sPluginThreadAsyncCallLock = new Mutex("nsNPAPIPlugin.sPluginThreadAsyncCallLock"); initialized = PR_TRUE; @@ -840,7 +841,7 @@ nsPluginThreadRunnable::nsPluginThreadRunnable(NPP instance, PR_INIT_CLIST(this); { - nsAutoLock lock(sPluginThreadAsyncCallLock); + MutexAutoLock lock(*sPluginThreadAsyncCallLock); nsNPAPIPluginInstance *inst = (nsNPAPIPluginInstance *)instance->ndata; if (!inst || !inst->IsRunning()) { @@ -861,7 +862,7 @@ nsPluginThreadRunnable::~nsPluginThreadRunnable() } { - nsAutoLock lock(sPluginThreadAsyncCallLock); + MutexAutoLock lock(*sPluginThreadAsyncCallLock); PR_REMOVE_LINK(this); } @@ -887,7 +888,7 @@ OnPluginDestroy(NPP instance) } { - nsAutoLock lock(sPluginThreadAsyncCallLock); + MutexAutoLock lock(*sPluginThreadAsyncCallLock); if (PR_CLIST_IS_EMPTY(&sPendingAsyncCalls)) { return; @@ -913,28 +914,23 @@ OnShutdown() "Pending async plugin call list not cleaned up!"); if (sPluginThreadAsyncCallLock) { - nsAutoLock::DestroyLock(sPluginThreadAsyncCallLock); + delete sPluginThreadAsyncCallLock; sPluginThreadAsyncCallLock = nsnull; } } -void -EnterAsyncPluginThreadCallLock() +AsyncCallbackAutoLock::AsyncCallbackAutoLock() { - if (sPluginThreadAsyncCallLock) { - PR_Lock(sPluginThreadAsyncCallLock); - } + sPluginThreadAsyncCallLock->Lock(); } -void -ExitAsyncPluginThreadCallLock() +AsyncCallbackAutoLock::~AsyncCallbackAutoLock() { - if (sPluginThreadAsyncCallLock) { - PR_Unlock(sPluginThreadAsyncCallLock); - } + sPluginThreadAsyncCallLock->Unlock(); } + NPP NPPStack::sCurrentNPP = nsnull; const char * diff --git a/modules/plugin/base/src/nsNPAPIPlugin.h b/modules/plugin/base/src/nsNPAPIPlugin.h index 1630544f312..d484f0fe72f 100644 --- a/modules/plugin/base/src/nsNPAPIPlugin.h +++ b/modules/plugin/base/src/nsNPAPIPlugin.h @@ -383,10 +383,15 @@ OnPluginDestroy(NPP instance); void OnShutdown(); -void -EnterAsyncPluginThreadCallLock(); -void -ExitAsyncPluginThreadCallLock(); +/** + * within a lexical scope, locks and unlocks the mutex used to + * serialize modifications to plugin async callback state. + */ +struct NS_STACK_CLASS AsyncCallbackAutoLock +{ + AsyncCallbackAutoLock(); + ~AsyncCallbackAutoLock(); +}; class NPPStack { diff --git a/modules/plugin/base/src/nsNPAPIPluginInstance.cpp b/modules/plugin/base/src/nsNPAPIPluginInstance.cpp index 82b60d70532..5316d6f0d92 100644 --- a/modules/plugin/base/src/nsNPAPIPluginInstance.cpp +++ b/modules/plugin/base/src/nsNPAPIPluginInstance.cpp @@ -189,10 +189,11 @@ NS_IMETHODIMP nsNPAPIPluginInstance::Stop() // Make sure we lock while we're writing to mRunning after we've // started as other threads might be checking that inside a lock. - EnterAsyncPluginThreadCallLock(); - mRunning = DESTROYING; - mStopTime = TimeStamp::Now(); - ExitAsyncPluginThreadCallLock(); + { + AsyncCallbackAutoLock lock; + mRunning = DESTROYING; + mStopTime = TimeStamp::Now(); + } OnPluginDestroy(&mNPP); diff --git a/netwerk/base/src/nsAsyncStreamCopier.cpp b/netwerk/base/src/nsAsyncStreamCopier.cpp index 1bb3129c4c0..30d482b1d9f 100644 --- a/netwerk/base/src/nsAsyncStreamCopier.cpp +++ b/netwerk/base/src/nsAsyncStreamCopier.cpp @@ -41,9 +41,10 @@ #include "nsStreamUtils.h" #include "nsNetSegmentUtils.h" #include "nsNetUtil.h" -#include "nsAutoLock.h" #include "prlog.h" +using namespace mozilla; + #if defined(PR_LOGGING) // // NSPR_LOG_MODULES=nsStreamCopier:5 @@ -55,7 +56,7 @@ static PRLogModuleInfo *gStreamCopierLog = nsnull; //----------------------------------------------------------------------------- nsAsyncStreamCopier::nsAsyncStreamCopier() - : mLock(nsnull) + : mLock("nsAsyncStreamCopier.mLock") , mMode(NS_ASYNCCOPY_VIA_READSEGMENTS) , mChunkSize(nsIOService::gDefaultSegmentSize) , mStatus(NS_OK) @@ -71,14 +72,12 @@ nsAsyncStreamCopier::nsAsyncStreamCopier() nsAsyncStreamCopier::~nsAsyncStreamCopier() { LOG(("Destroying nsAsyncStreamCopier @%x\n", this)); - if (mLock) - nsAutoLock::DestroyLock(mLock); } PRBool nsAsyncStreamCopier::IsComplete(nsresult *status) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (status) *status = mStatus; return !mIsPending; @@ -92,7 +91,7 @@ nsAsyncStreamCopier::Complete(nsresult status) nsCOMPtr observer; nsCOMPtr ctx; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mCopierCtx = nsnull; if (mIsPending) { @@ -157,7 +156,7 @@ nsAsyncStreamCopier::Cancel(nsresult status) { nsCOMPtr copierCtx; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mIsPending) return NS_OK; copierCtx.swap(mCopierCtx); @@ -229,11 +228,6 @@ nsAsyncStreamCopier::Init(nsIInputStream *source, { NS_ASSERTION(sourceBuffered || sinkBuffered, "at least one stream must be buffered"); - NS_ASSERTION(!mLock, "already initialized"); - mLock = nsAutoLock::NewLock("nsAsyncStreamCopier::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - if (chunkSize == 0) chunkSize = nsIOService::gDefaultSegmentSize; mChunkSize = chunkSize; diff --git a/netwerk/base/src/nsAsyncStreamCopier.h b/netwerk/base/src/nsAsyncStreamCopier.h index 0e6e888754a..f245ad769ad 100644 --- a/netwerk/base/src/nsAsyncStreamCopier.h +++ b/netwerk/base/src/nsAsyncStreamCopier.h @@ -42,9 +42,9 @@ #include "nsIAsyncInputStream.h" #include "nsIAsyncOutputStream.h" #include "nsIRequestObserver.h" +#include "mozilla/Mutex.h" #include "nsStreamUtils.h" #include "nsCOMPtr.h" -#include "prlock.h" //----------------------------------------------------------------------------- @@ -78,7 +78,7 @@ private: nsCOMPtr mCopierCtx; - PRLock *mLock; + mozilla::Mutex mLock; nsAsyncCopyMode mMode; PRUint32 mChunkSize; diff --git a/netwerk/base/src/nsPACMan.cpp b/netwerk/base/src/nsPACMan.cpp index 94b4a44b924..fe9a65c477b 100644 --- a/netwerk/base/src/nsPACMan.cpp +++ b/netwerk/base/src/nsPACMan.cpp @@ -47,7 +47,6 @@ #include "nsIPrefService.h" #include "nsIPrefBranch.h" #include "nsNetUtil.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsCRT.h" #include "prmon.h" diff --git a/netwerk/base/src/nsProtocolProxyService.cpp b/netwerk/base/src/nsProtocolProxyService.cpp index 173f6cee5f0..f0a0c05c6c7 100644 --- a/netwerk/base/src/nsProtocolProxyService.cpp +++ b/netwerk/base/src/nsProtocolProxyService.cpp @@ -43,7 +43,6 @@ #include "nsIServiceManager.h" #include "nsXPIDLString.h" #include "nsIProxyAutoConfig.h" -#include "nsAutoLock.h" #include "nsIIOService.h" #include "nsIObserverService.h" #include "nsIProtocolHandler.h" diff --git a/netwerk/base/src/nsServerSocket.cpp b/netwerk/base/src/nsServerSocket.cpp index 2c55b58d0b6..3d2a5ab3dc0 100644 --- a/netwerk/base/src/nsServerSocket.cpp +++ b/netwerk/base/src/nsServerSocket.cpp @@ -40,13 +40,14 @@ #include "nsSocketTransport2.h" #include "nsServerSocket.h" #include "nsProxyRelease.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsNetError.h" #include "nsNetCID.h" #include "prnetdb.h" #include "prio.h" +using namespace mozilla; + static NS_DEFINE_CID(kSocketTransportServiceCID, NS_SOCKETTRANSPORTSERVICE_CID); //----------------------------------------------------------------------------- @@ -71,7 +72,7 @@ PostEvent(nsServerSocket *s, nsServerSocketFunc func) //----------------------------------------------------------------------------- nsServerSocket::nsServerSocket() - : mLock(nsnull) + : mLock("nsServerSocket.mLock") , mFD(nsnull) , mAttached(PR_FALSE) { @@ -91,9 +92,6 @@ nsServerSocket::~nsServerSocket() { Close(); // just in case :) - if (mLock) - nsAutoLock::DestroyLock(mLock); - // release our reference to the STS nsSocketTransportService *serv = gSocketTransportService; NS_IF_RELEASE(serv); @@ -246,7 +244,7 @@ nsServerSocket::OnSocketDetached(PRFileDesc *fd) // need to atomically clear mListener. see our Close() method. nsIServerSocketListener *listener = nsnull; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mListener.swap(listener); } // XXX we need to proxy the release to the listener's target thread to work @@ -290,13 +288,6 @@ nsServerSocket::InitWithAddress(const PRNetAddr *aAddr, PRInt32 aBackLog) { NS_ENSURE_TRUE(mFD == nsnull, NS_ERROR_ALREADY_INITIALIZED); - if (!mLock) - { - mLock = nsAutoLock::NewLock("nsServerSocket::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - } - // // configure listening socket... // @@ -353,9 +344,8 @@ fail: NS_IMETHODIMP nsServerSocket::Close() { - NS_ENSURE_TRUE(mLock, NS_ERROR_NOT_INITIALIZED); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // we want to proxy the close operation to the socket thread if a listener // has been set. otherwise, we should just close the socket here... if (!mListener) @@ -378,7 +368,7 @@ nsServerSocket::AsyncListen(nsIServerSocketListener *aListener) NS_ENSURE_TRUE(mFD, NS_ERROR_NOT_INITIALIZED); NS_ENSURE_TRUE(mListener == nsnull, NS_ERROR_IN_PROGRESS); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsresult rv = NS_GetProxyForObject(NS_PROXY_TO_CURRENT_THREAD, NS_GET_IID(nsIServerSocketListener), aListener, diff --git a/netwerk/base/src/nsServerSocket.h b/netwerk/base/src/nsServerSocket.h index 0b5a166b92f..8be866d6005 100644 --- a/netwerk/base/src/nsServerSocket.h +++ b/netwerk/base/src/nsServerSocket.h @@ -40,6 +40,7 @@ #include "nsIServerSocket.h" #include "nsSocketTransportService2.h" +#include "mozilla/Mutex.h" //----------------------------------------------------------------------------- @@ -67,7 +68,7 @@ private: nsresult TryAttach(); // lock protects access to mListener; so it is not cleared while being used. - PRLock *mLock; + mozilla::Mutex mLock; PRFileDesc *mFD; PRNetAddr mAddr; nsCOMPtr mListener; diff --git a/netwerk/base/src/nsSocketTransport2.cpp b/netwerk/base/src/nsSocketTransport2.cpp index 6d0812e584c..f24b8a78d9e 100644 --- a/netwerk/base/src/nsSocketTransport2.cpp +++ b/netwerk/base/src/nsSocketTransport2.cpp @@ -50,7 +50,6 @@ #include "nsTransportUtils.h" #include "nsProxyInfo.h" #include "nsNetCID.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsCOMPtr.h" #include "netCore.h" @@ -75,6 +74,8 @@ #include "nsNativeConnectionHelper.h" #endif +using namespace mozilla; + //----------------------------------------------------------------------------- static NS_DEFINE_CID(kSocketProviderServiceCID, NS_SOCKETPROVIDERSERVICE_CID); @@ -237,7 +238,7 @@ nsSocketInputStream::OnSocketReady(nsresult condition) nsCOMPtr callback; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); // update condition, but be careful not to erase an already // existing error condition. @@ -290,7 +291,7 @@ nsSocketInputStream::Available(PRUint32 *avail) PRFileDesc *fd; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); if (NS_FAILED(mCondition)) return mCondition; @@ -307,7 +308,7 @@ nsSocketInputStream::Available(PRUint32 *avail) nsresult rv; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); mTransport->ReleaseFD_Locked(fd); @@ -335,7 +336,7 @@ nsSocketInputStream::Read(char *buf, PRUint32 count, PRUint32 *countRead) PRFileDesc *fd; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); if (NS_FAILED(mCondition)) return (mCondition == NS_BASE_STREAM_CLOSED) ? NS_OK : mCondition; @@ -356,7 +357,7 @@ nsSocketInputStream::Read(char *buf, PRUint32 count, PRUint32 *countRead) nsresult rv; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); #ifdef ENABLE_SOCKET_TRACING if (n > 0) @@ -409,7 +410,7 @@ nsSocketInputStream::CloseWithStatus(nsresult reason) nsresult rv; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); if (NS_SUCCEEDED(mCondition)) rv = mCondition = reason; @@ -434,7 +435,7 @@ nsSocketInputStream::AsyncWait(nsIInputStreamCallback *callback, // (different from callback when target is not null) nsCOMPtr directCallback; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); if (callback && target) { // @@ -496,7 +497,7 @@ nsSocketOutputStream::OnSocketReady(nsresult condition) nsCOMPtr callback; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); // update condition, but be careful not to erase an already // existing error condition. @@ -558,7 +559,7 @@ nsSocketOutputStream::Write(const char *buf, PRUint32 count, PRUint32 *countWrit PRFileDesc *fd; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); if (NS_FAILED(mCondition)) return mCondition; @@ -580,7 +581,7 @@ nsSocketOutputStream::Write(const char *buf, PRUint32 count, PRUint32 *countWrit nsresult rv; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); #ifdef ENABLE_SOCKET_TRACING if (n > 0) @@ -651,7 +652,7 @@ nsSocketOutputStream::CloseWithStatus(nsresult reason) nsresult rv; { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); if (NS_SUCCEEDED(mCondition)) rv = mCondition = reason; @@ -672,7 +673,7 @@ nsSocketOutputStream::AsyncWait(nsIOutputStreamCallback *callback, SOCKET_LOG(("nsSocketOutputStream::AsyncWait [this=%x]\n", this)); { - nsAutoLock lock(mTransport->mLock); + MutexAutoLock lock(mTransport->mLock); if (callback && target) { // @@ -713,7 +714,7 @@ nsSocketTransport::nsSocketTransport() , mInputClosed(PR_TRUE) , mOutputClosed(PR_TRUE) , mResolving(PR_FALSE) - , mLock(nsAutoLock::NewLock("nsSocketTransport::mLock")) + , mLock("nsSocketTransport.mLock") , mFD(nsnull) , mFDref(0) , mFDconnected(PR_FALSE) @@ -740,9 +741,6 @@ nsSocketTransport::~nsSocketTransport() PL_strfree(mTypes[i]); free(mTypes); } - - if (mLock) - nsAutoLock::DestroyLock(mLock); nsSocketTransportService *serv = gSocketTransportService; NS_RELEASE(serv); // nulls argument @@ -753,9 +751,6 @@ nsSocketTransport::Init(const char **types, PRUint32 typeCount, const nsACString &host, PRUint16 port, nsIProxyInfo *givenProxyInfo) { - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - nsCOMPtr proxyInfo; if (givenProxyInfo) { proxyInfo = do_QueryInterface(givenProxyInfo); @@ -837,9 +832,6 @@ nsSocketTransport::Init(const char **types, PRUint32 typeCount, nsresult nsSocketTransport::InitWithConnectedSocket(PRFileDesc *fd, const PRNetAddr *addr) { - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - NS_ASSERTION(!mFD, "already initialized"); char buf[64]; @@ -897,7 +889,7 @@ nsSocketTransport::SendStatus(nsresult status) nsCOMPtr sink; PRUint64 progress; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); sink = mEventSink; switch (status) { case STATUS_SENDING_TO: @@ -1040,7 +1032,7 @@ nsSocketTransport::BuildSocket(PRFileDesc *&fd, PRBool &proxyTransparent, PRBool // remember security info and give notification callbacks to PSM... nsCOMPtr callbacks; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mSecInfo = secinfo; callbacks = mCallbacks; SOCKET_LOG((" [secinfo=%x callbacks=%x]\n", mSecInfo.get(), mCallbacks.get())); @@ -1159,7 +1151,7 @@ nsSocketTransport::InitiateSocket() // assign mFD so that we can properly handle OnSocketDetached before we've // established a connection. { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mFD = fd; mFDref = 1; mFDconnected = PR_FALSE; @@ -1373,7 +1365,7 @@ nsSocketTransport::OnSocketConnected() // assign mFD (must do this within the transport lock), but take care not // to trample over mFDref if mFD is already set. { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(mFD, "no socket"); NS_ASSERTION(mFDref == 1, "wrong socket ref count"); mFDconnected = PR_TRUE; @@ -1640,7 +1632,7 @@ nsSocketTransport::OnSocketDetached(PRFileDesc *fd) nsCOMPtr ourCallbacks; nsCOMPtr ourEventSink; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mFD) { ReleaseFD_Locked(mFD); // flag mFD as unusable; this prevents other consumers from @@ -1781,7 +1773,7 @@ nsSocketTransport::Close(nsresult reason) NS_IMETHODIMP nsSocketTransport::GetSecurityInfo(nsISupports **secinfo) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_IF_ADDREF(*secinfo = mSecInfo); return NS_OK; } @@ -1789,7 +1781,7 @@ nsSocketTransport::GetSecurityInfo(nsISupports **secinfo) NS_IMETHODIMP nsSocketTransport::GetSecurityCallbacks(nsIInterfaceRequestor **callbacks) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_IF_ADDREF(*callbacks = mCallbacks); return NS_OK; } @@ -1797,7 +1789,7 @@ nsSocketTransport::GetSecurityCallbacks(nsIInterfaceRequestor **callbacks) NS_IMETHODIMP nsSocketTransport::SetSecurityCallbacks(nsIInterfaceRequestor *callbacks) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mCallbacks = callbacks; // XXX should we tell PSM about this? return NS_OK; @@ -1816,7 +1808,7 @@ nsSocketTransport::SetEventSink(nsITransportEventSink *sink, sink = temp.get(); } - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mEventSink = sink; return NS_OK; } @@ -1828,7 +1820,7 @@ nsSocketTransport::IsAlive(PRBool *result) PRFileDesc *fd; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (NS_FAILED(mCondition)) return NS_OK; fd = GetFD_Locked(); @@ -1845,7 +1837,7 @@ nsSocketTransport::IsAlive(PRBool *result) *result = PR_TRUE; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); ReleaseFD_Locked(fd); } return NS_OK; @@ -1888,7 +1880,7 @@ nsSocketTransport::GetSelfAddr(PRNetAddr *addr) PRFileDesc *fd; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); fd = GetFD_Locked(); } @@ -1899,7 +1891,7 @@ nsSocketTransport::GetSelfAddr(PRNetAddr *addr) (PR_GetSockName(fd, addr) == PR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); ReleaseFD_Locked(fd); } diff --git a/netwerk/base/src/nsSocketTransport2.h b/netwerk/base/src/nsSocketTransport2.h index 22ed9785967..9588002b0c7 100644 --- a/netwerk/base/src/nsSocketTransport2.h +++ b/netwerk/base/src/nsSocketTransport2.h @@ -42,6 +42,7 @@ #define ENABLE_SOCKET_TRACING #endif +#include "mozilla/Mutex.h" #include "nsSocketTransportService2.h" #include "nsString.h" #include "nsCOMPtr.h" @@ -134,6 +135,8 @@ class nsSocketTransport : public nsASocketHandler , public nsIDNSListener , public nsIClassInfo { + typedef mozilla::Mutex Mutex; + public: NS_DECL_ISUPPORTS NS_DECL_NSITRANSPORT @@ -254,7 +257,7 @@ private: // socket input/output objects. these may be accessed on any thread with // the exception of some specific methods (XXX). - PRLock *mLock; // protects members in this section + Mutex mLock; // protects members in this section PRFileDesc *mFD; nsrefcnt mFDref; // mFD is closed when mFDref goes to zero. PRBool mFDconnected; // mFD is available to consumer when TRUE. diff --git a/netwerk/base/src/nsSocketTransportService2.cpp b/netwerk/base/src/nsSocketTransportService2.cpp index a4a1d4a176a..c24e624cc3d 100644 --- a/netwerk/base/src/nsSocketTransportService2.cpp +++ b/netwerk/base/src/nsSocketTransportService2.cpp @@ -43,10 +43,8 @@ #include "nsSocketTransportService2.h" #include "nsSocketTransport2.h" #include "nsReadableUtils.h" -#include "nsAutoLock.h" #include "nsNetError.h" #include "prnetdb.h" -#include "prlock.h" #include "prerror.h" #include "plstr.h" #include "nsIPrefService.h" @@ -56,6 +54,8 @@ #include "mozilla/FunctionTimer.h" +using namespace mozilla; + #if defined(PR_LOGGING) PRLogModuleInfo *gSocketTransportLog = nsnull; #endif @@ -72,7 +72,7 @@ nsSocketTransportService::nsSocketTransportService() : mThread(nsnull) , mThreadEvent(nsnull) , mAutodialEnabled(PR_FALSE) - , mLock(nsAutoLock::NewLock("nsSocketTransportService::mLock")) + , mLock("nsSocketTransportService::mLock") , mInitialized(PR_FALSE) , mShuttingDown(PR_FALSE) , mActiveCount(0) @@ -93,9 +93,6 @@ nsSocketTransportService::~nsSocketTransportService() { NS_ASSERTION(NS_IsMainThread(), "wrong thread"); NS_ASSERTION(!mInitialized, "not shutdown properly"); - - if (mLock) - nsAutoLock::DestroyLock(mLock); if (mThreadEvent) PR_DestroyPollableEvent(mThreadEvent); @@ -109,7 +106,7 @@ nsSocketTransportService::~nsSocketTransportService() already_AddRefed nsSocketTransportService::GetThreadSafely() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsIThread* result = mThread; NS_IF_ADDREF(result); return result; @@ -383,8 +380,6 @@ nsSocketTransportService::Init() { NS_TIME_FUNCTION; - NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY); - if (!NS_IsMainThread()) { NS_ERROR("wrong thread"); return NS_ERROR_UNEXPECTED; @@ -425,7 +420,7 @@ nsSocketTransportService::Init() if (NS_FAILED(rv)) return rv; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Install our mThread, protecting against concurrent readers thread.swap(mThread); } @@ -456,7 +451,7 @@ nsSocketTransportService::Shutdown() return NS_ERROR_UNEXPECTED; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // signal the socket thread to shutdown mShuttingDown = PR_TRUE; @@ -469,7 +464,7 @@ nsSocketTransportService::Shutdown() // join with thread mThread->Shutdown(); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Drop our reference to mThread and make sure that any concurrent // readers are excluded mThread = nsnull; @@ -528,7 +523,7 @@ nsSocketTransportService::SetAutodialEnabled(PRBool value) NS_IMETHODIMP nsSocketTransportService::OnDispatchedEvent(nsIThreadInternal *thread) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mThreadEvent) PR_SetPollableEvent(mThreadEvent); return NS_OK; @@ -585,7 +580,7 @@ nsSocketTransportService::Run() // now that our event queue is empty, check to see if we should exit { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mShuttingDown) break; } @@ -720,7 +715,7 @@ nsSocketTransportService::DoPollIteration(PRBool wait) // new pollable event. If that fails, we fall back // on "busy wait". { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); PR_DestroyPollableEvent(mThreadEvent); mThreadEvent = PR_NewPollableEvent(); } diff --git a/netwerk/base/src/nsSocketTransportService2.h b/netwerk/base/src/nsSocketTransportService2.h index b21c1bd240f..3468fb90101 100644 --- a/netwerk/base/src/nsSocketTransportService2.h +++ b/netwerk/base/src/nsSocketTransportService2.h @@ -50,6 +50,7 @@ #include "prio.h" #include "nsASocketHandler.h" #include "nsIObserver.h" +#include "mozilla/Mutex.h" //----------------------------------------------------------------------------- @@ -75,6 +76,8 @@ class nsSocketTransportService : public nsPISocketTransportService , public nsIRunnable , public nsIObserver { + typedef mozilla::Mutex Mutex; + public: NS_DECL_ISUPPORTS NS_DECL_NSPISOCKETTRANSPORTSERVICE @@ -126,7 +129,7 @@ private: // initialization and shutdown (any thread) //------------------------------------------------------------------------- - PRLock *mLock; + Mutex mLock; PRPackedBool mInitialized; PRPackedBool mShuttingDown; // indicates whether we are currently in the diff --git a/netwerk/base/src/nsStreamTransportService.cpp b/netwerk/base/src/nsStreamTransportService.cpp index e8e31ef0746..55ae71f4364 100644 --- a/netwerk/base/src/nsStreamTransportService.cpp +++ b/netwerk/base/src/nsStreamTransportService.cpp @@ -38,7 +38,6 @@ #include "nsStreamTransportService.h" #include "nsXPCOMCIDInternal.h" #include "nsNetSegmentUtils.h" -#include "nsAutoLock.h" #include "nsInt64.h" #include "nsTransportUtils.h" #include "nsStreamUtils.h" diff --git a/netwerk/base/src/nsTransportUtils.cpp b/netwerk/base/src/nsTransportUtils.cpp index 09e21e8b9d0..d9558004208 100644 --- a/netwerk/base/src/nsTransportUtils.cpp +++ b/netwerk/base/src/nsTransportUtils.cpp @@ -34,14 +34,16 @@ * * ***** END LICENSE BLOCK ***** */ +#include "mozilla/Mutex.h" #include "nsTransportUtils.h" #include "nsITransport.h" #include "nsProxyRelease.h" #include "nsThreadUtils.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsCOMPtr.h" +using namespace mozilla; + //----------------------------------------------------------------------------- class nsTransportStatusEvent; @@ -57,7 +59,7 @@ public: PRBool coalesceAll) : mSink(sink) , mTarget(target) - , mLock(nsAutoLock::NewLock("nsTransportEventSinkProxy::mLock")) + , mLock("nsTransportEventSinkProxy.mLock") , mLastEvent(nsnull) , mCoalesceAll(coalesceAll) { @@ -66,9 +68,6 @@ public: virtual ~nsTransportEventSinkProxy() { - if (mLock) - nsAutoLock::DestroyLock(mLock); - // our reference to mSink could be the last, so be sure to release // it on the target thread. otherwise, we could get into trouble. NS_ProxyRelease(mTarget, mSink); @@ -76,7 +75,7 @@ public: nsITransportEventSink *mSink; nsCOMPtr mTarget; - PRLock *mLock; + Mutex mLock; nsTransportStatusEvent *mLastEvent; PRBool mCoalesceAll; }; @@ -103,7 +102,7 @@ public: // since this event is being handled, we need to clear the proxy's ref. // if not coalescing all, then last event may not equal self! { - nsAutoLock lock(mProxy->mLock); + MutexAutoLock lock(mProxy->mLock); if (mProxy->mLastEvent == this) mProxy->mLastEvent = nsnull; } @@ -133,7 +132,7 @@ nsTransportEventSinkProxy::OnTransportStatus(nsITransport *transport, nsresult rv = NS_OK; nsRefPtr event; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // try to coalesce events! ;-) if (mLastEvent && (mCoalesceAll || mLastEvent->mStatus == status)) { @@ -154,7 +153,7 @@ nsTransportEventSinkProxy::OnTransportStatus(nsITransport *transport, if (NS_FAILED(rv)) { NS_WARNING("unable to post transport status event"); - nsAutoLock lock(mLock); // cleanup.. don't reference anymore! + MutexAutoLock lock(mLock); // cleanup.. don't reference anymore! mLastEvent = nsnull; } } diff --git a/netwerk/build/nsNetModule.cpp b/netwerk/build/nsNetModule.cpp index efc58e858f0..a51bff8f3bf 100644 --- a/netwerk/build/nsNetModule.cpp +++ b/netwerk/build/nsNetModule.cpp @@ -254,7 +254,7 @@ NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsHttpHandler, Init) NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsHttpsHandler, Init) NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsHttpAuthManager, Init) NS_GENERIC_FACTORY_CONSTRUCTOR(nsHttpChannelAuthProvider) -NS_GENERIC_FACTORY_CONSTRUCTOR_INIT(nsHttpActivityDistributor, Init) +NS_GENERIC_FACTORY_CONSTRUCTOR(nsHttpActivityDistributor) NS_GENERIC_FACTORY_CONSTRUCTOR(nsHttpBasicAuth) NS_GENERIC_FACTORY_CONSTRUCTOR(nsHttpDigestAuth) #endif // !NECKO_PROTOCOL_http diff --git a/netwerk/cache/nsCacheRequest.h b/netwerk/cache/nsCacheRequest.h index 9ccdad7747e..cc6fd7148eb 100644 --- a/netwerk/cache/nsCacheRequest.h +++ b/netwerk/cache/nsCacheRequest.h @@ -42,6 +42,8 @@ #define _nsCacheRequest_h_ #include "nspr.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" #include "nsCOMPtr.h" #include "nsICache.h" #include "nsICacheListener.h" @@ -51,6 +53,10 @@ class nsCacheRequest : public PRCList { + typedef mozilla::CondVar CondVar; + typedef mozilla::MutexAutoLock MutexAutoLock; + typedef mozilla::Mutex Mutex; + private: friend class nsCacheService; friend class nsCacheEntry; @@ -64,8 +70,8 @@ private: : mKey(key), mInfo(0), mListener(listener), - mLock(nsnull), - mCondVar(nsnull) + mLock("nsCacheRequest.mLock"), + mCondVar(mLock, "nsCacheRequest.mCondVar") { MOZ_COUNT_CTOR(nsCacheRequest); PR_INIT_CLIST(this); @@ -82,8 +88,6 @@ private: { MOZ_COUNT_DTOR(nsCacheRequest); delete mKey; - if (mLock) PR_DestroyLock(mLock); - if (mCondVar) PR_DestroyCondVar(mCondVar); NS_ASSERTION(PR_CLIST_IS_EMPTY(this), "request still on a list"); if (mListener) @@ -151,40 +155,20 @@ private: MarkWaitingForValidation(); // set up for next time return NS_OK; // early exit; } - - if (!mLock) { - mLock = PR_NewLock(); - if (!mLock) return NS_ERROR_OUT_OF_MEMORY; - - NS_ASSERTION(!mCondVar,"we have mCondVar, but didn't have mLock?"); - mCondVar = PR_NewCondVar(mLock); - if (!mCondVar) { - PR_DestroyLock(mLock); - return NS_ERROR_OUT_OF_MEMORY; + { + MutexAutoLock lock(mLock); + while (WaitingForValidation()) { + mCondVar.Wait(); } - } - PRStatus status = PR_SUCCESS; - PR_Lock(mLock); - while (WaitingForValidation() && (status == PR_SUCCESS) ) { - status = PR_WaitCondVar(mCondVar, PR_INTERVAL_NO_TIMEOUT); - } - MarkWaitingForValidation(); // set up for next time - PR_Unlock(mLock); - - NS_ASSERTION(status == PR_SUCCESS, "PR_WaitCondVar() returned PR_FAILURE?"); - if (status == PR_FAILURE) - return NS_ERROR_UNEXPECTED; - + MarkWaitingForValidation(); // set up for next time + } return NS_OK; } void WakeUp(void) { DoneWaitingForValidation(); - if (mLock) { - PR_Lock(mLock); - PR_NotifyCondVar(mCondVar); - PR_Unlock(mLock); - } + MutexAutoLock lock(mLock); + mCondVar.Notify(); } /** @@ -194,8 +178,8 @@ private: PRUint32 mInfo; nsICacheListener * mListener; // strong ref nsCOMPtr mThread; - PRLock * mLock; - PRCondVar * mCondVar; + Mutex mLock; + CondVar mCondVar; }; #endif // _nsCacheRequest_h_ diff --git a/netwerk/cache/nsCacheService.cpp b/netwerk/cache/nsCacheService.cpp index 98a17f31e25..4687cd346aa 100644 --- a/netwerk/cache/nsCacheService.cpp +++ b/netwerk/cache/nsCacheService.cpp @@ -80,6 +80,8 @@ #include "mozilla/net/NeckoCommon.h" #endif +using namespace mozilla; + /****************************************************************************** * nsCacheProfilePrefObserver *****************************************************************************/ @@ -275,12 +277,11 @@ public: } NS_IMETHOD Run() { - mozilla::MonitorAutoEnter - autoMonitor(nsCacheService::gService->mMonitor); + nsCacheServiceAutoLock autoLock; #ifdef PR_LOGGING CACHE_LOG_DEBUG(("nsBlockOnCacheThreadEvent [%p]\n", this)); #endif - autoMonitor.Notify(); + nsCacheService::gService->mCondVar.Notify(); return NS_OK; } }; @@ -809,12 +810,9 @@ nsCacheService::DispatchToCacheIOThread(nsIRunnable* event) nsresult nsCacheService::SyncWithCacheIOThread() { - NS_ASSERTION(gService->mLockedThread == PR_GetCurrentThread(), - "not holding cache-lock"); + gService->mLock.AssertCurrentThreadOwns(); if (!gService->mCacheIOThread) return NS_ERROR_NOT_AVAILABLE; - mozilla::MonitorAutoEnter autoMonitor(gService->mMonitor); - nsCOMPtr event = new nsBlockOnCacheThreadEvent(); // dispatch event - it will notify the monitor when it's done @@ -825,10 +823,8 @@ nsCacheService::SyncWithCacheIOThread() return NS_ERROR_UNEXPECTED; } - Unlock(); // wait until notified, then return - rv = autoMonitor.Wait(); - Lock(); + rv = gService->mCondVar.Wait(); return rv; } @@ -985,8 +981,8 @@ nsCacheService * nsCacheService::gService = nsnull; NS_IMPL_THREADSAFE_ISUPPORTS1(nsCacheService, nsICacheService) nsCacheService::nsCacheService() - : mLock(nsnull), - mMonitor("block-on-cache-monitor"), + : mLock("nsCacheService.mLock"), + mCondVar(mLock, "nsCacheService.mCondVar"), mInitialized(PR_FALSE), mEnableMemoryDevice(PR_TRUE), mEnableDiskDevice(PR_TRUE), @@ -1007,13 +1003,6 @@ nsCacheService::nsCacheService() // create list of cache devices PR_INIT_CLIST(&mDoomedEntries); - - // allocate service lock - mLock = PR_NewLock(); - -#if defined(DEBUG) - mLockedThread = nsnull; -#endif } nsCacheService::~nsCacheService() @@ -1021,7 +1010,6 @@ nsCacheService::~nsCacheService() if (mInitialized) // Shutdown hasn't been called yet. (void) Shutdown(); - PR_DestroyLock(mLock); gService = nsnull; } @@ -1041,9 +1029,6 @@ nsCacheService::Init() } #endif - if (mLock == nsnull) - return NS_ERROR_OUT_OF_MEMORY; - CACHE_LOG_INIT(); nsresult rv = NS_NewThread(getter_AddRefs(mCacheIOThread)); @@ -2211,25 +2196,18 @@ nsCacheService::OnDataSizeChange(nsCacheEntry * entry, PRInt32 deltaSize) void nsCacheService::Lock() { - PR_Lock(gService->mLock); - -#if defined(DEBUG) - gService->mLockedThread = PR_GetCurrentThread(); -#endif + gService->mLock.Lock(); } void nsCacheService::Unlock() { - NS_ASSERTION(gService->mLockedThread == PR_GetCurrentThread(), "oops"); + gService->mLock.AssertCurrentThreadOwns(); nsTArray doomed; doomed.SwapElements(gService->mDoomedObjects); -#if defined(DEBUG) - gService->mLockedThread = nsnull; -#endif - PR_Unlock(gService->mLock); + gService->mLock.Unlock(); for (PRUint32 i = 0; i < doomed.Length(); ++i) doomed[i]->Release(); @@ -2239,7 +2217,7 @@ void nsCacheService::ReleaseObject_Locked(nsISupports * obj, nsIEventTarget * target) { - NS_ASSERTION(gService->mLockedThread == PR_GetCurrentThread(), "oops"); + gService->mLock.AssertCurrentThreadOwns(); PRBool isCur; if (!target || (NS_SUCCEEDED(target->IsOnCurrentThread(&isCur)) && isCur)) { diff --git a/netwerk/cache/nsCacheService.h b/netwerk/cache/nsCacheService.h index 1107d633e5c..3e64f87e8b5 100644 --- a/netwerk/cache/nsCacheService.h +++ b/netwerk/cache/nsCacheService.h @@ -50,13 +50,13 @@ #include "nsCacheDevice.h" #include "nsCacheEntry.h" -#include "prlock.h" #include "prthread.h" #include "nsIObserver.h" #include "nsString.h" #include "nsProxiedService.h" #include "nsTArray.h" -#include "mozilla/Monitor.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" class nsCacheRequest; class nsCacheProfilePrefObserver; @@ -172,6 +172,10 @@ public: nsresult Init(); void Shutdown(); + + static void AssertOwnsLock() + { gService->mLock.AssertCurrentThreadOwns(); } + private: friend class nsCacheServiceAutoLock; friend class nsOfflineCacheDevice; @@ -254,13 +258,8 @@ private: nsCacheProfilePrefObserver * mObserver; - PRLock * mLock; - - mozilla::Monitor mMonitor; - -#if defined(DEBUG) - PRThread * mLockedThread; // The thread holding mLock -#endif + mozilla::Mutex mLock; + mozilla::CondVar mCondVar; nsCOMPtr mCacheIOThread; diff --git a/netwerk/cache/nsDiskCacheDevice.cpp b/netwerk/cache/nsDiskCacheDevice.cpp index 715020ba6f6..0a960870c39 100644 --- a/netwerk/cache/nsDiskCacheDevice.cpp +++ b/netwerk/cache/nsDiskCacheDevice.cpp @@ -75,7 +75,6 @@ #include "nsReadableUtils.h" #include "nsIInputStream.h" #include "nsIOutputStream.h" -#include "nsAutoLock.h" #include "nsCRT.h" #include "nsCOMArray.h" #include "nsISimpleEnumerator.h" @@ -398,6 +397,8 @@ nsDiskCacheDevice::Init() nsresult nsDiskCacheDevice::Shutdown() { + nsCacheService::AssertOwnsLock(); + nsresult rv = Shutdown_Private(PR_TRUE); if (NS_FAILED(rv)) return rv; diff --git a/netwerk/dns/nsDNSService2.cpp b/netwerk/dns/nsDNSService2.cpp index 563550bba23..57d13953b6c 100644 --- a/netwerk/dns/nsDNSService2.cpp +++ b/netwerk/dns/nsDNSService2.cpp @@ -46,7 +46,6 @@ #include "nsIServiceManager.h" #include "nsReadableUtils.h" #include "nsString.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsNetCID.h" #include "nsNetError.h" @@ -61,6 +60,8 @@ #include "mozilla/FunctionTimer.h" +using namespace mozilla; + static const char kPrefDnsCacheEntries[] = "network.dnsCacheEntries"; static const char kPrefDnsCacheExpiration[] = "network.dnsCacheExpiration"; static const char kPrefEnableIDN[] = "network.enableIDN"; @@ -105,13 +106,14 @@ nsDNSRecord::GetCanonicalName(nsACString &result) // if the record is for an IP address literal, then the canonical // host name is the IP address literal. const char *cname; - PR_Lock(mHostRecord->addr_info_lock); - if (mHostRecord->addr_info) - cname = PR_GetCanonNameFromAddrInfo(mHostRecord->addr_info); - else - cname = mHostRecord->host; - result.Assign(cname); - PR_Unlock(mHostRecord->addr_info_lock); + { + MutexAutoLock lock(*mHostRecord->addr_info_lock); + if (mHostRecord->addr_info) + cname = PR_GetCanonNameFromAddrInfo(mHostRecord->addr_info); + else + cname = mHostRecord->host; + result.Assign(cname); + } return NS_OK; } @@ -124,7 +126,7 @@ nsDNSRecord::GetNextAddr(PRUint16 port, PRNetAddr *addr) if (mDone) return NS_ERROR_NOT_AVAILABLE; - PR_Lock(mHostRecord->addr_info_lock); + mHostRecord->addr_info_lock->Lock(); if (mHostRecord->addr_info) { if (!mIter) mIterGenCnt = mHostRecord->addr_info_gencnt; @@ -135,14 +137,14 @@ nsDNSRecord::GetNextAddr(PRUint16 port, PRNetAddr *addr) mIterGenCnt = mHostRecord->addr_info_gencnt; } mIter = PR_EnumerateAddrInfo(mIter, mHostRecord->addr_info, port, addr); - PR_Unlock(mHostRecord->addr_info_lock); + mHostRecord->addr_info_lock->Unlock(); if (!mIter) { mDone = PR_TRUE; return NS_ERROR_NOT_AVAILABLE; } } else { - PR_Unlock(mHostRecord->addr_info_lock); + mHostRecord->addr_info_lock->Unlock(); if (!mHostRecord->addr) { // Both mHostRecord->addr_info and mHostRecord->addr are null. // This can happen if mHostRecord->addr_info expired and the @@ -306,14 +308,13 @@ nsDNSSyncRequest::OnLookupComplete(nsHostResolver *resolver, //----------------------------------------------------------------------------- nsDNSService::nsDNSService() - : mLock(nsnull) + : mLock("nsDNSServer.mLock") + , mFirstTime(PR_TRUE) { } nsDNSService::~nsDNSService() { - if (mLock) - nsAutoLock::DestroyLock(mLock); } NS_IMPL_THREADSAFE_ISUPPORTS3(nsDNSService, nsIDNSService, nsPIDNSService, @@ -326,8 +327,6 @@ nsDNSService::Init() NS_ENSURE_TRUE(!mResolver, NS_ERROR_ALREADY_INITIALIZED); - PRBool firstTime = (mLock == nsnull); - // prefs PRUint32 maxCacheEntries = 400; PRUint32 maxCacheLifetime = 3; // minutes @@ -357,10 +356,8 @@ nsDNSService::Init() prefs->GetIntPref("network.proxy.type", &proxyType); } - if (firstTime) { - mLock = nsAutoLock::NewLock("nsDNSService::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; + if (mFirstTime) { + mFirstTime = PR_FALSE; // register as prefs observer if (prefs) { @@ -396,7 +393,7 @@ nsDNSService::Init() getter_AddRefs(res)); if (NS_SUCCEEDED(rv)) { // now, set all of our member variables while holding the lock - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mResolver = res; mIDN = idn; mIPv4OnlyDomains = ipv4OnlyDomains; // exchanges buffer ownership @@ -413,7 +410,7 @@ nsDNSService::Shutdown() { nsRefPtr res; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); res = mResolver; mResolver = nsnull; } @@ -434,7 +431,7 @@ nsDNSService::AsyncResolve(const nsACString &hostname, nsRefPtr res; nsCOMPtr idn; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mDisablePrefetch && (flags & RESOLVE_SPECULATE)) return NS_ERROR_DNS_LOOKUP_QUEUE_FULL; @@ -493,7 +490,7 @@ nsDNSService::Resolve(const nsACString &hostname, nsRefPtr res; nsCOMPtr idn; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); res = mResolver; idn = mIDN; } @@ -588,7 +585,7 @@ nsDNSService::GetAFForLookup(const nsACString &host) if (mDisableIPv6) return PR_AF_INET; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); PRUint16 af = PR_AF_UNSPEC; diff --git a/netwerk/dns/nsDNSService2.h b/netwerk/dns/nsDNSService2.h index 9487d7836a3..d5fbbefbca5 100644 --- a/netwerk/dns/nsDNSService2.h +++ b/netwerk/dns/nsDNSService2.h @@ -40,7 +40,7 @@ #include "nsHostResolver.h" #include "nsAutoPtr.h" #include "nsString.h" -#include "prlock.h" +#include "mozilla/Mutex.h" class nsDNSService : public nsPIDNSService , public nsIObserver @@ -61,7 +61,7 @@ private: nsCOMPtr mIDN; // mLock protects access to mResolver and mIPv4OnlyDomains - PRLock *mLock; + mozilla::Mutex mLock; // mIPv4OnlyDomains is a comma-separated list of domains for which only // IPv4 DNS lookups are performed. This allows the user to disable IPv6 on @@ -69,4 +69,5 @@ private: nsAdoptingCString mIPv4OnlyDomains; PRBool mDisableIPv6; PRBool mDisablePrefetch; + PRBool mFirstTime; }; diff --git a/netwerk/dns/nsHostResolver.cpp b/netwerk/dns/nsHostResolver.cpp index 0e50b950286..51ad82322f9 100644 --- a/netwerk/dns/nsHostResolver.cpp +++ b/netwerk/dns/nsHostResolver.cpp @@ -53,12 +53,10 @@ #include "nsNetError.h" #include "nsISupportsBase.h" #include "nsISupportsUtils.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "pratom.h" #include "prthread.h" #include "prerror.h" -#include "prcvar.h" #include "prtime.h" #include "prlong.h" #include "prlog.h" @@ -68,6 +66,8 @@ #include "mozilla/FunctionTimer.h" +using namespace mozilla; + //---------------------------------------------------------------------------- // Use a persistent thread pool in order to avoid spinning up new threads all the time. @@ -181,18 +181,10 @@ private: nsresult nsHostRecord::Create(const nsHostKey *key, nsHostRecord **result) { - PRLock *lock = PR_NewLock(); - if (!lock) - return NS_ERROR_OUT_OF_MEMORY; - size_t hostLen = strlen(key->host) + 1; size_t size = hostLen + sizeof(nsHostRecord); nsHostRecord *rec = (nsHostRecord*) ::operator new(size); - if (!rec) { - PR_DestroyLock(lock); - return NS_ERROR_OUT_OF_MEMORY; - } rec->host = ((char *) rec) + sizeof(nsHostRecord); rec->flags = key->flags; @@ -200,7 +192,7 @@ nsHostRecord::Create(const nsHostKey *key, nsHostRecord **result) rec->_refc = 1; // addref NS_LOG_ADDREF(rec, 1, "nsHostRecord", sizeof(nsHostRecord)); - rec->addr_info_lock = lock; + rec->addr_info_lock = new Mutex("nsHostRecord.addr_info_lock"); rec->addr_info = nsnull; rec->addr_info_gencnt = 0; rec->addr = nsnull; @@ -219,10 +211,7 @@ nsHostRecord::Create(const nsHostKey *key, nsHostRecord **result) nsHostRecord::~nsHostRecord() { - if (addr_info_lock) - PR_DestroyLock(addr_info_lock); - if (addr_info) - PR_FreeAddrInfo(addr_info); + delete addr_info_lock; if (addr) free(addr); } @@ -330,8 +319,8 @@ nsHostResolver::nsHostResolver(PRUint32 maxCacheEntries, PRUint32 maxCacheLifetime) : mMaxCacheEntries(maxCacheEntries) , mMaxCacheLifetime(maxCacheLifetime) - , mLock(nsnull) - , mIdleThreadCV(nsnull) + , mLock("nsHostResolver.mLock") + , mIdleThreadCV(mLock, "nsHostResolver.mIdleThreadCV") , mNumIdleThreads(0) , mThreadCount(0) , mActiveAnyThreadCount(0) @@ -351,12 +340,6 @@ nsHostResolver::nsHostResolver(PRUint32 maxCacheEntries, nsHostResolver::~nsHostResolver() { - if (mIdleThreadCV) - PR_DestroyCondVar(mIdleThreadCV); - - if (mLock) - nsAutoLock::DestroyLock(mLock); - PL_DHashTableFinish(&mDB); } @@ -365,14 +348,6 @@ nsHostResolver::Init() { NS_TIME_FUNCTION; - mLock = nsAutoLock::NewLock("nsHostResolver::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - - mIdleThreadCV = PR_NewCondVar(mLock); - if (!mIdleThreadCV) - return NS_ERROR_OUT_OF_MEMORY; - PL_DHashTableInit(&mDB, &gHostDB_ops, nsnull, sizeof(nsHostDBEnt), 0); mShutdown = PR_FALSE; @@ -418,7 +393,7 @@ nsHostResolver::Shutdown() PR_INIT_CLIST(&evictionQ); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mShutdown = PR_TRUE; @@ -430,7 +405,7 @@ nsHostResolver::Shutdown() mPendingCount = 0; if (mNumIdleThreads) - PR_NotifyAllCondVar(mIdleThreadCV); + mIdleThreadCV.NotifyAll(); // empty host database PL_DHashTableEnumerate(&mDB, HostDB_RemoveEntry, nsnull); @@ -512,7 +487,7 @@ nsHostResolver::ResolveHost(const char *host, nsRefPtr result; nsresult status = NS_OK, rv = NS_OK; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mShutdown) rv = NS_ERROR_NOT_INITIALIZED; @@ -602,7 +577,7 @@ nsHostResolver::ResolveHost(const char *host, // Move from low to med. MoveQueue(he->rec, mMediumQ); he->rec->flags = flags; - PR_NotifyCondVar(mIdleThreadCV); + mIdleThreadCV.Notify(); } } } @@ -622,7 +597,7 @@ nsHostResolver::DetachCallback(const char *host, { nsRefPtr rec; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsHostKey key = { host, flags, af }; nsHostDBEnt *he = static_cast @@ -653,7 +628,7 @@ nsHostResolver::ConditionallyCreateThread(nsHostRecord *rec) { if (mNumIdleThreads) { // wake up idle thread to process this lookup - PR_NotifyCondVar(mIdleThreadCV); + mIdleThreadCV.Notify(); } else if ((mThreadCount < HighThreadThreshold) || (IsHighPriority(rec->flags) && mThreadCount < MAX_RESOLVER_THREADS)) { @@ -734,7 +709,7 @@ nsHostResolver::GetHostToLookup(nsHostRecord **result) PRBool timedOut = PR_FALSE; PRIntervalTime epoch, now, timeout; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); timeout = (mNumIdleThreads >= HighThreadThreshold) ? mShortIdleTimeout : mLongIdleTimeout; epoch = PR_IntervalNow(); @@ -774,7 +749,7 @@ nsHostResolver::GetHostToLookup(nsHostRecord **result) // (3) the thread has been idle for too long mNumIdleThreads++; - PR_WaitCondVar(mIdleThreadCV, timeout); + mIdleThreadCV.Wait(timeout); mNumIdleThreads--; now = PR_IntervalNow(); @@ -803,7 +778,7 @@ nsHostResolver::OnLookupComplete(nsHostRecord *rec, nsresult status, PRAddrInfo PRCList cbs; PR_INIT_CLIST(&cbs); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // grab list of callbacks to notify MoveCList(rec->callbacks, cbs); @@ -811,11 +786,12 @@ nsHostResolver::OnLookupComplete(nsHostRecord *rec, nsresult status, PRAddrInfo // update record fields. We might have a rec->addr_info already if a // previous lookup result expired and we're reresolving it.. PRAddrInfo *old_addr_info; - PR_Lock(rec->addr_info_lock); - old_addr_info = rec->addr_info; - rec->addr_info = result; - rec->addr_info_gencnt++; - PR_Unlock(rec->addr_info_lock); + { + MutexAutoLock lock(*rec->addr_info_lock); + old_addr_info = rec->addr_info; + rec->addr_info = result; + rec->addr_info_gencnt++; + } if (old_addr_info) PR_FreeAddrInfo(old_addr_info); rec->expiration = NowInMinutes(); diff --git a/netwerk/dns/nsHostResolver.h b/netwerk/dns/nsHostResolver.h index f3eb33fe921..7c74f89e89d 100644 --- a/netwerk/dns/nsHostResolver.h +++ b/netwerk/dns/nsHostResolver.h @@ -40,10 +40,11 @@ #include "nscore.h" #include "nsAtomicRefcnt.h" -#include "prcvar.h" #include "prclist.h" #include "prnetdb.h" #include "pldhash.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" #include "nsISupportsImpl.h" class nsHostResolver; @@ -85,6 +86,8 @@ struct nsHostKey */ class nsHostRecord : public PRCList, public nsHostKey { + typedef mozilla::Mutex Mutex; + public: NS_DECL_REFCOUNTED_THREADSAFE(nsHostRecord) @@ -108,7 +111,7 @@ public: * the other threads just read it. therefore the resolver worker * thread doesn't need to lock when reading |addr_info|. */ - PRLock *addr_info_lock; + Mutex *addr_info_lock; int addr_info_gencnt; /* generation count of |addr_info| */ PRAddrInfo *addr_info; PRNetAddr *addr; @@ -171,6 +174,9 @@ public: */ class nsHostResolver { + typedef mozilla::CondVar CondVar; + typedef mozilla::Mutex Mutex; + public: /** * host resolver instances are reference counted. @@ -247,8 +253,8 @@ private: PRUint32 mMaxCacheEntries; PRUint32 mMaxCacheLifetime; - PRLock *mLock; - PRCondVar *mIdleThreadCV; // non-null if idle thread + Mutex mLock; + CondVar mIdleThreadCV; PRUint32 mNumIdleThreads; PRUint32 mThreadCount; PRUint32 mActiveAnyThreadCount; diff --git a/netwerk/protocol/ftp/nsFTPChannel.h b/netwerk/protocol/ftp/nsFTPChannel.h index b30e6443c2d..95c32f01c53 100644 --- a/netwerk/protocol/ftp/nsFTPChannel.h +++ b/netwerk/protocol/ftp/nsFTPChannel.h @@ -55,7 +55,6 @@ #include "nsFtpConnectionThread.h" #include "netCore.h" #include "nsIStreamListener.h" -#include "nsAutoLock.h" #include "nsIFTPChannel.h" #include "nsIUploadChannel.h" #include "nsIProxyInfo.h" diff --git a/netwerk/protocol/ftp/nsFtpConnectionThread.h b/netwerk/protocol/ftp/nsFtpConnectionThread.h index 499d689bad6..f8dc0440f0e 100644 --- a/netwerk/protocol/ftp/nsFtpConnectionThread.h +++ b/netwerk/protocol/ftp/nsFtpConnectionThread.h @@ -60,7 +60,6 @@ #include "nsCOMPtr.h" #include "nsIAsyncInputStream.h" #include "nsIOutputStream.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsIPrompt.h" #include "nsITransport.h" diff --git a/netwerk/protocol/ftp/nsFtpControlConnection.h b/netwerk/protocol/ftp/nsFtpControlConnection.h index 3921107681a..7a162074586 100644 --- a/netwerk/protocol/ftp/nsFtpControlConnection.h +++ b/netwerk/protocol/ftp/nsFtpControlConnection.h @@ -47,7 +47,6 @@ #include "nsISocketTransport.h" #include "nsIOutputStream.h" #include "nsIAsyncInputStream.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsString.h" diff --git a/netwerk/protocol/http/nsHttp.cpp b/netwerk/protocol/http/nsHttp.cpp index aa3858e7985..ca32c3e2abc 100644 --- a/netwerk/protocol/http/nsHttp.cpp +++ b/netwerk/protocol/http/nsHttp.cpp @@ -38,8 +38,8 @@ * ***** END LICENSE BLOCK ***** */ #include "nsHttp.h" -#include "nsAutoLock.h" #include "pldhash.h" +#include "mozilla/Mutex.h" #include "nsCRT.h" #include "prbit.h" @@ -60,6 +60,8 @@ enum { }; #undef HTTP_ATOM +using namespace mozilla; + // we keep a linked list of atoms allocated on the heap for easy clean up when // the atom table is destroyed. The structure and value string are allocated // as one contiguous block. @@ -71,7 +73,7 @@ struct HttpHeapAtom { static struct PLDHashTable sAtomTable = {0}; static struct HttpHeapAtom *sHeapAtoms = nsnull; -static PRLock *sLock = nsnull; +static Mutex *sLock = nsnull; HttpHeapAtom * NewHeapAtom(const char *value) { @@ -129,9 +131,7 @@ nsHttp::CreateAtomTable() NS_ASSERTION(!sAtomTable.ops, "atom table already initialized"); if (!sLock) { - sLock = nsAutoLock::NewLock("nsHttp::sLock"); - if (!sLock) - return NS_ERROR_OUT_OF_MEMORY; + sLock = new Mutex("nsHttp.sLock"); } // The capacity for this table is initialized to a value greater than the @@ -179,7 +179,7 @@ nsHttp::DestroyAtomTable() } if (sLock) { - nsAutoLock::DestroyLock(sLock); + delete sLock; sLock = nsnull; } } @@ -193,7 +193,7 @@ nsHttp::ResolveAtom(const char *str) if (!str || !sAtomTable.ops) return atom; - nsAutoLock lock(sLock); + MutexAutoLock lock(*sLock); PLDHashEntryStub *stub = reinterpret_cast (PL_DHashTableOperate(&sAtomTable, str, PL_DHASH_ADD)); diff --git a/netwerk/protocol/http/nsHttpActivityDistributor.cpp b/netwerk/protocol/http/nsHttpActivityDistributor.cpp index 1f06fa3999d..42a71020bcd 100644 --- a/netwerk/protocol/http/nsHttpActivityDistributor.cpp +++ b/netwerk/protocol/http/nsHttpActivityDistributor.cpp @@ -38,10 +38,11 @@ #include "nsIChannel.h" #include "nsCOMPtr.h" #include "nsAutoPtr.h" -#include "nsAutoLock.h" #include "nsNetUtil.h" #include "nsThreadUtils.h" +using namespace mozilla; + class nsHttpActivityEvent : public nsRunnable { public: @@ -91,14 +92,12 @@ NS_IMPL_THREADSAFE_ISUPPORTS2(nsHttpActivityDistributor, nsIHttpActivityObserver) nsHttpActivityDistributor::nsHttpActivityDistributor() - : mLock(nsnull) + : mLock("nsHttpActivityDistributor.mLock") { } nsHttpActivityDistributor::~nsHttpActivityDistributor() { - if (mLock) - nsAutoLock::DestroyLock(mLock); } NS_IMETHODIMP @@ -111,7 +110,7 @@ nsHttpActivityDistributor::ObserveActivity(nsISupports *aHttpChannel, { nsRefPtr event; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mObservers.Count()) return NS_OK; @@ -129,7 +128,7 @@ NS_IMETHODIMP nsHttpActivityDistributor::GetIsActive(PRBool *isActive) { NS_ENSURE_ARG_POINTER(isActive); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); *isActive = !!mObservers.Count(); return NS_OK; } @@ -137,7 +136,7 @@ nsHttpActivityDistributor::GetIsActive(PRBool *isActive) NS_IMETHODIMP nsHttpActivityDistributor::AddObserver(nsIHttpActivityObserver *aObserver) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mObservers.AppendObject(aObserver)) return NS_ERROR_OUT_OF_MEMORY; @@ -148,22 +147,10 @@ nsHttpActivityDistributor::AddObserver(nsIHttpActivityObserver *aObserver) NS_IMETHODIMP nsHttpActivityDistributor::RemoveObserver(nsIHttpActivityObserver *aObserver) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mObservers.RemoveObject(aObserver)) return NS_ERROR_FAILURE; return NS_OK; } - -nsresult -nsHttpActivityDistributor::Init() -{ - NS_ENSURE_TRUE(!mLock, NS_ERROR_ALREADY_INITIALIZED); - - mLock = nsAutoLock::NewLock("nsHttpActivityDistributor::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - - return NS_OK; -} diff --git a/netwerk/protocol/http/nsHttpActivityDistributor.h b/netwerk/protocol/http/nsHttpActivityDistributor.h index 87c8cef2404..e02f63a7db1 100644 --- a/netwerk/protocol/http/nsHttpActivityDistributor.h +++ b/netwerk/protocol/http/nsHttpActivityDistributor.h @@ -39,7 +39,7 @@ #include "nsIHttpActivityObserver.h" #include "nsCOMArray.h" -#include "prlock.h" +#include "mozilla/Mutex.h" class nsHttpActivityDistributor : public nsIHttpActivityDistributor { @@ -50,11 +50,10 @@ public: nsHttpActivityDistributor(); virtual ~nsHttpActivityDistributor(); - nsresult Init(); protected: nsCOMArray mObservers; - PRLock *mLock; + mozilla::Mutex mLock; }; #endif // nsHttpActivityDistributor_h__ diff --git a/netwerk/protocol/http/nsHttpConnection.cpp b/netwerk/protocol/http/nsHttpConnection.cpp index ae87851f080..4719caa7d5f 100644 --- a/netwerk/protocol/http/nsHttpConnection.cpp +++ b/netwerk/protocol/http/nsHttpConnection.cpp @@ -50,7 +50,6 @@ #include "nsStringStream.h" #include "netCore.h" #include "nsNetCID.h" -#include "nsAutoLock.h" #include "prmem.h" #ifdef DEBUG diff --git a/netwerk/protocol/http/nsHttpConnection.h b/netwerk/protocol/http/nsHttpConnection.h index 4008d0076f1..5812cdf3377 100644 --- a/netwerk/protocol/http/nsHttpConnection.h +++ b/netwerk/protocol/http/nsHttpConnection.h @@ -45,7 +45,6 @@ #include "nsAHttpTransaction.h" #include "nsXPIDLString.h" #include "nsCOMPtr.h" -#include "prlock.h" #include "nsAutoPtr.h" #include "nsIStreamListener.h" diff --git a/netwerk/protocol/http/nsHttpConnectionMgr.cpp b/netwerk/protocol/http/nsHttpConnectionMgr.cpp index c74f2162987..06ebca06947 100644 --- a/netwerk/protocol/http/nsHttpConnectionMgr.cpp +++ b/netwerk/protocol/http/nsHttpConnectionMgr.cpp @@ -40,7 +40,6 @@ #include "nsHttpConnection.h" #include "nsHttpPipeline.h" #include "nsHttpHandler.h" -#include "nsAutoLock.h" #include "nsNetCID.h" #include "nsCOMPtr.h" #include "nsNetUtil.h" @@ -49,6 +48,8 @@ #include "nsIObserverService.h" +using namespace mozilla; + // defined by the socket transport service while active extern PRThread *gSocketThread; @@ -80,7 +81,7 @@ InsertTransactionSorted(nsTArray &pendingQ, nsHttpTransactio nsHttpConnectionMgr::nsHttpConnectionMgr() : mRef(0) - , mMonitor(nsAutoMonitor::NewMonitor("nsHttpConnectionMgr")) + , mMonitor("nsHttpConnectionMgr.mMonitor") , mMaxConns(0) , mMaxConnsPerHost(0) , mMaxConnsPerProxy(0) @@ -97,9 +98,6 @@ nsHttpConnectionMgr::nsHttpConnectionMgr() nsHttpConnectionMgr::~nsHttpConnectionMgr() { LOG(("Destroying nsHttpConnectionMgr @%x\n", this)); - - if (mMonitor) - nsAutoMonitor::DestroyMonitor(mMonitor); } nsresult @@ -117,7 +115,7 @@ nsHttpConnectionMgr::EnsureSocketThreadTargetIfOnline() } } - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); // do nothing if already initialized or if we've shut down if (mSocketThreadTarget || mIsShuttingDown) @@ -140,7 +138,7 @@ nsHttpConnectionMgr::Init(PRUint16 maxConns, LOG(("nsHttpConnectionMgr::Init\n")); { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mMaxConns = maxConns; mMaxConnsPerHost = maxConnsPerHost; @@ -161,7 +159,7 @@ nsHttpConnectionMgr::Shutdown() { LOG(("nsHttpConnectionMgr::Shutdown\n")); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); // do nothing if already shutdown if (!mSocketThreadTarget) @@ -194,7 +192,7 @@ nsHttpConnectionMgr::PostEvent(nsConnEventHandler handler, PRInt32 iparam, void // care of initializing the socket thread target if that's the case. EnsureSocketThreadTargetIfOnline(); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); nsresult rv; if (!mSocketThreadTarget) { @@ -319,7 +317,7 @@ nsHttpConnectionMgr::GetSocketThreadTarget(nsIEventTarget **target) // care of initializing the socket thread target if that's the case. EnsureSocketThreadTargetIfOnline(); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); NS_IF_ADDREF(*target = mSocketThreadTarget); return NS_OK; } @@ -877,7 +875,7 @@ nsHttpConnectionMgr::OnMsgShutdown(PRInt32, void *) mCT.Reset(ShutdownPassCB, this); // signal shutdown complete - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mon.Notify(); } diff --git a/netwerk/protocol/http/nsHttpConnectionMgr.h b/netwerk/protocol/http/nsHttpConnectionMgr.h index 569ed8d7efe..2aede2faca2 100644 --- a/netwerk/protocol/http/nsHttpConnectionMgr.h +++ b/netwerk/protocol/http/nsHttpConnectionMgr.h @@ -46,7 +46,7 @@ #include "nsThreadUtils.h" #include "nsHashtable.h" #include "nsAutoPtr.h" -#include "prmon.h" +#include "mozilla/Monitor.h" #include "nsIObserver.h" #include "nsITimer.h" @@ -187,7 +187,7 @@ private: //------------------------------------------------------------------------- PRInt32 mRef; - PRMonitor *mMonitor; + mozilla::Monitor mMonitor; nsCOMPtr mSocketThreadTarget; // connection limits diff --git a/netwerk/protocol/http/nsHttpHandler.cpp b/netwerk/protocol/http/nsHttpHandler.cpp index fe91f80ca01..22ecc506e57 100644 --- a/netwerk/protocol/http/nsHttpHandler.cpp +++ b/netwerk/protocol/http/nsHttpHandler.cpp @@ -69,7 +69,6 @@ #include "nsPrintfCString.h" #include "nsCOMPtr.h" #include "nsNetCID.h" -#include "nsAutoLock.h" #include "prprf.h" #include "nsReadableUtils.h" #include "nsQuickSort.h" diff --git a/netwerk/protocol/http/nsHttpPipeline.cpp b/netwerk/protocol/http/nsHttpPipeline.cpp index bc0fccc6a6a..9e6b1fb2b52 100644 --- a/netwerk/protocol/http/nsHttpPipeline.cpp +++ b/netwerk/protocol/http/nsHttpPipeline.cpp @@ -47,7 +47,6 @@ #include "nsIPipe.h" #include "nsCOMPtr.h" #include "nsComponentManagerUtils.h" -#include "nsAutoLock.h" #ifdef DEBUG #include "prthread.h" diff --git a/netwerk/protocol/http/nsHttpTransaction.cpp b/netwerk/protocol/http/nsHttpTransaction.cpp index f991138a2dc..53b8970c272 100644 --- a/netwerk/protocol/http/nsHttpTransaction.cpp +++ b/netwerk/protocol/http/nsHttpTransaction.cpp @@ -53,7 +53,6 @@ #include "nsNetUtil.h" #include "nsProxyRelease.h" #include "nsIOService.h" -#include "nsAutoLock.h" #include "nsAtomicRefcnt.h" #include "nsISeekableStream.h" diff --git a/netwerk/protocol/res/nsResProtocolHandler.cpp b/netwerk/protocol/res/nsResProtocolHandler.cpp index 37617b52c2e..8dbdf153928 100644 --- a/netwerk/protocol/res/nsResProtocolHandler.cpp +++ b/netwerk/protocol/res/nsResProtocolHandler.cpp @@ -43,7 +43,6 @@ #endif #include "nsResProtocolHandler.h" -#include "nsAutoLock.h" #include "nsIURL.h" #include "nsIIOService.h" #include "nsIServiceManager.h" diff --git a/netwerk/wifi/nsWifiMonitor.cpp b/netwerk/wifi/nsWifiMonitor.cpp index 5f34595af5d..400273c68c6 100644 --- a/netwerk/wifi/nsWifiMonitor.cpp +++ b/netwerk/wifi/nsWifiMonitor.cpp @@ -43,7 +43,6 @@ #include "nsThreadUtils.h" #include "nsXPCOM.h" #include "nsXPCOMCID.h" -#include "nsAutoLock.h" #include "nsIObserver.h" #include "nsIObserverService.h" #include "nsWifiMonitor.h" @@ -53,6 +52,8 @@ #include "nsComponentManagerUtils.h" #include "mozilla/Services.h" +using namespace mozilla; + #if defined(PR_LOGGING) PRLogModuleInfo *gWifiMonitorLog; #endif @@ -64,13 +65,12 @@ NS_IMPL_THREADSAFE_ISUPPORTS3(nsWifiMonitor, nsWifiMonitor::nsWifiMonitor() : mKeepGoing(PR_TRUE) +, mMonitor("nsWifiMonitor.mMonitor") { #if defined(PR_LOGGING) gWifiMonitorLog = PR_NewLogModule("WifiMonitor"); #endif - mMonitor = nsAutoMonitor::NewMonitor("nsWifiMonitor"); - nsCOMPtr obsSvc = mozilla::services::GetObserverService(); if (obsSvc) obsSvc->AddObserver(this, "xpcom-shutdown", PR_FALSE); @@ -80,8 +80,6 @@ nsWifiMonitor::nsWifiMonitor() nsWifiMonitor::~nsWifiMonitor() { - if (mMonitor) - nsAutoMonitor::DestroyMonitor(mMonitor); } NS_IMETHODIMP @@ -92,7 +90,7 @@ nsWifiMonitor::Observe(nsISupports *subject, const char *topic, LOG(("Shutting down\n")); mKeepGoing = PR_FALSE; - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mon.Notify(); } return NS_OK; @@ -111,7 +109,7 @@ NS_IMETHODIMP nsWifiMonitor::StartWatching(nsIWifiListener *aListener) return rv; } - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mKeepGoing = PR_TRUE; @@ -129,7 +127,7 @@ NS_IMETHODIMP nsWifiMonitor::StopWatching(nsIWifiListener *aListener) LOG(("removing listener\n")); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); for (PRUint32 i = 0; i < mListeners.Length(); i++) { diff --git a/netwerk/wifi/nsWifiMonitor.h b/netwerk/wifi/nsWifiMonitor.h index 9e835777576..6def1bf6142 100644 --- a/netwerk/wifi/nsWifiMonitor.h +++ b/netwerk/wifi/nsWifiMonitor.h @@ -40,12 +40,11 @@ #include "nsIWifiMonitor.h" #include "nsCOMPtr.h" #include "nsAutoPtr.h" -#include "nsAutoLock.h" #include "nsIThread.h" #include "nsIRunnable.h" #include "nsCOMArray.h" #include "nsIWifiMonitor.h" -#include "prmon.h" +#include "mozilla/Monitor.h" #include "prlog.h" #include "nsIObserver.h" #include "nsTArray.h" @@ -98,7 +97,7 @@ class nsWifiMonitor : nsIRunnable, nsIWifiMonitor, nsIObserver nsTArray mListeners; - PRMonitor* mMonitor; + mozilla::Monitor mMonitor; }; diff --git a/netwerk/wifi/nsWifiScannerMac.cpp b/netwerk/wifi/nsWifiScannerMac.cpp index ebe16ba8f44..1e43d731d2d 100644 --- a/netwerk/wifi/nsWifiScannerMac.cpp +++ b/netwerk/wifi/nsWifiScannerMac.cpp @@ -53,6 +53,8 @@ #include "nsComponentManagerUtils.h" #include "nsIMutableArray.h" +using namespace mozilla; + // defined in osx_corewlan.mm // basically relaces accesspoints in the passed reference // it lives in a separate file so that we can use objective c. @@ -75,7 +77,7 @@ nsWifiMonitor::DoScanWithCoreWLAN() nsCOMArray currentListeners; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); for (PRUint32 i = 0; i < mListeners.Length(); i++) { if (!mListeners[i].mHasSentData || accessPointsChanged) { @@ -125,7 +127,7 @@ nsWifiMonitor::DoScanWithCoreWLAN() // wait for some reasonable amount of time. pref? LOG(("waiting on monitor\n")); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mon.Wait(PR_SecondsToInterval(60)); } while (mKeepGoing); @@ -210,7 +212,7 @@ nsWifiMonitor::DoScanOld() nsCOMArray currentListeners; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); for (PRUint32 i = 0; i < mListeners.Length(); i++) { if (!mListeners[i].mHasSentData || accessPointsChanged) { @@ -261,7 +263,7 @@ nsWifiMonitor::DoScanOld() // wait for some reasonable amount of time. pref? LOG(("waiting on monitor\n")); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mon.Wait(PR_SecondsToInterval(60)); } while (mKeepGoing); diff --git a/netwerk/wifi/nsWifiScannerUnix.cpp b/netwerk/wifi/nsWifiScannerUnix.cpp index 98e6a91c092..9ba6d019d1d 100644 --- a/netwerk/wifi/nsWifiScannerUnix.cpp +++ b/netwerk/wifi/nsWifiScannerUnix.cpp @@ -41,7 +41,6 @@ #include "dlfcn.h" -#include "nsAutoPtr.h" #include "nsWifiMonitor.h" #include "nsWifiAccessPoint.h" @@ -50,7 +49,7 @@ #include "nsComponentManagerUtils.h" #include "nsIMutableArray.h" - +using namespace mozilla; typedef int (*iw_open_t)(void); @@ -171,7 +170,7 @@ nsWifiMonitor::DoScan() nsCOMArray currentListeners; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); for (PRUint32 i = 0; i < mListeners.Length(); i++) { if (!mListeners[i].mHasSentData || accessPointsChanged) { @@ -221,7 +220,7 @@ nsWifiMonitor::DoScan() LOG(("waiting on monitor\n")); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mon.Wait(PR_SecondsToInterval(60)); } diff --git a/netwerk/wifi/nsWifiScannerWin.cpp b/netwerk/wifi/nsWifiScannerWin.cpp index 063af535714..1a0436ef383 100644 --- a/netwerk/wifi/nsWifiScannerWin.cpp +++ b/netwerk/wifi/nsWifiScannerWin.cpp @@ -46,7 +46,6 @@ #include "winioctl.h" #include "stdlib.h" -#include "nsAutoPtr.h" #include "nsWifiMonitor.h" #include "nsWifiAccessPoint.h" @@ -55,6 +54,8 @@ #include "nsComponentManagerUtils.h" #include "nsIMutableArray.h" +using namespace mozilla; + nsresult nsWifiMonitor::DoScan() { @@ -153,7 +154,7 @@ nsWifiMonitor::DoScan() nsCOMArray currentListeners; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); for (PRUint32 i = 0; i < mListeners.Length(); i++) { if (!mListeners[i].mHasSentData || accessPointsChanged) { @@ -201,7 +202,7 @@ nsWifiMonitor::DoScan() // wait for some reasonable amount of time. pref? LOG(("waiting on monitor\n")); - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); mon.Wait(PR_SecondsToInterval(60)); } while (mKeepGoing); diff --git a/parser/htmlparser/src/nsParser.cpp b/parser/htmlparser/src/nsParser.cpp index 0f93771253a..f4fc3ae3da3 100644 --- a/parser/htmlparser/src/nsParser.cpp +++ b/parser/htmlparser/src/nsParser.cpp @@ -54,7 +54,6 @@ #include "prenv.h" #include "prlock.h" #include "prcvar.h" -#include "nsAutoLock.h" #include "nsParserCIID.h" #include "nsReadableUtils.h" #include "nsCOMPtr.h" @@ -73,6 +72,10 @@ #include "nsXPCOMCIDInternal.h" #include "nsMimeTypes.h" #include "nsViewSourceHTML.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" + +using namespace mozilla; #define NS_PARSER_FLAG_PARSER_ENABLED 0x00000002 #define NS_PARSER_FLAG_OBSERVERS_ENABLED 0x00000004 @@ -198,8 +201,8 @@ private: class nsSpeculativeScriptThread : public nsIRunnable { public: nsSpeculativeScriptThread() - : mLock(nsAutoLock::DestroyLock), - mCVar(PR_DestroyCondVar), + : mLock("nsSpeculativeScriptThread.mLock"), + mCVar(mLock, "nsSpeculativeScriptThread.mCVar"), mKeepParsing(PR_FALSE), mCurrentlyParsing(PR_FALSE), mNumConsumed(0), @@ -268,8 +271,8 @@ private: // The following members are shared across the main thread and the // speculatively parsing thread. - Holder mLock; - Holder mCVar; + Mutex mLock; + CondVar mCVar; volatile PRBool mKeepParsing; volatile PRBool mCurrentlyParsing; @@ -412,10 +415,10 @@ nsSpeculativeScriptThread::Run() } { - nsAutoLock al(mLock.get()); + MutexAutoLock al(mLock); mCurrentlyParsing = PR_FALSE; - PR_NotifyCondVar(mCVar.get()); + mCVar.Notify(); } return NS_OK; } @@ -442,17 +445,7 @@ nsSpeculativeScriptThread::StartParsing(nsParser *aParser) nsAutoString toScan; CParserContext *context = aParser->PeekContext(); - if (!mLock.get()) { - mLock = nsAutoLock::NewLock("nsSpeculativeScriptThread::mLock"); - if (!mLock.get()) { - return NS_ERROR_OUT_OF_MEMORY; - } - - mCVar = PR_NewCondVar(mLock.get()); - if (!mCVar.get()) { - return NS_ERROR_OUT_OF_MEMORY; - } - + if (!mTokenizer) { if (!mPreloadedURIs.Init(15)) { return NS_ERROR_OUT_OF_MEMORY; } @@ -519,17 +512,12 @@ nsSpeculativeScriptThread::StopParsing(PRBool /*aFromDocWrite*/) { NS_ASSERTION(NS_IsMainThread(), "Can't stop parsing from another thread"); - if (!mLock.get()) { - // If we bailed early out of StartParsing, don't do anything. - return; - } - { - nsAutoLock al(mLock.get()); + MutexAutoLock al(mLock); mKeepParsing = PR_FALSE; if (mCurrentlyParsing) { - PR_WaitCondVar(mCVar.get(), PR_INTERVAL_NO_TIMEOUT); + mCVar.Wait(); NS_ASSERTION(!mCurrentlyParsing, "Didn't actually stop parsing?"); } } diff --git a/security/manager/boot/src/nsSecureBrowserUIImpl.cpp b/security/manager/boot/src/nsSecureBrowserUIImpl.cpp index b6aad66ce6c..d9cb52b4670 100644 --- a/security/manager/boot/src/nsSecureBrowserUIImpl.cpp +++ b/security/manager/boot/src/nsSecureBrowserUIImpl.cpp @@ -85,7 +85,8 @@ #include "nsNetUtil.h" #include "nsNetCID.h" #include "nsCRT.h" -#include "nsAutoLock.h" + +using namespace mozilla; #define SECURITY_STRING_BUNDLE_URL "chrome://pipnss/locale/security.properties" @@ -159,7 +160,8 @@ class nsAutoAtomic { #endif nsSecureBrowserUIImpl::nsSecureBrowserUIImpl() - : mNotifiedSecurityState(lis_no_security) + : mMonitor("nsSecureBrowserUIImpl.mMonitor") + , mNotifiedSecurityState(lis_no_security) , mNotifiedToplevelIsEV(PR_FALSE) , mNewToplevelSecurityState(STATE_IS_INSECURE) , mNewToplevelIsEV(PR_FALSE) @@ -173,7 +175,6 @@ nsSecureBrowserUIImpl::nsSecureBrowserUIImpl() , mOnStateLocationChangeReentranceDetection(0) #endif { - mMonitor = nsAutoMonitor::NewMonitor("security.secureBrowserUIImplMonitor"); mTransferringRequests.ops = nsnull; ResetStateTracking(); @@ -189,8 +190,6 @@ nsSecureBrowserUIImpl::~nsSecureBrowserUIImpl() PL_DHashTableFinish(&mTransferringRequests); mTransferringRequests.ops = nsnull; } - if (mMonitor) - nsAutoMonitor::DestroyMonitor(mMonitor); } NS_IMPL_THREADSAFE_ISUPPORTS6(nsSecureBrowserUIImpl, @@ -278,7 +277,7 @@ nsSecureBrowserUIImpl::Init(nsIDOMWindow *aWindow) NS_IMETHODIMP nsSecureBrowserUIImpl::GetState(PRUint32* aState) { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); return MapInternalToExternalState(aState, mNotifiedSecurityState, mNotifiedToplevelIsEV); } @@ -342,7 +341,7 @@ nsSecureBrowserUIImpl::GetTooltipText(nsAString& aText) nsXPIDLString tooltip; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); state = mNotifiedSecurityState; tooltip = mInfoTooltip; } @@ -461,7 +460,7 @@ nsSecureBrowserUIImpl::Notify(nsIDOMHTMLFormElement* aDOMForm, nsCOMPtr window; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); window = do_QueryReferent(mWindow); NS_ASSERTION(window, "Window has gone away?!"); } @@ -497,7 +496,7 @@ nsSecureBrowserUIImpl::OnProgressChange(nsIWebProgress* aWebProgress, void nsSecureBrowserUIImpl::ResetStateTracking() { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); mInfoTooltip.Truncate(); mDocumentRequestsInProgress = 0; @@ -559,7 +558,7 @@ nsSecureBrowserUIImpl::EvaluateAndUpdateSecurityState(nsIRequest* aRequest, nsIS // see code that is directly above { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); mNewToplevelSecurityStateKnown = PR_TRUE; mNewToplevelSecurityState = temp_NewToplevelSecurityState; mNewToplevelIsEV = temp_NewToplevelIsEV; @@ -592,7 +591,7 @@ nsSecureBrowserUIImpl::UpdateSubrequestMembers(nsISupports *securityInfo) PRUint32 reqState = GetSecurityStateFromSecurityInfo(securityInfo); // the code above this line should run without a lock - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); if (reqState & STATE_IS_SECURE) { if (reqState & STATE_SECURE_LOW || reqState & STATE_SECURE_MED) { @@ -725,7 +724,7 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, nsCOMPtr ioService; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); window = do_QueryReferent(mWindow); NS_ASSERTION(window, "Window has gone away?!"); isViewSource = mIsViewSource; @@ -737,7 +736,7 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, ioService = do_GetService(NS_IOSERVICE_CONTRACTID); if (ioService) { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); mIOService = ioService; } } @@ -1014,7 +1013,7 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, // The listing of a request in mTransferringRequests // means, there has already been data transfered. - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); PL_DHashTableOperate(&mTransferringRequests, aRequest, PL_DHASH_ADD); return NS_OK; @@ -1026,8 +1025,8 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, && aProgressStateFlags & STATE_IS_REQUEST) { - { /* scope for the nsAutoMonitor */ - nsAutoMonitor lock(mMonitor); + { /* scope for the MonitorAutoEnter */ + MonitorAutoEnter lock(mMonitor); PLDHashEntryHdr *entry = PL_DHashTableOperate(&mTransferringRequests, aRequest, PL_DHASH_LOOKUP); if (PL_DHASH_ENTRY_IS_BUSY(entry)) { @@ -1085,7 +1084,7 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, PRInt32 newSubNo = 0; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); inProgress = (mDocumentRequestsInProgress!=0); if (allowSecurityStateChange && !inProgress) @@ -1155,7 +1154,7 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, } { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); if (allowSecurityStateChange && !inProgress) { @@ -1191,7 +1190,7 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, nsCOMPtr temp_ToplevelEventSink; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); temp_DocumentRequestsInProgress = mDocumentRequestsInProgress; if (allowSecurityStateChange) { @@ -1219,7 +1218,7 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, } { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); if (allowSecurityStateChange) { mToplevelEventSink = temp_ToplevelEventSink; @@ -1264,7 +1263,7 @@ nsSecureBrowserUIImpl::OnStateChange(nsIWebProgress* aWebProgress, PRBool temp_NewToplevelSecurityStateKnown; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); temp_NewToplevelSecurityStateKnown = mNewToplevelSecurityStateKnown; } @@ -1310,7 +1309,7 @@ nsresult nsSecureBrowserUIImpl::UpdateSecurityState(nsIRequest* aRequest, // returns true if our overall state has changed and we must send out notifications PRBool nsSecureBrowserUIImpl::UpdateMyFlags(PRBool &showWarning, lockIconState &warnSecurityState) { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); PRBool mustTellTheWorld = PR_FALSE; lockIconState newSecurityState; @@ -1460,7 +1459,7 @@ nsresult nsSecureBrowserUIImpl::TellTheWorld(PRBool showWarning, PRBool temp_NotifiedToplevelIsEV; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); temp_ToplevelEventSink = mToplevelEventSink; temp_NotifiedSecurityState = mNotifiedSecurityState; temp_NotifiedToplevelIsEV = mNotifiedToplevelIsEV; @@ -1547,7 +1546,7 @@ nsSecureBrowserUIImpl::OnLocationChange(nsIWebProgress* aWebProgress, } { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); if (updateIsViewSource) { mIsViewSource = temp_IsViewSource; } @@ -1595,7 +1594,7 @@ nsSecureBrowserUIImpl::OnLocationChange(nsIWebProgress* aWebProgress, PRBool temp_NewToplevelSecurityStateKnown; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); temp_NewToplevelSecurityStateKnown = mNewToplevelSecurityStateKnown; } @@ -1646,7 +1645,7 @@ nsSecureBrowserUIImpl::GetSSLStatus(nsISupports** _result) { NS_ENSURE_ARG_POINTER(_result); - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); switch (mNotifiedSecurityState) { @@ -1698,7 +1697,7 @@ nsSecureBrowserUIImpl::GetBundleString(const PRUnichar* name, nsCOMPtr temp_StringBundle; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); temp_StringBundle = mStringBundle; } @@ -1842,7 +1841,7 @@ ConfirmEnteringSecure() nsCOMPtr window; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); window = do_QueryReferent(mWindow); NS_ASSERTION(window, "Window has gone away?!"); } @@ -1865,7 +1864,7 @@ ConfirmEnteringWeak() nsCOMPtr window; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); window = do_QueryReferent(mWindow); NS_ASSERTION(window, "Window has gone away?!"); } @@ -1888,7 +1887,7 @@ ConfirmLeavingSecure() nsCOMPtr window; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); window = do_QueryReferent(mWindow); NS_ASSERTION(window, "Window has gone away?!"); } @@ -1911,7 +1910,7 @@ ConfirmMixedMode() nsCOMPtr window; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); window = do_QueryReferent(mWindow); NS_ASSERTION(window, "Window has gone away?!"); } @@ -1941,7 +1940,7 @@ ConfirmPostToInsecure() nsCOMPtr window; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); window = do_QueryReferent(mWindow); NS_ASSERTION(window, "Window has gone away?!"); } @@ -1973,7 +1972,7 @@ ConfirmPostToInsecureFromSecure() nsCOMPtr window; { - nsAutoMonitor lock(mMonitor); + MonitorAutoEnter lock(mMonitor); window = do_QueryReferent(mWindow); NS_ASSERTION(window, "Window has gone away?!"); } diff --git a/security/manager/boot/src/nsSecureBrowserUIImpl.h b/security/manager/boot/src/nsSecureBrowserUIImpl.h index f27a05f16a7..dd71bc4eb72 100644 --- a/security/manager/boot/src/nsSecureBrowserUIImpl.h +++ b/security/manager/boot/src/nsSecureBrowserUIImpl.h @@ -42,6 +42,7 @@ #ifndef nsSecureBrowserUIImpl_h_ #define nsSecureBrowserUIImpl_h_ +#include "mozilla/Monitor.h" #include "nsCOMPtr.h" #include "nsXPIDLString.h" #include "nsString.h" @@ -60,7 +61,6 @@ #include "nsISSLStatusProvider.h" #include "nsIAssociatedContentSecurity.h" #include "pldhash.h" -#include "prmon.h" #include "nsINetUtil.h" class nsITransportSecurityInfo; @@ -97,7 +97,7 @@ public: nsIArray* invalidElements) { return NS_OK; }; protected: - PRMonitor *mMonitor; + mozilla::Monitor mMonitor; nsWeakPtr mWindow; nsCOMPtr mIOService; diff --git a/security/manager/ssl/src/nsCertOverrideService.cpp b/security/manager/ssl/src/nsCertOverrideService.cpp index 8a5f7d2870d..9e0da756a07 100644 --- a/security/manager/ssl/src/nsCertOverrideService.cpp +++ b/security/manager/ssl/src/nsCertOverrideService.cpp @@ -52,7 +52,6 @@ #include "nsPromiseFlatString.h" #include "nsProxiedService.h" #include "nsStringBuffer.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nspr.h" #include "pk11pub.h" @@ -63,6 +62,8 @@ #include "nsNSSCleaner.h" NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate) +using namespace mozilla; + static const char kCertOverrideFileName[] = "cert_override.txt"; void @@ -119,14 +120,12 @@ NS_IMPL_THREADSAFE_ISUPPORTS3(nsCertOverrideService, nsISupportsWeakReference) nsCertOverrideService::nsCertOverrideService() + : monitor("nsCertOverrideService.monitor") { - monitor = nsAutoMonitor::NewMonitor("security.certOverrideServiceMonitor"); } nsCertOverrideService::~nsCertOverrideService() { - if (monitor) - nsAutoMonitor::DestroyMonitor(monitor); } nsresult @@ -180,7 +179,7 @@ nsCertOverrideService::Observe(nsISupports *aSubject, // The profile is about to change, // or is going away because the application is shutting down. - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); if (!nsCRT::strcmp(aData, NS_LITERAL_STRING("shutdown-cleanse").get())) { RemoveAllFromMemory(); @@ -197,7 +196,7 @@ nsCertOverrideService::Observe(nsISupports *aSubject, // Now read from the new profile location. // we also need to update the cached file location - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); nsresult rv = NS_GetSpecialDirectory(NS_APP_USER_PROFILE_50_DIR, getter_AddRefs(mSettingsFile)); if (NS_SUCCEEDED(rv)) { @@ -213,7 +212,7 @@ nsCertOverrideService::Observe(nsISupports *aSubject, void nsCertOverrideService::RemoveAllFromMemory() { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); mSettingsTable.Clear(); } @@ -233,7 +232,7 @@ void nsCertOverrideService::RemoveAllTemporaryOverrides() { { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); mSettingsTable.EnumerateEntries(RemoveTemporariesCallback, nsnull); // no need to write, as temporaries are never written to disk } @@ -242,7 +241,7 @@ nsCertOverrideService::RemoveAllTemporaryOverrides() nsresult nsCertOverrideService::Read() { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); nsresult rv; nsCOMPtr fileInputStream; @@ -361,7 +360,7 @@ WriteEntryCallback(nsCertOverrideEntry *aEntry, nsresult nsCertOverrideService::Write() { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); if (!mSettingsFile) { return NS_ERROR_NULL_POINTER; @@ -555,7 +554,7 @@ nsCertOverrideService::RememberValidityOverride(const nsACString & aHostName, PR } { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); AddEntryToList(aHostName, aPort, aTemporary ? aCert : nsnull, // keep a reference to the cert for temporary overrides @@ -594,7 +593,7 @@ nsCertOverrideService::HasMatchingOverride(const nsACString & aHostName, PRInt32 nsCertOverride settings; { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); nsCertOverrideEntry *entry = mSettingsTable.GetEntry(hostPort.get()); if (!entry) @@ -641,7 +640,7 @@ nsCertOverrideService::GetValidityOverride(const nsACString & aHostName, PRInt32 nsCertOverride settings; { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); nsCertOverrideEntry *entry = mSettingsTable.GetEntry(hostPort.get()); if (entry) { @@ -673,7 +672,7 @@ nsCertOverrideService::AddEntryToList(const nsACString &aHostName, PRInt32 aPort GetHostWithPort(aHostName, aPort, hostPort); { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); nsCertOverrideEntry *entry = mSettingsTable.PutEntry(hostPort.get()); if (!entry) { @@ -708,7 +707,7 @@ nsCertOverrideService::ClearValidityOverride(const nsACString & aHostName, PRInt nsCAutoString hostPort; GetHostWithPort(aHostName, aPort, hostPort); { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); mSettingsTable.RemoveEntry(hostPort.get()); Write(); } @@ -838,7 +837,7 @@ nsCertOverrideService::IsCertUsedForOverrides(nsIX509Cert *aCert, cai.mDottedOidForStoringNewHashes = mDottedOidForStoringNewHashes; { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); mSettingsTable.EnumerateEntries(FindMatchingCertCallback, &cai); } *_retval = cai.counter; @@ -904,7 +903,7 @@ nsCertOverrideService::EnumerateCertOverrides(nsIX509Cert *aCert, capac.mDottedOidForStoringNewHashes = mDottedOidForStoringNewHashes; { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); mSettingsTable.EnumerateEntries(EnumerateCertOverridesCallback, &capac); } return NS_OK; diff --git a/security/manager/ssl/src/nsCertOverrideService.h b/security/manager/ssl/src/nsCertOverrideService.h index 8e018483066..acbeb4bc38b 100644 --- a/security/manager/ssl/src/nsCertOverrideService.h +++ b/security/manager/ssl/src/nsCertOverrideService.h @@ -41,12 +41,12 @@ #ifndef __NSCERTOVERRIDESERVICE_H__ #define __NSCERTOVERRIDESERVICE_H__ +#include "mozilla/Monitor.h" #include "nsICertOverrideService.h" #include "nsTHashtable.h" #include "nsIObserver.h" #include "nsString.h" #include "nsIFile.h" -#include "prmon.h" #include "secoidt.h" #include "nsWeakReference.h" @@ -190,7 +190,7 @@ public: static void GetHostWithPort(const nsACString & aHostName, PRInt32 aPort, nsACString& _retval); protected: - PRMonitor *monitor; + mozilla::Monitor monitor; nsCOMPtr mSettingsFile; nsTHashtable mSettingsTable; diff --git a/security/manager/ssl/src/nsCertVerificationThread.cpp b/security/manager/ssl/src/nsCertVerificationThread.cpp index 1cdc2a1e27e..b70d448ce69 100644 --- a/security/manager/ssl/src/nsCertVerificationThread.cpp +++ b/security/manager/ssl/src/nsCertVerificationThread.cpp @@ -36,10 +36,11 @@ * ***** END LICENSE BLOCK ***** */ #include "nsMemory.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsCertVerificationThread.h" +using namespace mozilla; + nsCertVerificationThread *nsCertVerificationThread::verification_thread_singleton; NS_IMPL_THREADSAFE_ISUPPORTS1(nsCertVerificationResult, nsICertVerificationResult) @@ -115,10 +116,10 @@ nsresult nsCertVerificationThread::addJob(nsBaseVerificationJob *aJob) if (!verification_thread_singleton->mThreadHandle) return NS_ERROR_OUT_OF_MEMORY; - nsAutoLock threadLock(verification_thread_singleton->mMutex); + MutexAutoLock threadLock(verification_thread_singleton->mMutex); verification_thread_singleton->mJobQ.Push(aJob); - PR_NotifyAllCondVar(verification_thread_singleton->mCond); + verification_thread_singleton->mCond.NotifyAll(); return NS_OK; } @@ -130,12 +131,12 @@ void nsCertVerificationThread::Run(void) nsBaseVerificationJob *job = nsnull; { - nsAutoLock threadLock(verification_thread_singleton->mMutex); + MutexAutoLock threadLock(verification_thread_singleton->mMutex); while (!mExitRequested && (0 == verification_thread_singleton->mJobQ.GetSize())) { // no work to do ? let's wait a moment - PR_WaitCondVar(mCond, PR_INTERVAL_NO_TIMEOUT); + mCond.Wait(); } if (mExitRequested) @@ -152,7 +153,7 @@ void nsCertVerificationThread::Run(void) } { - nsAutoLock threadLock(verification_thread_singleton->mMutex); + MutexAutoLock threadLock(verification_thread_singleton->mMutex); while (verification_thread_singleton->mJobQ.GetSize()) { nsCertVerificationJob *job = diff --git a/security/manager/ssl/src/nsClientAuthRemember.cpp b/security/manager/ssl/src/nsClientAuthRemember.cpp index 01d5f9b3c4f..78da1f35e97 100644 --- a/security/manager/ssl/src/nsClientAuthRemember.cpp +++ b/security/manager/ssl/src/nsClientAuthRemember.cpp @@ -48,7 +48,6 @@ #include "nsPromiseFlatString.h" #include "nsProxiedService.h" #include "nsStringBuffer.h" -#include "nsAutoLock.h" #include "nspr.h" #include "pk11pub.h" #include "certdb.h" @@ -56,6 +55,9 @@ #include "ssl.h" // For SSL_ClearSessionCache #include "nsNSSCleaner.h" + +using namespace mozilla; + NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate) NS_IMPL_THREADSAFE_ISUPPORTS2(nsClientAuthRememberService, @@ -63,15 +65,13 @@ NS_IMPL_THREADSAFE_ISUPPORTS2(nsClientAuthRememberService, nsISupportsWeakReference) nsClientAuthRememberService::nsClientAuthRememberService() + : monitor("nsClientAuthRememberService.monitor") { - monitor = nsAutoMonitor::NewMonitor("security.clientAuthRememberServiceMonitor"); } nsClientAuthRememberService::~nsClientAuthRememberService() { RemoveAllFromMemory(); - if (monitor) - nsAutoMonitor::DestroyMonitor(monitor); } nsresult @@ -110,7 +110,7 @@ nsClientAuthRememberService::Observe(nsISupports *aSubject, // The profile is about to change, // or is going away because the application is shutting down. - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); RemoveAllFromMemory(); } @@ -119,7 +119,7 @@ nsClientAuthRememberService::Observe(nsISupports *aSubject, void nsClientAuthRememberService::ClearRememberedDecisions() { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); RemoveAllFromMemory(); } @@ -165,7 +165,7 @@ nsClientAuthRememberService::RememberDecision(const nsACString & aHostName, return rv; { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); if (aClientCert) { nsNSSCertificate pipCert(aClientCert); char *dbkey = NULL; @@ -211,7 +211,7 @@ nsClientAuthRememberService::HasRememberedDecision(const nsACString & aHostName, nsClientAuthRemember settings; { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); nsClientAuthRememberEntry *entry = mSettingsTable.GetEntry(hostCert.get()); if (!entry) return NS_OK; @@ -233,7 +233,7 @@ nsClientAuthRememberService::AddEntryToList(const nsACString &aHostName, GetHostWithCert(aHostName, fingerprint, hostCert); { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); nsClientAuthRememberEntry *entry = mSettingsTable.PutEntry(hostCert.get()); if (!entry) { diff --git a/security/manager/ssl/src/nsClientAuthRemember.h b/security/manager/ssl/src/nsClientAuthRemember.h index cc8d738371d..36a9f16fee6 100644 --- a/security/manager/ssl/src/nsClientAuthRemember.h +++ b/security/manager/ssl/src/nsClientAuthRemember.h @@ -40,6 +40,7 @@ #ifndef __NSCLIENTAUTHREMEMBER_H__ #define __NSCLIENTAUTHREMEMBER_H__ +#include "mozilla/Monitor.h" #include "nsTHashtable.h" #include "nsIObserver.h" #include "nsIX509Cert.h" @@ -47,7 +48,6 @@ #include "nsNSSCertificate.h" #include "nsString.h" #include "nsWeakReference.h" -#include "prmon.h" class nsClientAuthRemember { @@ -163,7 +163,7 @@ public: void ClearRememberedDecisions(); protected: - PRMonitor *monitor; + mozilla::Monitor monitor; nsTHashtable mSettingsTable; void RemoveAllFromMemory(); diff --git a/security/manager/ssl/src/nsKeygenThread.cpp b/security/manager/ssl/src/nsKeygenThread.cpp index 19d7844924f..3f52ceb7b37 100644 --- a/security/manager/ssl/src/nsKeygenThread.cpp +++ b/security/manager/ssl/src/nsKeygenThread.cpp @@ -44,11 +44,13 @@ #include "nsIObserver.h" #include "nsNSSShutDown.h" +using namespace mozilla; + NS_IMPL_THREADSAFE_ISUPPORTS1(nsKeygenThread, nsIKeygenThread) nsKeygenThread::nsKeygenThread() -:mutex(nsnull), +:mutex("nsKeygenThread.mutex"), iAmRunning(PR_FALSE), keygenReady(PR_FALSE), statusDialogClosed(PR_FALSE), @@ -63,14 +65,10 @@ nsKeygenThread::nsKeygenThread() wincx(nsnull), threadHandle(nsnull) { - mutex = PR_NewLock(); } nsKeygenThread::~nsKeygenThread() { - if (mutex) { - PR_DestroyLock(mutex); - } } void nsKeygenThread::SetParams( @@ -82,7 +80,7 @@ void nsKeygenThread::SetParams( void *a_wincx ) { nsNSSShutDownPreventionLock locker; - PR_Lock(mutex); + MutexAutoLock lock(mutex); if (!alreadyReceivedParams) { alreadyReceivedParams = PR_TRUE; @@ -98,8 +96,6 @@ void nsKeygenThread::SetParams( isSensitive = a_isSensitive; wincx = a_wincx; } - - PR_Unlock(mutex); } nsresult nsKeygenThread::GetParams( @@ -111,8 +107,8 @@ nsresult nsKeygenThread::GetParams( } nsresult rv; - - PR_Lock(mutex); + + MutexAutoLock lock(mutex); // GetParams must not be called until thread creator called // Join on this thread. @@ -131,8 +127,6 @@ nsresult nsKeygenThread::GetParams( rv = NS_ERROR_FAILURE; } - PR_Unlock(mutex); - return rv; } @@ -144,9 +138,6 @@ static void PR_CALLBACK nsKeygenThreadRunner(void *arg) nsresult nsKeygenThread::StartKeyGeneration(nsIObserver* aObserver) { - if (!mutex) - return NS_OK; - if (!aObserver) return NS_OK; @@ -157,10 +148,9 @@ nsresult nsKeygenThread::StartKeyGeneration(nsIObserver* aObserver) NS_PROXY_SYNC | NS_PROXY_ALWAYS, getter_AddRefs(obs)); - PR_Lock(mutex); + MutexAutoLock lock(mutex); if (iAmRunning || keygenReady) { - PR_Unlock(mutex); return NS_OK; } @@ -174,8 +164,6 @@ nsresult nsKeygenThread::StartKeyGeneration(nsIObserver* aObserver) // bool thread_started_ok = (threadHandle != nsnull); // we might want to return "thread started ok" to caller in the future NS_ASSERTION(threadHandle, "Could not create nsKeygenThreadRunner thread\n"); - - PR_Unlock(mutex); return NS_OK; } @@ -187,10 +175,7 @@ nsresult nsKeygenThread::UserCanceled(PRBool *threadAlreadyClosedDialog) *threadAlreadyClosedDialog = PR_FALSE; - if (!mutex) - return NS_OK; - - PR_Lock(mutex); + MutexAutoLock lock(mutex); if (keygenReady) *threadAlreadyClosedDialog = statusDialogClosed; @@ -201,8 +186,6 @@ nsresult nsKeygenThread::UserCanceled(PRBool *threadAlreadyClosedDialog) // it again to avoid problems. statusDialogClosed = PR_TRUE; - PR_Unlock(mutex); - return NS_OK; } @@ -211,14 +194,13 @@ void nsKeygenThread::Run(void) nsNSSShutDownPreventionLock locker; PRBool canGenerate = PR_FALSE; - PR_Lock(mutex); - + { + MutexAutoLock lock(mutex); if (alreadyReceivedParams) { canGenerate = PR_TRUE; keygenReady = PR_FALSE; } - - PR_Unlock(mutex); + } if (canGenerate) privateKey = PK11_GenerateKeyPair(slot, keyGenMechanism, @@ -232,7 +214,8 @@ void nsKeygenThread::Run(void) // to care for cleaning this up. nsCOMPtr obs; - PR_Lock(mutex); + { + MutexAutoLock lock(mutex); keygenReady = PR_TRUE; iAmRunning = PR_FALSE; @@ -250,8 +233,7 @@ void nsKeygenThread::Run(void) obs = observer; observer = nsnull; - - PR_Unlock(mutex); + } if (obs) obs->Observe(nsnull, "keygen-finished", nsnull); diff --git a/security/manager/ssl/src/nsKeygenThread.h b/security/manager/ssl/src/nsKeygenThread.h index 93860e4b70d..3ecaa6f1ba4 100644 --- a/security/manager/ssl/src/nsKeygenThread.h +++ b/security/manager/ssl/src/nsKeygenThread.h @@ -42,6 +42,7 @@ #include "keyhi.h" #include "nspr.h" +#include "mozilla/Mutex.h" #include "nsIKeygenThread.h" #include "nsCOMPtr.h" @@ -50,7 +51,7 @@ class nsIObserver; class nsKeygenThread : public nsIKeygenThread { private: - PRLock *mutex; + mozilla::Mutex mutex; nsCOMPtr observer; diff --git a/security/manager/ssl/src/nsNSSCallbacks.cpp b/security/manager/ssl/src/nsNSSCallbacks.cpp index 07a3764e873..58e4e2bc90f 100644 --- a/security/manager/ssl/src/nsNSSCallbacks.cpp +++ b/security/manager/ssl/src/nsNSSCallbacks.cpp @@ -64,7 +64,6 @@ #include "nsIUploadChannel.h" #include "nsSSLThread.h" #include "nsThreadUtils.h" -#include "nsAutoLock.h" #include "nsIThread.h" #include "nsIWindowWatcher.h" #include "nsIPrompt.h" @@ -77,6 +76,8 @@ #include "nssb64.h" #include "secerr.h" +using namespace mozilla; + static NS_DEFINE_CID(kNSSComponentCID, NS_NSSCOMPONENT_CID); NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate) @@ -372,11 +373,8 @@ nsNSSHttpRequestSession::internal_send_receive_attempt(PRBool &retryable_error, if (!mListener) return SECFailure; - if (NS_FAILED(mListener->InitLocks())) - return SECFailure; - - PRLock *waitLock = mListener->mLock; - PRCondVar *waitCondition = mListener->mCondition; + Mutex& waitLock = mListener->mLock; + CondVar& waitCondition = mListener->mCondition; volatile PRBool &waitFlag = mListener->mWaitFlag; waitFlag = PR_TRUE; @@ -398,7 +396,7 @@ nsNSSHttpRequestSession::internal_send_receive_attempt(PRBool &retryable_error, PRBool request_canceled = PR_FALSE; { - nsAutoLock locker(waitLock); + MutexAutoLock locker(waitLock); const PRIntervalTime start_time = PR_IntervalNow(); PRIntervalTime wait_interval; @@ -426,12 +424,11 @@ nsNSSHttpRequestSession::internal_send_receive_attempt(PRBool &retryable_error, // thread manager. Thanks a lot to Christian Biesinger who // made me aware of this possibility. (kaie) - locker.unlock(); + MutexAutoUnlock unlock(waitLock); NS_ProcessNextEvent(nsnull); - locker.lock(); } - PR_WaitCondVar(waitCondition, wait_interval); + waitCondition.Wait(wait_interval); if (!waitFlag) break; @@ -557,8 +554,8 @@ void nsNSSHttpInterface::unregisterHttpClient() nsHTTPListener::nsHTTPListener() : mResultData(nsnull), mResultLen(0), - mLock(nsnull), - mCondition(nsnull), + mLock("nsHTTPListener.mLock"), + mCondition(mLock, "nsHTTPListener.mCondition"), mWaitFlag(PR_TRUE), mResponsibleForDoneSignal(PR_FALSE), mLoadGroup(nsnull), @@ -566,34 +563,11 @@ nsHTTPListener::nsHTTPListener() { } -nsresult nsHTTPListener::InitLocks() -{ - mLock = nsAutoLock::NewLock("nsHttpListener::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - - mCondition = PR_NewCondVar(mLock); - if (!mCondition) - { - nsAutoLock::DestroyLock(mLock); - mLock = nsnull; - return NS_ERROR_OUT_OF_MEMORY; - } - - return NS_OK; -} - nsHTTPListener::~nsHTTPListener() { if (mResponsibleForDoneSignal) send_done_signal(); - if (mCondition) - PR_DestroyCondVar(mCondition); - - if (mLock) - nsAutoLock::DestroyLock(mLock); - if (mLoader) { nsCOMPtr mainThread(do_GetMainThread()); NS_ProxyRelease(mainThread, mLoader); @@ -607,18 +581,16 @@ nsHTTPListener::FreeLoadGroup(PRBool aCancelLoad) { nsILoadGroup *lg = nsnull; - if (mLock) { - nsAutoLock locker(mLock); + MutexAutoLock locker(mLock); - if (mLoadGroup) { - if (mLoadGroupOwnerThread != PR_GetCurrentThread()) { - NS_ASSERTION(PR_FALSE, - "attempt to access nsHTTPDownloadEvent::mLoadGroup on multiple threads, leaking it!"); - } - else { - lg = mLoadGroup; - mLoadGroup = nsnull; - } + if (mLoadGroup) { + if (mLoadGroupOwnerThread != PR_GetCurrentThread()) { + NS_ASSERTION(PR_FALSE, + "attempt to access nsHTTPDownloadEvent::mLoadGroup on multiple threads, leaking it!"); + } + else { + lg = mLoadGroup; + mLoadGroup = nsnull; } } @@ -688,9 +660,9 @@ void nsHTTPListener::send_done_signal() mResponsibleForDoneSignal = PR_FALSE; { - nsAutoLock locker(mLock); + MutexAutoLock locker(mLock); mWaitFlag = PR_FALSE; - PR_NotifyAllCondVar(mCondition); + mCondition.NotifyAll(); } } diff --git a/security/manager/ssl/src/nsNSSCallbacks.h b/security/manager/ssl/src/nsNSSCallbacks.h index 5ac7d6a4b89..fd4481e5b10 100644 --- a/security/manager/ssl/src/nsNSSCallbacks.h +++ b/security/manager/ssl/src/nsNSSCallbacks.h @@ -45,6 +45,8 @@ #include "nspr.h" #include "ocspt.h" #include "nsIStreamLoader.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" char* PR_CALLBACK PK11PasswordPrompt(PK11SlotInfo *slot, PRBool retry, void* arg); @@ -81,10 +83,8 @@ public: const PRUint8* mResultData; // not owned, refers to mLoader PRUint32 mResultLen; - nsresult InitLocks(); - - PRLock *mLock; - PRCondVar *mCondition; + mozilla::Mutex mLock; + mozilla::CondVar mCondition; volatile PRBool mWaitFlag; PRBool mResponsibleForDoneSignal; diff --git a/security/manager/ssl/src/nsNSSCertCache.cpp b/security/manager/ssl/src/nsNSSCertCache.cpp index 789d50a6b40..1d8d2fed34c 100644 --- a/security/manager/ssl/src/nsNSSCertCache.cpp +++ b/security/manager/ssl/src/nsNSSCertCache.cpp @@ -36,18 +36,18 @@ #include "nsNSSCertCache.h" #include "nsNSSCertificate.h" -#include "nsAutoLock.h" #include "cert.h" #include "nsCOMPtr.h" #include "nsIInterfaceRequestor.h" #include "nsNSSHelper.h" +using namespace mozilla; + NS_IMPL_THREADSAFE_ISUPPORTS1(nsNSSCertCache, nsINSSCertCache) nsNSSCertCache::nsNSSCertCache() -:mCertList(nsnull) +:mutex("nsNSSCertCache.mutex"), mCertList(nsnull) { - mutex = nsAutoLock::NewLock("nsNSSCertCache::mutex"); } nsNSSCertCache::~nsNSSCertCache() @@ -69,11 +69,6 @@ void nsNSSCertCache::destructorSafeDestroyNSSReference() { if (isAlreadyShutDown()) return; - - if (mutex) { - nsAutoLock::DestroyLock(mutex); - mutex = nsnull; - } } NS_IMETHODIMP @@ -88,7 +83,7 @@ nsNSSCertCache::CacheAllCerts() CERTCertList *newList = PK11_ListCerts(PK11CertListUnique, cxt); if (newList) { - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); mCertList = new nsNSSCertList(newList, PR_TRUE); // adopt } @@ -103,7 +98,7 @@ nsNSSCertCache::CacheCertList(nsIX509CertList *list) return NS_ERROR_NOT_AVAILABLE; { - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); mCertList = list; //NS_ADDREF(mCertList); } @@ -119,7 +114,7 @@ nsNSSCertCache::GetX509CachedCerts(nsIX509CertList **list) return NS_ERROR_NOT_AVAILABLE; { - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); if (!mCertList) { return NS_ERROR_NOT_AVAILABLE; } @@ -137,6 +132,6 @@ void* nsNSSCertCache::GetCachedCerts() if (isAlreadyShutDown()) return nsnull; - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); return mCertList->GetRawCertList(); } diff --git a/security/manager/ssl/src/nsNSSCertCache.h b/security/manager/ssl/src/nsNSSCertCache.h index 3eebdf96a87..8af41431a82 100644 --- a/security/manager/ssl/src/nsNSSCertCache.h +++ b/security/manager/ssl/src/nsNSSCertCache.h @@ -40,6 +40,7 @@ #include "nsINSSCertCache.h" #include "nsIX509CertList.h" #include "certt.h" +#include "mozilla/Mutex.h" #include "nsNSSShutDown.h" #include "nsCOMPtr.h" @@ -54,7 +55,7 @@ public: virtual ~nsNSSCertCache(); private: - PRLock *mutex; + mozilla::Mutex mutex; nsCOMPtr mCertList; virtual void virtualDestroyNSSReference(); void destructorSafeDestroyNSSReference(); diff --git a/security/manager/ssl/src/nsNSSCertificate.cpp b/security/manager/ssl/src/nsNSSCertificate.cpp index 03e29a712db..6ec8949cb58 100644 --- a/security/manager/ssl/src/nsNSSCertificate.cpp +++ b/security/manager/ssl/src/nsNSSCertificate.cpp @@ -62,7 +62,6 @@ #include "nsTime.h" #include "nsIProxyObjectManager.h" #include "nsCRT.h" -#include "nsAutoLock.h" #include "nsUsageArrayHelper.h" #include "nsICertificateDialogs.h" #include "nsNSSCertHelper.h" diff --git a/security/manager/ssl/src/nsNSSComponent.cpp b/security/manager/ssl/src/nsNSSComponent.cpp index f17c6eeb6d1..ea53454b6da 100644 --- a/security/manager/ssl/src/nsNSSComponent.cpp +++ b/security/manager/ssl/src/nsNSSComponent.cpp @@ -72,7 +72,6 @@ #include "nsIPrefBranch2.h" #include "nsIDateTimeFormat.h" #include "nsDateTimeFormatCID.h" -#include "nsAutoLock.h" #include "nsIDOMEvent.h" #include "nsIDOMDocument.h" #include "nsIDOMDocumentEvent.h" @@ -133,6 +132,8 @@ extern "C" { #include "p12plcy.h" } +using namespace mozilla; + #ifdef PR_LOGGING PRLogModuleInfo* gPIPNSSLog = nsnull; #endif @@ -368,11 +369,12 @@ PRBool EnsureNSSInitialized(EnsureNSSOperator op) } nsNSSComponent::nsNSSComponent() - :mNSSInitialized(PR_FALSE), mThreadList(nsnull), + :mutex("nsNSSComponent.mutex"), + mNSSInitialized(PR_FALSE), + mCrlTimerLock("nsNSSComponent.mCrlTimerLock"), + mThreadList(nsnull), mSSLThread(NULL), mCertVerificationThread(NULL) { - mutex = nsAutoLock::NewLock("nsNSSComponent::mutex"); - #ifdef PR_LOGGING if (!gPIPNSSLog) gPIPNSSLog = PR_NewLogModule("pipnss"); @@ -382,7 +384,6 @@ nsNSSComponent::nsNSSComponent() crlDownloadTimerOn = PR_FALSE; crlsScheduledForDownload = nsnull; mTimer = nsnull; - mCrlTimerLock = nsnull; mObserversRegistered = PR_FALSE; // In order to keep startup time lower, we delay loading and @@ -415,13 +416,13 @@ nsNSSComponent::~nsNSSComponent() PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsNSSComponent::dtor\n")); if (mUpdateTimerInitialized) { - PR_Lock(mCrlTimerLock); - if (crlDownloadTimerOn) { - mTimer->Cancel(); + { + MutexAutoLock lock(mCrlTimerLock); + if (crlDownloadTimerOn) { + mTimer->Cancel(); + } + crlDownloadTimerOn = PR_FALSE; } - crlDownloadTimerOn = PR_FALSE; - PR_Unlock(mCrlTimerLock); - PR_DestroyLock(mCrlTimerLock); if(crlsScheduledForDownload != nsnull){ crlsScheduledForDownload->Reset(); delete crlsScheduledForDownload; @@ -437,11 +438,6 @@ nsNSSComponent::~nsNSSComponent() --mInstanceCount; delete mShutdownObjectList; - if (mutex) { - nsAutoLock::DestroyLock(mutex); - mutex = nsnull; - } - // We are being freed, drop the haveLoaded flag to re-enable // potential nss initialization later. EnsureNSSInitialized(nssShutdown); @@ -1302,9 +1298,10 @@ nsNSSComponent::Notify(nsITimer *timer) nsresult rv; //Timer has fired. So set the flag accordingly - PR_Lock(mCrlTimerLock); - crlDownloadTimerOn = PR_FALSE; - PR_Unlock(mCrlTimerLock); + { + MutexAutoLock lock(mCrlTimerLock); + crlDownloadTimerOn = PR_FALSE; + } //First, handle this download rv = DownloadCrlSilently(); @@ -1346,8 +1343,7 @@ nsNSSComponent::DefineNextTimer() //This part should be synchronized because this function might be called from separate //threads - //Lock the lock - PR_Lock(mCrlTimerLock); + MutexAutoLock lock(mCrlTimerLock); if (crlDownloadTimerOn) { mTimer->Cancel(); @@ -1356,8 +1352,7 @@ nsNSSComponent::DefineNextTimer() rv = getParamsForNextCrlToDownload(&mDownloadURL, &nextFiring, &mCrlUpdateKey); //If there are no more crls to be updated any time in future if(NS_FAILED(rv)){ - //Free the lock and return - no error - just implies nothing to schedule - PR_Unlock(mCrlTimerLock); + // Return - no error - just implies nothing to schedule return NS_OK; } @@ -1375,11 +1370,8 @@ nsNSSComponent::DefineNextTimer() interval, nsITimer::TYPE_ONE_SHOT); crlDownloadTimerOn = PR_TRUE; - //Release - PR_Unlock(mCrlTimerLock); return NS_OK; - } //Note that the StopCRLUpdateTimer and InitializeCRLUpdateTimer functions should never be called @@ -1396,15 +1388,13 @@ nsNSSComponent::StopCRLUpdateTimer() delete crlsScheduledForDownload; crlsScheduledForDownload = nsnull; } - - PR_Lock(mCrlTimerLock); - if (crlDownloadTimerOn) { - mTimer->Cancel(); + { + MutexAutoLock lock(mCrlTimerLock); + if (crlDownloadTimerOn) { + mTimer->Cancel(); + } + crlDownloadTimerOn = PR_FALSE; } - crlDownloadTimerOn = PR_FALSE; - PR_Unlock(mCrlTimerLock); - PR_DestroyLock(mCrlTimerLock); - mUpdateTimerInitialized = PR_FALSE; } @@ -1423,7 +1413,6 @@ nsNSSComponent::InitializeCRLUpdateTimer() return rv; } crlsScheduledForDownload = new nsHashtable(16, PR_TRUE); - mCrlTimerLock = PR_NewLock(); DefineNextTimer(); mUpdateTimerInitialized = PR_TRUE; } @@ -1561,7 +1550,7 @@ nsNSSComponent::InitializeNSS(PRBool showWarningBox) which_nss_problem = problem_none; { - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); // Init phase 1, prepare own variables used for NSS @@ -1821,7 +1810,7 @@ nsNSSComponent::ShutdownNSS() PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("nsNSSComponent::ShutdownNSS\n")); - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); nsresult rv = NS_OK; if (hashTableCerts) { @@ -1874,7 +1863,7 @@ nsNSSComponent::Init() PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("Beginning NSS initialization\n")); - if (!mutex || !mShutdownObjectList) + if (!mShutdownObjectList) { PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("NSS init, out of memory in constructor\n")); return NS_ERROR_OUT_OF_MEMORY; @@ -2083,7 +2072,7 @@ nsNSSComponent::VerifySignature(const char* aRSABuf, PRUint32 aRSABufLen, } if (!mScriptSecurityManager) { - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); // re-test the condition to prevent double initialization if (!mScriptSecurityManager) { mScriptSecurityManager = @@ -2138,7 +2127,7 @@ nsNSSComponent::RandomUpdate(void *entropy, PRInt32 bufLen) // Asynchronous event happening often, // must not interfere with initialization or profile switch. - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); if (!mNSSInitialized) return NS_ERROR_NOT_INITIALIZED; @@ -2192,7 +2181,7 @@ nsNSSComponent::Observe(nsISupports *aSubject, const char *aTopic, PRBool needsInit = PR_TRUE; { - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); if (mNSSInitialized) { // We have already initialized NSS before the profile came up, @@ -2448,7 +2437,7 @@ nsNSSComponent::RememberCert(CERTCertificate *cert) // Must not interfere with init / shutdown / profile switch. - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); if (!hashTableCerts || !cert) return NS_OK; @@ -2524,7 +2513,7 @@ nsNSSComponent::DoProfileBeforeChange(nsISupports* aSubject) PRBool needsCleanup = PR_TRUE; { - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); if (!mNSSInitialized) { // Make sure we don't try to cleanup if we have already done so. @@ -2572,7 +2561,7 @@ nsNSSComponent::GetClientAuthRememberService(nsClientAuthRememberService **cars) NS_IMETHODIMP nsNSSComponent::IsNSSInitialized(PRBool *initialized) { - nsAutoLock lock(mutex); + MutexAutoLock lock(mutex); *initialized = mNSSInitialized; return NS_OK; } diff --git a/security/manager/ssl/src/nsNSSComponent.h b/security/manager/ssl/src/nsNSSComponent.h index 3823d1722d9..1bf3955a0ca 100644 --- a/security/manager/ssl/src/nsNSSComponent.h +++ b/security/manager/ssl/src/nsNSSComponent.h @@ -44,6 +44,7 @@ #ifndef _nsNSSComponent_h_ #define _nsNSSComponent_h_ +#include "mozilla/Mutex.h" #include "nsCOMPtr.h" #include "nsISignatureVerifier.h" #include "nsIURIContentListener.h" @@ -62,7 +63,6 @@ #include "nsITimer.h" #include "nsNetUtil.h" #include "nsHashtable.h" -#include "prlock.h" #include "nsICryptoHash.h" #include "nsICryptoHMAC.h" #include "hasht.h" @@ -228,7 +228,6 @@ private: void destructorSafeDestroyNSSReference(); }; -struct PRLock; class nsNSSShutDownList; class nsSSLThread; class nsCertVerificationThread; @@ -241,6 +240,8 @@ class nsNSSComponent : public nsISignatureVerifier, public nsSupportsWeakReference, public nsITimerCallback { + typedef mozilla::Mutex Mutex; + public: NS_DEFINE_STATIC_CID_ACCESSOR( NS_NSSCOMPONENT_CID ) @@ -326,7 +327,7 @@ private: void DoProfileBeforeChange(nsISupports* aSubject); void DoProfileChangeNetRestore(); - PRLock *mutex; + Mutex mutex; nsCOMPtr mScriptSecurityManager; nsCOMPtr mPIPNSSBundle; @@ -339,7 +340,7 @@ private: PLHashTable *hashTableCerts; nsAutoString mDownloadURL; nsAutoString mCrlUpdateKey; - PRLock *mCrlTimerLock; + Mutex mCrlTimerLock; nsHashtable *crlsScheduledForDownload; PRBool crlDownloadTimerOn; PRBool mUpdateTimerInitialized; diff --git a/security/manager/ssl/src/nsNSSIOLayer.cpp b/security/manager/ssl/src/nsNSSIOLayer.cpp index 7d872c8195a..aec44d286bd 100644 --- a/security/manager/ssl/src/nsNSSIOLayer.cpp +++ b/security/manager/ssl/src/nsNSSIOLayer.cpp @@ -74,7 +74,6 @@ #include "nsCRT.h" #include "nsAutoPtr.h" #include "nsPrintfCString.h" -#include "nsAutoLock.h" #include "nsSSLThread.h" #include "nsNSSShutDown.h" #include "nsSSLStatus.h" @@ -100,6 +99,7 @@ #include "keyhi.h" #include "secport.h" +using namespace mozilla; //#define DEBUG_SSL_VERBOSE //Enable this define to get minimal //reports when doing SSL read/write @@ -936,7 +936,7 @@ void nsSSLIOLayerHelpers::Cleanup() PR_DestroyPollableEvent(mSharedPollableEvent); if (mutex) { - nsAutoLock::DestroyLock(mutex); + delete mutex; mutex = nsnull; } @@ -1801,7 +1801,7 @@ nsSSLIOLayerHelpers::rememberTolerantSite(PRFileDesc* ssl_layer_fd, nsCAutoString key; getSiteKey(socketInfo, key); - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); nsSSLIOLayerHelpers::mTLSTolerantSites->Put(key); } @@ -2073,7 +2073,7 @@ nsSSLIOLayerPoll(PRFileDesc *fd, PRInt16 in_flags, PRInt16 *out_flags) PRBool nsSSLIOLayerHelpers::nsSSLIOLayerInitialized = PR_FALSE; PRDescIdentity nsSSLIOLayerHelpers::nsSSLIOLayerIdentity; PRIOMethods nsSSLIOLayerHelpers::nsSSLIOLayerMethods; -PRLock *nsSSLIOLayerHelpers::mutex = nsnull; +Mutex *nsSSLIOLayerHelpers::mutex = nsnull; nsCStringHashSet *nsSSLIOLayerHelpers::mTLSIntolerantSites = nsnull; nsCStringHashSet *nsSSLIOLayerHelpers::mTLSTolerantSites = nsnull; nsPSMRememberCertErrorsTable *nsSSLIOLayerHelpers::mHostsWithCertErrors = nsnull; @@ -2275,9 +2275,7 @@ nsresult nsSSLIOLayerHelpers::Init() nsSSLIOLayerMethods.poll = nsSSLIOLayerPoll; } - mutex = nsAutoLock::NewLock("nsSSLIOLayerHelpers::mutex"); - if (!mutex) - return NS_ERROR_OUT_OF_MEMORY; + mutex = new Mutex("nsSSLIOLayerHelpers.mutex"); mSharedPollableEvent = PR_NewPollableEvent(); @@ -2315,7 +2313,7 @@ nsresult nsSSLIOLayerHelpers::Init() void nsSSLIOLayerHelpers::addIntolerantSite(const nsCString &str) { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); // Remember intolerant site only if it is not known as tolerant if (!mTLSTolerantSites->Contains(str)) nsSSLIOLayerHelpers::mTLSIntolerantSites->Put(str); @@ -2323,19 +2321,19 @@ void nsSSLIOLayerHelpers::addIntolerantSite(const nsCString &str) void nsSSLIOLayerHelpers::removeIntolerantSite(const nsCString &str) { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); nsSSLIOLayerHelpers::mTLSIntolerantSites->Remove(str); } PRBool nsSSLIOLayerHelpers::isKnownAsIntolerantSite(const nsCString &str) { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); return mTLSIntolerantSites->Contains(str); } void nsSSLIOLayerHelpers::setRenegoUnrestrictedSites(const nsCString &str) { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); if (mRenegoUnrestrictedSites) { delete mRenegoUnrestrictedSites; @@ -2360,31 +2358,31 @@ void nsSSLIOLayerHelpers::setRenegoUnrestrictedSites(const nsCString &str) PRBool nsSSLIOLayerHelpers::isRenegoUnrestrictedSite(const nsCString &str) { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); return mRenegoUnrestrictedSites->Contains(str); } void nsSSLIOLayerHelpers::setTreatUnsafeNegotiationAsBroken(PRBool broken) { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); mTreatUnsafeNegotiationAsBroken = broken; } PRBool nsSSLIOLayerHelpers::treatUnsafeNegotiationAsBroken() { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); return mTreatUnsafeNegotiationAsBroken; } void nsSSLIOLayerHelpers::setWarnLevelMissingRFC5746(PRInt32 level) { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); mWarnLevelMissingRFC5746 = level; } PRInt32 nsSSLIOLayerHelpers::getWarnLevelMissingRFC5746() { - nsAutoLock lock(mutex); + MutexAutoLock lock(*mutex); return mWarnLevelMissingRFC5746; } diff --git a/security/manager/ssl/src/nsNSSIOLayer.h b/security/manager/ssl/src/nsNSSIOLayer.h index c6192825d54..698bc06edb9 100644 --- a/security/manager/ssl/src/nsNSSIOLayer.h +++ b/security/manager/ssl/src/nsNSSIOLayer.h @@ -44,6 +44,7 @@ #include "prtypes.h" #include "prio.h" #include "certt.h" +#include "mozilla/Mutex.h" #include "nsString.h" #include "nsIInterfaceRequestor.h" #include "nsIInterfaceRequestorUtils.h" @@ -282,7 +283,7 @@ public: static PRDescIdentity nsSSLIOLayerIdentity; static PRIOMethods nsSSLIOLayerMethods; - static PRLock *mutex; + static mozilla::Mutex *mutex; static nsCStringHashSet *mTLSIntolerantSites; static nsCStringHashSet *mTLSTolerantSites; static nsPSMRememberCertErrorsTable* mHostsWithCertErrors; diff --git a/security/manager/ssl/src/nsNSSShutDown.cpp b/security/manager/ssl/src/nsNSSShutDown.cpp index 70e93a62e48..5f2b864020e 100644 --- a/security/manager/ssl/src/nsNSSShutDown.cpp +++ b/security/manager/ssl/src/nsNSSShutDown.cpp @@ -38,6 +38,8 @@ #include "nsNSSShutDown.h" #include "nsCOMPtr.h" +using namespace mozilla; + #ifdef PR_LOGGING extern PRLogModuleInfo* gPIPNSSLog; #endif @@ -77,8 +79,8 @@ static PLDHashTableOps gSetOps = { nsNSSShutDownList *nsNSSShutDownList::singleton = nsnull; nsNSSShutDownList::nsNSSShutDownList() +:mListLock("nsNSSShutDownList.mListLock") { - mListLock = PR_NewLock(); mActiveSSLSockets = 0; mPK11LogoutCancelObjects.ops = nsnull; mObjects.ops = nsnull; @@ -90,10 +92,6 @@ nsNSSShutDownList::nsNSSShutDownList() nsNSSShutDownList::~nsNSSShutDownList() { - if (mListLock) { - PR_DestroyLock(mListLock); - mListLock = nsnull; - } if (mObjects.ops) { PL_DHashTableFinish(&mObjects); mObjects.ops = nsnull; @@ -112,9 +110,8 @@ void nsNSSShutDownList::remember(nsNSSShutDownObject *o) return; PR_ASSERT(o); - PR_Lock(singleton->mListLock); + MutexAutoLock lock(singleton->mListLock); PL_DHashTableOperate(&singleton->mObjects, o, PL_DHASH_ADD); - PR_Unlock(singleton->mListLock); } void nsNSSShutDownList::forget(nsNSSShutDownObject *o) @@ -123,9 +120,8 @@ void nsNSSShutDownList::forget(nsNSSShutDownObject *o) return; PR_ASSERT(o); - PR_Lock(singleton->mListLock); - PL_DHashTableOperate(&singleton->mObjects, o, PL_DHASH_REMOVE); - PR_Unlock(singleton->mListLock); + MutexAutoLock lock(singleton->mListLock); + PL_DHashTableOperate(&singleton->mObjects, o, PL_DHASH_REMOVE); } void nsNSSShutDownList::remember(nsOnPK11LogoutCancelObject *o) @@ -134,9 +130,8 @@ void nsNSSShutDownList::remember(nsOnPK11LogoutCancelObject *o) return; PR_ASSERT(o); - PR_Lock(singleton->mListLock); - PL_DHashTableOperate(&singleton->mPK11LogoutCancelObjects, o, PL_DHASH_ADD); - PR_Unlock(singleton->mListLock); + MutexAutoLock lock(singleton->mListLock); + PL_DHashTableOperate(&singleton->mPK11LogoutCancelObjects, o, PL_DHASH_ADD); } void nsNSSShutDownList::forget(nsOnPK11LogoutCancelObject *o) @@ -145,9 +140,8 @@ void nsNSSShutDownList::forget(nsOnPK11LogoutCancelObject *o) return; PR_ASSERT(o); - PR_Lock(singleton->mListLock); - PL_DHashTableOperate(&singleton->mPK11LogoutCancelObjects, o, PL_DHASH_REMOVE); - PR_Unlock(singleton->mListLock); + MutexAutoLock lock(singleton->mListLock); + PL_DHashTableOperate(&singleton->mPK11LogoutCancelObjects, o, PL_DHASH_REMOVE); } void nsNSSShutDownList::trackSSLSocketCreate() @@ -155,9 +149,8 @@ void nsNSSShutDownList::trackSSLSocketCreate() if (!singleton) return; - PR_Lock(singleton->mListLock); - ++singleton->mActiveSSLSockets; - PR_Unlock(singleton->mListLock); + MutexAutoLock lock(singleton->mListLock); + ++singleton->mActiveSSLSockets; } void nsNSSShutDownList::trackSSLSocketClose() @@ -165,9 +158,8 @@ void nsNSSShutDownList::trackSSLSocketClose() if (!singleton) return; - PR_Lock(singleton->mListLock); - --singleton->mActiveSSLSockets; - PR_Unlock(singleton->mListLock); + MutexAutoLock lock(singleton->mListLock); + --singleton->mActiveSSLSockets; } PRBool nsNSSShutDownList::areSSLSocketsActive() @@ -180,12 +172,8 @@ PRBool nsNSSShutDownList::areSSLSocketsActive() return PR_FALSE; } - PRBool retval; - PR_Lock(singleton->mListLock); - retval = (singleton->mActiveSSLSockets > 0); - PR_Unlock(singleton->mListLock); - - return retval; + MutexAutoLock lock(singleton->mListLock); + return (singleton->mActiveSSLSockets > 0); } nsresult nsNSSShutDownList::doPK11Logout() @@ -196,9 +184,8 @@ nsresult nsNSSShutDownList::doPK11Logout() // We only must ensure that our objects do not go away. // This is guaranteed by holding the list lock. - PR_Lock(mListLock); - PL_DHashTableEnumerate(&mPK11LogoutCancelObjects, doPK11LogoutHelper, 0); - PR_Unlock(mListLock); + MutexAutoLock lock(singleton->mListLock); + PL_DHashTableEnumerate(&mPK11LogoutCancelObjects, doPK11LogoutHelper, 0); return NS_OK; } @@ -247,9 +234,8 @@ nsresult nsNSSShutDownList::evaporateAllNSSResources() PR_LOG(gPIPNSSLog, PR_LOG_DEBUG, ("now evaporating NSS resources\n")); int removedCount; do { - PR_Lock(mListLock); - removedCount = PL_DHashTableEnumerate(&mObjects, evaporateAllNSSResourcesHelper, 0); - PR_Unlock(mListLock); + MutexAutoLock lock(mListLock); + removedCount = PL_DHashTableEnumerate(&mObjects, evaporateAllNSSResourcesHelper, 0); } while (removedCount > 0); mActivityState.releaseCurrentThreadActivityRestriction(); @@ -260,17 +246,15 @@ PLDHashOperator PR_CALLBACK nsNSSShutDownList::evaporateAllNSSResourcesHelper(PLDHashTable *table, PLDHashEntryHdr *hdr, PRUint32 number, void *arg) { - ObjectHashEntry *entry = static_cast(hdr); - PR_Unlock(singleton->mListLock); - - entry->obj->shutdown(nsNSSShutDownObject::calledFromList); - - PR_Lock(singleton->mListLock); - - // Never free more than one entry, because other threads might be calling - // us and remove themselves while we are iterating over the list, - // and the behaviour of changing the list while iterating is undefined. - return (PLDHashOperator)(PL_DHASH_STOP | PL_DHASH_REMOVE); + ObjectHashEntry *entry = static_cast(hdr); + { + MutexAutoUnlock unlock(singleton->mListLock); + entry->obj->shutdown(nsNSSShutDownObject::calledFromList); + } + // Never free more than one entry, because other threads might be calling + // us and remove themselves while we are iterating over the list, + // and the behaviour of changing the list while iterating is undefined. + return (PLDHashOperator)(PL_DHASH_STOP | PL_DHASH_REMOVE); } nsNSSShutDownList *nsNSSShutDownList::construct() @@ -285,173 +269,129 @@ nsNSSShutDownList *nsNSSShutDownList::construct() } nsNSSActivityState::nsNSSActivityState() -:mNSSActivityStateLock(nsnull), - mNSSActivityChanged(nsnull), +:mNSSActivityStateLock("nsNSSActivityState.mNSSActivityStateLock"), + mNSSActivityChanged(mNSSActivityStateLock, + "nsNSSActivityState.mNSSActivityStateLock"), mNSSActivityCounter(0), mBlockingUICounter(0), mIsUIForbidden(PR_FALSE), mNSSRestrictedThread(nsnull) { - mNSSActivityStateLock = PR_NewLock(); - if (!mNSSActivityStateLock) - return; - - mNSSActivityChanged = PR_NewCondVar(mNSSActivityStateLock); } nsNSSActivityState::~nsNSSActivityState() { - if (mNSSActivityChanged) { - PR_DestroyCondVar(mNSSActivityChanged); - mNSSActivityChanged = nsnull; - } - - if (mNSSActivityStateLock) { - PR_DestroyLock(mNSSActivityStateLock); - mNSSActivityStateLock = nsnull; - } } void nsNSSActivityState::enter() { - PR_Lock(mNSSActivityStateLock); + MutexAutoLock lock(mNSSActivityStateLock); - while (mNSSRestrictedThread && mNSSRestrictedThread != PR_GetCurrentThread()) { - PR_WaitCondVar(mNSSActivityChanged, PR_INTERVAL_NO_TIMEOUT); - } + while (mNSSRestrictedThread && mNSSRestrictedThread != PR_GetCurrentThread()) { + mNSSActivityChanged.Wait(); + } - ++mNSSActivityCounter; - - PR_Unlock(mNSSActivityStateLock); + ++mNSSActivityCounter; } void nsNSSActivityState::leave() { - PR_Lock(mNSSActivityStateLock); + MutexAutoLock lock(mNSSActivityStateLock); - --mNSSActivityCounter; + --mNSSActivityCounter; - if (!mNSSActivityCounter) { - PR_NotifyAllCondVar(mNSSActivityChanged); - } - - PR_Unlock(mNSSActivityStateLock); + mNSSActivityChanged.NotifyAll(); } void nsNSSActivityState::enterBlockingUIState() { - PR_Lock(mNSSActivityStateLock); + MutexAutoLock lock(mNSSActivityStateLock); - ++mBlockingUICounter; - - PR_Unlock(mNSSActivityStateLock); + ++mBlockingUICounter; } void nsNSSActivityState::leaveBlockingUIState() { - PR_Lock(mNSSActivityStateLock); + MutexAutoLock lock(mNSSActivityStateLock); - --mBlockingUICounter; - - PR_Unlock(mNSSActivityStateLock); + --mBlockingUICounter; } PRBool nsNSSActivityState::isBlockingUIActive() { - PRBool retval; - - PR_Lock(mNSSActivityStateLock); - retval = (mBlockingUICounter > 0); - PR_Unlock(mNSSActivityStateLock); - - return retval; + MutexAutoLock lock(mNSSActivityStateLock); + return (mBlockingUICounter > 0); } PRBool nsNSSActivityState::isUIForbidden() { - PRBool retval; - - PR_Lock(mNSSActivityStateLock); - retval = mIsUIForbidden; - PR_Unlock(mNSSActivityStateLock); - - return retval; + MutexAutoLock lock(mNSSActivityStateLock); + return mIsUIForbidden; } PRBool nsNSSActivityState::ifPossibleDisallowUI(RealOrTesting rot) { PRBool retval = PR_FALSE; + MutexAutoLock lock(mNSSActivityStateLock); - PR_Lock(mNSSActivityStateLock); + // Checking and disallowing the UI must be done atomically. - // Checking and disallowing the UI must be done atomically. - - if (!mBlockingUICounter) { - // No UI is currently shown, we are able to evaporate. - retval = PR_TRUE; - if (rot == do_it_for_real) { - // Remember to disallow UI. - mIsUIForbidden = PR_TRUE; + if (!mBlockingUICounter) { + // No UI is currently shown, we are able to evaporate. + retval = PR_TRUE; + if (rot == do_it_for_real) { + // Remember to disallow UI. + mIsUIForbidden = PR_TRUE; - // to clear the "forbidden" state, - // one must either call - // restrictActivityToCurrentThread() + releaseCurrentThreadActivityRestriction() - // or cancel the operation by calling - // unprepareCurrentThreadRestriction() - } + // to clear the "forbidden" state, + // one must either call + // restrictActivityToCurrentThread() + releaseCurrentThreadActivityRestriction() + // or cancel the operation by calling + // unprepareCurrentThreadRestriction() } - - PR_Unlock(mNSSActivityStateLock); - + } return retval; } void nsNSSActivityState::allowUI() { - PR_Lock(mNSSActivityStateLock); + MutexAutoLock lock(mNSSActivityStateLock); - mIsUIForbidden = PR_FALSE; - - PR_Unlock(mNSSActivityStateLock); + mIsUIForbidden = PR_FALSE; } PRStatus nsNSSActivityState::restrictActivityToCurrentThread() { PRStatus retval = PR_FAILURE; - - PR_Lock(mNSSActivityStateLock); + MutexAutoLock lock(mNSSActivityStateLock); - if (!mBlockingUICounter) { - while (0 < mNSSActivityCounter && !mBlockingUICounter) { - PR_WaitCondVar(mNSSActivityChanged, PR_TicksPerSecond()); - } - - if (mBlockingUICounter) { - // This should never happen. - // If we arrive here, our logic is broken. - PR_ASSERT(0); - } - else { - mNSSRestrictedThread = PR_GetCurrentThread(); - retval = PR_SUCCESS; - } + if (!mBlockingUICounter) { + while (0 < mNSSActivityCounter && !mBlockingUICounter) { + mNSSActivityChanged.Wait(PR_TicksPerSecond()); } - - PR_Unlock(mNSSActivityStateLock); + + if (mBlockingUICounter) { + // This should never happen. + // If we arrive here, our logic is broken. + PR_ASSERT(0); + } + else { + mNSSRestrictedThread = PR_GetCurrentThread(); + retval = PR_SUCCESS; + } + } return retval; } void nsNSSActivityState::releaseCurrentThreadActivityRestriction() { - PR_Lock(mNSSActivityStateLock); + MutexAutoLock lock(mNSSActivityStateLock); - mNSSRestrictedThread = nsnull; - mIsUIForbidden = PR_FALSE; + mNSSRestrictedThread = nsnull; + mIsUIForbidden = PR_FALSE; - PR_NotifyAllCondVar(mNSSActivityChanged); - - PR_Unlock(mNSSActivityStateLock); + mNSSActivityChanged.NotifyAll(); } nsNSSShutDownPreventionLock::nsNSSShutDownPreventionLock() diff --git a/security/manager/ssl/src/nsNSSShutDown.h b/security/manager/ssl/src/nsNSSShutDown.h index 60ac2de119c..1cc668a995a 100644 --- a/security/manager/ssl/src/nsNSSShutDown.h +++ b/security/manager/ssl/src/nsNSSShutDown.h @@ -41,6 +41,8 @@ #include "nscore.h" #include "nspr.h" #include "pldhash.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" class nsNSSShutDownObject; class nsOnPK11LogoutCancelObject; @@ -89,12 +91,12 @@ public: private: // The lock protecting all our member variables. - PRLock *mNSSActivityStateLock; + mozilla::Mutex mNSSActivityStateLock; // The activity variable, bound to our lock, // used either to signal the activity counter reaches zero, // or a thread restriction has been released. - PRCondVar *mNSSActivityChanged; + mozilla::CondVar mNSSActivityChanged; // The number of active scopes holding resources. int mNSSActivityCounter; @@ -186,7 +188,7 @@ private: doPK11LogoutHelper(PLDHashTable *table, PLDHashEntryHdr *hdr, PRUint32 number, void *arg); protected: - PRLock* mListLock; + mozilla::Mutex mListLock; static nsNSSShutDownList *singleton; PLDHashTable mObjects; PRUint32 mActiveSSLSockets; diff --git a/security/manager/ssl/src/nsPSMBackgroundThread.cpp b/security/manager/ssl/src/nsPSMBackgroundThread.cpp index 3918390c69f..592e31d114b 100644 --- a/security/manager/ssl/src/nsPSMBackgroundThread.cpp +++ b/security/manager/ssl/src/nsPSMBackgroundThread.cpp @@ -36,7 +36,8 @@ * ***** END LICENSE BLOCK ***** */ #include "nsPSMBackgroundThread.h" -#include "nsAutoLock.h" + +using namespace mozilla; void PR_CALLBACK nsPSMBackgroundThread::nsThreadRunner(void *arg) { @@ -46,19 +47,14 @@ void PR_CALLBACK nsPSMBackgroundThread::nsThreadRunner(void *arg) nsPSMBackgroundThread::nsPSMBackgroundThread() : mThreadHandle(nsnull), - mMutex(nsnull), - mCond(nsnull), + mMutex("nsPSMBackgroundThread.mMutex"), + mCond(mMutex, "nsPSMBackgroundThread.mCond"), mExitRequested(PR_FALSE) { - mMutex = nsAutoLock::NewLock("nsPSMBackgroundThread::mMutex"); - mCond = PR_NewCondVar(mMutex); } nsresult nsPSMBackgroundThread::startThread() { - if (!mMutex || !mCond) - return NS_ERROR_OUT_OF_MEMORY; - mThreadHandle = PR_CreateThread(PR_USER_THREAD, nsThreadRunner, static_cast(this), PR_PRIORITY_NORMAL, PR_LOCAL_THREAD, PR_JOINABLE_THREAD, 0); @@ -72,11 +68,6 @@ nsresult nsPSMBackgroundThread::startThread() nsPSMBackgroundThread::~nsPSMBackgroundThread() { - if (mCond) - PR_DestroyCondVar(mCond); - - if (mMutex) - nsAutoLock::DestroyLock(mMutex); } void nsPSMBackgroundThread::requestExit() @@ -85,13 +76,13 @@ void nsPSMBackgroundThread::requestExit() return; { - nsAutoLock threadLock(mMutex); + MutexAutoLock threadLock(mMutex); if (mExitRequested) return; mExitRequested = PR_TRUE; - PR_NotifyAllCondVar(mCond); + mCond.NotifyAll(); } PR_JoinThread(mThreadHandle); diff --git a/security/manager/ssl/src/nsPSMBackgroundThread.h b/security/manager/ssl/src/nsPSMBackgroundThread.h index e790fb18d36..0683ad10411 100644 --- a/security/manager/ssl/src/nsPSMBackgroundThread.h +++ b/security/manager/ssl/src/nsPSMBackgroundThread.h @@ -40,6 +40,8 @@ #include "nspr.h" #include "nscore.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" class nsPSMBackgroundThread { @@ -54,10 +56,10 @@ protected: // and to protect access to mExitRequested. // Derived classes may use it to protect additional // resources. - PRLock *mMutex; + mozilla::Mutex mMutex; // Used to signal the thread's Run loop - PRCondVar *mCond; + mozilla::CondVar mCond; // Has termination of the SSL thread been requested? PRBool mExitRequested; diff --git a/security/manager/ssl/src/nsProtectedAuthThread.cpp b/security/manager/ssl/src/nsProtectedAuthThread.cpp index 0f06c80f388..fa4790bc8aa 100644 --- a/security/manager/ssl/src/nsProtectedAuthThread.cpp +++ b/security/manager/ssl/src/nsProtectedAuthThread.cpp @@ -43,6 +43,8 @@ #include "nsPKCS11Slot.h" #include "nsProtectedAuthThread.h" +using namespace mozilla; + NS_IMPL_THREADSAFE_ISUPPORTS1(nsProtectedAuthThread, nsIProtectedAuthThread) static void PR_CALLBACK nsProtectedAuthThreadRunner(void *arg) @@ -52,7 +54,7 @@ static void PR_CALLBACK nsProtectedAuthThreadRunner(void *arg) } nsProtectedAuthThread::nsProtectedAuthThread() -: mMutex(nsnull) +: mMutex("nsProtectedAuthThread.mMutex") , mIAmRunning(PR_FALSE) , mStatusObserverNotified(PR_FALSE) , mLoginReady(PR_FALSE) @@ -61,21 +63,15 @@ nsProtectedAuthThread::nsProtectedAuthThread() , mLoginResult(SECFailure) { NS_INIT_ISUPPORTS(); - mMutex = PR_NewLock(); } nsProtectedAuthThread::~nsProtectedAuthThread() { - if (mMutex) - PR_DestroyLock(mMutex); } NS_IMETHODIMP nsProtectedAuthThread::Login(nsIObserver *aObserver) { NS_ENSURE_ARG(aObserver); - - if (!mMutex) - return NS_ERROR_FAILURE; if (!mSlot) // We need pointer to the slot @@ -90,10 +86,9 @@ NS_IMETHODIMP nsProtectedAuthThread::Login(nsIObserver *aObserver) if (NS_FAILED(rv)) return rv; - PR_Lock(mMutex); + MutexAutoLock lock(mMutex); if (mIAmRunning || mLoginReady) { - PR_Unlock(mMutex); return NS_OK; } @@ -107,31 +102,26 @@ NS_IMETHODIMP nsProtectedAuthThread::Login(nsIObserver *aObserver) // we might want to return "thread started ok" to caller in the future NS_ASSERTION(mThreadHandle, "Could not create nsProtectedAuthThreadRunner thread\n"); - PR_Unlock(mMutex); - return NS_OK; } NS_IMETHODIMP nsProtectedAuthThread::GetTokenName(nsAString &_retval) { - PR_Lock(mMutex); + MutexAutoLock lock(mMutex); // Get token name CopyUTF8toUTF16(nsDependentCString(PK11_GetTokenName(mSlot)), _retval); - PR_Unlock(mMutex); - return NS_OK; } NS_IMETHODIMP nsProtectedAuthThread::GetSlot(nsIPKCS11Slot **_retval) { - PR_Lock(mMutex); - - nsRefPtr slot = new nsPKCS11Slot(mSlot); - - PR_Unlock(mMutex); - + nsRefPtr slot; + { + MutexAutoLock lock(mMutex); + slot = new nsPKCS11Slot(mSlot); + } if (!slot) return NS_ERROR_OUT_OF_MEMORY; @@ -140,11 +130,9 @@ NS_IMETHODIMP nsProtectedAuthThread::GetSlot(nsIPKCS11Slot **_retval) void nsProtectedAuthThread::SetParams(PK11SlotInfo* aSlot) { - PR_Lock(mMutex); + MutexAutoLock lock(mMutex); mSlot = (aSlot) ? PK11_ReferenceSlot(aSlot) : 0; - - PR_Unlock(mMutex); } SECStatus nsProtectedAuthThread::GetResult() @@ -159,28 +147,27 @@ void nsProtectedAuthThread::Run(void) mLoginResult = PK11_CheckUserPassword(mSlot, 0); nsCOMPtr observer; - - PR_Lock(mMutex); - - mLoginReady = PR_TRUE; - mIAmRunning = PR_FALSE; - - // Forget the slot - if (mSlot) { - PK11_FreeSlot(mSlot); - mSlot = 0; - } - - if (!mStatusObserverNotified) - { - observer = mStatusObserver; - } + MutexAutoLock lock(mMutex); - mStatusObserver = nsnull; - mStatusObserverNotified = PR_TRUE; - - PR_Unlock(mMutex); + mLoginReady = PR_TRUE; + mIAmRunning = PR_FALSE; + + // Forget the slot + if (mSlot) + { + PK11_FreeSlot(mSlot); + mSlot = 0; + } + + if (!mStatusObserverNotified) + { + observer = mStatusObserver; + } + + mStatusObserver = nsnull; + mStatusObserverNotified = PR_TRUE; + } if (observer) observer->Observe(nsnull, "operation-completed", nsnull); diff --git a/security/manager/ssl/src/nsProtectedAuthThread.h b/security/manager/ssl/src/nsProtectedAuthThread.h index 5820c8ab041..df9e27e9917 100644 --- a/security/manager/ssl/src/nsProtectedAuthThread.h +++ b/security/manager/ssl/src/nsProtectedAuthThread.h @@ -41,12 +41,13 @@ #include "keyhi.h" #include "nspr.h" +#include "mozilla/Mutex.h" #include "nsIProtectedAuthThread.h" class nsProtectedAuthThread : public nsIProtectedAuthThread { private: - PRLock *mMutex; + mozilla::Mutex mMutex; nsCOMPtr mStatusObserver; diff --git a/security/manager/ssl/src/nsRecentBadCerts.cpp b/security/manager/ssl/src/nsRecentBadCerts.cpp index 490cbdbd6bc..3ab47e17e48 100644 --- a/security/manager/ssl/src/nsRecentBadCerts.cpp +++ b/security/manager/ssl/src/nsRecentBadCerts.cpp @@ -46,7 +46,6 @@ #include "nsCRT.h" #include "nsPromiseFlatString.h" #include "nsStringBuffer.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nspr.h" #include "pk11pub.h" @@ -54,21 +53,22 @@ #include "sechash.h" #include "nsNSSCleaner.h" + +using namespace mozilla; + NSSCleanupAutoPtrClass(CERTCertificate, CERT_DestroyCertificate) NS_IMPL_THREADSAFE_ISUPPORTS1(nsRecentBadCertsService, nsIRecentBadCertsService) nsRecentBadCertsService::nsRecentBadCertsService() -:mNextStorePosition(0) +:monitor("nsRecentBadCertsService.monitor") +,mNextStorePosition(0) { - monitor = nsAutoMonitor::NewMonitor("security.recentBadCertsMonitor"); } nsRecentBadCertsService::~nsRecentBadCertsService() { - if (monitor) - nsAutoMonitor::DestroyMonitor(monitor); } nsresult @@ -99,7 +99,7 @@ nsRecentBadCertsService::GetRecentBadCert(const nsAString & aHostNameWithPort, PRBool isUntrusted = PR_FALSE; { - nsAutoMonitor lock(monitor); + MonitorAutoEnter lock(monitor); for (size_t i=0; imThreadHandle) return nsnull; - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (si->mThreadData->mReplacedSSLFileDesc) { @@ -144,7 +145,7 @@ PRInt32 nsSSLThread::requestRecvMsgPeek(nsNSSSocketInfo *si, void *buf, PRInt32 PRFileDesc *realSSLFD; { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (si == ssl_thread_singleton->mBusySocket) { @@ -240,7 +241,7 @@ PRInt16 nsSSLThread::requestPoll(nsNSSSocketInfo *si, PRInt16 in_flags, PRInt16 PRBool handshake_timeout = PR_FALSE; { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (ssl_thread_singleton->mBusySocket) { @@ -395,7 +396,7 @@ PRStatus nsSSLThread::requestClose(nsNSSSocketInfo *si) nsCOMPtr requestToCancel; { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (ssl_thread_singleton->mBusySocket == si) { @@ -414,7 +415,7 @@ PRStatus nsSSLThread::requestClose(nsNSSSocketInfo *si) close_later = PR_TRUE; ssl_thread_singleton->mSocketScheduledToBeDestroyed = si; - PR_NotifyAllCondVar(ssl_thread_singleton->mCond); + ssl_thread_singleton->mCond.NotifyAll(); } } @@ -507,7 +508,7 @@ PRInt32 nsSSLThread::requestRead(nsNSSSocketInfo *si, void *buf, PRInt32 amount, PRFileDesc *blockingFD = nsnull; { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (ssl_thread_singleton->mExitRequested) { PR_SetError(PR_UNKNOWN_ERROR, 0); @@ -695,7 +696,7 @@ PRInt32 nsSSLThread::requestRead(nsNSSSocketInfo *si, void *buf, PRInt32 amount, // Finally, we return the data obtained on the SSL thread back to our caller. { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (nsSSLIOLayerHelpers::mSharedPollableEvent) { @@ -712,7 +713,7 @@ PRInt32 nsSSLThread::requestRead(nsNSSSocketInfo *si, void *buf, PRInt32 amount, ssl_thread_singleton->mBusySocket = si; // notify the thread - PR_NotifyAllCondVar(ssl_thread_singleton->mCond); + ssl_thread_singleton->mCond.NotifyAll(); } PORT_SetError(PR_WOULD_BLOCK_ERROR); @@ -734,7 +735,7 @@ PRInt32 nsSSLThread::requestWrite(nsNSSSocketInfo *si, const void *buf, PRInt32 PRFileDesc *blockingFD = nsnull; { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (ssl_thread_singleton->mExitRequested) { PR_SetError(PR_UNKNOWN_ERROR, 0); @@ -892,7 +893,7 @@ PRInt32 nsSSLThread::requestWrite(nsNSSSocketInfo *si, const void *buf, PRInt32 si->mThreadData->mSSLState = nsSSLSocketThreadData::ssl_pending_write; { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (nsSSLIOLayerHelpers::mSharedPollableEvent) { @@ -908,7 +909,7 @@ PRInt32 nsSSLThread::requestWrite(nsNSSSocketInfo *si, const void *buf, PRInt32 nsSSLIOLayerHelpers::mSocketOwningPollableEvent = si; ssl_thread_singleton->mBusySocket = si; - PR_NotifyAllCondVar(ssl_thread_singleton->mCond); + ssl_thread_singleton->mCond.NotifyAll(); } PORT_SetError(PR_WOULD_BLOCK_ERROR); @@ -936,7 +937,7 @@ void nsSSLThread::Run(void) // In this scope we need mutex protection, // as we find out what needs to be done. - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (mSocketScheduledToBeDestroyed) { @@ -977,7 +978,7 @@ void nsSSLThread::Run(void) { // no work to do ? let's wait a moment - PR_WaitCondVar(mCond, PR_INTERVAL_NO_TIMEOUT); + mCond.Wait(); } } while (!pending_work && !mExitRequested && !mSocketScheduledToBeDestroyed); @@ -1095,7 +1096,7 @@ void nsSSLThread::Run(void) PRBool needToSetPollableEvent = PR_FALSE; { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); mBusySocket->mThreadData->mSSLState = busy_socket_ssl_state; @@ -1119,7 +1120,7 @@ void nsSSLThread::Run(void) } { - nsAutoLock threadLock(ssl_thread_singleton->mMutex); + MutexAutoLock threadLock(ssl_thread_singleton->mMutex); if (mBusySocket) { restoreOriginalSocket_locked(mBusySocket); diff --git a/storage/src/mozStorageConnection.cpp b/storage/src/mozStorageConnection.cpp index 3aa50f7b329..4864bedbd51 100644 --- a/storage/src/mozStorageConnection.cpp +++ b/storage/src/mozStorageConnection.cpp @@ -50,7 +50,6 @@ #include "nsIFile.h" #include "nsIMemoryReporter.h" #include "nsThreadUtils.h" -#include "nsAutoLock.h" #include "mozIStorageAggregateFunction.h" #include "mozIStorageCompletionCallback.h" diff --git a/testing/xpcshell/runxpcshelltests.py b/testing/xpcshell/runxpcshelltests.py index 3d75dde4c81..138b8ae2fa9 100644 --- a/testing/xpcshell/runxpcshelltests.py +++ b/testing/xpcshell/runxpcshelltests.py @@ -163,6 +163,12 @@ class XPCShellTests(object): self.env["XPCOM_DEBUG_BREAK"] = "stack-and-abort" # Don't launch the crash reporter client self.env["MOZ_CRASHREPORTER_NO_REPORT"] = "1" + # Capturing backtraces is very slow on some platforms, and it's + # disabled by automation.py too + if not (sys.platform == 'osx' or sys.platform == "darwin"): + # XXX automation.py has this odd special case; without it, bug + # 618052 seems to be exacerbated + self.env["NS_TRACE_MALLOC_DISABLE_STACKS"] = "1" if sys.platform == 'win32': self.env["PATH"] = self.env["PATH"] + ";" + self.xrePath diff --git a/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp b/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp index 83b73846b5d..526a0284b04 100644 --- a/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp +++ b/toolkit/components/url-classifier/nsUrlClassifierDBService.cpp @@ -47,7 +47,6 @@ #include "mozStorageHelper.h" #include "mozStorageCID.h" #include "nsAppDirectoryServiceDefs.h" -#include "nsAutoLock.h" #include "nsCRT.h" #include "nsDataHashtable.h" #include "nsICryptoHash.h" @@ -72,8 +71,8 @@ #include "nsNetCID.h" #include "nsThreadUtils.h" #include "nsXPCOMStrings.h" +#include "mozilla/Mutex.h" #include "prlog.h" -#include "prlock.h" #include "prprf.h" #include "prnetdb.h" #include "zlib.h" @@ -81,6 +80,8 @@ // Needed to interpert mozIStorageConnection::GetLastError #include +using namespace mozilla; + /** * The DBServices stores a set of Fragments. A fragment is one URL * fragment containing two or more domain components and some number @@ -1292,7 +1293,7 @@ private: // The clean-host-key cache is updated in the worker thread, but // checked in the main thread (to avoid posting lookup requests if // not necessary). - PRLock* mCleanHostKeysLock; + Mutex mCleanHostKeysLock; // We maintain an MRU cache of clean fragments (fragments with no // entry in the db). @@ -1305,7 +1306,7 @@ private: // Pending lookups are stored in a queue for processing. The queue // is protected by mPendingLookupLock. - PRLock* mPendingLookupLock; + Mutex mPendingLookupLock; class PendingLookup { public: @@ -1340,8 +1341,8 @@ nsUrlClassifierDBServiceWorker::nsUrlClassifierDBServiceWorker() , mHaveCachedSubChunks(PR_FALSE) , mUpdateStartTime(0) , mGethashNoise(0) - , mCleanHostKeysLock(nsnull) - , mPendingLookupLock(nsnull) + , mCleanHostKeysLock("nsUrlClassifierDBServerWorker.mCleanHostKeysLock") + , mPendingLookupLock("nsUrlClassifierDBServerWorker.mPendingLookupLock") { } @@ -1350,12 +1351,6 @@ nsUrlClassifierDBServiceWorker::~nsUrlClassifierDBServiceWorker() NS_ASSERTION(!mConnection, "Db connection not closed, leaking memory! Call CloseDb " "to close the connection."); - - if (mCleanHostKeysLock) - nsAutoLock::DestroyLock(mCleanHostKeysLock); - - if (mPendingLookupLock) - nsAutoLock::DestroyLock(mPendingLookupLock); } nsresult @@ -1380,22 +1375,12 @@ nsUrlClassifierDBServiceWorker::Init(PRInt32 gethashNoise) rv = mDBFile->Append(NS_LITERAL_STRING(DATABASE_FILENAME)); NS_ENSURE_SUCCESS(rv, rv); - mCleanHostKeysLock = - nsAutoLock::NewLock("nsUrlClassifierDBServiceWorker::mCleanHostKeysLock"); - if (!mCleanHostKeysLock) - return NS_ERROR_OUT_OF_MEMORY; - if (!mCleanHostKeys.Init(CLEAN_HOST_KEYS_SIZE)) return NS_ERROR_OUT_OF_MEMORY; if (!mCleanFragments.Init(CLEAN_FRAGMENTS_SIZE)) return NS_ERROR_OUT_OF_MEMORY; - mPendingLookupLock = - nsAutoLock::NewLock("nsUrlClassifierDBServiceWorker::mPendingLookupLock"); - if (!mPendingLookupLock) - return NS_ERROR_OUT_OF_MEMORY; - ResetUpdate(); mTableFreshness.Init(); @@ -1407,7 +1392,7 @@ nsresult nsUrlClassifierDBServiceWorker::QueueLookup(const nsACString& spec, nsIUrlClassifierLookupCallback* callback) { - nsAutoLock lock(mPendingLookupLock); + MutexAutoLock lock(mPendingLookupLock); PendingLookup* lookup = mPendingLookups.AppendElement(); if (!lookup) return NS_ERROR_OUT_OF_MEMORY; @@ -1426,7 +1411,7 @@ nsUrlClassifierDBServiceWorker::CheckCleanHost(const nsACString &spec, nsresult rv = GetHostKeys(spec, lookupHosts); NS_ENSURE_SUCCESS(rv, rv); - nsAutoLock lock(mCleanHostKeysLock); + MutexAutoLock lock(mCleanHostKeysLock); for (PRUint32 i = 0; i < lookupHosts.Length(); i++) { if (!mCleanHostKeys.Has(lookupHosts[i])) { @@ -1566,7 +1551,7 @@ nsUrlClassifierDBServiceWorker::CacheEntries(const nsACString& spec) // case multiple lookups are queued at the same time, it's worth // checking again here. { - nsAutoLock lock(mCleanHostKeysLock); + MutexAutoLock lock(mCleanHostKeysLock); if (mCleanHostKeys.Has(lookupHosts[i])) continue; } @@ -1580,7 +1565,7 @@ nsUrlClassifierDBServiceWorker::CacheEntries(const nsACString& spec) // There were no entries in the db for this host key. Go // ahead and mark the host key as clean to help short-circuit // future lookups. - nsAutoLock lock(mCleanHostKeysLock); + MutexAutoLock lock(mCleanHostKeysLock); mCleanHostKeys.Put(lookupHosts[i]); } else { prevLength = mCachedEntries.Length(); @@ -1738,15 +1723,14 @@ nsUrlClassifierDBServiceWorker::DoLookup(const nsACString& spec, nsresult nsUrlClassifierDBServiceWorker::HandlePendingLookups() { - nsAutoLock lock(mPendingLookupLock); + MutexAutoLock lock(mPendingLookupLock); while (mPendingLookups.Length() > 0) { PendingLookup lookup = mPendingLookups[0]; mPendingLookups.RemoveElementAt(0); - lock.unlock(); - - DoLookup(lookup.mKey, lookup.mCallback); - - lock.lock(); + { + MutexAutoUnlock unlock(mPendingLookupLock); + DoLookup(lookup.mKey, lookup.mCallback); + } } return NS_OK; @@ -2899,7 +2883,7 @@ nsUrlClassifierDBServiceWorker::ResetLookupCache() mCleanFragments.Clear(); - nsAutoLock lock(mCleanHostKeysLock); + MutexAutoLock lock(mCleanHostKeysLock); mCleanHostKeys.Clear(); } diff --git a/tools/trace-malloc/lib/nsWinTraceMalloc.cpp b/tools/trace-malloc/lib/nsWinTraceMalloc.cpp index b44a6d24474..f993d7a5dd6 100644 --- a/tools/trace-malloc/lib/nsWinTraceMalloc.cpp +++ b/tools/trace-malloc/lib/nsWinTraceMalloc.cpp @@ -42,9 +42,9 @@ #include #include "prtypes.h" +#include "prinrval.h" #include "prlock.h" #include "nscore.h" -#include "nsAutoLock.h" #include "nsDebugHelpWin32.h" #include "nsTraceMallocCallbacks.h" diff --git a/widget/src/android/nsAppShell.cpp b/widget/src/android/nsAppShell.cpp index 05a88d78a6b..ee05d72e425 100644 --- a/widget/src/android/nsAppShell.cpp +++ b/widget/src/android/nsAppShell.cpp @@ -82,9 +82,9 @@ nsAppShell *nsAppShell::gAppShell = nsnull; NS_IMPL_ISUPPORTS_INHERITED1(nsAppShell, nsBaseAppShell, nsIObserver) nsAppShell::nsAppShell() - : mQueueLock(nsnull), - mCondLock(nsnull), - mQueueCond(nsnull), + : mQueueLock("nsAppShell.mQueueLock"), + mCondLock("nsAppShell.mCondLock"), + mQueueCond(mCondLock, "nsAppShell.mQueueCond"), mNumDraws(0) { gAppShell = this; @@ -98,9 +98,8 @@ nsAppShell::~nsAppShell() void nsAppShell::NotifyNativeEvent() { - PR_Lock(mCondLock); - PR_NotifyCondVar(mQueueCond); - PR_Unlock(mCondLock); + MutexAutoLock lock(mCondLock); + mQueueCond.Notify(); } nsresult @@ -111,10 +110,6 @@ nsAppShell::Init() gWidgetLog = PR_NewLogModule("Widget"); #endif - mQueueLock = PR_NewLock(); - mCondLock = PR_NewLock(); - mQueueCond = PR_NewCondVar(mCondLock); - mObserversHash.Init(); nsresult rv = nsBaseAppShell::Init(); @@ -235,30 +230,29 @@ nsAppShell::ProcessNextNativeEvent(PRBool mayWait) { EVLOG("nsAppShell::ProcessNextNativeEvent %d", mayWait); - PR_Lock(mCondLock); - nsAutoPtr curEvent; AndroidGeckoEvent *nextEvent; - - curEvent = GetNextEvent(); - if (!curEvent && mayWait) { - // hmm, should we really hardcode this 10s? -#if defined(ANDROID_DEBUG_EVENTS) - PRTime t0, t1; - EVLOG("nsAppShell: waiting on mQueueCond"); - t0 = PR_Now(); - - PR_WaitCondVar(mQueueCond, PR_MillisecondsToInterval(10000)); - t1 = PR_Now(); - EVLOG("nsAppShell: wait done, waited %d ms", (int)(t1-t0)/1000); -#else - PR_WaitCondVar(mQueueCond, PR_INTERVAL_NO_TIMEOUT); -#endif + { + MutexAutoLock lock(mCondLock); curEvent = GetNextEvent(); - } + if (!curEvent && mayWait) { + // hmm, should we really hardcode this 10s? +#if defined(ANDROID_DEBUG_EVENTS) + PRTime t0, t1; + EVLOG("nsAppShell: waiting on mQueueCond"); + t0 = PR_Now(); - PR_Unlock(mCondLock); + mQueueCond.Wait(PR_MillisecondsToInterval(10000)); + t1 = PR_Now(); + EVLOG("nsAppShell: wait done, waited %d ms", (int)(t1-t0)/1000); +#else + mQueueCond.Wait(); +#endif + + curEvent = GetNextEvent(); + } + } if (!curEvent) return false; @@ -410,7 +404,7 @@ AndroidGeckoEvent* nsAppShell::GetNextEvent() { AndroidGeckoEvent *ae = nsnull; - PR_Lock(mQueueLock); + MutexAutoLock lock(mQueueLock); if (mEventQueue.Length()) { ae = mEventQueue[0]; mEventQueue.RemoveElementAt(0); @@ -418,7 +412,6 @@ nsAppShell::GetNextEvent() mNumDraws--; } } - PR_Unlock(mQueueLock); return ae; } @@ -427,11 +420,10 @@ AndroidGeckoEvent* nsAppShell::PeekNextEvent() { AndroidGeckoEvent *ae = nsnull; - PR_Lock(mQueueLock); + MutexAutoLock lock(mQueueLock); if (mEventQueue.Length()) { ae = mEventQueue[0]; } - PR_Unlock(mQueueLock); return ae; } @@ -439,12 +431,13 @@ nsAppShell::PeekNextEvent() void nsAppShell::PostEvent(AndroidGeckoEvent *ae) { - PR_Lock(mQueueLock); - mEventQueue.AppendElement(ae); - if (ae->Type() == AndroidGeckoEvent::DRAW) { - mNumDraws++; + { + MutexAutoLock lock(mQueueLock); + mEventQueue.AppendElement(ae); + if (ae->Type() == AndroidGeckoEvent::DRAW) { + mNumDraws++; + } } - PR_Unlock(mQueueLock); NotifyNativeEvent(); } @@ -452,7 +445,7 @@ void nsAppShell::RemoveNextEvent() { AndroidGeckoEvent *ae = nsnull; - PR_Lock(mQueueLock); + MutexAutoLock lock(mQueueLock); if (mEventQueue.Length()) { ae = mEventQueue[0]; mEventQueue.RemoveElementAt(0); @@ -460,7 +453,6 @@ nsAppShell::RemoveNextEvent() mNumDraws--; } } - PR_Unlock(mQueueLock); } void diff --git a/widget/src/android/nsAppShell.h b/widget/src/android/nsAppShell.h index 56f5c9262b2..f396093568f 100644 --- a/widget/src/android/nsAppShell.h +++ b/widget/src/android/nsAppShell.h @@ -39,13 +39,13 @@ #ifndef nsAppShell_h__ #define nsAppShell_h__ +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" #include "nsBaseAppShell.h" #include "nsCOMPtr.h" #include "nsTArray.h" #include "nsInterfaceHashtable.h" -#include "prcvar.h" - namespace mozilla { class AndroidGeckoEvent; bool ProcessNextEvent(); @@ -55,6 +55,9 @@ void NotifyEvent(); class nsAppShell : public nsBaseAppShell { + typedef mozilla::CondVar CondVar; + typedef mozilla::Mutex Mutex; + public: static nsAppShell *gAppShell; static mozilla::AndroidGeckoEvent *gEarlyEvent; @@ -83,9 +86,9 @@ protected: virtual void ScheduleNativeEventCallback(); virtual ~nsAppShell(); - PRLock *mQueueLock; - PRLock *mCondLock; - PRCondVar *mQueueCond; + Mutex mQueueLock; + Mutex mCondLock; + CondVar mQueueCond; int mNumDraws; nsTArray mEventQueue; nsInterfaceHashtable mObserversHash; diff --git a/xpcom/base/nsConsoleService.cpp b/xpcom/base/nsConsoleService.cpp index 0e3721d0dd5..bd26dfce2b4 100644 --- a/xpcom/base/nsConsoleService.cpp +++ b/xpcom/base/nsConsoleService.cpp @@ -53,6 +53,8 @@ #include "nsConsoleMessage.h" #include "nsIClassInfoImpl.h" +using namespace mozilla; + NS_IMPL_THREADSAFE_ADDREF(nsConsoleService) NS_IMPL_THREADSAFE_RELEASE(nsConsoleService) NS_IMPL_CLASSINFO(nsConsoleService, NULL, nsIClassInfo::THREADSAFE | nsIClassInfo::SINGLETON, NS_CONSOLESERVICE_CID) @@ -60,7 +62,7 @@ NS_IMPL_QUERY_INTERFACE1_CI(nsConsoleService, nsIConsoleService) NS_IMPL_CI_INTERFACE_GETTER1(nsConsoleService, nsIConsoleService) nsConsoleService::nsConsoleService() - : mMessages(nsnull), mCurrent(0), mFull(PR_FALSE), mListening(PR_FALSE), mLock(nsnull) + : mMessages(nsnull), mCurrent(0), mFull(PR_FALSE), mListening(PR_FALSE), mLock("nsConsoleService.mLock") { // XXX grab this from a pref! // hm, but worry about circularity, bc we want to be able to report @@ -88,8 +90,6 @@ nsConsoleService::~nsConsoleService() if (mMessages) nsMemory::Free(mMessages); - if (mLock) - nsAutoLock::DestroyLock(mLock); } nsresult @@ -103,10 +103,6 @@ nsConsoleService::Init() // Array elements should be 0 initially for circular buffer algorithm. memset(mMessages, 0, mBufferSize * sizeof(nsIConsoleMessage *)); - mLock = nsAutoLock::NewLock("nsConsoleService::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - return NS_OK; } @@ -137,7 +133,7 @@ nsConsoleService::LogMessage(nsIConsoleMessage *message) * listeners array. */ { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); /* * If there's already a message in the slot we're about to replace, @@ -172,7 +168,7 @@ nsConsoleService::LogMessage(nsIConsoleMessage *message) PRInt32 snapshotCount = listenersSnapshot.Count(); { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mListening) return NS_OK; mListening = PR_TRUE; @@ -183,7 +179,7 @@ nsConsoleService::LogMessage(nsIConsoleMessage *message) } { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mListening = PR_FALSE; } @@ -206,7 +202,7 @@ nsConsoleService::GetMessageArray(nsIConsoleMessage ***messages, PRUint32 *count * Lock the whole method, as we don't want anyone mucking with mCurrent or * mFull while we're copying out the buffer. */ - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mCurrent == 0 && !mFull) { /* @@ -272,7 +268,7 @@ nsConsoleService::RegisterListener(nsIConsoleListener *listener) { return rv; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsISupportsKey key(listener); /* @@ -291,7 +287,7 @@ nsConsoleService::RegisterListener(nsIConsoleListener *listener) { NS_IMETHODIMP nsConsoleService::UnregisterListener(nsIConsoleListener *listener) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsISupportsKey key(listener); mListeners.Remove(&key); @@ -318,7 +314,7 @@ nsConsoleService::Reset() /* * Make sure nobody trips into the buffer while it's being reset */ - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mCurrent = 0; mFull = PR_FALSE; diff --git a/xpcom/base/nsConsoleService.h b/xpcom/base/nsConsoleService.h index 24a6fe7db19..6fbe97fbdc8 100644 --- a/xpcom/base/nsConsoleService.h +++ b/xpcom/base/nsConsoleService.h @@ -42,9 +42,9 @@ #ifndef __nsconsoleservice_h__ #define __nsconsoleservice_h__ +#include "mozilla/Mutex.h" #include "nsCOMPtr.h" #include "nsHashtable.h" -#include "nsAutoLock.h" #include "nsIConsoleService.h" @@ -84,7 +84,7 @@ private: PRBool mListening; // To serialize interesting methods. - PRLock *mLock; + mozilla::Mutex mLock; }; #endif /* __nsconsoleservice_h__ */ diff --git a/xpcom/base/nsExceptionService.cpp b/xpcom/base/nsExceptionService.cpp index 50e1b45af37..7723c8330e4 100644 --- a/xpcom/base/nsExceptionService.cpp +++ b/xpcom/base/nsExceptionService.cpp @@ -41,13 +41,14 @@ #include "nsIServiceManager.h" #include "nsCOMPtr.h" #include "prthread.h" -#include "prlock.h" #include "mozilla/Services.h" +using namespace mozilla; + static const PRUintn BAD_TLS_INDEX = (PRUintn) -1; -#define CHECK_SERVICE_USE_OK() if (!lock) return NS_ERROR_NOT_INITIALIZED -#define CHECK_MANAGER_USE_OK() if (!mService || !nsExceptionService::lock) return NS_ERROR_NOT_INITIALIZED +#define CHECK_SERVICE_USE_OK() if (!sLock) return NS_ERROR_NOT_INITIALIZED +#define CHECK_MANAGER_USE_OK() if (!mService || !nsExceptionService::sLock) return NS_ERROR_NOT_INITIALIZED // A key for our registered module providers hashtable class nsProviderKey : public nsHashKey { @@ -144,7 +145,7 @@ NS_IMETHODIMP nsExceptionManager::GetExceptionFromProvider(nsresult rc, nsIExcep /* The Exception Service */ PRUintn nsExceptionService::tlsIndex = BAD_TLS_INDEX; -PRLock *nsExceptionService::lock = nsnull; +Mutex *nsExceptionService::sLock = nsnull; nsExceptionManager *nsExceptionService::firstThread = nsnull; #ifdef NS_DEBUG @@ -170,8 +171,7 @@ nsExceptionService::nsExceptionService() status = PR_NewThreadPrivateIndex( &tlsIndex, ThreadDestruct ); NS_ASSERTION(status==0, "ScriptErrorService could not allocate TLS storage."); } - lock = PR_NewLock(); - NS_ASSERTION(lock, "Error allocating ExceptionService lock"); + sLock = new Mutex("nsExceptionService.sLock"); // observe XPCOM shutdown. nsCOMPtr observerService = @@ -193,7 +193,7 @@ nsExceptionService::~nsExceptionService() /*static*/ void nsExceptionService::ThreadDestruct( void *data ) { - if (!lock) { + if (!sLock) { NS_WARNING("nsExceptionService ignoring thread destruction after shutdown"); return; } @@ -204,10 +204,10 @@ void nsExceptionService::ThreadDestruct( void *data ) void nsExceptionService::Shutdown() { mProviders.Reset(); - if (lock) { + if (sLock) { DropAllThreads(); - PR_DestroyLock(lock); - lock = nsnull; + delete sLock; + sLock = nsnull; } PR_SetThreadPrivate(tlsIndex, nsnull); } @@ -250,8 +250,6 @@ NS_IMETHODIMP nsExceptionService::GetCurrentExceptionManager(nsIExceptionManager if (mgr == nsnull) { // Stick the new exception object in with no reference count. mgr = new nsExceptionManager(this); - if (mgr == nsnull) - return NS_ERROR_OUT_OF_MEMORY; PR_SetThreadPrivate(tlsIndex, mgr); // The reference count is held in the thread-list AddThread(mgr); @@ -323,11 +321,10 @@ nsExceptionService::DoGetExceptionFromProvider(nsresult errCode, // thread management /*static*/ void nsExceptionService::AddThread(nsExceptionManager *thread) { - PR_Lock(lock); + MutexAutoLock lock(*sLock); thread->mNextThread = firstThread; firstThread = thread; NS_ADDREF(thread); - PR_Unlock(lock); } /*static*/ void nsExceptionService::DoDropThread(nsExceptionManager *thread) @@ -343,15 +340,13 @@ nsExceptionService::DoGetExceptionFromProvider(nsresult errCode, /*static*/ void nsExceptionService::DropThread(nsExceptionManager *thread) { - PR_Lock(lock); + MutexAutoLock lock(*sLock); DoDropThread(thread); - PR_Unlock(lock); } /*static*/ void nsExceptionService::DropAllThreads() { - PR_Lock(lock); + MutexAutoLock lock(*sLock); while (firstThread) DoDropThread(firstThread); - PR_Unlock(lock); } diff --git a/xpcom/base/nsExceptionService.h b/xpcom/base/nsExceptionService.h index 01fb83f66a4..db3b9c3b961 100644 --- a/xpcom/base/nsExceptionService.h +++ b/xpcom/base/nsExceptionService.h @@ -39,6 +39,7 @@ #ifndef nsExceptionService_h__ #define nsExceptionService_h__ +#include "mozilla/Mutex.h" #include "nsIException.h" #include "nsIExceptionService.h" #include "nsIObserverService.h" @@ -77,7 +78,7 @@ public: /* single lock protects both providers hashtable and thread list */ - static PRLock* lock; + static mozilla::Mutex* sLock; static PRUintn tlsIndex; static void ThreadDestruct( void *data ); diff --git a/xpcom/base/nsMemoryImpl.cpp b/xpcom/base/nsMemoryImpl.cpp index 77fb4d6a821..012d90a1fb0 100644 --- a/xpcom/base/nsMemoryImpl.cpp +++ b/xpcom/base/nsMemoryImpl.cpp @@ -49,7 +49,6 @@ #include "pratom.h" #include "nsAlgorithm.h" -#include "nsAutoLock.h" #include "nsCOMPtr.h" #include "nsString.h" #include "mozilla/Services.h" diff --git a/xpcom/base/nsTraceRefcntImpl.cpp b/xpcom/base/nsTraceRefcntImpl.cpp index 9f8bb279486..a912b37052d 100644 --- a/xpcom/base/nsTraceRefcntImpl.cpp +++ b/xpcom/base/nsTraceRefcntImpl.cpp @@ -104,6 +104,8 @@ NS_MeanAndStdDev(double n, double sumOfValues, double sumOfSquaredValues, #include "prlock.h" +// TraceRefcnt has to use bare PRLock instead of mozilla::Mutex +// because TraceRefcnt can be used very early in startup. static PRLock* gTraceLock; #define LOCK_TRACELOG() PR_Lock(gTraceLock) diff --git a/xpcom/base/nsUUIDGenerator.cpp b/xpcom/base/nsUUIDGenerator.cpp index 83f584f8491..f8c97a76b44 100644 --- a/xpcom/base/nsUUIDGenerator.cpp +++ b/xpcom/base/nsUUIDGenerator.cpp @@ -48,31 +48,24 @@ #include "nsMemory.h" -#include "nsAutoLock.h" - #include "nsUUIDGenerator.h" +using namespace mozilla; + NS_IMPL_THREADSAFE_ISUPPORTS1(nsUUIDGenerator, nsIUUIDGenerator) nsUUIDGenerator::nsUUIDGenerator() - : mLock(nsnull) + : mLock("nsUUIDGenerator.mLock") { } nsUUIDGenerator::~nsUUIDGenerator() { - if (mLock) { - nsAutoLock::DestroyLock(mLock); - } } nsresult nsUUIDGenerator::Init() { - mLock = nsAutoLock::NewLock("nsUUIDGenerator::mLock"); - - NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY); - // We're a service, so we're guaranteed that Init() is not going // to be reentered while we're inside Init(). @@ -136,7 +129,7 @@ nsUUIDGenerator::GenerateUUIDInPlace(nsID* id) { // The various code in this method is probably not threadsafe, so lock // across the whole method. - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); #if defined(WINCE) // WINCE only has CoCreateGuid if DCOM support is compiled into the BSP; diff --git a/xpcom/base/nsUUIDGenerator.h b/xpcom/base/nsUUIDGenerator.h index a07e633449d..fb2dc722453 100644 --- a/xpcom/base/nsUUIDGenerator.h +++ b/xpcom/base/nsUUIDGenerator.h @@ -39,8 +39,8 @@ #ifndef _NSUUIDGENERATOR_H_ #define _NSUUIDGENERATOR_H_ +#include "mozilla/Mutex.h" #include "nsIUUIDGenerator.h" -#include "prlock.h" class nsUUIDGenerator : public nsIUUIDGenerator { public: @@ -57,7 +57,7 @@ private: protected: - PRLock* mLock; + mozilla::Mutex mLock; #if defined(WINCE) #elif !defined(XP_WIN) && !defined(XP_MACOSX) && !defined(ANDROID) char mState[128]; diff --git a/xpcom/build/XPCOM.h b/xpcom/build/XPCOM.h index ad224caba94..15b28f333f9 100644 --- a/xpcom/build/XPCOM.h +++ b/xpcom/build/XPCOM.h @@ -163,7 +163,6 @@ #include "nsArrayEnumerator.h" #include "nsArrayUtils.h" -#include "nsAutoLock.h" #include "nsCRTGlue.h" #include "nsCycleCollectionParticipant.h" #include "nsDeque.h" diff --git a/xpcom/build/nsXPComInit.cpp b/xpcom/build/nsXPComInit.cpp index 722bbc56358..8bc3aa8dbe9 100644 --- a/xpcom/build/nsXPComInit.cpp +++ b/xpcom/build/nsXPComInit.cpp @@ -183,10 +183,6 @@ extern nsresult NS_CategoryManagerGetFactory( nsIFactory** ); extern nsresult ScheduleMediaCacheRemover(); #endif -#ifdef DEBUG -extern void _FreeAutoLockStatics(); -#endif - NS_GENERIC_FACTORY_CONSTRUCTOR(nsProcess) NS_GENERIC_FACTORY_CONSTRUCTOR(nsSupportsIDImpl) @@ -744,11 +740,6 @@ ShutdownXPCOM(nsIServiceManager* servMgr) nsComponentManagerImpl::gComponentManager = nsnull; nsCategoryManager::Destroy(); -#ifdef DEBUG - // FIXME BUG 456272: this should disappear - _FreeAutoLockStatics(); -#endif - ShutdownSpecialSystemDirectory(); NS_PurgeAtomTable(); diff --git a/xpcom/components/nsComponentManager.cpp b/xpcom/components/nsComponentManager.cpp index e8c1d52a76b..ceb1cbe80fd 100644 --- a/xpcom/components/nsComponentManager.cpp +++ b/xpcom/components/nsComponentManager.cpp @@ -58,7 +58,6 @@ #define PL_ARENA_CONST_ALIGN_MASK 7 #define NS_CM_BLOCK_SIZE (1024 * 8) -#include "nsAutoLock.h" #include "nsCategoryManager.h" #include "nsCOMPtr.h" #include "nsComponentManager.h" @@ -106,6 +105,8 @@ static NS_DEFINE_CID(kZipReaderCID, NS_ZIPREADER_CID); #include "prlog.h" +using namespace mozilla; + NS_COM PRLogModuleInfo* nsComponentManagerLog = nsnull; #if 0 || defined (DEBUG_timeless) @@ -292,7 +293,7 @@ nsComponentManagerImpl::Create(nsISupports* aOuter, REFNSIID aIID, void** aResul } nsComponentManagerImpl::nsComponentManagerImpl() - : mMon(NULL) + : mMon("nsComponentManagerImpl.mMon") , mStatus(NOT_INITIALIZED) { } @@ -348,10 +349,6 @@ nsresult nsComponentManagerImpl::Init() mKnownFileModules.Init(); mKnownJARModules.Init(); - mMon = nsAutoMonitor::NewMonitor("nsComponentManagerImpl"); - if (mMon == nsnull) - return NS_ERROR_OUT_OF_MEMORY; - nsCOMPtr greDir = GetLocationFromDirectoryService(NS_GRE_DIR); nsCOMPtr appDir = @@ -431,7 +428,7 @@ void nsComponentManagerImpl::RegisterModule(const mozilla::Module* aModule, nsILocalFile* aFile) { - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); KnownModule* m = new KnownModule(aModule, aFile); if (aFile) { @@ -471,7 +468,7 @@ void nsComponentManagerImpl::RegisterCIDEntry(const mozilla::Module::CIDEntry* aEntry, KnownModule* aModule) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMon); + mMon.AssertCurrentThreadIn(); nsFactoryEntry* f = mFactories.Get(*aEntry->cid); if (f) { @@ -500,7 +497,7 @@ nsComponentManagerImpl::RegisterCIDEntry(const mozilla::Module::CIDEntry* aEntry void nsComponentManagerImpl::RegisterContractID(const mozilla::Module::ContractIDEntry* aEntry) { - PR_ASSERT_CURRENT_THREAD_IN_MONITOR(mMon); + mMon.AssertCurrentThreadIn(); nsFactoryEntry* f = mFactories.Get(*aEntry->cid); if (!f) { @@ -798,7 +795,7 @@ nsComponentManagerImpl::ManifestComponent(ManifestProcessingContext& cx, int lin return; } - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); nsFactoryEntry* f = mFactories.Get(cid); if (f) { char idstr[NSID_LENGTH]; @@ -883,7 +880,7 @@ nsComponentManagerImpl::ManifestContract(ManifestProcessingContext& cx, int line return; } - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); nsFactoryEntry* f = mFactories.Get(cid); if (!f) { LogMessageWithContext(cx.mFile, cx.mPath, lineno, @@ -1036,9 +1033,6 @@ nsComponentManagerImpl::~nsComponentManagerImpl() if (SHUTDOWN_COMPLETE != mStatus) Shutdown(); - if (mMon) { - nsAutoMonitor::DestroyMonitor(mMon); - } PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, ("nsComponentManager: Destroyed.")); } @@ -1063,7 +1057,7 @@ nsFactoryEntry * nsComponentManagerImpl::GetFactoryEntry(const char *aContractID, PRUint32 aContractIDLen) { - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); return mContractIDs.Get(nsDependentCString(aContractID, aContractIDLen)); } @@ -1071,7 +1065,7 @@ nsComponentManagerImpl::GetFactoryEntry(const char *aContractID, nsFactoryEntry * nsComponentManagerImpl::GetFactoryEntry(const nsCID &aClass) { - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); return mFactories.Get(aClass); } @@ -1387,6 +1381,47 @@ nsComponentManagerImpl::GetPendingServiceThread(const nsCID& aServiceCID) const return nsnull; } +// GetService() wants to manually Exit()/Enter() a monitor which is +// wrapped in MonitorAutoEnter, which nsAutoMonitor used to allow. +// One use is block-scoped Exit()/Enter(), which could be supported +// with something like a MonitoAutoExit, but that's not a well-defined +// operation in general so that helper doesn't exist. The other use +// is early-Exit() for perf reasons. This code is probably hot enough +// to warrant special considerations. +// +// We could use bare mozilla::Monitor, but that's error prone. +// Instead, we just add a hacky wrapper here that acts like the old +// nsAutoMonitor. +struct NS_STACK_CLASS AutoMonitor +{ + AutoMonitor(Monitor& aMonitor) : mMonitor(&aMonitor), mEnterCount(0) + { + Enter(); + } + + ~AutoMonitor() + { + if (mEnterCount) { + Exit(); + } + } + + void Enter() + { + mMonitor->Enter(); + ++mEnterCount; + } + + void Exit() + { + --mEnterCount; + mMonitor->Exit(); + } + + Monitor* mMonitor; + PRInt32 mEnterCount; +}; + NS_IMETHODIMP nsComponentManagerImpl::GetService(const nsCID& aClass, const nsIID& aIID, @@ -1407,7 +1442,7 @@ nsComponentManagerImpl::GetService(const nsCID& aClass, return NS_ERROR_UNEXPECTED; } - nsAutoMonitor mon(mMon); + AutoMonitor mon(mMon); nsFactoryEntry* entry = mFactories.Get(aClass); if (!entry) @@ -1526,7 +1561,7 @@ nsComponentManagerImpl::IsServiceInstantiated(const nsCID & aClass, nsFactoryEntry* entry; { - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); entry = mFactories.Get(aClass); } @@ -1565,7 +1600,7 @@ NS_IMETHODIMP nsComponentManagerImpl::IsServiceInstantiatedByContractID(const ch nsresult rv = NS_ERROR_SERVICE_NOT_AVAILABLE; nsFactoryEntry *entry; { - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); entry = mContractIDs.Get(nsDependentCString(aContractID)); } @@ -1597,7 +1632,7 @@ nsComponentManagerImpl::GetServiceByContractID(const char* aContractID, return NS_ERROR_UNEXPECTED; } - nsAutoMonitor mon(mMon); + AutoMonitor mon(mMon); nsFactoryEntry *entry = mContractIDs.Get(nsDependentCString(aContractID)); if (!entry) @@ -1717,7 +1752,7 @@ nsComponentManagerImpl::RegisterFactory(const nsCID& aClass, if (!aContractID) return NS_ERROR_INVALID_ARG; - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); nsFactoryEntry* oldf = mFactories.Get(aClass); if (!oldf) return NS_ERROR_FACTORY_NOT_REGISTERED; @@ -1728,7 +1763,7 @@ nsComponentManagerImpl::RegisterFactory(const nsCID& aClass, nsAutoPtr f(new nsFactoryEntry(aClass, aFactory)); - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); nsFactoryEntry* oldf = mFactories.Get(aClass); if (oldf) return NS_ERROR_FACTORY_EXISTS; @@ -1751,7 +1786,7 @@ nsComponentManagerImpl::UnregisterFactory(const nsCID& aClass, nsCOMPtr dyingServiceObject; { - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); nsFactoryEntry* f = mFactories.Get(aClass); if (!f || f->mFactory != aFactory) return NS_ERROR_FACTORY_NOT_REGISTERED; @@ -1886,7 +1921,7 @@ nsComponentManagerImpl::ContractIDToCID(const char *aContractID, nsCID * *_retval) { { - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); nsFactoryEntry* entry = mContractIDs.Get(nsDependentCString(aContractID)); if (entry) { *_retval = (nsCID*) NS_Alloc(sizeof(nsCID)); diff --git a/xpcom/components/nsComponentManager.h b/xpcom/components/nsComponentManager.h index d6eee6c161e..c438d40d7ca 100644 --- a/xpcom/components/nsComponentManager.h +++ b/xpcom/components/nsComponentManager.h @@ -47,6 +47,7 @@ #include "nsILocalFile.h" #include "mozilla/Module.h" #include "mozilla/ModuleLoader.h" +#include "mozilla/Monitor.h" #include "nsXULAppAPI.h" #include "nsNativeComponentLoader.h" #include "nsIFactory.h" @@ -54,7 +55,6 @@ #include "nsIInterfaceRequestorUtils.h" #include "pldhash.h" #include "prtime.h" -#include "prmon.h" #include "nsCOMPtr.h" #include "nsAutoPtr.h" #include "nsWeakReference.h" @@ -150,7 +150,7 @@ public: nsDataHashtable mFactories; nsDataHashtable mContractIDs; - PRMonitor* mMon; + mozilla::Monitor mMon; static void InitializeStaticModules(); static void InitializeModuleLocations(); diff --git a/xpcom/ds/TimeStamp.cpp b/xpcom/ds/TimeStamp.cpp index b8f4b574859..75c5c5dfcbc 100644 --- a/xpcom/ds/TimeStamp.cpp +++ b/xpcom/ds/TimeStamp.cpp @@ -90,6 +90,8 @@ TimeStamp::Startup() if (gTimeStampLock) return NS_OK; + // TimeStamp has to use bare PRLock instead of mozilla::Mutex + // because TimeStamp can be used very early in startup. gTimeStampLock = PR_NewLock(); gRolloverCount = 1; gLastNow = 0; diff --git a/xpcom/ds/nsRecyclingAllocator.cpp b/xpcom/ds/nsRecyclingAllocator.cpp index f449fe10553..fdb58a6ebcb 100644 --- a/xpcom/ds/nsRecyclingAllocator.cpp +++ b/xpcom/ds/nsRecyclingAllocator.cpp @@ -45,10 +45,11 @@ #include #include "nsRecyclingAllocator.h" #include "nsIMemory.h" -#include "nsAutoLock.h" #include "prprf.h" #include "nsITimer.h" +using namespace mozilla; + #define NS_SEC_TO_MS(s) ((s) * 1000) void @@ -56,7 +57,7 @@ nsRecyclingAllocator::nsRecycleTimerCallback(nsITimer *aTimer, void *aClosure) { nsRecyclingAllocator *obj = (nsRecyclingAllocator *) aClosure; - nsAutoLock lock(obj->mLock); + MutexAutoLock lock(obj->mLock); if (!obj->mTouched) { @@ -73,19 +74,18 @@ nsRecyclingAllocator::nsRecycleTimerCallback(nsITimer *aTimer, void *aClosure) nsRecyclingAllocator::nsRecyclingAllocator(PRUint32 nbucket, PRUint32 recycleAfter, const char *id) : mMaxBlocks(nbucket), mFreeListCount(0), mFreeList(nsnull), + mLock("nsRecyclingAllocator.mLock"), mRecycleTimer(nsnull), mRecycleAfter(recycleAfter), mTouched(PR_FALSE) #ifdef DEBUG , mId(id), mNAllocated(0) #endif { - mLock = nsAutoLock::NewLock("nsRecyclingAllocatior::mLock"); - NS_ASSERTION(mLock, "Recycling allocator cannot get lock"); } nsresult nsRecyclingAllocator::Init(PRUint32 nbucket, PRUint32 recycleAfter, const char *id) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); ClearFreeList(); @@ -102,12 +102,6 @@ nsRecyclingAllocator::Init(PRUint32 nbucket, PRUint32 recycleAfter, const char * nsRecyclingAllocator::~nsRecyclingAllocator() { ClearFreeList(); - - if (mLock) - { - nsAutoLock::DestroyLock(mLock); - mLock = nsnull; - } } // Allocation and free routines @@ -130,7 +124,7 @@ nsRecyclingAllocator::Malloc(PRSize bytes, PRBool zeroit) // there are no free blocks, we don't want to impose any more overhead than // we already are for failing over to malloc/free. if (mFreeList) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Mark that we are using. This will prevent any // Timer based release of unused memory. @@ -187,7 +181,7 @@ nsRecyclingAllocator::Free(void *ptr) { Block* block = DATA_TO_BLOCK(ptr); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Mark that we are using the allocator. This will prevent any // timer based release of unused memory. diff --git a/xpcom/ds/nsRecyclingAllocator.h b/xpcom/ds/nsRecyclingAllocator.h index 3941b8923ec..d891258ad74 100644 --- a/xpcom/ds/nsRecyclingAllocator.h +++ b/xpcom/ds/nsRecyclingAllocator.h @@ -61,8 +61,8 @@ #ifndef nsRecyclingAllocator_h__ #define nsRecyclingAllocator_h__ +#include "mozilla/Mutex.h" #include "nscore.h" -#include "prlock.h" #include "nsIRecyclingAllocator.h" #define NS_DEFAULT_RECYCLE_TIMEOUT 10 // secs @@ -92,7 +92,7 @@ class NS_COM nsRecyclingAllocator { // mLock: Thread safety for the member variables: // mFreeList, mFreeListCount, mRecycleTimer, and mTouched - PRLock *mLock; + mozilla::Mutex mLock; // Timer for freeing unused memory nsITimer *mRecycleTimer; diff --git a/xpcom/glue/BlockingResourceBase.h b/xpcom/glue/BlockingResourceBase.h index 8291591d9c7..b9d64b72ebe 100644 --- a/xpcom/glue/BlockingResourceBase.h +++ b/xpcom/glue/BlockingResourceBase.h @@ -47,6 +47,7 @@ #include "nscore.h" #include "nsDebug.h" #include "nsError.h" +#include "nsTraceRefcnt.h" #ifdef DEBUG #include "prinit.h" @@ -109,6 +110,7 @@ private: mType(aType), mAcquisitionContext(CallStack::kNone) { + NS_ABORT_IF_FALSE(mName, "Name must be nonnull"); } /** diff --git a/xpcom/glue/CondVar.h b/xpcom/glue/CondVar.h index e186f889d9f..57cf26c6c1f 100644 --- a/xpcom/glue/CondVar.h +++ b/xpcom/glue/CondVar.h @@ -70,6 +70,7 @@ public: BlockingResourceBase(aName, eCondVar), mLock(&aLock) { + MOZ_COUNT_CTOR(CondVar); // |lock| must necessarily already be known to the deadlock detector mCvar = PR_NewCondVar(mLock->mLock); if (!mCvar) @@ -87,6 +88,7 @@ public: PR_DestroyCondVar(mCvar); mCvar = 0; mLock = 0; + MOZ_COUNT_DTOR(CondVar); } #ifndef DEBUG diff --git a/xpcom/glue/Makefile.in b/xpcom/glue/Makefile.in index 424dbec5929..c3b17c19e65 100644 --- a/xpcom/glue/Makefile.in +++ b/xpcom/glue/Makefile.in @@ -66,11 +66,9 @@ CPPSRCS = \ GenericModule.cpp \ $(NULL) -# TODO nsAutoLock.h should die soon SDK_HEADERS = \ nsArrayEnumerator.h \ nsArrayUtils.h \ - nsAutoLock.h \ nsBaseHashtable.h \ nsCOMArray.h \ nsCOMPtr.h \ diff --git a/xpcom/glue/Monitor.h b/xpcom/glue/Monitor.h index 6d6b3851cba..02f999562f2 100644 --- a/xpcom/glue/Monitor.h +++ b/xpcom/glue/Monitor.h @@ -78,6 +78,7 @@ public: , mEntryCount(0) #endif { + MOZ_COUNT_CTOR(Monitor); mMonitor = PR_NewMonitor(); if (!mMonitor) NS_RUNTIMEABORT("Can't allocate mozilla::Monitor"); @@ -92,6 +93,7 @@ public: "improperly constructed Monitor or double free"); PR_DestroyMonitor(mMonitor); mMonitor = 0; + MOZ_COUNT_DTOR(Monitor); } #ifndef DEBUG diff --git a/xpcom/glue/Mutex.h b/xpcom/glue/Mutex.h index 489e003078f..25686cee40f 100644 --- a/xpcom/glue/Mutex.h +++ b/xpcom/glue/Mutex.h @@ -77,6 +77,7 @@ public: Mutex(const char* name) : BlockingResourceBase(name, eMutex) { + MOZ_COUNT_CTOR(Mutex); mLock = PR_NewLock(); if (!mLock) NS_RUNTIMEABORT("Can't allocate mozilla::Mutex"); @@ -92,6 +93,7 @@ public: // NSPR does consistency checks for us PR_DestroyLock(mLock); mLock = 0; + MOZ_COUNT_DTOR(Mutex); } #ifndef DEBUG diff --git a/xpcom/glue/nsAutoLock.cpp b/xpcom/glue/nsAutoLock.cpp deleted file mode 100644 index c4fbf60be0a..00000000000 --- a/xpcom/glue/nsAutoLock.cpp +++ /dev/null @@ -1,464 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either of the GNU General Public License Version 2 or later (the "GPL"), - * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - -#include "nsAutoLock.h" - -#ifdef DEBUG - -#include "plhash.h" -#include "prprf.h" -#include "prthread.h" -#include "nsDebug.h" -#include "nsVoidArray.h" - -#ifdef NS_TRACE_MALLOC -# include -# include "nsTraceMalloc.h" -#endif - -static PRUintn LockStackTPI = (PRUintn)-1; -static PLHashTable* OrderTable = 0; -static PRLock* OrderTableLock = 0; - -static const char* const LockTypeNames[] = {"Lock", "Monitor", "CMonitor"}; - -struct nsNamedVector : public nsVoidArray { - const char* mName; - -#ifdef NS_TRACE_MALLOC - // Callsites for the inner locks/monitors stored in our base nsVoidArray. - // This array parallels our base nsVoidArray. - nsVoidArray mInnerSites; -#endif - - nsNamedVector(const char* name = 0, PRUint32 initialSize = 0) - : nsVoidArray(initialSize), - mName(name) - { - } -}; - -static void * -_hash_alloc_table(void *pool, PRSize size) -{ - return operator new(size); -} - -static void -_hash_free_table(void *pool, void *item) -{ - operator delete(item); -} - -static PLHashEntry * -_hash_alloc_entry(void *pool, const void *key) -{ - return new PLHashEntry; -} - -/* - * Because monitors and locks may be associated with an nsAutoLockBase, - * without having had their associated nsNamedVector created explicitly in - * nsAutoMonitor::NewMonitor/DeleteMonitor, we need to provide a freeEntry - * PLHashTable hook, to avoid leaking nsNamedVectors which are replaced by - * nsAutoMonitor::NewMonitor. - * - * There is still a problem with the OrderTable containing orphaned - * nsNamedVector entries, for manually created locks wrapped by nsAutoLocks. - * (there should be no manually created monitors wrapped by nsAutoMonitors: - * you should use nsAutoMonitor::NewMonitor and nsAutoMonitor::DestroyMonitor - * instead of PR_NewMonitor and PR_DestroyMonitor). These lock vectors don't - * strictly leak, as they are killed on shutdown, but there are unnecessary - * named vectors in the hash table that outlive their associated locks. - * - * XXX so we should have nsLock, nsMonitor, etc. and strongly type their - * XXX nsAutoXXX counterparts to take only the non-auto types as inputs - */ -static void -_hash_free_entry(void *pool, PLHashEntry *entry, PRUintn flag) -{ - nsNamedVector* vec = (nsNamedVector*) entry->value; - if (vec) { - entry->value = 0; - delete vec; - } - if (flag == HT_FREE_ENTRY) - delete entry; -} - -static const PLHashAllocOps _hash_alloc_ops = { - _hash_alloc_table, _hash_free_table, - _hash_alloc_entry, _hash_free_entry -}; - -static PRIntn -_purge_one(PLHashEntry* he, PRIntn cnt, void* arg) -{ - nsNamedVector* vec = (nsNamedVector*) he->value; - - if (he->key == arg) - return HT_ENUMERATE_REMOVE; - vec->RemoveElement(arg); - return HT_ENUMERATE_NEXT; -} - -/* static */ void -nsAutoLockBase::OnSemaphoreRecycle(void* addr) -{ - if (OrderTable) { - PR_Lock(OrderTableLock); - PL_HashTableEnumerateEntries(OrderTable, _purge_one, addr); - PR_Unlock(OrderTableLock); - } -} - -static PLHashNumber -_hash_pointer(const void* key) -{ - return PLHashNumber(NS_PTR_TO_INT32(key)) >> 2; -} - -// Must be single-threaded here, early in primordial thread. -/* static */ void -nsAutoLockBase::InitAutoLockStatics() -{ - (void) PR_NewThreadPrivateIndex(&LockStackTPI, 0); - OrderTable = PL_NewHashTable(64, _hash_pointer, - PL_CompareValues, PL_CompareValues, - &_hash_alloc_ops, 0); - if (OrderTable && !(OrderTableLock = PR_NewLock())) { - PL_HashTableDestroy(OrderTable); - OrderTable = 0; - } - PR_CSetOnMonitorRecycle(nsAutoLockBase::OnSemaphoreRecycle); -} - -void _FreeAutoLockStatics() -{ - PLHashTable* table = OrderTable; - if (!table) return; - - // Called at shutdown, so we don't need to lock. - PR_CSetOnMonitorRecycle(0); - PR_DestroyLock(OrderTableLock); - OrderTableLock = 0; - PL_HashTableDestroy(table); - OrderTable = 0; -} - -static nsNamedVector* GetVector(PLHashTable* table, const void* key) -{ - PLHashNumber hash = _hash_pointer(key); - PLHashEntry** hep = PL_HashTableRawLookup(table, hash, key); - PLHashEntry* he = *hep; - if (he) - return (nsNamedVector*) he->value; - nsNamedVector* vec = new nsNamedVector(); - if (vec) - PL_HashTableRawAdd(table, hep, hash, key, vec); - return vec; -} - -/* static */ void -nsAutoLockBase::OnSemaphoreCreated(const void* key, const char* name ) -{ - if (LockStackTPI == PRUintn(-1)) - InitAutoLockStatics(); - - if (key && OrderTable) { - nsNamedVector* value = new nsNamedVector(name); - if (value) { - PR_Lock(OrderTableLock); - PL_HashTableAdd(OrderTable, key, value); - PR_Unlock(OrderTableLock); - } - } -} - -// We maintain an acyclic graph in OrderTable, so recursion can't diverge. -static PRBool Reachable(PLHashTable* table, const void* goal, const void* start) -{ - PR_ASSERT(goal); - PR_ASSERT(start); - nsNamedVector* vec = GetVector(table, start); - for (PRUint32 i = 0, n = vec->Count(); i < n; i++) { - void* addr = vec->ElementAt(i); - if (addr == goal || Reachable(table, goal, addr)) - return PR_TRUE; - } - return PR_FALSE; -} - -static PRBool WellOrdered(const void* addr1, const void* addr2, - const void *callsite2, PRUint32* index2p, - nsNamedVector** vec1p, nsNamedVector** vec2p) -{ - PRBool rv = PR_TRUE; - PLHashTable* table = OrderTable; - if (!table) return rv; - PR_Lock(OrderTableLock); - - // Check whether we've already asserted (addr1 < addr2). - nsNamedVector* vec1 = GetVector(table, addr1); - if (vec1) { - PRUint32 i, n; - - NS_ASSERTION(vec1->mName, - "caller should have used nsAutoLock::NewLock " - "or nsAutoMonitor::NewMonitor"); - - for (i = 0, n = vec1->Count(); i < n; i++) - if (vec1->ElementAt(i) == addr2) - break; - - if (i == n) { - // Now check for (addr2 < addr1) and return false if so. - nsNamedVector* vec2 = GetVector(table, addr2); - if (vec2) { - NS_ASSERTION(vec2->mName, - "caller should have used nsAutoLock::NewLock " - "or nsAutoMonitor::NewMonitor"); - for (i = 0, n = vec2->Count(); i < n; i++) { - void* addri = vec2->ElementAt(i); - PR_ASSERT(addri); - if (addri == addr1 || Reachable(table, addr1, addri)) { - *index2p = i; - *vec1p = vec1; - *vec2p = vec2; - rv = PR_FALSE; - break; - } - } - - if (rv) { - // Assert (addr1 < addr2) into the order table. - // XXX fix plvector/nsVector to use const void* - vec1->AppendElement((void*) addr2); -#ifdef NS_TRACE_MALLOC - vec1->mInnerSites.AppendElement((void*) callsite2); -#endif - } - } - } - } - - PR_Unlock(OrderTableLock); - return rv; -} - -nsAutoLockBase::nsAutoLockBase(void* addr, nsAutoLockType type) -{ - if (LockStackTPI == PRUintn(-1)) - InitAutoLockStatics(); - - nsAutoLockBase* stackTop = - (nsAutoLockBase*) PR_GetThreadPrivate(LockStackTPI); - if (stackTop) { - if (stackTop->mAddr == addr) { - // Ignore reentry: it's legal for monitors, and NSPR will assert - // if you reenter a PRLock. - } else if (!addr) { - // Ignore null addresses: the caller promises not to use the - // lock at all, and NSPR will assert if you enter it. - } else { - const void* node = -#ifdef NS_TRACE_MALLOC - (const void*)NS_TraceMallocGetStackTrace(); -#else - nsnull -#endif - ; - nsNamedVector* vec1; - nsNamedVector* vec2; - PRUint32 i2; - - if (!WellOrdered(stackTop->mAddr, addr, node, &i2, &vec1, &vec2)) { - char buf[128]; - PR_snprintf(buf, sizeof buf, - "Potential deadlock between %s%s@%p and %s%s@%p", - vec1->mName ? vec1->mName : "", - LockTypeNames[stackTop->mType], - stackTop->mAddr, - vec2->mName ? vec2->mName : "", - LockTypeNames[type], - addr); -#ifdef NS_TRACE_MALLOC - fprintf(stderr, "\n*** %s\n\nCurrent stack:\n", buf); - NS_TraceMallocPrintStackTrace(stderr, - NS_TraceMallocGetStackTrace()); - - fputs("\nPrevious stack:\n", stderr); - NS_TraceMallocPrintStackTrace(stderr, - (nsTMStackTraceIDStruct *)vec2->mInnerSites.ElementAt(i2)); - putc('\n', stderr); -#endif - NS_ERROR(buf); - } - } - } - - mAddr = addr; - mDown = stackTop; - mType = type; - if (mAddr) - (void) PR_SetThreadPrivate(LockStackTPI, this); -} - -nsAutoLockBase::~nsAutoLockBase() -{ - if (mAddr) - (void) PR_SetThreadPrivate(LockStackTPI, mDown); -} - -void nsAutoLockBase::Show() -{ - if (!mAddr) - return; - nsAutoLockBase* curr = (nsAutoLockBase*) PR_GetThreadPrivate(LockStackTPI); - nsAutoLockBase* prev = nsnull; - while (curr != mDown) { - prev = curr; - curr = prev->mDown; - } - if (!prev) - PR_SetThreadPrivate(LockStackTPI, this); - else - prev->mDown = this; -} - -void nsAutoLockBase::Hide() -{ - if (!mAddr) - return; - nsAutoLockBase* curr = (nsAutoLockBase*) PR_GetThreadPrivate(LockStackTPI); - nsAutoLockBase* prev = nsnull; - while (curr != this) { - prev = curr; - curr = prev->mDown; - } - if (!prev) - PR_SetThreadPrivate(LockStackTPI, mDown); - else - prev->mDown = mDown; -} - -nsAutoUnlockBase::nsAutoUnlockBase(void* addr) -{ - if (addr) - { - nsAutoLockBase* curr = (nsAutoLockBase*) PR_GetThreadPrivate(LockStackTPI); - while (curr && curr->mAddr != addr) - curr = curr->mDown; - - mLock = curr; - } - else - mLock = nsnull; - - if (mLock) - mLock->Hide(); -} - -nsAutoUnlockBase::~nsAutoUnlockBase() -{ - if (mLock) - mLock->Show(); -} - -#endif /* DEBUG */ - -void nsAutoMonitor::Enter() -{ -#ifdef DEBUG - if (!mAddr) { - NS_ERROR("It is not legal to enter a null monitor"); - return; - } - nsAutoLockBase* stackTop = - (nsAutoLockBase*) PR_GetThreadPrivate(LockStackTPI); - NS_ASSERTION(stackTop == mDown, "non-LIFO nsAutoMonitor::Enter"); - mDown = stackTop; - (void) PR_SetThreadPrivate(LockStackTPI, this); -#endif - PR_EnterMonitor(mMonitor); - mLockCount += 1; -} - -void nsAutoMonitor::Exit() -{ -#ifdef DEBUG - if (!mAddr) { - NS_ERROR("It is not legal to exit a null monitor"); - return; - } - (void) PR_SetThreadPrivate(LockStackTPI, mDown); -#endif - // Split 'status' init to avoid an "unused variable" compiler warning. - PRStatus status; - status = PR_ExitMonitor(mMonitor); - NS_ASSERTION(status == PR_SUCCESS, "PR_ExitMonitor failed"); - mLockCount -= 1; -} - -// XXX we don't worry about cached monitors being destroyed behind our back. -// XXX current NSPR (mozilla/nsprpub/pr/src/threads/prcmon.c) never destroys -// XXX a cached monitor! potential resource pig in conjunction with necko... - -void nsAutoCMonitor::Enter() -{ -#ifdef DEBUG - nsAutoLockBase* stackTop = - (nsAutoLockBase*) PR_GetThreadPrivate(LockStackTPI); - NS_ASSERTION(stackTop == mDown, "non-LIFO nsAutoCMonitor::Enter"); - mDown = stackTop; - (void) PR_SetThreadPrivate(LockStackTPI, this); -#endif - PR_CEnterMonitor(mLockObject); - mLockCount += 1; -} - -void nsAutoCMonitor::Exit() -{ -#ifdef DEBUG - (void) PR_SetThreadPrivate(LockStackTPI, mDown); -#endif - // Split 'status' init to avoid an "unused variable" compiler warning. - PRStatus status; - status = PR_CExitMonitor(mLockObject); - NS_ASSERTION(status == PR_SUCCESS, "PR_CExitMonitor failed"); - mLockCount -= 1; -} diff --git a/xpcom/glue/nsAutoLock.h b/xpcom/glue/nsAutoLock.h deleted file mode 100644 index 189dda35786..00000000000 --- a/xpcom/glue/nsAutoLock.h +++ /dev/null @@ -1,491 +0,0 @@ -/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ -/* ***** BEGIN LICENSE BLOCK ***** - * Version: MPL 1.1/GPL 2.0/LGPL 2.1 - * - * The contents of this file are subject to the Mozilla Public License Version - * 1.1 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * http://www.mozilla.org/MPL/ - * - * Software distributed under the License is distributed on an "AS IS" basis, - * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License - * for the specific language governing rights and limitations under the - * License. - * - * The Original Code is mozilla.org code. - * - * The Initial Developer of the Original Code is - * Netscape Communications Corporation. - * Portions created by the Initial Developer are Copyright (C) 1998 - * the Initial Developer. All Rights Reserved. - * - * Contributor(s): - * - * Alternatively, the contents of this file may be used under the terms of - * either of the GNU General Public License Version 2 or later (the "GPL"), - * or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), - * in which case the provisions of the GPL or the LGPL are applicable instead - * of those above. If you wish to allow use of your version of this file only - * under the terms of either the GPL or the LGPL, and not to allow others to - * use your version of this file under the terms of the MPL, indicate your - * decision by deleting the provisions above and replace them with the notice - * and other provisions required by the GPL or the LGPL. If you do not delete - * the provisions above, a recipient may use your version of this file under - * the terms of any one of the MPL, the GPL or the LGPL. - * - * ***** END LICENSE BLOCK ***** */ - - -/* - A stack-based lock object that makes using PRLock a bit more - convenient. It acquires the monitor when constructed, and releases - it when it goes out of scope. - - For example, - - class Foo { - private: - PRLock* mLock; - - public: - Foo(void) { - mLock = nsAutoLock::NewLock("Foo::mLock"); - } - - ~Foo(void) { - nsAutoLock::DestroyLock(mLock); - } - - void ThreadSafeMethod(void) { - // we're don't hold the lock yet... - - nsAutoLock lock(mLock); - // ...but now we do. - - // we even can do wacky stuff like return from arbitrary places w/o - // worrying about forgetting to release the lock - if (some_weird_condition) - return; - - // otherwise do some other stuff - } - - void ThreadSafeBlockScope(void) { - // we're not in the lock here... - - { - nsAutoLock lock(mLock); - // but we are now, at least until the block scope closes - } - - // ...now we're not in the lock anymore - } - }; - - A similar stack-based locking object is available for PRMonitor. The - major difference is that the PRMonitor must be created and destroyed - via the static methods on nsAutoMonitor. - - For example: - Foo::Foo() { - mMon = nsAutoMonitor::NewMonitor("FooMonitor"); - } - nsresult Foo::MyMethod(...) { - nsAutoMonitor mon(mMon); - ... - // go ahead and do deeply nested returns... - return NS_ERROR_FAILURE; - ... - // or call Wait or Notify... - mon.Wait(); - ... - // cleanup is automatic - } - */ - -#ifndef nsAutoLock_h__ -#define nsAutoLock_h__ - -#include "nscore.h" -#include "prlock.h" -#include "prlog.h" -#include "mozilla/AutoRestore.h" - -/** - * nsAutoLockBase - * This is the base class for the stack-based locking objects. - * Clients of derived classes need not play with this superclass. - **/ -class NS_COM_GLUE NS_STACK_CLASS nsAutoLockBase { - friend class nsAutoUnlockBase; - -protected: - nsAutoLockBase() {} - enum nsAutoLockType {eAutoLock, eAutoMonitor, eAutoCMonitor}; - -#ifdef DEBUG - nsAutoLockBase(void* addr, nsAutoLockType type); - ~nsAutoLockBase(); - - static void InitAutoLockStatics(); - static void OnSemaphoreRecycle(void* addr); - static void OnSemaphoreCreated(const void* key, const char* name); - - void Show(); - void Hide(); - - void* mAddr; - nsAutoLockBase* mDown; - nsAutoLockType mType; -#else - nsAutoLockBase(void* addr, nsAutoLockType type) {} - ~nsAutoLockBase() {} - - void Show() {} - void Hide() {} -#endif -}; - -/** - * nsAutoUnlockBase - * This is the base class for stack-based unlocking objects. - * It unlocks locking objects based on nsAutoLockBase. - **/ -class NS_COM_GLUE NS_STACK_CLASS nsAutoUnlockBase { -protected: - nsAutoUnlockBase() {} - -#ifdef DEBUG - nsAutoUnlockBase(void* addr); - ~nsAutoUnlockBase(); - - nsAutoLockBase* mLock; -#else - nsAutoUnlockBase(void* addr) {} - ~nsAutoUnlockBase() {} -#endif -}; - -/** - * nsAutoLock - * Stack-based locking object for PRLock. - **/ -class NS_COM_GLUE NS_STACK_CLASS nsAutoLock : public nsAutoLockBase { -private: - PRLock* mLock; - PRBool mLocked; - MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER - - // Not meant to be implemented. This makes it a compiler error to - // construct or assign an nsAutoLock object incorrectly. - nsAutoLock(void) {} - nsAutoLock(nsAutoLock& /*aLock*/) {} - nsAutoLock& operator =(nsAutoLock& /*aLock*/) { - return *this; - } - - // Not meant to be implemented. This makes it a compiler error to - // attempt to create an nsAutoLock object on the heap. - static void* operator new(size_t /*size*/) CPP_THROW_NEW { - return nsnull; - } - static void operator delete(void* /*memory*/) {} - -public: - - /** - * NewLock - * Allocates a new PRLock for use with nsAutoLock. name is - * not checked for uniqueness. - * @param name A name which can reference this lock - * @param lock A valid PRLock* that was created by nsAutoLock::NewLock() - * @returns nsnull if failure - * A valid PRLock* if successful, which must be destroyed - * by nsAutoLock::DestroyLock() - **/ - static PRLock* NewLock(const char* name) - { - PRLock* lock = PR_NewLock(); - #ifdef DEBUG - OnSemaphoreCreated(lock, name); - #endif - return lock; - } - - static void DestroyLock(PRLock* lock) - { - #ifdef DEBUG - OnSemaphoreRecycle(lock); - #endif - PR_DestroyLock(lock); - } - - - /** - * Constructor - * The constructor aquires the given lock. The destructor - * releases the lock. - * - * @param aLock A valid PRLock* returned from the NSPR's - * PR_NewLock() function. - **/ - nsAutoLock(PRLock* aLock MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM) - : nsAutoLockBase(aLock, eAutoLock), - mLock(aLock), - mLocked(PR_TRUE) { - MOZILLA_GUARD_OBJECT_NOTIFIER_INIT; - PR_ASSERT(mLock); - - // This will assert deep in the bowels of NSPR if you attempt - // to re-enter the lock. - PR_Lock(mLock); - } - - ~nsAutoLock(void) { - if (mLocked) - PR_Unlock(mLock); - } - - /** - * lock - * Client may call this to reaquire the given lock. Take special - * note that attempting to aquire a locked lock will hang or crash. - **/ - void lock() { - Show(); - PR_ASSERT(!mLocked); - PR_Lock(mLock); - mLocked = PR_TRUE; - } - - - /** - * unlock - * Client may call this to release the given lock. Take special - * note unlocking an unlocked lock has undefined results. - **/ - void unlock() { - PR_ASSERT(mLocked); - PR_Unlock(mLock); - mLocked = PR_FALSE; - Hide(); - } -}; - -class NS_STACK_CLASS nsAutoUnlock : private nsAutoUnlockBase -{ -private: - PRLock *mLock; - MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER - -public: - nsAutoUnlock(PRLock *lock MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM) : - nsAutoUnlockBase(lock), - mLock(lock) - { - MOZILLA_GUARD_OBJECT_NOTIFIER_INIT; - PR_Unlock(mLock); - } - - ~nsAutoUnlock() { - PR_Lock(mLock); - } -}; - -#include "prcmon.h" -#include "nsError.h" -#include "nsDebug.h" - -class NS_COM_GLUE NS_STACK_CLASS nsAutoMonitor : public nsAutoLockBase { -public: - - /** - * NewMonitor - * Allocates a new PRMonitor for use with nsAutoMonitor. - * @param name A (unique /be?) name which can reference this monitor - * @returns nsnull if failure - * A valid PRMonitor* is successful while must be destroyed - * by nsAutoMonitor::DestroyMonitor() - **/ - static PRMonitor* NewMonitor(const char* name) - { - PRMonitor* mon = PR_NewMonitor(); - #ifdef DEBUG - OnSemaphoreCreated(mon, name); - #endif - return mon; - } - - static void DestroyMonitor(PRMonitor* mon) - { - #ifdef DEBUG - OnSemaphoreRecycle(mon); - #endif - PR_DestroyMonitor(mon); - } - - - /** - * Constructor - * The constructor locks the given monitor. During destruction - * the monitor will be unlocked. - * - * @param mon A valid PRMonitor* returned from - * nsAutoMonitor::NewMonitor(). - **/ - nsAutoMonitor(PRMonitor* mon MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM) - : nsAutoLockBase((void*)mon, eAutoMonitor), - mMonitor(mon), mLockCount(0) - { - MOZILLA_GUARD_OBJECT_NOTIFIER_INIT; - NS_ASSERTION(mMonitor, "null monitor"); - if (mMonitor) { - PR_EnterMonitor(mMonitor); - mLockCount = 1; - } - } - - ~nsAutoMonitor() { - NS_ASSERTION(mMonitor, "null monitor"); - if (mMonitor && mLockCount) { -#ifdef DEBUG - PRStatus status = -#endif - PR_ExitMonitor(mMonitor); - NS_ASSERTION(status == PR_SUCCESS, "PR_ExitMonitor failed"); - } - } - - /** - * Enter - * Client may call this to reenter the given monitor. - * @see prmon.h - **/ - void Enter(); - - /** - * Exit - * Client may call this to exit the given monitor. - * @see prmon.h - **/ - void Exit(); - - /** - * Wait - * @see prmon.h - **/ - nsresult Wait(PRIntervalTime interval = PR_INTERVAL_NO_TIMEOUT) { - return PR_Wait(mMonitor, interval) == PR_SUCCESS - ? NS_OK : NS_ERROR_FAILURE; - } - - /** - * Notify - * @see prmon.h - **/ - nsresult Notify() { - return PR_Notify(mMonitor) == PR_SUCCESS - ? NS_OK : NS_ERROR_FAILURE; - } - - /** - * NotifyAll - * @see prmon.h - **/ - nsresult NotifyAll() { - return PR_NotifyAll(mMonitor) == PR_SUCCESS - ? NS_OK : NS_ERROR_FAILURE; - } - -private: - PRMonitor* mMonitor; - PRInt32 mLockCount; - MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER - - // Not meant to be implemented. This makes it a compiler error to - // construct or assign an nsAutoLock object incorrectly. - nsAutoMonitor(void) {} - nsAutoMonitor(nsAutoMonitor& /*aMon*/) {} - nsAutoMonitor& operator =(nsAutoMonitor& /*aMon*/) { - return *this; - } - - // Not meant to be implemented. This makes it a compiler error to - // attempt to create an nsAutoLock object on the heap. - static void* operator new(size_t /*size*/) CPP_THROW_NEW { - return nsnull; - } - static void operator delete(void* /*memory*/) {} -}; - -//////////////////////////////////////////////////////////////////////////////// -// Once again, this time with a cache... -// (Using this avoids the need to allocate a PRMonitor, which may be useful when -// a large number of objects of the same class need associated monitors.) - -#include "prcmon.h" -#include "nsError.h" - -class NS_COM_GLUE NS_STACK_CLASS nsAutoCMonitor : public nsAutoLockBase { -public: - nsAutoCMonitor(void* lockObject MOZILLA_GUARD_OBJECT_NOTIFIER_PARAM) - : nsAutoLockBase(lockObject, eAutoCMonitor), - mLockObject(lockObject), mLockCount(0) - { - MOZILLA_GUARD_OBJECT_NOTIFIER_INIT; - NS_ASSERTION(lockObject, "null lock object"); - PR_CEnterMonitor(mLockObject); - mLockCount = 1; - } - - ~nsAutoCMonitor() { - if (mLockCount) { -#ifdef DEBUG - PRStatus status = -#endif - PR_CExitMonitor(mLockObject); - NS_ASSERTION(status == PR_SUCCESS, "PR_CExitMonitor failed"); - } - } - - void Enter(); - void Exit(); - - nsresult Wait(PRIntervalTime interval = PR_INTERVAL_NO_TIMEOUT) { - return PR_CWait(mLockObject, interval) == PR_SUCCESS - ? NS_OK : NS_ERROR_FAILURE; - } - - nsresult Notify() { - return PR_CNotify(mLockObject) == PR_SUCCESS - ? NS_OK : NS_ERROR_FAILURE; - } - - nsresult NotifyAll() { - return PR_CNotifyAll(mLockObject) == PR_SUCCESS - ? NS_OK : NS_ERROR_FAILURE; - } - -private: - void* mLockObject; - PRInt32 mLockCount; - MOZILLA_DECL_USE_GUARD_OBJECT_NOTIFIER - - // Not meant to be implemented. This makes it a compiler error to - // construct or assign an nsAutoLock object incorrectly. - nsAutoCMonitor(void) {} - nsAutoCMonitor(nsAutoCMonitor& /*aMon*/) {} - nsAutoCMonitor& operator =(nsAutoCMonitor& /*aMon*/) { - return *this; - } - - // Not meant to be implemented. This makes it a compiler error to - // attempt to create an nsAutoLock object on the heap. - static void* operator new(size_t /*size*/) CPP_THROW_NEW { - return nsnull; - } - static void operator delete(void* /*memory*/) {} -}; - -#endif // nsAutoLock_h__ - diff --git a/xpcom/glue/objs.mk b/xpcom/glue/objs.mk index 9fe7fb85462..6796fb2dd91 100644 --- a/xpcom/glue/objs.mk +++ b/xpcom/glue/objs.mk @@ -71,14 +71,11 @@ XPCOM_GLUE_SRC_LCPPSRCS = \ XPCOM_GLUE_SRC_CPPSRCS = $(addprefix $(topsrcdir)/xpcom/glue/, $(XPCOM_GLUE_SRC_LCPPSRCS)) -# TODO nsAutoLock.cpp should die soon - XPCOM_GLUENS_SRC_LCPPSRCS = \ BlockingResourceBase.cpp \ DeadlockDetector.cpp \ SSE.cpp \ unused.cpp \ - nsAutoLock.cpp \ nsProxyRelease.cpp \ nsTextFormatter.cpp \ GenericFactory.cpp \ diff --git a/xpcom/io/nsFastLoadService.cpp b/xpcom/io/nsFastLoadService.cpp index 9bbc11a3440..276a97e2754 100644 --- a/xpcom/io/nsFastLoadService.cpp +++ b/xpcom/io/nsFastLoadService.cpp @@ -42,7 +42,6 @@ #include "pldhash.h" #include "nsAppDirectoryServiceDefs.h" -#include "nsAutoLock.h" #include "nsCOMPtr.h" #include "nsFastLoadFile.h" #include "nsFastLoadService.h" @@ -57,10 +56,12 @@ #include "nsISeekableStream.h" #include "nsISupports.h" +using namespace mozilla; + NS_IMPL_THREADSAFE_ISUPPORTS1(nsFastLoadService, nsIFastLoadService) nsFastLoadService::nsFastLoadService() - : mLock(nsnull), + : mLock("nsFastLoadService.mLock"), mFastLoadPtrMap(nsnull), mDirection(0) { @@ -75,8 +76,6 @@ nsFastLoadService::~nsFastLoadService() if (mFastLoadPtrMap) PL_DHashTableDestroy(mFastLoadPtrMap); - if (mLock) - nsAutoLock::DestroyLock(mLock); } nsresult @@ -90,12 +89,6 @@ nsFastLoadService::Create(nsISupports *aOuter, REFNSIID aIID, void **aResult) if (!fastLoadService) return NS_ERROR_OUT_OF_MEMORY; - fastLoadService->mLock = nsAutoLock::NewLock("nsFastLoadService::mLock"); - if (!fastLoadService->mLock) { - delete fastLoadService; - return NS_ERROR_OUT_OF_MEMORY; - } - NS_ADDREF(fastLoadService); nsresult rv = fastLoadService->QueryInterface(aIID, aResult); NS_RELEASE(fastLoadService); @@ -165,7 +158,7 @@ nsFastLoadService::NewFastLoadFile(const char* aBaseName, nsIFile* *aResult) NS_IMETHODIMP nsFastLoadService::NewInputStream(nsIFile *aFile, nsIObjectInputStream* *aResult) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsCOMPtr stream; nsresult rv = NS_NewFastLoadFileReader(getter_AddRefs(stream), aFile); @@ -182,7 +175,7 @@ NS_IMETHODIMP nsFastLoadService::NewOutputStream(nsIOutputStream* aDestStream, nsIObjectOutputStream* *aResult) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return NS_NewFastLoadFileWriter(aResult, aDestStream, mFileIO); } @@ -197,7 +190,7 @@ nsFastLoadService::GetInputStream(nsIObjectInputStream* *aResult) NS_IMETHODIMP nsFastLoadService::SetInputStream(nsIObjectInputStream* aStream) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mInputStream = aStream; return NS_OK; } @@ -212,7 +205,7 @@ nsFastLoadService::GetOutputStream(nsIObjectOutputStream* *aResult) NS_IMETHODIMP nsFastLoadService::SetOutputStream(nsIObjectOutputStream* aStream) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mOutputStream = aStream; return NS_OK; } @@ -227,7 +220,7 @@ nsFastLoadService::GetFileIO(nsIFastLoadFileIO* *aResult) NS_IMETHODIMP nsFastLoadService::SetFileIO(nsIFastLoadFileIO* aFileIO) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mFileIO = aFileIO; return NS_OK; } @@ -246,7 +239,7 @@ nsFastLoadService::HasMuxedDocument(const char* aURISpec, PRBool *aResult) nsCOMPtr control; *aResult = PR_FALSE; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mInputStream) { control = do_QueryInterface(mInputStream); @@ -269,7 +262,7 @@ nsFastLoadService::StartMuxedDocument(nsISupports* aURI, const char* aURISpec, { nsresult rv = NS_ERROR_NOT_AVAILABLE; nsCOMPtr control; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Try for an input stream first, in case aURISpec's data is multiplexed // in the current FastLoad file. @@ -313,7 +306,7 @@ nsFastLoadService::SelectMuxedDocument(nsISupports* aURI, nsISupports** aResult) { nsresult rv = NS_ERROR_NOT_AVAILABLE; nsCOMPtr control; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Try to select the reader, if any; then only if the URI was not in the // file already, select the writer/updater. @@ -343,7 +336,7 @@ nsFastLoadService::EndMuxedDocument(nsISupports* aURI) { nsresult rv = NS_ERROR_NOT_AVAILABLE; nsCOMPtr control; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Try to end the document identified by aURI in the reader, if any; then // only if the URI was not in the file already, end the writer/updater. @@ -366,7 +359,7 @@ nsFastLoadService::EndMuxedDocument(nsISupports* aURI) NS_IMETHODIMP nsFastLoadService::AddDependency(nsIFile* aFile) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); nsCOMPtr control(do_QueryInterface(mOutputStream)); if (!control) @@ -434,7 +427,7 @@ nsFastLoadService::GetFastLoadReferent(nsISupports* *aPtrAddr) NS_ASSERTION(*aPtrAddr == nsnull, "aPtrAddr doesn't point to null nsFastLoadPtr::mRawAddr?"); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mFastLoadPtrMap || !mInputStream) return NS_OK; @@ -477,7 +470,7 @@ nsFastLoadService::ReadFastLoadPtr(nsIObjectInputStream* aInputStream, nsresult rv; PRUint32 nextOffset; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); rv = aInputStream->Read32(&nextOffset); if (NS_FAILED(rv)) @@ -525,7 +518,7 @@ nsFastLoadService::WriteFastLoadPtr(nsIObjectOutputStream* aOutputStream, return NS_ERROR_UNEXPECTED; nsresult rv; - nsAutoLock lock(mLock); // serialize writes to aOutputStream + MutexAutoLock lock(mLock); // serialize writes to aOutputStream nsCOMPtr seekable(do_QueryInterface(aOutputStream)); if (!seekable) diff --git a/xpcom/io/nsFastLoadService.h b/xpcom/io/nsFastLoadService.h index c2ea9c229ac..4300e6fdd7c 100644 --- a/xpcom/io/nsFastLoadService.h +++ b/xpcom/io/nsFastLoadService.h @@ -37,6 +37,7 @@ * ***** END LICENSE BLOCK ***** */ #include "prtypes.h" #include "pldhash.h" +#include "mozilla/Mutex.h" #include "nsCOMPtr.h" #include "nsHashtable.h" #include "nsIFastLoadService.h" @@ -61,7 +62,7 @@ class nsFastLoadService : public nsIFastLoadService Create(nsISupports *aOuter, REFNSIID aIID, void **aResult); private: - PRLock* mLock; + mozilla::Mutex mLock; PLDHashTable* mFastLoadPtrMap; nsCOMPtr mInputStream; nsCOMPtr mOutputStream; diff --git a/xpcom/io/nsInputStreamTee.cpp b/xpcom/io/nsInputStreamTee.cpp index dc522a174c2..2c6830fdd21 100644 --- a/xpcom/io/nsInputStreamTee.cpp +++ b/xpcom/io/nsInputStreamTee.cpp @@ -39,6 +39,7 @@ #include #include "prlog.h" +#include "mozilla/Mutex.h" #include "nsIInputStreamTee.h" #include "nsIInputStream.h" #include "nsIOutputStream.h" @@ -46,8 +47,8 @@ #include "nsAutoPtr.h" #include "nsIEventTarget.h" #include "nsThreadUtils.h" -#include -#include "nsAutoLock.h" + +using namespace mozilla; #ifdef PR_LOGGING static PRLogModuleInfo* gInputStreamTeeLog = PR_NewLogModule("nsInputStreamTee"); @@ -68,7 +69,7 @@ public: void InvalidateSink(); private: - ~nsInputStreamTee() { if (mLock) nsAutoLock::DestroyLock(mLock); } + ~nsInputStreamTee() {} nsresult TeeSegment(const char *buf, PRUint32 count); @@ -81,7 +82,7 @@ private: nsCOMPtr mEventTarget; nsWriteSegmentFun mWriter; // for implementing ReadSegments void *mClosure; // for implementing ReadSegments - PRLock *mLock; // synchronize access to mSinkIsValid + nsAutoPtr mLock; // synchronize access to mSinkIsValid bool mSinkIsValid; // False if TeeWriteEvent fails }; @@ -163,14 +164,14 @@ nsInputStreamTee::nsInputStreamTee(): mLock(nsnull) bool nsInputStreamTee::SinkIsValid() { - nsAutoLock lock(mLock); + MutexAutoLock lock(*mLock); return mSinkIsValid; } void nsInputStreamTee::InvalidateSink() { - nsAutoLock lock(mLock); + MutexAutoLock lock(*mLock); mSinkIsValid = false; } @@ -324,11 +325,7 @@ nsInputStreamTee::SetEventTarget(nsIEventTarget *anEventTarget) mEventTarget = anEventTarget; if (mEventTarget) { // Only need synchronization if this is an async tee - mLock = nsAutoLock::NewLock("nsInputStreamTee::mLock"); - if (!mLock) { - NS_ERROR("Failed to allocate lock for nsInputStreamTee"); - return NS_ERROR_OUT_OF_MEMORY; - } + mLock = new Mutex("nsInputStreamTee.mLock"); } return NS_OK; } diff --git a/xpcom/io/nsLocalFileWin.cpp b/xpcom/io/nsLocalFileWin.cpp index adb6a3e0741..3a9d2fdf18d 100644 --- a/xpcom/io/nsLocalFileWin.cpp +++ b/xpcom/io/nsLocalFileWin.cpp @@ -79,11 +79,13 @@ #include "prproces.h" #include "nsITimelineService.h" -#include "nsAutoLock.h" +#include "mozilla/Mutex.h" #include "SpecialSystemDirectory.h" #include "nsTraceRefcntImpl.h" +using namespace mozilla; + #define CHECK_mWorkingPath() \ PR_BEGIN_MACRO \ if (mWorkingPath.IsEmpty()) \ @@ -159,24 +161,20 @@ public: nsresult Resolve(const WCHAR* in, WCHAR* out); private: - PRLock* mLock; + Mutex mLock; IPersistFile* mPersistFile; // Win 95 and 98 don't have IShellLinkW IShellLinkW* mShellLink; }; -ShortcutResolver::ShortcutResolver() +ShortcutResolver::ShortcutResolver() : mLock("ShortcutResolver.mLock") { - mLock = nsnull; mPersistFile = nsnull; mShellLink = nsnull; } ShortcutResolver::~ShortcutResolver() { - if (mLock) - nsAutoLock::DestroyLock(mLock); - // Release the pointer to the IPersistFile interface. if (mPersistFile) mPersistFile->Release(); @@ -193,10 +191,6 @@ ShortcutResolver::Init() { CoInitialize(NULL); // FIX: we should probably move somewhere higher up during startup - mLock = nsAutoLock::NewLock("ShortcutResolver::mLock"); - if (!mLock) - return NS_ERROR_FAILURE; - HRESULT hres; hres = CoCreateInstance(CLSID_ShellLink, NULL, @@ -220,7 +214,7 @@ ShortcutResolver::Init() nsresult ShortcutResolver::Resolve(const WCHAR* in, WCHAR* out) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // see if we can Load the path. HRESULT hres = mPersistFile->Load(in, STGM_READ); diff --git a/xpcom/io/nsNativeCharsetUtils.cpp b/xpcom/io/nsNativeCharsetUtils.cpp index 49a902e0a6a..86e17985a2c 100644 --- a/xpcom/io/nsNativeCharsetUtils.cpp +++ b/xpcom/io/nsNativeCharsetUtils.cpp @@ -83,11 +83,13 @@ NS_ShutdownNativeCharsetUtils() #include // mbtowc, wctomb #include // setlocale +#include "mozilla/Mutex.h" #include "nscore.h" -#include "prlock.h" #include "nsAString.h" #include "nsReadableUtils.h" +using namespace mozilla; + // // choose a conversion library. we used to use mbrtowc/wcrtomb under Linux, // but that doesn't work for non-BMP characters whether we use '-fshort-wchar' @@ -307,14 +309,14 @@ private: static iconv_t gUnicodeToUTF8; static iconv_t gUTF8ToUnicode; #endif - static PRLock *gLock; + static Mutex *gLock; static PRBool gInitialized; static PRBool gIsNativeUTF8; static void LazyInit(); - static void Lock() { if (gLock) PR_Lock(gLock); } - static void Unlock() { if (gLock) PR_Unlock(gLock); } + static void Lock() { if (gLock) gLock->Lock(); } + static void Unlock() { if (gLock) gLock->Unlock(); } }; iconv_t nsNativeCharsetConverter::gNativeToUnicode = INVALID_ICONV_T; @@ -325,7 +327,7 @@ iconv_t nsNativeCharsetConverter::gUTF8ToNative = INVALID_ICONV_T; iconv_t nsNativeCharsetConverter::gUnicodeToUTF8 = INVALID_ICONV_T; iconv_t nsNativeCharsetConverter::gUTF8ToUnicode = INVALID_ICONV_T; #endif -PRLock *nsNativeCharsetConverter::gLock = nsnull; +Mutex *nsNativeCharsetConverter::gLock = nsnull; PRBool nsNativeCharsetConverter::gInitialized = PR_FALSE; PRBool nsNativeCharsetConverter::gIsNativeUTF8 = PR_FALSE; @@ -407,15 +409,14 @@ nsNativeCharsetConverter::LazyInit() void nsNativeCharsetConverter::GlobalInit() { - gLock = PR_NewLock(); - NS_ASSERTION(gLock, "lock creation failed"); + gLock = new Mutex("nsNativeCharsetConverter.gLock"); } void nsNativeCharsetConverter::GlobalShutdown() { if (gLock) { - PR_DestroyLock(gLock); + delete gLock; gLock = nsnull; } diff --git a/xpcom/io/nsPipe3.cpp b/xpcom/io/nsPipe3.cpp index b5765af2909..554d47c46b6 100644 --- a/xpcom/io/nsPipe3.cpp +++ b/xpcom/io/nsPipe3.cpp @@ -35,13 +35,13 @@ * * ***** END LICENSE BLOCK ***** */ +#include "mozilla/Monitor.h" #include "nsIPipe.h" #include "nsIEventTarget.h" #include "nsISeekableStream.h" #include "nsIProgrammingLanguage.h" #include "nsSegmentedBuffer.h" #include "nsStreamUtils.h" -#include "nsAutoLock.h" #include "nsCOMPtr.h" #include "nsCRT.h" #include "prlog.h" @@ -49,6 +49,8 @@ #include "nsIClassInfoImpl.h" #include "nsAtomicRefcnt.h" +using namespace mozilla; + #if defined(PR_LOGGING) // // set NSPR_LOG_MODULES=nsPipe:5 @@ -259,7 +261,7 @@ protected: nsPipeInputStream mInput; nsPipeOutputStream mOutput; - PRMonitor* mMonitor; + Monitor mMonitor; nsSegmentedBuffer mBuffer; char* mReadCursor; @@ -270,6 +272,7 @@ protected: char* mWriteLimit; nsresult mStatus; + PRPackedBool mInited; }; // @@ -318,20 +321,19 @@ protected: nsPipe::nsPipe() : mInput(this) , mOutput(this) - , mMonitor(nsnull) + , mMonitor("nsPipe.mMonitor") , mReadCursor(nsnull) , mReadLimit(nsnull) , mWriteSegment(-1) , mWriteCursor(nsnull) , mWriteLimit(nsnull) , mStatus(NS_OK) + , mInited(PR_FALSE) { } nsPipe::~nsPipe() { - if (mMonitor) - nsAutoMonitor::DestroyMonitor(mMonitor); } NS_IMPL_THREADSAFE_ISUPPORTS1(nsPipe, nsIPipe) @@ -343,9 +345,7 @@ nsPipe::Init(PRBool nonBlockingIn, PRUint32 segmentCount, nsIMemory *segmentAlloc) { - mMonitor = nsAutoMonitor::NewMonitor("pipeMonitor"); - if (!mMonitor) - return NS_ERROR_OUT_OF_MEMORY; + mInited = PR_TRUE; if (segmentSize == 0) segmentSize = DEFAULT_SEGMENT_SIZE; @@ -369,7 +369,6 @@ nsPipe::Init(PRBool nonBlockingIn, NS_IMETHODIMP nsPipe::GetInputStream(nsIAsyncInputStream **aInputStream) { - NS_ENSURE_TRUE(mMonitor, NS_ERROR_NOT_INITIALIZED); NS_ADDREF(*aInputStream = &mInput); return NS_OK; } @@ -377,7 +376,7 @@ nsPipe::GetInputStream(nsIAsyncInputStream **aInputStream) NS_IMETHODIMP nsPipe::GetOutputStream(nsIAsyncOutputStream **aOutputStream) { - NS_ENSURE_TRUE(mMonitor, NS_ERROR_NOT_INITIALIZED); + NS_ENSURE_TRUE(mInited, NS_ERROR_NOT_INITIALIZED); NS_ADDREF(*aOutputStream = &mOutput); return NS_OK; } @@ -407,7 +406,7 @@ nsPipe::PeekSegment(PRUint32 index, char *&cursor, char *&limit) nsresult nsPipe::GetReadSegment(const char *&segment, PRUint32 &segmentLen) { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); if (mReadCursor == mReadLimit) return NS_FAILED(mStatus) ? mStatus : NS_BASE_STREAM_WOULD_BLOCK; @@ -424,7 +423,7 @@ nsPipe::AdvanceReadCursor(PRUint32 bytesRead) nsPipeEvents events; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); LOG(("III advancing read cursor by %u\n", bytesRead)); NS_ASSERTION(bytesRead <= mBuffer.GetSegmentSize(), "read too much"); @@ -479,7 +478,7 @@ nsPipe::AdvanceReadCursor(PRUint32 bytesRead) nsresult nsPipe::GetWriteSegment(char *&segment, PRUint32 &segmentLen) { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); if (NS_FAILED(mStatus)) return mStatus; @@ -522,7 +521,7 @@ nsPipe::AdvanceWriteCursor(PRUint32 bytesWritten) nsPipeEvents events; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); LOG(("OOO advancing write cursor by %u\n", bytesWritten)); @@ -579,7 +578,7 @@ nsPipe::OnPipeException(nsresult reason, PRBool outputOnly) nsPipeEvents events; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); // if we've already hit an exception, then ignore this one. if (NS_FAILED(mStatus)) @@ -645,7 +644,7 @@ nsPipeInputStream::Wait() { NS_ASSERTION(mBlocking, "wait on non-blocking pipe input stream"); - nsAutoMonitor mon(mPipe->mMonitor); + MonitorAutoEnter mon(mPipe->mMonitor); while (NS_SUCCEEDED(mPipe->mStatus) && (mAvailable == 0)) { LOG(("III pipe input: waiting for data\n")); @@ -739,7 +738,7 @@ nsPipeInputStream::Close() NS_IMETHODIMP nsPipeInputStream::Available(PRUint32 *result) { - nsAutoMonitor mon(mPipe->mMonitor); + MonitorAutoEnter mon(mPipe->mMonitor); // return error if pipe closed if (!mAvailable && NS_FAILED(mPipe->mStatus)) @@ -845,7 +844,7 @@ nsPipeInputStream::AsyncWait(nsIInputStreamCallback *callback, nsPipeEvents pipeEvents; { - nsAutoMonitor mon(mPipe->mMonitor); + MonitorAutoEnter mon(mPipe->mMonitor); // replace a pending callback mCallback = 0; @@ -886,7 +885,7 @@ nsPipeInputStream::Seek(PRInt32 whence, PRInt64 offset) NS_IMETHODIMP nsPipeInputStream::Tell(PRInt64 *offset) { - nsAutoMonitor mon(mPipe->mMonitor); + MonitorAutoEnter mon(mPipe->mMonitor); // return error if pipe closed if (!mAvailable && NS_FAILED(mPipe->mStatus)) @@ -916,7 +915,7 @@ nsPipeInputStream::Search(const char *forString, { LOG(("III Search [for=%s ic=%u]\n", forString, ignoreCase)); - nsAutoMonitor mon(mPipe->mMonitor); + MonitorAutoEnter mon(mPipe->mMonitor); char *cursor1, *limit1; PRUint32 index = 0, offset = 0; @@ -1004,7 +1003,7 @@ nsPipeOutputStream::Wait() { NS_ASSERTION(mBlocking, "wait on non-blocking pipe output stream"); - nsAutoMonitor mon(mPipe->mMonitor); + MonitorAutoEnter mon(mPipe->mMonitor); if (NS_SUCCEEDED(mPipe->mStatus) && !mWritable) { LOG(("OOO pipe output: waiting for space\n")); @@ -1226,7 +1225,7 @@ nsPipeOutputStream::AsyncWait(nsIOutputStreamCallback *callback, nsPipeEvents pipeEvents; { - nsAutoMonitor mon(mPipe->mMonitor); + MonitorAutoEnter mon(mPipe->mMonitor); // replace a pending callback mCallback = 0; diff --git a/xpcom/io/nsStreamUtils.cpp b/xpcom/io/nsStreamUtils.cpp index 80e23d22c7d..b2a606752d5 100644 --- a/xpcom/io/nsStreamUtils.cpp +++ b/xpcom/io/nsStreamUtils.cpp @@ -36,15 +36,17 @@ * * ***** END LICENSE BLOCK ***** */ +#include "mozilla/Mutex.h" #include "nsStreamUtils.h" #include "nsCOMPtr.h" #include "nsIPipe.h" #include "nsIEventTarget.h" #include "nsIRunnable.h" #include "nsISafeOutputStream.h" -#include "nsAutoLock.h" #include "nsString.h" +using namespace mozilla; + //----------------------------------------------------------------------------- class nsInputStreamReadyEvent : public nsIRunnable @@ -245,7 +247,7 @@ public: NS_DECL_ISUPPORTS nsAStreamCopier() - : mLock(nsnull) + : mLock("nsAStreamCopier.mLock") , mCallback(nsnull) , mClosure(nsnull) , mChunkSize(0) @@ -261,8 +263,6 @@ public: // virtual since subclasses call superclass Release() virtual ~nsAStreamCopier() { - if (mLock) - nsAutoLock::DestroyLock(mLock); } // kick off the async copy... @@ -284,10 +284,6 @@ public: mCloseSource = closeSource; mCloseSink = closeSink; - mLock = nsAutoLock::NewLock("nsAStreamCopier::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - mAsyncSource = do_QueryInterface(mSource); mAsyncSink = do_QueryInterface(mSink); @@ -307,7 +303,7 @@ public: nsresult cancelStatus; PRBool canceled; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); canceled = mCanceled; cancelStatus = mCancelStatus; } @@ -324,7 +320,7 @@ public: copyFailed = NS_FAILED(sourceCondition) || NS_FAILED(sinkCondition) || n == 0; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); canceled = mCanceled; cancelStatus = mCancelStatus; } @@ -407,7 +403,7 @@ public: nsresult Cancel(nsresult aReason) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mCanceled) return NS_ERROR_FAILURE; @@ -439,7 +435,7 @@ public: Process(); // clear "in process" flag and post any pending continuation event - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mEventInProcess = PR_FALSE; if (mEventIsPending) { mEventIsPending = PR_FALSE; @@ -458,7 +454,7 @@ public: // just let that existing event take care of posting the real // continuation event. - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); return PostContinuationEvent_Locked(); } @@ -483,7 +479,7 @@ protected: nsCOMPtr mAsyncSource; nsCOMPtr mAsyncSink; nsCOMPtr mTarget; - PRLock *mLock; + Mutex mLock; nsAsyncCopyCallbackFun mCallback; void *mClosure; PRUint32 mChunkSize; diff --git a/xpcom/proxy/src/nsProxyEvent.cpp b/xpcom/proxy/src/nsProxyEvent.cpp index 62f04c6b4cb..d3963eb3f66 100644 --- a/xpcom/proxy/src/nsProxyEvent.cpp +++ b/xpcom/proxy/src/nsProxyEvent.cpp @@ -59,7 +59,6 @@ #include "prmem.h" #include "xptcall.h" -#include "nsAutoLock.h" #include "nsXPCOMCID.h" #include "nsServiceManagerUtils.h" #include "nsIComponentManager.h" @@ -67,6 +66,8 @@ #include "nsEventQueue.h" #include "nsMemory.h" +using namespace mozilla; + /** * Map the nsAUTF8String, nsUTF8String classes to the nsACString and * nsCString classes respectively for now. These defines need to be removed @@ -363,14 +364,14 @@ nsProxyObject::~nsProxyObject() NS_IMETHODIMP_(nsrefcnt) nsProxyObject::AddRef() { - nsAutoLock lock(nsProxyObjectManager::GetInstance()->GetLock()); + MutexAutoLock lock(nsProxyObjectManager::GetInstance()->GetLock()); return LockedAddRef(); } NS_IMETHODIMP_(nsrefcnt) nsProxyObject::Release() { - nsAutoLock lock(nsProxyObjectManager::GetInstance()->GetLock()); + MutexAutoLock lock(nsProxyObjectManager::GetInstance()->GetLock()); return LockedRelease(); } @@ -394,7 +395,7 @@ nsProxyObject::LockedRelease() nsProxyObjectManager *pom = nsProxyObjectManager::GetInstance(); pom->LockedRemove(this); - nsAutoUnlock unlock(pom->GetLock()); + MutexAutoUnlock unlock(pom->GetLock()); delete this; return 0; @@ -418,7 +419,7 @@ nsProxyObject::QueryInterface(REFNSIID aIID, void **aResult) nsProxyObjectManager *pom = nsProxyObjectManager::GetInstance(); NS_ASSERTION(pom, "Deleting a proxy without a global proxy-object-manager."); - nsAutoLock lock(pom->GetLock()); + MutexAutoLock lock(pom->GetLock()); return LockedFind(aIID, aResult); } @@ -443,7 +444,7 @@ nsProxyObject::LockedFind(REFNSIID aIID, void **aResult) // Both GetClass and QueryInterface call out to XPCOM, so we unlock for them { nsProxyObjectManager* pom = nsProxyObjectManager::GetInstance(); - nsAutoUnlock unlock(pom->GetLock()); + MutexAutoUnlock unlock(pom->GetLock()); nsProxyEventClass *pec; nsresult rv = pom->GetClass(aIID, &pec); diff --git a/xpcom/proxy/src/nsProxyEventClass.cpp b/xpcom/proxy/src/nsProxyEventClass.cpp index adea1594a99..43e84796e14 100644 --- a/xpcom/proxy/src/nsProxyEventClass.cpp +++ b/xpcom/proxy/src/nsProxyEventClass.cpp @@ -46,7 +46,6 @@ #include "nsMemory.h" #include "nsHashtable.h" -#include "nsAutoLock.h" #include "xptcall.h" // LIFETIME_CACHE will cache class for the entire cyle of the application. diff --git a/xpcom/proxy/src/nsProxyEventObject.cpp b/xpcom/proxy/src/nsProxyEventObject.cpp index 08b38bba82b..e60156c9578 100644 --- a/xpcom/proxy/src/nsProxyEventObject.cpp +++ b/xpcom/proxy/src/nsProxyEventObject.cpp @@ -51,7 +51,7 @@ #include "nsIInterfaceInfoManager.h" #include "xptcall.h" -#include "nsAutoLock.h" +using namespace mozilla; nsProxyEventObject::nsProxyEventObject(nsProxyObject *aParent, nsProxyEventClass* aClass, @@ -83,7 +83,7 @@ nsProxyEventObject::~nsProxyEventObject() NS_IMETHODIMP_(nsrefcnt) nsProxyEventObject::AddRef() { - nsAutoLock lock(nsProxyObjectManager::GetInstance()->GetLock()); + MutexAutoLock lock(nsProxyObjectManager::GetInstance()->GetLock()); return LockedAddRef(); } @@ -99,7 +99,7 @@ NS_IMETHODIMP_(nsrefcnt) nsProxyEventObject::Release(void) { { - nsAutoLock lock(nsProxyObjectManager::GetInstance()->GetLock()); + MutexAutoLock lock(nsProxyObjectManager::GetInstance()->GetLock()); NS_PRECONDITION(0 != mRefCnt, "dup release"); --mRefCnt; diff --git a/xpcom/proxy/src/nsProxyEventPrivate.h b/xpcom/proxy/src/nsProxyEventPrivate.h index 6e9ba137c68..60f9b37b48c 100644 --- a/xpcom/proxy/src/nsProxyEventPrivate.h +++ b/xpcom/proxy/src/nsProxyEventPrivate.h @@ -47,6 +47,7 @@ #include "nsXPTCUtils.h" +#include "mozilla/Mutex.h" #include "nsAutoPtr.h" #include "nsCOMPtr.h" #include "nsThreadUtils.h" @@ -54,7 +55,6 @@ #include "nsClassHashtable.h" #include "nsHashtable.h" -#include "prmon.h" #include "prlog.h" class nsProxyEventObject; @@ -273,6 +273,8 @@ NS_DEFINE_STATIC_IID_ACCESSOR(nsProxyObjectCallInfo, NS_PROXYEVENT_IID) class nsProxyObjectManager: public nsIProxyObjectManager { + typedef mozilla::Mutex Mutex; + public: NS_DECL_ISUPPORTS NS_DECL_NSIPROXYOBJECTMANAGER @@ -290,7 +292,7 @@ public: void LockedRemove(nsProxyObject* aProxy); - PRLock* GetLock() const { return mProxyCreationLock; } + Mutex& GetLock() { return mProxyCreationLock; } #ifdef PR_LOGGING static PRLogModuleInfo *sLog; @@ -302,7 +304,7 @@ private: static nsProxyObjectManager* gInstance; nsHashtable mProxyObjectMap; nsClassHashtable mProxyClassMap; - PRLock *mProxyCreationLock; + Mutex mProxyCreationLock; }; #define NS_XPCOMPROXY_CLASSNAME "nsProxyObjectManager" diff --git a/xpcom/proxy/src/nsProxyObjectManager.cpp b/xpcom/proxy/src/nsProxyObjectManager.cpp index c6e1620844f..8dc947177a3 100644 --- a/xpcom/proxy/src/nsProxyObjectManager.cpp +++ b/xpcom/proxy/src/nsProxyObjectManager.cpp @@ -53,11 +53,11 @@ #include "nsIServiceManager.h" #include "nsIThread.h" -#include "nsAutoLock.h" #include "nsCOMPtr.h" #include "nsThreadUtils.h" #include "xptiprivate.h" +using namespace mozilla; #ifdef PR_LOGGING PRLogModuleInfo *nsProxyObjectManager::sLog = PR_NewLogModule("xpcomproxy"); @@ -114,9 +114,8 @@ nsProxyObjectManager::Release() nsProxyObjectManager::nsProxyObjectManager() : mProxyObjectMap(256, PR_FALSE) + , mProxyCreationLock("nsProxyObjectManager.mProxyCreationLock") { - mProxyCreationLock = - nsAutoLock::NewLock("nsProxyObjectManager::mProxyCreationLock"); mProxyClassMap.Init(256); } @@ -124,9 +123,6 @@ nsProxyObjectManager::~nsProxyObjectManager() { mProxyClassMap.Clear(); - if (mProxyCreationLock) - nsAutoLock::DestroyLock(mProxyCreationLock); - nsProxyObjectManager::gInstance = nsnull; } @@ -238,7 +234,7 @@ nsProxyObjectManager::GetProxyForObject(nsIEventTarget* aTarget, nsProxyEventKey rootKey(realObj, realEQ, proxyType); { - nsAutoLock lock(mProxyCreationLock); + MutexAutoLock lock(mProxyCreationLock); nsProxyLockedRefPtr root = (nsProxyObject*) mProxyObjectMap.Get(&rootKey); if (root) @@ -252,7 +248,7 @@ nsProxyObjectManager::GetProxyForObject(nsIEventTarget* aTarget, // lock again, and check for a race putting into mProxyObjectMap { - nsAutoLock lock(mProxyCreationLock); + MutexAutoLock lock(mProxyCreationLock); nsProxyLockedRefPtr root = (nsProxyObject*) mProxyObjectMap.Get(&rootKey); if (root) { @@ -283,7 +279,7 @@ nsresult nsProxyObjectManager::GetClass(REFNSIID aIID, nsProxyEventClass **aResult) { { - nsAutoLock lock(mProxyCreationLock); + MutexAutoLock lock(mProxyCreationLock); if (mProxyClassMap.Get(aIID, aResult)) { NS_ASSERTION(*aResult, "Null data in mProxyClassMap"); return NS_OK; @@ -306,7 +302,7 @@ nsProxyObjectManager::GetClass(REFNSIID aIID, nsProxyEventClass **aResult) // Re-lock to put this class into our map. Before putting, check to see // if another thread raced to put before us - nsAutoLock lock(mProxyCreationLock); + MutexAutoLock lock(mProxyCreationLock); if (mProxyClassMap.Get(aIID, aResult)) { NS_ASSERTION(*aResult, "Null data in mProxyClassMap"); diff --git a/xpcom/proxy/tests/proxy-create-threadsafety.cpp b/xpcom/proxy/tests/proxy-create-threadsafety.cpp index 3dee1fea5e4..4eec9f45822 100644 --- a/xpcom/proxy/tests/proxy-create-threadsafety.cpp +++ b/xpcom/proxy/tests/proxy-create-threadsafety.cpp @@ -43,16 +43,16 @@ #include "nsIComponentRegistrar.h" #include "nsIServiceManager.h" #include "nsAutoPtr.h" -#include "nsAutoLock.h" #include "nsCOMPtr.h" #include "nscore.h" #include "nspr.h" -#include "prmon.h" #include "nsITestProxy.h" #include "nsISupportsPrimitives.h" +#include "mozilla/Monitor.h" +#include "mozilla/Mutex.h" #include "nsIRunnable.h" #include "nsIProxyObjectManager.h" #include "nsXPCOMCIDInternal.h" @@ -61,6 +61,8 @@ #include "nsThreadUtils.h" #include "nsISupportsUtils.h" +using namespace mozilla; + /* A quick diagram of how this test works: @@ -97,7 +99,9 @@ class ProxyTest : public nsIRunnable, { public: ProxyTest() - : mCounter(0) + : mCounterLock("ProxyTest.mCounterLock") + , mEvilMonitor("ProxyTest.mEvilMonitor") + , mCounter(0) {} NS_IMETHOD Run() @@ -125,11 +129,6 @@ public: if (!NS_IsMainThread()) return NS_ERROR_UNEXPECTED; - mCounterLock = nsAutoLock::NewLock(__FILE__ " counter lock"); - NS_ENSURE_TRUE(mCounterLock, NS_ERROR_OUT_OF_MEMORY); - mEvilMonitor = nsAutoMonitor::NewMonitor(__FILE__ " evil monitor"); - NS_ENSURE_TRUE(mEvilMonitor, NS_ERROR_OUT_OF_MEMORY); - /* note that we don't have an event queue... */ rv = NS_NewThread(getter_AddRefs(mThreadOne), @@ -175,14 +174,14 @@ public: foundInterface = NS_ISUPPORTS_CAST(nsIRunnable*, this); } else if ( aIID.Equals(NS_GET_IID(nsISupportsPrimitive)) ) { { - nsAutoLock counterLock(mCounterLock); + MutexAutoLock counterLock(mCounterLock); switch(mCounter) { case 0: ++mCounter; { /* be evil here and hang */ - nsAutoUnlock counterUnlock(mCounterLock); - nsAutoMonitor evilMonitor(mEvilMonitor); + MutexAutoUnlock counterUnlock(mCounterLock); + MonitorAutoEnter evilMonitor(mEvilMonitor); nsresult rv = evilMonitor.Wait(); NS_ENSURE_SUCCESS(rv, rv); break; @@ -191,8 +190,8 @@ public: ++mCounter; { /* okay, we had our fun, un-hang */ - nsAutoUnlock counterUnlock(mCounterLock); - nsAutoMonitor evilMonitor(mEvilMonitor); + MutexAutoUnlock counterUnlock(mCounterLock); + MonitorAutoEnter evilMonitor(mEvilMonitor); nsresult rv = evilMonitor.Notify(); NS_ENSURE_SUCCESS(rv, rv); break; @@ -228,8 +227,8 @@ protected: NS_DECL_OWNINGTHREAD private: - PRLock* mCounterLock; - PRMonitor* mEvilMonitor; + Mutex mCounterLock; + Monitor mEvilMonitor; PRInt32 mCounter; nsCOMPtr mThreadOne; nsCOMPtr mThreadTwo; diff --git a/xpcom/reflect/xptinfo/src/xptiInterfaceInfo.cpp b/xpcom/reflect/xptinfo/src/xptiInterfaceInfo.cpp index 9fa49da1f1a..82665f7e759 100644 --- a/xpcom/reflect/xptinfo/src/xptiInterfaceInfo.cpp +++ b/xpcom/reflect/xptinfo/src/xptiInterfaceInfo.cpp @@ -42,6 +42,8 @@ #include "xptiprivate.h" #include "nsAtomicRefcnt.h" +using namespace mozilla; + /***************************************************************************/ // Debug Instrumentation... @@ -102,7 +104,7 @@ xptiInterfaceEntry::xptiInterfaceEntry(const char* name, PRBool xptiInterfaceEntry::Resolve() { - nsAutoLock lock(xptiInterfaceInfoManager::GetResolveLock()); + MutexAutoLock lock(xptiInterfaceInfoManager::GetResolveLock()); return ResolveLocked(); } @@ -617,7 +619,7 @@ xptiInterfaceEntry::HasAncestor(const nsIID * iid, PRBool *_retval) nsresult xptiInterfaceEntry::GetInterfaceInfo(xptiInterfaceInfo** info) { - nsAutoMonitor lock(xptiInterfaceInfoManager::GetInfoMonitor()); + MonitorAutoEnter lock(xptiInterfaceInfoManager::GetInfoMonitor()); LOG_INFO_MONITOR_ENTRY; if(!mInfo) @@ -677,7 +679,7 @@ xptiInterfaceInfo::Release(void) NS_LOG_RELEASE(this, cnt, "xptiInterfaceInfo"); if(!cnt) { - nsAutoMonitor lock(xptiInterfaceInfoManager::GetInfoMonitor()); + MonitorAutoEnter lock(xptiInterfaceInfoManager::GetInfoMonitor()); LOG_INFO_MONITOR_ENTRY; // If GetInterfaceInfo added and *released* a reference before we diff --git a/xpcom/reflect/xptinfo/src/xptiInterfaceInfoManager.cpp b/xpcom/reflect/xptinfo/src/xptiInterfaceInfoManager.cpp index 34a2e60e3d5..b99ef214dd1 100644 --- a/xpcom/reflect/xptinfo/src/xptiInterfaceInfoManager.cpp +++ b/xpcom/reflect/xptinfo/src/xptiInterfaceInfoManager.cpp @@ -47,6 +47,8 @@ #include "mozilla/FunctionTimer.h" #include "nsDirectoryService.h" +using namespace mozilla; + NS_IMPL_THREADSAFE_ISUPPORTS2(xptiInterfaceInfoManager, nsIInterfaceInfoManager, nsIInterfaceInfoSuperManager) @@ -77,13 +79,11 @@ xptiInterfaceInfoManager::FreeInterfaceInfoManager() xptiInterfaceInfoManager::xptiInterfaceInfoManager() : mWorkingSet(), - mResolveLock(nsAutoLock::NewLock( - "xptiInterfaceInfoManager::mResolveLock")), - mAutoRegLock(nsAutoLock::NewLock( - "xptiInterfaceInfoManager::mAutoRegLock")), // FIXME: unused! - mInfoMonitor(nsAutoMonitor::NewMonitor("xptiInfoMonitor")), - mAdditionalManagersLock(nsAutoLock::NewLock( - "xptiInterfaceInfoManager::mAdditionalManagersLock")) + mResolveLock("xptiInterfaceInfoManager.mResolveLock"), + mAutoRegLock("xptiInterfaceInfoManager.mAutoRegLock"), // FIXME: unused! + mInfoMonitor("xptiInterfaceInfoManager.mInfoMonitor"), + mAdditionalManagersLock( + "xptiInterfaceInfoManager.mAdditionalManagersLock") { } @@ -92,15 +92,6 @@ xptiInterfaceInfoManager::~xptiInterfaceInfoManager() // We only do this on shutdown of the service. mWorkingSet.InvalidateInterfaceInfos(); - if (mResolveLock) - nsAutoLock::DestroyLock(mResolveLock); - if (mAutoRegLock) - nsAutoLock::DestroyLock(mAutoRegLock); - if (mInfoMonitor) - nsAutoMonitor::DestroyMonitor(mInfoMonitor); - if (mAdditionalManagersLock) - nsAutoLock::DestroyLock(mAdditionalManagersLock); - gInterfaceInfoManager = nsnull; #ifdef DEBUG gCallCount = 0; @@ -452,7 +443,7 @@ NS_IMETHODIMP xptiInterfaceInfoManager::AddAdditionalManager(nsIInterfaceInfoMan static_cast(weakRef) : static_cast(manager); { // scoped lock... - nsAutoLock lock(mAdditionalManagersLock); + MutexAutoLock lock(mAdditionalManagersLock); if (mAdditionalManagers.IndexOf(ptrToAdd) != -1) return NS_ERROR_FAILURE; if (!mAdditionalManagers.AppendObject(ptrToAdd)) @@ -469,7 +460,7 @@ NS_IMETHODIMP xptiInterfaceInfoManager::RemoveAdditionalManager(nsIInterfaceInfo static_cast(weakRef) : static_cast(manager); { // scoped lock... - nsAutoLock lock(mAdditionalManagersLock); + MutexAutoLock lock(mAdditionalManagersLock); if (!mAdditionalManagers.RemoveObject(ptrToRemove)) return NS_ERROR_FAILURE; } @@ -486,7 +477,7 @@ NS_IMETHODIMP xptiInterfaceInfoManager::HasAdditionalManagers(PRBool *_retval) /* nsISimpleEnumerator enumerateAdditionalManagers (); */ NS_IMETHODIMP xptiInterfaceInfoManager::EnumerateAdditionalManagers(nsISimpleEnumerator **_retval) { - nsAutoLock lock(mAdditionalManagersLock); + MutexAutoLock lock(mAdditionalManagersLock); nsCOMArray managerArray(mAdditionalManagers); /* Resolve all the weak references in the array. */ diff --git a/xpcom/reflect/xptinfo/src/xptiWorkingSet.cpp b/xpcom/reflect/xptinfo/src/xptiWorkingSet.cpp index 5c125a95c30..f2eece16df0 100644 --- a/xpcom/reflect/xptinfo/src/xptiWorkingSet.cpp +++ b/xpcom/reflect/xptinfo/src/xptiWorkingSet.cpp @@ -42,6 +42,8 @@ #include "xptiprivate.h" #include "nsString.h" +using namespace mozilla; + #define XPTI_STRUCT_ARENA_BLOCK_SIZE (1024 * 1) #define XPTI_HASHTABLE_SIZE 2048 @@ -66,7 +68,7 @@ xpti_Invalidator(const char* keyname, xptiInterfaceEntry* entry, void* arg) void xptiWorkingSet::InvalidateInterfaceInfos() { - nsAutoMonitor lock(xptiInterfaceInfoManager::GetInfoMonitor()); + MonitorAutoEnter lock(xptiInterfaceInfoManager::GetInfoMonitor()); mNameTable.EnumerateRead(xpti_Invalidator, NULL); } diff --git a/xpcom/reflect/xptinfo/src/xptiprivate.h b/xpcom/reflect/xptinfo/src/xptiprivate.h index f27ccff7806..2eaeef3ecb7 100644 --- a/xpcom/reflect/xptinfo/src/xptiprivate.h +++ b/xpcom/reflect/xptinfo/src/xptiprivate.h @@ -62,6 +62,9 @@ #include "nsAppDirectoryServiceDefs.h" #include "nsIWeakReference.h" +#include "mozilla/Monitor.h" +#include "mozilla/Mutex.h" + #include "nsCRT.h" #include "nsMemory.h" @@ -73,8 +76,6 @@ #include "nsIInputStream.h" -#include "nsAutoLock.h" - #include "nsHashKeys.h" #include "nsDataHashtable.h" #include "plstr.h" @@ -432,7 +433,11 @@ class xptiInterfaceInfoManager NS_DECL_NSIINTERFACEINFOMANAGER NS_DECL_NSIINTERFACEINFOSUPERMANAGER + typedef mozilla::Monitor Monitor; + typedef mozilla::Mutex Mutex; + public: + // GetSingleton() is infallible static xptiInterfaceInfoManager* GetSingleton(); static void FreeInterfaceInfoManager(); @@ -441,20 +446,23 @@ public: xptiWorkingSet* GetWorkingSet() {return &mWorkingSet;} - static PRLock* GetResolveLock(xptiInterfaceInfoManager* self = nsnull) - {if(!self && !(self = GetSingleton())) - return nsnull; - return self->mResolveLock;} + static Mutex& GetResolveLock(xptiInterfaceInfoManager* self = nsnull) + { + self = self ? self : GetSingleton(); + return self->mResolveLock; + } - static PRLock* GetAutoRegLock(xptiInterfaceInfoManager* self = nsnull) - {if(!self && !(self = GetSingleton())) - return nsnull; - return self->mAutoRegLock;} + static Mutex& GetAutoRegLock(xptiInterfaceInfoManager* self = nsnull) + { + self = self ? self : GetSingleton(); + return self->mAutoRegLock; + } - static PRMonitor* GetInfoMonitor(xptiInterfaceInfoManager* self = nsnull) - {if(!self && !(self = GetSingleton())) - return nsnull; - return self->mInfoMonitor;} + static Monitor& GetInfoMonitor(xptiInterfaceInfoManager* self = nsnull) + { + self = self ? self : GetSingleton(); + return self->mInfoMonitor; + } xptiInterfaceEntry* GetInterfaceEntryForIID(const nsIID *iid); @@ -474,10 +482,10 @@ private: private: xptiWorkingSet mWorkingSet; - PRLock* mResolveLock; - PRLock* mAutoRegLock; - PRMonitor* mInfoMonitor; - PRLock* mAdditionalManagersLock; + Mutex mResolveLock; + Mutex mAutoRegLock; + Monitor mInfoMonitor; + Mutex mAdditionalManagersLock; nsCOMArray mAdditionalManagers; }; diff --git a/xpcom/threads/TimerThread.cpp b/xpcom/threads/TimerThread.cpp index e31f5f86f64..b28ee886d6c 100644 --- a/xpcom/threads/TimerThread.cpp +++ b/xpcom/threads/TimerThread.cpp @@ -41,7 +41,6 @@ #include "nsTimerImpl.h" #include "TimerThread.h" -#include "nsAutoLock.h" #include "nsThreadUtils.h" #include "pratom.h" @@ -52,13 +51,15 @@ #include +using namespace mozilla; + NS_IMPL_THREADSAFE_ISUPPORTS2(TimerThread, nsIRunnable, nsIObserver) TimerThread::TimerThread() : mInitInProgress(0), mInitialized(PR_FALSE), - mLock(nsnull), - mCondVar(nsnull), + mLock("TimerThread.mLock"), + mCondVar(mLock, "TimerThread.mCondVar"), mShutdown(PR_FALSE), mWaiting(PR_FALSE), mSleeping(PR_FALSE), @@ -69,11 +70,6 @@ TimerThread::TimerThread() : TimerThread::~TimerThread() { - if (mCondVar) - PR_DestroyCondVar(mCondVar); - if (mLock) - nsAutoLock::DestroyLock(mLock); - mThread = nsnull; NS_ASSERTION(mTimers.IsEmpty(), "Timers remain in TimerThread::~TimerThread"); @@ -82,15 +78,6 @@ TimerThread::~TimerThread() nsresult TimerThread::InitLocks() { - NS_ASSERTION(!mLock, "InitLocks called twice?"); - mLock = nsAutoLock::NewLock("TimerThread::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - - mCondVar = PR_NewCondVar(mLock); - if (!mCondVar) - return NS_ERROR_OUT_OF_MEMORY; - return NS_OK; } @@ -130,17 +117,17 @@ nsresult TimerThread::Init() } } - PR_Lock(mLock); - mInitialized = PR_TRUE; - PR_NotifyAllCondVar(mCondVar); - PR_Unlock(mLock); + { + MutexAutoLock lock(mLock); + mInitialized = PR_TRUE; + mCondVar.NotifyAll(); + } } else { - PR_Lock(mLock); + MutexAutoLock lock(mLock); while (!mInitialized) { - PR_WaitCondVar(mCondVar, PR_INTERVAL_NO_TIMEOUT); + mCondVar.Wait(); } - PR_Unlock(mLock); } if (!mThread) @@ -158,13 +145,13 @@ nsresult TimerThread::Shutdown() nsTArray timers; { // lock scope - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mShutdown = PR_TRUE; // notify the cond var so that Run() can return - if (mCondVar && mWaiting) - PR_NotifyCondVar(mCondVar); + if (mWaiting) + mCondVar.Notify(); // Need to copy content of mTimers array to a local array // because call to timers' ReleaseCallback() (and release its self) @@ -246,7 +233,7 @@ void TimerThread::UpdateFilter(PRUint32 aDelay, TimeStamp aTimeout, /* void Run(); */ NS_IMETHODIMP TimerThread::Run() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // We need to know how many microseconds give a positive PRIntervalTime. This // is platform-dependent, we calculate it at runtime now. @@ -296,40 +283,41 @@ NS_IMETHODIMP TimerThread::Run() NS_ADDREF(timer); RemoveTimerInternal(timer); - // We release mLock around the Fire call to avoid deadlock. - lock.unlock(); + { + // We release mLock around the Fire call to avoid deadlock. + MutexAutoUnlock unlock(mLock); #ifdef DEBUG_TIMERS - if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) { - PR_LOG(gTimerLog, PR_LOG_DEBUG, - ("Timer thread woke up %fms from when it was supposed to\n", - fabs((now - timer->mTimeout).ToMilliseconds()))); - } + if (PR_LOG_TEST(gTimerLog, PR_LOG_DEBUG)) { + PR_LOG(gTimerLog, PR_LOG_DEBUG, + ("Timer thread woke up %fms from when it was supposed to\n", + fabs((now - timer->mTimeout).ToMilliseconds()))); + } #endif - // We are going to let the call to PostTimerEvent here handle the - // release of the timer so that we don't end up releasing the timer - // on the TimerThread instead of on the thread it targets. - if (NS_FAILED(timer->PostTimerEvent())) { - nsrefcnt rc; - NS_RELEASE2(timer, rc); + // We are going to let the call to PostTimerEvent here handle the + // release of the timer so that we don't end up releasing the timer + // on the TimerThread instead of on the thread it targets. + if (NS_FAILED(timer->PostTimerEvent())) { + nsrefcnt rc; + NS_RELEASE2(timer, rc); - // The nsITimer interface requires that its users keep a reference - // to the timers they use while those timers are initialized but - // have not yet fired. If this ever happens, it is a bug in the - // code that created and used the timer. - // - // Further, note that this should never happen even with a - // misbehaving user, because nsTimerImpl::Release checks for a - // refcount of 1 with an armed timer (a timer whose only reference - // is from the timer thread) and when it hits this will remove the - // timer from the timer thread and thus destroy the last reference, - // preventing this situation from occurring. - NS_ASSERTION(rc != 0, "destroyed timer off its target thread!"); + // The nsITimer interface requires that its users keep a reference + // to the timers they use while those timers are initialized but + // have not yet fired. If this ever happens, it is a bug in the + // code that created and used the timer. + // + // Further, note that this should never happen even with a + // misbehaving user, because nsTimerImpl::Release checks for a + // refcount of 1 with an armed timer (a timer whose only reference + // is from the timer thread) and when it hits this will remove the + // timer from the timer thread and thus destroy the last reference, + // preventing this situation from occurring. + NS_ASSERTION(rc != 0, "destroyed timer off its target thread!"); + } + timer = nsnull; } - timer = nsnull; - lock.lock(); if (mShutdown) break; @@ -372,7 +360,7 @@ NS_IMETHODIMP TimerThread::Run() } mWaiting = PR_TRUE; - PR_WaitCondVar(mCondVar, waitFor); + mCondVar.Wait(waitFor); mWaiting = PR_FALSE; } @@ -381,7 +369,7 @@ NS_IMETHODIMP TimerThread::Run() nsresult TimerThread::AddTimer(nsTimerImpl *aTimer) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Add the timer to our list. PRInt32 i = AddTimerInternal(aTimer); @@ -389,15 +377,15 @@ nsresult TimerThread::AddTimer(nsTimerImpl *aTimer) return NS_ERROR_OUT_OF_MEMORY; // Awaken the timer thread. - if (mCondVar && mWaiting && i == 0) - PR_NotifyCondVar(mCondVar); + if (mWaiting && i == 0) + mCondVar.Notify(); return NS_OK; } nsresult TimerThread::TimerDelayChanged(nsTimerImpl *aTimer) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Our caller has a strong ref to aTimer, so it can't go away here under // ReleaseTimerInternal. @@ -408,15 +396,15 @@ nsresult TimerThread::TimerDelayChanged(nsTimerImpl *aTimer) return NS_ERROR_OUT_OF_MEMORY; // Awaken the timer thread. - if (mCondVar && mWaiting && i == 0) - PR_NotifyCondVar(mCondVar); + if (mWaiting && i == 0) + mCondVar.Notify(); return NS_OK; } nsresult TimerThread::RemoveTimer(nsTimerImpl *aTimer) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Remove the timer from our array. Tell callers that aTimer was not found // by returning NS_ERROR_NOT_AVAILABLE. Unlike the TimerDelayChanged case @@ -429,8 +417,8 @@ nsresult TimerThread::RemoveTimer(nsTimerImpl *aTimer) return NS_ERROR_NOT_AVAILABLE; // Awaken the timer thread. - if (mCondVar && mWaiting) - PR_NotifyCondVar(mCondVar); + if (mWaiting) + mCondVar.Notify(); return NS_OK; } diff --git a/xpcom/threads/TimerThread.h b/xpcom/threads/TimerThread.h index 61945588e51..087aead940d 100644 --- a/xpcom/threads/TimerThread.h +++ b/xpcom/threads/TimerThread.h @@ -49,14 +49,16 @@ #include "nsTArray.h" -#include "prcvar.h" +#include "mozilla/CondVar.h" +#include "mozilla/Mutex.h" #include "mozilla/TimeStamp.h" -#include "prlock.h" class TimerThread : public nsIRunnable, public nsIObserver { public: + typedef mozilla::CondVar CondVar; + typedef mozilla::Mutex Mutex; typedef mozilla::TimeStamp TimeStamp; typedef mozilla::TimeDuration TimeDuration; @@ -97,8 +99,8 @@ private: void ReleaseTimerInternal(nsTimerImpl *aTimer); nsCOMPtr mThread; - PRLock *mLock; - PRCondVar *mCondVar; + Mutex mLock; + CondVar mCondVar; PRPackedBool mShutdown; PRPackedBool mWaiting; diff --git a/xpcom/threads/nsEnvironment.cpp b/xpcom/threads/nsEnvironment.cpp index 1c1507edd73..32d6ab0b4d3 100644 --- a/xpcom/threads/nsEnvironment.cpp +++ b/xpcom/threads/nsEnvironment.cpp @@ -40,13 +40,14 @@ #include "nsEnvironment.h" #include "prenv.h" #include "prprf.h" -#include "nsAutoLock.h" #include "nsBaseHashtable.h" #include "nsHashKeys.h" #include "nsPromiseFlatString.h" #include "nsDependentString.h" #include "nsNativeCharsetUtils.h" +using namespace mozilla; + NS_IMPL_THREADSAFE_ISUPPORTS1(nsEnvironment, nsIEnvironment) nsresult @@ -65,12 +66,6 @@ nsEnvironment::Create(nsISupports *aOuter, REFNSIID aIID, return NS_ERROR_OUT_OF_MEMORY; } - obj->mLock = nsAutoLock::NewLock("nsEnvironment::mLock"); - if (!obj->mLock) { - delete obj; - return NS_ERROR_OUT_OF_MEMORY; - } - rv = obj->QueryInterface(aIID, aResult); if (NS_FAILED(rv)) { delete obj; @@ -80,8 +75,6 @@ nsEnvironment::Create(nsISupports *aOuter, REFNSIID aIID, nsEnvironment::~nsEnvironment() { - if (mLock) - nsAutoLock::DestroyLock(mLock); } NS_IMETHODIMP @@ -172,7 +165,7 @@ nsEnvironment::Set(const nsAString& aName, const nsAString& aValue) rv = NS_CopyUnicodeToNative(aValue, nativeVal); NS_ENSURE_SUCCESS(rv, rv); - nsAutoLock lock(mLock); // autolock unlocks automagically + MutexAutoLock lock(mLock); if (!EnsureEnvHash()){ return NS_ERROR_UNEXPECTED; diff --git a/xpcom/threads/nsEnvironment.h b/xpcom/threads/nsEnvironment.h index 4a35aac5d0c..4e2629be206 100644 --- a/xpcom/threads/nsEnvironment.h +++ b/xpcom/threads/nsEnvironment.h @@ -40,8 +40,8 @@ #ifndef nsEnvironment_h__ #define nsEnvironment_h__ +#include "mozilla/Mutex.h" #include "nsIEnvironment.h" -#include "prlock.h" #define NS_ENVIRONMENT_CID \ { 0X3D68F92UL, 0X9513, 0X4E25, \ @@ -58,10 +58,10 @@ public: void **aResult); private: - nsEnvironment() { } + nsEnvironment() : mLock("nsEnvironment.mLock") { } ~nsEnvironment(); - PRLock *mLock; + mozilla::Mutex mLock; }; #endif /* !nsEnvironment_h__ */ diff --git a/xpcom/threads/nsEventQueue.cpp b/xpcom/threads/nsEventQueue.cpp index 3ae4310cf37..63525b47b91 100644 --- a/xpcom/threads/nsEventQueue.cpp +++ b/xpcom/threads/nsEventQueue.cpp @@ -37,18 +37,19 @@ * ***** END LICENSE BLOCK ***** */ #include "nsEventQueue.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "prlog.h" #include "nsThreadUtils.h" +using namespace mozilla; + #ifdef PR_LOGGING static PRLogModuleInfo *sLog = PR_NewLogModule("nsEventQueue"); #endif #define LOG(args) PR_LOG(sLog, PR_LOG_DEBUG, args) nsEventQueue::nsEventQueue() - : mMonitor(nsAutoMonitor::NewMonitor("xpcom.eventqueue")) + : mMonitor("nsEventQueue.mMonitor") , mHead(nsnull) , mTail(nsnull) , mOffsetHead(0) @@ -64,16 +65,13 @@ nsEventQueue::~nsEventQueue() if (mHead) FreePage(mHead); - - if (mMonitor) - nsAutoMonitor::DestroyMonitor(mMonitor); } PRBool nsEventQueue::GetEvent(PRBool mayWait, nsIRunnable **result) { { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); while (IsEmpty()) { if (!mayWait) { @@ -109,7 +107,7 @@ nsEventQueue::PutEvent(nsIRunnable *runnable) nsRefPtr event(runnable); PRBool rv = PR_TRUE; { - nsAutoMonitor mon(mMonitor); + MonitorAutoEnter mon(mMonitor); if (!mHead) { mHead = NewPage(); diff --git a/xpcom/threads/nsEventQueue.h b/xpcom/threads/nsEventQueue.h index 7b89577416b..c919ac034f3 100644 --- a/xpcom/threads/nsEventQueue.h +++ b/xpcom/threads/nsEventQueue.h @@ -40,19 +40,18 @@ #define nsEventQueue_h__ #include -#include "prmon.h" +#include "mozilla/Monitor.h" #include "nsIRunnable.h" // A threadsafe FIFO event queue... class NS_COM nsEventQueue { + typedef mozilla::Monitor Monitor; + public: nsEventQueue(); ~nsEventQueue(); - // Returns "true" if the event queue has been completely constructed. - PRBool IsInitialized() { return mMonitor != nsnull; } - // This method adds a new event to the pending event queue. The event object // is AddRef'd if this method succeeds. This method returns PR_TRUE if the // event was stored in the event queue, and it returns PR_FALSE if it could @@ -83,7 +82,7 @@ public: } // Expose the event queue's monitor for "power users" - PRMonitor *Monitor() { + Monitor& GetMonitor() { return mMonitor; } @@ -111,7 +110,7 @@ private: free(p); } - PRMonitor *mMonitor; + Monitor mMonitor; Page *mHead; Page *mTail; diff --git a/xpcom/threads/nsProcess.h b/xpcom/threads/nsProcess.h index 5dc230ff5cd..4357f85a56c 100644 --- a/xpcom/threads/nsProcess.h +++ b/xpcom/threads/nsProcess.h @@ -44,6 +44,7 @@ #define PROCESSMODEL_WINAPI #endif +#include "mozilla/Mutex.h" #include "nsIProcess.h" #include "nsIFile.h" #include "nsIThread.h" @@ -89,7 +90,7 @@ private: PRBool holdWeak, PRBool argsUTF8); PRThread* mThread; - PRLock* mLock; + mozilla::Mutex mLock; PRBool mShutdown; nsCOMPtr mExecutable; diff --git a/xpcom/threads/nsProcessCommon.cpp b/xpcom/threads/nsProcessCommon.cpp index 6644a955655..10c7067b00d 100644 --- a/xpcom/threads/nsProcessCommon.cpp +++ b/xpcom/threads/nsProcessCommon.cpp @@ -53,7 +53,6 @@ #include "prio.h" #include "prenv.h" #include "nsCRT.h" -#include "nsAutoLock.h" #include "nsThreadUtils.h" #include "nsIObserverService.h" #include "mozilla/Services.h" @@ -84,6 +83,8 @@ #define ShellExecuteExW ShellExecuteEx #endif +using namespace mozilla; + #ifdef XP_MACOSX cpu_type_t pref_cpu_types[2] = { #if defined(__i386__) @@ -105,7 +106,7 @@ NS_IMPL_THREADSAFE_ISUPPORTS2(nsProcess, nsIProcess, //Constructor nsProcess::nsProcess() : mThread(nsnull) - , mLock(nsAutoLock::NewLock("nsProcess::mLock")) + , mLock("nsProcess.mLock") , mShutdown(PR_FALSE) , mPid(-1) , mObserver(nsnull) @@ -120,7 +121,6 @@ nsProcess::nsProcess() //Destructor nsProcess::~nsProcess() { - nsAutoLock::DestroyLock(mLock); } NS_IMETHODIMP @@ -276,7 +276,7 @@ void PR_CALLBACK nsProcess::Monitor(void *arg) // Lock in case Kill or GetExitCode are called during this { - nsAutoLock lock(process->mLock); + MutexAutoLock lock(process->mLock); CloseHandle(process->mProcess); process->mProcess = NULL; process->mExitValue = exitCode; @@ -303,7 +303,7 @@ void PR_CALLBACK nsProcess::Monitor(void *arg) // Lock in case Kill or GetExitCode are called during this { - nsAutoLock lock(process->mLock); + MutexAutoLock lock(process->mLock); #if !defined(XP_MACOSX) process->mProcess = nsnull; #endif @@ -606,7 +606,7 @@ nsProcess::Kill() return NS_ERROR_FAILURE; { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); #if defined(PROCESSMODEL_WINAPI) if (TerminateProcess(mProcess, NULL) == 0) return NS_ERROR_FAILURE; @@ -633,7 +633,7 @@ nsProcess::Kill() NS_IMETHODIMP nsProcess::GetExitValue(PRInt32 *aExitValue) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); *aExitValue = mExitValue; @@ -655,7 +655,7 @@ nsProcess::Observe(nsISupports* subject, const char* topic, const PRUnichar* dat mObserver = nsnull; mWeakObserver = nsnull; - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mShutdown = PR_TRUE; return NS_OK; diff --git a/xpcom/threads/nsThread.cpp b/xpcom/threads/nsThread.cpp index c5d37305e7f..70a929496bf 100644 --- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -36,11 +36,11 @@ * * ***** END LICENSE BLOCK ***** */ +#include "mozilla/Monitor.h" #include "nsThread.h" #include "nsThreadManager.h" #include "nsIClassInfoImpl.h" #include "nsIProgrammingLanguage.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsCOMPtr.h" #include "prlog.h" @@ -69,6 +69,8 @@ #include "nsCRT.h" #endif +using namespace mozilla; + #ifdef PR_LOGGING static PRLogModuleInfo *sLog = PR_NewLogModule("nsThread"); #endif @@ -174,12 +176,7 @@ class nsThreadStartupEvent : public nsRunnable { public: // Create a new thread startup object. static nsThreadStartupEvent *Create() { - nsThreadStartupEvent *startup = new nsThreadStartupEvent(); - if (startup && startup->mMon) - return startup; - // Allocation failure - delete startup; - return nsnull; + return new nsThreadStartupEvent(); } // This method does not return until the thread startup object is in the @@ -187,7 +184,7 @@ public: void Wait() { if (mInitialized) // Maybe avoid locking... return; - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); while (!mInitialized) mon.Wait(); } @@ -195,24 +192,22 @@ public: // This method needs to be public to support older compilers (xlC_r on AIX). // It should be called directly as this class type is reference counted. virtual ~nsThreadStartupEvent() { - if (mMon) - nsAutoMonitor::DestroyMonitor(mMon); } private: NS_IMETHOD Run() { - nsAutoMonitor mon(mMon); + MonitorAutoEnter mon(mMon); mInitialized = PR_TRUE; mon.Notify(); return NS_OK; } nsThreadStartupEvent() - : mMon(nsAutoMonitor::NewMonitor("xpcom.threadstartup")) + : mMon("nsThreadStartupEvent.mMon") , mInitialized(PR_FALSE) { } - PRMonitor *mMon; + Monitor mMon; PRBool mInitialized; }; @@ -284,7 +279,7 @@ nsThread::ThreadFunc(void *arg) // NS_ProcessPendingEvents. while (PR_TRUE) { { - nsAutoLock lock(self->mLock); + MutexAutoLock lock(self->mLock); if (!self->mEvents->HasPendingEvent()) { // No events in the queue, so we will stop now. Don't let any more // events be added, since they won't be processed. It is critical @@ -313,7 +308,7 @@ nsThread::ThreadFunc(void *arg) //----------------------------------------------------------------------------- nsThread::nsThread() - : mLock(nsAutoLock::NewLock("nsThread::mLock")) + : mLock("nsThread.mLock") , mEvents(&mEventsRoot) , mPriority(PRIORITY_NORMAL) , mThread(nsnull) @@ -326,15 +321,11 @@ nsThread::nsThread() nsThread::~nsThread() { - if (mLock) - nsAutoLock::DestroyLock(mLock); } nsresult nsThread::Init() { - NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY); - // spawn thread and wait until it is fully setup nsRefPtr startup = nsThreadStartupEvent::Create(); NS_ENSURE_TRUE(startup, NS_ERROR_OUT_OF_MEMORY); @@ -356,7 +347,7 @@ nsThread::Init() // mThread. By delaying insertion of this event into the queue, we ensure // that mThread is set properly. { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mEvents->PutEvent(startup); } @@ -369,8 +360,6 @@ nsThread::Init() nsresult nsThread::InitCurrentThread() { - NS_ENSURE_TRUE(mLock, NS_ERROR_OUT_OF_MEMORY); - mThread = PR_GetCurrentThread(); nsThreadManager::get()->RegisterCurrentThread(this); @@ -381,7 +370,7 @@ nsresult nsThread::PutEvent(nsIRunnable *event) { { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (mEventsAreDoomed) { NS_WARNING("An event was posted to a thread that will never run it (rejected)"); return NS_ERROR_UNEXPECTED; @@ -465,7 +454,7 @@ nsThread::Shutdown() // Prevent multiple calls to this method { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); if (!mShutdownRequired) return NS_ERROR_UNEXPECTED; mShutdownRequired = PR_FALSE; @@ -498,7 +487,7 @@ nsThread::Shutdown() #ifdef DEBUG { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_ASSERTION(!mObserver, "Should have been cleared at shutdown!"); } #endif @@ -702,7 +691,7 @@ nsThread::AdjustPriority(PRInt32 delta) NS_IMETHODIMP nsThread::GetObserver(nsIThreadObserver **obs) { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); NS_IF_ADDREF(*obs = mObserver); return NS_OK; } @@ -712,7 +701,7 @@ nsThread::SetObserver(nsIThreadObserver *obs) { NS_ENSURE_STATE(PR_GetCurrentThread() == mThread); - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); mObserver = obs; return NS_OK; } @@ -721,12 +710,8 @@ NS_IMETHODIMP nsThread::PushEventQueue(nsIThreadEventFilter *filter) { nsChainedEventQueue *queue = new nsChainedEventQueue(filter); - if (!queue || !queue->IsInitialized()) { - delete queue; - return NS_ERROR_OUT_OF_MEMORY; - } - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); queue->mNext = mEvents; mEvents = queue; return NS_OK; @@ -735,7 +720,7 @@ nsThread::PushEventQueue(nsIThreadEventFilter *filter) NS_IMETHODIMP nsThread::PopEventQueue() { - nsAutoLock lock(mLock); + MutexAutoLock lock(mLock); // Make sure we do not pop too many! NS_ENSURE_STATE(mEvents != &mEventsRoot); diff --git a/xpcom/threads/nsThread.h b/xpcom/threads/nsThread.h index 2a435fdcb52..f3dfc86c66c 100644 --- a/xpcom/threads/nsThread.h +++ b/xpcom/threads/nsThread.h @@ -39,13 +39,12 @@ #ifndef nsThread_h__ #define nsThread_h__ +#include "mozilla/Mutex.h" #include "nsIThreadInternal.h" #include "nsISupportsPriority.h" #include "nsEventQueue.h" #include "nsThreadUtils.h" #include "nsString.h" -#include "nsAutoLock.h" -#include "nsAutoPtr.h" #include "nsTObserverArray.h" // A native thread @@ -106,10 +105,6 @@ private: : mNext(nsnull), mFilter(filter) { } - PRBool IsInitialized() { - return mQueue.IsInitialized(); - } - PRBool GetEvent(PRBool mayWait, nsIRunnable **event) { return mQueue.GetEvent(mayWait, event); } @@ -131,7 +126,7 @@ private: // another thread). This means that we can avoid holding the lock while // using mObserver and mEvents on the thread itself. When calling PutEvent // on mEvents, we have to hold the lock to synchronize with PopEventQueue. - PRLock *mLock; + mozilla::Mutex mLock; nsCOMPtr mObserver; diff --git a/xpcom/threads/nsThreadManager.cpp b/xpcom/threads/nsThreadManager.cpp index 9d2ebc44d01..4d9ee128af6 100644 --- a/xpcom/threads/nsThreadManager.cpp +++ b/xpcom/threads/nsThreadManager.cpp @@ -42,9 +42,10 @@ #include "nsIClassInfoImpl.h" #include "nsTArray.h" #include "nsAutoPtr.h" -#include "nsAutoLock.h" #include "nsCycleCollectorUtils.h" +using namespace mozilla; + #ifdef XP_WIN #include DWORD gTLSThreadIDIndex = TlsAlloc(); @@ -88,16 +89,14 @@ NS_IMPL_CI_INTERFACE_GETTER1(nsThreadManager, nsIThreadManager) nsresult nsThreadManager::Init() { - mLock = nsAutoLock::NewLock("nsThreadManager::mLock"); - if (!mLock) - return NS_ERROR_OUT_OF_MEMORY; - if (!mThreadsByPRThread.Init()) return NS_ERROR_OUT_OF_MEMORY; if (PR_NewThreadPrivateIndex(&mCurThreadIndex, ReleaseObject) == PR_FAILURE) return NS_ERROR_FAILURE; + mLock = new Mutex("nsThreadManager.mLock"); + // Setup "main" thread mMainThread = new nsThread(); if (!mMainThread) @@ -142,7 +141,7 @@ nsThreadManager::Shutdown() // holding the hashtable lock while calling nsIThread::Shutdown. nsThreadArray threads; { - nsAutoLock lock(mLock); + MutexAutoLock lock(*mLock); mThreadsByPRThread.Enumerate(AppendAndRemoveThread, &threads); } @@ -169,7 +168,7 @@ nsThreadManager::Shutdown() // Clear the table of threads. { - nsAutoLock lock(mLock); + MutexAutoLock lock(*mLock); mThreadsByPRThread.Clear(); } @@ -180,13 +179,10 @@ nsThreadManager::Shutdown() // Release main thread object. mMainThread = nsnull; + mLock = nsnull; // Remove the TLS entry for the main thread. PR_SetThreadPrivate(mCurThreadIndex, nsnull); - - // We don't need this lock anymore. - nsAutoLock::DestroyLock(mLock); - mLock = nsnull; } void @@ -194,7 +190,7 @@ nsThreadManager::RegisterCurrentThread(nsThread *thread) { NS_ASSERTION(thread->GetPRThread() == PR_GetCurrentThread(), "bad thread"); - nsAutoLock lock(mLock); + MutexAutoLock lock(*mLock); mThreadsByPRThread.Put(thread->GetPRThread(), thread); // XXX check OOM? @@ -207,7 +203,7 @@ nsThreadManager::UnregisterCurrentThread(nsThread *thread) { NS_ASSERTION(thread->GetPRThread() == PR_GetCurrentThread(), "bad thread"); - nsAutoLock lock(mLock); + MutexAutoLock lock(*mLock); mThreadsByPRThread.Remove(thread->GetPRThread()); @@ -269,7 +265,7 @@ nsThreadManager::GetThreadFromPRThread(PRThread *thread, nsIThread **result) nsRefPtr temp; { - nsAutoLock lock(mLock); + MutexAutoLock lock(*mLock); mThreadsByPRThread.Get(thread, getter_AddRefs(temp)); } diff --git a/xpcom/threads/nsThreadManager.h b/xpcom/threads/nsThreadManager.h index e561f81a2ab..8d297b22907 100644 --- a/xpcom/threads/nsThreadManager.h +++ b/xpcom/threads/nsThreadManager.h @@ -39,6 +39,7 @@ #ifndef nsThreadManager_h__ #define nsThreadManager_h__ +#include "mozilla/Mutex.h" #include "nsIThreadManager.h" #include "nsRefPtrHashtable.h" #include "nsThread.h" @@ -91,7 +92,9 @@ private: PRUintn mCurThreadIndex; // thread-local-storage index nsRefPtr mMainThread; PRThread *mMainPRThread; - PRLock *mLock; // protects tables + // This is a pointer in order to allow creating nsThreadManager from + // the static context in debug builds. + nsAutoPtr mLock; // protects tables PRBool mInitialized; }; diff --git a/xpcom/threads/nsThreadPool.cpp b/xpcom/threads/nsThreadPool.cpp index 969493efc0d..25f2a321f99 100644 --- a/xpcom/threads/nsThreadPool.cpp +++ b/xpcom/threads/nsThreadPool.cpp @@ -43,10 +43,11 @@ #include "nsThread.h" #include "nsMemory.h" #include "nsAutoPtr.h" -#include "nsAutoLock.h" #include "prinrval.h" #include "prlog.h" +using namespace mozilla; + #ifdef PR_LOGGING static PRLogModuleInfo *sLog = PR_NewLogModule("nsThreadPool"); #endif @@ -91,7 +92,7 @@ nsThreadPool::PutEvent(nsIRunnable *event) PRBool spawnThread = PR_FALSE; { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); LOG(("THRD-P(%p) put [%d %d %d]\n", this, mIdleCount, mThreads.Count(), mThreadLimit)); @@ -114,7 +115,7 @@ nsThreadPool::PutEvent(nsIRunnable *event) PRBool killThread = PR_FALSE; { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); if (mThreads.Count() < (PRInt32) mThreadLimit) { mThreads.AppendObject(thread); } else { @@ -166,7 +167,7 @@ nsThreadPool::Run() nsCOMPtr listener; { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); listener = mListener; } @@ -177,7 +178,7 @@ nsThreadPool::Run() do { nsCOMPtr event; { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); if (!mEvents.GetPendingEvent(getter_AddRefs(event))) { PRIntervalTime now = PR_IntervalNow(); PRIntervalTime timeout = PR_MillisecondsToInterval(mIdleThreadTimeout); @@ -276,7 +277,7 @@ nsThreadPool::Shutdown() nsCOMArray threads; nsCOMPtr listener; { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); mShutdown = PR_TRUE; mon.NotifyAll(); @@ -308,7 +309,7 @@ nsThreadPool::GetThreadLimit(PRUint32 *value) NS_IMETHODIMP nsThreadPool::SetThreadLimit(PRUint32 value) { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); mThreadLimit = value; if (mIdleThreadLimit > mThreadLimit) mIdleThreadLimit = mThreadLimit; @@ -326,7 +327,7 @@ nsThreadPool::GetIdleThreadLimit(PRUint32 *value) NS_IMETHODIMP nsThreadPool::SetIdleThreadLimit(PRUint32 value) { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); mIdleThreadLimit = value; if (mIdleThreadLimit > mThreadLimit) mIdleThreadLimit = mThreadLimit; @@ -344,7 +345,7 @@ nsThreadPool::GetIdleThreadTimeout(PRUint32 *value) NS_IMETHODIMP nsThreadPool::SetIdleThreadTimeout(PRUint32 value) { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); mIdleThreadTimeout = value; mon.NotifyAll(); // wake up threads so they observe this change return NS_OK; @@ -353,7 +354,7 @@ nsThreadPool::SetIdleThreadTimeout(PRUint32 value) NS_IMETHODIMP nsThreadPool::GetListener(nsIThreadPoolListener** aListener) { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); NS_IF_ADDREF(*aListener = mListener); return NS_OK; } @@ -363,7 +364,7 @@ nsThreadPool::SetListener(nsIThreadPoolListener* aListener) { nsCOMPtr swappedListener(aListener); { - nsAutoMonitor mon(mEvents.Monitor()); + MonitorAutoEnter mon(mEvents.GetMonitor()); mListener.swap(swappedListener); } return NS_OK; diff --git a/xpcom/threads/nsTimerImpl.cpp b/xpcom/threads/nsTimerImpl.cpp index 859b89df3aa..200e1283fce 100644 --- a/xpcom/threads/nsTimerImpl.cpp +++ b/xpcom/threads/nsTimerImpl.cpp @@ -40,7 +40,6 @@ #include "nsTimerImpl.h" #include "TimerThread.h" -#include "nsAutoLock.h" #include "nsAutoPtr.h" #include "nsThreadManager.h" #include "nsThreadUtils.h" diff --git a/xpfe/appshell/src/nsWebShellWindow.cpp b/xpfe/appshell/src/nsWebShellWindow.cpp index e515044910e..090b7cd94a4 100644 --- a/xpfe/appshell/src/nsWebShellWindow.cpp +++ b/xpfe/appshell/src/nsWebShellWindow.cpp @@ -77,7 +77,6 @@ #include "nsXULPopupManager.h" #include "prmem.h" -#include "prlock.h" #include "nsIDOMXULDocument.h" @@ -116,6 +115,8 @@ #define USE_NATIVE_MENUS #endif +using namespace mozilla; + /* Define Class IDs */ static NS_DEFINE_CID(kWindowCID, NS_WINDOW_CID); @@ -123,8 +124,8 @@ static NS_DEFINE_CID(kWindowCID, NS_WINDOW_CID); nsWebShellWindow::nsWebShellWindow(PRUint32 aChromeFlags) : nsXULWindow(aChromeFlags) + , mSPTimerLock("nsWebShellWindow.mSPTimerLock") { - mSPTimerLock = PR_NewLock(); } @@ -136,13 +137,9 @@ nsWebShellWindow::~nsWebShellWindow() mWindow = nsnull; // Force release here. } - if (mSPTimerLock) { - PR_Lock(mSPTimerLock); - if (mSPTimer) - mSPTimer->Cancel(); - PR_Unlock(mSPTimerLock); - PR_DestroyLock(mSPTimerLock); - } + MutexAutoLock lock(mSPTimerLock); + if (mSPTimer) + mSPTimer->Cancel(); } NS_IMPL_ADDREF_INHERITED(nsWebShellWindow, nsXULWindow) @@ -517,10 +514,7 @@ static void LoadNativeMenus(nsIDOMDocument *aDOMDoc, nsIWidget *aParentWindow) void nsWebShellWindow::SetPersistenceTimer(PRUint32 aDirtyFlags) { - if (!mSPTimerLock) - return; - - PR_Lock(mSPTimerLock); + MutexAutoLock lock(mSPTimerLock); if (!mSPTimer) { nsresult rv; mSPTimer = do_CreateInstance("@mozilla.org/timer;1", &rv); @@ -531,18 +525,14 @@ nsWebShellWindow::SetPersistenceTimer(PRUint32 aDirtyFlags) mSPTimer->InitWithFuncCallback(FirePersistenceTimer, this, SIZE_PERSISTENCE_TIMEOUT, nsITimer::TYPE_ONE_SHOT); PersistentAttributesDirty(aDirtyFlags); - PR_Unlock(mSPTimerLock); } void nsWebShellWindow::FirePersistenceTimer(nsITimer *aTimer, void *aClosure) { nsWebShellWindow *win = static_cast(aClosure); - if (!win->mSPTimerLock) - return; - PR_Lock(win->mSPTimerLock); + MutexAutoLock lock(win->mSPTimerLock); win->SavePersistentAttributes(); - PR_Unlock(win->mSPTimerLock); } @@ -817,17 +807,14 @@ NS_IMETHODIMP nsWebShellWindow::Destroy() } nsCOMPtr kungFuDeathGrip(this); - if (mSPTimerLock) { - PR_Lock(mSPTimerLock); - if (mSPTimer) { - mSPTimer->Cancel(); - SavePersistentAttributes(); - mSPTimer = nsnull; - NS_RELEASE_THIS(); // the timer held a reference to us - } - PR_Unlock(mSPTimerLock); - PR_DestroyLock(mSPTimerLock); - mSPTimerLock = nsnull; + { + MutexAutoLock lock(mSPTimerLock); + if (mSPTimer) { + mSPTimer->Cancel(); + SavePersistentAttributes(); + mSPTimer = nsnull; + NS_RELEASE_THIS(); // the timer held a reference to us + } } return nsXULWindow::Destroy(); } diff --git a/xpfe/appshell/src/nsWebShellWindow.h b/xpfe/appshell/src/nsWebShellWindow.h index 974c8cb9712..3c26c02a2e0 100644 --- a/xpfe/appshell/src/nsWebShellWindow.h +++ b/xpfe/appshell/src/nsWebShellWindow.h @@ -38,6 +38,7 @@ #ifndef nsWebShellWindow_h__ #define nsWebShellWindow_h__ +#include "mozilla/Mutex.h" #include "nsEvent.h" #include "nsIWebProgressListener.h" #include "nsITimer.h" @@ -89,7 +90,7 @@ protected: static nsEventStatus HandleEvent(nsGUIEvent *aEvent); nsCOMPtr mSPTimer; - PRLock * mSPTimerLock; + mozilla::Mutex mSPTimerLock; void SetPersistenceTimer(PRUint32 aDirtyFlags); static void FirePersistenceTimer(nsITimer *aTimer, void *aClosure); diff --git a/xpfe/appshell/src/nsWindowMediator.cpp b/xpfe/appshell/src/nsWindowMediator.cpp index 2a7fc068160..87f0fcb3181 100644 --- a/xpfe/appshell/src/nsWindowMediator.cpp +++ b/xpfe/appshell/src/nsWindowMediator.cpp @@ -37,7 +37,6 @@ * ***** END LICENSE BLOCK ***** */ #include "nsCOMPtr.h" -#include "nsAutoLock.h" #include "nsString.h" #include "nsReadableUtils.h" #include "nsUnicharUtils.h" @@ -63,6 +62,8 @@ #include "nsIInterfaceRequestorUtils.h" #include "nsIXULWindow.h" +using namespace mozilla; + static nsresult GetDOMWindow(nsIXULWindow* inWindow, nsCOMPtr< nsIDOMWindowInternal>& outDOMWindow); @@ -89,7 +90,7 @@ GetDOMWindow(nsIXULWindow* inWindow, nsCOMPtr& outDOMWindo nsWindowMediator::nsWindowMediator() : mEnumeratorList(), mOldestWindow(nsnull), mTopmostWindow(nsnull), mTimeStamp(0), mSortingZOrder(PR_FALSE), mReady(PR_FALSE), - mListLock(nsnull) + mListLock("nsWindowMediator.mListLock") { } @@ -97,17 +98,10 @@ nsWindowMediator::~nsWindowMediator() { while (mOldestWindow) UnregisterWindow(mOldestWindow); - - if (mListLock) - nsAutoLock::DestroyLock(mListLock); } nsresult nsWindowMediator::Init() { - mListLock = nsAutoLock::NewLock("nsWindowMediator::mListLock"); - if (!mListLock) - return NS_ERROR_OUT_OF_MEMORY; - nsresult rv; nsCOMPtr obsSvc = do_GetService("@mozilla.org/observer-service;1", &rv); @@ -140,7 +134,7 @@ NS_IMETHODIMP nsWindowMediator::RegisterWindow(nsIXULWindow* inWindow) mListeners->EnumerateForwards(notifyOpenWindow, (void*)&winData); } - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); if (mOldestWindow) windowInfo->InsertAfter(mOldestWindow->mOlder, nsnull); else @@ -153,7 +147,7 @@ NS_IMETHODIMP nsWindowMediator::UnregisterWindow(nsIXULWindow* inWindow) { NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsWindowInfo *info = GetInfoFor(inWindow); if (info) return UnregisterWindow(info); @@ -240,7 +234,7 @@ nsWindowMediator::GetEnumerator(const PRUnichar* inType, nsISimpleEnumerator** o { NS_ENSURE_ARG_POINTER(outEnumerator); NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsAppShellWindowEnumerator *enumerator = new nsASDOMWindowEarlyToLateEnumerator(inType, *this); if (enumerator) return enumerator->QueryInterface(NS_GET_IID(nsISimpleEnumerator) , (void**)outEnumerator); @@ -253,7 +247,7 @@ nsWindowMediator::GetXULWindowEnumerator(const PRUnichar* inType, nsISimpleEnume { NS_ENSURE_ARG_POINTER(outEnumerator); NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsAppShellWindowEnumerator *enumerator = new nsASXULWindowEarlyToLateEnumerator(inType, *this); if (enumerator) return enumerator->QueryInterface(NS_GET_IID(nsISimpleEnumerator) , (void**)outEnumerator); @@ -268,7 +262,7 @@ nsWindowMediator::GetZOrderDOMWindowEnumerator( { NS_ENSURE_ARG_POINTER(_retval); NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsAppShellWindowEnumerator *enumerator; if (aFrontToBack) enumerator = new nsASDOMWindowFrontToBackEnumerator(aWindowType, *this); @@ -287,7 +281,7 @@ nsWindowMediator::GetZOrderXULWindowEnumerator( { NS_ENSURE_ARG_POINTER(_retval); NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsAppShellWindowEnumerator *enumerator; if (aFrontToBack) enumerator = new nsASXULWindowFrontToBackEnumerator(aWindowType, *this); @@ -324,7 +318,7 @@ nsWindowMediator::GetMostRecentWindow(const PRUnichar* inType, nsIDOMWindowInter // Find the most window with the highest time stamp that matches // the requested type - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsWindowInfo *info = MostRecentWindowInfo(inType); if (info && info->mWindow) { @@ -372,7 +366,7 @@ NS_IMETHODIMP nsWindowMediator::UpdateWindowTimeStamp(nsIXULWindow* inWindow) { NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsWindowInfo *info = GetInfoFor(inWindow); if (info) { // increment the window's time stamp @@ -387,7 +381,7 @@ nsWindowMediator::UpdateWindowTitle(nsIXULWindow* inWindow, const PRUnichar* inTitle) { NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); if (mListeners && GetInfoFor(inWindow)) { WindowTitleData winData = { inWindow, inTitle }; mListeners->EnumerateForwards(notifyWindowTitleChange, (void*)&winData); @@ -441,7 +435,7 @@ nsWindowMediator::CalculateZPosition( PRUint32 inZ; GetZLevel(inWindow, &inZ); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); if (inPosition == nsIWindowMediator::zLevelBelow) { // locate inBelow. use topmost if it can't be found or isn't in the @@ -555,7 +549,7 @@ nsWindowMediator::SetZPosition( return NS_OK; NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); /* Locate inWindow and unlink it from the z-order list. It's important we look for it in the age list, not the z-order list. @@ -613,7 +607,7 @@ NS_IMETHODIMP nsWindowMediator::SetZLevel(nsIXULWindow *aWindow, PRUint32 aZLevel) { NS_ENSURE_STATE(mReady); - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); nsWindowInfo *info = GetInfoFor(aWindow); NS_ASSERTION(info, "setting z level of unregistered window"); @@ -801,7 +795,7 @@ nsWindowMediator::Observe(nsISupports* aSubject, const PRUnichar* aData) { if (!strcmp(aTopic, "xpcom-shutdown") && mReady) { - nsAutoLock lock(mListLock); + MutexAutoLock lock(mListLock); while (mOldestWindow) UnregisterWindow(mOldestWindow); mReady = PR_FALSE; diff --git a/xpfe/appshell/src/nsWindowMediator.h b/xpfe/appshell/src/nsWindowMediator.h index 46d41981d6c..4343f68a287 100644 --- a/xpfe/appshell/src/nsWindowMediator.h +++ b/xpfe/appshell/src/nsWindowMediator.h @@ -38,6 +38,7 @@ #ifndef nsWindowMediator_h_ #define nsWindowMediator_h_ +#include "mozilla/Mutex.h" #include "nsCOMPtr.h" #include "nsIWindowMediator.h" #include "nsISupportsArray.h" @@ -97,7 +98,7 @@ private: PRInt32 mTimeStamp; PRBool mSortingZOrder; PRBool mReady; - PRLock *mListLock; + mozilla::Mutex mListLock; nsCOMPtr mListeners; };