1 // Copyright 2015 The Chromium Authors. All rights reserved.
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 <functional>
9 #include <map>
10 #include <memory>
11 #include <string>
12 #include <utility>
13 #include <vector>
14 
15 #include "base/base_export.h"
16 #include "base/gtest_prod_util.h"
17 #include "base/metrics/field_trial_params.h"
18 #include "base/metrics/persistent_memory_allocator.h"
19 #include "base/strings/string_piece.h"
20 #include "base/synchronization/lock.h"
21 
22 namespace base {
23 
24 class FieldTrial;
25 class FieldTrialList;
26 
27 // Specifies whether a given feature is enabled or disabled by default.
28 // NOTE: The actual runtime state may be different, due to a field trial or a
29 // command line switch.
30 enum FeatureState {
31   FEATURE_DISABLED_BY_DEFAULT,
32   FEATURE_ENABLED_BY_DEFAULT,
33 };
34 
35 // The Feature struct is used to define the default state for a feature. See
36 // comment below for more details. There must only ever be one struct instance
37 // for a given feature name - generally defined as a constant global variable or
38 // file static. It should never be used as a constexpr as it breaks
39 // pointer-based identity lookup.
40 struct BASE_EXPORT Feature {
41   // The name of the feature. This should be unique to each feature and is used
42   // for enabling/disabling features via command line flags and experiments.
43   // It is strongly recommended to use CamelCase style for feature names, e.g.
44   // "MyGreatFeature".
45   const char* const name;
46 
47   // The default state (i.e. enabled or disabled) for this feature.
48   // NOTE: The actual runtime state may be different, due to a field trial or a
49   // command line switch.
50   const FeatureState default_state;
51 };
52 
53 #if defined(DCHECK_IS_CONFIGURABLE)
54 // DCHECKs have been built-in, and are configurable at run-time to be fatal, or
55 // not, via a DcheckIsFatal feature. We define the Feature here since it is
56 // checked in FeatureList::SetInstance(). See https://crbug.com/596231.
57 extern BASE_EXPORT const Feature kDCheckIsFatalFeature;
58 #endif  // defined(DCHECK_IS_CONFIGURABLE)
59 
60 // The FeatureList class is used to determine whether a given feature is on or
61 // off. It provides an authoritative answer, taking into account command-line
62 // overrides and experimental control.
63 //
64 // The basic use case is for any feature that can be toggled (e.g. through
65 // command-line or an experiment) to have a defined Feature struct, e.g.:
66 //
67 //   const base::Feature kMyGreatFeature {
68 //     "MyGreatFeature", base::FEATURE_ENABLED_BY_DEFAULT
69 //   };
70 //
71 // Then, client code that wishes to query the state of the feature would check:
72 //
73 //   if (base::FeatureList::IsEnabled(kMyGreatFeature)) {
74 //     // Feature code goes here.
75 //   }
76 //
77 // Behind the scenes, the above call would take into account any command-line
78 // flags to enable or disable the feature, any experiments that may control it
79 // and finally its default state (in that order of priority), to determine
80 // whether the feature is on.
81 //
82 // Features can be explicitly forced on or off by specifying a list of comma-
83 // separated feature names via the following command-line flags:
84 //
85 //   --enable-features=Feature5,Feature7
86 //   --disable-features=Feature1,Feature2,Feature3
87 //
88 // To enable/disable features in a test, do NOT append --enable-features or
89 // --disable-features to the command-line directly. Instead, use
90 // ScopedFeatureList. See base/test/scoped_feature_list.h for details.
91 //
92 // After initialization (which should be done single-threaded), the FeatureList
93 // API is thread safe.
94 //
95 // Note: This class is a singleton, but does not use base/memory/singleton.h in
96 // order to have control over its initialization sequence. Specifically, the
97 // intended use is to create an instance of this class and fully initialize it,
98 // before setting it as the singleton for a process, via SetInstance().
99 class BASE_EXPORT FeatureList {
100  public:
101   FeatureList();
102   FeatureList(const FeatureList&) = delete;
103   FeatureList& operator=(const FeatureList&) = delete;
104   ~FeatureList();
105 
106   // Used by common test fixture classes to prevent abuse of ScopedFeatureList
107   // after multiple threads have started.
108   class BASE_EXPORT ScopedDisallowOverrides {
109    public:
110     explicit ScopedDisallowOverrides(const char* reason);
111     ScopedDisallowOverrides(const ScopedDisallowOverrides&) = delete;
112     ScopedDisallowOverrides& operator=(const ScopedDisallowOverrides&) = delete;
113     ~ScopedDisallowOverrides();
114 
115    private:
116 #if DCHECK_IS_ON()
117     const char* const previous_reason_;
118 #endif
119   };
120 
121   // Specifies whether a feature override enables or disables the feature.
122   enum OverrideState {
123     OVERRIDE_USE_DEFAULT,
124     OVERRIDE_DISABLE_FEATURE,
125     OVERRIDE_ENABLE_FEATURE,
126   };
127 
128   // Describes a feature override. The first member is a Feature that will be
129   // overridden with the state given by the second member.
130   using FeatureOverrideInfo =
131       std::pair<const std::reference_wrapper<const Feature>, OverrideState>;
132 
133   // Initializes feature overrides via command-line flags `--enable-features=`
134   // and `--disable-features=`, each of which is a comma-separated list of
135   // features to enable or disable, respectively. This function also allows
136   // users to set a feature's field trial params via `--enable-features=`. Must
137   // only be invoked during the initialization phase (before
138   // FinalizeInitialization() has been called).
139   //
140   // If a feature appears on both lists, then it will be disabled. If
141   // a list entry has the format "FeatureName<TrialName" then this
142   // initialization will also associate the feature state override with the
143   // named field trial, if it exists. If a list entry has the format
144   // "FeatureName:k1/v1/k2/v2", "FeatureName<TrailName:k1/v1/k2/v2" or
145   // "FeatureName<TrailName.GroupName:k1/v1/k2/v2" then this initialization will
146   // also associate the feature state override with the named field trial and
147   // its params. If the feature params part is provided but trial and/or group
148   // isn't, this initialization will also create a synthetic trial, named
149   // "Study" followed by the feature name, i.e. "StudyFeature", and group, named
150   // "Group" followed by the feature name, i.e. "GroupFeature", for the params.
151   // If a feature name is prefixed with the '*' character, it will be created
152   // with OVERRIDE_USE_DEFAULT - which is useful for associating with a trial
153   // while using the default state.
154   void InitializeFromCommandLine(const std::string& enable_features,
155                                  const std::string& disable_features);
156 
157   // Initializes feature overrides through the field trial allocator, which
158   // we're using to store the feature names, their override state, and the name
159   // of the associated field trial.
160   void InitializeFromSharedMemory(PersistentMemoryAllocator* allocator);
161 
162   // Returns true if the state of |feature_name| has been overridden (regardless
163   // of whether the overridden value is the same as the default value) for any
164   // reason (e.g. command line or field trial).
165   bool IsFeatureOverridden(const std::string& feature_name) const;
166 
167   // Returns true if the state of |feature_name| has been overridden via
168   // |InitializeFromCommandLine()|. This includes features explicitly
169   // disabled/enabled with --disable-features and --enable-features, as well as
170   // any extra feature overrides that depend on command line switches.
171   bool IsFeatureOverriddenFromCommandLine(
172       const std::string& feature_name) const;
173 
174   // Returns true if the state |feature_name| has been overridden by
175   // |InitializeFromCommandLine()| and the state matches |state|.
176   bool IsFeatureOverriddenFromCommandLine(const std::string& feature_name,
177                                           OverrideState state) const;
178 
179   // Associates a field trial for reporting purposes corresponding to the
180   // command-line setting the feature state to |for_overridden_state|. The trial
181   // will be activated when the state of the feature is first queried. This
182   // should be called during registration, after InitializeFromCommandLine() has
183   // been called but before the instance is registered via SetInstance().
184   void AssociateReportingFieldTrial(const std::string& feature_name,
185                                     OverrideState for_overridden_state,
186                                     FieldTrial* field_trial);
187 
188   // Registers a field trial to override the enabled state of the specified
189   // feature to |override_state|. Command-line overrides still take precedence
190   // over field trials, so this will have no effect if the feature is being
191   // overridden from the command-line. The associated field trial will be
192   // activated when the feature state for this feature is queried. This should
193   // be called during registration, after InitializeFromCommandLine() has been
194   // called but before the instance is registered via SetInstance().
195   void RegisterFieldTrialOverride(const std::string& feature_name,
196                                   OverrideState override_state,
197                                   FieldTrial* field_trial);
198 
199   // Adds extra overrides (not associated with a field trial). Should be called
200   // before SetInstance().
201   // The ordering of calls with respect to InitializeFromCommandLine(),
202   // RegisterFieldTrialOverride(), etc. matters. The first call wins out,
203   // because the |overrides_| map uses insert(), which retains the first
204   // inserted entry and does not overwrite it on subsequent calls to insert().
205   void RegisterExtraFeatureOverrides(
206       const std::vector<FeatureOverrideInfo>& extra_overrides);
207 
208   // Loops through feature overrides and serializes them all into |allocator|.
209   void AddFeaturesToAllocator(PersistentMemoryAllocator* allocator);
210 
211   // Returns comma-separated lists of feature names (in the same format that is
212   // accepted by InitializeFromCommandLine()) corresponding to features that
213   // have been overridden - either through command-line or via FieldTrials. For
214   // those features that have an associated FieldTrial, the output entry will be
215   // of the format "FeatureName<TrialName", where "TrialName" is the name of the
216   // FieldTrial. Features that have overrides with OVERRIDE_USE_DEFAULT will be
217   // added to |enable_overrides| with a '*' character prefix. Must be called
218   // only after the instance has been initialized and registered.
219   void GetFeatureOverrides(std::string* enable_overrides,
220                            std::string* disable_overrides);
221 
222   // Like GetFeatureOverrides(), but only returns overrides that were specified
223   // explicitly on the command-line, omitting the ones from field trials.
224   void GetCommandLineFeatureOverrides(std::string* enable_overrides,
225                                       std::string* disable_overrides);
226 
227   // Returns whether the given |feature| is enabled. Must only be called after
228   // the singleton instance has been registered via SetInstance(). Additionally,
229   // a feature with a given name must only have a single corresponding Feature
230   // struct, which is checked in builds with DCHECKs enabled.
231   static bool IsEnabled(const Feature& feature);
232 
233   // Returns the field trial associated with the given |feature|. Must only be
234   // called after the singleton instance has been registered via SetInstance().
235   static FieldTrial* GetFieldTrial(const Feature& feature);
236 
237   // Splits a comma-separated string containing feature names into a vector. The
238   // resulting pieces point to parts of |input|.
239   static std::vector<base::StringPiece> SplitFeatureListString(
240       base::StringPiece input);
241 
242   // Initializes and sets an instance of FeatureList with feature overrides via
243   // command-line flags |enable_features| and |disable_features| if one has not
244   // already been set from command-line flags. Returns true if an instance did
245   // not previously exist. See InitializeFromCommandLine() for more details
246   // about |enable_features| and |disable_features| parameters.
247   static bool InitializeInstance(const std::string& enable_features,
248                                  const std::string& disable_features);
249 
250   // Like the above, but also adds extra overrides. If a feature appears in
251   // |extra_overrides| and also |enable_features| or |disable_features|, the
252   // disable/enable will supersede the extra overrides.
253   static bool InitializeInstance(
254       const std::string& enable_features,
255       const std::string& disable_features,
256       const std::vector<FeatureOverrideInfo>& extra_overrides);
257 
258   // Returns the singleton instance of FeatureList. Will return null until an
259   // instance is registered via SetInstance().
260   static FeatureList* GetInstance();
261 
262   // Registers the given |instance| to be the singleton feature list for this
263   // process. This should only be called once and |instance| must not be null.
264   // Note: If you are considering using this for the purposes of testing, take
265   // a look at using base/test/scoped_feature_list.h instead.
266   static void SetInstance(std::unique_ptr<FeatureList> instance);
267 
268   // Clears the previously-registered singleton instance for tests and returns
269   // the old instance.
270   // Note: Most tests should never call this directly. Instead consider using
271   // base::test::ScopedFeatureList.
272   static std::unique_ptr<FeatureList> ClearInstanceForTesting();
273 
274   // Sets a given (initialized) |instance| to be the singleton feature list,
275   // for testing. Existing instance must be null. This is primarily intended
276   // to support base::test::ScopedFeatureList helper class.
277   static void RestoreInstanceForTesting(std::unique_ptr<FeatureList> instance);
278 
279  private:
280   FRIEND_TEST_ALL_PREFIXES(FeatureListTest, CheckFeatureIdentity);
281   FRIEND_TEST_ALL_PREFIXES(FeatureListTest,
282                            StoreAndRetrieveFeaturesFromSharedMemory);
283   FRIEND_TEST_ALL_PREFIXES(FeatureListTest,
284                            StoreAndRetrieveAssociatedFeaturesFromSharedMemory);
285 
286   struct OverrideEntry {
287     // The overridden enable (on/off) state of the feature.
288     const OverrideState overridden_state;
289 
290     // An optional associated field trial, which will be activated when the
291     // state of the feature is queried for the first time. Weak pointer to the
292     // FieldTrial object that is owned by the FieldTrialList singleton.
293     base::FieldTrial* field_trial;
294 
295     // Specifies whether the feature's state is overridden by |field_trial|.
296     // If it's not, and |field_trial| is not null, it means it is simply an
297     // associated field trial for reporting purposes (and |overridden_state|
298     // came from the command-line).
299     const bool overridden_by_field_trial;
300 
301     // TODO(asvitkine): Expand this as more support is added.
302 
303     // Constructs an OverrideEntry for the given |overridden_state|. If
304     // |field_trial| is not null, it implies that |overridden_state| comes from
305     // the trial, so |overridden_by_field_trial| will be set to true.
306     OverrideEntry(OverrideState overridden_state, FieldTrial* field_trial);
307   };
308 
309   // Finalizes the initialization state of the FeatureList, so that no further
310   // overrides can be registered. This is called by SetInstance() on the
311   // singleton feature list that is being registered.
312   void FinalizeInitialization();
313 
314   // Returns whether the given |feature| is enabled. This is invoked by the
315   // public FeatureList::IsEnabled() static function on the global singleton.
316   // Requires the FeatureList to have already been fully initialized.
317   bool IsFeatureEnabled(const Feature& feature);
318 
319   // Returns the field trial associated with the given |feature|. This is
320   // invoked by the public FeatureList::GetFieldTrial() static function on the
321   // global singleton. Requires the FeatureList to have already been fully
322   // initialized.
323   base::FieldTrial* GetAssociatedFieldTrial(const Feature& feature);
324 
325   // For each feature name in comma-separated list of strings |feature_list|,
326   // registers an override with the specified |overridden_state|. Also, will
327   // associate an optional named field trial if the entry is of the format
328   // "FeatureName<TrialName".
329   void RegisterOverridesFromCommandLine(const std::string& feature_list,
330                                         OverrideState overridden_state);
331 
332   // Registers an override for feature |feature_name|. The override specifies
333   // whether the feature should be on or off (via |overridden_state|), which
334   // will take precedence over the feature's default state. If |field_trial| is
335   // not null, registers the specified field trial object to be associated with
336   // the feature, which will activate the field trial when the feature state is
337   // queried. If an override is already registered for the given feature, it
338   // will not be changed.
339   void RegisterOverride(StringPiece feature_name,
340                         OverrideState overridden_state,
341                         FieldTrial* field_trial);
342 
343   // Implementation of GetFeatureOverrides() with a parameter that specifies
344   // whether only command-line enabled overrides should be emitted. See that
345   // function's comments for more details.
346   void GetFeatureOverridesImpl(std::string* enable_overrides,
347                                std::string* disable_overrides,
348                                bool command_line_only);
349 
350   // Verifies that there's only a single definition of a Feature struct for a
351   // given feature name. Keeps track of the first seen Feature struct for each
352   // feature. Returns false when called on a Feature struct with a different
353   // address than the first one it saw for that feature name. Used only from
354   // DCHECKs and tests.
355   bool CheckFeatureIdentity(const Feature& feature);
356 
357   // Map from feature name to an OverrideEntry struct for the feature, if it
358   // exists.
359   std::map<std::string, OverrideEntry, std::less<>> overrides_;
360 
361   // Locked map that keeps track of seen features, to ensure a single feature is
362   // only defined once. This verification is only done in builds with DCHECKs
363   // enabled.
364   Lock feature_identity_tracker_lock_;
365   std::map<std::string, const Feature*> feature_identity_tracker_
366       GUARDED_BY(feature_identity_tracker_lock_);
367 
368   // Tracks the associated FieldTrialList for DCHECKs. This is used to catch
369   // the scenario where multiple FieldTrialList are used with the same
370   // FeatureList - which can lead to overrides pointing to invalid FieldTrial
371   // objects.
372   base::FieldTrialList* field_trial_list_ = nullptr;
373 
374   // Whether this object has been fully initialized. This gets set to true as a
375   // result of FinalizeInitialization().
376   bool initialized_ = false;
377 
378   // Whether this object has been initialized from command line.
379   bool initialized_from_command_line_ = false;
380 };
381 
382 }  // namespace base
383 
384 #endif  // BASE_FEATURE_LIST_H_
385