feature_list.h 18 KB

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