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