xref: /aosp_15_r20/external/cronet/components/prefs/pref_service.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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.
4 
5 #include "components/prefs/pref_service.h"
6 
7 #include <algorithm>
8 #include <map>
9 #include <string>
10 #include <utility>
11 
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"
33 
34 #if BUILDFLAG(IS_CHROMEOS_ASH)
35 #include "components/prefs/value_map_pref_store.h"
36 #endif
37 
38 #if BUILDFLAG(IS_ANDROID)
39 #include "components/prefs/android/pref_service_android.h"
40 #endif
41 
42 namespace {
43 
44 
45 }  // namespace
46 
47 PrefService::PersistentPrefStoreLoadingObserver::
PersistentPrefStoreLoadingObserver(PrefService * pref_service)48     PersistentPrefStoreLoadingObserver(PrefService* pref_service)
49     : pref_service_(pref_service) {
50   DCHECK(pref_service_);
51 }
52 
OnInitializationCompleted(bool succeeded)53 void PrefService::PersistentPrefStoreLoadingObserver::OnInitializationCompleted(
54     bool succeeded) {
55   pref_service_->CheckPrefsLoaded();
56 }
57 
PrefService(std::unique_ptr<PrefNotifierImpl> pref_notifier,std::unique_ptr<PrefValueStore> pref_value_store,scoped_refptr<PersistentPrefStore> user_prefs,scoped_refptr<PersistentPrefStore> standalone_browser_prefs,scoped_refptr<PrefRegistry> pref_registry,base::RepeatingCallback<void (PersistentPrefStore::PrefReadError)> read_error_callback,bool async)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)>
65         read_error_callback,
66     bool async)
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)),
73       pref_store_observer_(
74           std::make_unique<PrefService::PersistentPrefStoreLoadingObserver>(
75               this)) {
76   pref_notifier_->SetPrefService(this);
77 
78   DCHECK(pref_registry_);
79   DCHECK(pref_value_store_);
80 
81   InitFromStorage(async);
82 }
83 
~PrefService()84 PrefService::~PrefService() {
85   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
86 
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());
92   }
93 
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);
107 }
108 
InitFromStorage(bool async)109 void PrefService::InitFromStorage(bool async) {
110   if (!async) {
111     if (!user_pref_store_->IsInitializationComplete()) {
112       user_pref_store_->ReadPrefs();
113     }
114     if (standalone_browser_pref_store_ &&
115         !standalone_browser_pref_store_->IsInitializationComplete()) {
116       standalone_browser_pref_store_->ReadPrefs();
117     }
118     CheckPrefsLoaded();
119     return;
120   }
121 
122   CheckPrefsLoaded();
123 
124   if (!user_pref_store_->IsInitializationComplete()) {
125     user_pref_store_->AddObserver(pref_store_observer_.get());
126     user_pref_store_->ReadPrefsAsync(nullptr);
127   }
128 
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);
133   }
134 }
135 
CheckPrefsLoaded()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.
141     return;
142   }
143 
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());
147   }
148 
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);
154     return;
155   }
156   PersistentPrefStore::PrefReadError standalone_browser_store_error =
157       standalone_browser_pref_store_->GetReadError();
158 
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);
169   } else {
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);
175   }
176 }
177 
CommitPendingWrite(base::OnceClosure reply_callback,base::OnceClosure synchronous_done_callback)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));
184 }
185 
SchedulePendingLossyWrites()186 void PrefService::SchedulePendingLossyWrites() {
187   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
188   user_pref_store_->SchedulePendingLossyWrites();
189 }
190 
GetBoolean(base::StringPiece path) const191 bool PrefService::GetBoolean(base::StringPiece path) const {
192   return GetValue(path).GetBool();
193 }
194 
GetInteger(base::StringPiece path) const195 int PrefService::GetInteger(base::StringPiece path) const {
196   return GetValue(path).GetInt();
197 }
198 
GetDouble(base::StringPiece path) const199 double PrefService::GetDouble(base::StringPiece path) const {
200   return GetValue(path).GetDouble();
201 }
202 
GetString(base::StringPiece path) const203 const std::string& PrefService::GetString(base::StringPiece path) const {
204   return GetValue(path).GetString();
205 }
206 
GetFilePath(base::StringPiece path) const207 base::FilePath PrefService::GetFilePath(base::StringPiece path) const {
208   const base::Value& value = GetValue(path);
209   std::optional<base::FilePath> result = base::ValueToFilePath(value);
210   DCHECK(result);
211   return *result;
212 }
213 
HasPrefPath(const std::string & path) const214 bool PrefService::HasPrefPath(const std::string& path) const {
215   const Preference* pref = FindPreference(path);
216   return pref && !pref->IsDefaultValue();
217 }
218 
IteratePreferenceValues(base::RepeatingCallback<void (const std::string & key,const base::Value & value)> callback) const219 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));
225 }
226 
GetPreferenceValues(IncludeDefaults include_defaults) const227 base::Value::Dict PrefService::GetPreferenceValues(
228     IncludeDefaults include_defaults) const {
229   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
230 
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());
235     } else {
236       const Preference* pref = FindPreference(it.first);
237       if (pref->IsDefaultValue()) {
238         continue;
239       }
240       out.SetByDottedPath(it.first, pref->GetValue()->Clone());
241     }
242   }
243   return out;
244 }
245 
246 std::vector<PrefService::PreferenceValueAndStore>
GetPreferencesValueAndStore() const247 PrefService::GetPreferencesValueAndStore() const {
248   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
249 
250   std::vector<PreferenceValueAndStore> result;
251   for (const auto& it : *pref_registry_) {
252     auto* preference = FindPreference(it.first);
253     CHECK(preference);
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));
258   }
259   return result;
260 }
261 
FindPreference(const std::string & pref_name) const262 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))
270     return nullptr;
271   it = prefs_map_
272            .insert(std::make_pair(
273                pref_name, Preference(this, pref_name, default_value->type())))
274            .first;
275   return &(it->second);
276 }
277 
ReadOnly() const278 bool PrefService::ReadOnly() const {
279   return user_pref_store_->ReadOnly();
280 }
281 
GetInitializationStatus() const282 PrefService::PrefInitializationStatus PrefService::GetInitializationStatus()
283     const {
284   if (!user_pref_store_->IsInitializationComplete())
285     return INITIALIZATION_STATUS_WAITING;
286 
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;
292     default:
293       return INITIALIZATION_STATUS_ERROR;
294   }
295 }
296 
297 PrefService::PrefInitializationStatus
GetAllPrefStoresInitializationStatus() const298 PrefService::GetAllPrefStoresInitializationStatus() const {
299   if (!pref_value_store_->IsInitializationComplete())
300     return INITIALIZATION_STATUS_WAITING;
301 
302   return GetInitializationStatus();
303 }
304 
IsManagedPreference(const std::string & pref_name) const305 bool PrefService::IsManagedPreference(const std::string& pref_name) const {
306   const Preference* pref = FindPreference(pref_name);
307   return pref && pref->IsManaged();
308 }
309 
IsPreferenceManagedByCustodian(const std::string & pref_name) const310 bool PrefService::IsPreferenceManagedByCustodian(
311     const std::string& pref_name) const {
312   const Preference* pref = FindPreference(pref_name);
313   return pref && pref->IsManagedByCustodian();
314 }
315 
IsUserModifiablePreference(const std::string & pref_name) const316 bool PrefService::IsUserModifiablePreference(
317     const std::string& pref_name) const {
318   const Preference* pref = FindPreference(pref_name);
319   return pref && pref->IsUserModifiable();
320 }
321 
GetValue(base::StringPiece path) const322 const base::Value& PrefService::GetValue(base::StringPiece path) const {
323   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
324   return *GetPreferenceValue(path);
325 }
326 
GetDict(base::StringPiece path) const327 const base::Value::Dict& PrefService::GetDict(base::StringPiece path) const {
328   const base::Value& value = GetValue(path);
329   return value.GetDict();
330 }
331 
GetList(base::StringPiece path) const332 const base::Value::List& PrefService::GetList(base::StringPiece path) const {
333   const base::Value& value = GetValue(path);
334   return value.GetList();
335 }
336 
GetUserPrefValue(const std::string & path) const337 const base::Value* PrefService::GetUserPrefValue(
338     const std::string& path) const {
339   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
340 
341   const Preference* pref = FindPreference(path);
342   if (!pref) {
343     NOTREACHED() << "Trying to get an unregistered pref: " << path;
344     return nullptr;
345   }
346 
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))
351     return nullptr;
352 
353   if (value->type() != pref->GetType()) {
354     DUMP_WILL_BE_NOTREACHED_NORETURN()
355         << "Pref value type doesn't match registered type.";
356     return nullptr;
357   }
358 
359   return value;
360 }
361 
SetDefaultPrefValue(const std::string & path,base::Value value)362 void PrefService::SetDefaultPrefValue(const std::string& path,
363                                       base::Value value) {
364   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
365   pref_registry_->SetDefaultPrefValue(path, std::move(value));
366 }
367 
GetDefaultPrefValue(const std::string & path) const368 const base::Value* PrefService::GetDefaultPrefValue(
369     const std::string& path) const {
370   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
371   // Lookup the preference in the default store.
372   const base::Value* value = nullptr;
373   bool has_value = pref_registry_->defaults()->GetValue(path, &value);
374   DCHECK(has_value) << "Default value missing for pref: " << path;
375   return value;
376 }
377 
AddPrefObserver(const std::string & path,PrefObserver * obs)378 void PrefService::AddPrefObserver(const std::string& path, PrefObserver* obs) {
379   pref_notifier_->AddPrefObserver(path, obs);
380 }
381 
RemovePrefObserver(const std::string & path,PrefObserver * obs)382 void PrefService::RemovePrefObserver(const std::string& path,
383                                      PrefObserver* obs) {
384   pref_notifier_->RemovePrefObserver(path, obs);
385 }
386 
AddPrefInitObserver(base::OnceCallback<void (bool)> obs)387 void PrefService::AddPrefInitObserver(base::OnceCallback<void(bool)> obs) {
388   pref_notifier_->AddInitObserver(std::move(obs));
389 }
390 
DeprecatedGetPrefRegistry()391 PrefRegistry* PrefService::DeprecatedGetPrefRegistry() {
392   return pref_registry_.get();
393 }
394 
ClearPref(const std::string & path)395 void PrefService::ClearPref(const std::string& path) {
396   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
397 
398   const Preference* pref = FindPreference(path);
399   if (!pref) {
400     NOTREACHED() << "Trying to clear an unregistered pref: " << path;
401     return;
402   }
403   user_pref_store_->RemoveValue(path, GetWriteFlags(pref));
404 }
405 
ClearPrefsWithPrefixSilently(const std::string & prefix)406 void PrefService::ClearPrefsWithPrefixSilently(const std::string& prefix) {
407   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
408   user_pref_store_->RemoveValuesByPrefixSilently(prefix);
409 }
410 
OnStoreDeletionFromDisk()411 void PrefService::OnStoreDeletionFromDisk() {
412   user_pref_store_->OnStoreDeletionFromDisk();
413 }
414 
AddPrefObserverAllPrefs(PrefObserver * obs)415 void PrefService::AddPrefObserverAllPrefs(PrefObserver* obs) {
416   pref_notifier_->AddPrefObserverAllPrefs(obs);
417 }
418 
RemovePrefObserverAllPrefs(PrefObserver * obs)419 void PrefService::RemovePrefObserverAllPrefs(PrefObserver* obs) {
420   pref_notifier_->RemovePrefObserverAllPrefs(obs);
421 }
422 
423 #if BUILDFLAG(IS_ANDROID)
GetJavaObject()424 base::android::ScopedJavaLocalRef<jobject> PrefService::GetJavaObject() {
425   if (!pref_service_android_) {
426     pref_service_android_ = std::make_unique<PrefServiceAndroid>(this);
427   }
428   return pref_service_android_->GetJavaObject();
429 }
430 #endif
431 
Set(const std::string & path,const base::Value & value)432 void PrefService::Set(const std::string& path, const base::Value& value) {
433   SetUserPrefValue(path, value.Clone());
434 }
435 
SetBoolean(const std::string & path,bool value)436 void PrefService::SetBoolean(const std::string& path, bool value) {
437   SetUserPrefValue(path, base::Value(value));
438 }
439 
SetInteger(const std::string & path,int value)440 void PrefService::SetInteger(const std::string& path, int value) {
441   SetUserPrefValue(path, base::Value(value));
442 }
443 
SetDouble(const std::string & path,double value)444 void PrefService::SetDouble(const std::string& path, double value) {
445   SetUserPrefValue(path, base::Value(value));
446 }
447 
SetString(const std::string & path,base::StringPiece value)448 void PrefService::SetString(const std::string& path, base::StringPiece value) {
449   SetUserPrefValue(path, base::Value(value));
450 }
451 
SetDict(const std::string & path,base::Value::Dict dict)452 void PrefService::SetDict(const std::string& path, base::Value::Dict dict) {
453   SetUserPrefValue(path, base::Value(std::move(dict)));
454 }
455 
SetList(const std::string & path,base::Value::List list)456 void PrefService::SetList(const std::string& path, base::Value::List list) {
457   SetUserPrefValue(path, base::Value(std::move(list)));
458 }
459 
SetFilePath(const std::string & path,const base::FilePath & value)460 void PrefService::SetFilePath(const std::string& path,
461                               const base::FilePath& value) {
462   SetUserPrefValue(path, base::FilePathToValue(value));
463 }
464 
SetInt64(const std::string & path,int64_t value)465 void PrefService::SetInt64(const std::string& path, int64_t value) {
466   SetUserPrefValue(path, base::Int64ToValue(value));
467 }
468 
GetInt64(const std::string & path) const469 int64_t PrefService::GetInt64(const std::string& path) const {
470   const base::Value& value = GetValue(path);
471   std::optional<int64_t> integer = base::ValueToInt64(value);
472   DCHECK(integer);
473   return integer.value_or(0);
474 }
475 
SetUint64(const std::string & path,uint64_t value)476 void PrefService::SetUint64(const std::string& path, uint64_t value) {
477   SetUserPrefValue(path, base::Value(base::NumberToString(value)));
478 }
479 
GetUint64(const std::string & path) const480 uint64_t PrefService::GetUint64(const std::string& path) const {
481   const base::Value& value = GetValue(path);
482   if (!value.is_string())
483     return 0;
484 
485   uint64_t result;
486   base::StringToUint64(value.GetString(), &result);
487   return result;
488 }
489 
SetTime(const std::string & path,base::Time value)490 void PrefService::SetTime(const std::string& path, base::Time value) {
491   SetUserPrefValue(path, base::TimeToValue(value));
492 }
493 
GetTime(const std::string & path) const494 base::Time PrefService::GetTime(const std::string& path) const {
495   const base::Value& value = GetValue(path);
496   std::optional<base::Time> time = base::ValueToTime(value);
497   DCHECK(time);
498   return time.value_or(base::Time());
499 }
500 
SetTimeDelta(const std::string & path,base::TimeDelta value)501 void PrefService::SetTimeDelta(const std::string& path, base::TimeDelta value) {
502   SetUserPrefValue(path, base::TimeDeltaToValue(value));
503 }
504 
GetTimeDelta(const std::string & path) const505 base::TimeDelta PrefService::GetTimeDelta(const std::string& path) const {
506   const base::Value& value = GetValue(path);
507   std::optional<base::TimeDelta> time_delta = base::ValueToTimeDelta(value);
508   DCHECK(time_delta);
509   return time_delta.value_or(base::TimeDelta());
510 }
511 
GetMutableUserPref(const std::string & path,base::Value::Type type)512 base::Value* PrefService::GetMutableUserPref(const std::string& path,
513                                              base::Value::Type type) {
514   CHECK(type == base::Value::Type::DICT || type == base::Value::Type::LIST);
515   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
516 
517   const Preference* pref = FindPreference(path);
518   if (!pref) {
519     NOTREACHED() << "Trying to get an unregistered pref: " << path;
520     return nullptr;
521   }
522   if (pref->GetType() != type) {
523     NOTREACHED() << "Wrong type for GetMutableValue: " << path;
524     return nullptr;
525   }
526 
527   // Look for an existing preference in the user store. Return it in case it
528   // exists and has the correct type.
529   base::Value* value = nullptr;
530   if (user_pref_store_->GetMutableValue(path, &value) &&
531       value->type() == type) {
532     return value;
533   }
534 
535   // If no user preference of the correct type exists, clone default value.
536   const base::Value* default_value = nullptr;
537   pref_registry_->defaults()->GetValue(path, &default_value);
538   DCHECK_EQ(default_value->type(), type);
539   user_pref_store_->SetValueSilently(path, default_value->Clone(),
540                                      GetWriteFlags(pref));
541   user_pref_store_->GetMutableValue(path, &value);
542   return value;
543 }
544 
ReportUserPrefChanged(const std::string & key)545 void PrefService::ReportUserPrefChanged(const std::string& key) {
546   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
547   user_pref_store_->ReportValueChanged(key, GetWriteFlags(FindPreference(key)));
548 }
549 
ReportUserPrefChanged(const std::string & key,std::set<std::vector<std::string>> path_components)550 void PrefService::ReportUserPrefChanged(
551     const std::string& key,
552     std::set<std::vector<std::string>> path_components) {
553   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
554   user_pref_store_->ReportSubValuesChanged(key, std::move(path_components),
555                                            GetWriteFlags(FindPreference(key)));
556 }
557 
SetUserPrefValue(const std::string & path,base::Value new_value)558 void PrefService::SetUserPrefValue(const std::string& path,
559                                    base::Value new_value) {
560   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
561 
562   const Preference* pref = FindPreference(path);
563   if (!pref) {
564     NOTREACHED() << "Trying to write an unregistered pref: " << path;
565     return;
566   }
567   if (pref->GetType() != new_value.type()) {
568     NOTREACHED() << "Trying to set pref " << path << " of type "
569                  << pref->GetType() << " to value of type " << new_value.type();
570     return;
571   }
572 
573   user_pref_store_->SetValue(path, std::move(new_value), GetWriteFlags(pref));
574 }
575 
UpdateCommandLinePrefStore(PrefStore * command_line_store)576 void PrefService::UpdateCommandLinePrefStore(PrefStore* command_line_store) {
577   pref_value_store_->UpdateCommandLinePrefStore(command_line_store);
578 }
579 
580 ///////////////////////////////////////////////////////////////////////////////
581 // PrefService::Preference
582 
Preference(const PrefService * service,std::string name,base::Value::Type type)583 PrefService::Preference::Preference(const PrefService* service,
584                                     std::string name,
585                                     base::Value::Type type)
586     : name_(std::move(name)),
587       type_(type),
588       // Cache the registration flags at creation time to avoid multiple map
589       // lookups later.
590       registration_flags_(service->pref_registry_->GetRegistrationFlags(name_)),
591       pref_service_(service) {}
592 
GetValue() const593 const base::Value* PrefService::Preference::GetValue() const {
594   return pref_service_->GetPreferenceValue(name_);
595 }
596 
GetRecommendedValue() const597 const base::Value* PrefService::Preference::GetRecommendedValue() const {
598   DCHECK(pref_service_->FindPreference(name_))
599       << "Must register pref before getting its value";
600 
601   const base::Value* found_value = nullptr;
602   if (pref_value_store()->GetRecommendedValue(name_, type_, &found_value)) {
603     DCHECK(found_value->type() == type_);
604     return found_value;
605   }
606 
607   // The pref has no recommended value.
608   return nullptr;
609 }
610 
IsManaged() const611 bool PrefService::Preference::IsManaged() const {
612   return pref_value_store()->PrefValueInManagedStore(name_);
613 }
614 
IsManagedByCustodian() const615 bool PrefService::Preference::IsManagedByCustodian() const {
616   return pref_value_store()->PrefValueInSupervisedStore(name_);
617 }
618 
IsRecommended() const619 bool PrefService::Preference::IsRecommended() const {
620   return pref_value_store()->PrefValueFromRecommendedStore(name_);
621 }
622 
HasExtensionSetting() const623 bool PrefService::Preference::HasExtensionSetting() const {
624   return pref_value_store()->PrefValueInExtensionStore(name_);
625 }
626 
HasUserSetting() const627 bool PrefService::Preference::HasUserSetting() const {
628   return pref_value_store()->PrefValueInUserStore(name_);
629 }
630 
IsExtensionControlled() const631 bool PrefService::Preference::IsExtensionControlled() const {
632   return pref_value_store()->PrefValueFromExtensionStore(name_);
633 }
634 
IsUserControlled() const635 bool PrefService::Preference::IsUserControlled() const {
636   return pref_value_store()->PrefValueFromUserStore(name_);
637 }
638 
IsDefaultValue() const639 bool PrefService::Preference::IsDefaultValue() const {
640   return pref_value_store()->PrefValueFromDefaultStore(name_);
641 }
642 
IsUserModifiable() const643 bool PrefService::Preference::IsUserModifiable() const {
644   return pref_value_store()->PrefValueUserModifiable(name_);
645 }
646 
IsExtensionModifiable() const647 bool PrefService::Preference::IsExtensionModifiable() const {
648   return pref_value_store()->PrefValueExtensionModifiable(name_);
649 }
650 
651 #if BUILDFLAG(IS_CHROMEOS_ASH)
IsStandaloneBrowserControlled() const652 bool PrefService::Preference::IsStandaloneBrowserControlled() const {
653   return pref_value_store()->PrefValueFromStandaloneBrowserStore(name_);
654 }
655 
IsStandaloneBrowserModifiable() const656 bool PrefService::Preference::IsStandaloneBrowserModifiable() const {
657   return pref_value_store()->PrefValueStandaloneBrowserModifiable(name_);
658 }
659 #endif
660 
GetPreferenceValue(base::StringPiece path) const661 const base::Value* PrefService::GetPreferenceValue(
662     base::StringPiece path) const {
663   DCHECK_CALLED_ON_VALID_SEQUENCE(sequence_checker_);
664 
665   const base::Value* default_value = nullptr;
666   CHECK(pref_registry_->defaults()->GetValue(path, &default_value))
667       << "Trying to access an unregistered pref: " << path;
668   CHECK(default_value);
669   const base::Value::Type default_type = default_value->type();
670 
671   const base::Value* found_value = nullptr;
672   // GetValue shouldn't fail because every registered preference has at least a
673   // default value.
674   CHECK(pref_value_store_->GetValue(path, default_type, &found_value));
675   CHECK(found_value);
676   // The type is expected to match here thanks to a verification in
677   // PrefValueStore::GetValueFromStoreWithType which discards polluted values
678   // (and we should at least get a matching type from the default store if no
679   // other store has a valid value+type).
680   CHECK_EQ(found_value->type(), default_type);
681   return found_value;
682 }
683 
684 #if BUILDFLAG(IS_CHROMEOS_ASH)
SetStandaloneBrowserPref(const std::string & path,const base::Value & value)685 void PrefService::SetStandaloneBrowserPref(const std::string& path,
686                                            const base::Value& value) {
687   if (!standalone_browser_pref_store_) {
688     LOG(WARNING) << "Failure to set value of " << path
689                  << " in standalone browser store";
690     return;
691   }
692   standalone_browser_pref_store_->SetValue(
693       path, value.Clone(), WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
694 }
695 
RemoveStandaloneBrowserPref(const std::string & path)696 void PrefService::RemoveStandaloneBrowserPref(const std::string& path) {
697   if (!standalone_browser_pref_store_) {
698     LOG(WARNING) << "Failure to remove value of " << path
699                  << " in standalone browser store";
700     return;
701   }
702   standalone_browser_pref_store_->RemoveValue(
703       path, WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS);
704 }
705 #endif
706 
707 // static
GetWriteFlags(const PrefService::Preference * pref)708 uint32_t PrefService::GetWriteFlags(const PrefService::Preference* pref) {
709   uint32_t write_flags = WriteablePrefStore::DEFAULT_PREF_WRITE_FLAGS;
710 
711   if (!pref) {
712     return write_flags;
713   }
714 
715   if (pref->registration_flags() & PrefRegistry::LOSSY_PREF) {
716     write_flags |= WriteablePrefStore::LOSSY_PREF_WRITE_FLAG;
717   }
718   return write_flags;
719 }
720