author | Phil Ringnalda <philringnalda@gmail.com> |
Tue, 19 Nov 2013 14:38:29 -0800 | |
changeset 171124 | 78fb435aa0d2a1130271ae2016c3c98042c1d887 |
parent 171123 | bc781a9dd992bdc817f38d0d089db39cfc1e7159 |
child 171125 | 21a8de163f5ba621e0264fd484fe03d4b64bd934 |
push id | 3224 |
push user | lsblakk@mozilla.com |
push date | Tue, 04 Feb 2014 01:06:49 +0000 |
treeherder | mozilla-beta@60c04d0987f1 [default view] [failures only] |
perfherder | [talos] [build metrics] [platform microbench] (compared to previous push) |
bugs | 672843 |
milestone | 28.0a1 |
backs out | bbb7760083aec579ce15664d3f5fc91e14bf459d eaf2fd75d7fc98b651c827f853f4f8bef73e010e eb08cc206b8de83e5bb41847dda9a52fdae71393 6a0e4afd52ab064aca0f1cd5424f9fa4a1e42903 |
first release with | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
last release without | nightly linux32
nightly linux64
nightly mac
nightly win32
nightly win64
|
--- a/accessible/src/windows/msaa/IUnknownImpl.cpp +++ b/accessible/src/windows/msaa/IUnknownImpl.cpp @@ -18,17 +18,17 @@ namespace a11y { HRESULT GetHRESULT(nsresult aResult) { switch (aResult) { case NS_OK: return S_OK; - case NS_ERROR_INVALID_ARG: + case NS_ERROR_INVALID_ARG: case NS_ERROR_INVALID_POINTER: return E_INVALIDARG; case NS_ERROR_OUT_OF_MEMORY: return E_OUTOFMEMORY; case NS_ERROR_NOT_IMPLEMENTED: return E_NOTIMPL;
--- a/xpcom/base/ErrorList.h +++ b/xpcom/base/ErrorList.h @@ -11,29 +11,29 @@ ERROR(NS_ERROR_NOT_INITIALIZED, NS_ERROR_BASE + 1), /* Returned when an instance is already initialized */ ERROR(NS_ERROR_ALREADY_INITIALIZED, NS_ERROR_BASE + 2), /* Returned by a not implemented function */ ERROR(NS_ERROR_NOT_IMPLEMENTED, 0x80004001), /* Returned when a given interface is not supported. */ ERROR(NS_NOINTERFACE, 0x80004002), ERROR(NS_ERROR_NO_INTERFACE, NS_NOINTERFACE), + ERROR(NS_ERROR_INVALID_POINTER, 0x80004003), + ERROR(NS_ERROR_NULL_POINTER, NS_ERROR_INVALID_POINTER), /* Returned when a function aborts */ ERROR(NS_ERROR_ABORT, 0x80004004), /* Returned when a function fails */ ERROR(NS_ERROR_FAILURE, 0x80004005), /* Returned when an unexpected error occurs */ ERROR(NS_ERROR_UNEXPECTED, 0x8000ffff), /* Returned when a memory allocation fails */ ERROR(NS_ERROR_OUT_OF_MEMORY, 0x8007000e), /* Returned when an illegal value is passed */ ERROR(NS_ERROR_ILLEGAL_VALUE, 0x80070057), ERROR(NS_ERROR_INVALID_ARG, NS_ERROR_ILLEGAL_VALUE), - ERROR(NS_ERROR_INVALID_POINTER, NS_ERROR_INVALID_ARG), - ERROR(NS_ERROR_NULL_POINTER, NS_ERROR_INVALID_ARG), /* Returned when a class doesn't allow aggregation */ ERROR(NS_ERROR_NO_AGGREGATION, 0x80040110), /* Returned when an operation can't complete due to an unavailable resource */ ERROR(NS_ERROR_NOT_AVAILABLE, 0x80040111), /* Returned when a class is not registered */ ERROR(NS_ERROR_FACTORY_NOT_REGISTERED, 0x80040154), /* Returned when a class cannot be registered, but may be tried again later */ ERROR(NS_ERROR_FACTORY_REGISTER_AGAIN, 0x80040155),
--- a/xpcom/base/nsAgg.h +++ b/xpcom/base/nsAgg.h @@ -280,19 +280,19 @@ nsresult if (!tmp->IsPartOfAggregated()) \ NS_IMPL_CYCLE_COLLECTION_DESCRIBE(_class, tmp->mRefCnt.get()) #define NS_GENERIC_AGGREGATED_CONSTRUCTOR(_InstanceClass) \ static nsresult \ _InstanceClass##Constructor(nsISupports *aOuter, REFNSIID aIID, \ void **aResult) \ { \ - *aResult = nullptr; \ - if (NS_WARN_IF(aOuter && !aIID.Equals(NS_GET_IID(nsISupports)))) \ - return NS_ERROR_INVALID_ARG; \ + *aResult = nullptr; \ + \ + NS_ENSURE_PROPER_AGGREGATION(aOuter, aIID); \ \ _InstanceClass* inst = new _InstanceClass(aOuter); \ if (!inst) { \ return NS_ERROR_OUT_OF_MEMORY; \ } \ \ nsISupports* inner = inst->InnerObject(); \ nsresult rv = inner->QueryInterface(aIID, aResult); \ @@ -303,19 +303,19 @@ static nsresult return rv; \ } \ #define NS_GENERIC_AGGREGATED_CONSTRUCTOR_INIT(_InstanceClass, _InitMethod) \ static nsresult \ _InstanceClass##Constructor(nsISupports *aOuter, REFNSIID aIID, \ void **aResult) \ { \ - *aResult = nullptr; \ - if (NS_WARN_IF(aOuter && !aIID.Equals(NS_GET_IID(nsISupports)))) \ - return NS_ERROR_INVALID_ARG; \ + *aResult = nullptr; \ + \ + NS_ENSURE_PROPER_AGGREGATION(aOuter, aIID); \ \ _InstanceClass* inst = new _InstanceClass(aOuter); \ if (!inst) { \ return NS_ERROR_OUT_OF_MEMORY; \ } \ \ nsISupports* inner = inst->InnerObject(); \ NS_ADDREF(inner); \
--- a/xpcom/base/nsCycleCollector.cpp +++ b/xpcom/base/nsCycleCollector.cpp @@ -1216,41 +1216,37 @@ public: } // Initially create the log in a file starting with // "incomplete-gc-edges". We'll move the file and strip off the // "incomplete-" once the dump completes. (We do this because we don't // want scripts which poll the filesystem looking for gc/cc dumps to // grab a file before we're finished writing to it.) nsCOMPtr<nsIFile> gcLogFile = CreateTempFile("incomplete-gc-edges"); - if (NS_WARN_IF(!gcLogFile)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(gcLogFile); // Dump the JS heap. FILE* gcLogANSIFile = nullptr; gcLogFile->OpenANSIFileDesc("w", &gcLogANSIFile); - if (NS_WARN_IF(!gcLogANSIFile)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(gcLogANSIFile); MozillaRegisterDebugFILE(gcLogANSIFile); CollectorData *data = sCollectorData.get(); if (data && data->mRuntime) data->mRuntime->DumpJSHeap(gcLogANSIFile); MozillaUnRegisterDebugFILE(gcLogANSIFile); fclose(gcLogANSIFile); // Strip off "incomplete-". nsCOMPtr<nsIFile> gcLogFileFinalDestination = CreateTempFile("gc-edges"); - if (NS_WARN_IF(!gcLogFileFinalDestination)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(gcLogFileFinalDestination); nsAutoString gcLogFileFinalDestinationName; gcLogFileFinalDestination->GetLeafName(gcLogFileFinalDestinationName); - if (NS_WARN_IF(gcLogFileFinalDestinationName.IsEmpty())) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(!gcLogFileFinalDestinationName.IsEmpty()); gcLogFile->MoveTo(/* directory */ nullptr, gcLogFileFinalDestinationName); // Log to the error console. nsCOMPtr<nsIConsoleService> cs = do_GetService(NS_CONSOLESERVICE_CONTRACTID); if (cs) { nsAutoString gcLogPath; @@ -1259,22 +1255,20 @@ public: nsString msg = NS_LITERAL_STRING("Garbage Collector log dumped to ") + gcLogPath; cs->LogStringMessage(msg.get()); } // Open a file for dumping the CC graph. We again prefix with // "incomplete-". mOutFile = CreateTempFile("incomplete-cc-edges"); - if (NS_WARN_IF(!mOutFile)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mOutFile); MOZ_ASSERT(!mStream); mOutFile->OpenANSIFileDesc("w", &mStream); - if (NS_WARN_IF(!mStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mStream); MozillaRegisterDebugFILE(mStream); fprintf(mStream, "# WantAllTraces=%s\n", mWantAllTraces ? "true" : "false"); return NS_OK; } NS_IMETHOD NoteRefCountedObject(uint64_t aAddress, uint32_t refCount, const char *aObjectDescription) @@ -1389,23 +1383,21 @@ public: MozillaUnRegisterDebugFILE(mStream); fclose(mStream); mStream = nullptr; // Strip off "incomplete-" from the log file's name. nsCOMPtr<nsIFile> logFileFinalDestination = CreateTempFile("cc-edges"); - if (NS_WARN_IF(!logFileFinalDestination)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(logFileFinalDestination); nsAutoString logFileFinalDestinationName; logFileFinalDestination->GetLeafName(logFileFinalDestinationName); - if (NS_WARN_IF(logFileFinalDestinationName.IsEmpty())) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(!logFileFinalDestinationName.IsEmpty()); mOutFile->MoveTo(/* directory = */ nullptr, logFileFinalDestinationName); mOutFile = nullptr; // Log to the error console. nsCOMPtr<nsIConsoleService> cs = do_GetService(NS_CONSOLESERVICE_CONTRACTID); @@ -1418,18 +1410,17 @@ public: cs->LogStringMessage(msg.get()); } } return NS_OK; } NS_IMETHOD ProcessNext(nsICycleCollectorHandler* aHandler, bool* aCanContinue) { - if (NS_WARN_IF(!aHandler) || NS_WARN_IF(!mWantAfterProcessing)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(aHandler && mWantAfterProcessing); CCGraphDescriber* d = mDescribers.popFirst(); if (d) { switch (d->mType) { case CCGraphDescriber::eRefCountedObject: aHandler->NoteRefCountedObject(d->mAddress, d->mCnt, d->mName); break; @@ -1519,18 +1510,17 @@ private: NS_IMPL_ISUPPORTS1(nsCycleCollectorLogger, nsICycleCollectorListener) nsresult nsCycleCollectorLoggerConstructor(nsISupports* aOuter, const nsIID& aIID, void* *aInstancePtr) { - if (NS_WARN_IF(aOuter)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_TRUE(!aOuter, NS_ERROR_NO_AGGREGATION); nsISupports *logger = new nsCycleCollectorLogger(); return logger->QueryInterface(aIID, aInstancePtr); } //////////////////////////////////////////////////////////////////////// // Bacon & Rajan's |MarkRoots| routine. @@ -2443,18 +2433,17 @@ class CycleCollectorReporter MOZ_FINAL : do { \ size_t amount = _amount; /* evaluate |_amount| only once */ \ if (amount > 0) { \ nsresult rv; \ rv = aCb->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path), \ nsIMemoryReporter::KIND_HEAP, \ nsIMemoryReporter::UNITS_BYTES, _amount, \ NS_LITERAL_CSTRING(_desc), aClosure); \ - if (NS_WARN_IF(NS_FAILED(rv))) \ - return rv; \ + NS_ENSURE_SUCCESS(rv, rv); \ } \ } while (0) REPORT("explicit/cycle-collector/collector-object", objectSize, "Memory used for the cycle collector object itself."); REPORT("explicit/cycle-collector/graph-nodes", graphNodesSize, "Memory used for the nodes of the cycle collector's graph. "
--- a/xpcom/base/nsDebugImpl.cpp +++ b/xpcom/base/nsDebugImpl.cpp @@ -560,18 +560,17 @@ Break(const char *aMsg) #endif } static const nsDebugImpl kImpl; nsresult nsDebugImpl::Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr) { - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_NO_AGGREGATION(outer); return const_cast<nsDebugImpl*>(&kImpl)-> QueryInterface(aIID, aInstancePtr); } //////////////////////////////////////////////////////////////////////////////// nsresult
--- a/xpcom/base/nsErrorService.cpp +++ b/xpcom/base/nsErrorService.cpp @@ -60,18 +60,17 @@ nsInt2StrHashtable::Remove(uint32_t key) //////////////////////////////////////////////////////////////////////////////// NS_IMPL_ISUPPORTS1(nsErrorService, nsIErrorService) nsresult nsErrorService::Create(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr) { - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_NO_AGGREGATION(outer); nsRefPtr<nsErrorService> serv = new nsErrorService(); return serv->QueryInterface(aIID, aInstancePtr); } NS_IMETHODIMP nsErrorService::RegisterErrorStringBundle(int16_t errorModule, const char *stringBundleURL) { return mErrorStringBundleURLMap.Put(errorModule, stringBundleURL);
--- a/xpcom/base/nsGZFileWriter.cpp +++ b/xpcom/base/nsGZFileWriter.cpp @@ -28,71 +28,64 @@ nsGZFileWriter::~nsGZFileWriter() if (mInitialized && !mFinished) { Finish(); } } NS_IMETHODIMP nsGZFileWriter::Init(nsIFile* aFile) { - if (NS_WARN_IF(mInitialized) || - NS_WARN_IF(mFinished)) - return NS_ERROR_FAILURE; + NS_ENSURE_FALSE(mInitialized, NS_ERROR_FAILURE); + NS_ENSURE_FALSE(mFinished, NS_ERROR_FAILURE); // Get a FILE out of our nsIFile. Convert that into a file descriptor which // gzip can own. Then close our FILE, leaving only gzip's fd open. FILE* file; nsresult rv = aFile->OpenANSIFileDesc("wb", &file); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mGZFile = gzdopen(dup(fileno(file)), "wb"); fclose(file); // gzdopen returns nullptr on error. - if (NS_WARN_IF(!mGZFile)) - return NS_ERROR_FAILURE; - + NS_ENSURE_TRUE(mGZFile, NS_ERROR_FAILURE); mInitialized = true; return NS_OK; } NS_IMETHODIMP nsGZFileWriter::Write(const nsACString& aStr) { - if (NS_WARN_IF(!mInitialized) || - NS_WARN_IF(mFinished)) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(mInitialized, NS_ERROR_NOT_INITIALIZED); + NS_ENSURE_FALSE(mFinished, NS_ERROR_FAILURE); // gzwrite uses a return value of 0 to indicate failure. Otherwise, it // returns the number of uncompressed bytes written. To ensure we can // distinguish between success and failure, don't call gzwrite when we have 0 // bytes to write. if (aStr.IsEmpty()) { return NS_OK; } // gzwrite never does a short write -- that is, the return value should // always be either 0 or aStr.Length(), and we shouldn't have to call it // multiple times in order to get it to read the whole buffer. int rv = gzwrite(mGZFile, aStr.BeginReading(), aStr.Length()); - if (NS_WARN_IF(rv != static_cast<int>(aStr.Length()))) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(rv == static_cast<int>(aStr.Length()), NS_ERROR_FAILURE); return NS_OK; } NS_IMETHODIMP nsGZFileWriter::Finish() { - if (NS_WARN_IF(!mInitialized) || - NS_WARN_IF(mFinished)) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(mInitialized, NS_ERROR_NOT_INITIALIZED); + NS_ENSURE_FALSE(mFinished, NS_ERROR_FAILURE); mFinished = true; gzclose(mGZFile); // Ignore errors from gzclose; it's not like there's anything we can do about // it, at this point! return NS_OK; }
--- a/xpcom/base/nsIMemoryReporter.idl +++ b/xpcom/base/nsIMemoryReporter.idl @@ -530,18 +530,17 @@ public: return NS_OK; } NS_IMETHOD CollectReports(nsIMemoryReporterCallback* aCallback, nsISupports* aData) { int64_t amount; nsresult rv = GetAmount(&amount); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return aCallback->Callback(EmptyCString(), mNameAndPath, mKind, mUnits, amount, mDescription, aData); } protected: NS_IMETHOD GetAmount(int64_t* aAmount) {
--- a/xpcom/base/nsMacUtilsImpl.cpp +++ b/xpcom/base/nsMacUtilsImpl.cpp @@ -84,18 +84,17 @@ nsresult nsMacUtilsImpl::GetArchString(n archString.Assign(mBinaryArchs); return (archString.IsEmpty() ? NS_ERROR_FAILURE : NS_OK); } NS_IMETHODIMP nsMacUtilsImpl::GetIsUniversalBinary(bool *aIsUniversalBinary) { - if (NS_WARN_IF(!aIsUniversalBinary)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aIsUniversalBinary); *aIsUniversalBinary = false; nsAutoString archString; nsresult rv = GetArchString(archString); if (NS_FAILED(rv)) return rv; // The delimiter char in the arch string is '-', so if that character
--- a/xpcom/base/nsMemoryImpl.cpp +++ b/xpcom/base/nsMemoryImpl.cpp @@ -88,18 +88,17 @@ nsMemoryImpl::IsLowMemoryPlatform(bool * *result = false; #endif return NS_OK; } /*static*/ nsresult nsMemoryImpl::Create(nsISupports* outer, const nsIID& aIID, void **aResult) { - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_NO_AGGREGATION(outer); return sGlobalMemory.QueryInterface(aIID, aResult); } nsresult nsMemoryImpl::FlushMemory(const PRUnichar* aReason, bool aImmediate) { nsresult rv = NS_OK;
--- a/xpcom/base/nsMemoryInfoDumper.cpp +++ b/xpcom/base/nsMemoryInfoDumper.cpp @@ -411,28 +411,25 @@ public: if (NS_SUCCEEDED(rv)) { rv = XRE_GetFileFromPath(dirPath.get(), getter_AddRefs(file)); if (NS_FAILED(rv)) { LOG("FifoWatcher failed to open file \"%s\"", dirPath.get()); return -1; } } else { rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(file)); - if (NS_WARN_IF(NS_FAILED(rv))) - return -1; + NS_ENSURE_SUCCESS(rv, -1); } rv = file->AppendNative(NS_LITERAL_CSTRING("debug_info_trigger")); - if (NS_WARN_IF(NS_FAILED(rv))) - return -1; + NS_ENSURE_SUCCESS(rv, -1); nsAutoCString path; rv = file->GetNativePath(path); - if (NS_WARN_IF(NS_FAILED(rv))) - return -1; + NS_ENSURE_SUCCESS(rv, -1); // unlink might fail because the file doesn't exist, or for other reasons. // But we don't care it fails; any problems will be detected later, when we // try to mkfifo or open the file. if (unlink(path.get())) { LOG("FifoWatcher::OpenFifo unlink failed; errno=%d. " "Continuing despite error.", errno); } @@ -604,18 +601,17 @@ nsMemoryInfoDumper::DumpGCAndCCLogsToFil return NS_OK; } namespace mozilla { #define DUMP(o, s) \ do { \ nsresult rv = (o)->Write(s); \ - if (NS_WARN_IF(NS_FAILED(rv))) \ - return rv; \ + NS_ENSURE_SUCCESS(rv, rv); \ } while (0) static nsresult DumpReport(nsIGZFileWriter *aWriter, bool aIsFirst, const nsACString &aProcess, const nsACString &aPath, int32_t aKind, int32_t aUnits, int64_t aAmount, const nsACString &aDescription) { DUMP(aWriter, aIsFirst ? "[" : ","); @@ -679,18 +675,17 @@ public: DumpReportCallback() : mIsFirst(true) {} NS_IMETHOD Callback(const nsACString &aProcess, const nsACString &aPath, int32_t aKind, int32_t aUnits, int64_t aAmount, const nsACString &aDescription, nsISupports *aData) { nsCOMPtr<nsIGZFileWriter> writer = do_QueryInterface(aData); - if (NS_WARN_IF(!writer)) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(writer, NS_ERROR_FAILURE); nsresult rv = DumpReport(writer, mIsFirst, aProcess, aPath, aKind, aUnits, aAmount, aDescription); mIsFirst = false; return rv; } private: @@ -722,59 +717,53 @@ nsMemoryInfoDumper::OpenTempFile(const n if (env) { NS_NewNativeLocalFile(nsCString(env), /* followLinks = */ true, aFile); } } #endif nsresult rv; if (!*aFile) { rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, aFile); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } #ifdef ANDROID // /data/local/tmp is a true tmp directory; anyone can create a file there, // but only the user which created the file can remove it. We want non-root // users to be able to remove these files, so we write them into a // subdirectory of the temp directory and chmod 777 that directory. rv = (*aFile)->AppendNative(NS_LITERAL_CSTRING("memory-reports")); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // It's OK if this fails; that probably just means that the directory already // exists. (*aFile)->Create(nsIFile::DIRECTORY_TYPE, 0777); nsAutoCString dirPath; rv = (*aFile)->GetNativePath(dirPath); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); while (chmod(dirPath.get(), 0777) == -1 && errno == EINTR) {} #endif nsCOMPtr<nsIFile> file(*aFile); rv = file->AppendNative(aFilename); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = file->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0666); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); #ifdef ANDROID // Make this file world-read/writable; the permissions passed to the // CreateUnique call above are not sufficient on Android, which runs with a // umask. nsAutoCString path; rv = file->GetNativePath(path); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); while (chmod(path.get(), 0666) == -1 && errno == EINTR) {} #endif return NS_OK; } #ifdef MOZ_DMD @@ -807,18 +796,17 @@ DumpHeader(nsIGZFileWriter* aWriter) // over 200 KiB of memory. // DUMP(aWriter, "{\n \"version\": 1,\n"); DUMP(aWriter, " \"hasMozMallocUsableSize\": "); nsCOMPtr<nsIMemoryReporterManager> mgr = do_GetService("@mozilla.org/memory-reporter-manager;1"); - if (NS_WARN_IF(!mgr)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mgr); DUMP(aWriter, mgr->GetHasMozMallocUsableSize() ? "true" : "false"); DUMP(aWriter, ",\n"); DUMP(aWriter, " \"reports\": "); return NS_OK; } @@ -879,22 +867,21 @@ DumpProcessMemoryInfoToTempDir(const nsA nsCString mrFilename; MakeFilename("memory-report", aIdentifier, "json.gz", mrFilename); nsCOMPtr<nsIFile> mrTmpFile; nsresult rv; rv = nsMemoryInfoDumper::OpenTempFile(NS_LITERAL_CSTRING("incomplete-") + mrFilename, getter_AddRefs(mrTmpFile)); - if (NS_WARN_IF(NS_FAILED(rv))) return rv; + NS_ENSURE_SUCCESS(rv, rv); nsRefPtr<nsGZFileWriter> mrWriter = new nsGZFileWriter(); rv = mrWriter->Init(mrTmpFile); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // Dump the memory reports to the file. DumpProcessMemoryReportsToGZFileWriter(mrWriter); #ifdef MOZ_DMD // Create a filename like dmd-<identifier>-<pid>.txt.gz, which will be used // if DMD is enabled. nsCString dmdFilename; @@ -902,86 +889,74 @@ DumpProcessMemoryInfoToTempDir(const nsA // Open a new DMD file named |dmdFilename| in NS_OS_TEMP_DIR for writing, // and dump DMD output to it. This must occur after the memory reporters // have been run (above), but before the memory-reports file has been // renamed (so scripts can detect the DMD file, if present). nsCOMPtr<nsIFile> dmdFile; rv = nsMemoryInfoDumper::OpenTempFile(dmdFilename, getter_AddRefs(dmdFile)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); nsRefPtr<nsGZFileWriter> dmdWriter = new nsGZFileWriter(); rv = dmdWriter->Init(dmdFile); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // Dump DMD output to the file. DMDWriteState state(dmdWriter); dmd::Writer w(DMDWrite, &state); dmd::Dump(w); rv = dmdWriter->Finish(); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); #endif // MOZ_DMD // The call to Finish() deallocates the memory allocated by mrWriter's first // DUMP() call (within DumpProcessMemoryReportsToGZFileWriter()). Because // that memory was live while the memory reporters ran and thus measured by // them -- by "heap-allocated" if nothing else -- we want DMD to see it as // well. So we deliberately don't call Finish() until after DMD finishes. rv = mrWriter->Finish(); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // Rename the memory reports file, now that we're done writing all the files. // Its final name is "memory-report<-identifier>-<pid>.json.gz". nsCOMPtr<nsIFile> mrFinalFile; rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(mrFinalFile)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); #ifdef ANDROID rv = mrFinalFile->AppendNative(NS_LITERAL_CSTRING("memory-reports")); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); #endif rv = mrFinalFile->AppendNative(mrFilename); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = mrFinalFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0600); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); nsAutoString mrActualFinalFilename; rv = mrFinalFile->GetLeafName(mrActualFinalFilename); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = mrTmpFile->MoveTo(/* directory */ nullptr, mrActualFinalFilename); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // Write a message to the console. nsCOMPtr<nsIConsoleService> cs = do_GetService(NS_CONSOLESERVICE_CONTRACTID, &rv); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); nsString path; mrTmpFile->GetPath(path); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); nsString msg = NS_LITERAL_STRING( "nsIMemoryInfoDumper dumped reports to "); msg.Append(path); return cs->LogStringMessage(msg.get()); } NS_IMETHODIMP @@ -1008,18 +983,17 @@ nsMemoryInfoDumper::DumpMemoryInfoToTemp if (aMinimizeMemoryUsage) { // Minimize memory usage, then run DumpMemoryInfoToTempDir again. nsRefPtr<DumpMemoryInfoToTempDirRunnable> callback = new DumpMemoryInfoToTempDirRunnable(identifier, /* minimizeMemoryUsage = */ false, /* dumpChildProcesses = */ false); nsCOMPtr<nsIMemoryReporterManager> mgr = do_GetService("@mozilla.org/memory-reporter-manager;1"); - if (NS_WARN_IF(!mgr)) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(mgr, NS_ERROR_FAILURE); nsCOMPtr<nsICancelableRunnable> runnable; mgr->MinimizeMemoryUsage(callback, getter_AddRefs(runnable)); return NS_OK; } return DumpProcessMemoryInfoToTempDir(identifier); } @@ -1064,44 +1038,38 @@ nsMemoryInfoDumper::DumpMemoryReportsToN nsISupports* aFinishDumpingData) { MOZ_ASSERT(!aFilename.IsEmpty()); // Create the file. nsCOMPtr<nsIFile> mrFile; nsresult rv = NS_NewLocalFile(aFilename, false, getter_AddRefs(mrFile)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mrFile->InitWithPath(aFilename); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); bool exists; rv = mrFile->Exists(&exists); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); if (!exists) { rv = mrFile->Create(nsIFile::NORMAL_FILE_TYPE, 0644); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } // Write the memory reports to the file. nsRefPtr<nsGZFileWriter> mrWriter = new nsGZFileWriter(); rv = mrWriter->Init(mrFile); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = DumpHeader(mrWriter); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // Process reports and finish up. nsRefPtr<DumpReportCallback> dumpReport = new DumpReportCallback(); nsRefPtr<FinishReportingCallback> finishReporting = new FinishReportingCallback(aFinishDumping, aFinishDumpingData); nsCOMPtr<nsIMemoryReporterManager> mgr = do_GetService("@mozilla.org/memory-reporter-manager;1"); return mgr->GetReports(dumpReport, mrWriter, finishReporting, mrWriter);
--- a/xpcom/base/nsMemoryReporterManager.cpp +++ b/xpcom/base/nsMemoryReporterManager.cpp @@ -97,18 +97,17 @@ private: // statm's "shared" value actually counts pages backed by files, which has // little to do with whether the pages are actually shared. // /proc/self/smaps on the other hand appears to give us the correct // information. *aAmount = 0; FILE *f = fopen("/proc/self/smaps", "r"); - if (NS_WARN_IF(!f)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(f); int64_t total = 0; char line[256]; while (fgets(line, sizeof(line), f)) { long long val = 0; if (sscanf(line, "Private_Dirty: %lld kB", &val) == 1 || sscanf(line, "Private_Clean: %lld kB", &val) == 1) { total += val * 1024; // convert from kB to bytes @@ -748,18 +747,17 @@ public: #define REPORT(_path, _amount, _desc) \ do { \ nsresult rv; \ rv = aHandleReport->Callback(EmptyCString(), NS_LITERAL_CSTRING(_path), \ nsIMemoryReporter::KIND_HEAP, \ nsIMemoryReporter::UNITS_BYTES, _amount, \ NS_LITERAL_CSTRING(_desc), aData); \ - if (NS_WARN_IF(NS_FAILED(rv))) \ - return rv; \ + NS_ENSURE_SUCCESS(rv, rv); \ } while (0) REPORT("explicit/dmd/stack-traces/used", sizes.mStackTracesUsed, "Memory used by stack traces which correspond to at least " "one heap block DMD is tracking."); REPORT("explicit/dmd/stack-traces/unused", @@ -1281,18 +1279,17 @@ public: return NS_OK; } }; NS_IMPL_ISUPPORTS1(ExplicitCallback, nsIHandleReportCallback) NS_IMETHODIMP nsMemoryReporterManager::GetExplicit(int64_t* aAmount) { - if (NS_WARN_IF(!aAmount)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aAmount); *aAmount = 0; #ifndef HAVE_JEMALLOC_STATS return NS_ERROR_NOT_AVAILABLE; #else bool more; // For each reporter we call CollectReports and filter out the // non-explicit, non-NONHEAP measurements (except for "heap-allocated"). @@ -1548,18 +1545,17 @@ private: }; } // anonymous namespace NS_IMETHODIMP nsMemoryReporterManager::MinimizeMemoryUsage(nsIRunnable* aCallback, nsICancelableRunnable** aResult) { - if (NS_WARN_IF(!aResult)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aResult); nsRefPtr<nsICancelableRunnable> runnable = new MinimizeMemoryUsageRunnable(aCallback); NS_ADDREF(*aResult = runnable); return NS_DispatchToMainThread(runnable); } @@ -1572,29 +1568,27 @@ nsMemoryReporterManager::SizeOfTab(nsIDO int64_t* aStyleSize, int64_t* aOtherSize, int64_t* aTotalSize, double* aJSMilliseconds, double* aNonJSMilliseconds) { nsCOMPtr<nsIGlobalObject> global = do_QueryInterface(aTopWindow); nsCOMPtr<nsPIDOMWindow> piWindow = do_QueryInterface(aTopWindow); - if (NS_WARN_IF(!global) || NS_WARN_IF(!piWindow)) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(!!global && !!piWindow, NS_ERROR_FAILURE); TimeStamp t1 = TimeStamp::Now(); // Measure JS memory consumption (and possibly some non-JS consumption, via // |jsPrivateSize|). size_t jsObjectsSize, jsStringsSize, jsPrivateSize, jsOtherSize; nsresult rv = mSizeOfTabFns.mJS(global->GetGlobalJSObject(), &jsObjectsSize, &jsStringsSize, &jsPrivateSize, &jsOtherSize); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); TimeStamp t2 = TimeStamp::Now(); // Measure non-JS memory consumption. size_t domSize, styleSize, otherSize; mSizeOfTabFns.mNonJS(piWindow, &domSize, &styleSize, &otherSize); TimeStamp t3 = TimeStamp::Now();
--- a/xpcom/base/nsMessageLoop.cpp +++ b/xpcom/base/nsMessageLoop.cpp @@ -82,18 +82,17 @@ MessageLoopIdleTask::MessageLoopIdleTask mTimer = nullptr; } } nsresult MessageLoopIdleTask::Init(uint32_t aEnsureRunsAfterMS) { mTimer = do_CreateInstance("@mozilla.org/timer;1"); - if (NS_WARN_IF(!mTimer)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mTimer); nsRefPtr<MessageLoopTimerCallback> callback = new MessageLoopTimerCallback(this); return mTimer->InitWithCallback(callback, aEnsureRunsAfterMS, nsITimer::TYPE_ONE_SHOT); } @@ -149,13 +148,12 @@ nsMessageLoop::PostIdleTask(nsIRunnable* return NS_OK; } nsresult nsMessageLoopConstructor(nsISupports* aOuter, const nsIID& aIID, void** aInstancePtr) { - if (NS_WARN_IF(aOuter)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_FALSE(aOuter, NS_ERROR_NO_AGGREGATION); nsISupports* messageLoop = new nsMessageLoop(); return messageLoop->QueryInterface(aIID, aInstancePtr); }
--- a/xpcom/base/nsSystemInfo.cpp +++ b/xpcom/base/nsSystemInfo.cpp @@ -160,46 +160,43 @@ nsSystemInfo::Init() { PR_SI_RELEASE, "version" } }; for (uint32_t i = 0; i < (sizeof(items) / sizeof(items[0])); i++) { char buf[SYS_INFO_BUFFER_LENGTH]; if (PR_GetSystemInfo(items[i].cmd, buf, sizeof(buf)) == PR_SUCCESS) { rv = SetPropertyAsACString(NS_ConvertASCIItoUTF16(items[i].name), nsDependentCString(buf)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } else { NS_WARNING("PR_GetSystemInfo failed"); } } // Additional informations not available through PR_GetSystemInfo. SetInt32Property(NS_LITERAL_STRING("pagesize"), PR_GetPageSize()); SetInt32Property(NS_LITERAL_STRING("pageshift"), PR_GetPageShift()); SetInt32Property(NS_LITERAL_STRING("memmapalign"), PR_GetMemMapAlignment()); SetInt32Property(NS_LITERAL_STRING("cpucount"), PR_GetNumberOfProcessors()); SetUint64Property(NS_LITERAL_STRING("memsize"), PR_GetPhysicalMemorySize()); for (uint32_t i = 0; i < ArrayLength(cpuPropItems); i++) { rv = SetPropertyAsBool(NS_ConvertASCIItoUTF16(cpuPropItems[i].name), cpuPropItems[i].propfun()); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } #ifdef XP_WIN BOOL isWow64; BOOL gotWow64Value = IsWow64Process(GetCurrentProcess(), &isWow64); NS_WARN_IF_FALSE(gotWow64Value, "IsWow64Process failed"); if (gotWow64Value) { rv = SetPropertyAsBool(NS_LITERAL_STRING("isWow64"), !!isWow64); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } nsAutoCString hddModel, hddRevision; if (NS_SUCCEEDED(GetProfileHDDInfo(hddModel, hddRevision))) { rv = SetPropertyAsACString(NS_LITERAL_STRING("profileHDDModel"), hddModel); NS_ENSURE_SUCCESS(rv, rv); rv = SetPropertyAsACString(NS_LITERAL_STRING("profileHDDRevision"), hddRevision); NS_ENSURE_SUCCESS(rv, rv); @@ -208,18 +205,17 @@ nsSystemInfo::Init() #if defined(MOZ_WIDGET_GTK) // This must be done here because NSPR can only separate OS's when compiled, not libraries. char* gtkver = PR_smprintf("GTK %u.%u.%u", gtk_major_version, gtk_minor_version, gtk_micro_version); if (gtkver) { rv = SetPropertyAsACString(NS_LITERAL_STRING("secondaryLibrary"), nsDependentCString(gtkver)); PR_smprintf_free(gtkver); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } #endif #ifdef MOZ_WIDGET_ANDROID if (mozilla::AndroidBridge::Bridge()) { nsAutoString str; if (mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build", "MODEL", str)) SetPropertyAsAString(NS_LITERAL_STRING("device"), str);
--- a/xpcom/build/Omnijar.cpp +++ b/xpcom/build/Omnijar.cpp @@ -140,30 +140,28 @@ Omnijar::GetURIString(Type aType, nsACSt // Return an empty string for APP in the unified case. if ((aType == APP) && sIsUnified) { return NS_OK; } nsAutoCString omniJarSpec; if (sPath[aType]) { nsresult rv = NS_GetURLSpecFromActualFile(sPath[aType], omniJarSpec); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); result = "jar:"; if (sIsNested[aType]) result += "jar:"; result += omniJarSpec; result += "!"; if (sIsNested[aType]) result += "/" NS_STRINGIFY(OMNIJAR_NAME) "!"; } else { nsCOMPtr<nsIFile> dir; nsDirectoryService::gService->Get(SPROP(aType), NS_GET_IID(nsIFile), getter_AddRefs(dir)); nsresult rv = NS_GetURLSpecFromActualFile(dir, result); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } result += "/"; return NS_OK; } } /* namespace mozilla */
--- a/xpcom/build/nsXPCOMStrings.cpp +++ b/xpcom/build/nsXPCOMStrings.cpp @@ -35,18 +35,17 @@ NS_StringContainerInit2(nsStringContaine if (!aData) { new (&aContainer) nsString(); } else { if (aDataLength == UINT32_MAX) { - if (NS_WARN_IF(aFlags & NS_STRING_CONTAINER_INIT_SUBSTRING)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(!(aFlags & NS_STRING_CONTAINER_INIT_SUBSTRING)); aDataLength = nsCharTraits<PRUnichar>::length(aData); } if (aFlags & (NS_STRING_CONTAINER_INIT_DEPEND | NS_STRING_CONTAINER_INIT_ADOPT)) { uint32_t flags; if (aFlags & NS_STRING_CONTAINER_INIT_SUBSTRING) @@ -196,18 +195,17 @@ NS_CStringContainerInit2(nsCStringContai if (!aData) { new (&aContainer) nsCString(); } else { if (aDataLength == UINT32_MAX) { - if (NS_WARN_IF(aFlags & NS_CSTRING_CONTAINER_INIT_SUBSTRING)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(!(aFlags & NS_CSTRING_CONTAINER_INIT_SUBSTRING)); aDataLength = nsCharTraits<char>::length(aData); } if (aFlags & (NS_CSTRING_CONTAINER_INIT_DEPEND | NS_CSTRING_CONTAINER_INIT_ADOPT)) { uint32_t flags; if (aFlags & NS_CSTRING_CONTAINER_INIT_SUBSTRING)
--- a/xpcom/build/nsXPComInit.cpp +++ b/xpcom/build/nsXPComInit.cpp @@ -214,32 +214,30 @@ NS_GENERIC_FACTORY_CONSTRUCTOR(nsIOUtil) NS_GENERIC_FACTORY_CONSTRUCTOR(nsSecurityConsoleMessage) static nsresult nsThreadManagerGetSingleton(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr) { NS_ASSERTION(aInstancePtr, "null outptr"); - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_TRUE(!outer, NS_ERROR_NO_AGGREGATION); return nsThreadManager::get()->QueryInterface(aIID, aInstancePtr); } NS_GENERIC_FACTORY_CONSTRUCTOR(nsThreadPool) static nsresult nsXPTIInterfaceInfoManagerGetSingleton(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr) { NS_ASSERTION(aInstancePtr, "null outptr"); - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_TRUE(!outer, NS_ERROR_NO_AGGREGATION); nsCOMPtr<nsIInterfaceInfoManager> iim (XPTInterfaceInfoManager::GetSingleton()); if (!iim) return NS_ERROR_FAILURE; return iim->QueryInterface(aIID, aInstancePtr); } @@ -310,26 +308,26 @@ const mozilla::Module::ContractIDEntry k const mozilla::Module kXPCOMModule = { mozilla::Module::kVersion, kXPCOMCIDEntries, kXPCOMContracts }; // gDebug will be freed during shutdown. static nsIDebug* gDebug = nullptr; EXPORT_XPCOM_API(nsresult) NS_GetDebug(nsIDebug** result) { - return nsDebugImpl::Create(nullptr, - NS_GET_IID(nsIDebug), + return nsDebugImpl::Create(nullptr, + NS_GET_IID(nsIDebug), (void**) result); } EXPORT_XPCOM_API(nsresult) NS_GetTraceRefcnt(nsITraceRefcnt** result) { - return nsTraceRefcntImpl::Create(nullptr, - NS_GET_IID(nsITraceRefcnt), + return nsTraceRefcntImpl::Create(nullptr, + NS_GET_IID(nsITraceRefcnt), (void**) result); } EXPORT_XPCOM_API(nsresult) NS_InitXPCOM(nsIServiceManager* *result, nsIFile* binDirectory) { return NS_InitXPCOM2(result, binDirectory, nullptr); @@ -408,48 +406,48 @@ NS_InitXPCOM2(nsIServiceManager* *result NS_LogInit(); // Set up chromium libs NS_ASSERTION(!sExitManager && !sMessageLoop, "Bad logic!"); if (!AtExitManager::AlreadyRegistered()) { sExitManager = new AtExitManager(); + NS_ENSURE_STATE(sExitManager); } if (!MessageLoop::current()) { sMessageLoop = new MessageLoopForUI(MessageLoop::TYPE_MOZILLA_UI); + NS_ENSURE_STATE(sMessageLoop); } if (XRE_GetProcessType() == GeckoProcessType_Default && !BrowserProcessSubThread::GetMessageLoop(BrowserProcessSubThread::IO)) { scoped_ptr<BrowserProcessSubThread> ioThread( new BrowserProcessSubThread(BrowserProcessSubThread::IO)); + NS_ENSURE_TRUE(ioThread.get(), NS_ERROR_OUT_OF_MEMORY); base::Thread::Options options; options.message_loop_type = MessageLoop::TYPE_IO; - if (NS_WARN_IF(!ioThread->StartWithOptions(options))) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(ioThread->StartWithOptions(options), NS_ERROR_FAILURE); sIOThread = ioThread.release(); } // Establish the main thread here. rv = nsThreadManager::get()->Init(); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + if (NS_FAILED(rv)) return rv; // Set up the timer globals/timer thread rv = nsTimerImpl::Startup(); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); #ifndef ANDROID // If the locale hasn't already been setup by our embedder, - // get us out of the "C" locale and into the system + // get us out of the "C" locale and into the system if (strcmp(setlocale(LC_ALL, nullptr), "C") == 0) setlocale(LC_ALL, ""); #endif #if defined(XP_UNIX) || defined(XP_OS2) NS_StartupNativeCharsetUtils(); #endif @@ -490,31 +488,28 @@ NS_InitXPCOM2(nsIServiceManager* *result mozilla::Omnijar::Init(); } if ((sCommandLineWasInitialized = !CommandLine::IsInitialized())) { #ifdef OS_WIN CommandLine::Init(0, nullptr); #else nsCOMPtr<nsIFile> binaryFile; - nsDirectoryService::gService->Get(NS_XPCOM_CURRENT_PROCESS_DIR, - NS_GET_IID(nsIFile), + nsDirectoryService::gService->Get(NS_XPCOM_CURRENT_PROCESS_DIR, + NS_GET_IID(nsIFile), getter_AddRefs(binaryFile)); - if (NS_WARN_IF(!binaryFile)) - return NS_ERROR_FAILURE; - + NS_ENSURE_STATE(binaryFile); + rv = binaryFile->AppendNative(NS_LITERAL_CSTRING("nonexistent-executable")); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; - + NS_ENSURE_SUCCESS(rv, rv); + nsCString binaryPath; rv = binaryFile->GetNativePath(binaryPath); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; - + NS_ENSURE_SUCCESS(rv, rv); + static char const *const argv = { strdup(binaryPath.get()) }; CommandLine::Init(1, &argv); #endif } NS_ASSERTION(nsComponentManagerImpl::gComponentManager == nullptr, "CompMgr not null at init"); // Create the Component/Service Manager @@ -568,17 +563,17 @@ NS_InitXPCOM2(nsIServiceManager* *result // Force layout to spin up so that nsContentUtils is available for cx stack // munging. nsCOMPtr<nsISupports> componentLoader = do_GetService("@mozilla.org/moz/jsloader;1"); mozilla::scache::StartupCache::GetSingleton(); mozilla::AvailableMemoryTracker::Activate(); // Notify observers of xpcom autoregistration start - NS_CreateServicesFromCategory(NS_XPCOM_STARTUP_CATEGORY, + NS_CreateServicesFromCategory(NS_XPCOM_STARTUP_CATEGORY, nullptr, NS_XPCOM_STARTUP_OBSERVER_ID); #ifdef XP_WIN CreateAnonTempFileRemover(); #endif // The memory reporter manager is up and running -- register a reporter for // ICU's memory usage. @@ -626,31 +621,28 @@ NS_ShutdownXPCOM(nsIServiceManager* serv namespace mozilla { nsresult ShutdownXPCOM(nsIServiceManager* servMgr) { // Make sure the hang monitor is enabled for shutdown. HangMonitor::NotifyActivity(); - if (!NS_IsMainThread()) { - NS_RUNTIMEABORT("Shutdown on wrong thread"); - } + NS_ENSURE_STATE(NS_IsMainThread()); nsresult rv; nsCOMPtr<nsISimpleEnumerator> moduleLoaders; // Notify observers of xpcom shutting down { // Block it so that the COMPtr will get deleted before we hit // servicemanager shutdown nsCOMPtr<nsIThread> thread = do_GetCurrentThread(); - if (NS_WARN_IF(!thread)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(thread); nsRefPtr<nsObserverService> observerService; CallGetService("@mozilla.org/observer-service;1", (nsObserverService**) getter_AddRefs(observerService)); if (observerService) { (void) observerService->
--- a/xpcom/build/perfprobe.cpp +++ b/xpcom/build/perfprobe.cpp @@ -208,18 +208,17 @@ nsresult ProbeManager::StartSession(nsTA /*MofImagePath: Must be nullptr, says MSDN*/, nullptr /*MofResourceName:Must be nullptr, says MSDN*/, &mRegistrationHandle /*RegistrationHandle: Handler. used only for unregistration*/ ); delete[] probes; - if (NS_WARN_IF(result != ERROR_SUCCESS)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_TRUE(result == ERROR_SUCCESS, NS_ERROR_UNEXPECTED); return NS_OK; } nsresult ProbeManager::StopSession() { LOG(("Probes: Stopping measures")); if (mSessionHandle != 0) { ULONG result = UnregisterTraceGuids(mSessionHandle);
--- a/xpcom/components/nsCategoryManager.cpp +++ b/xpcom/components/nsCategoryManager.cpp @@ -294,18 +294,17 @@ CategoryNode::DeleteLeaf(const char* aEn // we can just remove the entire hash entry without introspection mTable.RemoveEntry(aEntryName); } NS_METHOD CategoryNode::Enumerate(nsISimpleEnumerator **_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); MutexAutoLock lock(mLock); EntryEnumerator* enumObj = EntryEnumerator::Create(mTable); if (!enumObj) return NS_ERROR_OUT_OF_MEMORY; *_retval = enumObj; @@ -589,20 +588,19 @@ nsCategoryManager::NotifyObservers( cons NS_DispatchToMainThread(r); } NS_IMETHODIMP nsCategoryManager::GetCategoryEntry( const char *aCategoryName, const char *aEntryName, char **_retval ) { - if (NS_WARN_IF(!aCategoryName) || - NS_WARN_IF(!aEntryName) || - NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG;; + NS_ENSURE_ARG_POINTER(aCategoryName); + NS_ENSURE_ARG_POINTER(aEntryName); + NS_ENSURE_ARG_POINTER(_retval); nsresult status = NS_ERROR_NOT_AVAILABLE; CategoryNode* category; { MutexAutoLock lock(mLock); category = get_category(aCategoryName); } @@ -684,19 +682,18 @@ nsCategoryManager::AddCategoryEntry(cons } } NS_IMETHODIMP nsCategoryManager::DeleteCategoryEntry( const char *aCategoryName, const char *aEntryName, bool aDontPersist) { - if (NS_WARN_IF(!aCategoryName) || - NS_WARN_IF(!aEntryName)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aCategoryName); + NS_ENSURE_ARG_POINTER(aEntryName); /* Note: no errors are reported since failure to delete probably won't hurt you, and returning errors seriously inconveniences JS clients */ CategoryNode* category; @@ -713,18 +710,17 @@ nsCategoryManager::DeleteCategoryEntry( } return NS_OK; } NS_IMETHODIMP nsCategoryManager::DeleteCategory( const char *aCategoryName ) { - if (NS_WARN_IF(!aCategoryName)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aCategoryName); // the categories are arena-allocated, so we don't // actually delete them. We just remove all of the // leaf nodes. CategoryNode* category; { MutexAutoLock lock(mLock); @@ -739,19 +735,18 @@ nsCategoryManager::DeleteCategory( const return NS_OK; } NS_IMETHODIMP nsCategoryManager::EnumerateCategory( const char *aCategoryName, nsISimpleEnumerator **_retval ) { - if (NS_WARN_IF(!aCategoryName) || - NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aCategoryName); + NS_ENSURE_ARG_POINTER(_retval); CategoryNode* category; { MutexAutoLock lock(mLock); category = get_category(aCategoryName); } if (!category) { @@ -759,18 +754,17 @@ nsCategoryManager::EnumerateCategory( co } return category->Enumerate(_retval); } NS_IMETHODIMP nsCategoryManager::EnumerateCategories(nsISimpleEnumerator **_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); MutexAutoLock lock(mLock); CategoryEnumerator* enumObj = CategoryEnumerator::Create(mTable); if (!enumObj) return NS_ERROR_OUT_OF_MEMORY; *_retval = enumObj;
--- a/xpcom/components/nsComponentManager.cpp +++ b/xpcom/components/nsComponentManager.cpp @@ -927,19 +927,18 @@ nsComponentManagerImpl::GetClassObject(c } NS_IMETHODIMP nsComponentManagerImpl::GetClassObjectByContractID(const char *contractID, const nsIID &aIID, void **aResult) { - if (NS_WARN_IF(!aResult) || - NS_WARN_IF(!contractID)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aResult); + NS_ENSURE_ARG_POINTER(contractID); nsresult rv; #ifdef PR_LOGGING if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_DEBUG)) { PR_LogPrint("nsComponentManager: GetClassObject(%s)", contractID); @@ -1048,18 +1047,17 @@ nsComponentManagerImpl::CreateInstance(c * CreateInstance() with classid and iid. */ NS_IMETHODIMP nsComponentManagerImpl::CreateInstanceByContractID(const char *aContractID, nsISupports *aDelegate, const nsIID &aIID, void **aResult) { - if (NS_WARN_IF(!aContractID)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aContractID); // test this first, since there's no point in creating a component during // shutdown -- whether it's available or not would depend on the order it // occurs in the list if (gXPCOMShuttingDown) { // When processing shutdown, don't process new GetService() requests #ifdef SHOW_DENIED_ON_SHUTDOWN nsXPIDLCString iid; @@ -1604,19 +1602,17 @@ nsComponentManagerImpl::IsCIDRegistered( *_retval = (nullptr != GetFactoryEntry(aClass)); return NS_OK; } NS_IMETHODIMP nsComponentManagerImpl::IsContractIDRegistered(const char *aClass, bool *_retval) { - if (NS_WARN_IF(!aClass)) - return NS_ERROR_INVALID_ARG; - + NS_ENSURE_ARG_POINTER(aClass); nsFactoryEntry *entry = GetFactoryEntry(aClass, strlen(aClass)); if (entry) *_retval = true; else *_retval = false; return NS_OK; }
--- a/xpcom/ds/nsHashPropertyBag.cpp +++ b/xpcom/ds/nsHashPropertyBag.cpp @@ -59,18 +59,17 @@ nsHashPropertyBag::GetProperty(const nsA return NS_ERROR_FAILURE; return NS_OK; } NS_IMETHODIMP nsHashPropertyBag::SetProperty(const nsAString& name, nsIVariant *value) { - if (NS_WARN_IF(!value)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(value); mPropertyHash.Put(name, value); return NS_OK; } NS_IMETHODIMP nsHashPropertyBag::DeleteProperty(const nsAString& name)
--- a/xpcom/ds/nsINIParserImpl.cpp +++ b/xpcom/ds/nsINIParserImpl.cpp @@ -46,18 +46,17 @@ nsINIParserFactory::CreateINIParser(nsIF return rv; } NS_IMETHODIMP nsINIParserFactory::CreateInstance(nsISupports* aOuter, REFNSIID aIID, void **aResult) { - if (NS_WARN_IF(aOuter)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_NO_AGGREGATION(aOuter); // We are our own singleton. return QueryInterface(aIID, aResult); } NS_IMETHODIMP nsINIParserFactory::LockFactory(bool aLock) {
--- a/xpcom/ds/nsObserverService.cpp +++ b/xpcom/ds/nsObserverService.cpp @@ -145,55 +145,51 @@ ObserverServiceReporter::CollectReports( nsIMemoryReporter::UNITS_COUNT, suspect.referentCount, NS_LITERAL_CSTRING("A topic with a suspiciously large number of " "referents. This may be symptomatic of a leak " "if the number of referents is high with " "respect to the number of windows."), aClosure); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } rv = cb->Callback(/* process */ EmptyCString(), NS_LITERAL_CSTRING("observer-service/referent/strong"), nsIMemoryReporter::KIND_OTHER, nsIMemoryReporter::UNITS_COUNT, referentCount.numStrong, NS_LITERAL_CSTRING("The number of strong references held by the " "observer service."), aClosure); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = cb->Callback(/* process */ EmptyCString(), NS_LITERAL_CSTRING("observer-service/referent/weak/alive"), nsIMemoryReporter::KIND_OTHER, nsIMemoryReporter::UNITS_COUNT, referentCount.numWeakAlive, NS_LITERAL_CSTRING("The number of weak references held by the " "observer service that are still alive."), aClosure); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = cb->Callback(/* process */ EmptyCString(), NS_LITERAL_CSTRING("observer-service/referent/weak/dead"), nsIMemoryReporter::KIND_OTHER, nsIMemoryReporter::UNITS_COUNT, referentCount.numWeakDead, NS_LITERAL_CSTRING("The number of weak references held by the " "observer service that are dead."), aClosure); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } } // namespace mozilla using namespace mozilla; @@ -265,18 +261,17 @@ nsObserverService::Create(nsISupports* o NS_IMETHODIMP nsObserverService::AddObserver(nsIObserver* anObserver, const char* aTopic, bool ownsWeak) { LOG(("nsObserverService::AddObserver(%p: %s)", (void*) anObserver, aTopic)); NS_ENSURE_VALIDCALL - if (NS_WARN_IF(!anObserver) || NS_WARN_IF(!aTopic)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(anObserver && aTopic); if (mozilla::net::IsNeckoChild() && !strncmp(aTopic, "http-on-", 8)) { return NS_ERROR_NOT_IMPLEMENTED; } nsObserverList *observerList = mObserverTopicTable.PutEntry(aTopic); if (!observerList) return NS_ERROR_OUT_OF_MEMORY; @@ -285,54 +280,51 @@ nsObserverService::AddObserver(nsIObserv } NS_IMETHODIMP nsObserverService::RemoveObserver(nsIObserver* anObserver, const char* aTopic) { LOG(("nsObserverService::RemoveObserver(%p: %s)", (void*) anObserver, aTopic)); NS_ENSURE_VALIDCALL - if (NS_WARN_IF(!anObserver) || NS_WARN_IF(!aTopic)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(anObserver && aTopic); nsObserverList *observerList = mObserverTopicTable.GetEntry(aTopic); if (!observerList) return NS_ERROR_FAILURE; /* This death grip is to protect against stupid consumers who call RemoveObserver from their Destructor, see bug 485834/bug 325392. */ nsCOMPtr<nsIObserver> kungFuDeathGrip(anObserver); return observerList->RemoveObserver(anObserver); } NS_IMETHODIMP nsObserverService::EnumerateObservers(const char* aTopic, nsISimpleEnumerator** anEnumerator) { NS_ENSURE_VALIDCALL - if (NS_WARN_IF(!anEnumerator) || NS_WARN_IF(!aTopic)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aTopic && anEnumerator); nsObserverList *observerList = mObserverTopicTable.GetEntry(aTopic); if (!observerList) return NS_NewEmptyEnumerator(anEnumerator); return observerList->GetObserverList(anEnumerator); } // Enumerate observers of aTopic and call Observe on each. NS_IMETHODIMP nsObserverService::NotifyObservers(nsISupports *aSubject, const char *aTopic, const PRUnichar *someData) { LOG(("nsObserverService::NotifyObservers(%s)", aTopic)); NS_ENSURE_VALIDCALL - if (NS_WARN_IF(!aTopic)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aTopic); nsObserverList *observerList = mObserverTopicTable.GetEntry(aTopic); if (observerList) observerList->NotifyObservers(aSubject, aTopic, someData); #ifdef NOTIFY_GLOBAL_OBSERVERS observerList = mObserverTopicTable.GetEntry("*"); if (observerList)
--- a/xpcom/ds/nsProperties.cpp +++ b/xpcom/ds/nsProperties.cpp @@ -10,54 +10,50 @@ NS_IMPL_AGGREGATED(nsProperties) NS_INTERFACE_MAP_BEGIN_AGGREGATED(nsProperties) NS_INTERFACE_MAP_ENTRY(nsIProperties) NS_INTERFACE_MAP_END NS_IMETHODIMP nsProperties::Get(const char* prop, const nsIID & uuid, void* *result) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(prop); nsCOMPtr<nsISupports> value; if (!nsProperties_HashBase::Get(prop, getter_AddRefs(value))) { return NS_ERROR_FAILURE; } return (value) ? value->QueryInterface(uuid, result) : NS_ERROR_NO_INTERFACE; } NS_IMETHODIMP nsProperties::Set(const char* prop, nsISupports* value) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(prop); Put(prop, value); return NS_OK; } NS_IMETHODIMP nsProperties::Undefine(const char* prop) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(prop); nsCOMPtr<nsISupports> value; if (!nsProperties_HashBase::Get(prop, getter_AddRefs(value))) return NS_ERROR_FAILURE; Remove(prop); return NS_OK; } NS_IMETHODIMP nsProperties::Has(const char* prop, bool *result) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(prop); nsCOMPtr<nsISupports> value; *result = nsProperties_HashBase::Get(prop, getter_AddRefs(value)); return NS_OK; } struct GetKeysEnumData @@ -81,21 +77,22 @@ GetKeysEnumerate(const char *key, nsISup gkedp->next++; return PL_DHASH_NEXT; } NS_IMETHODIMP nsProperties::GetKeys(uint32_t *count, char ***keys) { - if (NS_WARN_IF(!count) || NS_WARN_IF(!keys)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(count); + NS_ENSURE_ARG(keys); uint32_t n = Count(); char ** k = (char **) nsMemory::Alloc(n * sizeof(char *)); + NS_ENSURE_TRUE(k, NS_ERROR_OUT_OF_MEMORY); GetKeysEnumData gked; gked.keys = k; gked.next = 0; gked.res = NS_OK; EnumerateRead(GetKeysEnumerate, &gked);
--- a/xpcom/ds/nsStringEnumerator.cpp +++ b/xpcom/ds/nsStringEnumerator.cpp @@ -79,16 +79,17 @@ private: NS_IMPL_ISUPPORTS3(nsStringEnumerator, nsIStringEnumerator, nsIUTF8StringEnumerator, nsISimpleEnumerator) NS_IMETHODIMP nsStringEnumerator::HasMore(bool* aResult) { + NS_ENSURE_ARG_POINTER(aResult); *aResult = mIndex < Count(); return NS_OK; } NS_IMETHODIMP nsStringEnumerator::HasMoreElements(bool* aResult) { return HasMore(aResult); @@ -113,32 +114,30 @@ nsStringEnumerator::GetNext(nsISupports* } NS_ADDREF(*aResult); return NS_OK; } NS_IMETHODIMP nsStringEnumerator::GetNext(nsAString& aResult) { - if (NS_WARN_IF(mIndex >= Count())) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_TRUE(mIndex < Count(), NS_ERROR_UNEXPECTED); if (mIsUnicode) aResult = mArray->ElementAt(mIndex++); else CopyUTF8toUTF16(mCArray->ElementAt(mIndex++), aResult); return NS_OK; } NS_IMETHODIMP nsStringEnumerator::GetNext(nsACString& aResult) { - if (NS_WARN_IF(mIndex >= Count())) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_TRUE(mIndex < Count(), NS_ERROR_UNEXPECTED); if (mIsUnicode) CopyUTF16toUTF8(mArray->ElementAt(mIndex++), aResult); else aResult = mCArray->ElementAt(mIndex++); return NS_OK; } @@ -156,72 +155,72 @@ StringEnumeratorTail(T** aResult) // // constructors // nsresult NS_NewStringEnumerator(nsIStringEnumerator** aResult, const nsTArray<nsString>* aArray, nsISupports* aOwner) { - if (NS_WARN_IF(!aResult) || NS_WARN_IF(!aArray)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aResult); + NS_ENSURE_ARG_POINTER(aArray); *aResult = new nsStringEnumerator(aArray, aOwner); return StringEnumeratorTail(aResult); } nsresult NS_NewUTF8StringEnumerator(nsIUTF8StringEnumerator** aResult, const nsTArray<nsCString>* aArray, nsISupports* aOwner) { - if (NS_WARN_IF(!aResult) || NS_WARN_IF(!aArray)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aResult); + NS_ENSURE_ARG_POINTER(aArray); *aResult = new nsStringEnumerator(aArray, aOwner); return StringEnumeratorTail(aResult); } nsresult NS_NewAdoptingStringEnumerator(nsIStringEnumerator** aResult, nsTArray<nsString>* aArray) { - if (NS_WARN_IF(!aResult) || NS_WARN_IF(!aArray)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aResult); + NS_ENSURE_ARG_POINTER(aArray); *aResult = new nsStringEnumerator(aArray, true); return StringEnumeratorTail(aResult); } nsresult NS_NewAdoptingUTF8StringEnumerator(nsIUTF8StringEnumerator** aResult, nsTArray<nsCString>* aArray) { - if (NS_WARN_IF(!aResult) || NS_WARN_IF(!aArray)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aResult); + NS_ENSURE_ARG_POINTER(aArray); *aResult = new nsStringEnumerator(aArray, true); return StringEnumeratorTail(aResult); } // const ones internally just forward to the non-const equivalents nsresult NS_NewStringEnumerator(nsIStringEnumerator** aResult, const nsTArray<nsString>* aArray) { - if (NS_WARN_IF(!aResult) || NS_WARN_IF(!aArray)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aResult); + NS_ENSURE_ARG_POINTER(aArray); *aResult = new nsStringEnumerator(aArray, false); return StringEnumeratorTail(aResult); } nsresult NS_NewUTF8StringEnumerator(nsIUTF8StringEnumerator** aResult, const nsTArray<nsCString>* aArray) { - if (NS_WARN_IF(!aResult) || NS_WARN_IF(!aArray)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aResult); + NS_ENSURE_ARG_POINTER(aArray); *aResult = new nsStringEnumerator(aArray, false); return StringEnumeratorTail(aResult); }
--- a/xpcom/ds/nsSupportsArray.cpp +++ b/xpcom/ds/nsSupportsArray.cpp @@ -580,18 +580,17 @@ nsSupportsArray::Enumerate(nsIEnumerator return NS_OK; } NS_IMETHODIMP nsSupportsArray::Clone(nsISupportsArray** aResult) { nsCOMPtr<nsISupportsArray> newArray; nsresult rv = NS_NewISupportsArray(getter_AddRefs(newArray)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); uint32_t count = 0; Count(&count); for (uint32_t i = 0; i < count; i++) { if (!newArray->InsertElementAt(mArray[i], i)) { return NS_ERROR_OUT_OF_MEMORY; } }
--- a/xpcom/ds/nsSupportsPrimitives.cpp +++ b/xpcom/ds/nsSupportsPrimitives.cpp @@ -805,35 +805,33 @@ NS_IMPL_ISUPPORTS2(nsSupportsDependentCS nsSupportsDependentCString::nsSupportsDependentCString(const char* aStr) : mData(aStr) { } NS_IMETHODIMP nsSupportsDependentCString::GetType(uint16_t *aType) { - if (NS_WARN_IF(!aType)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aType); *aType = TYPE_CSTRING; return NS_OK; } NS_IMETHODIMP nsSupportsDependentCString::GetData(nsACString& aData) { aData = mData; return NS_OK; } NS_IMETHODIMP nsSupportsDependentCString::ToString(char **_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); *_retval = ToNewCString(mData); if (!*_retval) return NS_ERROR_OUT_OF_MEMORY; return NS_OK; }
--- a/xpcom/ds/nsWindowsRegKey.cpp +++ b/xpcom/ds/nsWindowsRegKey.cpp @@ -98,68 +98,63 @@ nsWindowsRegKey::Create(uint32_t rootKey return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::OpenChild(const nsAString &path, uint32_t mode, nsIWindowsRegKey **result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); nsCOMPtr<nsIWindowsRegKey> child = new nsWindowsRegKey(); nsresult rv = child->Open((uintptr_t) mKey, path, mode); if (NS_FAILED(rv)) return rv; child.swap(*result); return NS_OK; } NS_IMETHODIMP nsWindowsRegKey::CreateChild(const nsAString &path, uint32_t mode, nsIWindowsRegKey **result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); nsCOMPtr<nsIWindowsRegKey> child = new nsWindowsRegKey(); nsresult rv = child->Create((uintptr_t) mKey, path, mode); if (NS_FAILED(rv)) return rv; child.swap(*result); return NS_OK; } NS_IMETHODIMP nsWindowsRegKey::GetChildCount(uint32_t *result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); DWORD numSubKeys; LONG rv = RegQueryInfoKeyW(mKey, nullptr, nullptr, nullptr, &numSubKeys, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr); - if (rv != ERROR_SUCCESS) - return NS_ERROR_FAILURE; + NS_ENSURE_STATE(rv == ERROR_SUCCESS); *result = numSubKeys; return NS_OK; } NS_IMETHODIMP nsWindowsRegKey::GetChildName(uint32_t index, nsAString &result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); FILETIME lastWritten; PRUnichar nameBuf[MAX_KEY_NAME_LEN + 1]; DWORD nameLen = sizeof(nameBuf) / sizeof(nameBuf[0]); LONG rv = RegEnumKeyExW(mKey, index, nameBuf, &nameLen, nullptr, nullptr, nullptr, &lastWritten); @@ -169,18 +164,17 @@ nsWindowsRegKey::GetChildName(uint32_t i result.Assign(nameBuf, nameLen); return NS_OK; } NS_IMETHODIMP nsWindowsRegKey::HasChild(const nsAString &name, bool *result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); // Check for the existence of a child key by opening the key with minimal // rights. Perhaps there is a more efficient way to do this? HKEY key; LONG rv = RegOpenKeyExW(mKey, PromiseFlatString(name).get(), 0, STANDARD_RIGHTS_READ, &key); @@ -188,35 +182,32 @@ nsWindowsRegKey::HasChild(const nsAStrin RegCloseKey(key); return NS_OK; } NS_IMETHODIMP nsWindowsRegKey::GetValueCount(uint32_t *result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); DWORD numValues; LONG rv = RegQueryInfoKeyW(mKey, nullptr, nullptr, nullptr, nullptr, nullptr, nullptr, &numValues, nullptr, nullptr, nullptr, nullptr); - if (rv != ERROR_SUCCESS) - return NS_ERROR_FAILURE; + NS_ENSURE_STATE(rv == ERROR_SUCCESS); *result = numValues; return NS_OK; } NS_IMETHODIMP nsWindowsRegKey::GetValueName(uint32_t index, nsAString &result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); PRUnichar nameBuf[MAX_VALUE_NAME_LEN]; DWORD nameLen = sizeof(nameBuf) / sizeof(nameBuf[0]); LONG rv = RegEnumValueW(mKey, index, nameBuf, &nameLen, nullptr, nullptr, nullptr, nullptr); if (rv != ERROR_SUCCESS) return NS_ERROR_NOT_AVAILABLE; // XXX what's the best error code here? @@ -224,82 +215,77 @@ nsWindowsRegKey::GetValueName(uint32_t i result.Assign(nameBuf, nameLen); return NS_OK; } NS_IMETHODIMP nsWindowsRegKey::HasValue(const nsAString &name, bool *result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); LONG rv = RegQueryValueExW(mKey, PromiseFlatString(name).get(), 0, nullptr, nullptr, nullptr); *result = (rv == ERROR_SUCCESS); return NS_OK; } NS_IMETHODIMP nsWindowsRegKey::RemoveChild(const nsAString &name) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); LONG rv = RegDeleteKeyW(mKey, PromiseFlatString(name).get()); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::RemoveValue(const nsAString &name) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); LONG rv = RegDeleteValueW(mKey, PromiseFlatString(name).get()); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::GetValueType(const nsAString &name, uint32_t *result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); LONG rv = RegQueryValueExW(mKey, PromiseFlatString(name).get(), 0, (LPDWORD) result, nullptr, nullptr); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::ReadStringValue(const nsAString &name, nsAString &result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); DWORD type, size; const nsString &flatName = PromiseFlatString(name); LONG rv = RegQueryValueExW(mKey, flatName.get(), 0, &type, nullptr, &size); if (rv != ERROR_SUCCESS) return NS_ERROR_FAILURE; // This must be a string type in order to fetch the value as a string. // We're being a bit forgiving here by allowing types other than REG_SZ. - if (type != REG_SZ && type == REG_EXPAND_SZ && type == REG_MULTI_SZ) - return NS_ERROR_FAILURE; + NS_ENSURE_STATE(type == REG_SZ || + type == REG_EXPAND_SZ || + type == REG_MULTI_SZ); // The buffer size must be a multiple of 2. - if (size % 2 != 0) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(size % 2 == 0); if (size == 0) { result.Truncate(); return NS_OK; } // |size| may or may not include the terminating null character. DWORD resultLen = size / 2; @@ -346,44 +332,41 @@ nsWindowsRegKey::ReadStringValue(const n } return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::ReadIntValue(const nsAString &name, uint32_t *result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); DWORD size = sizeof(*result); LONG rv = RegQueryValueExW(mKey, PromiseFlatString(name).get(), 0, nullptr, (LPBYTE) result, &size); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::ReadInt64Value(const nsAString &name, uint64_t *result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); DWORD size = sizeof(*result); LONG rv = RegQueryValueExW(mKey, PromiseFlatString(name).get(), 0, nullptr, (LPBYTE) result, &size); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::ReadBinaryValue(const nsAString &name, nsACString &result) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); DWORD size; LONG rv = RegQueryValueExW(mKey, PromiseFlatString(name).get(), 0, nullptr, nullptr, &size); if (rv != ERROR_SUCCESS) return NS_ERROR_FAILURE; @@ -397,71 +380,66 @@ nsWindowsRegKey::ReadBinaryValue(const n (LPBYTE) begin.get(), &size); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::WriteStringValue(const nsAString &name, const nsAString &value) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); // Need to indicate complete size of buffer including null terminator. const nsString &flatValue = PromiseFlatString(value); LONG rv = RegSetValueExW(mKey, PromiseFlatString(name).get(), 0, REG_SZ, (const BYTE *) flatValue.get(), (flatValue.Length() + 1) * sizeof(PRUnichar)); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::WriteIntValue(const nsAString &name, uint32_t value) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); LONG rv = RegSetValueExW(mKey, PromiseFlatString(name).get(), 0, REG_DWORD, (const BYTE *) &value, sizeof(value)); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::WriteInt64Value(const nsAString &name, uint64_t value) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); LONG rv = RegSetValueExW(mKey, PromiseFlatString(name).get(), 0, REG_QWORD, (const BYTE *) &value, sizeof(value)); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::WriteBinaryValue(const nsAString &name, const nsACString &value) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); const nsCString &flatValue = PromiseFlatCString(value); LONG rv = RegSetValueExW(mKey, PromiseFlatString(name).get(), 0, REG_BINARY, (const BYTE *) flatValue.get(), flatValue.Length()); return (rv == ERROR_SUCCESS) ? NS_OK : NS_ERROR_FAILURE; } NS_IMETHODIMP nsWindowsRegKey::StartWatching(bool recurse) { - if (NS_WARN_IF(!mKey)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mKey, NS_ERROR_NOT_INITIALIZED); if (mWatchEvent) return NS_OK; mWatchEvent = CreateEvent(nullptr, TRUE, FALSE, nullptr); if (!mWatchEvent) return NS_ERROR_OUT_OF_MEMORY;
--- a/xpcom/glue/nsArrayEnumerator.cpp +++ b/xpcom/glue/nsArrayEnumerator.cpp @@ -175,16 +175,17 @@ nsCOMArrayEnumerator::operator new (size // create enough space such that mValueArray points to a large // enough value. Note that the initial value of size gives us // space for mValueArray[0], so we must subtract size += (aArray.Count() - 1) * sizeof(aArray[0]); // do the actual allocation nsCOMArrayEnumerator * result = static_cast<nsCOMArrayEnumerator*>(::operator new(size)); + NS_ENSURE_TRUE(result, nullptr); // now need to copy over the values, and addref each one // now this might seem like a lot of work, but we're actually just // doing all our AddRef's ahead of time since GetNext() doesn't // need to AddRef() on the way out uint32_t i; uint32_t max = result->mArraySize = aArray.Count(); for (i = 0; i<max; i++) {
--- a/xpcom/glue/nsCOMArray.cpp +++ b/xpcom/glue/nsCOMArray.cpp @@ -52,18 +52,17 @@ nsCOMArray_base::IndexOf(nsISupports* aO { return mArray.IndexOf(aObject, aStartIndex); } int32_t nsCOMArray_base::IndexOfObject(nsISupports* aObject) const { nsCOMPtr<nsISupports> supports = do_QueryInterface(aObject); - if (NS_WARN_IF(!supports)) - return -1; + NS_ENSURE_TRUE(supports, -1); uint32_t i, count; int32_t retval = -1; count = mArray.Length(); for (i = 0; i < count; ++i) { nsCOMPtr<nsISupports> arrayItem = do_QueryInterface(mArray[i]); if (arrayItem == supports) { retval = i;
--- a/xpcom/glue/nsComponentManagerUtils.cpp +++ b/xpcom/glue/nsComponentManagerUtils.cpp @@ -41,28 +41,26 @@ CallGetService(const char *aContractID, #else #include "nsComponentManager.h" nsresult CallGetService(const nsCID &aCID, const nsIID &aIID, void **aResult) { nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager; - if (NS_WARN_IF(!compMgr)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(compMgr, NS_ERROR_NOT_INITIALIZED); return compMgr->nsComponentManagerImpl::GetService(aCID, aIID, aResult); } nsresult CallGetService(const char *aContractID, const nsIID &aIID, void **aResult) { nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager; - if (NS_WARN_IF(!compMgr)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(compMgr, NS_ERROR_NOT_INITIALIZED); return compMgr-> nsComponentManagerImpl::GetServiceByContractID(aContractID, aIID, aResult); } #endif @@ -116,54 +114,50 @@ CallGetClassObject(const char *aContract #include "nsComponentManager.h" nsresult CallCreateInstance(const nsCID &aCID, nsISupports *aDelegate, const nsIID &aIID, void **aResult) { nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager; - if (NS_WARN_IF(!compMgr)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(compMgr, NS_ERROR_NOT_INITIALIZED); return compMgr-> nsComponentManagerImpl::CreateInstance(aCID, aDelegate, aIID, aResult); } nsresult CallCreateInstance(const char *aContractID, nsISupports *aDelegate, const nsIID &aIID, void **aResult) { nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager; - if (NS_WARN_IF(!compMgr)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(compMgr, NS_ERROR_NOT_INITIALIZED); return compMgr-> nsComponentManagerImpl::CreateInstanceByContractID(aContractID, aDelegate, aIID, aResult); } nsresult CallGetClassObject(const nsCID &aCID, const nsIID &aIID, void **aResult) { nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager; - if (NS_WARN_IF(!compMgr)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(compMgr, NS_ERROR_NOT_INITIALIZED); return compMgr-> nsComponentManagerImpl::GetClassObject(aCID, aIID, aResult); } nsresult CallGetClassObject(const char *aContractID, const nsIID &aIID, void **aResult) { nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager; - if (NS_WARN_IF(!compMgr)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(compMgr, NS_ERROR_NOT_INITIALIZED); return compMgr-> nsComponentManagerImpl::GetClassObjectByContractID(aContractID, aIID, aResult); } #endif
--- a/xpcom/glue/nsDebug.h +++ b/xpcom/glue/nsDebug.h @@ -7,55 +7,27 @@ #define nsDebug_h___ #ifndef nscore_h___ #include "nscore.h" #endif #ifndef nsError_h__ #include "nsError.h" -#endif +#endif #include "nsXPCOM.h" #include "mozilla/Assertions.h" #include "mozilla/Likely.h" #ifdef DEBUG #include "prprf.h" #endif -/** - * Warn if the given condition is true. The condition is evaluated in both - * release and debug builds, and the result is an expression which can be - * used in subsequent expressions, such as: - * - * if (NS_WARN_IF(NS_FAILED(rv)) - * return rv; - * - * This explicit warning and return is preferred to the NS_ENSURE_* macros - * which hide the warning and the return control flow. - * - * @note This is C++-only - */ -#ifdef __cplusplus #ifdef DEBUG -inline bool NS_warn_if_impl(bool condition, const char* expr, const char* file, - int32_t line) -{ - if (MOZ_UNLIKELY(condition)) { - NS_DebugBreak(NS_DEBUG_WARNING, nullptr, expr, file, line); - } - return condition; -} -#define NS_WARN_IF(condition) \ - NS_warn_if_impl(condition, #condition, __FILE__, __LINE__) -#else -#define NS_WARN_IF(condition) (bool)(condition) -#endif -#endif /** * Abort the execution of the program if the expression evaluates to * false. * * There is no status value returned from the macro. * * Note that the non-debug version of this macro does <b>not</b> @@ -63,134 +35,128 @@ inline bool NS_warn_if_impl(bool conditi * as arguments to the macro will yield improper execution in a * non-debug build. For example: * * NS_ABORT_IF_FALSE(0 == foo++, "yikes foo should be zero"); * * Note also that the non-debug version of this macro does <b>not</b> * evaluate the message argument. */ -#ifdef DEBUG #define NS_ABORT_IF_FALSE(_expr, _msg) \ do { \ if (!(_expr)) { \ NS_DebugBreak(NS_DEBUG_ABORT, _msg, #_expr, __FILE__, __LINE__); \ } \ } while(0) -#else -#define NS_ABORT_IF_FALSE(_expr, _msg) do { /* nothing */ } while(0) -#endif /** * Warn if a given condition is false. * * Program execution continues past the usage of this macro. * * Note also that the non-debug version of this macro does <b>not</b> * evaluate the message argument. */ -#ifdef DEBUG #define NS_WARN_IF_FALSE(_expr,_msg) \ do { \ if (!(_expr)) { \ NS_DebugBreak(NS_DEBUG_WARNING, _msg, #_expr, __FILE__, __LINE__); \ } \ } while(0) -#else -#define NS_WARN_IF_FALSE(_expr, _msg) do { /* nothing */ } while(0) -#endif +/** + * Test a precondition for truth. If the expression is not true then + * trigger a program failure. + */ +#define NS_PRECONDITION(expr, str) \ + do { \ + if (!(expr)) { \ + NS_DebugBreak(NS_DEBUG_ASSERTION, str, #expr, __FILE__, __LINE__); \ + } \ + } while(0) /** * Test an assertion for truth. If the expression is not true then * trigger a program failure. - * - * Note that the non-debug version of this macro does <b>not</b> - * evaluate the message argument. */ -#ifdef DEBUG #define NS_ASSERTION(expr, str) \ do { \ if (!(expr)) { \ NS_DebugBreak(NS_DEBUG_ASSERTION, str, #expr, __FILE__, __LINE__); \ } \ } while(0) -#else -#define NS_ASSERTION(expr, str) do { /* nothing */ } while(0) -#endif /** - * NS_PRECONDITION/POSTCONDITION are synonyms for NS_ASSERTION. + * Test a post-condition for truth. If the expression is not true then + * trigger a program failure. */ -#define NS_PRECONDITION(expr, str) NS_ASSERTION(expr, str) -#define NS_POSTCONDITION(expr, str) NS_ASSERTION(expr, str) +#define NS_POSTCONDITION(expr, str) \ + do { \ + if (!(expr)) { \ + NS_DebugBreak(NS_DEBUG_ASSERTION, str, #expr, __FILE__, __LINE__); \ + } \ + } while(0) + +/** + * This macros triggers a program failure if executed. It indicates that + * an attempt was made to execute some unimplemented functionality. + */ +#define NS_NOTYETIMPLEMENTED(str) \ + NS_DebugBreak(NS_DEBUG_ASSERTION, str, "NotYetImplemented", __FILE__, __LINE__) /** * This macros triggers a program failure if executed. It indicates that * an attempt was made to execute some unimplemented functionality. */ -#ifdef DEBUG -#define NS_NOTYETIMPLEMENTED(str) \ - NS_DebugBreak(NS_DEBUG_ASSERTION, str, "NotYetImplemented", __FILE__, __LINE__) -#else -#define NS_NOTYETIMPLEMENTED(str) do { /* nothing */ } while(0) -#endif - -/** - * This macros triggers a program failure if executed. It indicates that - * an attempt was made to execute a codepath which should not be reachable. - */ -#ifdef DEBUG #define NS_NOTREACHED(str) \ NS_DebugBreak(NS_DEBUG_ASSERTION, str, "Not Reached", __FILE__, __LINE__) -#else -#define NS_NOTREACHED(str) do { /* nothing */ } while(0) -#endif /** * Log an error message. */ -#ifdef DEBUG #define NS_ERROR(str) \ NS_DebugBreak(NS_DEBUG_ASSERTION, str, "Error", __FILE__, __LINE__) -#else -#define NS_ERROR(str) do { /* nothing */ } while(0) -#endif /** * Log a warning message. */ -#ifdef DEBUG #define NS_WARNING(str) \ NS_DebugBreak(NS_DEBUG_WARNING, str, nullptr, __FILE__, __LINE__) -#else -#define NS_WARNING(str) do { /* nothing */ } while(0) -#endif + +/** + * Trigger an abort + */ +#define NS_ABORT() \ + NS_DebugBreak(NS_DEBUG_ABORT, nullptr, nullptr, __FILE__, __LINE__) /** - * Trigger an debug-only abort. - * - * @see NS_RUNTIMEABORT for release-mode asserts. + * Cause a break */ -#ifdef DEBUG -#define NS_ABORT() \ - NS_DebugBreak(NS_DEBUG_ABORT, nullptr, nullptr, __FILE__, __LINE__) -#else -#define NS_ABORT() do { /* nothing */ } while(0) -#endif +#define NS_BREAK() \ + NS_DebugBreak(NS_DEBUG_BREAK, nullptr, nullptr, __FILE__, __LINE__) + +#else /* DEBUG */ /** - * Trigger a debugger breakpoint, only in debug builds. + * The non-debug version of these macros do not evaluate the + * expression or the message arguments to the macro. */ -#ifdef DEBUG -#define NS_BREAK() \ - NS_DebugBreak(NS_DEBUG_BREAK, nullptr, nullptr, __FILE__, __LINE__) -#else +#define NS_ABORT_IF_FALSE(_expr, _msg) do { /* nothing */ } while(0) +#define NS_WARN_IF_FALSE(_expr, _msg) do { /* nothing */ } while(0) +#define NS_PRECONDITION(expr, str) do { /* nothing */ } while(0) +#define NS_ASSERTION(expr, str) do { /* nothing */ } while(0) +#define NS_POSTCONDITION(expr, str) do { /* nothing */ } while(0) +#define NS_NOTYETIMPLEMENTED(str) do { /* nothing */ } while(0) +#define NS_NOTREACHED(str) do { /* nothing */ } while(0) +#define NS_ERROR(str) do { /* nothing */ } while(0) +#define NS_WARNING(str) do { /* nothing */ } while(0) +#define NS_ABORT() do { /* nothing */ } while(0) #define NS_BREAK() do { /* nothing */ } while(0) -#endif + +#endif /* ! DEBUG */ /****************************************************************************** ** Macros for static assertions. These are used by the sixgill tool. ** When the tool is not running these macros are no-ops. ******************************************************************************/ /* Avoid name collision if included with other headers defining annotations. */ #ifndef HAVE_STATIC_ANNOTATIONS @@ -259,33 +225,32 @@ inline bool NS_warn_if_impl(bool conditi #define NS_PRECONDITION(expr, str) STATIC_ASSERT_RUNTIME(expr) #define NS_ASSERTION(expr, str) STATIC_ASSERT_RUNTIME(expr) #define NS_POSTCONDITION(expr, str) STATIC_ASSERT_RUNTIME(expr) #endif /* XGILL_PLUGIN */ /****************************************************************************** ** Macros for terminating execution when an unrecoverable condition is -** reached. These need to be compiled regardless of the DEBUG flag. +** reached. These need to be compiled regardless of the DEBUG flag. ******************************************************************************/ /** * Terminate execution <i>immediately</i>, and if possible on the current * platform, in such a way that execution can't be continued by other * code (e.g., by intercepting a signal). */ #define NS_RUNTIMEABORT(msg) \ NS_DebugBreak(NS_DEBUG_ABORT, msg, nullptr, __FILE__, __LINE__) -/* Macros for checking the trueness of an expression passed in within an - * interface implementation. These need to be compiled regardless of the - * DEBUG flag. New code should use NS_WARN_IF(condition) instead! - * @status deprecated - */ +/* Macros for checking the trueness of an expression passed in within an + * interface implementation. These need to be compiled regardless of the */ +/* DEBUG flag +******************************************************************************/ #define NS_ENSURE_TRUE(x, ret) \ do { \ if (MOZ_UNLIKELY(!(x))) { \ NS_WARNING("NS_ENSURE_TRUE(" #x ") failed"); \ return ret; \ } \ } while(0) @@ -370,16 +335,19 @@ inline bool NS_warn_if_impl(bool conditi NS_ENSURE_TRUE(((arg) >= min) && ((arg) <= max), NS_ERROR_INVALID_ARG) #define NS_ENSURE_STATE(state) \ NS_ENSURE_TRUE(state, NS_ERROR_UNEXPECTED) #define NS_ENSURE_NO_AGGREGATION(outer) \ NS_ENSURE_FALSE(outer, NS_ERROR_NO_AGGREGATION) +#define NS_ENSURE_PROPER_AGGREGATION(outer, iid) \ + NS_ENSURE_FALSE(outer && !iid.Equals(NS_GET_IID(nsISupports)), NS_ERROR_INVALID_ARG) + /*****************************************************************************/ #ifdef XPCOM_GLUE #define NS_CheckThreadSafe(owningThread, msg) #else #define NS_CheckThreadSafe(owningThread, msg) \ if (MOZ_UNLIKELY(owningThread != PR_GetCurrentThread())) { \ MOZ_CRASH(msg); \
--- a/xpcom/glue/nsINIParser.cpp +++ b/xpcom/glue/nsINIParser.cpp @@ -60,18 +60,17 @@ nsINIParser::Init(nsIFile* aFile) pass FILE* across shared library boundaries, which may be using different CRTs */ AutoFILE fd; #ifdef XP_WIN nsAutoString path; nsresult rv = aFile->GetPath(path); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); fd = _wfopen(path.get(), READ_BINARYMODE); #else nsAutoCString path; aFile->GetNativePath(path); fd = fopen(path.get(), READ_BINARYMODE); #endif
--- a/xpcom/glue/nsMemory.cpp +++ b/xpcom/glue/nsMemory.cpp @@ -14,18 +14,17 @@ //////////////////////////////////////////////////////////////////////////////// // nsMemory static helper routines NS_COM_GLUE nsresult nsMemory::HeapMinimize(bool aImmediate) { nsCOMPtr<nsIMemory> mem; nsresult rv = NS_GetMemoryManager(getter_AddRefs(mem)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return mem->HeapMinimize(aImmediate); } NS_COM_GLUE void* nsMemory::Clone(const void* ptr, size_t size) { void* newPtr = NS_Alloc(size);
--- a/xpcom/glue/nsThreadUtils.cpp +++ b/xpcom/glue/nsThreadUtils.cpp @@ -65,61 +65,56 @@ NS_NewThread(nsIThread **result, nsIRunn nsCOMPtr<nsIThread> thread; #ifdef MOZILLA_INTERNAL_API nsresult rv = nsThreadManager::get()-> nsThreadManager::NewThread(0, stackSize, getter_AddRefs(thread)); #else nsresult rv; nsCOMPtr<nsIThreadManager> mgr = do_GetService(NS_THREADMANAGER_CONTRACTID, &rv); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = mgr->NewThread(0, stackSize, getter_AddRefs(thread)); #endif - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); if (event) { rv = thread->Dispatch(event, NS_DISPATCH_NORMAL); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } *result = nullptr; thread.swap(*result); return NS_OK; } NS_METHOD NS_GetCurrentThread(nsIThread **result) { #ifdef MOZILLA_INTERNAL_API return nsThreadManager::get()->nsThreadManager::GetCurrentThread(result); #else nsresult rv; nsCOMPtr<nsIThreadManager> mgr = do_GetService(NS_THREADMANAGER_CONTRACTID, &rv); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return mgr->GetCurrentThread(result); #endif } NS_METHOD NS_GetMainThread(nsIThread **result) { #ifdef MOZILLA_INTERNAL_API return nsThreadManager::get()->nsThreadManager::GetMainThread(result); #else nsresult rv; nsCOMPtr<nsIThreadManager> mgr = do_GetService(NS_THREADMANAGER_CONTRACTID, &rv); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return mgr->GetMainThread(result); #endif } #if defined(MOZILLA_INTERNAL_API) && defined(XP_WIN) extern DWORD gTLSThreadIDIndex; bool NS_IsMainThread() @@ -161,50 +156,46 @@ NS_METHOD NS_DispatchToCurrentThread(nsIRunnable *event) { #ifdef MOZILLA_INTERNAL_API nsIThread *thread = NS_GetCurrentThread(); if (!thread) { return NS_ERROR_UNEXPECTED; } #else nsCOMPtr<nsIThread> thread; nsresult rv = NS_GetCurrentThread(getter_AddRefs(thread)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); #endif return thread->Dispatch(event, NS_DISPATCH_NORMAL); } NS_METHOD NS_DispatchToMainThread(nsIRunnable *event, uint32_t dispatchFlags) { nsCOMPtr<nsIThread> thread; nsresult rv = NS_GetMainThread(getter_AddRefs(thread)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return thread->Dispatch(event, dispatchFlags); } #ifndef XPCOM_GLUE_AVOID_NSPR NS_METHOD NS_ProcessPendingEvents(nsIThread *thread, PRIntervalTime timeout) { nsresult rv = NS_OK; #ifdef MOZILLA_INTERNAL_API if (!thread) { thread = NS_GetCurrentThread(); - if (NS_WARN_IF(!thread)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(thread); } #else nsCOMPtr<nsIThread> current; if (!thread) { rv = NS_GetCurrentThread(getter_AddRefs(current)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); thread = current.get(); } #endif PRIntervalTime start = PR_IntervalNow(); for (;;) { bool processedEvent; rv = thread->ProcessNextEvent(false, &processedEvent); @@ -229,38 +220,35 @@ NS_HasPendingEvents(nsIThread *thread) { if (!thread) { #ifndef MOZILLA_INTERNAL_API nsCOMPtr<nsIThread> current; NS_GetCurrentThread(getter_AddRefs(current)); return hasPendingEvents(current); #else thread = NS_GetCurrentThread(); - if (NS_WARN_IF(!thread)) - return false; + NS_ENSURE_TRUE(thread, false); #endif } return hasPendingEvents(thread); } bool NS_ProcessNextEvent(nsIThread *thread, bool mayWait) { #ifdef MOZILLA_INTERNAL_API if (!thread) { thread = NS_GetCurrentThread(); - if (NS_WARN_IF(!thread)) - return false; + NS_ENSURE_TRUE(thread, false); } #else nsCOMPtr<nsIThread> current; if (!thread) { NS_GetCurrentThread(getter_AddRefs(current)); - if (NS_WARN_IF(!current)) - return false; + NS_ENSURE_TRUE(current, false); thread = current.get(); } #endif bool val; return NS_SUCCEEDED(thread->ProcessNextEvent(mayWait, &val)) && val; } #ifndef XPCOM_GLUE_AVOID_NSPR
--- a/xpcom/glue/nsThreadUtils.h +++ b/xpcom/glue/nsThreadUtils.h @@ -66,18 +66,17 @@ NS_NewThread(nsIThread **result, template <size_t LEN> inline NS_METHOD NS_NewNamedThread(const char (&name)[LEN], nsIThread **result, nsIRunnable *initialEvent = nullptr, uint32_t stackSize = nsIThreadManager::DEFAULT_STACK_SIZE) { nsresult rv = NS_NewThread(result, nullptr, stackSize); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); NS_SetThreadName<LEN>(*result, name); if (initialEvent) { rv = (*result)->Dispatch(initialEvent, NS_DISPATCH_NORMAL); NS_WARN_IF_FALSE(NS_SUCCEEDED(rv), "Initial event dispatch failed"); } return rv; }
--- a/xpcom/io/Base64.cpp +++ b/xpcom/io/Base64.cpp @@ -158,18 +158,17 @@ EncodeInputStream(nsIInputStream *aInput uint32_t aCount, uint32_t aOffset) { nsresult rv; uint64_t count64 = aCount; if (!aCount) { rv = aInputStream->Available(&count64); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // if count64 is over 4GB, it will be failed at the below condition, // then will return NS_ERROR_OUT_OF_MEMORY aCount = (uint32_t)count64; } uint64_t countlong = (count64 + 2) / 3 * 4; // +2 due to integer math. if (countlong + aOffset > UINT32_MAX)
--- a/xpcom/io/CocoaFileUtils.mm +++ b/xpcom/io/CocoaFileUtils.mm @@ -11,50 +11,48 @@ #include "nsDebug.h" namespace CocoaFileUtils { nsresult RevealFileInFinder(CFURLRef url) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; - if (NS_WARN_IF(!url)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(url); NSAutoreleasePool* ap = [[NSAutoreleasePool alloc] init]; BOOL success = [[NSWorkspace sharedWorkspace] selectFile:[(NSURL*)url path] inFileViewerRootedAtPath:@""]; [ap release]; return (success ? NS_OK : NS_ERROR_FAILURE); NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT; } nsresult OpenURL(CFURLRef url) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; - if (NS_WARN_IF(!url)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(url); NSAutoreleasePool* ap = [[NSAutoreleasePool alloc] init]; BOOL success = [[NSWorkspace sharedWorkspace] openURL:(NSURL*)url]; [ap release]; return (success ? NS_OK : NS_ERROR_FAILURE); NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT; } nsresult GetFileCreatorCode(CFURLRef url, OSType *creatorCode) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; - if (NS_WARN_IF(!url) || NS_WARN_IF(!creatorCode)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(url); + NS_ENSURE_ARG_POINTER(creatorCode); nsAutoreleasePool localPool; NSString *resolvedPath = [[(NSURL*)url path] stringByResolvingSymlinksInPath]; if (!resolvedPath) { return NS_ERROR_FAILURE; } @@ -73,34 +71,33 @@ nsresult GetFileCreatorCode(CFURLRef url NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT; } nsresult SetFileCreatorCode(CFURLRef url, OSType creatorCode) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; - if (NS_WARN_IF(!url)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(url); NSAutoreleasePool* ap = [[NSAutoreleasePool alloc] init]; NSDictionary* dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:creatorCode] forKey:NSFileHFSCreatorCode]; BOOL success = [[NSFileManager defaultManager] setAttributes:dict ofItemAtPath:[(NSURL*)url path] error:nil]; [ap release]; return (success ? NS_OK : NS_ERROR_FAILURE); NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT; } nsresult GetFileTypeCode(CFURLRef url, OSType *typeCode) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; - if (NS_WARN_IF(!url) || NS_WARN_IF(!typeCode)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(url); + NS_ENSURE_ARG_POINTER(typeCode); nsAutoreleasePool localPool; NSString *resolvedPath = [[(NSURL*)url path] stringByResolvingSymlinksInPath]; if (!resolvedPath) { return NS_ERROR_FAILURE; } @@ -119,18 +116,17 @@ nsresult GetFileTypeCode(CFURLRef url, O NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT; } nsresult SetFileTypeCode(CFURLRef url, OSType typeCode) { NS_OBJC_BEGIN_TRY_ABORT_BLOCK_NSRESULT; - if (NS_WARN_IF(!url)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(url); NSAutoreleasePool* ap = [[NSAutoreleasePool alloc] init]; NSDictionary* dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithUnsignedLong:typeCode] forKey:NSFileHFSTypeCode]; BOOL success = [[NSFileManager defaultManager] setAttributes:dict ofItemAtPath:[(NSURL*)url path] error:nil]; [ap release]; return (success ? NS_OK : NS_ERROR_FAILURE); NS_OBJC_END_TRY_ABORT_BLOCK_NSRESULT;
--- a/xpcom/io/nsAnonymousTemporaryFile.cpp +++ b/xpcom/io/nsAnonymousTemporaryFile.cpp @@ -45,68 +45,60 @@ using namespace mozilla; // 3. Content processes can access the system temp dir // (NS_GetSpecialDirectory fails on NS_APP_USER_PROFILE_LOCAL_50_DIR // for content process for example, which is where we previously stored // temp files on Windows). This argument applies to all platforms, not // just Windows. static nsresult GetTempDir(nsIFile** aTempDir) { - if (NS_WARN_IF(!aTempDir)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aTempDir); nsCOMPtr<nsIFile> tmpFile; nsresult rv = NS_GetSpecialDirectory(NS_OS_TEMP_DIR, getter_AddRefs(tmpFile)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv,rv); #ifdef XP_WIN // On windows DELETE_ON_CLOSE is unreliable, so we store temporary files // in a subdir of the temp dir and delete that in an idle service observer // to ensure it's been cleared. rv = tmpFile->AppendNative(nsDependentCString("mozilla-temp-files")); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv,rv); rv = tmpFile->Create(nsIFile::DIRECTORY_TYPE, 0700); - if (rv != NS_ERROR_FILE_ALREADY_EXISTS && NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_TRUE(rv == NS_ERROR_FILE_ALREADY_EXISTS || NS_SUCCEEDED(rv), rv); #endif tmpFile.forget(aTempDir); return NS_OK; } nsresult NS_OpenAnonymousTemporaryFile(PRFileDesc** aOutFileDesc) { - if (NS_WARN_IF(!aOutFileDesc)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aOutFileDesc); nsresult rv; nsCOMPtr<nsIFile> tmpFile; rv = GetTempDir(getter_AddRefs(tmpFile)); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv,rv); // Give the temp file a name with a random element. CreateUnique will also // append a counter to the name if it encounters a name collision. Adding // a random element to the name reduces the likelihood of a name collision, // so that CreateUnique() doesn't end up trying a lot of name variants in // its "try appending an incrementing counter" loop, as file IO can be // expensive on some mobile flash drives. nsAutoCString name("mozilla-temp-"); name.AppendInt(rand()); rv = tmpFile->AppendNative(name); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv,rv); rv = tmpFile->CreateUnique(nsIFile::NORMAL_FILE_TYPE, 0700); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv,rv); rv = tmpFile->OpenNSPRFileDesc(PR_RDWR | nsIFile::DELETE_ON_CLOSE, PR_IRWXU, aOutFileDesc); return rv; } #ifdef XP_WIN @@ -149,29 +141,26 @@ public: nsresult Init() { // We add the idle observer in a timer, so that the app has enough // time to start up before we add the idle observer. If we register the // idle observer too early, it will be registered before the fake idle // service is installed when running in xpcshell, and this interferes with // the fake idle service, causing xpcshell-test failures. mTimer = do_CreateInstance(NS_TIMER_CONTRACTID); - if (NS_WARN_IF(!mTimer)) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(mTimer != nullptr, NS_ERROR_FAILURE); nsresult rv = mTimer->Init(this, SCHEDULE_TIMEOUT_MS, nsITimer::TYPE_ONE_SHOT); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // Register shutdown observer so we can cancel the timer if we shutdown before // the timer runs. nsCOMPtr<nsIObserverService> obsSrv = services::GetObserverService(); - if (NS_WARN_IF(!obsSrv)) - return NS_ERROR_FAILURE; + NS_ENSURE_TRUE(obsSrv != nullptr, NS_ERROR_FAILURE); return obsSrv->AddObserver(this, XPCOM_SHUTDOWN_TOPIC, false); } void Cleanup() { // Cancel timer. if (mTimer) { mTimer->Cancel(); mTimer = nullptr; @@ -217,18 +206,17 @@ public: if (!idleSvc) return NS_ERROR_FAILURE; return idleSvc->AddIdleObserver(this, TEMP_FILE_IDLE_TIME_S); } void RemoveAnonTempFileFiles() { nsCOMPtr<nsIFile> tmpDir; nsresult rv = GetTempDir(getter_AddRefs(tmpDir)); - if (NS_WARN_IF(NS_FAILED(rv))) - return; + NS_ENSURE_SUCCESS_VOID(rv); // Remove the directory recursively. tmpDir->Remove(true); } private: nsCOMPtr<nsITimer> mTimer; };
--- a/xpcom/io/nsAppFileLocationProvider.cpp +++ b/xpcom/io/nsAppFileLocationProvider.cpp @@ -82,22 +82,20 @@ NS_IMPL_ISUPPORTS2(nsAppFileLocationProv //***************************************************************************** // nsAppFileLocationProvider::nsIDirectoryServiceProvider //***************************************************************************** NS_IMETHODIMP nsAppFileLocationProvider::GetFile(const char *prop, bool *persistent, nsIFile **_retval) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; - nsCOMPtr<nsIFile> localFile; nsresult rv = NS_ERROR_FAILURE; + NS_ENSURE_ARG(prop); *_retval = nullptr; *persistent = true; #ifdef MOZ_WIDGET_COCOA FSRef fileRef; nsCOMPtr<nsILocalFileMac> macFile; #endif @@ -247,18 +245,17 @@ nsAppFileLocationProvider::GetFile(const return localFile->QueryInterface(NS_GET_IID(nsIFile), (void**)_retval); return rv; } NS_METHOD nsAppFileLocationProvider::CloneMozBinDirectory(nsIFile **aLocalFile) { - if (NS_WARN_IF(!aLocalFile)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aLocalFile); nsresult rv; if (!mMozBinDirectory) { // Get the mozilla bin directory // 1. Check the directory service first for NS_XPCOM_CURRENT_PROCESS_DIR // This will be set if a directory was passed to NS_InitXPCOM // 2. If that doesn't work, set it to be the current process directory @@ -289,18 +286,17 @@ NS_METHOD nsAppFileLocationProvider::Clo // GetProductDirectory - Gets the directory which contains the application data folder // // UNIX : ~/.mozilla/ // WIN : <Application Data folder on user's machine>\Mozilla // Mac : :Documents:Mozilla: //---------------------------------------------------------------------------------------- NS_METHOD nsAppFileLocationProvider::GetProductDirectory(nsIFile **aLocalFile, bool aLocal) { - if (NS_WARN_IF(!aLocalFile)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aLocalFile); nsresult rv; bool exists; nsCOMPtr<nsIFile> localDir; #if defined(MOZ_WIDGET_COCOA) FSRef fsRef; OSType folderType = aLocal ? (OSType) kCachedDataFolderType : (OSType) kDomainLibraryFolderType; @@ -351,18 +347,17 @@ NS_METHOD nsAppFileLocationProvider::Get // GetDefaultUserProfileRoot - Gets the directory which contains each user profile dir // // UNIX : ~/.mozilla/ // WIN : <Application Data folder on user's machine>\Mozilla\Profiles // Mac : :Documents:Mozilla:Profiles: //---------------------------------------------------------------------------------------- NS_METHOD nsAppFileLocationProvider::GetDefaultUserProfileRoot(nsIFile **aLocalFile, bool aLocal) { - if (NS_WARN_IF(!aLocalFile)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aLocalFile); nsresult rv; nsCOMPtr<nsIFile> localDir; rv = GetProductDirectory(getter_AddRefs(localDir), aLocal); if (NS_FAILED(rv)) return rv; #if defined(MOZ_WIDGET_COCOA) || defined(XP_OS2) || defined(XP_WIN) @@ -416,18 +411,17 @@ class nsAppDirectoryEnumerator : public mNext = testFile; } *result = mNext != nullptr; return NS_OK; } NS_IMETHOD GetNext(nsISupports **result) { - if (NS_WARN_IF(!result)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(result); *result = nullptr; bool hasMore; HasMoreElements(&hasMore); if (!hasMore) return NS_ERROR_FAILURE; *result = mNext; @@ -512,18 +506,17 @@ class nsPathsDirectoryEnumerator : publi protected: const char *mEndPath; }; NS_IMETHODIMP nsAppFileLocationProvider::GetFiles(const char *prop, nsISimpleEnumerator **_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); *_retval = nullptr; nsresult rv = NS_ERROR_FAILURE; if (!nsCRT::strcmp(prop, NS_APP_PLUGINS_DIR_LIST)) { #ifdef MOZ_WIDGET_COCOA // As of Java for Mac OS X 10.5 Update 10, Apple has (in effect) deprecated Java Plugin2 on // on OS X 10.5, and removed the soft link to it from /Library/Internet Plug-Ins/. Java
--- a/xpcom/io/nsBinaryStream.cpp +++ b/xpcom/io/nsBinaryStream.cpp @@ -29,34 +29,31 @@ #include "jsfriendapi.h" NS_IMPL_ISUPPORTS3(nsBinaryOutputStream, nsIObjectOutputStream, nsIBinaryOutputStream, nsIOutputStream) NS_IMETHODIMP nsBinaryOutputStream::Flush() { - if (NS_WARN_IF(!mOutputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mOutputStream); return mOutputStream->Flush(); } NS_IMETHODIMP nsBinaryOutputStream::Close() { - if (NS_WARN_IF(!mOutputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mOutputStream); return mOutputStream->Close(); } NS_IMETHODIMP nsBinaryOutputStream::Write(const char *aBuf, uint32_t aCount, uint32_t *aActualBytes) { - if (NS_WARN_IF(!mOutputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mOutputStream); return mOutputStream->Write(aBuf, aCount, aActualBytes); } NS_IMETHODIMP nsBinaryOutputStream::WriteFrom(nsIInputStream *inStr, uint32_t count, uint32_t *_retval) { NS_NOTREACHED("WriteFrom"); return NS_ERROR_NOT_IMPLEMENTED; @@ -67,42 +64,39 @@ nsBinaryOutputStream::WriteSegments(nsRe { NS_NOTREACHED("WriteSegments"); return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsBinaryOutputStream::IsNonBlocking(bool *aNonBlocking) { - if (NS_WARN_IF(!mOutputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mOutputStream); return mOutputStream->IsNonBlocking(aNonBlocking); } nsresult nsBinaryOutputStream::WriteFully(const char *aBuf, uint32_t aCount) { - if (NS_WARN_IF(!mOutputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mOutputStream); nsresult rv; uint32_t bytesWritten; rv = mOutputStream->Write(aBuf, aCount, &bytesWritten); if (NS_FAILED(rv)) return rv; if (bytesWritten != aCount) return NS_ERROR_FAILURE; return NS_OK; } NS_IMETHODIMP nsBinaryOutputStream::SetOutputStream(nsIOutputStream *aOutputStream) { - if (NS_WARN_IF(!aOutputStream)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aOutputStream); mOutputStream = aOutputStream; mBufferAccess = do_QueryInterface(aOutputStream); return NS_OK; } NS_IMETHODIMP nsBinaryOutputStream::WriteBoolean(bool aBoolean) { @@ -246,58 +240,52 @@ nsBinaryOutputStream::WriteSingleRefObje true); } NS_IMETHODIMP nsBinaryOutputStream::WriteCompoundObject(nsISupports* aObject, const nsIID& aIID, bool aIsStrongRef) { + // Can't deal with weak refs + NS_ENSURE_TRUE(aIsStrongRef, NS_ERROR_UNEXPECTED); + nsCOMPtr<nsIClassInfo> classInfo = do_QueryInterface(aObject); - nsCOMPtr<nsISerializable> serializable = do_QueryInterface(aObject); + NS_ENSURE_TRUE(classInfo, NS_ERROR_NOT_AVAILABLE); - // Can't deal with weak refs - if (NS_WARN_IF(!aIsStrongRef)) - return NS_ERROR_UNEXPECTED; - if (NS_WARN_IF(!classInfo) || NS_WARN_IF(!serializable)) - return NS_ERROR_NOT_AVAILABLE; + nsCOMPtr<nsISerializable> serializable = do_QueryInterface(aObject); + NS_ENSURE_TRUE(serializable, NS_ERROR_NOT_AVAILABLE); nsCID cid; classInfo->GetClassIDNoAlloc(&cid); nsresult rv = WriteID(cid); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; - + NS_ENSURE_SUCCESS(rv, rv); + rv = WriteID(aIID); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return serializable->Write(this); } NS_IMETHODIMP nsBinaryOutputStream::WriteID(const nsIID& aIID) { nsresult rv = Write32(aIID.m0); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = Write16(aIID.m1); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = Write16(aIID.m2); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); for (int i = 0; i < 8; ++i) { rv = Write8(aIID.m3[i]); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } return NS_OK; } NS_IMETHODIMP_(char*) nsBinaryOutputStream::GetBuffer(uint32_t aLength, uint32_t aAlignMask) { @@ -313,26 +301,24 @@ nsBinaryOutputStream::PutBuffer(char* aB mBufferAccess->PutBuffer(aBuffer, aLength); } NS_IMPL_ISUPPORTS3(nsBinaryInputStream, nsIObjectInputStream, nsIBinaryInputStream, nsIInputStream) NS_IMETHODIMP nsBinaryInputStream::Available(uint64_t* aResult) { - if (NS_WARN_IF(!mInputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mInputStream); return mInputStream->Available(aResult); } NS_IMETHODIMP nsBinaryInputStream::Read(char* aBuffer, uint32_t aCount, uint32_t *aNumRead) { - if (NS_WARN_IF(!mInputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mInputStream); // mInputStream might give us short reads, so deal with that. uint32_t totalRead = 0; uint32_t bytesRead; do { nsresult rv = mInputStream->Read(aBuffer, aCount, &bytesRead); if (rv == NS_BASE_STREAM_WOULD_BLOCK && totalRead != 0) { @@ -392,18 +378,17 @@ ReadSegmentForwardingThunk(nsIInputStrea return thunkClosure->mRealResult; } NS_IMETHODIMP nsBinaryInputStream::ReadSegments(nsWriteSegmentFun writer, void * closure, uint32_t count, uint32_t *_retval) { - if (NS_WARN_IF(!mInputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mInputStream); ReadSegmentsClosure thunkClosure = { this, closure, writer, NS_OK, 0 }; // mInputStream might give us short reads, so deal with that. uint32_t bytesRead; do { nsresult rv = mInputStream->ReadSegments(ReadSegmentForwardingThunk, &thunkClosure, @@ -426,34 +411,31 @@ nsBinaryInputStream::ReadSegments(nsWrit *_retval = thunkClosure.mBytesRead; return NS_OK; } NS_IMETHODIMP nsBinaryInputStream::IsNonBlocking(bool *aNonBlocking) { - if (NS_WARN_IF(!mInputStream)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mInputStream); return mInputStream->IsNonBlocking(aNonBlocking); } NS_IMETHODIMP -nsBinaryInputStream::Close() -{ - if (NS_WARN_IF(!mInputStream)) - return NS_ERROR_UNEXPECTED; - return mInputStream->Close(); +nsBinaryInputStream::Close() +{ + NS_ENSURE_STATE(mInputStream); + return mInputStream->Close(); } NS_IMETHODIMP nsBinaryInputStream::SetInputStream(nsIInputStream *aInputStream) { - if (NS_WARN_IF(!aInputStream)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aInputStream); mInputStream = aInputStream; mBufferAccess = do_QueryInterface(aInputStream); return NS_OK; } NS_IMETHODIMP nsBinaryInputStream::ReadBoolean(bool* aBoolean) { @@ -742,36 +724,33 @@ nsBinaryInputStream::ReadArrayBuffer(uin } uint8_t* data = JS_GetArrayBufferData(&aBuffer.toObject()); if (!data) { return NS_ERROR_FAILURE; } uint32_t bytesRead; nsresult rv = Read(reinterpret_cast<char*>(data), aLength, &bytesRead); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); if (bytesRead != aLength) { return NS_ERROR_FAILURE; } return NS_OK; } NS_IMETHODIMP nsBinaryInputStream::ReadObject(bool aIsStrongRef, nsISupports* *aObject) { nsCID cid; nsIID iid; nsresult rv = ReadID(&cid); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = ReadID(&iid); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // HACK: Intercept old (pre-gecko6) nsIURI IID, and replace with // the updated IID, so that we're QI'ing to an actual interface. // (As soon as we drop support for upgrading from pre-gecko6, we can // remove this chunk.) static const nsIID oldURIiid = { 0x7a22cc0, 0xce5, 0x11d3, { 0x93, 0x31, 0x0, 0x10, 0x4b, 0xa0, 0xfd, 0x40 }}; @@ -790,49 +769,42 @@ nsBinaryInputStream::ReadObject(bool aIs iid.Equals(oldURIiid2) || iid.Equals(oldURIiid3)) { const nsIID newURIiid = NS_IURI_IID; iid = newURIiid; } // END HACK nsCOMPtr<nsISupports> object = do_CreateInstance(cid, &rv); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); nsCOMPtr<nsISerializable> serializable = do_QueryInterface(object); - if (NS_WARN_IF(!serializable)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_TRUE(serializable, NS_ERROR_UNEXPECTED); rv = serializable->Read(this); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return object->QueryInterface(iid, reinterpret_cast<void**>(aObject)); } NS_IMETHODIMP nsBinaryInputStream::ReadID(nsID *aResult) { nsresult rv = Read32(&aResult->m0); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = Read16(&aResult->m1); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = Read16(&aResult->m2); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); for (int i = 0; i < 8; ++i) { rv = Read8(&aResult->m3[i]); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } return NS_OK; } NS_IMETHODIMP_(char*) nsBinaryInputStream::GetBuffer(uint32_t aLength, uint32_t aAlignMask) {
--- a/xpcom/io/nsDirectoryService.cpp +++ b/xpcom/io/nsDirectoryService.cpp @@ -54,18 +54,17 @@ using namespace mozilla; #define HOME_DIR NS_OS2_HOME_DIR #endif //---------------------------------------------------------------------------------------- nsresult nsDirectoryService::GetCurrentProcessDirectory(nsIFile** aFile) //---------------------------------------------------------------------------------------- { - if (NS_WARN_IF(!aFile)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aFile); *aFile = nullptr; // Set the component registry location: if (!gService) return NS_ERROR_FAILURE; nsresult rv; @@ -221,20 +220,18 @@ nsDirectoryService* nsDirectoryService:: nsDirectoryService::nsDirectoryService() : mHashtable(256) { } nsresult nsDirectoryService::Create(nsISupports *outer, REFNSIID aIID, void **aResult) { - if (NS_WARN_IF(!aResult)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_ARG_POINTER(aResult); + NS_ENSURE_NO_AGGREGATION(outer); if (!gService) { return NS_ERROR_NOT_INITIALIZED; } return gService->QueryInterface(aIID, aResult); } @@ -282,18 +279,17 @@ nsDirectoryService::~nsDirectoryService( } NS_IMPL_ISUPPORTS4(nsDirectoryService, nsIProperties, nsIDirectoryService, nsIDirectoryServiceProvider, nsIDirectoryServiceProvider2) NS_IMETHODIMP nsDirectoryService::Undefine(const char* prop) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(prop); nsDependentCString key(prop); if (!mHashtable.Get(key, nullptr)) return NS_ERROR_FAILURE; mHashtable.Remove(key); return NS_OK; } @@ -359,18 +355,17 @@ static bool FindProviderFile(nsIDirector } return true; } NS_IMETHODIMP nsDirectoryService::Get(const char* prop, const nsIID & uuid, void* *result) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(prop); nsDependentCString key(prop); nsCOMPtr<nsIFile> cachedFile = mHashtable.Get(key); if (cachedFile) { nsCOMPtr<nsIFile> cloneFile; cachedFile->Clone(getter_AddRefs(cloneFile)); @@ -409,18 +404,17 @@ nsDirectoryService::Get(const char* prop } return NS_ERROR_FAILURE; } NS_IMETHODIMP nsDirectoryService::Set(const char* prop, nsISupports* value) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(prop); nsDependentCString key(prop); if (mHashtable.Get(key, nullptr) || !value) { return NS_ERROR_FAILURE; } nsCOMPtr<nsIFile> ourFile = do_QueryInterface(value); if (ourFile) { @@ -432,18 +426,17 @@ nsDirectoryService::Set(const char* prop } return NS_ERROR_FAILURE; } NS_IMETHODIMP nsDirectoryService::Has(const char *prop, bool *_retval) { - if (NS_WARN_IF(!prop)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(prop); *_retval = false; nsCOMPtr<nsIFile> value; nsresult rv = Get(prop, NS_GET_IID(nsIFile), getter_AddRefs(value)); if (NS_FAILED(rv)) return NS_OK; if (value) @@ -912,14 +905,13 @@ nsDirectoryService::GetFile(const char * return NS_ERROR_FAILURE; return CallQueryInterface(localFile, _retval); } NS_IMETHODIMP nsDirectoryService::GetFiles(const char *prop, nsISimpleEnumerator **_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); *_retval = nullptr; return NS_ERROR_FAILURE; }
--- a/xpcom/io/nsIOUtil.cpp +++ b/xpcom/io/nsIOUtil.cpp @@ -1,29 +1,27 @@ -/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ +/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 4 -*- */ /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ #include "nsIOUtil.h" #include "nsIInputStream.h" #include "nsIOutputStream.h" #include "nsStreamUtils.h" NS_IMPL_ISUPPORTS1(nsIOUtil, nsIIOUtil) NS_IMETHODIMP nsIOUtil::InputStreamIsBuffered(nsIInputStream* aStream, bool* _retval) { - if (NS_WARN_IF(!aStream)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aStream); *_retval = NS_InputStreamIsBuffered(aStream); return NS_OK; } NS_IMETHODIMP nsIOUtil::OutputStreamIsBuffered(nsIOutputStream* aStream, bool* _retval) { - if (NS_WARN_IF(!aStream)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aStream); *_retval = NS_OutputStreamIsBuffered(aStream); return NS_OK; }
--- a/xpcom/io/nsInputStreamTee.cpp +++ b/xpcom/io/nsInputStreamTee.cpp @@ -159,16 +159,17 @@ nsInputStreamTee::TeeSegment(const char if (!mSink) return NS_OK; // nothing to do if (mLock) { // asynchronous case NS_ASSERTION(mEventTarget, "mEventTarget is null, mLock is not null."); if (!SinkIsValid()) { return NS_OK; // nothing to do } nsRefPtr<nsIRunnable> event = new nsInputStreamTeeWriteEvent(buf, count, mSink, this); + NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY); LOG(("nsInputStreamTee::TeeSegment [%p] dispatching write %u bytes\n", this, count)); return mEventTarget->Dispatch(event, NS_DISPATCH_NORMAL); } else { // synchronous case NS_ASSERTION(!mEventTarget, "mEventTarget is not null, mLock is null."); nsresult rv; uint32_t totalBytesWritten = 0; while (count) { @@ -208,65 +209,60 @@ nsInputStreamTee::WriteSegmentFun(nsIInp } NS_IMPL_ISUPPORTS2(nsInputStreamTee, nsIInputStreamTee, nsIInputStream) NS_IMETHODIMP nsInputStreamTee::Close() { - if (NS_WARN_IF(!mSource)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSource, NS_ERROR_NOT_INITIALIZED); nsresult rv = mSource->Close(); mSource = 0; mSink = 0; return rv; } NS_IMETHODIMP nsInputStreamTee::Available(uint64_t *avail) { - if (NS_WARN_IF(!mSource)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSource, NS_ERROR_NOT_INITIALIZED); return mSource->Available(avail); } NS_IMETHODIMP nsInputStreamTee::Read(char *buf, uint32_t count, uint32_t *bytesRead) { - if (NS_WARN_IF(!mSource)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSource, NS_ERROR_NOT_INITIALIZED); nsresult rv = mSource->Read(buf, count, bytesRead); if (NS_FAILED(rv) || (*bytesRead == 0)) return rv; return TeeSegment(buf, *bytesRead); } NS_IMETHODIMP nsInputStreamTee::ReadSegments(nsWriteSegmentFun writer, void *closure, uint32_t count, uint32_t *bytesRead) { - if (NS_WARN_IF(!mSource)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSource, NS_ERROR_NOT_INITIALIZED); mWriter = writer; mClosure = closure; return mSource->ReadSegments(WriteSegmentFun, this, count, bytesRead); } NS_IMETHODIMP nsInputStreamTee::IsNonBlocking(bool *result) { - if (NS_WARN_IF(!mSource)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSource, NS_ERROR_NOT_INITIALIZED); return mSource->IsNonBlocking(result); } NS_IMETHODIMP nsInputStreamTee::SetSource(nsIInputStream *source) { mSource = source; return NS_OK;
--- a/xpcom/io/nsLocalFileCommon.cpp +++ b/xpcom/io/nsLocalFileCommon.cpp @@ -28,18 +28,17 @@ void NS_ShutdownLocalFile() { nsLocalFile::GlobalShutdown(); } #if !defined(MOZ_WIDGET_COCOA) && !defined(XP_WIN) NS_IMETHODIMP nsLocalFile::InitWithFile(nsIFile *aFile) { - if (NS_WARN_IF(!aFile)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aFile); nsAutoCString path; aFile->GetNativePath(path); if (path.IsEmpty()) return NS_ERROR_INVALID_ARG; return InitWithNativePath(path); } #endif @@ -185,18 +184,17 @@ static int32_t SplitPath(PRUnichar *path } return nodePtr - nodeArray; } NS_IMETHODIMP nsLocalFile::GetRelativeDescriptor(nsIFile *fromFile, nsACString& _retval) { - if (NS_WARN_IF(!fromFile)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(fromFile); const int32_t kMaxNodesInPath = 32; // // _retval will be UTF-8 encoded // nsresult rv; _retval.Truncate(0);
--- a/xpcom/io/nsLocalFileUnix.cpp +++ b/xpcom/io/nsLocalFileUnix.cpp @@ -238,20 +238,18 @@ NS_IMPL_ISUPPORTS3(nsLocalFile, nsIHashable) #endif nsresult nsLocalFile::nsLocalFileConstructor(nsISupports *outer, const nsIID &aIID, void **aInstancePtr) { - if (NS_WARN_IF(!aInstancePtr)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_ARG_POINTER(aInstancePtr); + NS_ENSURE_NO_AGGREGATION(outer); *aInstancePtr = nullptr; nsCOMPtr<nsIFile> inst = new nsLocalFile(); return inst->QueryInterface(aIID, aInstancePtr); } bool @@ -1002,18 +1000,17 @@ nsLocalFile::Remove(bool recursive) return NSRESULT_FOR_RETURN(rmdir(mPath.get())); } NS_IMETHODIMP nsLocalFile::GetLastModifiedTime(PRTime *aLastModTime) { CHECK_mPath(); - if (NS_WARN_IF(!aLastModTime)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aLastModTime); PRFileInfo64 info; if (PR_GetFileInfo64(mPath.get(), &info) != PR_SUCCESS) return NSRESULT_FOR_ERRNO(); PRTime modTime = info.modifyTime; if (modTime == 0) *aLastModTime = 0; else @@ -1041,18 +1038,17 @@ nsLocalFile::SetLastModifiedTime(PRTime } return NSRESULT_FOR_RETURN(result); } NS_IMETHODIMP nsLocalFile::GetLastModifiedTimeOfLink(PRTime *aLastModTimeOfLink) { CHECK_mPath(); - if (NS_WARN_IF(!aLastModTimeOfLink)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aLastModTimeOfLink); struct STAT sbuf; if (LSTAT(mPath.get(), &sbuf) == -1) return NSRESULT_FOR_ERRNO(); *aLastModTimeOfLink = PRTime(sbuf.st_mtime) * PR_MSEC_PER_SEC; return NS_OK; } @@ -1071,29 +1067,27 @@ nsLocalFile::SetLastModifiedTimeOfLink(P * mode_t to permit checks against other file types? */ #define NORMALIZE_PERMS(mode) ((mode)& (S_IRWXU | S_IRWXG | S_IRWXO)) NS_IMETHODIMP nsLocalFile::GetPermissions(uint32_t *aPermissions) { - if (NS_WARN_IF(!aPermissions)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aPermissions); ENSURE_STAT_CACHE(); *aPermissions = NORMALIZE_PERMS(mCachedStat.st_mode); return NS_OK; } NS_IMETHODIMP nsLocalFile::GetPermissionsOfLink(uint32_t *aPermissionsOfLink) { CHECK_mPath(); - if (NS_WARN_IF(!aPermissionsOfLink)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aPermissionsOfLink); struct STAT sbuf; if (LSTAT(mPath.get(), &sbuf) == -1) return NSRESULT_FOR_ERRNO(); *aPermissionsOfLink = NORMALIZE_PERMS(sbuf.st_mode); return NS_OK; } @@ -1128,18 +1122,17 @@ nsLocalFile::SetPermissionsOfLink(uint32 // There isn't a consistent mechanism for doing this on UNIX platforms. We // might want to carefully implement this in the future though. return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsLocalFile::GetFileSize(int64_t *aFileSize) { - if (NS_WARN_IF(!aFileSize)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aFileSize); *aFileSize = 0; ENSURE_STAT_CACHE(); #if defined(VMS) /* Only two record formats can report correct file content size */ if ((mCachedStat.st_fab_rfm != FAB$C_STMLF) && (mCachedStat.st_fab_rfm != FAB$C_STMCR)) { return NS_ERROR_FAILURE; @@ -1178,18 +1171,17 @@ nsLocalFile::SetFileSize(int64_t aFileSi #endif return NS_OK; } NS_IMETHODIMP nsLocalFile::GetFileSizeOfLink(int64_t *aFileSize) { CHECK_mPath(); - if (NS_WARN_IF(!aFileSize)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aFileSize); struct STAT sbuf; if (LSTAT(mPath.get(), &sbuf) == -1) return NSRESULT_FOR_ERRNO(); *aFileSize = (int64_t)sbuf.st_size; return NS_OK; } @@ -1244,18 +1236,17 @@ GetDeviceName(int deviceMajor, int devic fclose(f); return ret; } #endif NS_IMETHODIMP nsLocalFile::GetDiskSpaceAvailable(int64_t *aDiskSpaceAvailable) { - if (NS_WARN_IF(!aDiskSpaceAvailable)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aDiskSpaceAvailable); // These systems have the operations necessary to check disk space. #ifdef STATFS // check to make sure that mPath is properly initialized CHECK_mPath(); @@ -1330,18 +1321,17 @@ nsLocalFile::GetDiskSpaceAvailable(int64 #endif /* STATFS */ } NS_IMETHODIMP nsLocalFile::GetParent(nsIFile **aParent) { CHECK_mPath(); - if (NS_WARN_IF(!aParent)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aParent); *aParent = nullptr; // if '/' we are at the top of the volume, return null if (mPath.Equals("/")) return NS_OK; // <brendan, after jband> I promise to play nice char *buffer = mPath.BeginWriting(), @@ -1377,56 +1367,52 @@ nsLocalFile::GetParent(nsIFile **aParent * The results of Exists, isWritable and isReadable are not cached. */ NS_IMETHODIMP nsLocalFile::Exists(bool *_retval) { CHECK_mPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); *_retval = (access(mPath.get(), F_OK) == 0); return NS_OK; } NS_IMETHODIMP nsLocalFile::IsWritable(bool *_retval) { CHECK_mPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); *_retval = (access(mPath.get(), W_OK) == 0); if (*_retval || errno == EACCES) return NS_OK; return NSRESULT_FOR_ERRNO(); } NS_IMETHODIMP nsLocalFile::IsReadable(bool *_retval) { CHECK_mPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); *_retval = (access(mPath.get(), R_OK) == 0); if (*_retval || errno == EACCES) return NS_OK; return NSRESULT_FOR_ERRNO(); } NS_IMETHODIMP nsLocalFile::IsExecutable(bool *_retval) { CHECK_mPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); // Check extension (bug 663899). On certain platforms, the file // extension may cause the OS to treat it as executable regardless of // the execute bit, such as .jar on Mac OS X. We borrow the code from // nsLocalFileWin, slightly modified. // Don't be fooled by symlinks. bool symLink; @@ -1505,83 +1491,76 @@ nsLocalFile::IsExecutable(bool *_retval) if (*_retval || errno == EACCES) return NS_OK; return NSRESULT_FOR_ERRNO(); } NS_IMETHODIMP nsLocalFile::IsDirectory(bool *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); *_retval = false; ENSURE_STAT_CACHE(); *_retval = S_ISDIR(mCachedStat.st_mode); return NS_OK; } NS_IMETHODIMP nsLocalFile::IsFile(bool *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); *_retval = false; ENSURE_STAT_CACHE(); *_retval = S_ISREG(mCachedStat.st_mode); return NS_OK; } NS_IMETHODIMP nsLocalFile::IsHidden(bool *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); nsACString::const_iterator begin, end; LocateNativeLeafName(begin, end); *_retval = (*begin == '.'); return NS_OK; } NS_IMETHODIMP nsLocalFile::IsSymlink(bool *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); CHECK_mPath(); struct STAT symStat; if (LSTAT(mPath.get(), &symStat) == -1) return NSRESULT_FOR_ERRNO(); *_retval=S_ISLNK(symStat.st_mode); return NS_OK; } NS_IMETHODIMP nsLocalFile::IsSpecial(bool *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); ENSURE_STAT_CACHE(); *_retval = S_ISCHR(mCachedStat.st_mode) || S_ISBLK(mCachedStat.st_mode) || #ifdef S_ISSOCK S_ISSOCK(mCachedStat.st_mode) || #endif S_ISFIFO(mCachedStat.st_mode); return NS_OK; } NS_IMETHODIMP nsLocalFile::Equals(nsIFile *inFile, bool *_retval) { - if (NS_WARN_IF(!inFile)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(inFile); + NS_ENSURE_ARG_POINTER(_retval); *_retval = false; nsAutoCString inPath; nsresult rv = inFile->GetNativePath(inPath); if (NS_FAILED(rv)) return rv; // We don't need to worry about "/foo/" vs. "/foo" here @@ -1589,20 +1568,18 @@ nsLocalFile::Equals(nsIFile *inFile, boo *_retval = !strcmp(inPath.get(), mPath.get()); return NS_OK; } NS_IMETHODIMP nsLocalFile::Contains(nsIFile *inFile, bool recur, bool *_retval) { CHECK_mPath(); - if (NS_WARN_IF(!inFile)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(inFile); + NS_ENSURE_ARG_POINTER(_retval); nsAutoCString inPath; nsresult rv; if (NS_FAILED(rv = inFile->GetNativePath(inPath))) return rv; *_retval = false; @@ -1728,18 +1705,17 @@ nsLocalFile::GetDirectoryEntries(nsISimp return rv; } NS_IMETHODIMP nsLocalFile::Load(PRLibrary **_retval) { CHECK_mPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); #ifdef NS_BUILD_REFCNT_LOGGING nsTraceRefcntImpl::SetActivityIsLegal(false); #endif *_retval = PR_LoadLibrary(mPath.get()); #ifdef NS_BUILD_REFCNT_LOGGING @@ -2140,18 +2116,17 @@ nsLocalFile::InitWithCFURL(CFURLRef aCFU } return NS_ERROR_FAILURE; } NS_IMETHODIMP nsLocalFile::InitWithFSRef(const FSRef *aFSRef) { - if (NS_WARN_IF(!aFSRef)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aFSRef); CFURLRef newURLRef = ::CFURLCreateFromFSRef(kCFAllocatorDefault, aFSRef); if (newURLRef) { nsresult rv = InitWithCFURL(newURLRef); ::CFRelease(newURLRef); return rv; } @@ -2171,18 +2146,17 @@ nsLocalFile::GetCFURL(CFURLRef *_retval) isDir); return (*_retval ? NS_OK : NS_ERROR_FAILURE); } NS_IMETHODIMP nsLocalFile::GetFSRef(FSRef *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); nsresult rv = NS_ERROR_FAILURE; CFURLRef url = nullptr; if (NS_SUCCEEDED(GetCFURL(&url))) { if (::CFURLGetFSRef(url, _retval)) { rv = NS_OK; } @@ -2190,34 +2164,32 @@ nsLocalFile::GetFSRef(FSRef *_retval) } return rv; } NS_IMETHODIMP nsLocalFile::GetFSSpec(FSSpec *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(_retval); FSRef fsRef; nsresult rv = GetFSRef(&fsRef); if (NS_SUCCEEDED(rv)) { OSErr err = ::FSGetCatalogInfo(&fsRef, kFSCatInfoNone, nullptr, nullptr, _retval, nullptr); return MacErrorMapper(err); } return rv; } NS_IMETHODIMP nsLocalFile::GetFileSizeWithResFork(int64_t *aFileSizeWithResFork) { - if (NS_WARN_IF(!aFileSizeWithResFork)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aFileSizeWithResFork); FSRef fsRef; nsresult rv = GetFSRef(&fsRef); if (NS_FAILED(rv)) return rv; FSCatalogInfo catalogInfo; OSErr err = ::FSGetCatalogInfo(&fsRef, kFSCatInfoDataSizes + kFSCatInfoRsrcSizes, @@ -2366,18 +2338,17 @@ nsLocalFile::OpenDocWithApp(nsIFile *aAp return MacErrorMapper(err); return NS_OK; } NS_IMETHODIMP nsLocalFile::IsPackage(bool *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(_retval); *_retval = false; CFURLRef url; nsresult rv = GetCFURL(&url); if (NS_FAILED(rv)) return rv; LSItemInfoRecord info; @@ -2438,18 +2409,17 @@ nsLocalFile::GetBundleIdentifier(nsACStr return rv; } NS_IMETHODIMP nsLocalFile::GetBundleContentsLastModifiedTime(int64_t *aLastModTime) { CHECK_mPath(); - if (NS_WARN_IF(!aLastModTime)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aLastModTime); bool isPackage = false; nsresult rv = IsPackage(&isPackage); if (NS_FAILED(rv) || !isPackage) { return GetLastModifiedTime(aLastModTime); } nsAutoCString infoPlistPath(mPath); @@ -2465,18 +2435,17 @@ nsLocalFile::GetBundleContentsLastModifi *aLastModTime = modTime / int64_t(PR_USEC_PER_MSEC); } return NS_OK; } NS_IMETHODIMP nsLocalFile::InitWithFile(nsIFile *aFile) { - if (NS_WARN_IF(!aFile)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aFile); nsAutoCString nativePath; nsresult rv = aFile->GetNativePath(nativePath); if (NS_FAILED(rv)) return rv; return InitWithNativePath(nativePath); }
--- a/xpcom/io/nsLocalFileWin.cpp +++ b/xpcom/io/nsLocalFileWin.cpp @@ -720,18 +720,17 @@ struct nsDir HANDLE handle; WIN32_FIND_DATAW data; bool firstEntry; }; static nsresult OpenDir(const nsAFlatString &name, nsDir * *dir) { - if (NS_WARN_IF(!dir)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(dir); *dir = nullptr; if (name.Length() + 3 >= MAX_PATH) return NS_ERROR_FILE_NAME_TOO_LONG; nsDir *d = PR_NEW(nsDir); if (!d) return NS_ERROR_OUT_OF_MEMORY; @@ -761,18 +760,17 @@ OpenDir(const nsAFlatString &name, nsDir *dir = d; return NS_OK; } static nsresult ReadDir(nsDir *dir, PRDirFlags flags, nsString& name) { name.Truncate(); - if (NS_WARN_IF(!dir)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(dir); while (1) { BOOL rv; if (dir->firstEntry) { dir->firstEntry = false; rv = 1; } else @@ -806,18 +804,17 @@ ReadDir(nsDir *dir, PRDirFlags flags, ns DWORD err = GetLastError(); return err == ERROR_NO_MORE_FILES ? NS_OK : ConvertWinError(err); } static nsresult CloseDir(nsDir *&d) { - if (NS_WARN_IF(!d)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(d); BOOL isOk = FindClose(d->handle); // PR_DELETE also nulls out the passed in pointer. PR_DELETE(d); return isOk ? NS_OK : ConvertWinError(GetLastError()); } //----------------------------------------------------------------------------- @@ -960,20 +957,18 @@ nsLocalFile::nsLocalFile() , mResolveDirty(true) , mFollowSymlinks(false) { } nsresult nsLocalFile::nsLocalFileConstructor(nsISupports* outer, const nsIID& aIID, void* *aInstancePtr) { - if (NS_WARN_IF(!aInstancePtr)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_ARG_POINTER(aInstancePtr); + NS_ENSURE_NO_AGGREGATION(outer); nsLocalFile* inst = new nsLocalFile(); if (inst == nullptr) return NS_ERROR_OUT_OF_MEMORY; nsresult rv = inst->QueryInterface(aIID, aInstancePtr); if (NS_FAILED(rv)) { @@ -1149,18 +1144,17 @@ nsLocalFile::Clone(nsIFile **file) NS_ADDREF(*file); return NS_OK; } NS_IMETHODIMP nsLocalFile::InitWithFile(nsIFile *aFile) { - if (NS_WARN_IF(!aFile)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aFile); nsAutoString path; aFile->GetPath(path); if (path.IsEmpty()) return NS_ERROR_INVALID_ARG; return InitWithPath(path); } @@ -2073,41 +2067,38 @@ nsLocalFile::CopyMove(nsIFile *aParentDi file->IsSymlink(&isLink); if (move) { if (followSymlinks) return NS_ERROR_FAILURE; rv = file->MoveTo(target, EmptyString()); - if (NS_FAILED(rv)) - return rv; + NS_ENSURE_SUCCESS(rv,rv); } else { if (followSymlinks) rv = file->CopyToFollowingLinks(target, EmptyString()); else rv = file->CopyTo(target, EmptyString()); - if (NS_FAILED(rv)) - return rv; + NS_ENSURE_SUCCESS(rv,rv); } } } // we've finished moving all the children of this directory // in the new directory. so now delete the directory // note, we don't need to do a recursive delete. // MoveTo() is recursive. At this point, // we've already moved the children of the current folder // to the new location. nothing should be left in the folder. if (move) { rv = Remove(false /* recursive */); - if (NS_FAILED(rv)) - return rv; + NS_ENSURE_SUCCESS(rv,rv); } } // If we moved, we want to adjust this. if (move) { MakeDirty(); @@ -2262,18 +2253,17 @@ nsLocalFile::Remove(bool recursive) } NS_IMETHODIMP nsLocalFile::GetLastModifiedTime(PRTime *aLastModifiedTime) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!aLastModifiedTime)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aLastModifiedTime); // get the modified time of the target as determined by mFollowSymlinks // If true, then this will be for the target of the shortcut file, // otherwise it will be for the shortcut file itself (i.e. the same // results as GetLastModifiedTimeOfLink) nsresult rv = ResolveAndStat(); if (NS_FAILED(rv)) @@ -2286,18 +2276,17 @@ nsLocalFile::GetLastModifiedTime(PRTime NS_IMETHODIMP nsLocalFile::GetLastModifiedTimeOfLink(PRTime *aLastModifiedTime) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!aLastModifiedTime)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aLastModifiedTime); // The caller is assumed to have already called IsSymlink // and to have found that this file is a link. PRFileInfo64 info; nsresult rv = GetFileInfo(mWorkingPath, &info); if (NS_FAILED(rv)) return rv; @@ -2387,18 +2376,17 @@ nsLocalFile::SetModDate(PRTime aLastModi CloseHandle(file); return rv; } NS_IMETHODIMP nsLocalFile::GetPermissions(uint32_t *aPermissions) { - if (NS_WARN_IF(!aPermissions)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aPermissions); // get the permissions of the target as determined by mFollowSymlinks // If true, then this will be for the target of the shortcut file, // otherwise it will be for the shortcut file itself (i.e. the same // results as GetPermissionsOfLink) nsresult rv = ResolveAndStat(); if (NS_FAILED(rv)) return rv; @@ -2417,18 +2405,17 @@ nsLocalFile::GetPermissions(uint32_t *aP } NS_IMETHODIMP nsLocalFile::GetPermissionsOfLink(uint32_t *aPermissions) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!aPermissions)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aPermissions); // The caller is assumed to have already called IsSymlink // and to have found that this file is a link. It is not // possible for a link file to be executable. DWORD word = ::GetFileAttributesW(mWorkingPath.get()); if (word == INVALID_FILE_ATTRIBUTES) return NS_ERROR_FILE_INVALID_PATH; @@ -2487,36 +2474,34 @@ nsLocalFile::SetPermissionsOfLink(uint32 return NS_OK; } NS_IMETHODIMP nsLocalFile::GetFileSize(int64_t *aFileSize) { - if (NS_WARN_IF(!aFileSize)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aFileSize); nsresult rv = ResolveAndStat(); if (NS_FAILED(rv)) return rv; *aFileSize = mFileInfo64.size; return NS_OK; } NS_IMETHODIMP nsLocalFile::GetFileSizeOfLink(int64_t *aFileSize) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!aFileSize)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aFileSize); // The caller is assumed to have already called IsSymlink // and to have found that this file is a link. PRFileInfo64 info; if (NS_FAILED(GetFileInfo(mWorkingPath, &info))) return NS_ERROR_FILE_INVALID_PATH; @@ -2561,18 +2546,17 @@ nsLocalFile::SetFileSize(int64_t aFileSi } NS_IMETHODIMP nsLocalFile::GetDiskSpaceAvailable(int64_t *aDiskSpaceAvailable) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!aDiskSpaceAvailable)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aDiskSpaceAvailable); ResolveAndStat(); if (mFileInfo64.type == PR_FILE_FILE) { // Since GetDiskFreeSpaceExW works only on directories, use the parent. nsCOMPtr<nsIFile> parent; if (NS_SUCCEEDED(GetParent(getter_AddRefs(parent))) && parent) { return parent->GetDiskSpaceAvailable(aDiskSpaceAvailable); @@ -2591,18 +2575,17 @@ nsLocalFile::GetDiskSpaceAvailable(int64 } NS_IMETHODIMP nsLocalFile::GetParent(nsIFile * *aParent) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!aParent)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aParent); // A two-character path must be a drive such as C:, so it has no parent if (mWorkingPath.Length() == 2) { *aParent = nullptr; return NS_OK; } int32_t offset = mWorkingPath.RFindChar(PRUnichar('\\')); @@ -2636,18 +2619,17 @@ nsLocalFile::GetParent(nsIFile * *aParen } NS_IMETHODIMP nsLocalFile::Exists(bool *_retval) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(_retval); *_retval = false; MakeDirty(); nsresult rv = ResolveAndStat(); *_retval = NS_SUCCEEDED(rv) || rv == NS_ERROR_FILE_IS_LOCKED; return NS_OK; } @@ -2707,18 +2689,17 @@ nsLocalFile::IsWritable(bool *aIsWritabl } NS_IMETHODIMP nsLocalFile::IsReadable(bool *_retval) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(_retval); *_retval = false; nsresult rv = ResolveAndStat(); if (NS_FAILED(rv)) return rv; *_retval = true; return NS_OK; @@ -2726,18 +2707,17 @@ nsLocalFile::IsReadable(bool *_retval) NS_IMETHODIMP nsLocalFile::IsExecutable(bool *_retval) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(_retval); *_retval = false; nsresult rv; // only files can be executables bool isFile; rv = IsFile(&isFile); if (NS_FAILED(rv)) @@ -2882,18 +2862,17 @@ NS_IMETHODIMP nsLocalFile::IsHidden(bool *_retval) { return HasFileAttribute(FILE_ATTRIBUTE_HIDDEN, _retval); } nsresult nsLocalFile::HasFileAttribute(DWORD fileAttrib, bool *_retval) { - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(_retval); nsresult rv = Resolve(); if (NS_FAILED(rv)) { return rv; } DWORD attributes = GetFileAttributesW(mResolvedPath.get()); if (INVALID_FILE_ATTRIBUTES == attributes) { @@ -2905,18 +2884,17 @@ nsLocalFile::HasFileAttribute(DWORD file } NS_IMETHODIMP nsLocalFile::IsSymlink(bool *_retval) { // Check we are correctly initialized. CHECK_mWorkingPath(); - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(_retval); // unless it is a valid shortcut path it's not a symlink if (!IsShortcutPath(mWorkingPath)) { *_retval = false; return NS_OK; } // we need to know if this is a file or directory @@ -2937,20 +2915,18 @@ NS_IMETHODIMP nsLocalFile::IsSpecial(bool *_retval) { return HasFileAttribute(FILE_ATTRIBUTE_SYSTEM, _retval); } NS_IMETHODIMP nsLocalFile::Equals(nsIFile *inFile, bool *_retval) { - if (NS_WARN_IF(!inFile)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(inFile); + NS_ENSURE_ARG(_retval); EnsureShortPath(); nsCOMPtr<nsILocalFileWin> lf(do_QueryInterface(inFile)); if (!lf) { *_retval = false; return NS_OK; }
--- a/xpcom/io/nsMultiplexInputStream.cpp +++ b/xpcom/io/nsMultiplexInputStream.cpp @@ -113,16 +113,17 @@ nsMultiplexInputStream::AppendStream(nsI } /* void insertStream (in nsIInputStream stream, in unsigned long index); */ NS_IMETHODIMP nsMultiplexInputStream::InsertStream(nsIInputStream *aStream, uint32_t aIndex) { NS_ASSERTION(SeekableStreamAtBeginning(aStream), "Inserted stream not at beginning."); bool result = mStreams.InsertElementAt(aIndex, aStream); + NS_ENSURE_TRUE(result, NS_ERROR_OUT_OF_MEMORY); if (mCurrentStream > aIndex || (mCurrentStream == aIndex && mStartedReadingCurrent)) ++mCurrentStream; return NS_OK; } /* void removeStream (in unsigned long index); */ NS_IMETHODIMP @@ -137,18 +138,17 @@ nsMultiplexInputStream::RemoveStream(uin return NS_OK; } /* nsIInputStream getStream (in unsigned long index); */ NS_IMETHODIMP nsMultiplexInputStream::GetStream(uint32_t aIndex, nsIInputStream **_retval) { *_retval = mStreams.SafeElementAt(aIndex, nullptr); - if (NS_WARN_IF(!*_retval)) - return NS_ERROR_NOT_AVAILABLE; + NS_ENSURE_TRUE(*_retval, NS_ERROR_NOT_AVAILABLE); NS_ADDREF(*_retval); return NS_OK; } /* void close (); */ NS_IMETHODIMP nsMultiplexInputStream::Close() @@ -176,18 +176,17 @@ nsMultiplexInputStream::Available(uint64 nsresult rv; uint64_t avail = 0; uint32_t len = mStreams.Length(); for (uint32_t i = mCurrentStream; i < len; i++) { uint64_t streamAvail; rv = mStreams[i]->Available(&streamAvail); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); avail += streamAvail; } *_retval = avail; return NS_OK; } /* [noscript] unsigned long read (in charPtr buf, in unsigned long count); */ NS_IMETHODIMP @@ -324,18 +323,17 @@ nsMultiplexInputStream::IsNonBlocking(bo // On the other hand we'll never return NS_BASE_STREAM_WOULD_BLOCK, // so maybe we should claim to be blocking? It probably doesn't // matter in practice. *aNonBlocking = true; return NS_OK; } for (uint32_t i = 0; i < len; ++i) { nsresult rv = mStreams[i]->IsNonBlocking(aNonBlocking); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // If one is non-blocking the entire stream becomes non-blocking // (except that we don't implement nsIAsyncInputStream, so there's // not much for the caller to do if Read returns "would block") if (*aNonBlocking) return NS_OK; } return NS_OK; } @@ -364,65 +362,60 @@ nsMultiplexInputStream::Seek(int32_t aWh return NS_ERROR_FAILURE; } // See if all remaining streams should be rewound if (remaining == 0) { if (i < oldCurrentStream || (i == oldCurrentStream && oldStartedReadingCurrent)) { rv = stream->Seek(NS_SEEK_SET, 0); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); continue; } else { break; } } // Get position in current stream int64_t streamPos; if (i > oldCurrentStream || (i == oldCurrentStream && !oldStartedReadingCurrent)) { streamPos = 0; } else { rv = stream->Tell(&streamPos); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } // See if we need to seek current stream forward or backward if (remaining < streamPos) { rv = stream->Seek(NS_SEEK_SET, remaining); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mCurrentStream = i; mStartedReadingCurrent = remaining != 0; remaining = 0; } else if (remaining > streamPos) { if (i < oldCurrentStream) { // We're already at end so no need to seek this stream remaining -= streamPos; NS_ASSERTION(remaining >= 0, "Remaining invalid"); } else { uint64_t avail; rv = mStreams[i]->Available(&avail); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); int64_t newPos = XPCOM_MIN(remaining, streamPos + (int64_t)avail); rv = stream->Seek(NS_SEEK_SET, newPos); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mCurrentStream = i; mStartedReadingCurrent = true; remaining -= newPos; NS_ASSERTION(remaining >= 0, "Remaining invalid"); } } @@ -438,24 +431,22 @@ nsMultiplexInputStream::Seek(int32_t aWh if (aWhence == NS_SEEK_CUR && aOffset > 0) { int64_t remaining = aOffset; for (uint32_t i = mCurrentStream; remaining && i < mStreams.Length(); ++i) { nsCOMPtr<nsISeekableStream> stream = do_QueryInterface(mStreams[i]); uint64_t avail; rv = mStreams[i]->Available(&avail); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); int64_t seek = XPCOM_MIN((int64_t)avail, remaining); rv = stream->Seek(NS_SEEK_CUR, seek); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mCurrentStream = i; mStartedReadingCurrent = true; remaining -= seek; } return NS_OK; @@ -464,24 +455,22 @@ nsMultiplexInputStream::Seek(int32_t aWh if (aWhence == NS_SEEK_CUR && aOffset < 0) { int64_t remaining = -aOffset; for (uint32_t i = mCurrentStream; remaining && i != (uint32_t)-1; --i) { nsCOMPtr<nsISeekableStream> stream = do_QueryInterface(mStreams[i]); int64_t pos; rv = stream->Tell(&pos); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); int64_t seek = XPCOM_MIN(pos, remaining); rv = stream->Seek(NS_SEEK_CUR, -seek); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mCurrentStream = i; mStartedReadingCurrent = seek != -pos; remaining -= seek; } return NS_OK; @@ -501,63 +490,58 @@ nsMultiplexInputStream::Seek(int32_t aWh for (uint32_t i = mStreams.Length() - 1; i != (uint32_t)-1; --i) { nsCOMPtr<nsISeekableStream> stream = do_QueryInterface(mStreams[i]); // See if all remaining streams should be seeked to end if (remaining == 0) { if (i >= oldCurrentStream) { rv = stream->Seek(NS_SEEK_END, 0); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } else { break; } } // Get position in current stream int64_t streamPos; if (i < oldCurrentStream) { streamPos = 0; } else { uint64_t avail; rv = mStreams[i]->Available(&avail); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); streamPos = avail; } // See if we have enough data in the current stream. if (DeprecatedAbs(remaining) < streamPos) { rv = stream->Seek(NS_SEEK_END, remaining); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mCurrentStream = i; mStartedReadingCurrent = true; remaining = 0; } else if (DeprecatedAbs(remaining) > streamPos) { if (i > oldCurrentStream || (i == oldCurrentStream && !oldStartedReadingCurrent)) { // We're already at start so no need to seek this stream remaining += streamPos; } else { int64_t avail; rv = stream->Tell(&avail); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); int64_t newPos = streamPos + XPCOM_MIN(avail, DeprecatedAbs(remaining)); rv = stream->Seek(NS_SEEK_END, -newPos); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mCurrentStream = i; mStartedReadingCurrent = true; remaining += newPos; } } else { @@ -581,23 +565,21 @@ nsMultiplexInputStream::Tell(int64_t *_r return mStatus; nsresult rv; int64_t ret64 = 0; uint32_t i, last; last = mStartedReadingCurrent ? mCurrentStream+1 : mCurrentStream; for (i = 0; i < last; ++i) { nsCOMPtr<nsISeekableStream> stream = do_QueryInterface(mStreams[i]); - if (NS_WARN_IF(!stream)) - return NS_ERROR_NO_INTERFACE; + NS_ENSURE_TRUE(stream, NS_ERROR_NO_INTERFACE); int64_t pos; rv = stream->Tell(&pos); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); ret64 += pos; } *_retval = ret64; return NS_OK; } /* void setEOF (); */
--- a/xpcom/io/nsPipe3.cpp +++ b/xpcom/io/nsPipe3.cpp @@ -351,18 +351,17 @@ nsPipe::GetInputStream(nsIAsyncInputStre { NS_ADDREF(*aInputStream = &mInput); return NS_OK; } NS_IMETHODIMP nsPipe::GetOutputStream(nsIAsyncOutputStream **aOutputStream) { - if (NS_WARN_IF(!mInited)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mInited, NS_ERROR_NOT_INITIALIZED); NS_ADDREF(*aOutputStream = &mOutput); return NS_OK; } void nsPipe::PeekSegment(uint32_t index, char *&cursor, char *&limit) { if (index == 0) {
--- a/xpcom/io/nsStorageStream.cpp +++ b/xpcom/io/nsStorageStream.cpp @@ -83,20 +83,18 @@ nsStorageStream::Init(uint32_t segmentSi return mSegmentedBuffer->Init(segmentSize, maxSize, segmentAllocator); } NS_IMETHODIMP nsStorageStream::GetOutputStream(int32_t aStartingOffset, nsIOutputStream * *aOutputStream) { - if (NS_WARN_IF(!aOutputStream)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(!mSegmentedBuffer)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_ARG(aOutputStream); + NS_ENSURE_TRUE(mSegmentedBuffer, NS_ERROR_NOT_INITIALIZED); if (mWriteInProgress) return NS_ERROR_NOT_AVAILABLE; nsresult rv = Seek(aStartingOffset); if (NS_FAILED(rv)) return rv; // Enlarge the last segment in the buffer so that it is the same size as @@ -113,18 +111,17 @@ nsStorageStream::GetOutputStream(int32_t *aOutputStream = static_cast<nsIOutputStream*>(this); mWriteInProgress = true; return NS_OK; } NS_IMETHODIMP nsStorageStream::Close() { - if (NS_WARN_IF(!mSegmentedBuffer)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSegmentedBuffer, NS_ERROR_NOT_INITIALIZED); mWriteInProgress = false; int32_t segmentOffset = SegOffset(mLogicalLength); // Shrink the final segment in the segmented buffer to the minimum size // needed to contain the data, so as to conserve memory. if (segmentOffset) @@ -143,25 +140,25 @@ NS_IMETHODIMP nsStorageStream::Flush() { return NS_OK; } NS_IMETHODIMP nsStorageStream::Write(const char *aBuffer, uint32_t aCount, uint32_t *aNumWritten) { - if (NS_WARN_IF(!aNumWritten) || NS_WARN_IF(!aBuffer)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(!mSegmentedBuffer)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSegmentedBuffer, NS_ERROR_NOT_INITIALIZED); const char* readCursor; uint32_t count, availableInSegment, remaining; nsresult rv = NS_OK; + NS_ENSURE_ARG_POINTER(aNumWritten); + NS_ENSURE_ARG(aBuffer); + LOG(("nsStorageStream [%p] Write mWriteCursor=%x mSegmentEnd=%x aCount=%d\n", this, mWriteCursor, mSegmentEnd, aCount)); remaining = aCount; readCursor = aBuffer; // If no segments have been created yet, create one even if we don't have // to write any data; this enables creating an input stream which reads from // the very end of the data for any amount of data in the stream (i.e. @@ -221,26 +218,26 @@ nsStorageStream::IsNonBlocking(bool *aNo { *aNonBlocking = false; return NS_OK; } NS_IMETHODIMP nsStorageStream::GetLength(uint32_t *aLength) { + NS_ENSURE_ARG(aLength); *aLength = mLogicalLength; return NS_OK; } // Truncate the buffer by deleting the end segments NS_IMETHODIMP nsStorageStream::SetLength(uint32_t aLength) { - if (NS_WARN_IF(!mSegmentedBuffer)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSegmentedBuffer, NS_ERROR_NOT_INITIALIZED); if (mWriteInProgress) return NS_ERROR_NOT_AVAILABLE; if (aLength > mLogicalLength) return NS_ERROR_INVALID_ARG; int32_t newLastSegmentNum = SegNum(aLength); @@ -255,25 +252,26 @@ nsStorageStream::SetLength(uint32_t aLen mLogicalLength = aLength; return NS_OK; } NS_IMETHODIMP nsStorageStream::GetWriteInProgress(bool *aWriteInProgress) { + NS_ENSURE_ARG(aWriteInProgress); + *aWriteInProgress = mWriteInProgress; return NS_OK; } NS_METHOD nsStorageStream::Seek(int32_t aPosition) { - if (NS_WARN_IF(!mSegmentedBuffer)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSegmentedBuffer, NS_ERROR_NOT_INITIALIZED); // An argument of -1 means "seek to end of stream" if (aPosition == -1) aPosition = mLogicalLength; // Seeking beyond the buffer end is illegal if ((uint32_t)aPosition > mLogicalLength) return NS_ERROR_INVALID_ARG; @@ -355,18 +353,17 @@ private: NS_IMPL_ISUPPORTS2(nsStorageInputStream, nsIInputStream, nsISeekableStream) NS_IMETHODIMP nsStorageStream::NewInputStream(int32_t aStartingOffset, nsIInputStream* *aInputStream) { - if (NS_WARN_IF(!mSegmentedBuffer)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mSegmentedBuffer, NS_ERROR_NOT_INITIALIZED); nsStorageInputStream *inputStream = new nsStorageInputStream(this, mSegmentSize); if (!inputStream) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(inputStream); nsresult rv = inputStream->Seek(aStartingOffset); @@ -522,16 +519,18 @@ nsStorageInputStream::Seek(uint32_t aPos mSegmentEnd = mReadCursor + XPCOM_MIN(mSegmentSize - mReadCursor, available); mLogicalCursor = aPosition; return NS_OK; } nsresult NS_NewStorageStream(uint32_t segmentSize, uint32_t maxSize, nsIStorageStream **result) { + NS_ENSURE_ARG(result); + nsStorageStream* storageStream = new nsStorageStream(); if (!storageStream) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(storageStream); nsresult rv = storageStream->Init(segmentSize, maxSize, nullptr); if (NS_FAILED(rv)) { NS_RELEASE(storageStream); return rv;
--- a/xpcom/io/nsStringStream.cpp +++ b/xpcom/io/nsStringStream.cpp @@ -107,18 +107,17 @@ nsStringInputStream::GetType(uint16_t *t } NS_IMETHODIMP nsStringInputStream::GetData(nsACString &data) { // The stream doesn't have any data when it is closed. We could fake it // and return an empty string here, but it seems better to keep this return // value consistent with the behavior of the other 'getter' methods. - if (NS_WARN_IF(Closed())) - return NS_BASE_STREAM_CLOSED; + NS_ENSURE_TRUE(!Closed(), NS_BASE_STREAM_CLOSED); data.Assign(mData); return NS_OK; } NS_IMETHODIMP nsStringInputStream::SetData(const nsACString &data) { @@ -136,38 +135,35 @@ nsStringInputStream::ToString(char **res ///////// // nsIStringInputStream implementation ///////// NS_IMETHODIMP nsStringInputStream::SetData(const char *data, int32_t dataLen) { - if (NS_WARN_IF(!data)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(data); mData.Assign(data, dataLen); mOffset = 0; return NS_OK; } NS_IMETHODIMP nsStringInputStream::AdoptData(char *data, int32_t dataLen) { - if (NS_WARN_IF(!data)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(data); mData.Adopt(data, dataLen); mOffset = 0; return NS_OK; } NS_IMETHODIMP nsStringInputStream::ShareData(const char *data, int32_t dataLen) { - if (NS_WARN_IF(!data)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(data); if (dataLen < 0) dataLen = strlen(data); mData.Rebind(data, dataLen); mOffset = 0; return NS_OK; } @@ -261,18 +257,18 @@ nsStringInputStream::Seek(int32_t whence case NS_SEEK_END: newPos += Length(); break; default: NS_ERROR("invalid whence"); return NS_ERROR_INVALID_ARG; } - if (NS_WARN_IF(newPos < 0) || NS_WARN_IF(newPos > Length())) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(newPos >= 0); + NS_ENSURE_ARG(newPos <= Length()); mOffset = (uint32_t)newPos; return NS_OK; } NS_IMETHODIMP nsStringInputStream::Tell(int64_t* outWhere) { @@ -385,18 +381,17 @@ NS_NewCStringInputStream(nsIInputStream* } // factory method for constructing a nsStringInputStream object nsresult nsStringInputStreamConstructor(nsISupports *outer, REFNSIID iid, void **result) { *result = nullptr; - if (NS_WARN_IF(outer)) - return NS_ERROR_NO_AGGREGATION; + NS_ENSURE_TRUE(!outer, NS_ERROR_NO_AGGREGATION); nsStringInputStream *inst = new nsStringInputStream(); if (!inst) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(inst); nsresult rv = inst->QueryInterface(iid, result); NS_RELEASE(inst);
--- a/xpcom/reflect/xptcall/src/xptcall.cpp +++ b/xpcom/reflect/xptcall/src/xptcall.cpp @@ -35,23 +35,21 @@ nsXPTCStubBase::Release() { return mOuter->Release(); } EXPORT_XPCOM_API(nsresult) NS_GetXPTCallStub(REFNSIID aIID, nsIXPTCProxy* aOuter, nsISomeInterface* *aResult) { - if (NS_WARN_IF(!aOuter) || NS_WARN_IF(!aResult)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG(aOuter && aResult); XPTInterfaceInfoManager *iim = XPTInterfaceInfoManager::GetSingleton(); - if (NS_WARN_IF(!iim)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(iim, NS_ERROR_NOT_INITIALIZED); xptiInterfaceEntry *iie = iim->GetInterfaceEntryForIID(&aIID); if (!iie || !iie->EnsureResolved() || iie->GetBuiltinClassFlag()) return NS_ERROR_FAILURE; nsXPTCStubBase* newbase = new nsXPTCStubBase(aOuter, iie); if (!newbase) return NS_ERROR_OUT_OF_MEMORY;
--- a/xpcom/threads/LazyIdleThread.cpp +++ b/xpcom/threads/LazyIdleThread.cpp @@ -142,36 +142,31 @@ LazyIdleThread::EnsureThread() MOZ_ASSERT(!mIdleTimer, "Should have killed this long ago!"); MOZ_ASSERT(!mThreadIsShuttingDown, "Should have cleared that!"); nsresult rv; if (mShutdownMethod == AutomaticShutdown && NS_IsMainThread()) { nsCOMPtr<nsIObserverService> obs = do_GetService(NS_OBSERVERSERVICE_CONTRACTID, &rv); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = obs->AddObserver(this, "xpcom-shutdown-threads", false); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } mIdleTimer = do_CreateInstance(NS_TIMER_CONTRACTID, &rv); - if (NS_WARN_IF(!mIdleTimer)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_TRUE(mIdleTimer, NS_ERROR_FAILURE); nsCOMPtr<nsIRunnable> runnable = NS_NewRunnableMethod(this, &LazyIdleThread::InitThread); - if (NS_WARN_IF(!runnable)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_TRUE(runnable, NS_ERROR_FAILURE); rv = NS_NewThread(getter_AddRefs(mThread), runnable); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } void LazyIdleThread::InitThread() { char aLocal; @@ -268,24 +263,22 @@ LazyIdleThread::ShutdownThread() { MutexAutoLock lock(mMutex); MOZ_ASSERT(!mThreadIsShuttingDown, "Huh?!"); } #endif nsCOMPtr<nsIRunnable> runnable = NS_NewRunnableMethod(this, &LazyIdleThread::CleanupThread); - if (NS_WARN_IF(!runnable)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_TRUE(runnable, NS_ERROR_FAILURE); PreDispatch(); rv = mThread->Dispatch(runnable, NS_DISPATCH_NORMAL); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); // Put the temporary queue in place before calling Shutdown(). mQueuedRunnables = &queuedRunnables; if (NS_FAILED(mThread->Shutdown())) { NS_ERROR("Failed to shutdown the thread!"); } @@ -301,18 +294,17 @@ LazyIdleThread::ShutdownThread() MOZ_ASSERT(!mIdleNotificationCount, "Huh?!"); MOZ_ASSERT(mThreadIsShuttingDown, "Huh?!"); mThreadIsShuttingDown = false; } } if (mIdleTimer) { rv = mIdleTimer->Cancel(); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); mIdleTimer = nullptr; } // If our temporary queue has any runnables then we need to dispatch them. if (queuedRunnables.Length()) { // If the thread manager has gone away then these runnables will never run. if (mShutdown) { @@ -379,29 +371,27 @@ NS_IMPL_QUERY_INTERFACE5(LazyIdleThread, NS_IMETHODIMP LazyIdleThread::Dispatch(nsIRunnable* aEvent, uint32_t aFlags) { ASSERT_OWNING_THREAD(); // LazyIdleThread can't always support synchronous dispatch currently. - if (NS_WARN_IF(aFlags != NS_DISPATCH_NORMAL)) - return NS_ERROR_NOT_IMPLEMENTED; + NS_ENSURE_TRUE(aFlags == NS_DISPATCH_NORMAL, NS_ERROR_NOT_IMPLEMENTED); // If our thread is shutting down then we can't actually dispatch right now. // Queue this runnable for later. if (UseRunnableQueue()) { mQueuedRunnables->AppendElement(aEvent); return NS_OK; } nsresult rv = EnsureThread(); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); PreDispatch(); return mThread->Dispatch(aEvent, aFlags); } NS_IMETHODIMP LazyIdleThread::IsOnCurrentThread(bool* aIsOnCurrentThread) @@ -432,18 +422,17 @@ LazyIdleThread::Shutdown() mShutdown = true; nsresult rv = ShutdownThread(); MOZ_ASSERT(!mThread, "Should have destroyed this by now!"); mIdleObserver = nullptr; - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } NS_IMETHODIMP LazyIdleThread::HasPendingEvents(bool* aHasPendingEvents) { // This is only supposed to be called from the thread itself so it's not @@ -473,18 +462,17 @@ LazyIdleThread::Notify(nsITimer* aTimer) if (mPendingEventCount || mIdleNotificationCount) { // Another event was scheduled since this timer was set. Don't do // anything and wait for the timer to fire again. return NS_OK; } } nsresult rv = ShutdownThread(); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); return NS_OK; } NS_IMETHODIMP LazyIdleThread::OnDispatchedEvent(nsIThreadInternal* /*aThread */) { MOZ_ASSERT(NS_GetCurrentThread() == mOwningThread, "Wrong thread!"); @@ -520,22 +508,20 @@ LazyIdleThread::AfterProcessNextEvent(ns MOZ_ASSERT(mIdleNotificationCount < UINT32_MAX, "Way too many!"); mIdleNotificationCount++; } } if (shouldNotifyIdle) { nsCOMPtr<nsIRunnable> runnable = NS_NewRunnableMethod(this, &LazyIdleThread::ScheduleTimer); - if (NS_WARN_IF(!runnable)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_TRUE(runnable, NS_ERROR_FAILURE); nsresult rv = mOwningThread->Dispatch(runnable, NS_DISPATCH_NORMAL); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); } return NS_OK; } NS_IMETHODIMP LazyIdleThread::Observe(nsISupports* /* aSubject */, const char* aTopic,
--- a/xpcom/threads/nsEnvironment.cpp +++ b/xpcom/threads/nsEnvironment.cpp @@ -43,18 +43,17 @@ nsEnvironment::~nsEnvironment() { } NS_IMETHODIMP nsEnvironment::Exists(const nsAString& aName, bool *aOutValue) { nsAutoCString nativeName; nsresult rv = NS_CopyUnicodeToNative(aName, nativeName); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); nsAutoCString nativeVal; #if defined(XP_UNIX) /* For Unix/Linux platforms we follow the Unix definition: * An environment variable exists when |getenv()| returns a non-nullptr * value. An environment variable does not exist when |getenv()| returns * nullptr. */ @@ -74,18 +73,17 @@ nsEnvironment::Exists(const nsAString& a return NS_OK; } NS_IMETHODIMP nsEnvironment::Get(const nsAString& aName, nsAString& aOutValue) { nsAutoCString nativeName; nsresult rv = NS_CopyUnicodeToNative(aName, nativeName); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); nsAutoCString nativeVal; const char *value = PR_GetEnv(nativeName.get()); if (value && *value) { rv = NS_CopyNativeToUnicode(nsDependentCString(value), aOutValue); } else { aOutValue.Truncate(); rv = NS_OK; @@ -119,22 +117,20 @@ EnsureEnvHash() NS_IMETHODIMP nsEnvironment::Set(const nsAString& aName, const nsAString& aValue) { nsAutoCString nativeName; nsAutoCString nativeVal; nsresult rv = NS_CopyUnicodeToNative(aName, nativeName); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); rv = NS_CopyUnicodeToNative(aValue, nativeVal); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); MutexAutoLock lock(mLock); if (!EnsureEnvHash()){ return NS_ERROR_UNEXPECTED; } EnvEntryType* entry = gEnvHash->PutEntry(nativeName.get());
--- a/xpcom/threads/nsMemoryPressure.cpp +++ b/xpcom/threads/nsMemoryPressure.cpp @@ -44,10 +44,11 @@ NS_DispatchEventualMemoryPressure(Memory } } nsresult NS_DispatchMemoryPressure(MemoryPressureState state) { NS_DispatchEventualMemoryPressure(state); nsCOMPtr<nsIRunnable> event = new nsRunnable; + NS_ENSURE_TRUE(event, NS_ERROR_OUT_OF_MEMORY); return NS_DispatchToMainThread(event); }
--- a/xpcom/threads/nsProcessCommon.cpp +++ b/xpcom/threads/nsProcessCommon.cpp @@ -83,18 +83,17 @@ nsProcess::~nsProcess() } NS_IMETHODIMP nsProcess::Init(nsIFile* executable) { if (mExecutable) return NS_ERROR_ALREADY_INITIALIZED; - if (NS_WARN_IF(!executable)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(executable); bool isFile; //First make sure the file exists nsresult rv = executable->IsFile(&isFile); if (NS_FAILED(rv)) return rv; if (!isFile) return NS_ERROR_FAILURE; @@ -404,20 +403,18 @@ nsProcess::CopyArgsAndRunProcessw(bool b NS_Free(my_argv); return rv; } nsresult nsProcess::RunProcess(bool blocking, char **my_argv, nsIObserver* observer, bool holdWeak, bool argsUTF8) { - if (NS_WARN_IF(!mExecutable)) - return NS_ERROR_NOT_INITIALIZED; - if (NS_WARN_IF(mThread)) - return NS_ERROR_ALREADY_INITIALIZED; + NS_ENSURE_TRUE(mExecutable, NS_ERROR_NOT_INITIALIZED); + NS_ENSURE_FALSE(mThread, NS_ERROR_ALREADY_INITIALIZED); if (observer) { if (holdWeak) { mWeakObserver = do_GetWeakReference(observer); if (!mWeakObserver) return NS_NOINTERFACE; } else {
--- a/xpcom/threads/nsThread.cpp +++ b/xpcom/threads/nsThread.cpp @@ -147,19 +147,19 @@ NS_INTERFACE_MAP_BEGIN(nsThread) NS_INTERFACE_MAP_END NS_IMPL_CI_INTERFACE_GETTER4(nsThread, nsIThread, nsIThreadInternal, nsIEventTarget, nsISupportsPriority) //----------------------------------------------------------------------------- class nsThreadStartupEvent : public nsRunnable { public: - nsThreadStartupEvent() - : mMon("nsThreadStartupEvent.mMon") - , mInitialized(false) { + // Create a new thread startup object. + static nsThreadStartupEvent *Create() { + return new nsThreadStartupEvent(); } // This method does not return until the thread startup object is in the // completion state. void Wait() { if (mInitialized) // Maybe avoid locking... return; ReentrantMonitorAutoEnter mon(mMon); @@ -175,16 +175,21 @@ public: private: NS_IMETHOD Run() { ReentrantMonitorAutoEnter mon(mMon); mInitialized = true; mon.Notify(); return NS_OK; } + nsThreadStartupEvent() + : mMon("nsThreadStartupEvent.mMon") + , mInitialized(false) { + } + ReentrantMonitor mMon; bool mInitialized; }; //----------------------------------------------------------------------------- struct nsThreadShutdownContext { nsThread *joiningThread; @@ -300,17 +305,18 @@ nsThread::nsThread(MainThreadFlag aMainT nsThread::~nsThread() { } nsresult nsThread::Init() { // spawn thread and wait until it is fully setup - nsRefPtr<nsThreadStartupEvent> startup = new nsThreadStartupEvent(); + nsRefPtr<nsThreadStartupEvent> startup = nsThreadStartupEvent::Create(); + NS_ENSURE_TRUE(startup, NS_ERROR_OUT_OF_MEMORY); NS_ADDREF_THIS(); mShutdownRequired = true; // ThreadFunc is responsible for setting mThread PRThread *thr = PR_CreateThread(PR_USER_THREAD, ThreadFunc, this, PR_PRIORITY_NORMAL, PR_GLOBAL_THREAD, @@ -366,27 +372,25 @@ nsThread::PutEvent(nsIRunnable *event) //----------------------------------------------------------------------------- // nsIEventTarget NS_IMETHODIMP nsThread::Dispatch(nsIRunnable *event, uint32_t flags) { LOG(("THRD(%p) Dispatch [%p %x]\n", this, event, flags)); - if (NS_WARN_IF(!event)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(event); if (gXPCOMThreadsShutDown && MAIN_THREAD != mIsMainThread) { return NS_ERROR_ILLEGAL_DURING_SHUTDOWN; } if (flags & DISPATCH_SYNC) { nsThread *thread = nsThreadManager::get()->GetCurrentThread(); - if (NS_WARN_IF(!thread)) - return NS_ERROR_NOT_AVAILABLE; + NS_ENSURE_STATE(thread); // XXX we should be able to do something better here... we should // be able to monitor the slot occupied by this event and use // that to tell us when the event has been processed. nsRefPtr<nsThreadSyncDispatch> wrapper = new nsThreadSyncDispatch(thread, event); if (!wrapper) @@ -428,18 +432,17 @@ nsThread::Shutdown() LOG(("THRD(%p) shutdown\n", this)); // XXX If we make this warn, then we hit that warning at xpcom shutdown while // shutting down a thread in a thread pool. That happens b/c the thread // in the thread pool is already shutdown by the thread manager. if (!mThread) return NS_OK; - if (NS_WARN_IF(mThread == PR_GetCurrentThread())) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(mThread != PR_GetCurrentThread()); // Prevent multiple calls to this method { MutexAutoLock lock(mLock); if (!mShutdownRequired) return NS_ERROR_UNEXPECTED; mShutdownRequired = false; } @@ -482,18 +485,17 @@ nsThread::Shutdown() #endif return NS_OK; } NS_IMETHODIMP nsThread::HasPendingEvents(bool *result) { - if (NS_WARN_IF(PR_GetCurrentThread() != mThread)) - return NS_ERROR_NOT_SAME_THREAD; + NS_ENSURE_STATE(PR_GetCurrentThread() == mThread); *result = mEvents.GetEvent(false, nullptr); return NS_OK; } #ifdef MOZ_CANARY void canary_alarm_handler (int signum); @@ -541,18 +543,17 @@ void canary_alarm_handler (int signum) } \ PR_END_MACRO NS_IMETHODIMP nsThread::ProcessNextEvent(bool mayWait, bool *result) { LOG(("THRD(%p) ProcessNextEvent [%u %u]\n", this, mayWait, mRunningEvent)); - if (NS_WARN_IF(PR_GetCurrentThread() != mThread)) - return NS_ERROR_NOT_SAME_THREAD; + NS_ENSURE_STATE(PR_GetCurrentThread() == mThread); if (MAIN_THREAD == mIsMainThread && mayWait && !ShuttingDown()) HangMonitor::Suspend(); // Fire a memory pressure notification, if we're the main thread and one is // pending. if (MAIN_THREAD == mIsMainThread && !ShuttingDown()) { MemoryPressureState mpPending = NS_GetPendingMemoryPressure(); @@ -638,18 +639,17 @@ nsThread::GetPriority(int32_t *priority) { *priority = mPriority; return NS_OK; } NS_IMETHODIMP nsThread::SetPriority(int32_t priority) { - if (NS_WARN_IF(!mThread)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_STATE(mThread); // NSPR defines the following four thread priorities: // PR_PRIORITY_LOW // PR_PRIORITY_NORMAL // PR_PRIORITY_HIGH // PR_PRIORITY_URGENT // We map the priority values defined on nsISupportsPriority to these values. @@ -685,58 +685,54 @@ nsThread::GetObserver(nsIThreadObserver MutexAutoLock lock(mLock); NS_IF_ADDREF(*obs = mObserver); return NS_OK; } NS_IMETHODIMP nsThread::SetObserver(nsIThreadObserver *obs) { - if (NS_WARN_IF(PR_GetCurrentThread() != mThread)) - return NS_ERROR_NOT_SAME_THREAD; + NS_ENSURE_STATE(PR_GetCurrentThread() == mThread); MutexAutoLock lock(mLock); mObserver = obs; return NS_OK; } NS_IMETHODIMP nsThread::GetRecursionDepth(uint32_t *depth) { - if (NS_WARN_IF(PR_GetCurrentThread() != mThread)) - return NS_ERROR_NOT_SAME_THREAD; + NS_ENSURE_ARG_POINTER(depth); + NS_ENSURE_STATE(PR_GetCurrentThread() == mThread); *depth = mRunningEvent; return NS_OK; } NS_IMETHODIMP nsThread::AddObserver(nsIThreadObserver *observer) { - if (NS_WARN_IF(!observer)) - return NS_ERROR_INVALID_ARG; - if (NS_WARN_IF(PR_GetCurrentThread() != mThread)) - return NS_ERROR_NOT_SAME_THREAD; + NS_ENSURE_ARG_POINTER(observer); + NS_ENSURE_STATE(PR_GetCurrentThread() == mThread); NS_WARN_IF_FALSE(!mEventObservers.Contains(observer), "Adding an observer twice!"); if (!mEventObservers.AppendElement(observer)) { NS_WARNING("Out of memory!"); return NS_ERROR_OUT_OF_MEMORY; } return NS_OK; } NS_IMETHODIMP nsThread::RemoveObserver(nsIThreadObserver *observer) { - if (NS_WARN_IF(PR_GetCurrentThread() != mThread)) - return NS_ERROR_NOT_SAME_THREAD; + NS_ENSURE_STATE(PR_GetCurrentThread() == mThread); if (observer && !mEventObservers.RemoveElement(observer)) { NS_WARNING("Removing an observer that was never added!"); } return NS_OK; }
--- a/xpcom/threads/nsThreadManager.cpp +++ b/xpcom/threads/nsThreadManager.cpp @@ -212,18 +212,17 @@ nsThreadManager::GetCurrentThread() } NS_IMETHODIMP nsThreadManager::NewThread(uint32_t creationFlags, uint32_t stackSize, nsIThread **result) { // No new threads during Shutdown - if (NS_WARN_IF(!mInitialized)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mInitialized, NS_ERROR_NOT_INITIALIZED); nsThread *thr = new nsThread(nsThread::NOT_MAIN_THREAD, stackSize); if (!thr) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(thr); nsresult rv = thr->Init(); if (NS_FAILED(rv)) { @@ -238,47 +237,43 @@ nsThreadManager::NewThread(uint32_t crea *result = thr; return NS_OK; } NS_IMETHODIMP nsThreadManager::GetThreadFromPRThread(PRThread *thread, nsIThread **result) { // Keep this functioning during Shutdown - if (NS_WARN_IF(!mMainThread)) - return NS_ERROR_NOT_INITIALIZED; - if (NS_WARN_IF(!thread)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_TRUE(mMainThread, NS_ERROR_NOT_INITIALIZED); + NS_ENSURE_ARG_POINTER(thread); nsRefPtr<nsThread> temp; { MutexAutoLock lock(*mLock); mThreadsByPRThread.Get(thread, getter_AddRefs(temp)); } NS_IF_ADDREF(*result = temp); return NS_OK; } NS_IMETHODIMP nsThreadManager::GetMainThread(nsIThread **result) { // Keep this functioning during Shutdown - if (NS_WARN_IF(!mMainThread)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mMainThread, NS_ERROR_NOT_INITIALIZED); NS_ADDREF(*result = mMainThread); return NS_OK; } NS_IMETHODIMP nsThreadManager::GetCurrentThread(nsIThread **result) { // Keep this functioning during Shutdown - if (NS_WARN_IF(!mMainThread)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(mMainThread, NS_ERROR_NOT_INITIALIZED); *result = GetCurrentThread(); if (!*result) return NS_ERROR_OUT_OF_MEMORY; NS_ADDREF(*result); return NS_OK; } NS_IMETHODIMP
--- a/xpcom/threads/nsThreadPool.cpp +++ b/xpcom/threads/nsThreadPool.cpp @@ -87,18 +87,17 @@ nsThreadPool::PutEvent(nsIRunnable *even LOG(("THRD-P(%p) put [spawn=%d]\n", this, spawnThread)); if (!spawnThread) return NS_OK; nsCOMPtr<nsIThread> thread; nsThreadManager::get()->NewThread(0, nsIThreadManager::DEFAULT_STACK_SIZE, getter_AddRefs(thread)); - if (NS_WARN_IF(!thread)) - return NS_ERROR_UNEXPECTED; + NS_ENSURE_STATE(thread); bool killThread = false; { ReentrantMonitorAutoEnter mon(mEvents.GetReentrantMonitor()); if (mThreads.Count() < (int32_t) mThreadLimit) { mThreads.AppendObject(thread); } else { killThread = true; // okay, we don't need this thread anymore @@ -221,24 +220,22 @@ nsThreadPool::Run() return NS_OK; } NS_IMETHODIMP nsThreadPool::Dispatch(nsIRunnable *event, uint32_t flags) { LOG(("THRD-P(%p) dispatch [%p %x]\n", this, event, flags)); - if (NS_WARN_IF(mShutdown)) - return NS_ERROR_NOT_AVAILABLE; + NS_ENSURE_STATE(!mShutdown); if (flags & DISPATCH_SYNC) { nsCOMPtr<nsIThread> thread; nsThreadManager::get()->GetCurrentThread(getter_AddRefs(thread)); - if (NS_WARN_IF(!thread)) - return NS_ERROR_NOT_AVAILABLE; + NS_ENSURE_STATE(thread); nsRefPtr<nsThreadSyncDispatch> wrapper = new nsThreadSyncDispatch(thread, event); PutEvent(wrapper); while (wrapper->IsPending()) NS_ProcessNextEvent(thread); } else {
--- a/xpcom/threads/nsTimerImpl.cpp +++ b/xpcom/threads/nsTimerImpl.cpp @@ -312,26 +312,24 @@ void nsTimerImpl::Shutdown() nsTimerEvent::Shutdown(); } nsresult nsTimerImpl::InitCommon(uint32_t aType, uint32_t aDelay) { nsresult rv; - if (NS_WARN_IF(!gThread)) - return NS_ERROR_NOT_INITIALIZED; + NS_ENSURE_TRUE(gThread, NS_ERROR_NOT_INITIALIZED); if (!mEventTarget) { NS_ERROR("mEventTarget is NULL"); return NS_ERROR_NOT_INITIALIZED; } rv = gThread->Init(); - if (NS_WARN_IF(NS_FAILED(rv))) - return rv; + NS_ENSURE_SUCCESS(rv, rv); /** * In case of re-Init, both with and without a preceding Cancel, clear the * mCanceled flag and assign a new mGeneration. But first, remove any armed * timer from the timer thread's list. * * If we are racing with the timer thread to remove this timer and we lose, * the RemoveTimer call made here will fail to find this timer in the timer @@ -354,48 +352,45 @@ nsresult nsTimerImpl::InitCommon(uint32_ return gThread->AddTimer(this); } NS_IMETHODIMP nsTimerImpl::InitWithFuncCallback(nsTimerCallbackFunc aFunc, void *aClosure, uint32_t aDelay, uint32_t aType) { - if (NS_WARN_IF(!aFunc)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aFunc); ReleaseCallback(); mCallbackType = CALLBACK_TYPE_FUNC; mCallback.c = aFunc; mClosure = aClosure; return InitCommon(aType, aDelay); } NS_IMETHODIMP nsTimerImpl::InitWithCallback(nsITimerCallback *aCallback, uint32_t aDelay, uint32_t aType) { - if (NS_WARN_IF(!aCallback)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aCallback); ReleaseCallback(); mCallbackType = CALLBACK_TYPE_INTERFACE; mCallback.i = aCallback; NS_ADDREF(mCallback.i); return InitCommon(aType, aDelay); } NS_IMETHODIMP nsTimerImpl::Init(nsIObserver *aObserver, uint32_t aDelay, uint32_t aType) { - if (NS_WARN_IF(!aObserver)) - return NS_ERROR_INVALID_ARG; + NS_ENSURE_ARG_POINTER(aObserver); ReleaseCallback(); mCallbackType = CALLBACK_TYPE_OBSERVER; mCallback.o = aObserver; NS_ADDREF(mCallback.o); return InitCommon(aType, aDelay); } @@ -481,18 +476,18 @@ NS_IMETHODIMP nsTimerImpl::GetTarget(nsI { NS_IF_ADDREF(*aTarget = mEventTarget); return NS_OK; } NS_IMETHODIMP nsTimerImpl::SetTarget(nsIEventTarget* aTarget) { - if (NS_WARN_IF(mCallbackType != CALLBACK_TYPE_UNKNOWN)) - return NS_ERROR_ALREADY_INITIALIZED; + NS_ENSURE_TRUE(mCallbackType == CALLBACK_TYPE_UNKNOWN, + NS_ERROR_ALREADY_INITIALIZED); if (aTarget) mEventTarget = aTarget; else mEventTarget = static_cast<nsIEventTarget*>(NS_GetCurrentThread()); return NS_OK; }