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