1 // Copyright 2015 The Chromium Authors 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 <atomic> 9 #include <functional> 10 #include <map> 11 #include <memory> 12 #include <string> 13 #include <utility> 14 #include <vector> 15 16 #include "base/base_export.h" 17 #include "base/compiler_specific.h" 18 #include "base/containers/flat_map.h" 19 #include "base/dcheck_is_on.h" 20 #include "base/feature_list_buildflags.h" 21 #include "base/gtest_prod_util.h" 22 #include "base/logging.h" 23 #include "base/memory/raw_ptr.h" 24 #include "base/strings/string_piece.h" 25 #include "base/synchronization/lock.h" 26 #include "build/build_config.h" 27 #include "third_party/abseil-cpp/absl/types/optional.h" 28 29 namespace base { 30 31 class FieldTrial; 32 class FieldTrialList; 33 class PersistentMemoryAllocator; 34 35 // Specifies whether a given feature is enabled or disabled by default. 36 // NOTE: The actual runtime state may be different, due to a field trial or a 37 // command line switch. 38 enum FeatureState { 39 FEATURE_DISABLED_BY_DEFAULT, 40 FEATURE_ENABLED_BY_DEFAULT, 41 }; 42 43 // Recommended macros for declaring and defining features: 44 // 45 // - `kFeature` is the C++ identifier that will be used for the `base::Feature`. 46 // - `name` is the feature name, which must be globally unique. This name is 47 // used to enable/disable features via experiments and command-line flags. 48 // Names should use CamelCase-style naming, e.g. "MyGreatFeature". 49 // - `default_state` is the default state to use for the feature, i.e. 50 // `base::FEATURE_DISABLED_BY_DEFAULT` or `base::FEATURE_ENABLED_BY_DEFAULT`. 51 // As noted above, the actual runtime state may differ from the default state, 52 // due to field trials or command-line switches. 53 54 // Provides a forward declaration for `kFeature` in a header file, e.g. 55 // 56 // BASE_DECLARE_FEATURE(kMyFeature); 57 // 58 // If the feature needs to be marked as exported, i.e. it is referenced by 59 // multiple components, then write: 60 // 61 // COMPONENT_EXPORT(MY_COMPONENT) BASE_DECLARE_FEATURE(kMyFeature); 62 #define BASE_DECLARE_FEATURE(kFeature) \ 63 extern CONSTINIT const base::Feature kFeature 64 65 // Provides a definition for `kFeature` with `name` and `default_state`, e.g. 66 // 67 // BASE_FEATURE(kMyFeature, "MyFeature", base::FEATURE_DISABLED_BY_DEFAULT); 68 // 69 // Features should *not* be defined in header files; do not use this macro in 70 // header files. 71 #define BASE_FEATURE(feature, name, default_state) \ 72 CONSTINIT const base::Feature feature(name, default_state) 73 74 // The Feature struct is used to define the default state for a feature. There 75 // must only ever be one struct instance for a given feature name—generally 76 // defined as a constant global variable or file static. Declare and define 77 // features using the `BASE_DECLARE_FEATURE()` and `BASE_FEATURE()` macros 78 // above, as there are some subtleties involved. 79 // 80 // Feature constants are internally mutable, as this allows them to contain a 81 // mutable member to cache their override state, while still remaining declared 82 // as const. This cache member allows for significantly faster IsEnabled() 83 // checks. 84 // 85 // However, the "Mutable Constants" check [1] detects this as a regression, 86 // because this usually means that a readonly symbol is put in writable memory 87 // when readonly memory would be more efficient. 88 // 89 // The performance gains of the cache are large enough to offset the downsides 90 // to having the symbols in bssdata rather than rodata. Use LOGICALLY_CONST to 91 // suppress the "Mutable Constants" check. 92 // 93 // [1]: 94 // https://crsrc.org/c/docs/speed/binary_size/android_binary_size_trybot.md#Mutable-Constants 95 struct BASE_EXPORT LOGICALLY_CONST Feature { FeatureFeature96 constexpr Feature(const char* name, FeatureState default_state) 97 : name(name), default_state(default_state) { 98 #if BUILDFLAG(ENABLE_BANNED_BASE_FEATURE_PREFIX) 99 if (StringPiece(name).find(BUILDFLAG(BANNED_BASE_FEATURE_PREFIX)) == 0) { 100 LOG(FATAL) << "Invalid feature name " << name << " starts with " 101 << BUILDFLAG(BANNED_BASE_FEATURE_PREFIX); 102 } 103 #endif // BUILDFLAG(ENABLE_BANNED_BASE_FEATURE_PREFIX) 104 } 105 106 // Non-copyable since: 107 // - there should be only one `Feature` instance per unique name. 108 // - a `Feature` contains internal cached state about the override state. 109 Feature(const Feature&) = delete; 110 Feature& operator=(const Feature&) = delete; 111 112 // The name of the feature. This should be unique to each feature and is used 113 // for enabling/disabling features via command line flags and experiments. 114 // It is strongly recommended to use CamelCase style for feature names, e.g. 115 // "MyGreatFeature". 116 const char* const name; 117 118 // The default state (i.e. enabled or disabled) for this feature. 119 // NOTE: The actual runtime state may be different, due to a field trial or a 120 // command line switch. 121 const FeatureState default_state; 122 123 private: 124 friend class FeatureList; 125 126 // A packed value where the first 8 bits represent the `OverrideState` of this 127 // feature, and the last 16 bits are a caching context ID used to allow 128 // ScopedFeatureLists to invalidate these cached values in testing. A value of 129 // 0 in the caching context ID field indicates that this value has never been 130 // looked up and cached, a value of 1 indicates this value contains the cached 131 // `OverrideState` that was looked up via `base::FeatureList`, and any other 132 // value indicate that this cached value is only valid for a particular 133 // ScopedFeatureList instance. 134 // 135 // Packing these values into a uint32_t makes it so that atomic operations 136 // performed on this fields can be lock free. 137 // 138 // The override state stored in this field is only used if the current 139 // `FeatureList::caching_context_` field is equal to the lower 16 bits of the 140 // packed cached value. Otherwise, the override state is looked up in the 141 // feature list and the cache is updated. 142 mutable std::atomic<uint32_t> cached_value = 0; 143 }; 144 145 #if BUILDFLAG(DCHECK_IS_CONFIGURABLE) 146 // DCHECKs have been built-in, and are configurable at run-time to be fatal, or 147 // not, via a DcheckIsFatal feature. We define the Feature here since it is 148 // checked in FeatureList::SetInstance(). See https://crbug.com/596231. 149 BASE_EXPORT BASE_DECLARE_FEATURE(kDCheckIsFatalFeature); 150 #endif // BUILDFLAG(DCHECK_IS_CONFIGURABLE) 151 152 // The FeatureList class is used to determine whether a given feature is on or 153 // off. It provides an authoritative answer, taking into account command-line 154 // overrides and experimental control. 155 // 156 // The basic use case is for any feature that can be toggled (e.g. through 157 // command-line or an experiment) to have a defined Feature struct, e.g.: 158 // 159 // const base::Feature kMyGreatFeature { 160 // "MyGreatFeature", base::FEATURE_ENABLED_BY_DEFAULT 161 // }; 162 // 163 // Then, client code that wishes to query the state of the feature would check: 164 // 165 // if (base::FeatureList::IsEnabled(kMyGreatFeature)) { 166 // // Feature code goes here. 167 // } 168 // 169 // Behind the scenes, the above call would take into account any command-line 170 // flags to enable or disable the feature, any experiments that may control it 171 // and finally its default state (in that order of priority), to determine 172 // whether the feature is on. 173 // 174 // Features can be explicitly forced on or off by specifying a list of comma- 175 // separated feature names via the following command-line flags: 176 // 177 // --enable-features=Feature5,Feature7 178 // --disable-features=Feature1,Feature2,Feature3 179 // 180 // To enable/disable features in a test, do NOT append --enable-features or 181 // --disable-features to the command-line directly. Instead, use 182 // ScopedFeatureList. See base/test/scoped_feature_list.h for details. 183 // 184 // After initialization (which should be done single-threaded), the FeatureList 185 // API is thread safe. 186 // 187 // Note: This class is a singleton, but does not use base/memory/singleton.h in 188 // order to have control over its initialization sequence. Specifically, the 189 // intended use is to create an instance of this class and fully initialize it, 190 // before setting it as the singleton for a process, via SetInstance(). 191 class BASE_EXPORT FeatureList { 192 public: 193 FeatureList(); 194 FeatureList(const FeatureList&) = delete; 195 FeatureList& operator=(const FeatureList&) = delete; 196 ~FeatureList(); 197 198 // Used by common test fixture classes to prevent abuse of ScopedFeatureList 199 // after multiple threads have started. 200 class BASE_EXPORT ScopedDisallowOverrides { 201 public: 202 explicit ScopedDisallowOverrides(const char* reason); 203 ScopedDisallowOverrides(const ScopedDisallowOverrides&) = delete; 204 ScopedDisallowOverrides& operator=(const ScopedDisallowOverrides&) = delete; 205 ~ScopedDisallowOverrides(); 206 207 private: 208 #if DCHECK_IS_ON() 209 const char* const previous_reason_; 210 #endif 211 }; 212 213 // Specifies whether a feature override enables or disables the feature. 214 enum OverrideState { 215 OVERRIDE_USE_DEFAULT, 216 OVERRIDE_DISABLE_FEATURE, 217 OVERRIDE_ENABLE_FEATURE, 218 }; 219 220 // Accessor class, used to look up features by _name_ rather than by Feature 221 // object. 222 // Should only be used in limited cases. See ConstructAccessor() for details. 223 class BASE_EXPORT Accessor { 224 public: 225 Accessor(const Accessor&) = delete; 226 Accessor& operator=(const Accessor&) = delete; 227 228 // Looks up the feature, returning only its override state, rather than 229 // falling back on a default value (since there is no default value given). 230 // Callers of this MUST ensure that there is a consistent, compile-time 231 // default value associated. 232 FeatureList::OverrideState GetOverrideStateByFeatureName( 233 StringPiece feature_name); 234 235 // Look up the feature, and, if present, populate |params|. 236 // See GetFieldTrialParams in field_trial_params.h for more documentation. 237 bool GetParamsByFeatureName(StringPiece feature_name, 238 std::map<std::string, std::string>* params); 239 240 private: 241 // Allow FeatureList to construct this class. 242 friend class FeatureList; 243 244 explicit Accessor(FeatureList* feature_list); 245 246 // Unowned pointer to the FeatureList object we use to look up feature 247 // enablement. 248 raw_ptr<FeatureList> feature_list_; 249 }; 250 251 // Describes a feature override. The first member is a Feature that will be 252 // overridden with the state given by the second member. 253 using FeatureOverrideInfo = 254 std::pair<const std::reference_wrapper<const Feature>, OverrideState>; 255 256 // Initializes feature overrides via command-line flags `--enable-features=` 257 // and `--disable-features=`, each of which is a comma-separated list of 258 // features to enable or disable, respectively. This function also allows 259 // users to set a feature's field trial params via `--enable-features=`. Must 260 // only be invoked during the initialization phase (before 261 // FinalizeInitialization() has been called). 262 // 263 // If a feature appears on both lists, then it will be disabled. If 264 // a list entry has the format "FeatureName<TrialName" then this 265 // initialization will also associate the feature state override with the 266 // named field trial, if it exists. If a list entry has the format 267 // "FeatureName:k1/v1/k2/v2", "FeatureName<TrialName:k1/v1/k2/v2" or 268 // "FeatureName<TrialName.GroupName:k1/v1/k2/v2" then this initialization will 269 // also associate the feature state override with the named field trial and 270 // its params. If the feature params part is provided but trial and/or group 271 // isn't, this initialization will also create a synthetic trial, named 272 // "Study" followed by the feature name, i.e. "StudyFeature", and group, named 273 // "Group" followed by the feature name, i.e. "GroupFeature", for the params. 274 // If a feature name is prefixed with the '*' character, it will be created 275 // with OVERRIDE_USE_DEFAULT - which is useful for associating with a trial 276 // while using the default state. 277 void InitializeFromCommandLine(const std::string& enable_features, 278 const std::string& disable_features); 279 280 // Initializes feature overrides through the field trial allocator, which 281 // we're using to store the feature names, their override state, and the name 282 // of the associated field trial. 283 void InitializeFromSharedMemory(PersistentMemoryAllocator* allocator); 284 285 // Returns true if the state of |feature_name| has been overridden (regardless 286 // of whether the overridden value is the same as the default value) for any 287 // reason (e.g. command line or field trial). 288 bool IsFeatureOverridden(const std::string& feature_name) const; 289 290 // Returns true if the state of |feature_name| has been overridden via 291 // |InitializeFromCommandLine()|. This includes features explicitly 292 // disabled/enabled with --disable-features and --enable-features, as well as 293 // any extra feature overrides that depend on command line switches. 294 bool IsFeatureOverriddenFromCommandLine( 295 const std::string& feature_name) const; 296 297 // Returns true if the state |feature_name| has been overridden by 298 // |InitializeFromCommandLine()| and the state matches |state|. 299 bool IsFeatureOverriddenFromCommandLine(const std::string& feature_name, 300 OverrideState state) const; 301 302 // Associates a field trial for reporting purposes corresponding to the 303 // command-line setting the feature state to |for_overridden_state|. The trial 304 // will be activated when the state of the feature is first queried. This 305 // should be called during registration, after InitializeFromCommandLine() has 306 // been called but before the instance is registered via SetInstance(). 307 void AssociateReportingFieldTrial(const std::string& feature_name, 308 OverrideState for_overridden_state, 309 FieldTrial* field_trial); 310 311 // Registers a field trial to override the enabled state of the specified 312 // feature to |override_state|. Command-line overrides still take precedence 313 // over field trials, so this will have no effect if the feature is being 314 // overridden from the command-line. The associated field trial will be 315 // activated when the feature state for this feature is queried. This should 316 // be called during registration, after InitializeFromCommandLine() has been 317 // called but before the instance is registered via SetInstance(). 318 void RegisterFieldTrialOverride(const std::string& feature_name, 319 OverrideState override_state, 320 FieldTrial* field_trial); 321 322 // Adds extra overrides (not associated with a field trial). Should be called 323 // before SetInstance(). 324 // The ordering of calls with respect to InitializeFromCommandLine(), 325 // RegisterFieldTrialOverride(), etc. matters. The first call wins out, 326 // because the |overrides_| map uses insert(), which retains the first 327 // inserted entry and does not overwrite it on subsequent calls to insert(). 328 void RegisterExtraFeatureOverrides( 329 const std::vector<FeatureOverrideInfo>& extra_overrides); 330 331 // Loops through feature overrides and serializes them all into |allocator|. 332 void AddFeaturesToAllocator(PersistentMemoryAllocator* allocator); 333 334 // Returns comma-separated lists of feature names (in the same format that is 335 // accepted by InitializeFromCommandLine()) corresponding to features that 336 // have been overridden - either through command-line or via FieldTrials. For 337 // those features that have an associated FieldTrial, the output entry will be 338 // of the format "FeatureName<TrialName" (|include_group_name|=false) or 339 // "FeatureName<TrialName.GroupName" (if |include_group_name|=true), where 340 // "TrialName" is the name of the FieldTrial and "GroupName" is the group 341 // name of the FieldTrial. Features that have overrides with 342 // OVERRIDE_USE_DEFAULT will be added to |enable_overrides| with a '*' 343 // character prefix. Must be called only after the instance has been 344 // initialized and registered. 345 void GetFeatureOverrides(std::string* enable_overrides, 346 std::string* disable_overrides, 347 bool include_group_names = false) const; 348 349 // Like GetFeatureOverrides(), but only returns overrides that were specified 350 // explicitly on the command-line, omitting the ones from field trials. 351 void GetCommandLineFeatureOverrides(std::string* enable_overrides, 352 std::string* disable_overrides) const; 353 354 // Returns the field trial associated with the given feature |name|. Used for 355 // getting the FieldTrial without requiring a struct Feature. 356 base::FieldTrial* GetAssociatedFieldTrialByFeatureName( 357 StringPiece name) const; 358 359 // DO NOT USE outside of internal field trial implementation code. Instead use 360 // GetAssociatedFieldTrialByFeatureName(), which performs some additional 361 // validation. 362 // 363 // Returns whether the given feature |name| is associated with a field trial. 364 // If the given feature |name| does not exist, return false. Unlike 365 // GetAssociatedFieldTrialByFeatureName(), this function must be called during 366 // |FeatureList| initialization; the returned value will report whether the 367 // provided |name| has been used so far. 368 bool HasAssociatedFieldTrialByFeatureName(StringPiece name) const; 369 370 // Get associated field trial for the given feature |name| only if override 371 // enables it. 372 FieldTrial* GetEnabledFieldTrialByFeatureName(StringPiece name) const; 373 374 // Construct an accessor allowing access to GetOverrideStateByFeatureName(). 375 // This can only be called before the FeatureList is initialized, and is 376 // intended for very narrow use. 377 // If you're tempted to use it, do so only in consultation with feature_list 378 // OWNERS. 379 std::unique_ptr<Accessor> ConstructAccessor(); 380 381 // Returns whether the given `feature` is enabled. 382 // 383 // If no `FeatureList` instance is registered, this will: 384 // - DCHECK(), if FailOnFeatureAccessWithoutFeatureList() was called. 385 // TODO(crbug.com/1358639): Change the DCHECK to a CHECK when we're 386 // confident that all early accesses have been fixed. We don't want to 387 // get many crash reports from the field in the meantime. 388 // - Return the default state, otherwise. Registering a `FeatureList` later 389 // will fail. 390 // 391 // TODO(crbug.com/1358639): Make early FeatureList access fail on iOS, Android 392 // and ChromeOS. This currently only works on Windows, Mac and Linux. 393 // 394 // A feature with a given name must only have a single corresponding Feature 395 // instance, which is checked in builds with DCHECKs enabled. 396 static bool IsEnabled(const Feature& feature); 397 398 // Some characters are not allowed to appear in feature names or the 399 // associated field trial names, as they are used as special characters for 400 // command-line serialization. This function checks that the strings are ASCII 401 // (since they are used in command-line API functions that require ASCII) and 402 // whether there are any reserved characters present, returning true if the 403 // string is valid. 404 static bool IsValidFeatureOrFieldTrialName(StringPiece name); 405 406 // If the given |feature| is overridden, returns its enabled state; otherwise, 407 // returns an empty optional. Must only be called after the singleton instance 408 // has been registered via SetInstance(). Additionally, a feature with a given 409 // name must only have a single corresponding Feature struct, which is checked 410 // in builds with DCHECKs enabled. 411 static absl::optional<bool> GetStateIfOverridden(const Feature& feature); 412 413 // Returns the field trial associated with the given |feature|. Must only be 414 // called after the singleton instance has been registered via SetInstance(). 415 static FieldTrial* GetFieldTrial(const Feature& feature); 416 417 // Splits a comma-separated string containing feature names into a vector. The 418 // resulting pieces point to parts of |input|. 419 static std::vector<base::StringPiece> SplitFeatureListString( 420 base::StringPiece input); 421 422 // Checks and parses the |enable_feature| (e.g. 423 // FeatureName<Study.Group:Param1/value1/) obtained by applying 424 // SplitFeatureListString() to the |enable_features| flag, and sets 425 // |feature_name| to be the feature's name, |study_name| and |group_name| to 426 // be the field trial name and its group name if the field trial is specified 427 // or field trial parameters are given, |params| to be the field trial 428 // parameters if exists. 429 static bool ParseEnableFeatureString(StringPiece enable_feature, 430 std::string* feature_name, 431 std::string* study_name, 432 std::string* group_name, 433 std::string* params); 434 435 // Initializes and sets an instance of FeatureList with feature overrides via 436 // command-line flags |enable_features| and |disable_features| if one has not 437 // already been set from command-line flags. Returns true if an instance did 438 // not previously exist. See InitializeFromCommandLine() for more details 439 // about |enable_features| and |disable_features| parameters. 440 static bool InitializeInstance(const std::string& enable_features, 441 const std::string& disable_features); 442 443 // Like the above, but also adds extra overrides. If a feature appears in 444 // |extra_overrides| and also |enable_features| or |disable_features|, the 445 // disable/enable will supersede the extra overrides. 446 static bool InitializeInstance( 447 const std::string& enable_features, 448 const std::string& disable_features, 449 const std::vector<FeatureOverrideInfo>& extra_overrides); 450 451 // Returns the singleton instance of FeatureList. Will return null until an 452 // instance is registered via SetInstance(). 453 static FeatureList* GetInstance(); 454 455 // Registers the given |instance| to be the singleton feature list for this 456 // process. This should only be called once and |instance| must not be null. 457 // Note: If you are considering using this for the purposes of testing, take 458 // a look at using base/test/scoped_feature_list.h instead. 459 static void SetInstance(std::unique_ptr<FeatureList> instance); 460 461 // Clears the previously-registered singleton instance for tests and returns 462 // the old instance. 463 // Note: Most tests should never call this directly. Instead consider using 464 // base::test::ScopedFeatureList. 465 static std::unique_ptr<FeatureList> ClearInstanceForTesting(); 466 467 // Sets a given (initialized) |instance| to be the singleton feature list, 468 // for testing. Existing instance must be null. This is primarily intended 469 // to support base::test::ScopedFeatureList helper class. 470 static void RestoreInstanceForTesting(std::unique_ptr<FeatureList> instance); 471 472 // After calling this, an attempt to access feature state when no FeatureList 473 // is registered will DCHECK. 474 // 475 // TODO(crbug.com/1358639): Change the DCHECK to a CHECK when we're confident 476 // that all early accesses have been fixed. We don't want to get many crash 477 // reports from the field in the meantime. 478 // 479 // Note: This isn't the default behavior because accesses are tolerated in 480 // processes that never register a FeatureList. 481 static void FailOnFeatureAccessWithoutFeatureList(); 482 483 void SetCachingContextForTesting(uint16_t caching_context); 484 485 private: 486 FRIEND_TEST_ALL_PREFIXES(FeatureListTest, CheckFeatureIdentity); 487 FRIEND_TEST_ALL_PREFIXES(FeatureListTest, 488 StoreAndRetrieveFeaturesFromSharedMemory); 489 FRIEND_TEST_ALL_PREFIXES(FeatureListTest, 490 StoreAndRetrieveAssociatedFeaturesFromSharedMemory); 491 // Allow Accessor to access GetOverrideStateByFeatureName(). 492 friend class Accessor; 493 494 struct OverrideEntry { 495 // The overridden enable (on/off) state of the feature. 496 OverrideState overridden_state; 497 498 // An optional associated field trial, which will be activated when the 499 // state of the feature is queried for the first time. Weak pointer to the 500 // FieldTrial object that is owned by the FieldTrialList singleton. 501 raw_ptr<base::FieldTrial> field_trial; 502 503 // Specifies whether the feature's state is overridden by |field_trial|. 504 // If it's not, and |field_trial| is not null, it means it is simply an 505 // associated field trial for reporting purposes (and |overridden_state| 506 // came from the command-line). 507 bool overridden_by_field_trial; 508 509 // TODO(asvitkine): Expand this as more support is added. 510 511 // Constructs an OverrideEntry for the given |overridden_state|. If 512 // |field_trial| is not null, it implies that |overridden_state| comes from 513 // the trial, so |overridden_by_field_trial| will be set to true. 514 OverrideEntry(OverrideState overridden_state, FieldTrial* field_trial); 515 }; 516 517 // Returns the override for the field trial associated with the given feature 518 // |name| or null if the feature is not found. 519 const base::FeatureList::OverrideEntry* GetOverrideEntryByFeatureName( 520 StringPiece name) const; 521 522 // Finalizes the initialization state of the FeatureList, so that no further 523 // overrides can be registered. This is called by SetInstance() on the 524 // singleton feature list that is being registered. 525 void FinalizeInitialization(); 526 527 // Returns whether the given |feature| is enabled. This is invoked by the 528 // public FeatureList::IsEnabled() static function on the global singleton. 529 // Requires the FeatureList to have already been fully initialized. 530 bool IsFeatureEnabled(const Feature& feature) const; 531 532 // Returns whether the given |feature| is enabled. This is invoked by the 533 // public FeatureList::GetStateIfOverridden() static function on the global 534 // singleton. Requires the FeatureList to have already been fully initialized. 535 absl::optional<bool> IsFeatureEnabledIfOverridden( 536 const Feature& feature) const; 537 538 // Returns the override state of a given |feature|. If the feature was not 539 // overridden, returns OVERRIDE_USE_DEFAULT. Performs any necessary callbacks 540 // for when the feature state has been observed, e.g. activating field trials. 541 OverrideState GetOverrideState(const Feature& feature) const; 542 543 // Same as GetOverrideState(), but without a default value. 544 OverrideState GetOverrideStateByFeatureName(StringPiece feature_name) const; 545 546 // Returns the field trial associated with the given |feature|. This is 547 // invoked by the public FeatureList::GetFieldTrial() static function on the 548 // global singleton. Requires the FeatureList to have already been fully 549 // initialized. 550 base::FieldTrial* GetAssociatedFieldTrial(const Feature& feature) const; 551 552 // For each feature name in comma-separated list of strings |feature_list|, 553 // registers an override with the specified |overridden_state|. Also, will 554 // associate an optional named field trial if the entry is of the format 555 // "FeatureName<TrialName". 556 void RegisterOverridesFromCommandLine(const std::string& feature_list, 557 OverrideState overridden_state); 558 559 // Registers an override for feature |feature_name|. The override specifies 560 // whether the feature should be on or off (via |overridden_state|), which 561 // will take precedence over the feature's default state. If |field_trial| is 562 // not null, registers the specified field trial object to be associated with 563 // the feature, which will activate the field trial when the feature state is 564 // queried. If an override is already registered for the given feature, it 565 // will not be changed. 566 void RegisterOverride(StringPiece feature_name, 567 OverrideState overridden_state, 568 FieldTrial* field_trial); 569 570 // Implementation of GetFeatureOverrides() with a parameter that specifies 571 // whether only command-line enabled overrides should be emitted. See that 572 // function's comments for more details. 573 void GetFeatureOverridesImpl(std::string* enable_overrides, 574 std::string* disable_overrides, 575 bool command_line_only, 576 bool include_group_name = false) const; 577 578 // Verifies that there's only a single definition of a Feature struct for a 579 // given feature name. Keeps track of the first seen Feature struct for each 580 // feature. Returns false when called on a Feature struct with a different 581 // address than the first one it saw for that feature name. Used only from 582 // DCHECKs and tests. This is const because it's called from const getters and 583 // doesn't modify externally visible state. 584 bool CheckFeatureIdentity(const Feature& feature) const; 585 586 // Map from feature name to an OverrideEntry struct for the feature, if it 587 // exists. 588 base::flat_map<std::string, OverrideEntry> overrides_; 589 590 // Locked map that keeps track of seen features, to ensure a single feature is 591 // only defined once. This verification is only done in builds with DCHECKs 592 // enabled. This is mutable as it's not externally visible and needs to be 593 // usable from const getters. 594 mutable Lock feature_identity_tracker_lock_; 595 mutable std::map<std::string, const Feature*> feature_identity_tracker_ 596 GUARDED_BY(feature_identity_tracker_lock_); 597 598 // Tracks the associated FieldTrialList for DCHECKs. This is used to catch 599 // the scenario where multiple FieldTrialList are used with the same 600 // FeatureList - which can lead to overrides pointing to invalid FieldTrial 601 // objects. 602 raw_ptr<base::FieldTrialList> field_trial_list_ = nullptr; 603 604 // Whether this object has been fully initialized. This gets set to true as a 605 // result of FinalizeInitialization(). 606 bool initialized_ = false; 607 608 // Whether this object has been initialized from command line. 609 bool initialized_from_command_line_ = false; 610 611 // Used when querying `base::Feature` state to determine if the cached value 612 // in the `Feature` object is populated and valid. See the comment on 613 // `base::Feature::cached_value` for more details. 614 uint16_t caching_context_ = 1; 615 }; 616 617 } // namespace base 618 619 #endif // BASE_FEATURE_LIST_H_ 620