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