xref: /aosp_15_r20/external/cronet/base/feature_list.h (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
1 // Copyright 2015 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 #ifndef BASE_FEATURE_LIST_H_
6 #define BASE_FEATURE_LIST_H_
7 
8 #include <atomic>
9 #include <functional>
10 #include <map>
11 #include <memory>
12 #include <optional>
13 #include <string>
14 #include <string_view>
15 #include <utility>
16 #include <vector>
17 
18 #include "base/base_export.h"
19 #include "base/compiler_specific.h"
20 #include "base/containers/flat_map.h"
21 #include "base/containers/flat_set.h"
22 #include "base/dcheck_is_on.h"
23 #include "base/feature_list_buildflags.h"
24 #include "base/gtest_prod_util.h"
25 #include "base/logging.h"
26 #include "base/memory/raw_ptr.h"
27 #include "base/synchronization/lock.h"
28 #include "build/build_config.h"
29 #include "build/chromeos_buildflags.h"
30 
31 namespace base {
32 
33 class FieldTrial;
34 class FieldTrialList;
35 class PersistentMemoryAllocator;
36 
37 #if BUILDFLAG(IS_CHROMEOS_ASH)
38 class FeatureVisitor;
39 #endif  // BUILDFLAG(IS_CHROMEOS_ASH)
40 
41 // Specifies whether a given feature is enabled or disabled by default.
42 // NOTE: The actual runtime state may be different, due to a field trial or a
43 // command line switch.
44 enum FeatureState {
45   FEATURE_DISABLED_BY_DEFAULT,
46   FEATURE_ENABLED_BY_DEFAULT,
47 };
48 
49 // Recommended macros for declaring and defining features:
50 //
51 // - `kFeature` is the C++ identifier that will be used for the `base::Feature`.
52 // - `name` is the feature name, which must be globally unique. This name is
53 //   used to enable/disable features via experiments and command-line flags.
54 //   Names should use CamelCase-style naming, e.g. "MyGreatFeature".
55 // - `default_state` is the default state to use for the feature, i.e.
56 //   `base::FEATURE_DISABLED_BY_DEFAULT` or `base::FEATURE_ENABLED_BY_DEFAULT`.
57 //   As noted above, the actual runtime state may differ from the default state,
58 //   due to field trials or command-line switches.
59 
60 // Provides a forward declaration for `kFeature` in a header file, e.g.
61 //
62 //   BASE_DECLARE_FEATURE(kMyFeature);
63 //
64 // If the feature needs to be marked as exported, i.e. it is referenced by
65 // multiple components, then write:
66 //
67 //   COMPONENT_EXPORT(MY_COMPONENT) BASE_DECLARE_FEATURE(kMyFeature);
68 #define BASE_DECLARE_FEATURE(kFeature) \
69   extern constinit const base::Feature kFeature
70 
71 // Provides a definition for `kFeature` with `name` and `default_state`, e.g.
72 //
73 //   BASE_FEATURE(kMyFeature, "MyFeature", base::FEATURE_DISABLED_BY_DEFAULT);
74 //
75 // Features should *not* be defined in header files; do not use this macro in
76 // header files.
77 #define BASE_FEATURE(feature, name, default_state) \
78   constinit const base::Feature feature(name, default_state)
79 
80 // The Feature struct is used to define the default state for a feature. There
81 // must only ever be one struct instance for a given feature name—generally
82 // defined as a constant global variable or file static. Declare and define
83 // features using the `BASE_DECLARE_FEATURE()` and `BASE_FEATURE()` macros
84 // above, as there are some subtleties involved.
85 //
86 // Feature constants are internally mutable, as this allows them to contain a
87 // mutable member to cache their override state, while still remaining declared
88 // as const. This cache member allows for significantly faster IsEnabled()
89 // checks.
90 //
91 // However, the "Mutable Constants" check [1] detects this as a regression,
92 // because this usually means that a readonly symbol is put in writable memory
93 // when readonly memory would be more efficient.
94 //
95 // The performance gains of the cache are large enough to offset the downsides
96 // to having the symbols in bssdata rather than rodata. Use LOGICALLY_CONST to
97 // suppress the "Mutable Constants" check.
98 //
99 // [1]:
100 // https://crsrc.org/c/docs/speed/binary_size/android_binary_size_trybot.md#Mutable-Constants
101 struct BASE_EXPORT LOGICALLY_CONST Feature {
FeatureFeature102   constexpr Feature(const char* name, FeatureState default_state)
103       : name(name), default_state(default_state) {
104 #if BUILDFLAG(ENABLE_BANNED_BASE_FEATURE_PREFIX)
105     if (std::string_view(name).find(BUILDFLAG(BANNED_BASE_FEATURE_PREFIX)) ==
106         0) {
107       LOG(FATAL) << "Invalid feature name " << name << " starts with "
108                  << BUILDFLAG(BANNED_BASE_FEATURE_PREFIX);
109     }
110 #endif  // BUILDFLAG(ENABLE_BANNED_BASE_FEATURE_PREFIX)
111   }
112 
113   // Non-copyable since:
114   // - there should be only one `Feature` instance per unique name.
115   // - a `Feature` contains internal cached state about the override state.
116   Feature(const Feature&) = delete;
117   Feature& operator=(const Feature&) = delete;
118 
119   // The name of the feature. This should be unique to each feature and is used
120   // for enabling/disabling features via command line flags and experiments.
121   // It is strongly recommended to use CamelCase style for feature names, e.g.
122   // "MyGreatFeature".
123   const char* const name;
124 
125   // The default state (i.e. enabled or disabled) for this feature.
126   // NOTE: The actual runtime state may be different, due to a field trial or a
127   // command line switch.
128   const FeatureState default_state;
129 
130  private:
131   friend class FeatureList;
132 
133   // A packed value where the first 8 bits represent the `OverrideState` of this
134   // feature, and the last 16 bits are a caching context ID used to allow
135   // ScopedFeatureLists to invalidate these cached values in testing. A value of
136   // 0 in the caching context ID field indicates that this value has never been
137   // looked up and cached, a value of 1 indicates this value contains the cached
138   // `OverrideState` that was looked up via `base::FeatureList`, and any other
139   // value indicate that this cached value is only valid for a particular
140   // ScopedFeatureList instance.
141   //
142   // Packing these values into a uint32_t makes it so that atomic operations
143   // performed on this fields can be lock free.
144   //
145   // The override state stored in this field is only used if the current
146   // `FeatureList::caching_context_` field is equal to the lower 16 bits of the
147   // packed cached value. Otherwise, the override state is looked up in the
148   // feature list and the cache is updated.
149   mutable std::atomic<uint32_t> cached_value = 0;
150 };
151 
152 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE)
153 // DCHECKs have been built-in, and are configurable at run-time to be fatal, or
154 // not, via a DcheckIsFatal feature. We define the Feature here since it is
155 // checked in FeatureList::SetInstance(). See https://crbug.com/596231.
156 BASE_EXPORT BASE_DECLARE_FEATURE(kDCheckIsFatalFeature);
157 #endif  // BUILDFLAG(DCHECK_IS_CONFIGURABLE)
158 
159 // The FeatureList class is used to determine whether a given feature is on or
160 // off. It provides an authoritative answer, taking into account command-line
161 // overrides and experimental control.
162 //
163 // The basic use case is for any feature that can be toggled (e.g. through
164 // command-line or an experiment) to have a defined Feature struct, e.g.:
165 //
166 //   const base::Feature kMyGreatFeature {
167 //     "MyGreatFeature", base::FEATURE_ENABLED_BY_DEFAULT
168 //   };
169 //
170 // Then, client code that wishes to query the state of the feature would check:
171 //
172 //   if (base::FeatureList::IsEnabled(kMyGreatFeature)) {
173 //     // Feature code goes here.
174 //   }
175 //
176 // Behind the scenes, the above call would take into account any command-line
177 // flags to enable or disable the feature, any experiments that may control it
178 // and finally its default state (in that order of priority), to determine
179 // whether the feature is on.
180 //
181 // Features can be explicitly forced on or off by specifying a list of comma-
182 // separated feature names via the following command-line flags:
183 //
184 //   --enable-features=Feature5,Feature7
185 //   --disable-features=Feature1,Feature2,Feature3
186 //
187 // To enable/disable features in a test, do NOT append --enable-features or
188 // --disable-features to the command-line directly. Instead, use
189 // ScopedFeatureList. See base/test/scoped_feature_list.h for details.
190 //
191 // After initialization (which should be done single-threaded), the FeatureList
192 // API is thread safe.
193 //
194 // Note: This class is a singleton, but does not use base/memory/singleton.h in
195 // order to have control over its initialization sequence. Specifically, the
196 // intended use is to create an instance of this class and fully initialize it,
197 // before setting it as the singleton for a process, via SetInstance().
198 class BASE_EXPORT FeatureList {
199  public:
200   FeatureList();
201   FeatureList(const FeatureList&) = delete;
202   FeatureList& operator=(const FeatureList&) = delete;
203   ~FeatureList();
204 
205   // Used by common test fixture classes to prevent abuse of ScopedFeatureList
206   // after multiple threads have started.
207   class BASE_EXPORT ScopedDisallowOverrides {
208    public:
209     explicit ScopedDisallowOverrides(const char* reason);
210     ScopedDisallowOverrides(const ScopedDisallowOverrides&) = delete;
211     ScopedDisallowOverrides& operator=(const ScopedDisallowOverrides&) = delete;
212     ~ScopedDisallowOverrides();
213 
214    private:
215 #if DCHECK_IS_ON()
216     const char* const previous_reason_;
217 #endif
218   };
219 
220   // Specifies whether a feature override enables or disables the feature.
221   enum OverrideState {
222     OVERRIDE_USE_DEFAULT,
223     OVERRIDE_DISABLE_FEATURE,
224     OVERRIDE_ENABLE_FEATURE,
225   };
226 
227   // Accessor class, used to look up features by _name_ rather than by Feature
228   // object.
229   // Should only be used in limited cases. See ConstructAccessor() for details.
230   class BASE_EXPORT Accessor {
231    public:
232     Accessor(const Accessor&) = delete;
233     Accessor& operator=(const Accessor&) = delete;
234 
235     // Looks up the feature, returning only its override state, rather than
236     // falling back on a default value (since there is no default value given).
237     // Callers of this MUST ensure that there is a consistent, compile-time
238     // default value associated.
239     FeatureList::OverrideState GetOverrideStateByFeatureName(
240         std::string_view feature_name);
241 
242     // Look up the feature, and, if present, populate |params|.
243     // See GetFieldTrialParams in field_trial_params.h for more documentation.
244     bool GetParamsByFeatureName(std::string_view feature_name,
245                                 std::map<std::string, std::string>* params);
246 
247    private:
248     // Allow FeatureList to construct this class.
249     friend class FeatureList;
250 
251     explicit Accessor(FeatureList* feature_list);
252 
253     // Unowned pointer to the FeatureList object we use to look up feature
254     // enablement.
255     raw_ptr<FeatureList, DanglingUntriaged> feature_list_;
256   };
257 
258   // Describes a feature override. The first member is a Feature that will be
259   // overridden with the state given by the second member.
260   using FeatureOverrideInfo =
261       std::pair<const std::reference_wrapper<const Feature>, OverrideState>;
262 
263   // Initializes feature overrides via command-line flags `--enable-features=`
264   // and `--disable-features=`, each of which is a comma-separated list of
265   // features to enable or disable, respectively. This function also allows
266   // users to set a feature's field trial params via `--enable-features=`. Must
267   // only be invoked during the initialization phase (before
268   // FinalizeInitialization() has been called).
269   //
270   // If a feature appears on both lists, then it will be disabled. If
271   // a list entry has the format "FeatureName<TrialName" then this
272   // initialization will also associate the feature state override with the
273   // named field trial, if it exists. If a list entry has the format
274   // "FeatureName:k1/v1/k2/v2", "FeatureName<TrialName:k1/v1/k2/v2" or
275   // "FeatureName<TrialName.GroupName:k1/v1/k2/v2" then this initialization will
276   // also associate the feature state override with the named field trial and
277   // its params. If the feature params part is provided but trial and/or group
278   // isn't, this initialization will also create a synthetic trial, named
279   // "Study" followed by the feature name, i.e. "StudyFeature", and group, named
280   // "Group" followed by the feature name, i.e. "GroupFeature", for the params.
281   // If a feature name is prefixed with the '*' character, it will be created
282   // with OVERRIDE_USE_DEFAULT - which is useful for associating with a trial
283   // while using the default state.
284   void InitFromCommandLine(const std::string& enable_features,
285                            const std::string& disable_features);
286 
287   // Initializes feature overrides through the field trial allocator, which
288   // we're using to store the feature names, their override state, and the name
289   // of the associated field trial.
290   void InitFromSharedMemory(PersistentMemoryAllocator* allocator);
291 
292   // Returns true if the state of |feature_name| has been overridden (regardless
293   // of whether the overridden value is the same as the default value) for any
294   // reason (e.g. command line or field trial).
295   bool IsFeatureOverridden(const std::string& feature_name) const;
296 
297   // Returns true if the state of |feature_name| has been overridden via
298   // |InitFromCommandLine()|. This includes features explicitly
299   // disabled/enabled with --disable-features and --enable-features, as well as
300   // any extra feature overrides that depend on command line switches.
301   bool IsFeatureOverriddenFromCommandLine(
302       const std::string& feature_name) const;
303 
304   // Returns true if the state |feature_name| has been overridden by
305   // |InitFromCommandLine()| and the state matches |state|.
306   bool IsFeatureOverriddenFromCommandLine(const std::string& feature_name,
307                                           OverrideState state) const;
308 
309   // Associates a field trial for reporting purposes corresponding to the
310   // command-line setting the feature state to |for_overridden_state|. The trial
311   // will be activated when the state of the feature is first queried. This
312   // should be called during registration, after InitFromCommandLine() has
313   // been called but before the instance is registered via SetInstance().
314   void AssociateReportingFieldTrial(const std::string& feature_name,
315                                     OverrideState for_overridden_state,
316                                     FieldTrial* field_trial);
317 
318   // Registers a field trial to override the enabled state of the specified
319   // feature to |override_state|. Command-line overrides still take precedence
320   // over field trials, so this will have no effect if the feature is being
321   // overridden from the command-line. The associated field trial will be
322   // activated when the feature state for this feature is queried. This should
323   // be called during registration, after InitFromCommandLine() has been
324   // called but before the instance is registered via SetInstance().
325   void RegisterFieldTrialOverride(const std::string& feature_name,
326                                   OverrideState override_state,
327                                   FieldTrial* field_trial);
328 
329   // Adds extra overrides (not associated with a field trial). Should be called
330   // before SetInstance().
331   // The ordering of calls with respect to InitFromCommandLine(),
332   // RegisterFieldTrialOverride(), etc. matters. The first call wins out,
333   // because the |overrides_| map uses insert(), which retains the first
334   // inserted entry and does not overwrite it on subsequent calls to insert().
335   void RegisterExtraFeatureOverrides(
336       const std::vector<FeatureOverrideInfo>& extra_overrides);
337 
338   // Loops through feature overrides and serializes them all into |allocator|.
339   void AddFeaturesToAllocator(PersistentMemoryAllocator* allocator);
340 
341   // Returns comma-separated lists of feature names (in the same format that is
342   // accepted by InitFromCommandLine()) corresponding to features that
343   // have been overridden - either through command-line or via FieldTrials. For
344   // those features that have an associated FieldTrial, the output entry will be
345   // of the format "FeatureName<TrialName" (|include_group_name|=false) or
346   // "FeatureName<TrialName.GroupName" (if |include_group_name|=true), where
347   // "TrialName" is the name of the FieldTrial and "GroupName" is the group
348   // name of the FieldTrial. Features that have overrides with
349   // OVERRIDE_USE_DEFAULT will be added to |enable_overrides| with a '*'
350   // character prefix. Must be called only after the instance has been
351   // initialized and registered.
352   void GetFeatureOverrides(std::string* enable_overrides,
353                            std::string* disable_overrides,
354                            bool include_group_names = false) const;
355 
356   // Like GetFeatureOverrides(), but only returns overrides that were specified
357   // explicitly on the command-line, omitting the ones from field trials.
358   void GetCommandLineFeatureOverrides(std::string* enable_overrides,
359                                       std::string* disable_overrides) const;
360 
361   // Returns the field trial associated with the given feature |name|. Used for
362   // getting the FieldTrial without requiring a struct Feature.
363   base::FieldTrial* GetAssociatedFieldTrialByFeatureName(
364       std::string_view name) const;
365 
366   // DO NOT USE outside of internal field trial implementation code. Instead use
367   // GetAssociatedFieldTrialByFeatureName(), which performs some additional
368   // validation.
369   //
370   // Returns whether the given feature |name| is associated with a field trial.
371   // If the given feature |name| does not exist, return false. Unlike
372   // GetAssociatedFieldTrialByFeatureName(), this function must be called during
373   // |FeatureList| initialization; the returned value will report whether the
374   // provided |name| has been used so far.
375   bool HasAssociatedFieldTrialByFeatureName(std::string_view name) const;
376 
377   // Get associated field trial for the given feature |name| only if override
378   // enables it.
379   FieldTrial* GetEnabledFieldTrialByFeatureName(std::string_view name) const;
380 
381   // Construct an accessor allowing access to GetOverrideStateByFeatureName().
382   // This can only be called before the FeatureList is initialized, and is
383   // intended for very narrow use.
384   // If you're tempted to use it, do so only in consultation with feature_list
385   // OWNERS.
386   std::unique_ptr<Accessor> ConstructAccessor();
387 
388   // Returns whether the given `feature` is enabled.
389   //
390   // If no `FeatureList` instance is registered, this will:
391   // - DCHECK(), if FailOnFeatureAccessWithoutFeatureList() was called.
392   //     TODO(crbug.com/1358639): Change the DCHECK to a CHECK when we're
393   //     confident that all early accesses have been fixed. We don't want to
394   //     get many crash reports from the field in the meantime.
395   // - Return the default state, otherwise. Registering a `FeatureList` later
396   //   will fail.
397   //
398   // TODO(crbug.com/1358639): Make early FeatureList access fail on iOS, Android
399   // and ChromeOS. This currently only works on Windows, Mac and Linux.
400   //
401   // A feature with a given name must only have a single corresponding Feature
402   // instance, which is checked in builds with DCHECKs enabled.
403   static bool IsEnabled(const Feature& feature);
404 
405   // Some characters are not allowed to appear in feature names or the
406   // associated field trial names, as they are used as special characters for
407   // command-line serialization. This function checks that the strings are ASCII
408   // (since they are used in command-line API functions that require ASCII) and
409   // whether there are any reserved characters present, returning true if the
410   // string is valid.
411   static bool IsValidFeatureOrFieldTrialName(std::string_view name);
412 
413   // If the given |feature| is overridden, returns its enabled state; otherwise,
414   // returns an empty optional. Must only be called after the singleton instance
415   // has been registered via SetInstance(). Additionally, a feature with a given
416   // name must only have a single corresponding Feature struct, which is checked
417   // in builds with DCHECKs enabled.
418   static std::optional<bool> GetStateIfOverridden(const Feature& feature);
419 
420   // Returns the field trial associated with the given |feature|. Must only be
421   // called after the singleton instance has been registered via SetInstance().
422   static FieldTrial* GetFieldTrial(const Feature& feature);
423 
424   // Splits a comma-separated string containing feature names into a vector. The
425   // resulting pieces point to parts of |input|.
426   static std::vector<std::string_view> SplitFeatureListString(
427       std::string_view input);
428 
429   // Checks and parses the |enable_feature| (e.g.
430   // FeatureName<Study.Group:Param1/value1/) obtained by applying
431   // SplitFeatureListString() to the |enable_features| flag, and sets
432   // |feature_name| to be the feature's name, |study_name| and |group_name| to
433   // be the field trial name and its group name if the field trial is specified
434   // or field trial parameters are given, |params| to be the field trial
435   // parameters if exists.
436   static bool ParseEnableFeatureString(std::string_view enable_feature,
437                                        std::string* feature_name,
438                                        std::string* study_name,
439                                        std::string* group_name,
440                                        std::string* params);
441 
442   // Initializes and sets an instance of FeatureList with feature overrides via
443   // command-line flags |enable_features| and |disable_features| if one has not
444   // already been set from command-line flags. Returns true if an instance did
445   // not previously exist. See InitFromCommandLine() for more details
446   // about |enable_features| and |disable_features| parameters.
447   static bool InitInstance(const std::string& enable_features,
448                            const std::string& disable_features);
449 
450   // Like the above, but also adds extra overrides. If a feature appears in
451   // |extra_overrides| and also |enable_features| or |disable_features|, the
452   // disable/enable will supersede the extra overrides.
453   static bool InitInstance(
454       const std::string& enable_features,
455       const std::string& disable_features,
456       const std::vector<FeatureOverrideInfo>& extra_overrides);
457 
458   // Returns the singleton instance of FeatureList. Will return null until an
459   // instance is registered via SetInstance().
460   static FeatureList* GetInstance();
461 
462   // Registers the given |instance| to be the singleton feature list for this
463   // process. This should only be called once and |instance| must not be null.
464   // Note: If you are considering using this for the purposes of testing, take
465   // a look at using base/test/scoped_feature_list.h instead.
466   static void SetInstance(std::unique_ptr<FeatureList> instance);
467 
468   // Registers the given `instance` to be the temporary singleton feature list
469   // for this process. While the given `instance` is the singleton feature list,
470   // only the state of features matching `allowed_feature_names` can be checked.
471   // Attempting to query other feature will behave as if no feature list was set
472   // at all. It is expected that this instance is replaced using `SetInstance`
473   // with an instance without limitations as soon as practical.
474   static void SetEarlyAccessInstance(
475       std::unique_ptr<FeatureList> instance,
476       base::flat_set<std::string> allowed_feature_names);
477 
478   // Clears the previously-registered singleton instance for tests and returns
479   // the old instance.
480   // Note: Most tests should never call this directly. Instead consider using
481   // base::test::ScopedFeatureList.
482   static std::unique_ptr<FeatureList> ClearInstanceForTesting();
483 
484   // Sets a given (initialized) |instance| to be the singleton feature list,
485   // for testing. Existing instance must be null. This is primarily intended
486   // to support base::test::ScopedFeatureList helper class.
487   static void RestoreInstanceForTesting(std::unique_ptr<FeatureList> instance);
488 
489   // After calling this, an attempt to access feature state when no FeatureList
490   // is registered will DCHECK.
491   //
492   // TODO(crbug.com/1358639): Change the DCHECK to a CHECK when we're confident
493   // that all early accesses have been fixed. We don't want to get many crash
494   // reports from the field in the meantime.
495   //
496   // Note: This isn't the default behavior because accesses are tolerated in
497   // processes that never register a FeatureList.
498   static void FailOnFeatureAccessWithoutFeatureList();
499 
500   // Returns the first feature that was accessed before a FeatureList was
501   // registered that allows accessing the feature.
502   static const Feature* GetEarlyAccessedFeatureForTesting();
503 
504   // Resets the state of the early feature access tracker.
505   static void ResetEarlyFeatureAccessTrackerForTesting();
506 
507   // Adds a feature to the early allowed feature access list for tests. Should
508   // only be called on a FeatureList that was set with SetEarlyAccessInstance().
509   void AddEarlyAllowedFeatureForTesting(std::string feature_name);
510 
511 #if BUILDFLAG(IS_CHROMEOS_ASH)
512   // Allows a visitor to record override state, parameters, and field trial
513   // associated with each feature.
514   //
515   // NOTE: This is intended only for the special case of needing to get all
516   // overrides. This use case is specific to CrOS-Ash. Most users should call
517   // IsEnabled() to query a feature's state.
518   static void VisitFeaturesAndParams(FeatureVisitor& visitor);
519 #endif  // BULDFLAG(IS_CHROMEOS_ASH)
520 
521  private:
522   FRIEND_TEST_ALL_PREFIXES(FeatureListTest, CheckFeatureIdentity);
523   FRIEND_TEST_ALL_PREFIXES(FeatureListTest,
524                            StoreAndRetrieveFeaturesFromSharedMemory);
525   FRIEND_TEST_ALL_PREFIXES(FeatureListTest,
526                            StoreAndRetrieveAssociatedFeaturesFromSharedMemory);
527   // Allow Accessor to access GetOverrideStateByFeatureName().
528   friend class Accessor;
529 
530   struct OverrideEntry {
531     // The overridden enable (on/off) state of the feature.
532     OverrideState overridden_state;
533 
534     // An optional associated field trial, which will be activated when the
535     // state of the feature is queried for the first time. Weak pointer to the
536     // FieldTrial object that is owned by the FieldTrialList singleton.
537     raw_ptr<base::FieldTrial> field_trial;
538 
539     // Specifies whether the feature's state is overridden by |field_trial|.
540     // If it's not, and |field_trial| is not null, it means it is simply an
541     // associated field trial for reporting purposes (and |overridden_state|
542     // came from the command-line).
543     bool overridden_by_field_trial;
544 
545     // TODO(asvitkine): Expand this as more support is added.
546 
547     // Constructs an OverrideEntry for the given |overridden_state|. If
548     // |field_trial| is not null, it implies that |overridden_state| comes from
549     // the trial, so |overridden_by_field_trial| will be set to true.
550     OverrideEntry(OverrideState overridden_state, FieldTrial* field_trial);
551   };
552 
553   // Returns the override for the field trial associated with the given feature
554   // |name| or null if the feature is not found.
555   const base::FeatureList::OverrideEntry* GetOverrideEntryByFeatureName(
556       std::string_view name) const;
557 
558   // Finalizes the initialization state of the FeatureList, so that no further
559   // overrides can be registered. This is called by SetInstance() on the
560   // singleton feature list that is being registered.
561   void FinalizeInitialization();
562 
563   // Returns whether the given |feature| is enabled. This is invoked by the
564   // public FeatureList::IsEnabled() static function on the global singleton.
565   // Requires the FeatureList to have already been fully initialized.
566   bool IsFeatureEnabled(const Feature& feature) const;
567 
568   // Returns whether the given |feature| is enabled. This is invoked by the
569   // public FeatureList::GetStateIfOverridden() static function on the global
570   // singleton. Requires the FeatureList to have already been fully initialized.
571   std::optional<bool> IsFeatureEnabledIfOverridden(
572       const Feature& feature) const;
573 
574   // Returns the override state of a given |feature|. If the feature was not
575   // overridden, returns OVERRIDE_USE_DEFAULT. Performs any necessary callbacks
576   // for when the feature state has been observed, e.g. activating field trials.
577   OverrideState GetOverrideState(const Feature& feature) const;
578 
579   // Same as GetOverrideState(), but without a default value.
580   OverrideState GetOverrideStateByFeatureName(
581       std::string_view feature_name) const;
582 
583   // Returns the field trial associated with the given |feature|. This is
584   // invoked by the public FeatureList::GetFieldTrial() static function on the
585   // global singleton. Requires the FeatureList to have already been fully
586   // initialized.
587   base::FieldTrial* GetAssociatedFieldTrial(const Feature& feature) const;
588 
589   // For each feature name in comma-separated list of strings |feature_list|,
590   // registers an override with the specified |overridden_state|. Also, will
591   // associate an optional named field trial if the entry is of the format
592   // "FeatureName<TrialName".
593   void RegisterOverridesFromCommandLine(const std::string& feature_list,
594                                         OverrideState overridden_state);
595 
596   // Registers an override for feature |feature_name|. The override specifies
597   // whether the feature should be on or off (via |overridden_state|), which
598   // will take precedence over the feature's default state. If |field_trial| is
599   // not null, registers the specified field trial object to be associated with
600   // the feature, which will activate the field trial when the feature state is
601   // queried. If an override is already registered for the given feature, it
602   // will not be changed.
603   void RegisterOverride(std::string_view feature_name,
604                         OverrideState overridden_state,
605                         FieldTrial* field_trial);
606 
607   // Implementation of GetFeatureOverrides() with a parameter that specifies
608   // whether only command-line enabled overrides should be emitted. See that
609   // function's comments for more details.
610   void GetFeatureOverridesImpl(std::string* enable_overrides,
611                                std::string* disable_overrides,
612                                bool command_line_only,
613                                bool include_group_name = false) const;
614 
615   // Verifies that there's only a single definition of a Feature struct for a
616   // given feature name. Keeps track of the first seen Feature struct for each
617   // feature. Returns false when called on a Feature struct with a different
618   // address than the first one it saw for that feature name. Used only from
619   // DCHECKs and tests. This is const because it's called from const getters and
620   // doesn't modify externally visible state.
621   bool CheckFeatureIdentity(const Feature& feature) const;
622 
623   // Returns true if this feature list was set with SetEarlyAccessInstance().
624   bool IsEarlyAccessInstance() const;
625 
626   // Returns if this feature list instance allows access to the given feature.
627   // If a this feature list was set with SetEarlyAccessInstance(), only the
628   // features in `allowed_feature_names_` can be checked.
629   bool AllowFeatureAccess(const Feature& feature) const;
630 
631   // Map from feature name to an OverrideEntry struct for the feature, if it
632   // exists.
633   base::flat_map<std::string, OverrideEntry> overrides_;
634 
635   // Locked map that keeps track of seen features, to ensure a single feature is
636   // only defined once. This verification is only done in builds with DCHECKs
637   // enabled. This is mutable as it's not externally visible and needs to be
638   // usable from const getters.
639   mutable Lock feature_identity_tracker_lock_;
640   mutable std::map<std::string, const Feature*> feature_identity_tracker_
641       GUARDED_BY(feature_identity_tracker_lock_);
642 
643   // Tracks the associated FieldTrialList for DCHECKs. This is used to catch
644   // the scenario where multiple FieldTrialList are used with the same
645   // FeatureList - which can lead to overrides pointing to invalid FieldTrial
646   // objects.
647   raw_ptr<base::FieldTrialList> field_trial_list_ = nullptr;
648 
649   // Whether this object has been fully initialized. This gets set to true as a
650   // result of FinalizeInitialization().
651   bool initialized_ = false;
652 
653   // Whether this object has been initialized from command line.
654   bool initialized_from_command_line_ = false;
655 
656   // Used when querying `base::Feature` state to determine if the cached value
657   // in the `Feature` object is populated and valid. See the comment on
658   // `base::Feature::cached_value` for more details.
659   const uint16_t caching_context_;
660 
661   // If this instance was set with SetEarlyAccessInstance(), this set contains
662   // the names of the features whose state is allowed to be checked. Attempting
663   // to check the state of a feature not on this list will behave as if no
664   // feature list was initialized at all.
665   base::flat_set<std::string> allowed_feature_names_;
666 };
667 
668 }  // namespace base
669 
670 #endif  // BASE_FEATURE_LIST_H_
671