1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 // FieldTrial is a class for handling details of statistical experiments
6 // performed by actual users in the field (i.e., in a shipped or beta product).
7 // All code is called exclusively on the UI thread currently.
8 //
9 // The simplest example is an experiment to see whether one of two options
10 // produces "better" results across our user population.  In that scenario, UMA
11 // data is uploaded to aggregate the test results, and this FieldTrial class
12 // manages the state of each such experiment (state == which option was
13 // pseudo-randomly selected).
14 //
15 // States are typically generated randomly, either based on a one time
16 // randomization (which will yield the same results, in terms of selecting
17 // the client for a field trial or not, for every run of the program on a
18 // given machine), or by a session randomization (generated each time the
19 // application starts up, but held constant during the duration of the
20 // process).
21 
22 //------------------------------------------------------------------------------
23 // Example:  Suppose we have an experiment involving memory, such as determining
24 // the impact of some pruning algorithm.
25 // We assume that we already have a histogram of memory usage, such as:
26 
27 //   UMA_HISTOGRAM_COUNTS_1M("Memory.RendererTotal", count);
28 
29 // Somewhere in main thread initialization code, we'd probably define an
30 // instance of a FieldTrial, with code such as:
31 
32 // // FieldTrials are reference counted, and persist automagically until
33 // // process teardown, courtesy of their automatic registration in
34 // // FieldTrialList.
35 // // Note: This field trial will run in Chrome instances compiled through
36 // //       8 July, 2015, and after that all instances will be in "StandardMem".
37 // scoped_refptr<base::FieldTrial> trial(
38 //     base::FieldTrialList::FactoryGetFieldTrial(
39 //         "MemoryExperiment", 1000, "StandardMem",
40 //         base::FieldTrial::ONE_TIME_RANDOMIZED, nullptr));
41 //
42 // const int high_mem_group =
43 //     trial->AppendGroup("HighMem", 20);  // 2% in HighMem group.
44 // const int low_mem_group =
45 //     trial->AppendGroup("LowMem", 20);   // 2% in LowMem group.
46 // // Take action depending of which group we randomly land in.
47 // if (trial->group() == high_mem_group)
48 //   SetPruningAlgorithm(kType1);  // Sample setting of browser state.
49 // else if (trial->group() == low_mem_group)
50 //   SetPruningAlgorithm(kType2);  // Sample alternate setting.
51 
52 //------------------------------------------------------------------------------
53 
54 #ifndef BASE_METRICS_FIELD_TRIAL_H_
55 #define BASE_METRICS_FIELD_TRIAL_H_
56 
57 #include <stddef.h>
58 #include <stdint.h>
59 
60 #include <map>
61 #include <memory>
62 #include <string>
63 #include <vector>
64 
65 #include "base/atomicops.h"
66 #include "base/base_export.h"
67 #include "base/command_line.h"
68 #include "base/feature_list.h"
69 #include "base/gtest_prod_util.h"
70 #include "base/memory/read_only_shared_memory_region.h"
71 #include "base/memory/ref_counted.h"
72 #include "base/memory/shared_memory_mapping.h"
73 #include "base/metrics/persistent_memory_allocator.h"
74 #include "base/observer_list_threadsafe.h"
75 #include "base/pickle.h"
76 #include "base/process/launch.h"
77 #include "base/strings/string_piece.h"
78 #include "base/synchronization/lock.h"
79 #include "build/build_config.h"
80 
81 #if defined(OS_MAC)
82 #include "base/mac/mach_port_rendezvous.h"
83 #endif
84 
85 namespace base {
86 
87 class FieldTrialList;
88 
89 class BASE_EXPORT FieldTrial : public RefCounted<FieldTrial> {
90  public:
91   typedef int Probability;  // Probability type for being selected in a trial.
92 
93   // Specifies the persistence of the field trial group choice.
94   enum RandomizationType {
95     // One time randomized trials will persist the group choice between
96     // restarts, which is recommended for most trials, especially those that
97     // change user visible behavior.
98     ONE_TIME_RANDOMIZED,
99     // Session randomized trials will roll the dice to select a group on every
100     // process restart.
101     SESSION_RANDOMIZED,
102   };
103 
104   // EntropyProvider is an interface for providing entropy for one-time
105   // randomized (persistent) field trials.
106   class BASE_EXPORT EntropyProvider {
107    public:
108     virtual ~EntropyProvider();
109 
110     // Returns a double in the range of [0, 1) to be used for the dice roll for
111     // the specified field trial. If |randomization_seed| is not 0, it will be
112     // used in preference to |trial_name| for generating the entropy by entropy
113     // providers that support it. A given instance should always return the same
114     // value given the same input |trial_name| and |randomization_seed| values.
115     virtual double GetEntropyForTrial(const std::string& trial_name,
116                                       uint32_t randomization_seed) const = 0;
117   };
118 
119   // A pair representing a Field Trial and its selected group.
120   struct ActiveGroup {
121     std::string trial_name;
122     std::string group_name;
123   };
124 
125   // A triplet representing a FieldTrial, its selected group and whether it's
126   // active. String members are pointers to the underlying strings owned by the
127   // FieldTrial object. Does not use StringPiece to avoid conversions back to
128   // std::string.
129   struct BASE_EXPORT State {
130     const std::string* trial_name = nullptr;
131     const std::string* group_name = nullptr;
132     bool activated = false;
133 
134     State();
135     State(const State& other);
136     ~State();
137   };
138 
139   // We create one FieldTrialEntry per field trial in shared memory, via
140   // AddToAllocatorWhileLocked. The FieldTrialEntry is followed by a
141   // base::Pickle object that we unpickle and read from.
142   struct BASE_EXPORT FieldTrialEntry {
143     // SHA1(FieldTrialEntry): Increment this if structure changes!
144     static constexpr uint32_t kPersistentTypeId = 0xABA17E13 + 2;
145 
146     // Expected size for 32/64-bit check.
147     static constexpr size_t kExpectedInstanceSize = 8;
148 
149     // Whether or not this field trial is activated. This is really just a
150     // boolean but using a 32 bit value for portability reasons. It should be
151     // accessed via NoBarrier_Load()/NoBarrier_Store() to prevent the compiler
152     // from doing unexpected optimizations because it thinks that only one
153     // thread is accessing the memory location.
154     subtle::Atomic32 activated;
155 
156     // Size of the pickled structure, NOT the total size of this entry.
157     uint32_t pickle_size;
158 
159     // Calling this is only valid when the entry is initialized. That is, it
160     // resides in shared memory and has a pickle containing the trial name and
161     // group name following it.
162     bool GetTrialAndGroupName(StringPiece* trial_name,
163                               StringPiece* group_name) const;
164 
165     // Calling this is only valid when the entry is initialized as well. Reads
166     // the parameters following the trial and group name and stores them as
167     // key-value mappings in |params|.
168     bool GetParams(std::map<std::string, std::string>* params) const;
169 
170    private:
171     // Returns an iterator over the data containing names and params.
172     PickleIterator GetPickleIterator() const;
173 
174     // Takes the iterator and writes out the first two items into |trial_name|
175     // and |group_name|.
176     bool ReadStringPair(PickleIterator* iter,
177                         StringPiece* trial_name,
178                         StringPiece* group_name) const;
179   };
180 
181   typedef std::vector<ActiveGroup> ActiveGroups;
182 
183   // A return value to indicate that a given instance has not yet had a group
184   // assignment (and hence is not yet participating in the trial).
185   static const int kNotFinalized;
186 
187   FieldTrial(const FieldTrial&) = delete;
188   FieldTrial& operator=(const FieldTrial&) = delete;
189 
190   // Disables this trial, meaning it always determines the default group
191   // has been selected. May be called immediately after construction, or
192   // at any time after initialization (should not be interleaved with
193   // AppendGroup calls). Once disabled, there is no way to re-enable a
194   // trial.
195   // TODO(mad): http://code.google.com/p/chromium/issues/detail?id=121446
196   // This doesn't properly reset to Default when a group was forced.
197   void Disable();
198 
199   // Establish the name and probability of the next group in this trial.
200   // Sometimes, based on construction randomization, this call may cause the
201   // provided group to be *THE* group selected for use in this instance.
202   // The return value is the group number of the new group.
203   int AppendGroup(const std::string& name, Probability group_probability);
204 
205   // Return the name of the FieldTrial (excluding the group name).
trial_name()206   const std::string& trial_name() const { return trial_name_; }
207 
208   // Return the randomly selected group number that was assigned, and notify
209   // any/all observers that this finalized group number has presumably been used
210   // (queried), and will never change. Note that this will force an instance to
211   // participate, and make it illegal to attempt to probabilistically add any
212   // other groups to the trial.
213   int group();
214 
215   // If the group's name is empty, a string version containing the group number
216   // is used as the group name. This causes a winner to be chosen if none was.
217   const std::string& group_name();
218 
219   // Finalizes the group choice and returns the chosen group, but does not mark
220   // the trial as active - so its state will not be reported until group_name()
221   // or similar is called.
222   const std::string& GetGroupNameWithoutActivation();
223 
224   // Set the field trial as forced, meaning that it was setup earlier than
225   // the hard coded registration of the field trial to override it.
226   // This allows the code that was hard coded to register the field trial to
227   // still succeed even though the field trial has already been registered.
228   // This must be called after appending all the groups, since we will make
229   // the group choice here. Note that this is a NOOP for already forced trials.
230   // And, as the rest of the FieldTrial code, this is not thread safe and must
231   // be done from the UI thread.
232   void SetForced();
233 
234   // Enable benchmarking sets field trials to a common setting.
235   static void EnableBenchmarking();
236 
237   // Creates a FieldTrial object with the specified parameters, to be used for
238   // simulation of group assignment without actually affecting global field
239   // trial state in the running process. Group assignment will be done based on
240   // |entropy_value|, which must have a range of [0, 1).
241   //
242   // Note: Using this function will not register the field trial globally in the
243   // running process - for that, use FieldTrialList::FactoryGetFieldTrial().
244   //
245   // The ownership of the returned FieldTrial is transfered to the caller which
246   // is responsible for deref'ing it (e.g. by using scoped_refptr<FieldTrial>).
247   static FieldTrial* CreateSimulatedFieldTrial(
248       const std::string& trial_name,
249       Probability total_probability,
250       const std::string& default_group_name,
251       double entropy_value);
252 
253  private:
254   // Allow tests to access our innards for testing purposes.
255   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, Registration);
256   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, AbsoluteProbabilities);
257   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, RemainingProbability);
258   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, FiftyFiftyProbability);
259   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, MiddleProbabilities);
260   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, OneWinner);
261   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, DisableProbability);
262   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, ActiveGroups);
263   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, AllGroups);
264   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, ActiveGroupsNotFinalized);
265   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, Save);
266   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SaveAll);
267   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, DuplicateRestore);
268   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedTurnFeatureOff);
269   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedTurnFeatureOn);
270   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedChangeDefault_Default);
271   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, SetForcedChangeDefault_NonDefault);
272   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, FloatBoundariesGiveEqualGroupSizes);
273   FRIEND_TEST_ALL_PREFIXES(FieldTrialTest, DoesNotSurpassTotalProbability);
274   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest,
275                            DoNotAddSimulatedFieldTrialsToAllocator);
276   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, ClearParamsFromSharedMemory);
277 
278   friend class base::FieldTrialList;
279 
280   friend class RefCounted<FieldTrial>;
281 
282   using FieldTrialRef = PersistentMemoryAllocator::Reference;
283 
284   // This is the group number of the 'default' group when a choice wasn't forced
285   // by a call to FieldTrialList::CreateFieldTrial. It is kept private so that
286   // consumers don't use it by mistake in cases where the group was forced.
287   static const int kDefaultGroupNumber;
288 
289   // Creates a field trial with the specified parameters. Group assignment will
290   // be done based on |entropy_value|, which must have a range of [0, 1).
291   FieldTrial(const std::string& trial_name,
292              Probability total_probability,
293              const std::string& default_group_name,
294              double entropy_value);
295 
296   virtual ~FieldTrial();
297 
298   // Return the default group name of the FieldTrial.
default_group_name()299   std::string default_group_name() const { return default_group_name_; }
300 
301   // Marks this trial as having been registered with the FieldTrialList. Must be
302   // called no more than once and before any |group()| calls have occurred.
303   void SetTrialRegistered();
304 
305   // Sets the chosen group name and number.
306   void SetGroupChoice(const std::string& group_name, int number);
307 
308   // Ensures that a group is chosen, if it hasn't yet been. The field trial
309   // might yet be disabled, so this call will *not* notify observers of the
310   // status.
311   void FinalizeGroupChoice();
312 
313   // Implements FinalizeGroupChoice() with the added flexibility of being
314   // deadlock-free if |is_locked| is true and the caller is holding a lock.
315   void FinalizeGroupChoiceImpl(bool is_locked);
316 
317   // Returns the trial name and selected group name for this field trial via
318   // the output parameter |active_group|, but only if the group has already
319   // been chosen and has been externally observed via |group()| and the trial
320   // has not been disabled. In that case, true is returned and |active_group|
321   // is filled in; otherwise, the result is false and |active_group| is left
322   // untouched.
323   bool GetActiveGroup(ActiveGroup* active_group) const;
324 
325   // Returns the trial name and selected group name for this field trial via
326   // the output parameter |field_trial_state| for all the studies when
327   // |include_disabled| is true. In case when |include_disabled| is false, if
328   // the trial has not been disabled true is returned and |field_trial_state|
329   // is filled in; otherwise, the result is false and |field_trial_state| is
330   // left untouched.
331   bool GetStateWhileLocked(State* field_trial_state, bool include_disabled);
332 
333   // Returns the group_name. A winner need not have been chosen.
group_name_internal()334   std::string group_name_internal() const { return group_name_; }
335 
336   // The name of the field trial, as can be found via the FieldTrialList.
337   const std::string trial_name_;
338 
339   // The maximum sum of all probabilities supplied, which corresponds to 100%.
340   // This is the scaling factor used to adjust supplied probabilities.
341   const Probability divisor_;
342 
343   // The name of the default group.
344   const std::string default_group_name_;
345 
346   // The randomly selected probability that is used to select a group (or have
347   // the instance not participate).  It is the product of divisor_ and a random
348   // number between [0, 1).
349   Probability random_;
350 
351   // Sum of the probabilities of all appended groups.
352   Probability accumulated_group_probability_;
353 
354   // The number that will be returned by the next AppendGroup() call.
355   int next_group_number_;
356 
357   // The pseudo-randomly assigned group number.
358   // This is kNotFinalized if no group has been assigned.
359   int group_;
360 
361   // A textual name for the randomly selected group. Valid after |group()|
362   // has been called.
363   std::string group_name_;
364 
365   // When enable_field_trial_ is false, field trial reverts to the 'default'
366   // group.
367   bool enable_field_trial_;
368 
369   // When forced_ is true, we return the chosen group from AppendGroup when
370   // appropriate.
371   bool forced_;
372 
373   // Specifies whether the group choice has been reported to observers.
374   bool group_reported_;
375 
376   // Whether this trial is registered with the global FieldTrialList and thus
377   // should notify it when its group is queried.
378   bool trial_registered_;
379 
380   // Reference to related field trial struct and data in shared memory.
381   FieldTrialRef ref_;
382 
383   // When benchmarking is enabled, field trials all revert to the 'default'
384   // group.
385   static bool enable_benchmarking_;
386 };
387 
388 //------------------------------------------------------------------------------
389 // Class with a list of all active field trials.  A trial is active if it has
390 // been registered, which includes evaluating its state based on its probaility.
391 // Only one instance of this class exists and outside of testing, will live for
392 // the entire life time of the process.
393 class BASE_EXPORT FieldTrialList {
394  public:
395   using FieldTrialAllocator = PersistentMemoryAllocator;
396 
397   // Type for function pointer passed to |AllParamsToString| used to escape
398   // special characters from |input|.
399   typedef std::string (*EscapeDataFunc)(const std::string& input);
400 
401   // Observer is notified when a FieldTrial's group is selected.
402   class BASE_EXPORT Observer {
403    public:
404     // Notify observers when FieldTrials's group is selected.
405     virtual void OnFieldTrialGroupFinalized(const std::string& trial_name,
406                                             const std::string& group_name) = 0;
407 
408    protected:
409     virtual ~Observer();
410   };
411 
412   // This singleton holds the global list of registered FieldTrials.
413   //
414   // To support one-time randomized field trials, specify a non-null
415   // |entropy_provider| which should be a source of uniformly distributed
416   // entropy values. If one time randomization is not desired, pass in null for
417   // |entropy_provider|.
418   explicit FieldTrialList(
419       std::unique_ptr<const FieldTrial::EntropyProvider> entropy_provider);
420   FieldTrialList(const FieldTrialList&) = delete;
421   FieldTrialList& operator=(const FieldTrialList&) = delete;
422 
423   // Destructor Release()'s references to all registered FieldTrial instances.
424   ~FieldTrialList();
425 
426   // Get a FieldTrial instance from the factory.
427   //
428   // |name| is used to register the instance with the FieldTrialList class,
429   // and can be used to find the trial (only one trial can be present for each
430   // name). |default_group_name| is the name of the default group which will
431   // be chosen if none of the subsequent appended groups get to be chosen.
432   // |default_group_number| can receive the group number of the default group as
433   // AppendGroup returns the number of the subsequence groups. |trial_name| and
434   // |default_group_name| may not be empty but |default_group_number| can be
435   // null if the value is not needed.
436   //
437   // Group probabilities that are later supplied must sum to less than or equal
438   // to the |total_probability|.
439   //
440   // Use this static method to get a startup-randomized FieldTrial or a
441   // previously created forced FieldTrial.
442   static FieldTrial* FactoryGetFieldTrial(
443       const std::string& trial_name,
444       FieldTrial::Probability total_probability,
445       const std::string& default_group_name,
446       FieldTrial::RandomizationType randomization_type,
447       int* default_group_number);
448 
449   // Same as FactoryGetFieldTrial(), but allows specifying a custom seed to be
450   // used on one-time randomized field trials (instead of a hash of the trial
451   // name, which is used otherwise or if |randomization_seed| has value 0). The
452   // |randomization_seed| value (other than 0) should never be the same for two
453   // trials, else this would result in correlated group assignments.  Note:
454   // Using a custom randomization seed is only supported by the
455   // NormalizedMurmurHashEntropyProvider, which is used when UMA is not enabled
456   // (and is always used in Android WebView, where UMA is enabled
457   // asyncronously). If |override_entropy_provider| is not null, then it will be
458   // used for randomization instead of the provider given when the
459   // FieldTrialList was instantiated.
460   static FieldTrial* FactoryGetFieldTrialWithRandomizationSeed(
461       const std::string& trial_name,
462       FieldTrial::Probability total_probability,
463       const std::string& default_group_name,
464       FieldTrial::RandomizationType randomization_type,
465       uint32_t randomization_seed,
466       int* default_group_number,
467       const FieldTrial::EntropyProvider* override_entropy_provider);
468 
469   // The Find() method can be used to test to see if a named trial was already
470   // registered, or to retrieve a pointer to it from the global map.
471   static FieldTrial* Find(const std::string& trial_name);
472 
473   // Returns the group number chosen for the named trial, or
474   // FieldTrial::kNotFinalized if the trial does not exist.
475   static int FindValue(const std::string& trial_name);
476 
477   // Returns the group name chosen for the named trial, or the empty string if
478   // the trial does not exist. The first call of this function on a given field
479   // trial will mark it as active, so that its state will be reported with usage
480   // metrics, crashes, etc.
481   // Note: Direct use of this function and related FieldTrial functions is
482   // generally discouraged - instead please use base::Feature when possible.
483   static std::string FindFullName(const std::string& trial_name);
484 
485   // Returns true if the named trial has been registered.
486   static bool TrialExists(const std::string& trial_name);
487 
488   // Returns true if the named trial exists and has been activated.
489   static bool IsTrialActive(const std::string& trial_name);
490 
491   // Creates a persistent representation of active FieldTrial instances for
492   // resurrection in another process. This allows randomization to be done in
493   // one process, and secondary processes can be synchronized on the result.
494   // The resulting string contains the name and group name pairs of all
495   // registered FieldTrials for which the group has been chosen and externally
496   // observed (via |group()|) and which have not been disabled, with "/" used
497   // to separate all names and to terminate the string. This string is parsed
498   // by |CreateTrialsFromString()|.
499   static void StatesToString(std::string* output);
500 
501   // Creates a persistent representation of all FieldTrial instances for
502   // resurrection in another process. This allows randomization to be done in
503   // one process, and secondary processes can be synchronized on the result.
504   // The resulting string contains the name and group name pairs of all
505   // registered FieldTrials including disabled based on |include_disabled|,
506   // with "/" used to separate all names and to terminate the string. All
507   // activated trials have their name prefixed with "*". This string is parsed
508   // by |CreateTrialsFromString()|.
509   static void AllStatesToString(std::string* output, bool include_disabled);
510 
511   // Creates a persistent representation of all FieldTrial params for
512   // resurrection in another process. The returned string contains the trial
513   // name and group name pairs of all registered FieldTrials including disabled
514   // based on |include_disabled| separated by '.'. The pair is followed by ':'
515   // separator and list of param name and values separated by '/'. It also takes
516   // |encode_data_func| function pointer for encodeing special charactors.
517   // This string is parsed by |AssociateParamsFromString()|.
518   static std::string AllParamsToString(bool include_disabled,
519                                        EscapeDataFunc encode_data_func);
520 
521   // Fills in the supplied vector |active_groups| (which must be empty when
522   // called) with a snapshot of all registered FieldTrials for which the group
523   // has been chosen and externally observed (via |group()|) and which have
524   // not been disabled.
525   static void GetActiveFieldTrialGroups(
526       FieldTrial::ActiveGroups* active_groups);
527 
528   // Returns the field trials that are marked active in |trials_string|.
529   static void GetActiveFieldTrialGroupsFromString(
530       const std::string& trials_string,
531       FieldTrial::ActiveGroups* active_groups);
532 
533   // Returns the field trials that were active when the process was
534   // created. Either parses the field trial string or the shared memory
535   // holding field trial information.
536   // Must be called only after a call to CreateTrialsFromCommandLine().
537   static void GetInitiallyActiveFieldTrials(
538       const CommandLine& command_line,
539       FieldTrial::ActiveGroups* active_groups);
540 
541   // Use a state string (re: StatesToString()) to augment the current list of
542   // field trials to include the supplied trials, and using a 100% probability
543   // for each trial, force them to have the same group string. This is commonly
544   // used in a non-browser process, to carry randomly selected state in a
545   // browser process into this non-browser process, but could also be invoked
546   // through a command line argument to the browser process. Created field
547   // trials will be marked "used" for the purposes of active trial reporting
548   // if they are prefixed with |kActivationMarker|.
549   static bool CreateTrialsFromString(const std::string& trials_string);
550 
551   // Achieves the same thing as CreateTrialsFromString, except wraps the logic
552   // by taking in the trials from the command line, either via shared memory
553   // handle or command line argument. A bit of a misnomer since on POSIX we
554   // simply get the trials from opening |fd_key| if using shared memory. On
555   // Windows, we expect the |cmd_line| switch for |field_trial_handle_switch| to
556   // contain the shared memory handle that contains the field trial allocator.
557   // We need the |field_trial_handle_switch| and |fd_key| arguments to be passed
558   // in since base/ can't depend on content/.
559   static void CreateTrialsFromCommandLine(const CommandLine& cmd_line,
560                                           const char* field_trial_handle_switch,
561                                           int fd_key);
562 
563   // Creates base::Feature overrides from the command line by first trying to
564   // use shared memory and then falling back to the command line if it fails.
565   static void CreateFeaturesFromCommandLine(const CommandLine& command_line,
566                                             const char* enable_features_switch,
567                                             const char* disable_features_switch,
568                                             FeatureList* feature_list);
569 
570 #if defined(OS_WIN)
571   // On Windows, we need to explicitly pass down any handles to be inherited.
572   // This function adds the shared memory handle to field trial state to the
573   // list of handles to be inherited.
574   static void AppendFieldTrialHandleIfNeeded(HandlesToInheritVector* handles);
575 #elif defined(OS_FUCHSIA)
576   // TODO(fuchsia): Implement shared-memory configuration (crbug.com/752368).
577 #elif defined(OS_MAC)
578   // On Mac, the field trial shared memory is accessed via a Mach server, which
579   // the child looks up directly.
580   static void InsertFieldTrialHandleIfNeeded(
581       MachPortsForRendezvous* rendezvous_ports);
582 #elif defined(OS_POSIX) && !defined(OS_NACL)
583   // On POSIX, we also need to explicitly pass down this file descriptor that
584   // should be shared with the child process. Returns -1 if it was not
585   // initialized properly. The current process remains the onwer of the passed
586   // descriptor.
587   static int GetFieldTrialDescriptor();
588 #endif
589   static ReadOnlySharedMemoryRegion DuplicateFieldTrialSharedMemoryForTesting();
590 
591   // Adds a switch to the command line containing the field trial state as a
592   // string (if not using shared memory to share field trial state), or the
593   // shared memory handle + length.
594   // Needs the |field_trial_handle_switch| argument to be passed in since base/
595   // can't depend on content/.
596   static void CopyFieldTrialStateToFlags(const char* field_trial_handle_switch,
597                                          const char* enable_features_switch,
598                                          const char* disable_features_switch,
599                                          CommandLine* cmd_line);
600 
601   // Create a FieldTrial with the given |name| and using 100% probability for
602   // the FieldTrial, force FieldTrial to have the same group string as
603   // |group_name|. This is commonly used in a non-browser process, to carry
604   // randomly selected state in a browser process into this non-browser process.
605   // It returns NULL if there is a FieldTrial that is already registered with
606   // the same |name| but has different finalized group string (|group_name|).
607   static FieldTrial* CreateFieldTrial(const std::string& name,
608                                       const std::string& group_name);
609 
610   // Add an observer to be notified when a field trial is irrevocably committed
611   // to being part of some specific field_group (and hence the group_name is
612   // also finalized for that field_trial). Returns false and does nothing if
613   // there is no FieldTrialList singleton.
614   static bool AddObserver(Observer* observer);
615 
616   // Remove an observer.
617   static void RemoveObserver(Observer* observer);
618 
619   // Similar to AddObserver(), but the passed observer will be notified
620   // synchronously when a field trial is activated and its group selected. It
621   // will be notified synchronously on the same thread where the activation and
622   // group selection happened. It is the responsibility of the observer to make
623   // sure that this is a safe operation and the operation must be fast, as this
624   // work is done synchronously as part of group() or related APIs. Only a
625   // single such observer is supported, exposed specifically for crash
626   // reporting. Must be called on the main thread before any other threads
627   // have been started.
628   static void SetSynchronousObserver(Observer* observer);
629 
630   // Removes the single synchronous observer.
631   static void RemoveSynchronousObserver(Observer* observer);
632 
633   // Grabs the lock if necessary and adds the field trial to the allocator. This
634   // should only be called from FinalizeGroupChoice().
635   static void OnGroupFinalized(bool is_locked, FieldTrial* field_trial);
636 
637   // Notify all observers that a group has been finalized for |field_trial|.
638   static void NotifyFieldTrialGroupSelection(FieldTrial* field_trial);
639 
640   // Return the number of active field trials.
641   static size_t GetFieldTrialCount();
642 
643   // Gets the parameters for |field_trial| from shared memory and stores them in
644   // |params|. This is only exposed for use by FieldTrialParamAssociator and
645   // shouldn't be used by anything else.
646   static bool GetParamsFromSharedMemory(
647       FieldTrial* field_trial,
648       std::map<std::string, std::string>* params);
649 
650   // Clears all the params in the allocator.
651   static void ClearParamsFromSharedMemoryForTesting();
652 
653   // Dumps field trial state to an allocator so that it can be analyzed after a
654   // crash.
655   static void DumpAllFieldTrialsToPersistentAllocator(
656       PersistentMemoryAllocator* allocator);
657 
658   // Retrieves field trial state from an allocator so that it can be analyzed
659   // after a crash. The pointers in the returned vector are into the persistent
660   // memory segment and so are only valid as long as the allocator is valid.
661   static std::vector<const FieldTrial::FieldTrialEntry*>
662   GetAllFieldTrialsFromPersistentAllocator(
663       PersistentMemoryAllocator const& allocator);
664 
665   // Returns a pointer to the global instance. This is exposed so that it can
666   // be used in a DCHECK in FeatureList and ScopedFeatureList test-only logic
667   // and is not intended to be used widely beyond those cases.
668   static FieldTrialList* GetInstance();
669 
670   // For testing, sets the global instance to null and returns the previous one.
671   static FieldTrialList* BackupInstanceForTesting();
672 
673   // For testing, sets the global instance to |instance|.
674   static void RestoreInstanceForTesting(FieldTrialList* instance);
675 
676  private:
677   // Allow tests to access our innards for testing purposes.
678   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, InstantiateAllocator);
679   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, AddTrialsToAllocator);
680   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest,
681                            DoNotAddSimulatedFieldTrialsToAllocator);
682   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, AssociateFieldTrialParams);
683   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, ClearParamsFromSharedMemory);
684   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest,
685                            SerializeSharedMemoryRegionMetadata);
686   friend int SerializeSharedMemoryRegionMetadata(void);
687   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, CheckReadOnlySharedMemoryRegion);
688 
689   // Serialization is used to pass information about the handle to child
690   // processes. It passes a reference to the relevant OS resource, and it passes
691   // a GUID. Serialization and deserialization doesn't actually transport the
692   // underlying OS resource - that must be done by the Process launcher.
693   static std::string SerializeSharedMemoryRegionMetadata(
694       const ReadOnlySharedMemoryRegion& shm);
695 #if defined(OS_WIN) || defined(OS_FUCHSIA) || defined(OS_MAC)
696   static ReadOnlySharedMemoryRegion DeserializeSharedMemoryRegionMetadata(
697       const std::string& switch_value);
698 #elif defined(OS_POSIX) && !defined(OS_NACL)
699   static ReadOnlySharedMemoryRegion DeserializeSharedMemoryRegionMetadata(
700       int fd,
701       const std::string& switch_value);
702 #endif
703 
704 #if defined(OS_WIN) || defined(OS_FUCHSIA) || defined(OS_MAC)
705   // Takes in |handle_switch| from the command line which represents the shared
706   // memory handle for field trials, parses it, and creates the field trials.
707   // Returns true on success, false on failure.
708   // |switch_value| also contains the serialized GUID.
709   static bool CreateTrialsFromSwitchValue(const std::string& switch_value);
710 #elif defined(OS_POSIX) && !defined(OS_NACL)
711   // On POSIX systems that use the zygote, we look up the correct fd that backs
712   // the shared memory segment containing the field trials by looking it up via
713   // an fd key in GlobalDescriptors. Returns true on success, false on failure.
714   // |switch_value| also contains the serialized GUID.
715   static bool CreateTrialsFromDescriptor(int fd_key,
716                                          const std::string& switch_value);
717 #endif
718 
719   // Takes an unmapped ReadOnlySharedMemoryRegion, maps it with the correct size
720   // and creates field trials via CreateTrialsFromSharedMemoryMapping(). Returns
721   // true if successful and false otherwise.
722   static bool CreateTrialsFromSharedMemoryRegion(
723       const ReadOnlySharedMemoryRegion& shm_region);
724 
725   // Expects a mapped piece of shared memory |shm_mapping| that was created from
726   // the browser process's field_trial_allocator and shared via the command
727   // line. This function recreates the allocator, iterates through all the field
728   // trials in it, and creates them via CreateFieldTrial(). Returns true if
729   // successful and false otherwise.
730   static bool CreateTrialsFromSharedMemoryMapping(
731       ReadOnlySharedMemoryMapping shm_mapping);
732 
733   // Instantiate the field trial allocator, add all existing field trials to it,
734   // and duplicates its handle to a read-only handle, which gets stored in
735   // |readonly_allocator_handle|.
736   static void InstantiateFieldTrialAllocatorIfNeeded();
737 
738   // Adds the field trial to the allocator. Caller must hold a lock before
739   // calling this.
740   static void AddToAllocatorWhileLocked(PersistentMemoryAllocator* allocator,
741                                         FieldTrial* field_trial);
742 
743   // Activate the corresponding field trial entry struct in shared memory.
744   static void ActivateFieldTrialEntryWhileLocked(FieldTrial* field_trial);
745 
746   // A map from FieldTrial names to the actual instances.
747   typedef std::map<std::string, FieldTrial*> RegistrationMap;
748 
749   // If one-time randomization is enabled, returns a weak pointer to the
750   // corresponding EntropyProvider. Otherwise, returns NULL.
751   static const FieldTrial::EntropyProvider*
752       GetEntropyProviderForOneTimeRandomization();
753 
754   // Helper function should be called only while holding lock_.
755   FieldTrial* PreLockedFind(const std::string& name);
756 
757   // Register() stores a pointer to the given trial in a global map.
758   // This method also AddRef's the indicated trial.
759   // This should always be called after creating a new FieldTrial instance.
760   static void Register(FieldTrial* trial);
761 
762   // Returns all the registered trials.
763   static RegistrationMap GetRegisteredTrials();
764 
765   static FieldTrialList* global_;  // The singleton of this class.
766 
767   // This will tell us if there is an attempt to register a field
768   // trial or check if one-time randomization is enabled without
769   // creating the FieldTrialList. This is not an error, unless a
770   // FieldTrialList is created after that.
771   static bool used_without_global_;
772 
773   // Lock for access to registered_ and field_trial_allocator_.
774   Lock lock_;
775   RegistrationMap registered_;
776 
777   std::map<std::string, std::string> seen_states_;
778 
779   // Entropy provider to be used for one-time randomized field trials. If NULL,
780   // one-time randomization is not supported.
781   std::unique_ptr<const FieldTrial::EntropyProvider> entropy_provider_;
782 
783   // List of observers to be notified when a group is selected for a FieldTrial.
784   scoped_refptr<ObserverListThreadSafe<Observer> > observer_list_;
785 
786   // Single synchronous observer to be notified when a trial group is chosen.
787   Observer* synchronous_observer_ = nullptr;
788 
789   // Allocator in shared memory containing field trial data. Used in both
790   // browser and child processes, but readonly in the child.
791   // In the future, we may want to move this to a more generic place if we want
792   // to start passing more data other than field trials.
793   std::unique_ptr<FieldTrialAllocator> field_trial_allocator_ = nullptr;
794 
795   // Readonly copy of the region to the allocator. Needs to be a member variable
796   // because it's needed from both CopyFieldTrialStateToFlags() and
797   // AppendFieldTrialHandleIfNeeded().
798   ReadOnlySharedMemoryRegion readonly_allocator_region_;
799 
800   // Tracks whether CreateTrialsFromCommandLine() has been called.
801   bool create_trials_from_command_line_called_ = false;
802 };
803 
804 }  // namespace base
805 
806 #endif  // BASE_METRICS_FIELD_TRIAL_H_
807