From 0827bb1794e875925f58314b23a5884fb4b96962 Mon Sep 17 00:00:00 2001 From: Birunthan Mohanathas Date: Sat, 2 Aug 2014 13:44:06 -0700 Subject: [PATCH] Bug 1046841 - Convert xpcom/components/ to Gecko style. r=froydnj --- xpcom/components/ManifestParser.cpp | 379 ++-- xpcom/components/ManifestParser.h | 6 +- xpcom/components/Module.h | 6 +- xpcom/components/ModuleLoader.h | 2 +- xpcom/components/ModuleUtils.h | 13 +- xpcom/components/nsCategoryManager.cpp | 356 +-- xpcom/components/nsCategoryManager.h | 22 +- xpcom/components/nsCategoryManagerUtils.h | 6 +- xpcom/components/nsComponentManager.cpp | 2413 +++++++++++---------- xpcom/components/nsComponentManager.h | 485 +++-- xpcom/components/nsNativeModuleLoader.cpp | 252 +-- xpcom/components/nsNativeModuleLoader.h | 35 +- 12 files changed, 2086 insertions(+), 1889 deletions(-) diff --git a/xpcom/components/ManifestParser.cpp b/xpcom/components/ManifestParser.cpp index 00a2d471407e..3fc18a7daa60 100644 --- a/xpcom/components/ManifestParser.cpp +++ b/xpcom/components/ManifestParser.cpp @@ -69,76 +69,100 @@ struct ManifestDirective // Function to handle this directive. This isn't a union because C++ still // hasn't learned how to initialize unions in a sane way. - void (nsComponentManagerImpl::*mgrfunc) - (nsComponentManagerImpl::ManifestProcessingContext& cx, - int lineno, char *const * argv); - void (nsChromeRegistry::*regfunc) - (nsChromeRegistry::ManifestProcessingContext& cx, - int lineno, char *const *argv, - bool platform, bool contentaccessible); + void (nsComponentManagerImpl::*mgrfunc)( + nsComponentManagerImpl::ManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv); + void (nsChromeRegistry::*regfunc)( + nsChromeRegistry::ManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv, + bool aPlatform, bool aContentAccessible); #ifdef MOZ_B2G_LOADER // The function to handle the directive for XPT Only parsing. - void (*xptonlyfunc)(nsComponentManagerImpl::XPTOnlyManifestProcessingContext& cx, - int lineno, char *const * argv); + void (*xptonlyfunc)( + nsComponentManagerImpl::XPTOnlyManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv); #else - void *xptonlyfunc; + void* xptonlyfunc; #endif bool isContract; }; static const ManifestDirective kParsingTable[] = { - { "manifest", 1, false, true, true, false, - &nsComponentManagerImpl::ManifestManifest, nullptr, XPTONLY_MANIFEST }, - { "binary-component", 1, true, false, false, false, - &nsComponentManagerImpl::ManifestBinaryComponent, nullptr, nullptr }, - { "interfaces", 1, true, false, false, false, - &nsComponentManagerImpl::ManifestXPT, nullptr, XPTONLY_XPT }, - { "component", 2, true, false, false, false, - &nsComponentManagerImpl::ManifestComponent, nullptr, nullptr }, - { "contract", 2, true, false, false, false, - &nsComponentManagerImpl::ManifestContract, nullptr, nullptr, true}, - { "category", 3, true, false, false, false, - &nsComponentManagerImpl::ManifestCategory, nullptr, nullptr }, - { "content", 2, true, true, true, true, - nullptr, &nsChromeRegistry::ManifestContent, nullptr }, - { "locale", 3, true, true, true, false, - nullptr, &nsChromeRegistry::ManifestLocale, nullptr }, - { "skin", 3, false, true, true, false, - nullptr, &nsChromeRegistry::ManifestSkin, nullptr }, - { "overlay", 2, true, true, false, false, - nullptr, &nsChromeRegistry::ManifestOverlay, nullptr }, - { "style", 2, false, true, false, false, - nullptr, &nsChromeRegistry::ManifestStyle, nullptr }, - { "override", 2, true, true, true, false, - nullptr, &nsChromeRegistry::ManifestOverride, nullptr }, - { "resource", 2, true, true, false, false, - nullptr, &nsChromeRegistry::ManifestResource, nullptr } + { + "manifest", 1, false, true, true, false, + &nsComponentManagerImpl::ManifestManifest, nullptr, XPTONLY_MANIFEST + }, + { + "binary-component", 1, true, false, false, false, + &nsComponentManagerImpl::ManifestBinaryComponent, nullptr, nullptr + }, + { + "interfaces", 1, true, false, false, false, + &nsComponentManagerImpl::ManifestXPT, nullptr, XPTONLY_XPT + }, + { + "component", 2, true, false, false, false, + &nsComponentManagerImpl::ManifestComponent, nullptr, nullptr + }, + { + "contract", 2, true, false, false, false, + &nsComponentManagerImpl::ManifestContract, nullptr, nullptr, true + }, + { + "category", 3, true, false, false, false, + &nsComponentManagerImpl::ManifestCategory, nullptr, nullptr + }, + { + "content", 2, true, true, true, true, + nullptr, &nsChromeRegistry::ManifestContent, nullptr + }, + { + "locale", 3, true, true, true, false, + nullptr, &nsChromeRegistry::ManifestLocale, nullptr + }, + { + "skin", 3, false, true, true, false, + nullptr, &nsChromeRegistry::ManifestSkin, nullptr + }, + { + "overlay", 2, true, true, false, false, + nullptr, &nsChromeRegistry::ManifestOverlay, nullptr + }, + { + "style", 2, false, true, false, false, + nullptr, &nsChromeRegistry::ManifestStyle, nullptr + }, + { + "override", 2, true, true, true, false, + nullptr, &nsChromeRegistry::ManifestOverride, nullptr + }, + { + "resource", 2, true, true, false, false, + nullptr, &nsChromeRegistry::ManifestResource, nullptr + } }; static const char kWhitespace[] = "\t "; -static bool IsNewline(char c) +static bool +IsNewline(char aChar) { - return c == '\n' || c == '\r'; + return aChar == '\n' || aChar == '\r'; } namespace { struct AutoPR_smprintf_free { - AutoPR_smprintf_free(char* buf) - : mBuf(buf) - { - } + AutoPR_smprintf_free(char* aBuf) : mBuf(aBuf) {} ~AutoPR_smprintf_free() { - if (mBuf) + if (mBuf) { PR_smprintf_free(mBuf); + } } - operator char*() const { - return mBuf; - } + operator char*() const { return mBuf; } char* mBuf; }; @@ -149,7 +173,8 @@ struct AutoPR_smprintf_free * If we are pre-loading XPTs, this method may do nothing because the * console service is not initialized. */ -void LogMessage(const char* aMsg, ...) +void +LogMessage(const char* aMsg, ...) { if (!nsComponentManagerImpl::gComponentManager) { return; @@ -157,8 +182,9 @@ void LogMessage(const char* aMsg, ...) nsCOMPtr console = do_GetService(NS_CONSOLESERVICE_CONTRACTID); - if (!console) + if (!console) { return; + } va_list args; va_start(args, aMsg); @@ -174,15 +200,17 @@ void LogMessage(const char* aMsg, ...) * If we are pre-loading XPTs, this method may do nothing because the * console service is not initialized. */ -void LogMessageWithContext(FileLocation &aFile, - uint32_t aLineNumber, const char* aMsg, ...) +void +LogMessageWithContext(FileLocation& aFile, + uint32_t aLineNumber, const char* aMsg, ...) { va_list args; va_start(args, aMsg); AutoPR_smprintf_free formatted(PR_vsmprintf(aMsg, args)); va_end(args); - if (!formatted) + if (!formatted) { return; + } if (!nsComponentManagerImpl::gComponentManager) { return; @@ -203,15 +231,17 @@ void LogMessageWithContext(FileLocation &aFile, nsCOMPtr console = do_GetService(NS_CONSOLESERVICE_CONTRACTID); - if (!console) + if (!console) { return; + } nsresult rv = error->Init(NS_ConvertUTF8toUTF16(formatted), - NS_ConvertUTF8toUTF16(file), EmptyString(), - aLineNumber, 0, nsIScriptError::warningFlag, - "chrome registration"); - if (NS_FAILED(rv)) + NS_ConvertUTF8toUTF16(file), EmptyString(), + aLineNumber, 0, nsIScriptError::warningFlag, + "chrome registration"); + if (NS_FAILED(rv)) { return; + } console->LogMessage(error); } @@ -230,8 +260,9 @@ void LogMessageWithContext(FileLocation &aFile, static bool CheckFlag(const nsSubstring& aFlag, const nsSubstring& aData, bool& aResult) { - if (!StringBeginsWith(aData, aFlag)) + if (!StringBeginsWith(aData, aFlag)) { return false; + } if (aFlag.Length() == aData.Length()) { // the data is simply "flag", which is the same as "flag=yes" @@ -250,23 +281,24 @@ CheckFlag(const nsSubstring& aFlag, const nsSubstring& aData, bool& aResult) } switch (aData.CharAt(aFlag.Length() + 1)) { - case '1': - case 't': //true - case 'y': //yes - aResult = true; - return true; - - case '0': - case 'f': //false - case 'n': //no - aResult = false; - return true; + case '1': + case 't': //true + case 'y': //yes + aResult = true; + return true; + + case '0': + case 'f': //false + case 'n': //no + aResult = false; + return true; } return false; } -enum TriState { +enum TriState +{ eUnspecified, eBad, eOK @@ -288,28 +320,33 @@ static bool CheckStringFlag(const nsSubstring& aFlag, const nsSubstring& aData, const nsSubstring& aValue, TriState& aResult) { - if (aData.Length() < aFlag.Length() + 1) + if (aData.Length() < aFlag.Length() + 1) { return false; + } - if (!StringBeginsWith(aData, aFlag)) + if (!StringBeginsWith(aData, aFlag)) { return false; + } bool comparison = true; if (aData[aFlag.Length()] != '=') { if (aData[aFlag.Length()] == '!' && aData.Length() >= aFlag.Length() + 2 && - aData[aFlag.Length() + 1] == '=') + aData[aFlag.Length() + 1] == '=') { comparison = false; - else + } else { return false; + } } if (aResult != eOK) { - nsDependentSubstring testdata = Substring(aData, aFlag.Length() + (comparison ? 1 : 2)); - if (testdata.Equals(aValue)) + nsDependentSubstring testdata = + Substring(aData, aFlag.Length() + (comparison ? 1 : 2)); + if (testdata.Equals(aValue)) { aResult = comparison ? eOK : eBad; - else + } else { aResult = comparison ? eBad : eOK; + } } return true; @@ -340,15 +377,18 @@ static bool CheckVersionFlag(const nsString& aFlag, const nsString& aData, const nsString& aValue, TriState& aResult) { - if (aData.Length() < aFlag.Length() + 2) + if (aData.Length() < aFlag.Length() + 2) { return false; + } - if (!StringBeginsWith(aData, aFlag)) + if (!StringBeginsWith(aData, aFlag)) { return false; + } if (aValue.Length() == 0) { - if (aResult != eOK) + if (aResult != eOK) { aResult = eBad; + } return true; } @@ -356,49 +396,49 @@ CheckVersionFlag(const nsString& aFlag, const nsString& aData, nsAutoString testdata; switch (aData[aFlag.Length()]) { - case '=': - comparison = COMPARE_EQ; - testdata = Substring(aData, aFlag.Length() + 1); - break; - - case '<': - if (aData[aFlag.Length() + 1] == '=') { - comparison = COMPARE_EQ | COMPARE_LT; - testdata = Substring(aData, aFlag.Length() + 2); - } - else { - comparison = COMPARE_LT; + case '=': + comparison = COMPARE_EQ; testdata = Substring(aData, aFlag.Length() + 1); - } - break; + break; - case '>': - if (aData[aFlag.Length() + 1] == '=') { - comparison = COMPARE_EQ | COMPARE_GT; - testdata = Substring(aData, aFlag.Length() + 2); - } - else { - comparison = COMPARE_GT; - testdata = Substring(aData, aFlag.Length() + 1); - } - break; + case '<': + if (aData[aFlag.Length() + 1] == '=') { + comparison = COMPARE_EQ | COMPARE_LT; + testdata = Substring(aData, aFlag.Length() + 2); + } else { + comparison = COMPARE_LT; + testdata = Substring(aData, aFlag.Length() + 1); + } + break; - default: - return false; + case '>': + if (aData[aFlag.Length() + 1] == '=') { + comparison = COMPARE_EQ | COMPARE_GT; + testdata = Substring(aData, aFlag.Length() + 2); + } else { + comparison = COMPARE_GT; + testdata = Substring(aData, aFlag.Length() + 1); + } + break; + + default: + return false; } - if (testdata.Length() == 0) + if (testdata.Length() == 0) { return false; + } if (aResult != eOK) { int32_t c = mozilla::CompareVersions(NS_ConvertUTF16toUTF8(aValue).get(), NS_ConvertUTF16toUTF8(testdata).get()); if ((c == 0 && comparison & COMPARE_EQ) || - (c < 0 && comparison & COMPARE_LT) || - (c > 0 && comparison & COMPARE_GT)) + (c < 0 && comparison & COMPARE_LT) || + (c > 0 && comparison & COMPARE_GT)) { aResult = eOK; - else + } else { aResult = eBad; + } } return true; @@ -406,10 +446,11 @@ CheckVersionFlag(const nsString& aFlag, const nsString& aData, // In-place conversion of ascii characters to lower case static void -ToLowerCase(char* token) +ToLowerCase(char* aToken) { - for (; *token; ++token) - *token = NS_ToLower(*token); + for (; *aToken; ++aToken) { + *aToken = NS_ToLower(*aToken); + } } namespace { @@ -433,12 +474,14 @@ struct CachedDirective * parsing. */ void -ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOnly, bool aXPTOnly) +ParseManifest(NSLocationType aType, FileLocation& aFile, char* aBuf, + bool aChromeOnly, bool aXPTOnly) { - nsComponentManagerImpl::ManifestProcessingContext mgrcx(type, file, aChromeOnly); - nsChromeRegistry::ManifestProcessingContext chromecx(type, file); + nsComponentManagerImpl::ManifestProcessingContext mgrcx(aType, aFile, + aChromeOnly); + nsChromeRegistry::ManifestProcessingContext chromecx(aType, aFile); #ifdef MOZ_B2G_LOADER - nsComponentManagerImpl::XPTOnlyManifestProcessingContext xptonlycx(file); + nsComponentManagerImpl::XPTOnlyManifestProcessingContext xptonlycx(aFile); #endif nsresult rv; @@ -472,18 +515,21 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn if (xapp) { nsAutoCString s; rv = xapp->GetID(s); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { CopyUTF8toUTF16(s, appID); + } rv = xapp->GetVersion(s); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { CopyUTF8toUTF16(s, appVersion); + } rv = xapp->GetPlatformVersion(s); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { CopyUTF8toUTF16(s, geckoVersion); + } - nsCOMPtr xruntime (do_QueryInterface(xapp)); + nsCOMPtr xruntime(do_QueryInterface(xapp)); if (xruntime) { rv = xruntime->GetOS(s); if (NS_SUCCEEDED(rv)) { @@ -508,24 +554,26 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn OSVERSIONINFO info = { sizeof(OSVERSIONINFO) }; if (GetVersionEx(&info)) { nsTextFormatter::ssprintf(osVersion, MOZ_UTF16("%ld.%ld"), - info.dwMajorVersion, - info.dwMinorVersion); + info.dwMajorVersion, + info.dwMinorVersion); } #pragma warning(pop) #elif defined(MOZ_WIDGET_COCOA) SInt32 majorVersion = nsCocoaFeatures::OSXVersionMajor(); SInt32 minorVersion = nsCocoaFeatures::OSXVersionMinor(); nsTextFormatter::ssprintf(osVersion, NS_LITERAL_STRING("%ld.%ld").get(), - majorVersion, - minorVersion); + majorVersion, + minorVersion); #elif defined(MOZ_WIDGET_GTK) nsTextFormatter::ssprintf(osVersion, MOZ_UTF16("%ld.%ld"), - gtk_major_version, - gtk_minor_version); + gtk_major_version, + gtk_minor_version); #elif defined(MOZ_WIDGET_ANDROID) bool isTablet = false; if (mozilla::AndroidBridge::Bridge()) { - mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build$VERSION", "RELEASE", osVersion); + mozilla::AndroidBridge::Bridge()->GetStaticStringField("android/os/Build$VERSION", + "RELEASE", + osVersion); isTablet = mozilla::widget::android::GeckoAppShell::IsTablet(); } #endif @@ -534,8 +582,8 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn // at the end. nsTArray contracts; - char *token; - char *newline = buf; + char* token; + char* newline = aBuf; uint32_t line = 0; // outer loop tokenizes by newline @@ -544,12 +592,14 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn ++newline; ++line; } - if (!*newline) + if (!*newline) { break; + } token = newline; - while (*newline && !IsNewline(*newline)) + while (*newline && !IsNewline(*newline)) { ++newline; + } if (*newline) { *newline = '\0'; @@ -557,17 +607,20 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn } ++line; - if (*token == '#') // ignore lines that begin with # as comments + if (*token == '#') { // ignore lines that begin with # as comments continue; + } - char *whitespace = token; + char* whitespace = token; token = nsCRT::strtok(whitespace, kWhitespace, &whitespace); - if (!token) continue; + if (!token) { + continue; + } const ManifestDirective* directive = nullptr; for (const ManifestDirective* d = kParsingTable; - d < ArrayEnd(kParsingTable); - ++d) { + d < ArrayEnd(kParsingTable); + ++d) { if (!strcmp(d->directive, token) && (!aXPTOnly || d->xptonlyfunc)) { directive = d; @@ -576,21 +629,21 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn } if (!directive) { - LogMessageWithContext(file, line, + LogMessageWithContext(aFile, line, "Ignoring unrecognized chrome manifest directive '%s'.", token); continue; } - if (!directive->allowbootstrap && NS_BOOTSTRAPPED_LOCATION == type) { - LogMessageWithContext(file, line, + if (!directive->allowbootstrap && NS_BOOTSTRAPPED_LOCATION == aType) { + LogMessageWithContext(aFile, line, "Bootstrapped manifest not allowed to use '%s' directive.", token); continue; } - if (directive->componentonly && NS_SKIN_LOCATION == type) { - LogMessageWithContext(file, line, + if (directive->componentonly && NS_SKIN_LOCATION == aType) { + LogMessageWithContext(aFile, line, "Skin manifest not allowed to use '%s' directive.", token); continue; @@ -598,11 +651,12 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn NS_ASSERTION(directive->argc < 4, "Need to reset argv array length"); char* argv[4]; - for (int i = 0; i < directive->argc; ++i) + for (int i = 0; i < directive->argc; ++i) { argv[i] = nsCRT::strtok(whitespace, kWhitespace, &whitespace); + } if (!argv[directive->argc - 1]) { - LogMessageWithContext(file, line, + LogMessageWithContext(aFile, line, "Not enough arguments for chrome manifest directive '%s', expected %i.", token, directive->argc); continue; @@ -621,7 +675,8 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn bool platform = false; bool contentAccessible = false; - while (nullptr != (token = nsCRT::strtok(whitespace, kWhitespace, &whitespace)) && ok) { + while ((token = nsCRT::strtok(whitespace, kWhitespace, &whitespace)) && + ok) { ToLowerCase(token); NS_ConvertASCIItoUTF16 wtoken(token); @@ -644,18 +699,19 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn if (directive->contentflags && (CheckFlag(kPlatform, wtoken, platform) || - CheckFlag(kContentAccessible, wtoken, contentAccessible))) + CheckFlag(kContentAccessible, wtoken, contentAccessible))) { continue; + } bool xpcNativeWrappers = true; // Dummy for CheckFlag. if (CheckFlag(kXPCNativeWrappers, wtoken, xpcNativeWrappers)) { - LogMessageWithContext(file, line, + LogMessageWithContext(aFile, line, "Ignoring obsolete chrome registration modifier '%s'.", token); continue; } - LogMessageWithContext(file, line, + LogMessageWithContext(aFile, line, "Unrecognized chrome manifest modifier '%s'.", token); ok = false; @@ -670,8 +726,9 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn #ifdef MOZ_WIDGET_ANDROID stTablet == eBad || #endif - stABI == eBad) + stABI == eBad) { continue; + } #ifdef MOZ_B2G_LOADER if (aXPTOnly) { @@ -679,41 +736,41 @@ ParseManifest(NSLocationType type, FileLocation &file, char* buf, bool aChromeOn } else #endif /* MOZ_B2G_LOADER */ if (directive->regfunc) { - if (GeckoProcessType_Default != XRE_GetProcessType()) + if (GeckoProcessType_Default != XRE_GetProcessType()) { continue; + } if (!nsChromeRegistry::gChromeRegistry) { nsCOMPtr cr = mozilla::services::GetChromeRegistryService(); if (!nsChromeRegistry::gChromeRegistry) { - LogMessageWithContext(file, line, + LogMessageWithContext(aFile, line, "Chrome registry isn't available yet."); continue; } } - (nsChromeRegistry::gChromeRegistry->*(directive->regfunc)) - (chromecx, line, argv, platform, contentAccessible); - } - else if (directive->mgrfunc && (directive->ischrome || !aChromeOnly)) { + (nsChromeRegistry::gChromeRegistry->*(directive->regfunc))( + chromecx, line, argv, platform, contentAccessible); + } else if (directive->mgrfunc && (directive->ischrome || !aChromeOnly)) { if (directive->isContract) { CachedDirective* cd = contracts.AppendElement(); cd->lineno = line; cd->argv[0] = argv[0]; cd->argv[1] = argv[1]; + } else { + (nsComponentManagerImpl::gComponentManager->*(directive->mgrfunc))( + mgrcx, line, argv); } - else - (nsComponentManagerImpl::gComponentManager->*(directive->mgrfunc)) - (mgrcx, line, argv); } else { - LogMessageWithContext(file, line, - "No valid manifest directive."); + LogMessageWithContext(aFile, line, "No valid manifest directive."); } } for (uint32_t i = 0; i < contracts.Length(); ++i) { CachedDirective& d = contracts[i]; - nsComponentManagerImpl::gComponentManager->ManifestContract - (mgrcx, d.lineno, d.argv); + nsComponentManagerImpl::gComponentManager->ManifestContract(mgrcx, + d.lineno, + d.argv); } } diff --git a/xpcom/components/ManifestParser.h b/xpcom/components/ManifestParser.h index 61f70182deef..3f05bc3ebf5b 100644 --- a/xpcom/components/ManifestParser.h +++ b/xpcom/components/ManifestParser.h @@ -12,12 +12,12 @@ class nsIFile; -void ParseManifest(NSLocationType type, mozilla::FileLocation &file, - char* buf, bool aChromeOnly, bool aXPTOnly=false); +void ParseManifest(NSLocationType aType, mozilla::FileLocation& aFile, + char* aBuf, bool aChromeOnly, bool aXPTOnly = false); void LogMessage(const char* aMsg, ...); -void LogMessageWithContext(mozilla::FileLocation &aFile, +void LogMessageWithContext(mozilla::FileLocation& aFile, uint32_t aLineNumber, const char* aMsg, ...); #endif // ManifestParser_h diff --git a/xpcom/components/Module.h b/xpcom/components/Module.h index d2f3127f2e0d..445834f34750 100644 --- a/xpcom/components/Module.h +++ b/xpcom/components/Module.h @@ -25,8 +25,8 @@ struct Module struct CIDEntry; - typedef already_AddRefed (*GetFactoryProcPtr) - (const Module& module, const CIDEntry& entry); + typedef already_AddRefed (*GetFactoryProcPtr)( + const Module& module, const CIDEntry& entry); typedef nsresult (*ConstructorProcPtr)(nsISupports* aOuter, const nsIID& aIID, @@ -62,7 +62,7 @@ struct Module struct ContractIDEntry { const char* contractid; - nsID const * cid; + nsID const* cid; ProcessSelector processSelector; }; diff --git a/xpcom/components/ModuleLoader.h b/xpcom/components/ModuleLoader.h index ed991d6e1aba..a5db4c727a3c 100644 --- a/xpcom/components/ModuleLoader.h +++ b/xpcom/components/ModuleLoader.h @@ -34,7 +34,7 @@ class ModuleLoader : public nsISupports * to be loaded multiple times. The Module object should either be * statically or permanently allocated; it will not be freed. */ - virtual const Module* LoadModule(mozilla::FileLocation &aFile) = 0; + virtual const Module* LoadModule(mozilla::FileLocation& aFile) = 0; }; NS_DEFINE_STATIC_IID_ACCESSOR(ModuleLoader, MOZILLA_MODULELOADER_PSEUDO_IID) diff --git a/xpcom/components/ModuleUtils.h b/xpcom/components/ModuleUtils.h index d5944b2eb578..6291c97f0fe1 100644 --- a/xpcom/components/ModuleUtils.h +++ b/xpcom/components/ModuleUtils.h @@ -104,19 +104,16 @@ namespace mozilla { class GenericModule MOZ_FINAL : public nsIModule { - ~GenericModule() {} + ~GenericModule() {} public: - explicit GenericModule(const mozilla::Module* aData) - : mData(aData) - { - } + explicit GenericModule(const mozilla::Module* aData) : mData(aData) {} - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSIMODULE + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSIMODULE private: - const mozilla::Module* mData; + const mozilla::Module* mData; }; } // namespace mozilla diff --git a/xpcom/components/nsCategoryManager.cpp b/xpcom/components/nsCategoryManager.cpp index 3c5daf9f6a84..a5003a26f4ab 100644 --- a/xpcom/components/nsCategoryManager.cpp +++ b/xpcom/components/nsCategoryManager.cpp @@ -51,15 +51,15 @@ class nsIComponentLoaderManager; #define NS_CATEGORYMANAGER_ARENA_SIZE (1024 * 8) // pulled in from nsComponentManager.cpp -char* ArenaStrdup(const char* s, PLArenaPool* aArena); +char* ArenaStrdup(const char* aStr, PLArenaPool* aArena); // // BaseStringEnumerator is subclassed by EntryEnumerator and // CategoryEnumerator // class BaseStringEnumerator - : public nsISimpleEnumerator, - private nsIUTF8StringEnumerator + : public nsISimpleEnumerator + , private nsIUTF8StringEnumerator { public: NS_DECL_ISUPPORTS @@ -68,21 +68,24 @@ class BaseStringEnumerator protected: // Callback function for NS_QuickSort to sort mArray - static int SortCallback(const void *, const void *, void *); + static int SortCallback(const void*, const void*, void*); BaseStringEnumerator() - : mArray(nullptr), - mCount(0), - mSimpleCurItem(0), - mStringCurItem(0) { } + : mArray(nullptr) + , mCount(0) + , mSimpleCurItem(0) + , mStringCurItem(0) + { + } // A virtual destructor is needed here because subclasses of // BaseStringEnumerator do not implement their own Release() method. virtual ~BaseStringEnumerator() { - if (mArray) + if (mArray) { delete[] mArray; + } } void Sort(); @@ -93,56 +96,60 @@ class BaseStringEnumerator uint32_t mStringCurItem; }; -NS_IMPL_ISUPPORTS(BaseStringEnumerator, nsISimpleEnumerator, nsIUTF8StringEnumerator) +NS_IMPL_ISUPPORTS(BaseStringEnumerator, nsISimpleEnumerator, + nsIUTF8StringEnumerator) NS_IMETHODIMP -BaseStringEnumerator::HasMoreElements(bool *_retval) +BaseStringEnumerator::HasMoreElements(bool* aResult) { - *_retval = (mSimpleCurItem < mCount); + *aResult = (mSimpleCurItem < mCount); return NS_OK; } NS_IMETHODIMP -BaseStringEnumerator::GetNext(nsISupports **_retval) +BaseStringEnumerator::GetNext(nsISupports** aResult) { - if (mSimpleCurItem >= mCount) + if (mSimpleCurItem >= mCount) { return NS_ERROR_FAILURE; + } nsSupportsDependentCString* str = new nsSupportsDependentCString(mArray[mSimpleCurItem++]); - if (!str) + if (!str) { return NS_ERROR_OUT_OF_MEMORY; + } - *_retval = str; - NS_ADDREF(*_retval); + *aResult = str; + NS_ADDREF(*aResult); return NS_OK; } NS_IMETHODIMP -BaseStringEnumerator::HasMore(bool *_retval) +BaseStringEnumerator::HasMore(bool* aResult) { - *_retval = (mStringCurItem < mCount); + *aResult = (mStringCurItem < mCount); return NS_OK; } NS_IMETHODIMP -BaseStringEnumerator::GetNext(nsACString& _retval) +BaseStringEnumerator::GetNext(nsACString& aResult) { - if (mStringCurItem >= mCount) + if (mStringCurItem >= mCount) { return NS_ERROR_FAILURE; + } - _retval = nsDependentCString(mArray[mStringCurItem++]); + aResult = nsDependentCString(mArray[mStringCurItem++]); return NS_OK; } int -BaseStringEnumerator::SortCallback(const void *e1, const void *e2, - void * /*unused*/) +BaseStringEnumerator::SortCallback(const void* aE1, const void* aE2, + void* /*unused*/) { - char const *const *s1 = reinterpret_cast(e1); - char const *const *s2 = reinterpret_cast(e2); + char const* const* s1 = reinterpret_cast(aE1); + char const* const* s2 = reinterpret_cast(aE2); return strcmp(*s1, *s2); } @@ -163,17 +170,18 @@ class EntryEnumerator static EntryEnumerator* Create(nsTHashtable& aTable); private: - static PLDHashOperator - enumfunc_createenumerator(CategoryLeaf* aLeaf, void* userArg); + static PLDHashOperator enumfunc_createenumerator(CategoryLeaf* aLeaf, + void* aUserArg); }; PLDHashOperator -EntryEnumerator::enumfunc_createenumerator(CategoryLeaf* aLeaf, void* userArg) +EntryEnumerator::enumfunc_createenumerator(CategoryLeaf* aLeaf, void* aUserArg) { - EntryEnumerator* mythis = static_cast(userArg); - if (aLeaf->value) + EntryEnumerator* mythis = static_cast(aUserArg); + if (aLeaf->value) { mythis->mArray[mythis->mCount++] = aLeaf->GetKey(); + } return PL_DHASH_NEXT; } @@ -182,8 +190,9 @@ EntryEnumerator* EntryEnumerator::Create(nsTHashtable& aTable) { EntryEnumerator* enumObj = new EntryEnumerator(); - if (!enumObj) + if (!enumObj) { return nullptr; + } enumObj->mArray = new char const* [aTable.Count()]; if (!enumObj->mArray) { @@ -207,8 +216,9 @@ CategoryNode* CategoryNode::Create(PLArenaPool* aArena) { CategoryNode* node = new(aArena) CategoryNode(); - if (!node) + if (!node) { return nullptr; + } return node; } @@ -227,17 +237,17 @@ CategoryNode::operator new(size_t aSize, PLArenaPool* aArena) NS_METHOD CategoryNode::GetLeaf(const char* aEntryName, - char** _retval) + char** aResult) { MutexAutoLock lock(mLock); nsresult rv = NS_ERROR_NOT_AVAILABLE; - CategoryLeaf* ent = - mTable.GetEntry(aEntryName); + CategoryLeaf* ent = mTable.GetEntry(aEntryName); if (ent && ent->value) { - *_retval = NS_strdup(ent->value); - if (*_retval) + *aResult = NS_strdup(ent->value); + if (*aResult) { rv = NS_OK; + } } return rv; @@ -247,37 +257,42 @@ NS_METHOD CategoryNode::AddLeaf(const char* aEntryName, const char* aValue, bool aReplace, - char** _retval, + char** aResult, PLArenaPool* aArena) { - if (_retval) - *_retval = nullptr; + if (aResult) { + *aResult = nullptr; + } MutexAutoLock lock(mLock); - CategoryLeaf* leaf = - mTable.GetEntry(aEntryName); + CategoryLeaf* leaf = mTable.GetEntry(aEntryName); if (!leaf) { const char* arenaEntryName = ArenaStrdup(aEntryName, aArena); - if (!arenaEntryName) + if (!arenaEntryName) { return NS_ERROR_OUT_OF_MEMORY; + } leaf = mTable.PutEntry(arenaEntryName); - if (!leaf) + if (!leaf) { return NS_ERROR_OUT_OF_MEMORY; + } } - if (leaf->value && !aReplace) + if (leaf->value && !aReplace) { return NS_ERROR_INVALID_ARG; + } const char* arenaValue = ArenaStrdup(aValue, aArena); - if (!arenaValue) + if (!arenaValue) { return NS_ERROR_OUT_OF_MEMORY; + } - if (_retval && leaf->value) { - *_retval = ToNewCString(nsDependentCString(leaf->value)); - if (!*_retval) + if (aResult && leaf->value) { + *aResult = ToNewCString(nsDependentCString(leaf->value)); + if (!*aResult) { return NS_ERROR_OUT_OF_MEMORY; + } } leaf->value = arenaValue; @@ -295,42 +310,44 @@ CategoryNode::DeleteLeaf(const char* aEntryName) mTable.RemoveEntry(aEntryName); } -NS_METHOD -CategoryNode::Enumerate(nsISimpleEnumerator **_retval) +NS_METHOD +CategoryNode::Enumerate(nsISimpleEnumerator** aResult) { - if (NS_WARN_IF(!_retval)) + if (NS_WARN_IF(!aResult)) { return NS_ERROR_INVALID_ARG; + } MutexAutoLock lock(mLock); EntryEnumerator* enumObj = EntryEnumerator::Create(mTable); - if (!enumObj) + if (!enumObj) { return NS_ERROR_OUT_OF_MEMORY; + } - *_retval = enumObj; - NS_ADDREF(*_retval); + *aResult = enumObj; + NS_ADDREF(*aResult); return NS_OK; } size_t CategoryNode::SizeOfExcludingThis(MallocSizeOf aMallocSizeOf) { - // We don't measure the strings pointed to by the entries because the - // pointers are non-owning. - return mTable.SizeOfExcludingThis(nullptr, aMallocSizeOf); + // We don't measure the strings pointed to by the entries because the + // pointers are non-owning. + return mTable.SizeOfExcludingThis(nullptr, aMallocSizeOf); } -struct persistent_userstruct { +struct persistent_userstruct +{ PRFileDesc* fd; const char* categoryName; bool success; }; PLDHashOperator -enumfunc_pentries(CategoryLeaf* aLeaf, void* userArg) +enumfunc_pentries(CategoryLeaf* aLeaf, void* aUserArg) { - persistent_userstruct* args = - static_cast(userArg); + persistent_userstruct* args = static_cast(aUserArg); PLDHashOperator status = PL_DHASH_NEXT; @@ -339,7 +356,7 @@ enumfunc_pentries(CategoryLeaf* aLeaf, void* userArg) "%s,%s,%s\n", args->categoryName, aLeaf->GetKey(), - aLeaf->value) == (uint32_t) -1) { + aLeaf->value) == (uint32_t)-1) { args->success = false; status = PL_DHASH_STOP; } @@ -356,21 +373,24 @@ class CategoryEnumerator : public BaseStringEnumerator { public: - static CategoryEnumerator* Create(nsClassHashtable& aTable); + static CategoryEnumerator* Create(nsClassHashtable& aTable); private: static PLDHashOperator enumfunc_createenumerator(const char* aStr, CategoryNode* aNode, - void* userArg); + void* aUserArg); }; CategoryEnumerator* -CategoryEnumerator::Create(nsClassHashtable& aTable) +CategoryEnumerator::Create(nsClassHashtable& + aTable) { CategoryEnumerator* enumObj = new CategoryEnumerator(); - if (!enumObj) + if (!enumObj) { return nullptr; + } enumObj->mArray = new const char* [aTable.Count()]; if (!enumObj->mArray) { @@ -384,13 +404,16 @@ CategoryEnumerator::Create(nsClassHashtable& aTa } PLDHashOperator -CategoryEnumerator::enumfunc_createenumerator(const char* aStr, CategoryNode* aNode, void* userArg) +CategoryEnumerator::enumfunc_createenumerator(const char* aStr, + CategoryNode* aNode, + void* aUserArg) { - CategoryEnumerator* mythis = static_cast(userArg); + CategoryEnumerator* mythis = static_cast(aUserArg); // if a category has no entries, we pretend it doesn't exist - if (aNode->Count()) + if (aNode->Count()) { mythis->mArray[mythis->mCount++] = aStr; + } return PL_DHASH_NEXT; } @@ -419,8 +442,9 @@ nsCategoryManager* nsCategoryManager::gCategoryManager; /* static */ nsCategoryManager* nsCategoryManager::GetSingleton() { - if (!gCategoryManager) + if (!gCategoryManager) { gCategoryManager = new nsCategoryManager(); + } return gCategoryManager; } @@ -434,8 +458,9 @@ nsCategoryManager::Destroy() nsresult nsCategoryManager::Create(nsISupports* aOuter, REFNSIID aIID, void** aResult) { - if (aOuter) + if (aOuter) { return NS_ERROR_NO_AGGREGATION; + } return GetSingleton()->QueryInterface(aIID, aResult); } @@ -467,7 +492,8 @@ nsCategoryManager::~nsCategoryManager() } inline CategoryNode* -nsCategoryManager::get_category(const char* aName) { +nsCategoryManager::get_category(const char* aName) +{ CategoryNode* node; if (!mTable.Get(aName, &node)) { return nullptr; @@ -481,21 +507,21 @@ NS_IMETHODIMP nsCategoryManager::CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData, bool aAnonymize) { - return MOZ_COLLECT_REPORT( - "explicit/xpcom/category-manager", KIND_HEAP, UNITS_BYTES, - SizeOfIncludingThis(CategoryManagerMallocSizeOf), - "Memory used for the XPCOM category manager."); + return MOZ_COLLECT_REPORT("explicit/xpcom/category-manager", + KIND_HEAP, UNITS_BYTES, + SizeOfIncludingThis(CategoryManagerMallocSizeOf), + "Memory used for the XPCOM category manager."); } static size_t SizeOfCategoryManagerTableEntryExcludingThis(nsDepCharHashKey::KeyType aKey, - const nsAutoPtr &aData, + const nsAutoPtr& aData, MallocSizeOf aMallocSizeOf, void* aUserArg) { - // We don't measure the string pointed to by aKey because it's a non-owning - // pointer. - return aData.get()->SizeOfExcludingThis(aMallocSizeOf); + // We don't measure the string pointed to by aKey because it's a non-owning + // pointer. + return aData.get()->SizeOfExcludingThis(aMallocSizeOf); } size_t @@ -522,7 +548,8 @@ class CategoryNotificationRunnable : public nsRunnable : mSubject(aSubject) , mTopic(aTopic) , mData(aData) - { } + { + } NS_DECL_NSIRUNNABLE @@ -537,54 +564,59 @@ CategoryNotificationRunnable::Run() { nsCOMPtr observerService = mozilla::services::GetObserverService(); - if (observerService) + if (observerService) { observerService->NotifyObservers(mSubject, mTopic, mData.get()); + } return NS_OK; } - + } // anonymous namespace void -nsCategoryManager::NotifyObservers( const char *aTopic, - const char *aCategoryName, - const char *aEntryName ) +nsCategoryManager::NotifyObservers(const char* aTopic, + const char* aCategoryName, + const char* aEntryName) { - if (mSuppressNotifications) + if (mSuppressNotifications) { return; + } nsRefPtr r; if (aEntryName) { - nsCOMPtr entry - (do_CreateInstance (NS_SUPPORTS_CSTRING_CONTRACTID)); - if (!entry) + nsCOMPtr entry = + do_CreateInstance(NS_SUPPORTS_CSTRING_CONTRACTID); + if (!entry) { return; + } nsresult rv = entry->SetData(nsDependentCString(aEntryName)); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { return; + } r = new CategoryNotificationRunnable(entry, aTopic, aCategoryName); } else { - r = new CategoryNotificationRunnable( - NS_ISUPPORTS_CAST(nsICategoryManager*, this), - aTopic, aCategoryName); + r = new CategoryNotificationRunnable(NS_ISUPPORTS_CAST(nsICategoryManager*, + this), + aTopic, aCategoryName); } NS_DispatchToMainThread(r); } NS_IMETHODIMP -nsCategoryManager::GetCategoryEntry( const char *aCategoryName, - const char *aEntryName, - char **_retval ) +nsCategoryManager::GetCategoryEntry(const char* aCategoryName, + const char* aEntryName, + char** aResult) { if (NS_WARN_IF(!aCategoryName) || NS_WARN_IF(!aEntryName) || - NS_WARN_IF(!_retval)) - return NS_ERROR_INVALID_ARG;; + NS_WARN_IF(!aResult)) { + return NS_ERROR_INVALID_ARG; + } nsresult status = NS_ERROR_NOT_AVAILABLE; @@ -595,38 +627,39 @@ nsCategoryManager::GetCategoryEntry( const char *aCategoryName, } if (category) { - status = category->GetLeaf(aEntryName, _retval); + status = category->GetLeaf(aEntryName, aResult); } return status; } NS_IMETHODIMP -nsCategoryManager::AddCategoryEntry( const char *aCategoryName, - const char *aEntryName, - const char *aValue, - bool aPersist, - bool aReplace, - char **_retval ) +nsCategoryManager::AddCategoryEntry(const char* aCategoryName, + const char* aEntryName, + const char* aValue, + bool aPersist, + bool aReplace, + char** aResult) { if (aPersist) { NS_ERROR("Category manager doesn't support persistence."); return NS_ERROR_INVALID_ARG; } - AddCategoryEntry(aCategoryName, aEntryName, aValue, aReplace, _retval); + AddCategoryEntry(aCategoryName, aEntryName, aValue, aReplace, aResult); return NS_OK; } void -nsCategoryManager::AddCategoryEntry(const char *aCategoryName, - const char *aEntryName, - const char *aValue, +nsCategoryManager::AddCategoryEntry(const char* aCategoryName, + const char* aEntryName, + const char* aValue, bool aReplace, char** aOldValue) { - if (aOldValue) + if (aOldValue) { *aOldValue = nullptr; + } // Before we can insert a new entry, we'll need to // find the |CategoryNode| to put it in... @@ -638,17 +671,18 @@ nsCategoryManager::AddCategoryEntry(const char *aCategoryName, if (!category) { // That category doesn't exist yet; let's make it. category = CategoryNode::Create(&mArena); - + char* categoryName = ArenaStrdup(aCategoryName, &mArena); mTable.Put(categoryName, category); } } - if (!category) + if (!category) { return; + } // We will need the return value of AddLeaf even if the called doesn't want it - char *oldEntry = nullptr; + char* oldEntry = nullptr; nsresult rv = category->AddLeaf(aEntryName, aValue, @@ -664,21 +698,23 @@ nsCategoryManager::AddCategoryEntry(const char *aCategoryName, NotifyObservers(NS_XPCOM_CATEGORY_ENTRY_ADDED_OBSERVER_ID, aCategoryName, aEntryName); - if (aOldValue) + if (aOldValue) { *aOldValue = oldEntry; - else + } else { NS_Free(oldEntry); + } } } NS_IMETHODIMP -nsCategoryManager::DeleteCategoryEntry( const char *aCategoryName, - const char *aEntryName, - bool aDontPersist) +nsCategoryManager::DeleteCategoryEntry(const char* aCategoryName, + const char* aEntryName, + bool aDontPersist) { if (NS_WARN_IF(!aCategoryName) || - NS_WARN_IF(!aEntryName)) + NS_WARN_IF(!aEntryName)) { return NS_ERROR_INVALID_ARG; + } /* Note: no errors are reported since failure to delete @@ -703,10 +739,11 @@ nsCategoryManager::DeleteCategoryEntry( const char *aCategoryName, } NS_IMETHODIMP -nsCategoryManager::DeleteCategory( const char *aCategoryName ) +nsCategoryManager::DeleteCategory(const char* aCategoryName) { - if (NS_WARN_IF(!aCategoryName)) + if (NS_WARN_IF(!aCategoryName)) { return NS_ERROR_INVALID_ARG; + } // the categories are arena-allocated, so we don't // actually delete them. We just remove all of the @@ -728,44 +765,48 @@ nsCategoryManager::DeleteCategory( const char *aCategoryName ) } NS_IMETHODIMP -nsCategoryManager::EnumerateCategory( const char *aCategoryName, - nsISimpleEnumerator **_retval ) +nsCategoryManager::EnumerateCategory(const char* aCategoryName, + nsISimpleEnumerator** aResult) { if (NS_WARN_IF(!aCategoryName) || - NS_WARN_IF(!_retval)) + NS_WARN_IF(!aResult)) { return NS_ERROR_INVALID_ARG; + } CategoryNode* category; { MutexAutoLock lock(mLock); category = get_category(aCategoryName); } - + if (!category) { - return NS_NewEmptyEnumerator(_retval); + return NS_NewEmptyEnumerator(aResult); } - return category->Enumerate(_retval); + return category->Enumerate(aResult); } -NS_IMETHODIMP -nsCategoryManager::EnumerateCategories(nsISimpleEnumerator **_retval) +NS_IMETHODIMP +nsCategoryManager::EnumerateCategories(nsISimpleEnumerator** aResult) { - if (NS_WARN_IF(!_retval)) + if (NS_WARN_IF(!aResult)) { return NS_ERROR_INVALID_ARG; + } MutexAutoLock lock(mLock); CategoryEnumerator* enumObj = CategoryEnumerator::Create(mTable); - if (!enumObj) + if (!enumObj) { return NS_ERROR_OUT_OF_MEMORY; + } - *_retval = enumObj; - NS_ADDREF(*_retval); + *aResult = enumObj; + NS_ADDREF(*aResult); return NS_OK; } -struct writecat_struct { +struct writecat_struct +{ PRFileDesc* fd; bool success; }; @@ -780,29 +821,31 @@ nsCategoryManager::SuppressNotifications(bool aSuppress) /* * CreateServicesFromCategory() * - * Given a category, this convenience functions enumerates the category and + * Given a category, this convenience functions enumerates the category and * creates a service of every CID or ContractID registered under the category. * If observerTopic is non null and the service implements nsIObserver, * this will attempt to notify the observer with the origin, observerTopic string * as parameter. */ void -NS_CreateServicesFromCategory(const char *category, - nsISupports *origin, - const char *observerTopic) +NS_CreateServicesFromCategory(const char* aCategory, + nsISupports* aOrigin, + const char* aObserverTopic) { nsresult rv; - nsCOMPtr categoryManager = + nsCOMPtr categoryManager = do_GetService("@mozilla.org/categorymanager;1"); - if (!categoryManager) + if (!categoryManager) { return; + } nsCOMPtr enumerator; - rv = categoryManager->EnumerateCategory(category, + rv = categoryManager->EnumerateCategory(aCategory, getter_AddRefs(enumerator)); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { return; + } nsCOMPtr senumerator = do_QueryInterface(enumerator); @@ -815,30 +858,33 @@ NS_CreateServicesFromCategory(const char *category, while (NS_SUCCEEDED(senumerator->HasMore(&hasMore)) && hasMore) { // From here on just skip any error we get. nsAutoCString entryString; - if (NS_FAILED(senumerator->GetNext(entryString))) + if (NS_FAILED(senumerator->GetNext(entryString))) { continue; - + } + nsXPIDLCString contractID; - rv = categoryManager->GetCategoryEntry(category,entryString.get(), + rv = categoryManager->GetCategoryEntry(aCategory, entryString.get(), getter_Copies(contractID)); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { continue; + } nsCOMPtr instance = do_GetService(contractID); if (!instance) { LogMessage("While creating services from category '%s', could not create service for entry '%s', contract ID '%s'", - category, entryString.get(), contractID.get()); + aCategory, entryString.get(), contractID.get()); continue; } - if (observerTopic) { + if (aObserverTopic) { // try an observer, if it implements it. nsCOMPtr observer = do_QueryInterface(instance); - if (observer) - observer->Observe(origin, observerTopic, EmptyString().get()); - else + if (observer) { + observer->Observe(aOrigin, aObserverTopic, EmptyString().get()); + } else { LogMessage("While creating services from category '%s', service for entry '%s', contract ID '%s' does not implement nsIObserver.", - category, entryString.get(), contractID.get()); + aCategory, entryString.get(), contractID.get()); + } } } } diff --git a/xpcom/components/nsCategoryManager.h b/xpcom/components/nsCategoryManager.h index 95dc75e38c20..5c4c6cb853f2 100644 --- a/xpcom/components/nsCategoryManager.h +++ b/xpcom/components/nsCategoryManager.h @@ -34,9 +34,7 @@ class nsIMemoryReporter; class CategoryLeaf : public nsDepCharHashKey { public: - CategoryLeaf(const char* aKey) - : nsDepCharHashKey(aKey), - value(nullptr) { } + CategoryLeaf(const char* aKey) : nsDepCharHashKey(aKey), value(nullptr) {} const char* value; }; @@ -50,40 +48,40 @@ class CategoryNode { public: NS_METHOD GetLeaf(const char* aEntryName, - char** _retval); + char** aResult); NS_METHOD AddLeaf(const char* aEntryName, const char* aValue, bool aReplace, - char** _retval, + char** aResult, PLArenaPool* aArena); void DeleteLeaf(const char* aEntryName); - void Clear() { + void Clear() + { mozilla::MutexAutoLock lock(mLock); mTable.Clear(); } - uint32_t Count() { + uint32_t Count() + { mozilla::MutexAutoLock lock(mLock); uint32_t tCount = mTable.Count(); return tCount; } - NS_METHOD Enumerate(nsISimpleEnumerator** _retval); + NS_METHOD Enumerate(nsISimpleEnumerator** aResult); // CategoryNode is arena-allocated, with the strings static CategoryNode* Create(PLArenaPool* aArena); ~CategoryNode(); - void operator delete(void*) { } + void operator delete(void*) {} size_t SizeOfExcludingThis(mozilla::MallocSizeOf aMallocSizeOf); private: - CategoryNode() - : mLock("CategoryLeaf") - { } + CategoryNode() : mLock("CategoryLeaf") {} void* operator new(size_t aSize, PLArenaPool* aArena); diff --git a/xpcom/components/nsCategoryManagerUtils.h b/xpcom/components/nsCategoryManagerUtils.h index 151c4aca6114..81b2c769d4f9 100644 --- a/xpcom/components/nsCategoryManagerUtils.h +++ b/xpcom/components/nsCategoryManagerUtils.h @@ -9,8 +9,8 @@ #include "nsICategoryManager.h" void -NS_CreateServicesFromCategory(const char *category, - nsISupports *origin, - const char *observerTopic); +NS_CreateServicesFromCategory(const char* aCategory, + nsISupports* aOrigin, + const char* aObserverTopic); #endif diff --git a/xpcom/components/nsComponentManager.cpp b/xpcom/components/nsComponentManager.cpp index 61f670636eed..4ccfd7153fc8 100644 --- a/xpcom/components/nsComponentManager.cpp +++ b/xpcom/components/nsComponentManager.cpp @@ -92,14 +92,14 @@ PRLogModuleInfo* nsComponentManagerLog = nullptr; #define BIG_REGISTRY_BUFLEN (512*1024) // Common Key Names -const char xpcomComponentsKeyName[]="software/mozilla/XPCOM/components"; -const char xpcomKeyName[]="software/mozilla/XPCOM"; +const char xpcomComponentsKeyName[] = "software/mozilla/XPCOM/components"; +const char xpcomKeyName[] = "software/mozilla/XPCOM"; // Common Value Names -const char fileSizeValueName[]="FileSize"; -const char lastModValueName[]="LastModTimeStamp"; -const char nativeComponentType[]="application/x-mozilla-native"; -const char staticComponentType[]="application/x-mozilla-static"; +const char fileSizeValueName[] = "FileSize"; +const char lastModValueName[] = "LastModTimeStamp"; +const char nativeComponentType[] = "application/x-mozilla-native"; +const char staticComponentType[] = "application/x-mozilla-static"; NS_DEFINE_CID(kCategoryManagerCID, NS_CATEGORYMANAGER_CID); @@ -107,96 +107,103 @@ NS_DEFINE_CID(kCategoryManagerCID, NS_CATEGORYMANAGER_CID); #ifdef MOZ_B2G_LOADER typedef nsDataHashtable XPTIInfosBookType; -static XPTIInfosBookType *sXPTIInfosBook = nullptr; +static XPTIInfosBookType* sXPTIInfosBook = nullptr; -static XPTIInfosBookType * +static XPTIInfosBookType* GetXPTIInfosBook() { - if (sXPTIInfosBook == nullptr) { - sXPTIInfosBook = new XPTIInfosBookType; - } - return sXPTIInfosBook; + if (!sXPTIInfosBook) { + sXPTIInfosBook = new XPTIInfosBookType; + } + return sXPTIInfosBook; } static bool -IsRegisteredXPTIInfo(FileLocation &aFile) +IsRegisteredXPTIInfo(FileLocation& aFile) { - nsAutoCString uri; - aFile.GetURIString(uri); - return GetXPTIInfosBook()->Get(uri); + nsAutoCString uri; + aFile.GetURIString(uri); + return GetXPTIInfosBook()->Get(uri); } static void -MarkRegisteredXPTIInfo(FileLocation &aFile) +MarkRegisteredXPTIInfo(FileLocation& aFile) { - nsAutoCString uri; - aFile.GetURIString(uri); - GetXPTIInfosBook()->Put(uri, true); + nsAutoCString uri; + aFile.GetURIString(uri); + GetXPTIInfosBook()->Put(uri, true); } #endif /* MOZ_B2G_LOADER */ nsresult -nsGetServiceFromCategory::operator()(const nsIID& aIID, void** aInstancePtr) const -{ - nsresult rv; - nsXPIDLCString value; - nsCOMPtr catman; - nsComponentManagerImpl *compMgr = nsComponentManagerImpl::gComponentManager; - if (!compMgr) { - rv = NS_ERROR_NOT_INITIALIZED; - goto error; - } +nsGetServiceFromCategory::operator()(const nsIID& aIID, + void** aInstancePtr) const +{ + nsresult rv; + nsXPIDLCString value; + nsCOMPtr catman; + nsComponentManagerImpl* compMgr = nsComponentManagerImpl::gComponentManager; + if (!compMgr) { + rv = NS_ERROR_NOT_INITIALIZED; + goto error; + } - if (!mCategory || !mEntry) { - // when categories have defaults, use that for null mEntry - rv = NS_ERROR_NULL_POINTER; - goto error; - } + if (!mCategory || !mEntry) { + // when categories have defaults, use that for null mEntry + rv = NS_ERROR_NULL_POINTER; + goto error; + } - rv = compMgr->nsComponentManagerImpl::GetService(kCategoryManagerCID, - NS_GET_IID(nsICategoryManager), - getter_AddRefs(catman)); - if (NS_FAILED(rv)) goto error; - - /* find the contractID for category.entry */ - rv = catman->GetCategoryEntry(mCategory, mEntry, - getter_Copies(value)); - if (NS_FAILED(rv)) goto error; - if (!value) { - rv = NS_ERROR_SERVICE_NOT_AVAILABLE; - goto error; - } + rv = compMgr->nsComponentManagerImpl::GetService(kCategoryManagerCID, + NS_GET_IID(nsICategoryManager), + getter_AddRefs(catman)); + if (NS_FAILED(rv)) { + goto error; + } - rv = compMgr-> - nsComponentManagerImpl::GetServiceByContractID(value, - aIID, aInstancePtr); - if (NS_FAILED(rv)) { - error: - *aInstancePtr = 0; - } - if (mErrorPtr) - *mErrorPtr = rv; - return rv; + /* find the contractID for category.entry */ + rv = catman->GetCategoryEntry(mCategory, mEntry, + getter_Copies(value)); + if (NS_FAILED(rv)) { + goto error; + } + if (!value) { + rv = NS_ERROR_SERVICE_NOT_AVAILABLE; + goto error; + } + + rv = compMgr->nsComponentManagerImpl::GetServiceByContractID(value, + aIID, + aInstancePtr); + if (NS_FAILED(rv)) { +error: + *aInstancePtr = 0; + } + if (mErrorPtr) { + *mErrorPtr = rv; + } + return rv; } //////////////////////////////////////////////////////////////////////////////// // Arena helper functions //////////////////////////////////////////////////////////////////////////////// -char * -ArenaStrndup(const char *s, uint32_t len, PLArenaPool *arena) +char* +ArenaStrndup(const char* aStr, uint32_t aLen, PLArenaPool* aArena) { - void *mem; - // Include trailing null in the len - PL_ARENA_ALLOCATE(mem, arena, len+1); - if (mem) - memcpy(mem, s, len+1); - return static_cast(mem); + void* mem; + // Include trailing null in the aLen + PL_ARENA_ALLOCATE(mem, aArena, aLen + 1); + if (mem) { + memcpy(mem, aStr, aLen + 1); + } + return static_cast(mem); } char* -ArenaStrdup(const char *s, PLArenaPool *arena) +ArenaStrdup(const char* aStr, PLArenaPool* aArena) { - return ArenaStrndup(s, strlen(s), arena); + return ArenaStrndup(aStr, strlen(aStr), aArena); } // GetService and a few other functions need to exit their mutex mid-function @@ -208,72 +215,76 @@ namespace { class MOZ_STACK_CLASS MutexLock { public: - MutexLock(SafeMutex& aMutex) - : mMutex(aMutex) - , mLocked(false) - { - Lock(); - } + MutexLock(SafeMutex& aMutex) + : mMutex(aMutex) + , mLocked(false) + { + Lock(); + } - ~MutexLock() - { - if (mLocked) - Unlock(); + ~MutexLock() + { + if (mLocked) { + Unlock(); } + } - void Lock() - { - NS_ASSERTION(!mLocked, "Re-entering a mutex"); - mMutex.Lock(); - mLocked = true; - } + void Lock() + { + NS_ASSERTION(!mLocked, "Re-entering a mutex"); + mMutex.Lock(); + mLocked = true; + } - void Unlock() - { - NS_ASSERTION(mLocked, "Exiting a mutex that isn't held!"); - mMutex.Unlock(); - mLocked = false; - } + void Unlock() + { + NS_ASSERTION(mLocked, "Exiting a mutex that isn't held!"); + mMutex.Unlock(); + mLocked = false; + } private: - SafeMutex& mMutex; - bool mLocked; + SafeMutex& mMutex; + bool mLocked; }; } // anonymous namespace // this is safe to call during InitXPCOM static already_AddRefed -GetLocationFromDirectoryService(const char* prop) +GetLocationFromDirectoryService(const char* aProp) { - nsCOMPtr directoryService; - nsDirectoryService::Create(nullptr, - NS_GET_IID(nsIProperties), - getter_AddRefs(directoryService)); + nsCOMPtr directoryService; + nsDirectoryService::Create(nullptr, + NS_GET_IID(nsIProperties), + getter_AddRefs(directoryService)); - if (!directoryService) - return nullptr; + if (!directoryService) { + return nullptr; + } - nsCOMPtr file; - nsresult rv = directoryService->Get(prop, - NS_GET_IID(nsIFile), - getter_AddRefs(file)); - if (NS_FAILED(rv)) - return nullptr; + nsCOMPtr file; + nsresult rv = directoryService->Get(aProp, + NS_GET_IID(nsIFile), + getter_AddRefs(file)); + if (NS_FAILED(rv)) { + return nullptr; + } - return file.forget(); + return file.forget(); } static already_AddRefed -CloneAndAppend(nsIFile* aBase, const nsACString& append) +CloneAndAppend(nsIFile* aBase, const nsACString& aAppend) { - nsCOMPtr f; - aBase->Clone(getter_AddRefs(f)); - if (!f) - return nullptr; + nsCOMPtr f; + aBase->Clone(getter_AddRefs(f)); + if (!f) { + return nullptr; + } - f->AppendNative(append); - return f.forget(); + f->AppendNative(aAppend); + return f.forget(); } //////////////////////////////////////////////////////////////////////////////// @@ -281,24 +292,27 @@ CloneAndAppend(nsIFile* aBase, const nsACString& append) //////////////////////////////////////////////////////////////////////////////// nsresult -nsComponentManagerImpl::Create(nsISupports* aOuter, REFNSIID aIID, void** aResult) +nsComponentManagerImpl::Create(nsISupports* aOuter, REFNSIID aIID, + void** aResult) { - if (aOuter) - return NS_ERROR_NO_AGGREGATION; + if (aOuter) { + return NS_ERROR_NO_AGGREGATION; + } - if (!gComponentManager) - return NS_ERROR_FAILURE; + if (!gComponentManager) { + return NS_ERROR_FAILURE; + } - return gComponentManager->QueryInterface(aIID, aResult); + return gComponentManager->QueryInterface(aIID, aResult); } static const int CONTRACTID_HASHTABLE_INITIAL_SIZE = 2048; nsComponentManagerImpl::nsComponentManagerImpl() - : mFactories(CONTRACTID_HASHTABLE_INITIAL_SIZE) - , mContractIDs(CONTRACTID_HASHTABLE_INITIAL_SIZE) - , mLock("nsComponentManagerImpl.mLock") - , mStatus(NOT_INITIALIZED) + : mFactories(CONTRACTID_HASHTABLE_INITIAL_SIZE) + , mContractIDs(CONTRACTID_HASHTABLE_INITIAL_SIZE) + , mLock("nsComponentManagerImpl.mLock") + , mStatus(NOT_INITIALIZED) { } @@ -316,14 +330,17 @@ MOZ_ASAN_BLACKLIST /* static */ void nsComponentManagerImpl::InitializeStaticModules() { - if (sStaticModules) - return; + if (sStaticModules) { + return; + } - sStaticModules = new nsTArray; - for (const mozilla::Module *const *staticModules = &NSMODULE_NAME(start_kPStaticModules) + 1; - staticModules < &NSMODULE_NAME(end_kPStaticModules); ++staticModules) - if (*staticModules) // ASAN adds padding - sStaticModules->AppendElement(*staticModules); + sStaticModules = new nsTArray; + for (const mozilla::Module * const* staticModules = + &NSMODULE_NAME(start_kPStaticModules) + 1; + staticModules < &NSMODULE_NAME(end_kPStaticModules); ++staticModules) + if (*staticModules) { // ASAN adds padding + sStaticModules->AppendElement(*staticModules); + } } nsTArray* @@ -332,155 +349,162 @@ nsComponentManagerImpl::sModuleLocations; /* static */ void nsComponentManagerImpl::InitializeModuleLocations() { - if (sModuleLocations) - return; + if (sModuleLocations) { + return; + } - sModuleLocations = new nsTArray; + sModuleLocations = new nsTArray; } -nsresult nsComponentManagerImpl::Init() +nsresult +nsComponentManagerImpl::Init() { - PR_ASSERT(NOT_INITIALIZED == mStatus); + PR_ASSERT(NOT_INITIALIZED == mStatus); - if (nsComponentManagerLog == nullptr) - { - nsComponentManagerLog = PR_NewLogModule("nsComponentManager"); - } + if (!nsComponentManagerLog) { + nsComponentManagerLog = PR_NewLogModule("nsComponentManager"); + } - // Initialize our arena - PL_INIT_ARENA_POOL(&mArena, "ComponentManagerArena", NS_CM_BLOCK_SIZE); + // Initialize our arena + PL_INIT_ARENA_POOL(&mArena, "ComponentManagerArena", NS_CM_BLOCK_SIZE); - nsCOMPtr greDir = - GetLocationFromDirectoryService(NS_GRE_DIR); - nsCOMPtr appDir = - GetLocationFromDirectoryService(NS_XPCOM_CURRENT_PROCESS_DIR); + nsCOMPtr greDir = + GetLocationFromDirectoryService(NS_GRE_DIR); + nsCOMPtr appDir = + GetLocationFromDirectoryService(NS_XPCOM_CURRENT_PROCESS_DIR); - InitializeStaticModules(); - InitializeModuleLocations(); + InitializeStaticModules(); + InitializeModuleLocations(); - ComponentLocation* cl = sModuleLocations->InsertElementAt(0); - nsCOMPtr lf = CloneAndAppend(appDir, NS_LITERAL_CSTRING("chrome.manifest")); + ComponentLocation* cl = sModuleLocations->InsertElementAt(0); + nsCOMPtr lf = CloneAndAppend(appDir, + NS_LITERAL_CSTRING("chrome.manifest")); + cl->type = NS_COMPONENT_LOCATION; + cl->location.Init(lf); + + bool equals = false; + appDir->Equals(greDir, &equals); + if (!equals) { + cl = sModuleLocations->InsertElementAt(0); cl->type = NS_COMPONENT_LOCATION; + lf = CloneAndAppend(greDir, NS_LITERAL_CSTRING("chrome.manifest")); cl->location.Init(lf); + } - bool equals = false; - appDir->Equals(greDir, &equals); - if (!equals) { - cl = sModuleLocations->InsertElementAt(0); - cl->type = NS_COMPONENT_LOCATION; - lf = CloneAndAppend(greDir, NS_LITERAL_CSTRING("chrome.manifest")); - cl->location.Init(lf); - } - - PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, - ("nsComponentManager: Initialized.")); + PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, + ("nsComponentManager: Initialized.")); - nsresult rv = mNativeModuleLoader.Init(); - if (NS_FAILED(rv)) - return rv; + nsresult rv = mNativeModuleLoader.Init(); + if (NS_FAILED(rv)) { + return rv; + } - nsCategoryManager::GetSingleton()->SuppressNotifications(true); + nsCategoryManager::GetSingleton()->SuppressNotifications(true); - RegisterModule(&kXPCOMModule, nullptr); + RegisterModule(&kXPCOMModule, nullptr); - for (uint32_t i = 0; i < sStaticModules->Length(); ++i) - RegisterModule((*sStaticModules)[i], nullptr); + for (uint32_t i = 0; i < sStaticModules->Length(); ++i) { + RegisterModule((*sStaticModules)[i], nullptr); + } - nsRefPtr appOmnijar = mozilla::Omnijar::GetReader(mozilla::Omnijar::APP); - if (appOmnijar) { - cl = sModuleLocations->InsertElementAt(1); // Insert after greDir - cl->type = NS_COMPONENT_LOCATION; - cl->location.Init(appOmnijar, "chrome.manifest"); - } - nsRefPtr greOmnijar = mozilla::Omnijar::GetReader(mozilla::Omnijar::GRE); - if (greOmnijar) { - cl = sModuleLocations->InsertElementAt(0); - cl->type = NS_COMPONENT_LOCATION; - cl->location.Init(greOmnijar, "chrome.manifest"); - } + nsRefPtr appOmnijar = + mozilla::Omnijar::GetReader(mozilla::Omnijar::APP); + if (appOmnijar) { + cl = sModuleLocations->InsertElementAt(1); // Insert after greDir + cl->type = NS_COMPONENT_LOCATION; + cl->location.Init(appOmnijar, "chrome.manifest"); + } + nsRefPtr greOmnijar = + mozilla::Omnijar::GetReader(mozilla::Omnijar::GRE); + if (greOmnijar) { + cl = sModuleLocations->InsertElementAt(0); + cl->type = NS_COMPONENT_LOCATION; + cl->location.Init(greOmnijar, "chrome.manifest"); + } - RereadChromeManifests(false); + RereadChromeManifests(false); - nsCategoryManager::GetSingleton()->SuppressNotifications(false); + nsCategoryManager::GetSingleton()->SuppressNotifications(false); - RegisterWeakMemoryReporter(this); + RegisterWeakMemoryReporter(this); - // Unfortunately, we can't register the nsCategoryManager memory reporter - // in its constructor (which is triggered by the GetSingleton() call - // above) because the memory reporter manager isn't initialized at that - // point. So we wait until now. - nsCategoryManager::GetSingleton()->InitMemoryReporter(); + // Unfortunately, we can't register the nsCategoryManager memory reporter + // in its constructor (which is triggered by the GetSingleton() call + // above) because the memory reporter manager isn't initialized at that + // point. So we wait until now. + nsCategoryManager::GetSingleton()->InitMemoryReporter(); - mStatus = NORMAL; + mStatus = NORMAL; - return NS_OK; + return NS_OK; } void nsComponentManagerImpl::RegisterModule(const mozilla::Module* aModule, FileLocation* aFile) { - mLock.AssertNotCurrentThreadOwns(); - - { - // Scope the monitor so that we don't hold it while calling into the - // category manager. - MutexLock lock(mLock); - - KnownModule* m; - if (aFile) { - nsCString uri; - aFile->GetURIString(uri); - NS_ASSERTION(!mKnownModules.Get(uri), - "Must not register a binary module twice."); - - m = new KnownModule(aModule, *aFile); - mKnownModules.Put(uri, m); - } else { - m = new KnownModule(aModule); - mKnownStaticModules.AppendElement(m); - } - - if (aModule->mCIDs) { - const mozilla::Module::CIDEntry* entry; - for (entry = aModule->mCIDs; entry->cid; ++entry) - RegisterCIDEntryLocked(entry, m); - } - - if (aModule->mContractIDs) { - const mozilla::Module::ContractIDEntry* entry; - for (entry = aModule->mContractIDs; entry->contractid; ++entry) - RegisterContractIDLocked(entry); - MOZ_ASSERT(!entry->cid, "Incorrectly terminated contract list"); - } + mLock.AssertNotCurrentThreadOwns(); + + { + // Scope the monitor so that we don't hold it while calling into the + // category manager. + MutexLock lock(mLock); + + KnownModule* m; + if (aFile) { + nsCString uri; + aFile->GetURIString(uri); + NS_ASSERTION(!mKnownModules.Get(uri), + "Must not register a binary module twice."); + + m = new KnownModule(aModule, *aFile); + mKnownModules.Put(uri, m); + } else { + m = new KnownModule(aModule); + mKnownStaticModules.AppendElement(m); } - if (aModule->mCategoryEntries) { - const mozilla::Module::CategoryEntry* entry; - for (entry = aModule->mCategoryEntries; entry->category; ++entry) - nsCategoryManager::GetSingleton()-> - AddCategoryEntry(entry->category, - entry->entry, - entry->value); + if (aModule->mCIDs) { + const mozilla::Module::CIDEntry* entry; + for (entry = aModule->mCIDs; entry->cid; ++entry) { + RegisterCIDEntryLocked(entry, m); + } } + + if (aModule->mContractIDs) { + const mozilla::Module::ContractIDEntry* entry; + for (entry = aModule->mContractIDs; entry->contractid; ++entry) { + RegisterContractIDLocked(entry); + } + MOZ_ASSERT(!entry->cid, "Incorrectly terminated contract list"); + } + } + + if (aModule->mCategoryEntries) { + const mozilla::Module::CategoryEntry* entry; + for (entry = aModule->mCategoryEntries; entry->category; ++entry) + nsCategoryManager::GetSingleton()->AddCategoryEntry(entry->category, + entry->entry, + entry->value); + } } static bool -ProcessSelectorMatches(Module::ProcessSelector selector) +ProcessSelectorMatches(Module::ProcessSelector aSelector) { - if (selector == Module::ANY_PROCESS) { - return true; - } + if (aSelector == Module::ANY_PROCESS) { + return true; + } - GeckoProcessType type = XRE_GetProcessType(); - switch (selector) { - case Module::MAIN_PROCESS_ONLY: - return type == GeckoProcessType_Default; - case Module::CONTENT_PROCESS_ONLY: - return type == GeckoProcessType_Content; - default: - MOZ_CRASH("invalid process selector"); - } + GeckoProcessType type = XRE_GetProcessType(); + switch (aSelector) { + case Module::MAIN_PROCESS_ONLY: + return type == GeckoProcessType_Default; + case Module::CONTENT_PROCESS_ONLY: + return type == GeckoProcessType_Content; + default: + MOZ_CRASH("invalid process aSelector"); + } } void @@ -488,450 +512,470 @@ nsComponentManagerImpl::RegisterCIDEntryLocked( const mozilla::Module::CIDEntry* aEntry, KnownModule* aModule) { - mLock.AssertCurrentThreadOwns(); + mLock.AssertCurrentThreadOwns(); - if (!ProcessSelectorMatches(aEntry->processSelector)) { - return; - } + if (!ProcessSelectorMatches(aEntry->processSelector)) { + return; + } - nsFactoryEntry* f = mFactories.Get(*aEntry->cid); - if (f) { - NS_WARNING("Re-registering a CID?"); - - char idstr[NSID_LENGTH]; - aEntry->cid->ToProvidedString(idstr); - - nsCString existing; - if (f->mModule) - existing = f->mModule->Description(); - else - existing = ""; - SafeMutexAutoUnlock unlock(mLock); - LogMessage("While registering XPCOM module %s, trying to re-register CID '%s' already registered by %s.", - aModule->Description().get(), - idstr, - existing.get()); - return; - } + nsFactoryEntry* f = mFactories.Get(*aEntry->cid); + if (f) { + NS_WARNING("Re-registering a CID?"); + + char idstr[NSID_LENGTH]; + aEntry->cid->ToProvidedString(idstr); - f = new nsFactoryEntry(aEntry, aModule); - mFactories.Put(*aEntry->cid, f); + nsCString existing; + if (f->mModule) { + existing = f->mModule->Description(); + } else { + existing = ""; + } + SafeMutexAutoUnlock unlock(mLock); + LogMessage("While registering XPCOM module %s, trying to re-register CID '%s' already registered by %s.", + aModule->Description().get(), + idstr, + existing.get()); + return; + } + + f = new nsFactoryEntry(aEntry, aModule); + mFactories.Put(*aEntry->cid, f); } void nsComponentManagerImpl::RegisterContractIDLocked( const mozilla::Module::ContractIDEntry* aEntry) { - mLock.AssertCurrentThreadOwns(); + mLock.AssertCurrentThreadOwns(); - if (!ProcessSelectorMatches(aEntry->processSelector)) { - return; - } + if (!ProcessSelectorMatches(aEntry->processSelector)) { + return; + } - nsFactoryEntry* f = mFactories.Get(*aEntry->cid); - if (!f) { - NS_ERROR("No CID found when attempting to map contract ID"); + nsFactoryEntry* f = mFactories.Get(*aEntry->cid); + if (!f) { + NS_ERROR("No CID found when attempting to map contract ID"); - char idstr[NSID_LENGTH]; - aEntry->cid->ToProvidedString(idstr); + char idstr[NSID_LENGTH]; + aEntry->cid->ToProvidedString(idstr); - LogMessage("Could not map contract ID '%s' to CID %s because no implementation of the CID is registered.", - aEntry->contractid, - idstr); - - return; - } + LogMessage("Could not map contract ID '%s' to CID %s because no implementation of the CID is registered.", + aEntry->contractid, + idstr); - mContractIDs.Put(nsDependentCString(aEntry->contractid), f); + return; + } + + mContractIDs.Put(nsDependentCString(aEntry->contractid), f); } static void -CutExtension(nsCString& path) +CutExtension(nsCString& aPath) { - int32_t dotPos = path.RFindChar('.'); - if (kNotFound == dotPos) - path.Truncate(); - else - path.Cut(0, dotPos + 1); + int32_t dotPos = aPath.RFindChar('.'); + if (kNotFound == dotPos) { + aPath.Truncate(); + } else { + aPath.Cut(0, dotPos + 1); + } } static void DoRegisterManifest(NSLocationType aType, - FileLocation &aFile, + FileLocation& aFile, bool aChromeOnly, bool aXPTOnly) { - MOZ_ASSERT(!aXPTOnly || - nsComponentManagerImpl::gComponentManager == nullptr); - uint32_t len; - FileLocation::Data data; - nsAutoArrayPtr buf; - nsresult rv = aFile.GetData(data); - if (NS_SUCCEEDED(rv)) { - rv = data.GetSize(&len); - } - if (NS_SUCCEEDED(rv)) { - buf = new char[len + 1]; - rv = data.Copy(buf, len); - } - if (NS_SUCCEEDED(rv)) { - buf[len] = '\0'; - ParseManifest(aType, aFile, buf, aChromeOnly, aXPTOnly); - } else if (NS_BOOTSTRAPPED_LOCATION != aType) { - nsCString uri; - aFile.GetURIString(uri); - LogMessage("Could not read chrome manifest '%s'.", uri.get()); - } + MOZ_ASSERT(!aXPTOnly || !nsComponentManagerImpl::gComponentManager); + uint32_t len; + FileLocation::Data data; + nsAutoArrayPtr buf; + nsresult rv = aFile.GetData(data); + if (NS_SUCCEEDED(rv)) { + rv = data.GetSize(&len); + } + if (NS_SUCCEEDED(rv)) { + buf = new char[len + 1]; + rv = data.Copy(buf, len); + } + if (NS_SUCCEEDED(rv)) { + buf[len] = '\0'; + ParseManifest(aType, aFile, buf, aChromeOnly, aXPTOnly); + } else if (NS_BOOTSTRAPPED_LOCATION != aType) { + nsCString uri; + aFile.GetURIString(uri); + LogMessage("Could not read chrome manifest '%s'.", uri.get()); + } } void nsComponentManagerImpl::RegisterManifest(NSLocationType aType, - FileLocation &aFile, + FileLocation& aFile, bool aChromeOnly) { - DoRegisterManifest(aType, aFile, aChromeOnly, false); + DoRegisterManifest(aType, aFile, aChromeOnly, false); } void -nsComponentManagerImpl::ManifestManifest(ManifestProcessingContext& cx, int lineno, char *const * argv) +nsComponentManagerImpl::ManifestManifest(ManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv) { - char* file = argv[0]; - FileLocation f(cx.mFile, file); - RegisterManifest(cx.mType, f, cx.mChromeOnly); + char* file = aArgv[0]; + FileLocation f(aCx.mFile, file); + RegisterManifest(aCx.mType, f, aCx.mChromeOnly); } void -nsComponentManagerImpl::ManifestBinaryComponent(ManifestProcessingContext& cx, int lineno, char *const * argv) -{ - if (cx.mFile.IsZip()) { - NS_WARNING("Cannot load binary components from a jar."); - LogMessageWithContext(cx.mFile, lineno, - "Cannot load binary components from a jar."); - return; - } +nsComponentManagerImpl::ManifestBinaryComponent(ManifestProcessingContext& aCx, + int aLineNo, + char* const* aArgv) +{ + if (aCx.mFile.IsZip()) { + NS_WARNING("Cannot load binary components from a jar."); + LogMessageWithContext(aCx.mFile, aLineNo, + "Cannot load binary components from a jar."); + return; + } - FileLocation f(cx.mFile, argv[0]); - nsCString uri; - f.GetURIString(uri); + FileLocation f(aCx.mFile, aArgv[0]); + nsCString uri; + f.GetURIString(uri); - if (mKnownModules.Get(uri)) { - NS_WARNING("Attempting to register a binary component twice."); - LogMessageWithContext(cx.mFile, lineno, - "Attempting to register a binary component twice."); - return; - } + if (mKnownModules.Get(uri)) { + NS_WARNING("Attempting to register a binary component twice."); + LogMessageWithContext(aCx.mFile, aLineNo, + "Attempting to register a binary component twice."); + return; + } - const mozilla::Module* m = mNativeModuleLoader.LoadModule(f); - // The native module loader should report an error here, we don't have to - if (!m) - return; + const mozilla::Module* m = mNativeModuleLoader.LoadModule(f); + // The native module loader should report an error here, we don't have to + if (!m) { + return; + } - RegisterModule(m, &f); + RegisterModule(m, &f); } static void -DoRegisterXPT(FileLocation &aFile) +DoRegisterXPT(FileLocation& aFile) { #ifdef MOZ_B2G_LOADER - if (IsRegisteredXPTIInfo(aFile)) { - return; - } + if (IsRegisteredXPTIInfo(aFile)) { + return; + } #endif - uint32_t len; - FileLocation::Data data; - nsAutoArrayPtr buf; - nsresult rv = aFile.GetData(data); - if (NS_SUCCEEDED(rv)) { - rv = data.GetSize(&len); - } - if (NS_SUCCEEDED(rv)) { - buf = new char[len]; - rv = data.Copy(buf, len); - } - if (NS_SUCCEEDED(rv)) { - XPTInterfaceInfoManager::GetSingleton()->RegisterBuffer(buf, len); + uint32_t len; + FileLocation::Data data; + nsAutoArrayPtr buf; + nsresult rv = aFile.GetData(data); + if (NS_SUCCEEDED(rv)) { + rv = data.GetSize(&len); + } + if (NS_SUCCEEDED(rv)) { + buf = new char[len]; + rv = data.Copy(buf, len); + } + if (NS_SUCCEEDED(rv)) { + XPTInterfaceInfoManager::GetSingleton()->RegisterBuffer(buf, len); #ifdef MOZ_B2G_LOADER - MarkRegisteredXPTIInfo(aFile); + MarkRegisteredXPTIInfo(aFile); #endif - } else { - nsCString uri; - aFile.GetURIString(uri); - LogMessage("Could not read '%s'.", uri.get()); - } + } else { + nsCString uri; + aFile.GetURIString(uri); + LogMessage("Could not read '%s'.", uri.get()); + } } void -nsComponentManagerImpl::ManifestXPT(ManifestProcessingContext& cx, int lineno, char *const * argv) +nsComponentManagerImpl::ManifestXPT(ManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv) { - FileLocation f(cx.mFile, argv[0]); - DoRegisterXPT(f); + FileLocation f(aCx.mFile, aArgv[0]); + DoRegisterXPT(f); } void -nsComponentManagerImpl::ManifestComponent(ManifestProcessingContext& cx, int lineno, char *const * argv) +nsComponentManagerImpl::ManifestComponent(ManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv) { - mLock.AssertNotCurrentThreadOwns(); + mLock.AssertNotCurrentThreadOwns(); - char* id = argv[0]; - char* file = argv[1]; + char* id = aArgv[0]; + char* file = aArgv[1]; - nsID cid; - if (!cid.Parse(id)) { - LogMessageWithContext(cx.mFile, lineno, - "Malformed CID: '%s'.", id); - return; - } + nsID cid; + if (!cid.Parse(id)) { + LogMessageWithContext(aCx.mFile, aLineNo, + "Malformed CID: '%s'.", id); + return; + } - // Precompute the hash/file data outside of the lock - FileLocation fl(cx.mFile, file); - nsCString hash; - fl.GetURIString(hash); + // Precompute the hash/file data outside of the lock + FileLocation fl(aCx.mFile, file); + nsCString hash; + fl.GetURIString(hash); - MutexLock lock(mLock); - nsFactoryEntry* f = mFactories.Get(cid); - if (f) { - char idstr[NSID_LENGTH]; - cid.ToProvidedString(idstr); - - nsCString existing; - if (f->mModule) - existing = f->mModule->Description(); - else - existing = ""; - - lock.Unlock(); - - LogMessageWithContext(cx.mFile, lineno, - "Trying to re-register CID '%s' already registered by %s.", - idstr, - existing.get()); - return; + MutexLock lock(mLock); + nsFactoryEntry* f = mFactories.Get(cid); + if (f) { + char idstr[NSID_LENGTH]; + cid.ToProvidedString(idstr); + + nsCString existing; + if (f->mModule) { + existing = f->mModule->Description(); + } else { + existing = ""; } - KnownModule* km; + lock.Unlock(); - km = mKnownModules.Get(hash); - if (!km) { - km = new KnownModule(fl); - mKnownModules.Put(hash, km); - } + LogMessageWithContext(aCx.mFile, aLineNo, + "Trying to re-register CID '%s' already registered by %s.", + idstr, + existing.get()); + return; + } - void* place; + KnownModule* km; - PL_ARENA_ALLOCATE(place, &mArena, sizeof(nsCID)); - nsID* permanentCID = static_cast(place); - *permanentCID = cid; + km = mKnownModules.Get(hash); + if (!km) { + km = new KnownModule(fl); + mKnownModules.Put(hash, km); + } - PL_ARENA_ALLOCATE(place, &mArena, sizeof(mozilla::Module::CIDEntry)); - mozilla::Module::CIDEntry* e = new (place) mozilla::Module::CIDEntry(); - e->cid = permanentCID; + void* place; - f = new nsFactoryEntry(e, km); - mFactories.Put(cid, f); + PL_ARENA_ALLOCATE(place, &mArena, sizeof(nsCID)); + nsID* permanentCID = static_cast(place); + *permanentCID = cid; + + PL_ARENA_ALLOCATE(place, &mArena, sizeof(mozilla::Module::CIDEntry)); + mozilla::Module::CIDEntry* e = new (place) mozilla::Module::CIDEntry(); + e->cid = permanentCID; + + f = new nsFactoryEntry(e, km); + mFactories.Put(cid, f); } void -nsComponentManagerImpl::ManifestContract(ManifestProcessingContext& cx, int lineno, char *const * argv) +nsComponentManagerImpl::ManifestContract(ManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv) { - mLock.AssertNotCurrentThreadOwns(); + mLock.AssertNotCurrentThreadOwns(); - char* contract = argv[0]; - char* id = argv[1]; + char* contract = aArgv[0]; + char* id = aArgv[1]; - nsID cid; - if (!cid.Parse(id)) { - LogMessageWithContext(cx.mFile, lineno, - "Malformed CID: '%s'.", id); - return; - } + nsID cid; + if (!cid.Parse(id)) { + LogMessageWithContext(aCx.mFile, aLineNo, + "Malformed CID: '%s'.", id); + return; + } - MutexLock lock(mLock); - nsFactoryEntry* f = mFactories.Get(cid); - if (!f) { - lock.Unlock(); - LogMessageWithContext(cx.mFile, lineno, - "Could not map contract ID '%s' to CID %s because no implementation of the CID is registered.", - contract, id); - return; - } + MutexLock lock(mLock); + nsFactoryEntry* f = mFactories.Get(cid); + if (!f) { + lock.Unlock(); + LogMessageWithContext(aCx.mFile, aLineNo, + "Could not map contract ID '%s' to CID %s because no implementation of the CID is registered.", + contract, id); + return; + } - mContractIDs.Put(nsDependentCString(contract), f); + mContractIDs.Put(nsDependentCString(contract), f); } void -nsComponentManagerImpl::ManifestCategory(ManifestProcessingContext& cx, int lineno, char *const * argv) +nsComponentManagerImpl::ManifestCategory(ManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv) { - char* category = argv[0]; - char* key = argv[1]; - char* value = argv[2]; + char* category = aArgv[0]; + char* key = aArgv[1]; + char* value = aArgv[2]; - nsCategoryManager::GetSingleton()-> - AddCategoryEntry(category, key, value); + nsCategoryManager::GetSingleton()-> + AddCategoryEntry(category, key, value); } void nsComponentManagerImpl::RereadChromeManifests(bool aChromeOnly) { - for (uint32_t i = 0; i < sModuleLocations->Length(); ++i) { - ComponentLocation& l = sModuleLocations->ElementAt(i); - RegisterManifest(l.type, l.location, aChromeOnly); - } + for (uint32_t i = 0; i < sModuleLocations->Length(); ++i) { + ComponentLocation& l = sModuleLocations->ElementAt(i); + RegisterManifest(l.type, l.location, aChromeOnly); + } } bool nsComponentManagerImpl::KnownModule::EnsureLoader() { - if (!mLoader) { - nsCString extension; - mFile.GetURIString(extension); - CutExtension(extension); - mLoader = nsComponentManagerImpl::gComponentManager->LoaderForExtension(extension); - } - return !!mLoader; + if (!mLoader) { + nsCString extension; + mFile.GetURIString(extension); + CutExtension(extension); + mLoader = + nsComponentManagerImpl::gComponentManager->LoaderForExtension(extension); + } + return !!mLoader; } bool nsComponentManagerImpl::KnownModule::Load() { - if (mFailed) - return false; - if (!mModule) { - if (!EnsureLoader()) - return false; + if (mFailed) { + return false; + } + if (!mModule) { + if (!EnsureLoader()) { + return false; + } - mModule = mLoader->LoadModule(mFile); + mModule = mLoader->LoadModule(mFile); - if (!mModule) { - mFailed = true; - return false; - } + if (!mModule) { + mFailed = true; + return false; } - if (!mLoaded) { - if (mModule->loadProc) { - nsresult rv = mModule->loadProc(); - if (NS_FAILED(rv)) { - mFailed = true; - return false; - } - } - mLoaded = true; + } + if (!mLoaded) { + if (mModule->loadProc) { + nsresult rv = mModule->loadProc(); + if (NS_FAILED(rv)) { + mFailed = true; + return false; + } } - return true; + mLoaded = true; + } + return true; } nsCString nsComponentManagerImpl::KnownModule::Description() const { - nsCString s; - if (mFile) - mFile.GetURIString(s); - else - s = ""; - return s; + nsCString s; + if (mFile) { + mFile.GetURIString(s); + } else { + s = ""; + } + return s; } nsresult nsComponentManagerImpl::Shutdown(void) { - PR_ASSERT(NORMAL == mStatus); + PR_ASSERT(NORMAL == mStatus); - mStatus = SHUTDOWN_IN_PROGRESS; + mStatus = SHUTDOWN_IN_PROGRESS; - // Shutdown the component manager - PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, ("nsComponentManager: Beginning Shutdown.")); + // Shutdown the component manager + PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, + ("nsComponentManager: Beginning Shutdown.")); - UnregisterWeakMemoryReporter(this); + UnregisterWeakMemoryReporter(this); - // Release all cached factories - mContractIDs.Clear(); - mFactories.Clear(); // XXX release the objects, don't just clear - mLoaderMap.Clear(); - mKnownModules.Clear(); - mKnownStaticModules.Clear(); + // Release all cached factories + mContractIDs.Clear(); + mFactories.Clear(); // XXX release the objects, don't just clear + mLoaderMap.Clear(); + mKnownModules.Clear(); + mKnownStaticModules.Clear(); - delete sStaticModules; - delete sModuleLocations; + delete sStaticModules; + delete sModuleLocations; #ifdef MOZ_B2G_LOADER - delete sXPTIInfosBook; - sXPTIInfosBook = nullptr; + delete sXPTIInfosBook; + sXPTIInfosBook = nullptr; #endif - // Unload libraries - mNativeModuleLoader.UnloadLibraries(); + // Unload libraries + mNativeModuleLoader.UnloadLibraries(); - // delete arena for strings and small objects - PL_FinishArenaPool(&mArena); + // delete arena for strings and small objects + PL_FinishArenaPool(&mArena); - mStatus = SHUTDOWN_COMPLETE; + mStatus = SHUTDOWN_COMPLETE; - PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, ("nsComponentManager: Shutdown complete.")); + PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, + ("nsComponentManager: Shutdown complete.")); - return NS_OK; + return NS_OK; } nsComponentManagerImpl::~nsComponentManagerImpl() { - PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, ("nsComponentManager: Beginning destruction.")); + PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, + ("nsComponentManager: Beginning destruction.")); - if (SHUTDOWN_COMPLETE != mStatus) - Shutdown(); + if (SHUTDOWN_COMPLETE != mStatus) { + Shutdown(); + } - PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, ("nsComponentManager: Destroyed.")); + PR_LOG(nsComponentManagerLog, PR_LOG_DEBUG, + ("nsComponentManager: Destroyed.")); } -NS_IMPL_ISUPPORTS( - nsComponentManagerImpl, - nsIComponentManager, - nsIServiceManager, - nsIComponentRegistrar, - nsISupportsWeakReference, - nsIInterfaceRequestor, - nsIMemoryReporter) +NS_IMPL_ISUPPORTS(nsComponentManagerImpl, + nsIComponentManager, + nsIServiceManager, + nsIComponentRegistrar, + nsISupportsWeakReference, + nsIInterfaceRequestor, + nsIMemoryReporter) nsresult -nsComponentManagerImpl::GetInterface(const nsIID & uuid, void **result) +nsComponentManagerImpl::GetInterface(const nsIID& aUuid, void** aResult) { - NS_WARNING("This isn't supported"); - // fall through to QI as anything QIable is a superset of what can be - // got via the GetInterface() - return QueryInterface(uuid, result); + NS_WARNING("This isn't supported"); + // fall through to QI as anything QIable is a superset of what can be + // got via the GetInterface() + return QueryInterface(aUuid, aResult); } -nsFactoryEntry * -nsComponentManagerImpl::GetFactoryEntry(const char *aContractID, +nsFactoryEntry* +nsComponentManagerImpl::GetFactoryEntry(const char* aContractID, uint32_t aContractIDLen) { - SafeMutexAutoLock lock(mLock); - return mContractIDs.Get(nsDependentCString(aContractID, aContractIDLen)); + SafeMutexAutoLock lock(mLock); + return mContractIDs.Get(nsDependentCString(aContractID, aContractIDLen)); } -nsFactoryEntry * -nsComponentManagerImpl::GetFactoryEntry(const nsCID &aClass) +nsFactoryEntry* +nsComponentManagerImpl::GetFactoryEntry(const nsCID& aClass) { - SafeMutexAutoLock lock(mLock); - return mFactories.Get(aClass); + SafeMutexAutoLock lock(mLock); + return mFactories.Get(aClass); } already_AddRefed nsComponentManagerImpl::FindFactory(const nsCID& aClass) { - nsFactoryEntry* e = GetFactoryEntry(aClass); - if (!e) - return nullptr; + nsFactoryEntry* e = GetFactoryEntry(aClass); + if (!e) { + return nullptr; + } - return e->GetFactory(); + return e->GetFactory(); } already_AddRefed -nsComponentManagerImpl::FindFactory(const char *contractID, +nsComponentManagerImpl::FindFactory(const char* aContractID, uint32_t aContractIDLen) { - nsFactoryEntry *entry = GetFactoryEntry(contractID, aContractIDLen); - if (!entry) - return nullptr; + nsFactoryEntry* entry = GetFactoryEntry(aContractID, aContractIDLen); + if (!entry) { + return nullptr; + } - return entry->GetFactory(); + return entry->GetFactory(); } /** @@ -941,65 +985,67 @@ nsComponentManagerImpl::FindFactory(const char *contractID, * Returns an interface of type aIID off the singleton classobject. */ NS_IMETHODIMP -nsComponentManagerImpl::GetClassObject(const nsCID &aClass, const nsIID &aIID, - void **aResult) +nsComponentManagerImpl::GetClassObject(const nsCID& aClass, const nsIID& aIID, + void** aResult) { - nsresult rv; + nsresult rv; #ifdef PR_LOGGING - if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_DEBUG)) - { - char *buf = aClass.ToString(); - PR_LogPrint("nsComponentManager: GetClassObject(%s)", buf); - if (buf) - NS_Free(buf); + if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_DEBUG)) { + char* buf = aClass.ToString(); + PR_LogPrint("nsComponentManager: GetClassObject(%s)", buf); + if (buf) { + NS_Free(buf); } + } #endif - PR_ASSERT(aResult != nullptr); + PR_ASSERT(aResult != nullptr); - nsCOMPtr factory = FindFactory(aClass); - if (!factory) - return NS_ERROR_FACTORY_NOT_REGISTERED; + nsCOMPtr factory = FindFactory(aClass); + if (!factory) { + return NS_ERROR_FACTORY_NOT_REGISTERED; + } - rv = factory->QueryInterface(aIID, aResult); + rv = factory->QueryInterface(aIID, aResult); - PR_LOG(nsComponentManagerLog, PR_LOG_WARNING, - ("\t\tGetClassObject() %s", NS_SUCCEEDED(rv) ? "succeeded" : "FAILED")); + PR_LOG(nsComponentManagerLog, PR_LOG_WARNING, + ("\t\tGetClassObject() %s", NS_SUCCEEDED(rv) ? "succeeded" : "FAILED")); - return rv; + return rv; } NS_IMETHODIMP -nsComponentManagerImpl::GetClassObjectByContractID(const char *contractID, - const nsIID &aIID, - void **aResult) +nsComponentManagerImpl::GetClassObjectByContractID(const char* aContractID, + const nsIID& aIID, + void** aResult) { - if (NS_WARN_IF(!aResult) || - NS_WARN_IF(!contractID)) - return NS_ERROR_INVALID_ARG; + if (NS_WARN_IF(!aResult) || + NS_WARN_IF(!aContractID)) { + return NS_ERROR_INVALID_ARG; + } - nsresult rv; + nsresult rv; #ifdef PR_LOGGING - if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_DEBUG)) - { - PR_LogPrint("nsComponentManager: GetClassObject(%s)", contractID); - } + if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_DEBUG)) { + PR_LogPrint("nsComponentManager: GetClassObject(%s)", aContractID); + } #endif - nsCOMPtr factory = FindFactory(contractID, strlen(contractID)); - if (!factory) - return NS_ERROR_FACTORY_NOT_REGISTERED; + nsCOMPtr factory = FindFactory(aContractID, strlen(aContractID)); + if (!factory) { + return NS_ERROR_FACTORY_NOT_REGISTERED; + } - rv = factory->QueryInterface(aIID, aResult); + rv = factory->QueryInterface(aIID, aResult); - PR_LOG(nsComponentManagerLog, PR_LOG_WARNING, - ("\t\tGetClassObject() %s", NS_SUCCEEDED(rv) ? "succeeded" : "FAILED")); + PR_LOG(nsComponentManagerLog, PR_LOG_WARNING, + ("\t\tGetClassObject() %s", NS_SUCCEEDED(rv) ? "succeeded" : "FAILED")); - return rv; + return rv; } /** @@ -1010,76 +1056,75 @@ nsComponentManagerImpl::GetClassObjectByContractID(const char *contractID, * released and not held onto for any longer. */ NS_IMETHODIMP -nsComponentManagerImpl::CreateInstance(const nsCID &aClass, - nsISupports *aDelegate, - const nsIID &aIID, - void **aResult) -{ - // 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 +nsComponentManagerImpl::CreateInstance(const nsCID& aClass, + nsISupports* aDelegate, + const nsIID& aIID, + void** aResult) +{ + // 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 cid, iid; - cid.Adopt(aClass.ToString()); - iid.Adopt(aIID.ToString()); - fprintf(stderr, "Creating new instance on shutdown. Denied.\n" - " CID: %s\n IID: %s\n", cid.get(), iid.get()); + nsXPIDLCString cid, iid; + cid.Adopt(aClass.ToString()); + iid.Adopt(aIID.ToString()); + fprintf(stderr, "Creating new instance on shutdown. Denied.\n" + " CID: %s\n IID: %s\n", cid.get(), iid.get()); #endif /* SHOW_DENIED_ON_SHUTDOWN */ - return NS_ERROR_UNEXPECTED; - } + return NS_ERROR_UNEXPECTED; + } - if (aResult == nullptr) - { - return NS_ERROR_NULL_POINTER; - } - *aResult = nullptr; + if (!aResult) { + return NS_ERROR_NULL_POINTER; + } + *aResult = nullptr; - nsFactoryEntry *entry = GetFactoryEntry(aClass); + nsFactoryEntry* entry = GetFactoryEntry(aClass); - if (!entry) - return NS_ERROR_FACTORY_NOT_REGISTERED; + if (!entry) { + return NS_ERROR_FACTORY_NOT_REGISTERED; + } #ifdef SHOW_CI_ON_EXISTING_SERVICE - if (entry->mServiceObject) { - nsXPIDLCString cid; - cid.Adopt(aClass.ToString()); - nsAutoCString message; - message = NS_LITERAL_CSTRING("You are calling CreateInstance \"") + - cid + NS_LITERAL_CSTRING("\" when a service for this CID already exists!"); - NS_ERROR(message.get()); - } + if (entry->mServiceObject) { + nsXPIDLCString cid; + cid.Adopt(aClass.ToString()); + nsAutoCString message; + message = NS_LITERAL_CSTRING("You are calling CreateInstance \"") + + cid + + NS_LITERAL_CSTRING("\" when a service for this CID already exists!"); + NS_ERROR(message.get()); + } #endif - nsresult rv; - nsCOMPtr factory = entry->GetFactory(); - if (factory) - { - rv = factory->CreateInstance(aDelegate, aIID, aResult); - if (NS_SUCCEEDED(rv) && !*aResult) { - NS_ERROR("Factory did not return an object but returned success!"); - rv = NS_ERROR_SERVICE_NOT_FOUND; - } - } - else { - // Translate error values - rv = NS_ERROR_FACTORY_NOT_REGISTERED; + nsresult rv; + nsCOMPtr factory = entry->GetFactory(); + if (factory) { + rv = factory->CreateInstance(aDelegate, aIID, aResult); + if (NS_SUCCEEDED(rv) && !*aResult) { + NS_ERROR("Factory did not return an object but returned success!"); + rv = NS_ERROR_SERVICE_NOT_FOUND; } + } else { + // Translate error values + rv = NS_ERROR_FACTORY_NOT_REGISTERED; + } #ifdef PR_LOGGING - if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_WARNING)) - { - char *buf = aClass.ToString(); - PR_LOG(nsComponentManagerLog, PR_LOG_WARNING, - ("nsComponentManager: CreateInstance(%s) %s", buf, - NS_SUCCEEDED(rv) ? "succeeded" : "FAILED")); - if (buf) - NS_Free(buf); + if (PR_LOG_TEST(nsComponentManagerLog, PR_LOG_WARNING)) { + char* buf = aClass.ToString(); + PR_LOG(nsComponentManagerLog, PR_LOG_WARNING, + ("nsComponentManager: CreateInstance(%s) %s", buf, + NS_SUCCEEDED(rv) ? "succeeded" : "FAILED")); + if (buf) { + NS_Free(buf); } + } #endif - return rv; + return rv; } /** @@ -1092,94 +1137,95 @@ nsComponentManagerImpl::CreateInstance(const nsCID &aClass, * 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; - - // 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 +nsComponentManagerImpl::CreateInstanceByContractID(const char* aContractID, + nsISupports* aDelegate, + const nsIID& aIID, + void** aResult) +{ + if (NS_WARN_IF(!aContractID)) { + return NS_ERROR_INVALID_ARG; + } + + // 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; - iid.Adopt(aIID.ToString()); - fprintf(stderr, "Creating new instance on shutdown. Denied.\n" - " ContractID: %s\n IID: %s\n", aContractID, iid.get()); + nsXPIDLCString iid; + iid.Adopt(aIID.ToString()); + fprintf(stderr, "Creating new instance on shutdown. Denied.\n" + " ContractID: %s\n IID: %s\n", aContractID, iid.get()); #endif /* SHOW_DENIED_ON_SHUTDOWN */ - return NS_ERROR_UNEXPECTED; - } + return NS_ERROR_UNEXPECTED; + } - if (aResult == nullptr) - { - return NS_ERROR_NULL_POINTER; - } - *aResult = nullptr; + if (!aResult) { + return NS_ERROR_NULL_POINTER; + } + *aResult = nullptr; - nsFactoryEntry *entry = GetFactoryEntry(aContractID, strlen(aContractID)); + nsFactoryEntry* entry = GetFactoryEntry(aContractID, strlen(aContractID)); - if (!entry) - return NS_ERROR_FACTORY_NOT_REGISTERED; + if (!entry) { + return NS_ERROR_FACTORY_NOT_REGISTERED; + } #ifdef SHOW_CI_ON_EXISTING_SERVICE - if (entry->mServiceObject) { - nsAutoCString message; - message = - NS_LITERAL_CSTRING("You are calling CreateInstance \"") + - nsDependentCString(aContractID) + - NS_LITERAL_CSTRING("\" when a service for this CID already exists! " - "Add it to abusedContracts to track down the service consumer."); - NS_ERROR(message.get()); - } + if (entry->mServiceObject) { + nsAutoCString message; + message = + NS_LITERAL_CSTRING("You are calling CreateInstance \"") + + nsDependentCString(aContractID) + + NS_LITERAL_CSTRING("\" when a service for this CID already exists! " + "Add it to abusedContracts to track down the service consumer."); + NS_ERROR(message.get()); + } #endif - nsresult rv; - nsCOMPtr factory = entry->GetFactory(); - if (factory) - { + nsresult rv; + nsCOMPtr factory = entry->GetFactory(); + if (factory) { - rv = factory->CreateInstance(aDelegate, aIID, aResult); - if (NS_SUCCEEDED(rv) && !*aResult) { - NS_ERROR("Factory did not return an object but returned success!"); - rv = NS_ERROR_SERVICE_NOT_FOUND; - } - } - else { - // Translate error values - rv = NS_ERROR_FACTORY_NOT_REGISTERED; + rv = factory->CreateInstance(aDelegate, aIID, aResult); + if (NS_SUCCEEDED(rv) && !*aResult) { + NS_ERROR("Factory did not return an object but returned success!"); + rv = NS_ERROR_SERVICE_NOT_FOUND; } + } else { + // Translate error values + rv = NS_ERROR_FACTORY_NOT_REGISTERED; + } - PR_LOG(nsComponentManagerLog, PR_LOG_WARNING, - ("nsComponentManager: CreateInstanceByContractID(%s) %s", aContractID, - NS_SUCCEEDED(rv) ? "succeeded" : "FAILED")); + PR_LOG(nsComponentManagerLog, PR_LOG_WARNING, + ("nsComponentManager: CreateInstanceByContractID(%s) %s", aContractID, + NS_SUCCEEDED(rv) ? "succeeded" : "FAILED")); - return rv; + return rv; } static PLDHashOperator FreeFactoryEntries(const nsID& aCID, nsFactoryEntry* aEntry, - void* arg) + void* aArg) { - aEntry->mFactory = nullptr; - aEntry->mServiceObject = nullptr; - return PL_DHASH_NEXT; + aEntry->mFactory = nullptr; + aEntry->mServiceObject = nullptr; + return PL_DHASH_NEXT; } nsresult nsComponentManagerImpl::FreeServices() { - NS_ASSERTION(gXPCOMShuttingDown, "Must be shutting down in order to free all services"); + NS_ASSERTION(gXPCOMShuttingDown, + "Must be shutting down in order to free all services"); - if (!gXPCOMShuttingDown) - return NS_ERROR_FAILURE; + if (!gXPCOMShuttingDown) { + return NS_ERROR_FAILURE; + } - mFactories.EnumerateRead(FreeFactoryEntries, nullptr); - return NS_OK; + mFactories.EnumerateRead(FreeFactoryEntries, nullptr); + return NS_OK; } // This should only ever be called within the monitor! @@ -1226,322 +1272,329 @@ nsComponentManagerImpl::GetPendingServiceThread(const nsCID& aServiceCID) const NS_IMETHODIMP nsComponentManagerImpl::GetService(const nsCID& aClass, const nsIID& aIID, - void* *result) + void** aResult) { - // test this first, since there's no point in returning a service 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 + // test this first, since there's no point in returning a service 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 cid, iid; - cid.Adopt(aClass.ToString()); - iid.Adopt(aIID.ToString()); - fprintf(stderr, "Getting service on shutdown. Denied.\n" - " CID: %s\n IID: %s\n", cid.get(), iid.get()); + nsXPIDLCString cid, iid; + cid.Adopt(aClass.ToString()); + iid.Adopt(aIID.ToString()); + fprintf(stderr, "Getting service on shutdown. Denied.\n" + " CID: %s\n IID: %s\n", cid.get(), iid.get()); #endif /* SHOW_DENIED_ON_SHUTDOWN */ - return NS_ERROR_UNEXPECTED; - } - - // `service` must be released after the lock is released, so it must be - // declared before the lock in this C++ block. - nsCOMPtr service; - MutexLock lock(mLock); + return NS_ERROR_UNEXPECTED; + } - nsFactoryEntry* entry = mFactories.Get(aClass); - if (!entry) - return NS_ERROR_FACTORY_NOT_REGISTERED; + // `service` must be released after the lock is released, so it must be + // declared before the lock in this C++ block. + nsCOMPtr service; + MutexLock lock(mLock); - if (entry->mServiceObject) { - lock.Unlock(); - return entry->mServiceObject->QueryInterface(aIID, result); - } + nsFactoryEntry* entry = mFactories.Get(aClass); + if (!entry) { + return NS_ERROR_FACTORY_NOT_REGISTERED; + } - PRThread* currentPRThread = PR_GetCurrentThread(); - MOZ_ASSERT(currentPRThread, "This should never be null!"); + if (entry->mServiceObject) { + lock.Unlock(); + return entry->mServiceObject->QueryInterface(aIID, aResult); + } - // Needed to optimize the event loop below. - nsIThread* currentThread = nullptr; + PRThread* currentPRThread = PR_GetCurrentThread(); + MOZ_ASSERT(currentPRThread, "This should never be null!"); - PRThread* pendingPRThread; - while ((pendingPRThread = GetPendingServiceThread(aClass))) { - if (pendingPRThread == currentPRThread) { - NS_ERROR("Recursive GetService!"); - return NS_ERROR_NOT_AVAILABLE; - } + // Needed to optimize the event loop below. + nsIThread* currentThread = nullptr; + PRThread* pendingPRThread; + while ((pendingPRThread = GetPendingServiceThread(aClass))) { + if (pendingPRThread == currentPRThread) { + NS_ERROR("Recursive GetService!"); + return NS_ERROR_NOT_AVAILABLE; + } - SafeMutexAutoUnlock unlockPending(mLock); - if (!currentThread) { - currentThread = NS_GetCurrentThread(); - MOZ_ASSERT(currentThread, "This should never be null!"); - } + SafeMutexAutoUnlock unlockPending(mLock); - // This will process a single event or yield the thread if no event is - // pending. - if (!NS_ProcessNextEvent(currentThread, false)) { - PR_Sleep(PR_INTERVAL_NO_WAIT); - } + if (!currentThread) { + currentThread = NS_GetCurrentThread(); + MOZ_ASSERT(currentThread, "This should never be null!"); } - // It's still possible that the other thread failed to create the - // service so we're not guaranteed to have an entry or service yet. - if (entry->mServiceObject) { - lock.Unlock(); - return entry->mServiceObject->QueryInterface(aIID, result); + // This will process a single event or yield the thread if no event is + // pending. + if (!NS_ProcessNextEvent(currentThread, false)) { + PR_Sleep(PR_INTERVAL_NO_WAIT); } + } + + // It's still possible that the other thread failed to create the + // service so we're not guaranteed to have an entry or service yet. + if (entry->mServiceObject) { + lock.Unlock(); + return entry->mServiceObject->QueryInterface(aIID, aResult); + } #ifdef DEBUG - PendingServiceInfo* newInfo = + PendingServiceInfo* newInfo = #endif AddPendingService(aClass, currentPRThread); - NS_ASSERTION(newInfo, "Failed to add info to the array!"); + NS_ASSERTION(newInfo, "Failed to add info to the array!"); - // We need to not be holding the service manager's lock while calling - // CreateInstance, because it invokes user code which could try to re-enter - // the service manager: + // We need to not be holding the service manager's lock while calling + // CreateInstance, because it invokes user code which could try to re-enter + // the service manager: - nsresult rv; - { - SafeMutexAutoUnlock unlock(mLock); - rv = CreateInstance(aClass, nullptr, aIID, getter_AddRefs(service)); - } - if (NS_SUCCEEDED(rv) && !service) { - NS_ERROR("Factory did not return an object but returned success"); - return NS_ERROR_SERVICE_NOT_FOUND; - } + nsresult rv; + { + SafeMutexAutoUnlock unlock(mLock); + rv = CreateInstance(aClass, nullptr, aIID, getter_AddRefs(service)); + } + if (NS_SUCCEEDED(rv) && !service) { + NS_ERROR("Factory did not return an object but returned success"); + return NS_ERROR_SERVICE_NOT_FOUND; + } #ifdef DEBUG - pendingPRThread = GetPendingServiceThread(aClass); - MOZ_ASSERT(pendingPRThread == currentPRThread, - "Pending service array has been changed!"); + pendingPRThread = GetPendingServiceThread(aClass); + MOZ_ASSERT(pendingPRThread == currentPRThread, + "Pending service array has been changed!"); #endif - RemovePendingService(aClass); + RemovePendingService(aClass); - if (NS_FAILED(rv)) - return rv; + if (NS_FAILED(rv)) { + return rv; + } - NS_ASSERTION(!entry->mServiceObject, "Created two instances of a service!"); + NS_ASSERTION(!entry->mServiceObject, "Created two instances of a service!"); - entry->mServiceObject = service.forget(); + entry->mServiceObject = service.forget(); - lock.Unlock(); - nsISupports** sresult = reinterpret_cast(result); - *sresult = entry->mServiceObject; - (*sresult)->AddRef(); + lock.Unlock(); + nsISupports** sresult = reinterpret_cast(aResult); + *sresult = entry->mServiceObject; + (*sresult)->AddRef(); - return NS_OK; + return NS_OK; } NS_IMETHODIMP -nsComponentManagerImpl::IsServiceInstantiated(const nsCID & aClass, +nsComponentManagerImpl::IsServiceInstantiated(const nsCID& aClass, const nsIID& aIID, - bool *result) + bool* aResult) { - // Now we want to get the service if we already got it. If not, we don't want - // to create an instance of it. mmh! + // Now we want to get the service if we already got it. If not, we don't want + // to create an instance of it. mmh! - // test this first, since there's no point in returning a service 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 + // test this first, since there's no point in returning a service 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 cid, iid; - cid.Adopt(aClass.ToString()); - iid.Adopt(aIID.ToString()); - fprintf(stderr, "Checking for service on shutdown. Denied.\n" - " CID: %s\n IID: %s\n", cid.get(), iid.get()); + nsXPIDLCString cid, iid; + cid.Adopt(aClass.ToString()); + iid.Adopt(aIID.ToString()); + fprintf(stderr, "Checking for service on shutdown. Denied.\n" + " CID: %s\n IID: %s\n", cid.get(), iid.get()); #endif /* SHOW_DENIED_ON_SHUTDOWN */ - return NS_ERROR_UNEXPECTED; - } + return NS_ERROR_UNEXPECTED; + } - nsresult rv = NS_ERROR_SERVICE_NOT_AVAILABLE; - nsFactoryEntry* entry; + nsresult rv = NS_ERROR_SERVICE_NOT_AVAILABLE; + nsFactoryEntry* entry; - { - SafeMutexAutoLock lock(mLock); - entry = mFactories.Get(aClass); - } + { + SafeMutexAutoLock lock(mLock); + entry = mFactories.Get(aClass); + } - if (entry && entry->mServiceObject) { - nsCOMPtr service; - rv = entry->mServiceObject->QueryInterface(aIID, getter_AddRefs(service)); - *result = (service!=nullptr); - } + if (entry && entry->mServiceObject) { + nsCOMPtr service; + rv = entry->mServiceObject->QueryInterface(aIID, getter_AddRefs(service)); + *aResult = (service != nullptr); + } - return rv; + return rv; } -NS_IMETHODIMP nsComponentManagerImpl::IsServiceInstantiatedByContractID(const char *aContractID, - const nsIID& aIID, - bool *result) -{ - // Now we want to get the service if we already got it. If not, we don't want - // to create an instance of it. mmh! - - // test this first, since there's no point in returning a service 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 +NS_IMETHODIMP +nsComponentManagerImpl::IsServiceInstantiatedByContractID( + const char* aContractID, + const nsIID& aIID, + bool* aResult) +{ + // Now we want to get the service if we already got it. If not, we don't want + // to create an instance of it. mmh! + + // test this first, since there's no point in returning a service 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; - iid.Adopt(aIID.ToString()); - fprintf(stderr, "Checking for service on shutdown. Denied.\n" - " ContractID: %s\n IID: %s\n", aContractID, iid.get()); + nsXPIDLCString iid; + iid.Adopt(aIID.ToString()); + fprintf(stderr, "Checking for service on shutdown. Denied.\n" + " ContractID: %s\n IID: %s\n", aContractID, iid.get()); #endif /* SHOW_DENIED_ON_SHUTDOWN */ - return NS_ERROR_UNEXPECTED; - } + return NS_ERROR_UNEXPECTED; + } - nsresult rv = NS_ERROR_SERVICE_NOT_AVAILABLE; - nsFactoryEntry *entry; - { - SafeMutexAutoLock lock(mLock); - entry = mContractIDs.Get(nsDependentCString(aContractID)); - } + nsresult rv = NS_ERROR_SERVICE_NOT_AVAILABLE; + nsFactoryEntry* entry; + { + SafeMutexAutoLock lock(mLock); + entry = mContractIDs.Get(nsDependentCString(aContractID)); + } - if (entry && entry->mServiceObject) { - nsCOMPtr service; - rv = entry->mServiceObject->QueryInterface(aIID, getter_AddRefs(service)); - *result = (service!=nullptr); - } - return rv; + if (entry && entry->mServiceObject) { + nsCOMPtr service; + rv = entry->mServiceObject->QueryInterface(aIID, getter_AddRefs(service)); + *aResult = (service != nullptr); + } + return rv; } NS_IMETHODIMP nsComponentManagerImpl::GetServiceByContractID(const char* aContractID, const nsIID& aIID, - void* *result) + void** aResult) { - // test this first, since there's no point in returning a service 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 + // test this first, since there's no point in returning a service 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; - iid.Adopt(aIID.ToString()); - fprintf(stderr, "Getting service on shutdown. Denied.\n" - " ContractID: %s\n IID: %s\n", aContractID, iid.get()); + nsXPIDLCString iid; + iid.Adopt(aIID.ToString()); + fprintf(stderr, "Getting service on shutdown. Denied.\n" + " ContractID: %s\n IID: %s\n", aContractID, iid.get()); #endif /* SHOW_DENIED_ON_SHUTDOWN */ - return NS_ERROR_UNEXPECTED; - } + return NS_ERROR_UNEXPECTED; + } - // `service` must be released after the lock is released, so it must be - // declared before the lock in this C++ block. - nsCOMPtr service; - MutexLock lock(mLock); + // `service` must be released after the lock is released, so it must be + // declared before the lock in this C++ block. + nsCOMPtr service; + MutexLock lock(mLock); - nsFactoryEntry *entry = mContractIDs.Get(nsDependentCString(aContractID)); - if (!entry) - return NS_ERROR_FACTORY_NOT_REGISTERED; - - if (entry->mServiceObject) { - // We need to not be holding the service manager's monitor while calling - // QueryInterface, because it invokes user code which could try to re-enter - // the service manager, or try to grab some other lock/monitor/condvar - // and deadlock, e.g. bug 282743. - // `entry` is valid until XPCOM shutdown, so we can safely use it after - // exiting the lock. - lock.Unlock(); - return entry->mServiceObject->QueryInterface(aIID, result); - } + nsFactoryEntry* entry = mContractIDs.Get(nsDependentCString(aContractID)); + if (!entry) { + return NS_ERROR_FACTORY_NOT_REGISTERED; + } - PRThread* currentPRThread = PR_GetCurrentThread(); - MOZ_ASSERT(currentPRThread, "This should never be null!"); + if (entry->mServiceObject) { + // We need to not be holding the service manager's monitor while calling + // QueryInterface, because it invokes user code which could try to re-enter + // the service manager, or try to grab some other lock/monitor/condvar + // and deadlock, e.g. bug 282743. + // `entry` is valid until XPCOM shutdown, so we can safely use it after + // exiting the lock. + lock.Unlock(); + return entry->mServiceObject->QueryInterface(aIID, aResult); + } - // Needed to optimize the event loop below. - nsIThread* currentThread = nullptr; + PRThread* currentPRThread = PR_GetCurrentThread(); + MOZ_ASSERT(currentPRThread, "This should never be null!"); - PRThread* pendingPRThread; - while ((pendingPRThread = GetPendingServiceThread(*entry->mCIDEntry->cid))) { - if (pendingPRThread == currentPRThread) { - NS_ERROR("Recursive GetService!"); - return NS_ERROR_NOT_AVAILABLE; - } + // Needed to optimize the event loop below. + nsIThread* currentThread = nullptr; - SafeMutexAutoUnlock unlockPending(mLock); + PRThread* pendingPRThread; + while ((pendingPRThread = GetPendingServiceThread(*entry->mCIDEntry->cid))) { + if (pendingPRThread == currentPRThread) { + NS_ERROR("Recursive GetService!"); + return NS_ERROR_NOT_AVAILABLE; + } - if (!currentThread) { - currentThread = NS_GetCurrentThread(); - MOZ_ASSERT(currentThread, "This should never be null!"); - } + SafeMutexAutoUnlock unlockPending(mLock); - // This will process a single event or yield the thread if no event is - // pending. - if (!NS_ProcessNextEvent(currentThread, false)) { - PR_Sleep(PR_INTERVAL_NO_WAIT); - } + if (!currentThread) { + currentThread = NS_GetCurrentThread(); + MOZ_ASSERT(currentThread, "This should never be null!"); } - if (currentThread && entry->mServiceObject) { - // If we have a currentThread then we must have waited on another thread - // to create the service. Grab it now if that succeeded. - lock.Unlock(); - return entry->mServiceObject->QueryInterface(aIID, result); + // This will process a single event or yield the thread if no event is + // pending. + if (!NS_ProcessNextEvent(currentThread, false)) { + PR_Sleep(PR_INTERVAL_NO_WAIT); } + } + + if (currentThread && entry->mServiceObject) { + // If we have a currentThread then we must have waited on another thread + // to create the service. Grab it now if that succeeded. + lock.Unlock(); + return entry->mServiceObject->QueryInterface(aIID, aResult); + } #ifdef DEBUG - PendingServiceInfo* newInfo = + PendingServiceInfo* newInfo = #endif AddPendingService(*entry->mCIDEntry->cid, currentPRThread); - NS_ASSERTION(newInfo, "Failed to add info to the array!"); + NS_ASSERTION(newInfo, "Failed to add info to the array!"); - // We need to not be holding the service manager's lock while calling - // CreateInstance, because it invokes user code which could try to re-enter - // the service manager: + // We need to not be holding the service manager's lock while calling + // CreateInstance, because it invokes user code which could try to re-enter + // the service manager: - nsresult rv; - { - SafeMutexAutoUnlock unlock(mLock); - rv = CreateInstanceByContractID(aContractID, nullptr, aIID, - getter_AddRefs(service)); - } - if (NS_SUCCEEDED(rv) && !service) { - NS_ERROR("Factory did not return an object but returned success"); - return NS_ERROR_SERVICE_NOT_FOUND; - } + nsresult rv; + { + SafeMutexAutoUnlock unlock(mLock); + rv = CreateInstanceByContractID(aContractID, nullptr, aIID, + getter_AddRefs(service)); + } + if (NS_SUCCEEDED(rv) && !service) { + NS_ERROR("Factory did not return an object but returned success"); + return NS_ERROR_SERVICE_NOT_FOUND; + } #ifdef DEBUG - pendingPRThread = GetPendingServiceThread(*entry->mCIDEntry->cid); - MOZ_ASSERT(pendingPRThread == currentPRThread, - "Pending service array has been changed!"); + pendingPRThread = GetPendingServiceThread(*entry->mCIDEntry->cid); + MOZ_ASSERT(pendingPRThread == currentPRThread, + "Pending service array has been changed!"); #endif - RemovePendingService(*entry->mCIDEntry->cid); + RemovePendingService(*entry->mCIDEntry->cid); - if (NS_FAILED(rv)) - return rv; + if (NS_FAILED(rv)) { + return rv; + } - NS_ASSERTION(!entry->mServiceObject, "Created two instances of a service!"); + NS_ASSERTION(!entry->mServiceObject, "Created two instances of a service!"); - entry->mServiceObject = service.forget(); + entry->mServiceObject = service.forget(); - lock.Unlock(); + lock.Unlock(); - nsISupports** sresult = reinterpret_cast(result); - *sresult = entry->mServiceObject; - (*sresult)->AddRef(); + nsISupports** sresult = reinterpret_cast(aResult); + *sresult = entry->mServiceObject; + (*sresult)->AddRef(); - return NS_OK; + return NS_OK; } already_AddRefed nsComponentManagerImpl::LoaderForExtension(const nsACString& aExt) { - nsCOMPtr loader = mLoaderMap.Get(aExt); + nsCOMPtr loader = mLoaderMap.Get(aExt); + if (!loader) { + loader = do_GetServiceFromCategory("module-loader", + PromiseFlatCString(aExt).get()); if (!loader) { - loader = do_GetServiceFromCategory("module-loader", - PromiseFlatCString(aExt).get()); - if (!loader) - return nullptr; - - mLoaderMap.Put(aExt, loader); + return nullptr; } - return loader.forget(); + mLoaderMap.Put(aExt, loader); + } + + return loader.forget(); } NS_IMETHODIMP @@ -1550,75 +1603,80 @@ nsComponentManagerImpl::RegisterFactory(const nsCID& aClass, const char* aContractID, nsIFactory* aFactory) { - if (!aFactory) { - // If a null factory is passed in, this call just wants to reset - // the contract ID to point to an existing CID entry. - if (!aContractID) - return NS_ERROR_INVALID_ARG; - - SafeMutexAutoLock lock(mLock); - nsFactoryEntry* oldf = mFactories.Get(aClass); - if (!oldf) - return NS_ERROR_FACTORY_NOT_REGISTERED; - - mContractIDs.Put(nsDependentCString(aContractID), oldf); - return NS_OK; + if (!aFactory) { + // If a null factory is passed in, this call just wants to reset + // the contract ID to point to an existing CID entry. + if (!aContractID) { + return NS_ERROR_INVALID_ARG; } - nsAutoPtr f(new nsFactoryEntry(aClass, aFactory)); - SafeMutexAutoLock lock(mLock); nsFactoryEntry* oldf = mFactories.Get(aClass); - if (oldf) - return NS_ERROR_FACTORY_EXISTS; + if (!oldf) { + return NS_ERROR_FACTORY_NOT_REGISTERED; + } - if (aContractID) - mContractIDs.Put(nsDependentCString(aContractID), f); + mContractIDs.Put(nsDependentCString(aContractID), oldf); + return NS_OK; + } - mFactories.Put(aClass, f.forget()); + nsAutoPtr f(new nsFactoryEntry(aClass, aFactory)); - return NS_OK; + SafeMutexAutoLock lock(mLock); + nsFactoryEntry* oldf = mFactories.Get(aClass); + if (oldf) { + return NS_ERROR_FACTORY_EXISTS; + } + + if (aContractID) { + mContractIDs.Put(nsDependentCString(aContractID), f); + } + + mFactories.Put(aClass, f.forget()); + + return NS_OK; } NS_IMETHODIMP nsComponentManagerImpl::UnregisterFactory(const nsCID& aClass, nsIFactory* aFactory) { - // Don't release the dying factory or service object until releasing - // the component manager monitor. - nsCOMPtr dyingFactory; - nsCOMPtr dyingServiceObject; + // Don't release the dying factory or service object until releasing + // the component manager monitor. + nsCOMPtr dyingFactory; + nsCOMPtr dyingServiceObject; - { - SafeMutexAutoLock lock(mLock); - nsFactoryEntry* f = mFactories.Get(aClass); - if (!f || f->mFactory != aFactory) - return NS_ERROR_FACTORY_NOT_REGISTERED; + { + SafeMutexAutoLock lock(mLock); + nsFactoryEntry* f = mFactories.Get(aClass); + if (!f || f->mFactory != aFactory) { + return NS_ERROR_FACTORY_NOT_REGISTERED; + } - mFactories.Remove(aClass); + mFactories.Remove(aClass); - // This might leave a stale contractid -> factory mapping in - // place, so null out the factory entry (see - // nsFactoryEntry::GetFactory) - f->mFactory.swap(dyingFactory); - f->mServiceObject.swap(dyingServiceObject); - } + // This might leave a stale contractid -> factory mapping in + // place, so null out the factory entry (see + // nsFactoryEntry::GetFactory) + f->mFactory.swap(dyingFactory); + f->mServiceObject.swap(dyingServiceObject); + } - return NS_OK; + return NS_OK; } NS_IMETHODIMP nsComponentManagerImpl::AutoRegister(nsIFile* aLocation) { - XRE_AddManifestLocation(NS_COMPONENT_LOCATION, aLocation); - return NS_OK; + XRE_AddManifestLocation(NS_COMPONENT_LOCATION, aLocation); + return NS_OK; } NS_IMETHODIMP nsComponentManagerImpl::AutoUnregister(nsIFile* aLocation) { - NS_ERROR("AutoUnregister not implemented."); - return NS_ERROR_NOT_IMPLEMENTED; + NS_ERROR("AutoUnregister not implemented."); + return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP @@ -1629,126 +1687,131 @@ nsComponentManagerImpl::RegisterFactoryLocation(const nsCID& aCID, const char* aLoaderStr, const char* aType) { - NS_ERROR("RegisterFactoryLocation not implemented."); - return NS_ERROR_NOT_IMPLEMENTED; + NS_ERROR("RegisterFactoryLocation not implemented."); + return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP nsComponentManagerImpl::UnregisterFactoryLocation(const nsCID& aCID, nsIFile* aFile) { - NS_ERROR("UnregisterFactoryLocation not implemented."); - return NS_ERROR_NOT_IMPLEMENTED; + NS_ERROR("UnregisterFactoryLocation not implemented."); + return NS_ERROR_NOT_IMPLEMENTED; } NS_IMETHODIMP -nsComponentManagerImpl::IsCIDRegistered(const nsCID & aClass, - bool *_retval) +nsComponentManagerImpl::IsCIDRegistered(const nsCID& aClass, + bool* aResult) { - *_retval = (nullptr != GetFactoryEntry(aClass)); - return NS_OK; + *aResult = (nullptr != GetFactoryEntry(aClass)); + return NS_OK; } NS_IMETHODIMP -nsComponentManagerImpl::IsContractIDRegistered(const char *aClass, - bool *_retval) +nsComponentManagerImpl::IsContractIDRegistered(const char* aClass, + bool* aResult) { - if (NS_WARN_IF(!aClass)) - return NS_ERROR_INVALID_ARG; + if (NS_WARN_IF(!aClass)) { + return NS_ERROR_INVALID_ARG; + } - nsFactoryEntry *entry = GetFactoryEntry(aClass, strlen(aClass)); + nsFactoryEntry* entry = GetFactoryEntry(aClass, strlen(aClass)); - if (entry) - *_retval = true; - else - *_retval = false; - return NS_OK; + if (entry) { + *aResult = true; + } else { + *aResult = false; + } + return NS_OK; } static PLDHashOperator -EnumerateCIDHelper(const nsID& id, nsFactoryEntry* entry, void* closure) +EnumerateCIDHelper(const nsID& aId, nsFactoryEntry* aEntry, void* aClosure) { - nsCOMArray *array = static_cast*>(closure); - nsCOMPtr wrapper = new nsSupportsIDImpl(); - wrapper->SetData(&id); - array->AppendObject(wrapper); - return PL_DHASH_NEXT; + nsCOMArray* array = + static_cast*>(aClosure); + nsCOMPtr wrapper = new nsSupportsIDImpl(); + wrapper->SetData(&aId); + array->AppendObject(wrapper); + return PL_DHASH_NEXT; } NS_IMETHODIMP -nsComponentManagerImpl::EnumerateCIDs(nsISimpleEnumerator **aEnumerator) +nsComponentManagerImpl::EnumerateCIDs(nsISimpleEnumerator** aEnumerator) { - nsCOMArray array; - mFactories.EnumerateRead(EnumerateCIDHelper, &array); + nsCOMArray array; + mFactories.EnumerateRead(EnumerateCIDHelper, &array); - return NS_NewArrayEnumerator(aEnumerator, array); + return NS_NewArrayEnumerator(aEnumerator, array); } static PLDHashOperator -EnumerateContractsHelper(const nsACString& contract, nsFactoryEntry* entry, void* closure) +EnumerateContractsHelper(const nsACString& aContract, nsFactoryEntry* aEntry, + void* aClosure) { - nsTArray* array = static_cast*>(closure); - array->AppendElement(contract); - return PL_DHASH_NEXT; + nsTArray* array = static_cast*>(aClosure); + array->AppendElement(aContract); + return PL_DHASH_NEXT; } NS_IMETHODIMP -nsComponentManagerImpl::EnumerateContractIDs(nsISimpleEnumerator **aEnumerator) +nsComponentManagerImpl::EnumerateContractIDs(nsISimpleEnumerator** aEnumerator) { - nsTArray* array = new nsTArray; - mContractIDs.EnumerateRead(EnumerateContractsHelper, array); + nsTArray* array = new nsTArray; + mContractIDs.EnumerateRead(EnumerateContractsHelper, array); - nsCOMPtr e; - nsresult rv = NS_NewAdoptingUTF8StringEnumerator(getter_AddRefs(e), array); - if (NS_FAILED(rv)) - return rv; + nsCOMPtr e; + nsresult rv = NS_NewAdoptingUTF8StringEnumerator(getter_AddRefs(e), array); + if (NS_FAILED(rv)) { + return rv; + } - return CallQueryInterface(e, aEnumerator); + return CallQueryInterface(e, aEnumerator); } NS_IMETHODIMP -nsComponentManagerImpl::CIDToContractID(const nsCID & aClass, - char **_retval) +nsComponentManagerImpl::CIDToContractID(const nsCID& aClass, + char** aResult) { - NS_ERROR("CIDTOContractID not implemented"); - return NS_ERROR_FACTORY_NOT_REGISTERED; + NS_ERROR("CIDTOContractID not implemented"); + return NS_ERROR_FACTORY_NOT_REGISTERED; } NS_IMETHODIMP -nsComponentManagerImpl::ContractIDToCID(const char *aContractID, - nsCID * *_retval) -{ - { - SafeMutexAutoLock lock(mLock); - nsFactoryEntry* entry = mContractIDs.Get(nsDependentCString(aContractID)); - if (entry) { - *_retval = (nsCID*) NS_Alloc(sizeof(nsCID)); - **_retval = *entry->mCIDEntry->cid; - return NS_OK; - } +nsComponentManagerImpl::ContractIDToCID(const char* aContractID, + nsCID** aResult) +{ + { + SafeMutexAutoLock lock(mLock); + nsFactoryEntry* entry = mContractIDs.Get(nsDependentCString(aContractID)); + if (entry) { + *aResult = (nsCID*)NS_Alloc(sizeof(nsCID)); + **aResult = *entry->mCIDEntry->cid; + return NS_OK; } - *_retval = nullptr; - return NS_ERROR_FACTORY_NOT_REGISTERED; + } + *aResult = nullptr; + return NS_ERROR_FACTORY_NOT_REGISTERED; } static size_t SizeOfFactoriesEntryExcludingThis(nsIDHashKey::KeyType aKey, - nsFactoryEntry* const &aData, + nsFactoryEntry* const& aData, MallocSizeOf aMallocSizeOf, void* aUserArg) { - return aData->SizeOfIncludingThis(aMallocSizeOf); + return aData->SizeOfIncludingThis(aMallocSizeOf); } static size_t SizeOfContractIDsEntryExcludingThis(nsCStringHashKey::KeyType aKey, - nsFactoryEntry* const &aData, + nsFactoryEntry* const& aData, MallocSizeOf aMallocSizeOf, void* aUserArg) { - // We don't measure the nsFactoryEntry data because its owned by mFactories - // (which measures them in SizeOfFactoriesEntryExcludingThis). - return aKey.SizeOfExcludingThisMustBeUnshared(aMallocSizeOf); + // We don't measure the nsFactoryEntry data because its owned by mFactories + // (which measures them in SizeOfFactoriesEntryExcludingThis). + return aKey.SizeOfExcludingThisMustBeUnshared(aMallocSizeOf); } MOZ_DEFINE_MALLOC_SIZE_OF(ComponentManagerMallocSizeOf) @@ -1757,129 +1820,132 @@ NS_IMETHODIMP nsComponentManagerImpl::CollectReports(nsIHandleReportCallback* aHandleReport, nsISupports* aData, bool aAnonymize) { - return MOZ_COLLECT_REPORT( - "explicit/xpcom/component-manager", KIND_HEAP, UNITS_BYTES, - SizeOfIncludingThis(ComponentManagerMallocSizeOf), - "Memory used for the XPCOM component manager."); + return MOZ_COLLECT_REPORT("explicit/xpcom/component-manager", + KIND_HEAP, UNITS_BYTES, + SizeOfIncludingThis(ComponentManagerMallocSizeOf), + "Memory used for the XPCOM component manager."); } size_t nsComponentManagerImpl::SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf) { - size_t n = aMallocSizeOf(this); - n += mLoaderMap.SizeOfExcludingThis(nullptr, aMallocSizeOf); - n += mFactories.SizeOfExcludingThis(SizeOfFactoriesEntryExcludingThis, aMallocSizeOf); - n += mContractIDs.SizeOfExcludingThis(SizeOfContractIDsEntryExcludingThis, aMallocSizeOf); + size_t n = aMallocSizeOf(this); + n += mLoaderMap.SizeOfExcludingThis(nullptr, aMallocSizeOf); + n += mFactories.SizeOfExcludingThis(SizeOfFactoriesEntryExcludingThis, + aMallocSizeOf); + n += mContractIDs.SizeOfExcludingThis(SizeOfContractIDsEntryExcludingThis, + aMallocSizeOf); - n += sStaticModules->SizeOfIncludingThis(aMallocSizeOf); - n += sModuleLocations->SizeOfIncludingThis(aMallocSizeOf); + n += sStaticModules->SizeOfIncludingThis(aMallocSizeOf); + n += sModuleLocations->SizeOfIncludingThis(aMallocSizeOf); - n += mKnownStaticModules.SizeOfExcludingThis(aMallocSizeOf); - n += mKnownModules.SizeOfExcludingThis(nullptr, aMallocSizeOf); + n += mKnownStaticModules.SizeOfExcludingThis(aMallocSizeOf); + n += mKnownModules.SizeOfExcludingThis(nullptr, aMallocSizeOf); - n += PL_SizeOfArenaPoolExcludingPool(&mArena, aMallocSizeOf); + n += PL_SizeOfArenaPoolExcludingPool(&mArena, aMallocSizeOf); - n += mPendingServices.SizeOfExcludingThis(aMallocSizeOf); + n += mPendingServices.SizeOfExcludingThis(aMallocSizeOf); - // Measurement of the following members may be added later if DMD finds it is - // worthwhile: - // - mLoaderMap's keys and values - // - mMon - // - sStaticModules' entries - // - sModuleLocations' entries - // - mNativeModuleLoader - // - mKnownStaticModules' entries? - // - mKnownModules' keys and values? + // Measurement of the following members may be added later if DMD finds it is + // worthwhile: + // - mLoaderMap's keys and values + // - mMon + // - sStaticModules' entries + // - sModuleLocations' entries + // - mNativeModuleLoader + // - mKnownStaticModules' entries? + // - mKnownModules' keys and values? - return n; + return n; } //////////////////////////////////////////////////////////////////////////////// // nsFactoryEntry //////////////////////////////////////////////////////////////////////////////// -nsFactoryEntry::nsFactoryEntry(const mozilla::Module::CIDEntry* entry, - nsComponentManagerImpl::KnownModule* module) - : mCIDEntry(entry) - , mModule(module) +nsFactoryEntry::nsFactoryEntry(const mozilla::Module::CIDEntry* aEntry, + nsComponentManagerImpl::KnownModule* aModule) + : mCIDEntry(aEntry) + , mModule(aModule) { } -nsFactoryEntry::nsFactoryEntry(const nsCID& aCID, nsIFactory* factory) - : mCIDEntry(nullptr) - , mModule(nullptr) - , mFactory(factory) +nsFactoryEntry::nsFactoryEntry(const nsCID& aCID, nsIFactory* aFactory) + : mCIDEntry(nullptr) + , mModule(nullptr) + , mFactory(aFactory) { - mozilla::Module::CIDEntry* e = new mozilla::Module::CIDEntry(); - nsCID* cid = new nsCID; - *cid = aCID; - e->cid = cid; - mCIDEntry = e; + mozilla::Module::CIDEntry* e = new mozilla::Module::CIDEntry(); + nsCID* cid = new nsCID; + *cid = aCID; + e->cid = cid; + mCIDEntry = e; } nsFactoryEntry::~nsFactoryEntry() { - // If this was a RegisterFactory entry, we own the CIDEntry/CID - if (!mModule) { - delete mCIDEntry->cid; - delete mCIDEntry; - } + // If this was a RegisterFactory entry, we own the CIDEntry/CID + if (!mModule) { + delete mCIDEntry->cid; + delete mCIDEntry; + } } already_AddRefed nsFactoryEntry::GetFactory() { - nsComponentManagerImpl::gComponentManager->mLock.AssertNotCurrentThreadOwns(); + nsComponentManagerImpl::gComponentManager->mLock.AssertNotCurrentThreadOwns(); + + if (!mFactory) { + // RegisterFactory then UnregisterFactory can leave an entry in mContractIDs + // pointing to an unusable nsFactoryEntry. + if (!mModule) { + return nullptr; + } + + if (!mModule->Load()) { + return nullptr; + } + + // Don't set mFactory directly, it needs to be locked + nsCOMPtr factory; + if (mModule->Module()->getFactoryProc) { + factory = mModule->Module()->getFactoryProc(*mModule->Module(), + *mCIDEntry); + } else if (mCIDEntry->getFactoryProc) { + factory = mCIDEntry->getFactoryProc(*mModule->Module(), *mCIDEntry); + } else { + NS_ASSERTION(mCIDEntry->constructorProc, "no getfactory or constructor"); + factory = new mozilla::GenericFactory(mCIDEntry->constructorProc); + } + if (!factory) { + return nullptr; + } + + SafeMutexAutoLock lock(nsComponentManagerImpl::gComponentManager->mLock); + // Threads can race to set mFactory if (!mFactory) { - // RegisterFactory then UnregisterFactory can leave an entry in mContractIDs - // pointing to an unusable nsFactoryEntry. - if (!mModule) - return nullptr; - - if (!mModule->Load()) - return nullptr; - - // Don't set mFactory directly, it needs to be locked - nsCOMPtr factory; - - if (mModule->Module()->getFactoryProc) { - factory = mModule->Module()->getFactoryProc(*mModule->Module(), - *mCIDEntry); - } - else if (mCIDEntry->getFactoryProc) { - factory = mCIDEntry->getFactoryProc(*mModule->Module(), *mCIDEntry); - } - else { - NS_ASSERTION(mCIDEntry->constructorProc, "no getfactory or constructor"); - factory = new mozilla::GenericFactory(mCIDEntry->constructorProc); - } - if (!factory) - return nullptr; - - SafeMutexAutoLock lock(nsComponentManagerImpl::gComponentManager->mLock); - // Threads can race to set mFactory - if (!mFactory) { - factory.swap(mFactory); - } + factory.swap(mFactory); } - nsCOMPtr factory = mFactory; - return factory.forget(); + } + nsCOMPtr factory = mFactory; + return factory.forget(); } size_t nsFactoryEntry::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) { - size_t n = aMallocSizeOf(this); + size_t n = aMallocSizeOf(this); - // Measurement of the following members may be added later if DMD finds it is - // worthwhile: - // - mCIDEntry; - // - mModule; - // - mFactory; - // - mServiceObject; + // Measurement of the following members may be added later if DMD finds it is + // worthwhile: + // - mCIDEntry; + // - mModule; + // - mFactory; + // - mServiceObject; - return n; + return n; } //////////////////////////////////////////////////////////////////////////////// @@ -1887,47 +1953,53 @@ nsFactoryEntry::SizeOfIncludingThis(MallocSizeOf aMallocSizeOf) //////////////////////////////////////////////////////////////////////////////// nsresult -NS_GetComponentManager(nsIComponentManager* *result) +NS_GetComponentManager(nsIComponentManager** aResult) { - if (!nsComponentManagerImpl::gComponentManager) - return NS_ERROR_NOT_INITIALIZED; + if (!nsComponentManagerImpl::gComponentManager) { + return NS_ERROR_NOT_INITIALIZED; + } - NS_ADDREF(*result = nsComponentManagerImpl::gComponentManager); - return NS_OK; + NS_ADDREF(*aResult = nsComponentManagerImpl::gComponentManager); + return NS_OK; } nsresult -NS_GetServiceManager(nsIServiceManager* *result) +NS_GetServiceManager(nsIServiceManager** aResult) { - if (!nsComponentManagerImpl::gComponentManager) - return NS_ERROR_NOT_INITIALIZED; + if (!nsComponentManagerImpl::gComponentManager) { + return NS_ERROR_NOT_INITIALIZED; + } - NS_ADDREF(*result = nsComponentManagerImpl::gComponentManager); - return NS_OK; + NS_ADDREF(*aResult = nsComponentManagerImpl::gComponentManager); + return NS_OK; } nsresult -NS_GetComponentRegistrar(nsIComponentRegistrar* *result) +NS_GetComponentRegistrar(nsIComponentRegistrar** aResult) { - if (!nsComponentManagerImpl::gComponentManager) - return NS_ERROR_NOT_INITIALIZED; + if (!nsComponentManagerImpl::gComponentManager) { + return NS_ERROR_NOT_INITIALIZED; + } - NS_ADDREF(*result = nsComponentManagerImpl::gComponentManager); - return NS_OK; + NS_ADDREF(*aResult = nsComponentManagerImpl::gComponentManager); + return NS_OK; } EXPORT_XPCOM_API(nsresult) XRE_AddStaticComponent(const mozilla::Module* aComponent) { - nsComponentManagerImpl::InitializeStaticModules(); - nsComponentManagerImpl::sStaticModules->AppendElement(aComponent); + nsComponentManagerImpl::InitializeStaticModules(); + nsComponentManagerImpl::sStaticModules->AppendElement(aComponent); - if (nsComponentManagerImpl::gComponentManager && - nsComponentManagerImpl::NORMAL == nsComponentManagerImpl::gComponentManager->mStatus) - nsComponentManagerImpl::gComponentManager->RegisterModule(aComponent, nullptr); + if (nsComponentManagerImpl::gComponentManager && + nsComponentManagerImpl::NORMAL == + nsComponentManagerImpl::gComponentManager->mStatus) { + nsComponentManagerImpl::gComponentManager->RegisterModule(aComponent, + nullptr); + } - return NS_OK; + return NS_OK; } NS_IMETHODIMP @@ -1935,8 +2007,9 @@ nsComponentManagerImpl::AddBootstrappedManifestLocation(nsIFile* aLocation) { nsString path; nsresult rv = aLocation->GetPath(path); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { return rv; + } if (Substring(path, path.Length() - 4).EqualsLiteral(".xpi")) { return XRE_AddJarManifestLocation(NS_BOOTSTRAPPED_LOCATION, aLocation); @@ -1951,14 +2024,16 @@ NS_IMETHODIMP nsComponentManagerImpl::RemoveBootstrappedManifestLocation(nsIFile* aLocation) { nsCOMPtr cr = mozilla::services::GetChromeRegistryService(); - if (!cr) + if (!cr) { return NS_ERROR_FAILURE; + } nsCOMPtr manifest; nsString path; nsresult rv = aLocation->GetPath(path); - if (NS_FAILED(rv)) + if (NS_FAILED(rv)) { return rv; + } nsComponentManagerImpl::ComponentLocation elem; elem.type = NS_BOOTSTRAPPED_LOCATION; @@ -1966,25 +2041,28 @@ nsComponentManagerImpl::RemoveBootstrappedManifestLocation(nsIFile* aLocation) if (Substring(path, path.Length() - 4).EqualsLiteral(".xpi")) { elem.location.Init(aLocation, "chrome.manifest"); } else { - nsCOMPtr lf = CloneAndAppend(aLocation, NS_LITERAL_CSTRING("chrome.manifest")); + nsCOMPtr lf = + CloneAndAppend(aLocation, NS_LITERAL_CSTRING("chrome.manifest")); elem.location.Init(lf); } // Remove reference. - nsComponentManagerImpl::sModuleLocations->RemoveElement(elem, ComponentLocationComparator()); + nsComponentManagerImpl::sModuleLocations->RemoveElement(elem, + ComponentLocationComparator()); rv = cr->CheckForNewChrome(); return rv; } NS_IMETHODIMP -nsComponentManagerImpl::GetManifestLocations(nsIArray **aLocations) +nsComponentManagerImpl::GetManifestLocations(nsIArray** aLocations) { NS_ENSURE_ARG_POINTER(aLocations); *aLocations = nullptr; - if (!sModuleLocations) + if (!sModuleLocations) { return NS_ERROR_NOT_INITIALIZED; + } nsCOMPtr locations = nsArray::Create(); nsresult rv; @@ -1995,8 +2073,9 @@ nsComponentManagerImpl::GetManifestLocations(nsIArray **aLocations) loc.GetURIString(uriString); nsCOMPtr uri; rv = NS_NewURI(getter_AddRefs(uri), uriString); - if (NS_SUCCEEDED(rv)) + if (NS_SUCCEEDED(rv)) { locations->AppendElement(uri, false); + } } locations.forget(aLocations); @@ -2007,24 +2086,22 @@ nsComponentManagerImpl::GetManifestLocations(nsIArray **aLocations) /* static */ void -nsComponentManagerImpl::XPTOnlyManifestManifest(XPTOnlyManifestProcessingContext &aCx, - int aLineno, - char * const * aArgv) +nsComponentManagerImpl::XPTOnlyManifestManifest( + XPTOnlyManifestProcessingContext& aCx, int aLineNo, char* const* aArgv) { - char* file = aArgv[0]; - FileLocation f(aCx.mFile, file); + char* file = aArgv[0]; + FileLocation f(aCx.mFile, file); - DoRegisterManifest(NS_COMPONENT_LOCATION, f, false, true); + DoRegisterManifest(NS_COMPONENT_LOCATION, f, false, true); } /* static */ void -nsComponentManagerImpl::XPTOnlyManifestXPT(XPTOnlyManifestProcessingContext &aCx, - int aLineno, - char * const * aArgv) +nsComponentManagerImpl::XPTOnlyManifestXPT( + XPTOnlyManifestProcessingContext& aCx, int aLineNo, char* const* aArgv) { - FileLocation f(aCx.mFile, aArgv[0]); - DoRegisterXPT(f); + FileLocation f(aCx.mFile, aArgv[0]); + DoRegisterXPT(f); } /** @@ -2034,19 +2111,19 @@ nsComponentManagerImpl::XPTOnlyManifestXPT(XPTOnlyManifestProcessingContext &aCx * as possible to gain benefit of shared memory model of the kernel. */ /* static */ void -nsComponentManagerImpl::PreloadXPT(nsIFile *aFile) +nsComponentManagerImpl::PreloadXPT(nsIFile* aFile) { - MOZ_ASSERT(nsComponentManagerImpl::gComponentManager == nullptr); - FileLocation location(aFile, "chrome.manifest"); + MOZ_ASSERT(!nsComponentManagerImpl::gComponentManager); + FileLocation location(aFile, "chrome.manifest"); - DoRegisterManifest(NS_COMPONENT_LOCATION, location, - false, true /* aXPTOnly */); + DoRegisterManifest(NS_COMPONENT_LOCATION, location, + false, true /* aXPTOnly */); } void -PreloadXPT(nsIFile *aOmnijarFile) +PreloadXPT(nsIFile* aOmnijarFile) { - nsComponentManagerImpl::PreloadXPT(aOmnijarFile); + nsComponentManagerImpl::PreloadXPT(aOmnijarFile); } #endif /* MOZ_B2G_LOADER */ @@ -2054,33 +2131,41 @@ PreloadXPT(nsIFile *aOmnijarFile) EXPORT_XPCOM_API(nsresult) XRE_AddManifestLocation(NSLocationType aType, nsIFile* aLocation) { - nsComponentManagerImpl::InitializeModuleLocations(); - nsComponentManagerImpl::ComponentLocation* c = - nsComponentManagerImpl::sModuleLocations->AppendElement(); - c->type = aType; - c->location.Init(aLocation); - - if (nsComponentManagerImpl::gComponentManager && - nsComponentManagerImpl::NORMAL == nsComponentManagerImpl::gComponentManager->mStatus) - nsComponentManagerImpl::gComponentManager->RegisterManifest(aType, c->location, false); + nsComponentManagerImpl::InitializeModuleLocations(); + nsComponentManagerImpl::ComponentLocation* c = + nsComponentManagerImpl::sModuleLocations->AppendElement(); + c->type = aType; + c->location.Init(aLocation); + + if (nsComponentManagerImpl::gComponentManager && + nsComponentManagerImpl::NORMAL == + nsComponentManagerImpl::gComponentManager->mStatus) { + nsComponentManagerImpl::gComponentManager->RegisterManifest(aType, + c->location, + false); + } - return NS_OK; + return NS_OK; } EXPORT_XPCOM_API(nsresult) XRE_AddJarManifestLocation(NSLocationType aType, nsIFile* aLocation) { - nsComponentManagerImpl::InitializeModuleLocations(); - nsComponentManagerImpl::ComponentLocation* c = - nsComponentManagerImpl::sModuleLocations->AppendElement(); + nsComponentManagerImpl::InitializeModuleLocations(); + nsComponentManagerImpl::ComponentLocation* c = + nsComponentManagerImpl::sModuleLocations->AppendElement(); - c->type = aType; - c->location.Init(aLocation, "chrome.manifest"); + c->type = aType; + c->location.Init(aLocation, "chrome.manifest"); - if (nsComponentManagerImpl::gComponentManager && - nsComponentManagerImpl::NORMAL == nsComponentManagerImpl::gComponentManager->mStatus) - nsComponentManagerImpl::gComponentManager->RegisterManifest(aType, c->location, false); + if (nsComponentManagerImpl::gComponentManager && + nsComponentManagerImpl::NORMAL == + nsComponentManagerImpl::gComponentManager->mStatus) { + nsComponentManagerImpl::gComponentManager->RegisterManifest(aType, + c->location, + false); + } - return NS_OK; + return NS_OK; } diff --git a/xpcom/components/nsComponentManager.h b/xpcom/components/nsComponentManager.h index e0d3d159687a..d15a4dbd19ec 100644 --- a/xpcom/components/nsComponentManager.h +++ b/xpcom/components/nsComponentManager.h @@ -78,274 +78,287 @@ extern const mozilla::Module kXPCOMModule; class SafeMutex { public: - SafeMutex(const char* name) - : mMutex(name) - , mOwnerThread(nullptr) - { } - ~SafeMutex() - { } - - void Lock() - { - AssertNotCurrentThreadOwns(); - mMutex.Lock(); - MOZ_ASSERT(mOwnerThread == nullptr); - mOwnerThread = PR_GetCurrentThread(); - } - - void Unlock() - { - MOZ_ASSERT(mOwnerThread == PR_GetCurrentThread()); - mOwnerThread = nullptr; - mMutex.Unlock(); - } - - void AssertCurrentThreadOwns() const - { - // This method is a debug-only check - MOZ_ASSERT(mOwnerThread == PR_GetCurrentThread()); - } - - MOZ_NEVER_INLINE void AssertNotCurrentThreadOwns() const - { - // This method is a release-mode check - if (PR_GetCurrentThread() == mOwnerThread) { - MOZ_CRASH(); - } + SafeMutex(const char* aName) + : mMutex(aName) + , mOwnerThread(nullptr) + { + } + + ~SafeMutex() {} + + void Lock() + { + AssertNotCurrentThreadOwns(); + mMutex.Lock(); + MOZ_ASSERT(mOwnerThread == nullptr); + mOwnerThread = PR_GetCurrentThread(); + } + + void Unlock() + { + MOZ_ASSERT(mOwnerThread == PR_GetCurrentThread()); + mOwnerThread = nullptr; + mMutex.Unlock(); + } + + void AssertCurrentThreadOwns() const + { + // This method is a debug-only check + MOZ_ASSERT(mOwnerThread == PR_GetCurrentThread()); + } + + MOZ_NEVER_INLINE void AssertNotCurrentThreadOwns() const + { + // This method is a release-mode check + if (PR_GetCurrentThread() == mOwnerThread) { + MOZ_CRASH(); } + } private: - mozilla::Mutex mMutex; - volatile PRThread* mOwnerThread; + mozilla::Mutex mMutex; + volatile PRThread* mOwnerThread; }; typedef mozilla::BaseAutoLock SafeMutexAutoLock; typedef mozilla::BaseAutoUnlock SafeMutexAutoUnlock; class nsComponentManagerImpl MOZ_FINAL - : public nsIComponentManager - , public nsIServiceManager - , public nsSupportsWeakReference - , public nsIComponentRegistrar - , public nsIInterfaceRequestor - , public nsIMemoryReporter + : public nsIComponentManager + , public nsIServiceManager + , public nsSupportsWeakReference + , public nsIComponentRegistrar + , public nsIInterfaceRequestor + , public nsIMemoryReporter { public: - NS_DECL_THREADSAFE_ISUPPORTS - NS_DECL_NSIINTERFACEREQUESTOR - NS_DECL_NSICOMPONENTMANAGER - NS_DECL_NSICOMPONENTREGISTRAR - NS_DECL_NSIMEMORYREPORTER + NS_DECL_THREADSAFE_ISUPPORTS + NS_DECL_NSIINTERFACEREQUESTOR + NS_DECL_NSICOMPONENTMANAGER + NS_DECL_NSICOMPONENTREGISTRAR + NS_DECL_NSIMEMORYREPORTER - static nsresult Create(nsISupports* aOuter, REFNSIID aIID, void** aResult); + static nsresult Create(nsISupports* aOuter, REFNSIID aIID, void** aResult); - nsresult RegistryLocationForFile(nsIFile* aFile, - nsCString& aResult); - nsresult FileForRegistryLocation(const nsCString &aLocation, - nsIFile **aSpec); + nsresult RegistryLocationForFile(nsIFile* aFile, + nsCString& aResult); + nsresult FileForRegistryLocation(const nsCString& aLocation, + nsIFile** aSpec); - NS_DECL_NSISERVICEMANAGER + NS_DECL_NSISERVICEMANAGER - // nsComponentManagerImpl methods: - nsComponentManagerImpl(); + // nsComponentManagerImpl methods: + nsComponentManagerImpl(); - static nsComponentManagerImpl* gComponentManager; - nsresult Init(); + static nsComponentManagerImpl* gComponentManager; + nsresult Init(); - nsresult Shutdown(void); + nsresult Shutdown(void); - nsresult FreeServices(); + nsresult FreeServices(); - already_AddRefed LoaderForExtension(const nsACString& aExt); - nsInterfaceHashtable mLoaderMap; + already_AddRefed LoaderForExtension(const nsACString& aExt); + nsInterfaceHashtable mLoaderMap; - already_AddRefed FindFactory(const nsCID& aClass); - already_AddRefed FindFactory(const char *contractID, - uint32_t aContractIDLen); + already_AddRefed FindFactory(const nsCID& aClass); + already_AddRefed FindFactory(const char* aContractID, + uint32_t aContractIDLen); - already_AddRefed LoadFactory(nsFactoryEntry *aEntry); + already_AddRefed LoadFactory(nsFactoryEntry* aEntry); - nsFactoryEntry *GetFactoryEntry(const char *aContractID, - uint32_t aContractIDLen); - nsFactoryEntry *GetFactoryEntry(const nsCID &aClass); + nsFactoryEntry* GetFactoryEntry(const char* aContractID, + uint32_t aContractIDLen); + nsFactoryEntry* GetFactoryEntry(const nsCID& aClass); - nsDataHashtable mFactories; - nsDataHashtable mContractIDs; + nsDataHashtable mFactories; + nsDataHashtable mContractIDs; - SafeMutex mLock; + SafeMutex mLock; - static void InitializeStaticModules(); - static void InitializeModuleLocations(); + static void InitializeStaticModules(); + static void InitializeModuleLocations(); - struct ComponentLocation - { - NSLocationType type; - mozilla::FileLocation location; - }; + struct ComponentLocation + { + NSLocationType type; + mozilla::FileLocation location; + }; - class ComponentLocationComparator + class ComponentLocationComparator + { + public: + bool Equals(const ComponentLocation& aA, const ComponentLocation& aB) const { - public: - bool Equals(const ComponentLocation& a, const ComponentLocation& b) const - { - return (a.type == b.type && a.location.Equals(b.location)); - } - }; - - static nsTArray* sStaticModules; - static nsTArray* sModuleLocations; - - nsNativeModuleLoader mNativeModuleLoader; - - class KnownModule - { - public: - /** - * Static or binary module. - */ - KnownModule(const mozilla::Module* aModule, mozilla::FileLocation &aFile) - : mModule(aModule) - , mFile(aFile) - , mLoaded(false) - , mFailed(false) - { } - - KnownModule(const mozilla::Module* aModule) - : mModule(aModule) - , mLoaded(false) - , mFailed(false) - { } - - KnownModule(mozilla::FileLocation &aFile) - : mModule(nullptr) - , mFile(aFile) - , mLoader(nullptr) - , mLoaded(false) - , mFailed(false) - { } - - ~KnownModule() - { - if (mLoaded && mModule->unloadProc) - mModule->unloadProc(); - } - - bool EnsureLoader(); - bool Load(); - - const mozilla::Module* Module() const - { - return mModule; - } - - /** - * For error logging, get a description of this module, either the - * file path, or . - */ - nsCString Description() const; - - private: - const mozilla::Module* mModule; - mozilla::FileLocation mFile; - nsCOMPtr mLoader; - bool mLoaded; - bool mFailed; - }; - - // The KnownModule is kept alive by these members, it is - // referenced by pointer from the factory entries. - nsTArray< nsAutoPtr > mKnownStaticModules; - // The key is the URI string of the module - nsClassHashtable mKnownModules; - - // Mutex not held - void RegisterModule(const mozilla::Module* aModule, - mozilla::FileLocation* aFile); - - - // Mutex held - void RegisterCIDEntryLocked(const mozilla::Module::CIDEntry* aEntry, - KnownModule* aModule); - void RegisterContractIDLocked(const mozilla::Module::ContractIDEntry* aEntry); - - // Mutex not held - void RegisterManifest(NSLocationType aType, mozilla::FileLocation &aFile, - bool aChromeOnly); - - struct ManifestProcessingContext + return (aA.type == aB.type && aA.location.Equals(aB.location)); + } + }; + + static nsTArray* sStaticModules; + static nsTArray* sModuleLocations; + + nsNativeModuleLoader mNativeModuleLoader; + + class KnownModule + { + public: + /** + * Static or binary module. + */ + KnownModule(const mozilla::Module* aModule, mozilla::FileLocation& aFile) + : mModule(aModule) + , mFile(aFile) + , mLoaded(false) + , mFailed(false) { - ManifestProcessingContext(NSLocationType aType, mozilla::FileLocation &aFile, bool aChromeOnly) - : mType(aType) - , mFile(aFile) - , mChromeOnly(aChromeOnly) - { } - - ~ManifestProcessingContext() { } - - NSLocationType mType; - mozilla::FileLocation mFile; - bool mChromeOnly; - }; - - void ManifestManifest(ManifestProcessingContext& cx, int lineno, char *const * argv); - void ManifestBinaryComponent(ManifestProcessingContext& cx, int lineno, char *const * argv); - void ManifestXPT(ManifestProcessingContext& cx, int lineno, char *const * argv); - void ManifestComponent(ManifestProcessingContext& cx, int lineno, char *const * argv); - void ManifestContract(ManifestProcessingContext& cx, int lineno, char* const * argv); - void ManifestCategory(ManifestProcessingContext& cx, int lineno, char* const * argv); - - void RereadChromeManifests(bool aChromeOnly = true); - - // Shutdown - enum { - NOT_INITIALIZED, - NORMAL, - SHUTDOWN_IN_PROGRESS, - SHUTDOWN_COMPLETE - } mStatus; + } - PLArenaPool mArena; + KnownModule(const mozilla::Module* aModule) + : mModule(aModule) + , mLoaded(false) + , mFailed(false) + { + } - struct PendingServiceInfo { - const nsCID* cid; - PRThread* thread; - }; + KnownModule(mozilla::FileLocation& aFile) + : mModule(nullptr) + , mFile(aFile) + , mLoader(nullptr) + , mLoaded(false) + , mFailed(false) + { + } - inline PendingServiceInfo* AddPendingService(const nsCID& aServiceCID, - PRThread* aThread); - inline void RemovePendingService(const nsCID& aServiceCID); - inline PRThread* GetPendingServiceThread(const nsCID& aServiceCID) const; + ~KnownModule() + { + if (mLoaded && mModule->unloadProc) { + mModule->unloadProc(); + } + } - nsTArray mPendingServices; + bool EnsureLoader(); + bool Load(); + + const mozilla::Module* Module() const { return mModule; } + + /** + * For error logging, get a description of this module, either the + * file path, or . + */ + nsCString Description() const; + + private: + const mozilla::Module* mModule; + mozilla::FileLocation mFile; + nsCOMPtr mLoader; + bool mLoaded; + bool mFailed; + }; + + // The KnownModule is kept alive by these members, it is + // referenced by pointer from the factory entries. + nsTArray> mKnownStaticModules; + // The key is the URI string of the module + nsClassHashtable mKnownModules; + + // Mutex not held + void RegisterModule(const mozilla::Module* aModule, + mozilla::FileLocation* aFile); + + + // Mutex held + void RegisterCIDEntryLocked(const mozilla::Module::CIDEntry* aEntry, + KnownModule* aModule); + void RegisterContractIDLocked(const mozilla::Module::ContractIDEntry* aEntry); + + // Mutex not held + void RegisterManifest(NSLocationType aType, mozilla::FileLocation& aFile, + bool aChromeOnly); + + struct ManifestProcessingContext + { + ManifestProcessingContext(NSLocationType aType, + mozilla::FileLocation& aFile, bool aChromeOnly) + : mType(aType) + , mFile(aFile) + , mChromeOnly(aChromeOnly) + { + } - size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf); + ~ManifestProcessingContext() {} + + NSLocationType mType; + mozilla::FileLocation mFile; + bool mChromeOnly; + }; + + void ManifestManifest(ManifestProcessingContext& aCx, int aLineNo, + char* const* aArgv); + void ManifestBinaryComponent(ManifestProcessingContext& aCx, int aLineNo, + char* const* aArgv); + void ManifestXPT(ManifestProcessingContext& aCx, int aLineNo, + char* const* aArgv); + void ManifestComponent(ManifestProcessingContext& aCx, int aLineNo, + char* const* aArgv); + void ManifestContract(ManifestProcessingContext& aCx, int aLineNo, + char* const* aArgv); + void ManifestCategory(ManifestProcessingContext& aCx, int aLineNo, + char* const* aArgv); + + void RereadChromeManifests(bool aChromeOnly = true); + + // Shutdown + enum + { + NOT_INITIALIZED, + NORMAL, + SHUTDOWN_IN_PROGRESS, + SHUTDOWN_COMPLETE + } mStatus; + + PLArenaPool mArena; + + struct PendingServiceInfo + { + const nsCID* cid; + PRThread* thread; + }; + + inline PendingServiceInfo* AddPendingService(const nsCID& aServiceCID, + PRThread* aThread); + inline void RemovePendingService(const nsCID& aServiceCID); + inline PRThread* GetPendingServiceThread(const nsCID& aServiceCID) const; + + nsTArray mPendingServices; + + size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf); #ifdef MOZ_B2G_LOADER - // Preload XPT interface info for B2G loader. - // This function is called before XPCOM has been initialized. - static void PreloadXPT(nsIFile *aFile); + // Preload XPT interface info for B2G loader. + // This function is called before XPCOM has been initialized. + static void PreloadXPT(nsIFile* aFile); #endif #ifdef MOZ_B2G_LOADER - // Parsing functions of directives of manifest for XPT only parsing. - struct XPTOnlyManifestProcessingContext + // Parsing functions of directives of manifest for XPT only parsing. + struct XPTOnlyManifestProcessingContext + { + XPTOnlyManifestProcessingContext(mozilla::FileLocation& aFile) + : mFile(aFile) { - XPTOnlyManifestProcessingContext(mozilla::FileLocation &aFile) - : mFile(aFile) - { } - - ~XPTOnlyManifestProcessingContext() { } - - mozilla::FileLocation mFile; - }; - static void XPTOnlyManifestManifest(XPTOnlyManifestProcessingContext& aCx, - int aLineno, char * const *aArgv); - static void XPTOnlyManifestXPT(XPTOnlyManifestProcessingContext& aCx, - int aLineno, char * const *aArgv); + } + + ~XPTOnlyManifestProcessingContext() {} + + mozilla::FileLocation mFile; + }; + static void XPTOnlyManifestManifest(XPTOnlyManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv); + static void XPTOnlyManifestXPT(XPTOnlyManifestProcessingContext& aCx, + int aLineNo, char* const* aArgv); #endif private: - ~nsComponentManagerImpl(); + ~nsComponentManagerImpl(); }; @@ -355,23 +368,23 @@ class nsComponentManagerImpl MOZ_FINAL struct nsFactoryEntry { - nsFactoryEntry(const mozilla::Module::CIDEntry* entry, - nsComponentManagerImpl::KnownModule* module); + nsFactoryEntry(const mozilla::Module::CIDEntry* aEntry, + nsComponentManagerImpl::KnownModule* aModule); - // nsIComponentRegistrar.registerFactory support - nsFactoryEntry(const nsCID& aClass, nsIFactory* factory); + // nsIComponentRegistrar.registerFactory support + nsFactoryEntry(const nsCID& aClass, nsIFactory* aFactory); - ~nsFactoryEntry(); + ~nsFactoryEntry(); - already_AddRefed GetFactory(); + already_AddRefed GetFactory(); - size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf); + size_t SizeOfIncludingThis(mozilla::MallocSizeOf aMallocSizeOf); - const mozilla::Module::CIDEntry* mCIDEntry; - nsComponentManagerImpl::KnownModule* mModule; + const mozilla::Module::CIDEntry* mCIDEntry; + nsComponentManagerImpl::KnownModule* mModule; - nsCOMPtr mFactory; - nsCOMPtr mServiceObject; + nsCOMPtr mFactory; + nsCOMPtr mServiceObject; }; #endif // nsComponentManager_h__ diff --git a/xpcom/components/nsNativeModuleLoader.cpp b/xpcom/components/nsNativeModuleLoader.cpp index 4fc21ca416df..39b8a2329d3c 100644 --- a/xpcom/components/nsNativeModuleLoader.cpp +++ b/xpcom/components/nsNativeModuleLoader.cpp @@ -53,13 +53,14 @@ using namespace mozilla; -static PRLogModuleInfo * +static PRLogModuleInfo* GetNativeModuleLoaderLog() { - static PRLogModuleInfo *sLog; - if (!sLog) - sLog = PR_NewLogModule("nsNativeModuleLoader"); - return sLog; + static PRLogModuleInfo* sLog; + if (!sLog) { + sLog = PR_NewLogModule("nsNativeModuleLoader"); + } + return sLog; } #define LOG(level, args) PR_LOG(GetNativeModuleLoaderLog(), level, args) @@ -67,174 +68,177 @@ GetNativeModuleLoaderLog() nsresult nsNativeModuleLoader::Init() { - MOZ_ASSERT(NS_IsMainThread(), "Startup not on main thread?"); - LOG(PR_LOG_DEBUG, ("nsNativeModuleLoader::Init()")); - return NS_OK; + MOZ_ASSERT(NS_IsMainThread(), "Startup not on main thread?"); + LOG(PR_LOG_DEBUG, ("nsNativeModuleLoader::Init()")); + return NS_OK; } class LoadModuleMainThreadRunnable : public nsRunnable { public: - LoadModuleMainThreadRunnable(nsNativeModuleLoader* aLoader, - FileLocation &aFile) - : mManager(nsComponentManagerImpl::gComponentManager) - , mLoader(aLoader) - , mFile(aFile) - , mResult(nullptr) - { } - - NS_IMETHOD Run() - { - mResult = mLoader->LoadModule(mFile); - return NS_OK; - } + LoadModuleMainThreadRunnable(nsNativeModuleLoader* aLoader, + FileLocation& aFile) + : mManager(nsComponentManagerImpl::gComponentManager) + , mLoader(aLoader) + , mFile(aFile) + , mResult(nullptr) + { + } + + NS_IMETHOD Run() + { + mResult = mLoader->LoadModule(mFile); + return NS_OK; + } - nsRefPtr mManager; - nsNativeModuleLoader* mLoader; - FileLocation mFile; - const mozilla::Module* mResult; + nsRefPtr mManager; + nsNativeModuleLoader* mLoader; + FileLocation mFile; + const mozilla::Module* mResult; }; const mozilla::Module* -nsNativeModuleLoader::LoadModule(FileLocation &aFile) +nsNativeModuleLoader::LoadModule(FileLocation& aFile) { - if (aFile.IsZip()) { - NS_ERROR("Binary components cannot be loaded from JARs"); - return nullptr; - } - nsCOMPtr file = aFile.GetBaseFile(); - nsresult rv; - - if (!NS_IsMainThread()) { - // If this call is off the main thread, synchronously proxy it - // to the main thread. - nsRefPtr r = new LoadModuleMainThreadRunnable(this, aFile); - NS_DispatchToMainThread(r, NS_DISPATCH_SYNC); - return r->mResult; - } - - nsCOMPtr hashedFile(do_QueryInterface(file)); - if (!hashedFile) { - NS_ERROR("nsIFile is not nsIHashable"); - return nullptr; - } - - nsAutoCString filePath; - file->GetNativePath(filePath); - - NativeLoadData data; - - if (mLibraries.Get(hashedFile, &data)) { - NS_ASSERTION(data.mModule, "Corrupt mLibraries hash"); - LOG(PR_LOG_DEBUG, - ("nsNativeModuleLoader::LoadModule(\"%s\") - found in cache", - filePath.get())); - return data.mModule; - } + if (aFile.IsZip()) { + NS_ERROR("Binary components cannot be loaded from JARs"); + return nullptr; + } + nsCOMPtr file = aFile.GetBaseFile(); + nsresult rv; + + if (!NS_IsMainThread()) { + // If this call is off the main thread, synchronously proxy it + // to the main thread. + nsRefPtr r = + new LoadModuleMainThreadRunnable(this, aFile); + NS_DispatchToMainThread(r, NS_DISPATCH_SYNC); + return r->mResult; + } + + nsCOMPtr hashedFile(do_QueryInterface(file)); + if (!hashedFile) { + NS_ERROR("nsIFile is not nsIHashable"); + return nullptr; + } + + nsAutoCString filePath; + file->GetNativePath(filePath); + + NativeLoadData data; + + if (mLibraries.Get(hashedFile, &data)) { + NS_ASSERTION(data.mModule, "Corrupt mLibraries hash"); + LOG(PR_LOG_DEBUG, + ("nsNativeModuleLoader::LoadModule(\"%s\") - found in cache", + filePath.get())); + return data.mModule; + } - // We haven't loaded this module before - { + // We haven't loaded this module before + { #ifdef HAS_DLL_BLOCKLIST - AutoSetXPCOMLoadOnMainThread guard; + AutoSetXPCOMLoadOnMainThread guard; #endif - rv = file->Load(&data.mLibrary); - } + rv = file->Load(&data.mLibrary); + } - if (NS_FAILED(rv)) { - char errorMsg[1024] = ""; + if (NS_FAILED(rv)) { + char errorMsg[1024] = ""; - if (PR_GetErrorTextLength() < (int) sizeof(errorMsg)) - PR_GetErrorText(errorMsg); + if (PR_GetErrorTextLength() < (int)sizeof(errorMsg)) { + PR_GetErrorText(errorMsg); + } - LogMessage("Failed to load native module at path '%s': (%lx) %s", - filePath.get(), rv, errorMsg); + LogMessage("Failed to load native module at path '%s': (%lx) %s", + filePath.get(), rv, errorMsg); - return nullptr; - } + return nullptr; + } #ifdef IMPLEMENT_BREAK_AFTER_LOAD - nsAutoCString leafName; - file->GetNativeLeafName(leafName); - - char *env = getenv("XPCOM_BREAK_ON_LOAD"); - char *blist; - if (env && *env && (blist = strdup(env))) { - char *nextTok = blist; - while (char *token = NS_strtok(":", &nextTok)) { - if (leafName.Find(token, true) != kNotFound) { - NS_BREAK(); - } - } - - free(blist); - } -#endif - - void *module = PR_FindSymbol(data.mLibrary, "NSModule"); - if (!module) { - LogMessage("Native module at path '%s' doesn't export symbol `NSModule`.", - filePath.get()); - PR_UnloadLibrary(data.mLibrary); - return nullptr; + nsAutoCString leafName; + file->GetNativeLeafName(leafName); + + char* env = getenv("XPCOM_BREAK_ON_LOAD"); + char* blist; + if (env && *env && (blist = strdup(env))) { + char* nextTok = blist; + while (char* token = NS_strtok(":", &nextTok)) { + if (leafName.Find(token, true) != kNotFound) { + NS_BREAK(); + } } - data.mModule = *(mozilla::Module const *const *) module; - if (mozilla::Module::kVersion != data.mModule->mVersion) { - LogMessage("Native module at path '%s' is incompatible with this version of Firefox, has version %i, expected %i.", - filePath.get(), data.mModule->mVersion, - mozilla::Module::kVersion); - PR_UnloadLibrary(data.mLibrary); - return nullptr; - } + free(blist); + } +#endif - mLibraries.Put(hashedFile, data); // infallible - return data.mModule; + void* module = PR_FindSymbol(data.mLibrary, "NSModule"); + if (!module) { + LogMessage("Native module at path '%s' doesn't export symbol `NSModule`.", + filePath.get()); + PR_UnloadLibrary(data.mLibrary); + return nullptr; + } + + data.mModule = *(mozilla::Module const* const*)module; + if (mozilla::Module::kVersion != data.mModule->mVersion) { + LogMessage("Native module at path '%s' is incompatible with this version of Firefox, has version %i, expected %i.", + filePath.get(), data.mModule->mVersion, + mozilla::Module::kVersion); + PR_UnloadLibrary(data.mLibrary); + return nullptr; + } + + mLibraries.Put(hashedFile, data); // infallible + return data.mModule; } PLDHashOperator nsNativeModuleLoader::ReleaserFunc(nsIHashable* aHashedFile, NativeLoadData& aLoadData, void*) { - aLoadData.mModule = nullptr; - return PL_DHASH_NEXT; + aLoadData.mModule = nullptr; + return PL_DHASH_NEXT; } PLDHashOperator nsNativeModuleLoader::UnloaderFunc(nsIHashable* aHashedFile, NativeLoadData& aLoadData, void*) { - if (PR_LOG_TEST(GetNativeModuleLoaderLog(), PR_LOG_DEBUG)) { - nsCOMPtr file(do_QueryInterface(aHashedFile)); + if (PR_LOG_TEST(GetNativeModuleLoaderLog(), PR_LOG_DEBUG)) { + nsCOMPtr file(do_QueryInterface(aHashedFile)); - nsAutoCString filePath; - file->GetNativePath(filePath); + nsAutoCString filePath; + file->GetNativePath(filePath); - LOG(PR_LOG_DEBUG, - ("nsNativeModuleLoader::UnloaderFunc(\"%s\")", filePath.get())); - } + LOG(PR_LOG_DEBUG, + ("nsNativeModuleLoader::UnloaderFunc(\"%s\")", filePath.get())); + } #ifdef NS_BUILD_REFCNT_LOGGING - nsTraceRefcnt::SetActivityIsLegal(false); + nsTraceRefcnt::SetActivityIsLegal(false); #endif #if 0 - // XXXbsmedberg: do this as soon as the static-destructor crash(es) - // are fixed - PRStatus ret = PR_UnloadLibrary(aLoadData.mLibrary); - NS_ASSERTION(ret == PR_SUCCESS, "Failed to unload library"); + // XXXbsmedberg: do this as soon as the static-destructor crash(es) + // are fixed + PRStatus ret = PR_UnloadLibrary(aLoadData.mLibrary); + NS_ASSERTION(ret == PR_SUCCESS, "Failed to unload library"); #endif #ifdef NS_BUILD_REFCNT_LOGGING - nsTraceRefcnt::SetActivityIsLegal(true); + nsTraceRefcnt::SetActivityIsLegal(true); #endif - return PL_DHASH_REMOVE; + return PL_DHASH_REMOVE; } void nsNativeModuleLoader::UnloadLibraries() { - MOZ_ASSERT(NS_IsMainThread(), "Shutdown not on main thread?"); - mLibraries.Enumerate(ReleaserFunc, nullptr); - mLibraries.Enumerate(UnloaderFunc, nullptr); + MOZ_ASSERT(NS_IsMainThread(), "Shutdown not on main thread?"); + mLibraries.Enumerate(ReleaserFunc, nullptr); + mLibraries.Enumerate(UnloaderFunc, nullptr); } diff --git a/xpcom/components/nsNativeModuleLoader.h b/xpcom/components/nsNativeModuleLoader.h index f79968e4645d..9c728f07acef 100644 --- a/xpcom/components/nsNativeModuleLoader.h +++ b/xpcom/components/nsNativeModuleLoader.h @@ -16,32 +16,29 @@ class FileLocation; class nsNativeModuleLoader MOZ_FINAL { - public: - const mozilla::Module* LoadModule(mozilla::FileLocation &aFile); +public: + const mozilla::Module* LoadModule(mozilla::FileLocation& aFile); - nsresult Init(); + nsresult Init(); - void UnloadLibraries(); + void UnloadLibraries(); - private: - struct NativeLoadData - { - NativeLoadData() - : mModule(nullptr) - , mLibrary(nullptr) - { } +private: + struct NativeLoadData + { + NativeLoadData() : mModule(nullptr), mLibrary(nullptr) {} - const mozilla::Module* mModule; - PRLibrary* mLibrary; - }; + const mozilla::Module* mModule; + PRLibrary* mLibrary; + }; - static PLDHashOperator - ReleaserFunc(nsIHashable* aHashedFile, NativeLoadData &aLoadData, void*); + static PLDHashOperator + ReleaserFunc(nsIHashable* aHashedFile, NativeLoadData& aLoadData, void*); - static PLDHashOperator - UnloaderFunc(nsIHashable* aHashedFile, NativeLoadData &aLoadData, void*); + static PLDHashOperator + UnloaderFunc(nsIHashable* aHashedFile, NativeLoadData& aLoadData, void*); - nsDataHashtable mLibraries; + nsDataHashtable mLibraries; }; #endif /* nsNativeModuleLoader_h__ */