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