feature_list.h 17 KB

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