Bug 1675714 - Improve reliability of OSPreferences instance getters. r=lsalzman

Depends on D96201

Differential Revision: https://phabricator.services.mozilla.com/D96202
This commit is contained in:
Jonathan Kew 2020-11-07 17:29:48 +00:00
parent 44c5ff8518
commit f8d43ea75c
2 changed files with 21 additions and 5 deletions

View File

@ -23,9 +23,12 @@ NS_IMPL_ISUPPORTS(OSPreferences, mozIOSPreferences)
mozilla::StaticRefPtr<OSPreferences> OSPreferences::sInstance;
OSPreferences* OSPreferences::GetInstance() {
if (!sInstance) {
// Return a new strong reference to the instance, creating it if necessary.
already_AddRefed<OSPreferences> OSPreferences::GetInstanceAddRefed() {
RefPtr<OSPreferences> result = sInstance;
if (!result) {
sInstance = new OSPreferences();
result = sInstance;
DebugOnly<nsresult> rv = Preferences::RegisterPrefixCallback(
PreferenceChanged, "intl.date_time.pattern_override");
@ -33,6 +36,18 @@ OSPreferences* OSPreferences::GetInstance() {
ClearOnShutdown(&sInstance);
}
return result.forget();
}
// Return a raw pointer to the instance: not for off-main-thread use,
// because ClearOnShutdown means it could go away unexpectedly.
OSPreferences* OSPreferences::GetInstance() {
MOZ_ASSERT(NS_IsMainThread());
if (!sInstance) {
// This will create the static instance; then we just drop the extra
// reference.
RefPtr<OSPreferences> result = GetInstanceAddRefed();
}
return sInstance;
}

View File

@ -66,6 +66,9 @@ class OSPreferences : public mozIOSPreferences {
* instance, but does not need to hold a reference, as in
* nsAutoCString str;
* OSPreferences::GetInstance()->GetSystemLocale(str);
*
* NOTE that this is not safe for off-main-thread use, because it is possible
* that XPCOM shutdown on the main thread could invalidate it at any moment!
*/
static OSPreferences* GetInstance();
@ -73,9 +76,7 @@ class OSPreferences : public mozIOSPreferences {
* Return an addRef'd pointer to the singleton instance. This is used by the
* XPCOM constructor that exists to support usage from JS.
*/
static already_AddRefed<OSPreferences> GetInstanceAddRefed() {
return RefPtr<OSPreferences>(GetInstance()).forget();
}
static already_AddRefed<OSPreferences> GetInstanceAddRefed();
static bool GetPatternForSkeleton(const nsACString& aSkeleton,
const nsACString& aLocale,