1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/prefs/pref_service.h"
12 #include "base/check_op.h"
13 #include "base/debug/alias.h"
14 #include "base/debug/dump_without_crashing.h"
15 #include "base/files/file_path.h"
16 #include "base/functional/bind.h"
17 #include "base/json/values_util.h"
18 #include "base/location.h"
19 #include "base/logging.h"
20 #include "base/memory/ptr_util.h"
21 #include "base/metrics/histogram.h"
22 #include "base/notreached.h"
23 #include "base/strings/string_number_conversions.h"
24 #include "base/strings/string_piece.h"
25 #include "base/strings/string_util.h"
26 #include "base/task/sequenced_task_runner.h"
27 #include "base/values.h"
28 #include "build/chromeos_buildflags.h"
29 #include "components/prefs/default_pref_store.h"
30 #include "components/prefs/json_pref_store.h"
31 #include "components/prefs/pref_notifier_impl.h"
32 #include "components/prefs/pref_registry.h"
34 #if BUILDFLAG(IS_CHROMEOS_ASH)
35 #include "components/prefs/value_map_pref_store.h"
38 #if BUILDFLAG(IS_ANDROID)
39 #include "components/prefs/android/pref_service_android.h"
47 PrefService::PersistentPrefStoreLoadingObserver::
48 PersistentPrefStoreLoadingObserver(PrefService* pref_service)
49 : pref_service_(pref_service) {
50 DCHECK(pref_service_);
53 void PrefService::PersistentPrefStoreLoadingObserver::OnInitializationCompleted(
55 pref_service_->CheckPrefsLoaded();
58 PrefService::PrefService(
59 std::unique_ptr<PrefNotifierImpl> pref_notifier,
60 std::unique_ptr<PrefValueStore> pref_value_store,
61 scoped_refptr<PersistentPrefStore> user_prefs,
62 scoped_refptr<PersistentPrefStore> standalone_browser_prefs,
63 scoped_refptr<PrefRegistry> pref_registry,
64 base::RepeatingCallback<void(PersistentPrefStore::PrefReadError)>
67 : pref_notifier_(std::move(pref_notifier)),
68 pref_value_store_(std::move(pref_value_store)),
69 user_pref_store_(std::move(user_prefs)),
70 standalone_browser_pref_store_(std::move(standalone_browser_prefs)),
71 read_error_callback_(std::move(read_error_callback)),
72 pref_registry_(std::move(pref_registry)),
74 std::make_unique<PrefService::PersistentPrefStoreLoadingObserver>(
76 pref_notifier_->SetPrefService(this);
78 DCHECK(pref_registry_);
79 DCHECK(pref_value_store_);
81 InitFromStorage(async);
84 PrefService::~PrefService() {
85 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
87 // Remove observers. This could be necessary if this service is destroyed
88 // before the prefs are fully loaded.
89 user_pref_store_->RemoveObserver(pref_store_observer_.get());
90 if (standalone_browser_pref_store_) {
91 standalone_browser_pref_store_->RemoveObserver(pref_store_observer_.get());
94 // TODO(crbug.com/942491, 946668, 945772) The following code collects
95 // augments stack dumps created by ~PrefNotifierImpl() with information
96 // whether the profile owning the PrefService is an incognito profile.
97 // Delete this, once the bugs are closed.
98 const bool is_incognito_profile = user_pref_store_->IsInMemoryPrefStore();
99 base::debug::Alias(&is_incognito_profile);
100 // Export value of is_incognito_profile to a string so that `grep`
101 // is a sufficient tool to analyze crashdumps.
102 char is_incognito_profile_string[32];
103 strncpy(is_incognito_profile_string,
104 is_incognito_profile ? "is_incognito: yes" : "is_incognito: no",
105 sizeof(is_incognito_profile_string));
106 base::debug::Alias(&is_incognito_profile_string);
109 void PrefService::InitFromStorage(bool async) {
111 if (!user_pref_store_->IsInitializationComplete()) {
112 user_pref_store_->ReadPrefs();
114 if (standalone_browser_pref_store_ &&
115 !standalone_browser_pref_store_->IsInitializationComplete()) {
116 standalone_browser_pref_store_->ReadPrefs();
124 if (!user_pref_store_->IsInitializationComplete()) {
125 user_pref_store_->AddObserver(pref_store_observer_.get());
126 user_pref_store_->ReadPrefsAsync(nullptr);
129 if (standalone_browser_pref_store_ &&
130 !standalone_browser_pref_store_->IsInitializationComplete()) {
131 standalone_browser_pref_store_->AddObserver(pref_store_observer_.get());
132 standalone_browser_pref_store_->ReadPrefsAsync(nullptr);
136 void PrefService::CheckPrefsLoaded() {
137 if (!(user_pref_store_->IsInitializationComplete() &&
138 (!standalone_browser_pref_store_ ||
139 standalone_browser_pref_store_->IsInitializationComplete()))) {
140 // Not done initializing both prefstores.
144 user_pref_store_->RemoveObserver(pref_store_observer_.get());
145 if (standalone_browser_pref_store_) {
146 standalone_browser_pref_store_->RemoveObserver(pref_store_observer_.get());
149 // Both prefstores are initialized, get the read errors.
150 PersistentPrefStore::PrefReadError user_store_error =
151 user_pref_store_->GetReadError();
152 if (!standalone_browser_pref_store_) {
153 read_error_callback_.Run(user_store_error);
156 PersistentPrefStore::PrefReadError standalone_browser_store_error =
157 standalone_browser_pref_store_->GetReadError();
159 // If both stores have the same error (or no error), run the callback with
160 // either one. This avoids double-reporting (either way prefs weren't
161 // successfully fully loaded)
162 if (user_store_error == standalone_browser_store_error) {
163 read_error_callback_.Run(user_store_error);
164 } else if (user_store_error == PersistentPrefStore::PREF_READ_ERROR_NONE ||
165 user_store_error == PersistentPrefStore::PREF_READ_ERROR_NO_FILE) {
166 // Prefer to report the standalone_browser_pref_store error if the
167 // user_pref_store error is not significant.
168 read_error_callback_.Run(standalone_browser_store_error);
170 // Either the user_pref_store error is significant, or
171 // both stores failed to load but for different reasons.
172 // The user_store error is more significant in essentially all cases,
173 // so prefer to report that.
174 read_error_callback_.Run(user_store_error);
178 void PrefService::CommitPendingWrite(
179 base::OnceClosure reply_callback,
180 base::OnceClosure synchronous_done_callback) {
181 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
182 user_pref_store_->CommitPendingWrite(std::move(reply_callback),
183 std::move(synchronous_done_callback));
186 void PrefService::SchedulePendingLossyWrites() {
187 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
188 user_pref_store_->SchedulePendingLossyWrites();
191 bool PrefService::GetBoolean(base::StringPiece path) const {
192 return GetValue(path).GetBool();
195 int PrefService::GetInteger(base::StringPiece path) const {
196 return GetValue(path).GetInt();
199 double PrefService::GetDouble(base::StringPiece path) const {
200 return GetValue(path).GetDouble();
203 const std::string& PrefService::GetString(base::StringPiece path) const {
204 return GetValue(path).GetString();
207 base::FilePath PrefService::GetFilePath(base::StringPiece path) const {
208 const base::Value& value = GetValue(path);
209 absl::optional<base::FilePath> result = base::ValueToFilePath(value);
214 bool PrefService::HasPrefPath(const std::string& path) const {
215 const Preference* pref = FindPreference(path);
216 return pref && !pref->IsDefaultValue();
219 void PrefService::IteratePreferenceValues(
220 base::RepeatingCallback<void(const std::string& key,
221 const base::Value& value)> callback) const {
222 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
223 for (const auto& it : *pref_registry_)
224 callback.Run(it.first, *GetPreferenceValue(it.first));
227 base::Value::Dict PrefService::GetPreferenceValues(
228 IncludeDefaults include_defaults) const {
229 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
231 base::Value::Dict out;
232 for (const auto& it : *pref_registry_) {
233 if (include_defaults == INCLUDE_DEFAULTS) {
234 out.SetByDottedPath(it.first, GetPreferenceValue(it.first)->Clone());
236 const Preference* pref = FindPreference(it.first);
237 if (pref->IsDefaultValue()) {
240 out.SetByDottedPath(it.first, pref->GetValue()->Clone());
246 std::vector<PrefService::PreferenceValueAndStore>
247 PrefService::GetPreferencesValueAndStore() const {
248 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
250 std::vector<PreferenceValueAndStore> result;
251 for (const auto& it : *pref_registry_) {
252 auto* preference = FindPreference(it.first);
254 PreferenceValueAndStore pref_data{
255 it.first, preference->GetValue()->Clone(),
256 pref_value_store_->ControllingPrefStoreForPref(it.first)};
257 result.emplace_back(std::move(pref_data));
262 const PrefService::Preference* PrefService::FindPreference(
263 const std::string& pref_name) const {
264 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
265 auto it = prefs_map_.find(pref_name);
266 if (it != prefs_map_.end())
267 return &(it->second);
268 const base::Value* default_value = nullptr;
269 if (!pref_registry_->defaults()->GetValue(pref_name, &default_value))
272 .insert(std::make_pair(
273 pref_name, Preference(this, pref_name, default_value->type())))
275 return &(it->second);
278 bool PrefService::ReadOnly() const {
279 return user_pref_store_->ReadOnly();
282 PrefService::PrefInitializationStatus PrefService::GetInitializationStatus()
284 if (!user_pref_store_->IsInitializationComplete())
285 return INITIALIZATION_STATUS_WAITING;
287 switch (user_pref_store_->GetReadError()) {
288 case PersistentPrefStore::PREF_READ_ERROR_NONE:
289 return INITIALIZATION_STATUS_SUCCESS;
290 case PersistentPrefStore::PREF_READ_ERROR_NO_FILE:
291 return INITIALIZATION_STATUS_CREATED_NEW_PREF_STORE;
293 return INITIALIZATION_STATUS_ERROR;
297 PrefService::PrefInitializationStatus
298 PrefService::GetAllPrefStoresInitializationStatus() const {
299 if (!pref_value_store_->IsInitializationComplete())
300 return INITIALIZATION_STATUS_WAITING;
302 return GetInitializationStatus();
305 bool PrefService::IsManagedPreference(const std::string& pref_name) const {
306 const Preference* pref = FindPreference(pref_name);
307 return pref && pref->IsManaged();
310 bool PrefService::IsPreferenceManagedByCustodian(
311 const std::string& pref_name) const {
312 const Preference* pref = FindPreference(pref_name);
313 return pref && pref->IsManagedByCustodian();
316 bool PrefService::IsUserModifiablePreference(
317 const std::string& pref_name) const {
318 const Preference* pref = FindPreference(pref_name);
319 return pref && pref->IsUserModifiable();
322 const base::Value& PrefService::GetValue(base::StringPiece path) const {
323 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
324 return *GetPreferenceValueChecked(path);
327 const base::Value::Dict& PrefService::GetDict(base::StringPiece path) const {
328 const base::Value& value = GetValue(path);
329 return value.GetDict();
332 const base::Value::List& PrefService::GetList(base::StringPiece path) const {
333 const base::Value& value = GetValue(path);
334 return value.GetList();
337 const base::Value* PrefService::GetUserPrefValue(
338 const std::string& path) const {
339 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
341 const Preference* pref = FindPreference(path);
343 NOTREACHED() << "Trying to get an unregistered pref: " << path;
347 // Look for an existing preference in the user store. If it doesn't
348 // exist, return NULL.
349 base::Value* value = nullptr;
350 if (!user_pref_store_->GetMutableValue(path, &value))
353 if (value->type() != pref->GetType()) {
354 NOTREACHED() << "Pref value type doesn't match registered type.";
361 void PrefService::SetDefaultPrefValue(const std::string& path,
363 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
364 pref_registry_->SetDefaultPrefValue(path, std::move(value));
367 const base::Value* PrefService::GetDefaultPrefValue(
368 const std::string& path) const {
369 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
370 // Lookup the preference in the default store.
371 const base::Value* value = nullptr;
372 bool has_value = pref_registry_->defaults()->GetValue(path, &value);
373 DCHECK(has_value) << "Default value missing for pref: " << path;
377 void PrefService::AddPrefObserver(const std::string& path, PrefObserver* obs) {
378 pref_notifier_->AddPrefObserver(path, obs);
381 void PrefService::RemovePrefObserver(const std::string& path,
383 pref_notifier_->RemovePrefObserver(path, obs);
386 void PrefService::AddPrefInitObserver(base::OnceCallback<void(bool)> obs) {
387 pref_notifier_->AddInitObserver(std::move(obs));
390 PrefRegistry* PrefService::DeprecatedGetPrefRegistry() {
391 return pref_registry_.get();
394 void PrefService::ClearPref(const std::string& path) {
395 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
397 const Preference* pref = FindPreference(path);
399 NOTREACHED() << "Trying to clear an unregistered pref: " << path;
402 user_pref_store_->RemoveValue(path, GetWriteFlags(pref));
405 void PrefService::ClearPrefsWithPrefixSilently(const std::string& prefix) {
406 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
407 user_pref_store_->RemoveValuesByPrefixSilently(prefix);
410 void PrefService::OnStoreDeletionFromDisk() {
411 user_pref_store_->OnStoreDeletionFromDisk();
414 void PrefService::AddPrefObserverAllPrefs(PrefObserver* obs) {
415 pref_notifier_->AddPrefObserverAllPrefs(obs);
418 void PrefService::RemovePrefObserverAllPrefs(PrefObserver* obs) {
419 pref_notifier_->RemovePrefObserverAllPrefs(obs);
422 #if BUILDFLAG(IS_ANDROID)
423 base::android::ScopedJavaLocalRef<jobject> PrefService::GetJavaObject() {
424 if (!pref_service_android_) {
425 pref_service_android_ = std::make_unique<PrefServiceAndroid>(this);
427 return pref_service_android_->GetJavaObject();
431 void PrefService::Set(const std::string& path, const base::Value& value) {
432 SetUserPrefValue(path, value.Clone());
435 void PrefService::SetBoolean(const std::string& path, bool value) {
436 SetUserPrefValue(path, base::Value(value));
439 void PrefService::SetInteger(const std::string& path, int value) {
440 SetUserPrefValue(path, base::Value(value));
443 void PrefService::SetDouble(const std::string& path, double value) {
444 SetUserPrefValue(path, base::Value(value));
447 void PrefService::SetString(const std::string& path, base::StringPiece value) {
448 SetUserPrefValue(path, base::Value(value));
451 void PrefService::SetDict(const std::string& path, base::Value::Dict dict) {
452 SetUserPrefValue(path, base::Value(std::move(dict)));
455 void PrefService::SetList(const std::string& path, base::Value::List list) {
456 SetUserPrefValue(path, base::Value(std::move(list)));
459 void PrefService::SetFilePath(const std::string& path,
460 const base::FilePath& value) {
461 SetUserPrefValue(path, base::FilePathToValue(value));
464 void PrefService::SetInt64(const std::string& path, int64_t value) {
465 SetUserPrefValue(path, base::Int64ToValue(value));
468 int64_t PrefService::GetInt64(const std::string& path) const {
469 const base::Value& value = GetValue(path);
470 absl::optional<int64_t> integer = base::ValueToInt64(value);
472 return integer.value_or(0);
475 void PrefService::SetUint64(const std::string& path, uint64_t value) {
476 SetUserPrefValue(path, base::Value(base::NumberToString(value)));
479 uint64_t PrefService::GetUint64(const std::string& path) const {
480 const base::Value& value = GetValue(path);
481 if (!value.is_string())
485 base::StringToUint64(value.GetString(), &result);
489 void PrefService::SetTime(const std::string& path, base::Time value) {
490 SetUserPrefValue(path, base::TimeToValue(value));
493 base::Time PrefService::GetTime(const std::string& path) const {
494 const base::Value& value = GetValue(path);
495 absl::optional<base::Time> time = base::ValueToTime(value);
497 return time.value_or(base::Time());
500 void PrefService::SetTimeDelta(const std::string& path, base::TimeDelta value) {
501 SetUserPrefValue(path, base::TimeDeltaToValue(value));
504 base::TimeDelta PrefService::GetTimeDelta(const std::string& path) const {
505 const base::Value& value = GetValue(path);
506 absl::optional<base::TimeDelta> time_delta = base::ValueToTimeDelta(value);
508 return time_delta.value_or(base::TimeDelta());
511 base::Value* PrefService::GetMutableUserPref(const std::string& path,
512 base::Value::Type type) {
513 CHECK(type == base::Value::Type::DICT || type == base::Value::Type::LIST);
514 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
516 const Preference* pref = FindPreference(path);
518 NOTREACHED() << "Trying to get an unregistered pref: " << path;
521 if (pref->GetType() != type) {
522 NOTREACHED() << "Wrong type for GetMutableValue: " << path;
526 // Look for an existing preference in the user store. Return it in case it
527 // exists and has the correct type.
528 base::Value* value = nullptr;
529 if (user_pref_store_->GetMutableValue(path, &value) &&
530 value->type() == type) {
534 // If no user preference of the correct type exists, clone default value.
535 const base::Value* default_value = nullptr;
536 pref_registry_->defaults()->GetValue(path, &default_value);
537 DCHECK_EQ(default_value->type(), type);
538 user_pref_store_->SetValueSilently(path, default_value->Clone(),
539 GetWriteFlags(pref));
540 user_pref_store_->GetMutableValue(path, &value);
544 void PrefService::ReportUserPrefChanged(const std::string& key) {
545 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
546 user_pref_store_->ReportValueChanged(key, GetWriteFlags(FindPreference(key)));
549 void PrefService::ReportUserPrefChanged(
550 const std::string& key,
551 std::set<std::vector<std::string>> path_components) {
552 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
553 user_pref_store_->ReportSubValuesChanged(key, std::move(path_components),
554 GetWriteFlags(FindPreference(key)));
557 void PrefService::SetUserPrefValue(const std::string& path,
558 base::Value new_value) {
559 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
561 const Preference* pref = FindPreference(path);
563 NOTREACHED() << "Trying to write an unregistered pref: " << path;
566 if (pref->GetType() != new_value.type()) {
567 NOTREACHED() << "Trying to set pref " << path << " of type "
568 << pref->GetType() << " to value of type " << new_value.type();
572 user_pref_store_->SetValue(path, std::move(new_value), GetWriteFlags(pref));
575 void PrefService::UpdateCommandLinePrefStore(PrefStore* command_line_store) {
576 pref_value_store_->UpdateCommandLinePrefStore(command_line_store);
579 ///////////////////////////////////////////////////////////////////////////////
580 // PrefService::Preference
582 PrefService::Preference::Preference(const PrefService* service,
584 base::Value::Type type)
585 : name_(std::move(name)),
587 // Cache the registration flags at creation time to avoid multiple map
589 registration_flags_(service->pref_registry_->GetRegistrationFlags(name_)),
590 pref_service_(service) {}
592 const base::Value* PrefService::Preference::GetValue() const {
593 return pref_service_->GetPreferenceValueChecked(name_);
596 const base::Value* PrefService::Preference::GetRecommendedValue() const {
597 DCHECK(pref_service_->FindPreference(name_))
598 << "Must register pref before getting its value";
600 const base::Value* found_value = nullptr;
601 if (pref_value_store()->GetRecommendedValue(name_, type_, &found_value)) {
602 DCHECK(found_value->type() == type_);
606 // The pref has no recommended value.
610 bool PrefService::Preference::IsManaged() const {
611 return pref_value_store()->PrefValueInManagedStore(name_);
614 bool PrefService::Preference::IsManagedByCustodian() const {
615 return pref_value_store()->PrefValueInSupervisedStore(name_);
618 bool PrefService::Preference::IsRecommended() const {
619 return pref_value_store()->PrefValueFromRecommendedStore(name_);
622 bool PrefService::Preference::HasExtensionSetting() const {
623 return pref_value_store()->PrefValueInExtensionStore(name_);
626 bool PrefService::Preference::HasUserSetting() const {
627 return pref_value_store()->PrefValueInUserStore(name_);
630 bool PrefService::Preference::IsExtensionControlled() const {
631 return pref_value_store()->PrefValueFromExtensionStore(name_);
634 bool PrefService::Preference::IsUserControlled() const {
635 return pref_value_store()->PrefValueFromUserStore(name_);
638 bool PrefService::Preference::IsDefaultValue() const {
639 return pref_value_store()->PrefValueFromDefaultStore(name_);
642 bool PrefService::Preference::IsUserModifiable() const {
643 return pref_value_store()->PrefValueUserModifiable(name_);
646 bool PrefService::Preference::IsExtensionModifiable() const {
647 return pref_value_store()->PrefValueExtensionModifiable(name_);
650 #if BUILDFLAG(IS_CHROMEOS_ASH)
651 bool PrefService::Preference::IsStandaloneBrowserControlled() const {
652 return pref_value_store()->PrefValueFromStandaloneBrowserStore(name_);
655 bool PrefService::Preference::IsStandaloneBrowserModifiable() const {
656 return pref_value_store()->PrefValueStandaloneBrowserModifiable(name_);
660 const base::Value* PrefService::GetPreferenceValue(
661 base::StringPiece path) const {
662 DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
664 const base::Value* default_value = nullptr;
665 if (!pref_registry_->defaults()->GetValue(path, &default_value))
668 const base::Value* found_value = nullptr;
669 base::Value::Type default_type = default_value->type();
670 if (!pref_value_store_->GetValue(path, default_type, &found_value)) {
671 // Every registered preference has at least a default value.
672 NOTREACHED() << "no valid value found for registered pref " << path;
673 return default_value;
676 DCHECK_EQ(found_value->type(), default_type);
680 const base::Value* PrefService::GetPreferenceValueChecked(
681 base::StringPiece path) const {
682 const base::Value* value = GetPreferenceValue(path);
683 DCHECK(value) << "Trying to read an unregistered pref: " << path;
687 #if BUILDFLAG(IS_CHROMEOS_ASH)
688 void PrefService::SetStandaloneBrowserPref(const std::string& path,
689 const base::Value& value) {
690 if (!standalone_browser_pref_store_) {
691 LOG(WARNING) << "Failure to set value of " << path
692 << " in standalone browser store";
695 standalone_browser_pref_store_->SetValue(
696 path, value.Clone(), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
699 void PrefService::RemoveStandaloneBrowserPref(const std::string& path) {
700 if (!standalone_browser_pref_store_) {
701 LOG(WARNING) << "Failure to remove value of " << path
702 << " in standalone browser store";
705 standalone_browser_pref_store_->RemoveValue(
706 path, WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
711 uint32_t PrefService::GetWriteFlags(const PrefService::Preference* pref) {
712 uint32_t write_flags = WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS;
718 if (pref->registration_flags() & PrefRegistry::LOSSY_PREF) {
719 write_flags |= WriteablePrefStore::LOSSY_PREF_WRITE_FLAG;