• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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("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", 2015, 7, 8,
40 //         base::FieldTrial::ONE_TIME_RANDOMIZED, NULL));
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/files/file.h"
71 #include "base/gtest_prod_util.h"
72 #include "base/macros.h"
73 #include "base/memory/ref_counted.h"
74 #include "base/memory/shared_memory.h"
75 #include "base/memory/shared_memory_handle.h"
76 #include "base/metrics/persistent_memory_allocator.h"
77 #include "base/observer_list_threadsafe.h"
78 #include "base/pickle.h"
79 #include "base/process/launch.h"
80 #include "base/strings/string_piece.h"
81 #include "base/synchronization/lock.h"
82 #include "base/time/time.h"
83 #include "build/build_config.h"
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   // TODO(665129): Make private again after crash has been resolved.
94   typedef SharedPersistentMemoryAllocator::Reference FieldTrialRef;
95 
96   // Specifies the persistence of the field trial group choice.
97   enum RandomizationType {
98     // One time randomized trials will persist the group choice between
99     // restarts, which is recommended for most trials, especially those that
100     // change user visible behavior.
101     ONE_TIME_RANDOMIZED,
102     // Session randomized trials will roll the dice to select a group on every
103     // process restart.
104     SESSION_RANDOMIZED,
105   };
106 
107   // EntropyProvider is an interface for providing entropy for one-time
108   // randomized (persistent) field trials.
109   class BASE_EXPORT EntropyProvider {
110    public:
111     virtual ~EntropyProvider();
112 
113     // Returns a double in the range of [0, 1) to be used for the dice roll for
114     // the specified field trial. If |randomization_seed| is not 0, it will be
115     // used in preference to |trial_name| for generating the entropy by entropy
116     // providers that support it. A given instance should always return the same
117     // value given the same input |trial_name| and |randomization_seed| values.
118     virtual double GetEntropyForTrial(const std::string& trial_name,
119                                       uint32_t randomization_seed) const = 0;
120   };
121 
122   // A pair representing a Field Trial and its selected group.
123   struct ActiveGroup {
124     std::string trial_name;
125     std::string group_name;
126   };
127 
128   // A triplet representing a FieldTrial, its selected group and whether it's
129   // active. String members are pointers to the underlying strings owned by the
130   // FieldTrial object. Does not use StringPiece to avoid conversions back to
131   // std::string.
132   struct BASE_EXPORT State {
133     const std::string* trial_name = nullptr;
134     const std::string* group_name = nullptr;
135     bool activated = false;
136 
137     State();
138     State(const State& other);
139     ~State();
140   };
141 
142   // We create one FieldTrialEntry per field trial in shared memory, via
143   // AddToAllocatorWhileLocked. The FieldTrialEntry is followed by a
144   // base::Pickle object that we unpickle and read from.
145   struct BASE_EXPORT FieldTrialEntry {
146     // SHA1(FieldTrialEntry): Increment this if structure changes!
147     static constexpr uint32_t kPersistentTypeId = 0xABA17E13 + 2;
148 
149     // Expected size for 32/64-bit check.
150     static constexpr size_t kExpectedInstanceSize = 8;
151 
152     // Whether or not this field trial is activated. This is really just a
153     // boolean but using a 32 bit value for portability reasons. It should be
154     // accessed via NoBarrier_Load()/NoBarrier_Store() to prevent the compiler
155     // from doing unexpected optimizations because it thinks that only one
156     // thread is accessing the memory location.
157     subtle::Atomic32 activated;
158 
159     // Size of the pickled structure, NOT the total size of this entry.
160     uint32_t pickle_size;
161 
162     // Calling this is only valid when the entry is initialized. That is, it
163     // resides in shared memory and has a pickle containing the trial name and
164     // group name following it.
165     bool GetTrialAndGroupName(StringPiece* trial_name,
166                               StringPiece* group_name) const;
167 
168     // Calling this is only valid when the entry is initialized as well. Reads
169     // the parameters following the trial and group name and stores them as
170     // key-value mappings in |params|.
171     bool GetParams(std::map<std::string, std::string>* params) const;
172 
173    private:
174     // Returns an iterator over the data containing names and params.
175     PickleIterator GetPickleIterator() const;
176 
177     // Takes the iterator and writes out the first two items into |trial_name|
178     // and |group_name|.
179     bool ReadStringPair(PickleIterator* iter,
180                         StringPiece* trial_name,
181                         StringPiece* group_name) const;
182   };
183 
184   typedef std::vector<ActiveGroup> ActiveGroups;
185 
186   // A return value to indicate that a given instance has not yet had a group
187   // assignment (and hence is not yet participating in the trial).
188   static const int kNotFinalized;
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   // This is the group number of the 'default' group when a choice wasn't forced
283   // by a call to FieldTrialList::CreateFieldTrial. It is kept private so that
284   // consumers don't use it by mistake in cases where the group was forced.
285   static const int kDefaultGroupNumber;
286 
287   // Creates a field trial with the specified parameters. Group assignment will
288   // be done based on |entropy_value|, which must have a range of [0, 1).
289   FieldTrial(const std::string& trial_name,
290              Probability total_probability,
291              const std::string& default_group_name,
292              double entropy_value);
293   virtual ~FieldTrial();
294 
295   // Return the default group name of the FieldTrial.
default_group_name()296   std::string default_group_name() const { return default_group_name_; }
297 
298   // Marks this trial as having been registered with the FieldTrialList. Must be
299   // called no more than once and before any |group()| calls have occurred.
300   void SetTrialRegistered();
301 
302   // Sets the chosen group name and number.
303   void SetGroupChoice(const std::string& group_name, int number);
304 
305   // Ensures that a group is chosen, if it hasn't yet been. The field trial
306   // might yet be disabled, so this call will *not* notify observers of the
307   // status.
308   void FinalizeGroupChoice();
309 
310   // Implements FinalizeGroupChoice() with the added flexibility of being
311   // deadlock-free if |is_locked| is true and the caller is holding a lock.
312   void FinalizeGroupChoiceImpl(bool is_locked);
313 
314   // Returns the trial name and selected group name for this field trial via
315   // the output parameter |active_group|, but only if the group has already
316   // been chosen and has been externally observed via |group()| and the trial
317   // has not been disabled. In that case, true is returned and |active_group|
318   // is filled in; otherwise, the result is false and |active_group| is left
319   // untouched.
320   bool GetActiveGroup(ActiveGroup* active_group) const;
321 
322   // Returns the trial name and selected group name for this field trial via
323   // the output parameter |field_trial_state| for all the studies when
324   // |bool include_expired| is true. In case when |bool include_expired| is
325   // false, if the trial has not been disabled true is returned and
326   // |field_trial_state| is filled in; otherwise, the result is false and
327   // |field_trial_state| is left untouched.
328   // This function is deadlock-free if the caller is holding a lock.
329   bool GetStateWhileLocked(State* field_trial_state, bool include_expired);
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   typedef SharedPersistentMemoryAllocator FieldTrialAllocator;
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   // Year that is guaranteed to not be expired when instantiating a field trial
402   // via |FactoryGetFieldTrial()|.  Set to two years from the build date.
403   static int kNoExpirationYear;
404 
405   // Observer is notified when a FieldTrial's group is selected.
406   class BASE_EXPORT Observer {
407    public:
408     // Notify observers when FieldTrials's group is selected.
409     virtual void OnFieldTrialGroupFinalized(const std::string& trial_name,
410                                             const std::string& group_name) = 0;
411 
412    protected:
413     virtual ~Observer();
414   };
415 
416   // This singleton holds the global list of registered FieldTrials.
417   //
418   // To support one-time randomized field trials, specify a non-null
419   // |entropy_provider| which should be a source of uniformly distributed
420   // entropy values. If one time randomization is not desired, pass in null for
421   // |entropy_provider|.
422   explicit FieldTrialList(
423       std::unique_ptr<const FieldTrial::EntropyProvider> entropy_provider);
424 
425   // Destructor Release()'s references to all registered FieldTrial instances.
426   ~FieldTrialList();
427 
428   // Get a FieldTrial instance from the factory.
429   //
430   // |name| is used to register the instance with the FieldTrialList class,
431   // and can be used to find the trial (only one trial can be present for each
432   // name). |default_group_name| is the name of the default group which will
433   // be chosen if none of the subsequent appended groups get to be chosen.
434   // |default_group_number| can receive the group number of the default group as
435   // AppendGroup returns the number of the subsequence groups. |trial_name| and
436   // |default_group_name| may not be empty but |default_group_number| can be
437   // NULL if the value is not needed.
438   //
439   // Group probabilities that are later supplied must sum to less than or equal
440   // to the |total_probability|. Arguments |year|, |month| and |day_of_month|
441   // specify the expiration time. If the build time is after the expiration time
442   // then the field trial reverts to the 'default' group.
443   //
444   // Use this static method to get a startup-randomized FieldTrial or a
445   // previously created forced FieldTrial.
446   static FieldTrial* FactoryGetFieldTrial(
447       const std::string& trial_name,
448       FieldTrial::Probability total_probability,
449       const std::string& default_group_name,
450       const int year,
451       const int month,
452       const int day_of_month,
453       FieldTrial::RandomizationType randomization_type,
454       int* default_group_number);
455 
456   // Same as FactoryGetFieldTrial(), but allows specifying a custom seed to be
457   // used on one-time randomized field trials (instead of a hash of the trial
458   // name, which is used otherwise or if |randomization_seed| has value 0). The
459   // |randomization_seed| value (other than 0) should never be the same for two
460   // trials, else this would result in correlated group assignments.  Note:
461   // Using a custom randomization seed is only supported by the
462   // PermutedEntropyProvider (which is used when UMA is not enabled). If
463   // |override_entropy_provider| is not null, then it will be used for
464   // randomization instead of the provider given when the FieldTrialList was
465   // instantiated.
466   static FieldTrial* FactoryGetFieldTrialWithRandomizationSeed(
467       const std::string& trial_name,
468       FieldTrial::Probability total_probability,
469       const std::string& default_group_name,
470       const int year,
471       const int month,
472       const int day_of_month,
473       FieldTrial::RandomizationType randomization_type,
474       uint32_t randomization_seed,
475       int* default_group_number,
476       const FieldTrial::EntropyProvider* override_entropy_provider);
477 
478   // The Find() method can be used to test to see if a named trial was already
479   // registered, or to retrieve a pointer to it from the global map.
480   static FieldTrial* Find(const std::string& trial_name);
481 
482   // Returns the group number chosen for the named trial, or
483   // FieldTrial::kNotFinalized if the trial does not exist.
484   static int FindValue(const std::string& trial_name);
485 
486   // Returns the group name chosen for the named trial, or the empty string if
487   // the trial does not exist. The first call of this function on a given field
488   // trial will mark it as active, so that its state will be reported with usage
489   // metrics, crashes, etc.
490   static std::string FindFullName(const std::string& trial_name);
491 
492   // Returns true if the named trial has been registered.
493   static bool TrialExists(const std::string& trial_name);
494 
495   // Returns true if the named trial exists and has been activated.
496   static bool IsTrialActive(const std::string& trial_name);
497 
498   // Creates a persistent representation of active FieldTrial instances for
499   // resurrection in another process. This allows randomization to be done in
500   // one process, and secondary processes can be synchronized on the result.
501   // The resulting string contains the name and group name pairs of all
502   // registered FieldTrials for which the group has been chosen and externally
503   // observed (via |group()|) and which have not been disabled, with "/" used
504   // to separate all names and to terminate the string. This string is parsed
505   // by |CreateTrialsFromString()|.
506   static void StatesToString(std::string* output);
507 
508   // Creates a persistent representation of all FieldTrial instances for
509   // resurrection in another process. This allows randomization to be done in
510   // one process, and secondary processes can be synchronized on the result.
511   // The resulting string contains the name and group name pairs of all
512   // registered FieldTrials including disabled based on |include_expired|,
513   // with "/" used to separate all names and to terminate the string. All
514   // activated trials have their name prefixed with "*". This string is parsed
515   // by |CreateTrialsFromString()|.
516   static void AllStatesToString(std::string* output, bool include_expired);
517 
518   // Creates a persistent representation of all FieldTrial params for
519   // resurrection in another process. The returned string contains the trial
520   // name and group name pairs of all registered FieldTrials including disabled
521   // based on |include_expired| separated by '.'. The pair is followed by ':'
522   // separator and list of param name and values separated by '/'. It also takes
523   // |encode_data_func| function pointer for encodeing special charactors.
524   // This string is parsed by |AssociateParamsFromString()|.
525   static std::string AllParamsToString(bool include_expired,
526                                        EscapeDataFunc encode_data_func);
527 
528   // Fills in the supplied vector |active_groups| (which must be empty when
529   // called) with a snapshot of all registered FieldTrials for which the group
530   // has been chosen and externally observed (via |group()|) and which have
531   // not been disabled.
532   static void GetActiveFieldTrialGroups(
533       FieldTrial::ActiveGroups* active_groups);
534 
535   // Returns the field trials that are marked active in |trials_string|.
536   static void GetActiveFieldTrialGroupsFromString(
537       const std::string& trials_string,
538       FieldTrial::ActiveGroups* active_groups);
539 
540   // Returns the field trials that were active when the process was
541   // created. Either parses the field trial string or the shared memory
542   // holding field trial information.
543   // Must be called only after a call to CreateTrialsFromCommandLine().
544   static void GetInitiallyActiveFieldTrials(
545       const base::CommandLine& command_line,
546       FieldTrial::ActiveGroups* active_groups);
547 
548   // Use a state string (re: StatesToString()) to augment the current list of
549   // field trials to include the supplied trials, and using a 100% probability
550   // for each trial, force them to have the same group string. This is commonly
551   // used in a non-browser process, to carry randomly selected state in a
552   // browser process into this non-browser process, but could also be invoked
553   // through a command line argument to the browser process. Created field
554   // trials will be marked "used" for the purposes of active trial reporting
555   // if they are prefixed with |kActivationMarker|. Trial names in
556   // |ignored_trial_names| are ignored when parsing |trials_string|.
557   static bool CreateTrialsFromString(
558       const std::string& trials_string,
559       const std::set<std::string>& ignored_trial_names);
560 
561   // Achieves the same thing as CreateTrialsFromString, except wraps the logic
562   // by taking in the trials from the command line, either via shared memory
563   // handle or command line argument. A bit of a misnomer since on POSIX we
564   // simply get the trials from opening |fd_key| if using shared memory. On
565   // Windows, we expect the |cmd_line| switch for |field_trial_handle_switch| to
566   // contain the shared memory handle that contains the field trial allocator.
567   // We need the |field_trial_handle_switch| and |fd_key| arguments to be passed
568   // in since base/ can't depend on content/.
569   static void CreateTrialsFromCommandLine(const base::CommandLine& cmd_line,
570                                           const char* field_trial_handle_switch,
571                                           int fd_key);
572 
573   // Creates base::Feature overrides from the command line by first trying to
574   // use shared memory and then falling back to the command line if it fails.
575   static void CreateFeaturesFromCommandLine(
576       const base::CommandLine& command_line,
577       const char* enable_features_switch,
578       const char* disable_features_switch,
579       FeatureList* feature_list);
580 
581 #if defined(OS_WIN)
582   // On Windows, we need to explicitly pass down any handles to be inherited.
583   // This function adds the shared memory handle to field trial state to the
584   // list of handles to be inherited.
585   static void AppendFieldTrialHandleIfNeeded(
586       base::HandlesToInheritVector* handles);
587 #elif defined(OS_FUCHSIA)
588   // TODO(fuchsia): Implement shared-memory configuration (crbug.com/752368).
589 #elif defined(OS_POSIX) && !defined(OS_NACL)
590   // On POSIX, we also need to explicitly pass down this file descriptor that
591   // should be shared with the child process. Returns an invalid handle if it
592   // was not initialized properly.
593   static base::SharedMemoryHandle GetFieldTrialHandle();
594 #endif
595 
596   // Adds a switch to the command line containing the field trial state as a
597   // string (if not using shared memory to share field trial state), or the
598   // shared memory handle + length.
599   // Needs the |field_trial_handle_switch| argument to be passed in since base/
600   // can't depend on content/.
601   static void CopyFieldTrialStateToFlags(const char* field_trial_handle_switch,
602                                          const char* enable_features_switch,
603                                          const char* disable_features_switch,
604                                          base::CommandLine* cmd_line);
605 
606   // Create a FieldTrial with the given |name| and using 100% probability for
607   // the FieldTrial, force FieldTrial to have the same group string as
608   // |group_name|. This is commonly used in a non-browser process, to carry
609   // randomly selected state in a browser process into this non-browser process.
610   // It returns NULL if there is a FieldTrial that is already registered with
611   // the same |name| but has different finalized group string (|group_name|).
612   static FieldTrial* CreateFieldTrial(const std::string& name,
613                                       const std::string& group_name);
614 
615   // Add an observer to be notified when a field trial is irrevocably committed
616   // to being part of some specific field_group (and hence the group_name is
617   // also finalized for that field_trial). Returns false and does nothing if
618   // there is no FieldTrialList singleton.
619   static bool AddObserver(Observer* observer);
620 
621   // Remove an observer.
622   static void RemoveObserver(Observer* observer);
623 
624   // Similar to AddObserver(), but the passed observer will be notified
625   // synchronously when a field trial is activated and its group selected. It
626   // will be notified synchronously on the same thread where the activation and
627   // group selection happened. It is the responsibility of the observer to make
628   // sure that this is a safe operation and the operation must be fast, as this
629   // work is done synchronously as part of group() or related APIs. Only a
630   // single such observer is supported, exposed specifically for crash
631   // reporting. Must be called on the main thread before any other threads
632   // have been started.
633   static void SetSynchronousObserver(Observer* observer);
634 
635   // Removes the single synchronous observer.
636   static void RemoveSynchronousObserver(Observer* observer);
637 
638   // Grabs the lock if necessary and adds the field trial to the allocator. This
639   // should only be called from FinalizeGroupChoice().
640   static void OnGroupFinalized(bool is_locked, FieldTrial* field_trial);
641 
642   // Notify all observers that a group has been finalized for |field_trial|.
643   static void NotifyFieldTrialGroupSelection(FieldTrial* field_trial);
644 
645   // Return the number of active field trials.
646   static size_t GetFieldTrialCount();
647 
648   // Gets the parameters for |field_trial| from shared memory and stores them in
649   // |params|. This is only exposed for use by FieldTrialParamAssociator and
650   // shouldn't be used by anything else.
651   static bool GetParamsFromSharedMemory(
652       FieldTrial* field_trial,
653       std::map<std::string, std::string>* params);
654 
655   // Clears all the params in the allocator.
656   static void ClearParamsFromSharedMemoryForTesting();
657 
658   // Dumps field trial state to an allocator so that it can be analyzed after a
659   // crash.
660   static void DumpAllFieldTrialsToPersistentAllocator(
661       PersistentMemoryAllocator* allocator);
662 
663   // Retrieves field trial state from an allocator so that it can be analyzed
664   // after a crash. The pointers in the returned vector are into the persistent
665   // memory segment and so are only valid as long as the allocator is valid.
666   static std::vector<const FieldTrial::FieldTrialEntry*>
667   GetAllFieldTrialsFromPersistentAllocator(
668       PersistentMemoryAllocator const& allocator);
669 
670   // Returns true if a global field trial list is set. Only used for testing.
671   static bool IsGlobalSetForTesting();
672 
673  private:
674   // Allow tests to access our innards for testing purposes.
675   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, InstantiateAllocator);
676   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, AddTrialsToAllocator);
677   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest,
678                            DoNotAddSimulatedFieldTrialsToAllocator);
679   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, AssociateFieldTrialParams);
680   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, ClearParamsFromSharedMemory);
681   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest,
682                            SerializeSharedMemoryHandleMetadata);
683   FRIEND_TEST_ALL_PREFIXES(FieldTrialListTest, CheckReadOnlySharedMemoryHandle);
684 
685   // Serialization is used to pass information about the handle to child
686   // processes. It passes a reference to the relevant OS resource, and it passes
687   // a GUID. Serialization and deserialization doesn't actually transport the
688   // underlying OS resource - that must be done by the Process launcher.
689   static std::string SerializeSharedMemoryHandleMetadata(
690       const SharedMemoryHandle& shm);
691 #if defined(OS_WIN) || defined(OS_FUCHSIA)
692   static SharedMemoryHandle DeserializeSharedMemoryHandleMetadata(
693       const std::string& switch_value);
694 #elif defined(OS_POSIX) && !defined(OS_NACL)
695   static SharedMemoryHandle DeserializeSharedMemoryHandleMetadata(
696       int fd,
697       const std::string& switch_value);
698 #endif
699 
700 #if defined(OS_WIN) || defined(OS_FUCHSIA)
701   // Takes in |handle_switch| from the command line which represents the shared
702   // memory handle for field trials, parses it, and creates the field trials.
703   // Returns true on success, false on failure.
704   // |switch_value| also contains the serialized GUID.
705   static bool CreateTrialsFromSwitchValue(const std::string& switch_value);
706 #elif defined(OS_POSIX) && !defined(OS_NACL)
707   // On POSIX systems that use the zygote, we look up the correct fd that backs
708   // the shared memory segment containing the field trials by looking it up via
709   // an fd key in GlobalDescriptors. Returns true on success, false on failure.
710   // |switch_value| also contains the serialized GUID.
711   static bool CreateTrialsFromDescriptor(int fd_key,
712                                          const std::string& switch_value);
713 #endif
714 
715   // Takes an unmapped SharedMemoryHandle, creates a SharedMemory object from it
716   // and maps it with the correct size.
717   static bool CreateTrialsFromSharedMemoryHandle(SharedMemoryHandle shm_handle);
718 
719   // Expects a mapped piece of shared memory |shm| that was created from the
720   // browser process's field_trial_allocator and shared via the command line.
721   // This function recreates the allocator, iterates through all the field
722   // trials in it, and creates them via CreateFieldTrial(). Returns true if
723   // successful and false otherwise.
724   static bool CreateTrialsFromSharedMemory(
725       std::unique_ptr<base::SharedMemory> shm);
726 
727   // Instantiate the field trial allocator, add all existing field trials to it,
728   // and duplicates its handle to a read-only handle, which gets stored in
729   // |readonly_allocator_handle|.
730   static void InstantiateFieldTrialAllocatorIfNeeded();
731 
732   // Adds the field trial to the allocator. Caller must hold a lock before
733   // calling this.
734   static void AddToAllocatorWhileLocked(PersistentMemoryAllocator* allocator,
735                                         FieldTrial* field_trial);
736 
737   // Activate the corresponding field trial entry struct in shared memory.
738   static void ActivateFieldTrialEntryWhileLocked(FieldTrial* field_trial);
739 
740   // A map from FieldTrial names to the actual instances.
741   typedef std::map<std::string, FieldTrial*> RegistrationMap;
742 
743   // If one-time randomization is enabled, returns a weak pointer to the
744   // corresponding EntropyProvider. Otherwise, returns NULL.
745   static const FieldTrial::EntropyProvider*
746       GetEntropyProviderForOneTimeRandomization();
747 
748   // Helper function should be called only while holding lock_.
749   FieldTrial* PreLockedFind(const std::string& name);
750 
751   // Register() stores a pointer to the given trial in a global map.
752   // This method also AddRef's the indicated trial.
753   // This should always be called after creating a new FieldTrial instance.
754   static void Register(FieldTrial* trial);
755 
756   // Returns all the registered trials.
757   static RegistrationMap GetRegisteredTrials();
758 
759   static FieldTrialList* global_;  // The singleton of this class.
760 
761   // This will tell us if there is an attempt to register a field
762   // trial or check if one-time randomization is enabled without
763   // creating the FieldTrialList. This is not an error, unless a
764   // FieldTrialList is created after that.
765   static bool used_without_global_;
766 
767   // Lock for access to registered_ and field_trial_allocator_.
768   Lock lock_;
769   RegistrationMap registered_;
770 
771   std::map<std::string, std::string> seen_states_;
772 
773   // Entropy provider to be used for one-time randomized field trials. If NULL,
774   // one-time randomization is not supported.
775   std::unique_ptr<const FieldTrial::EntropyProvider> entropy_provider_;
776 
777   // List of observers to be notified when a group is selected for a FieldTrial.
778   scoped_refptr<ObserverListThreadSafe<Observer> > observer_list_;
779 
780   // Single synchronous observer to be notified when a trial group is chosen.
781   Observer* synchronous_observer_ = nullptr;
782 
783   // Allocator in shared memory containing field trial data. Used in both
784   // browser and child processes, but readonly in the child.
785   // In the future, we may want to move this to a more generic place if we want
786   // to start passing more data other than field trials.
787   std::unique_ptr<FieldTrialAllocator> field_trial_allocator_ = nullptr;
788 
789   // Readonly copy of the handle to the allocator. Needs to be a member variable
790   // because it's needed from both CopyFieldTrialStateToFlags() and
791   // AppendFieldTrialHandleIfNeeded().
792   base::SharedMemoryHandle readonly_allocator_handle_;
793 
794   // Tracks whether CreateTrialsFromCommandLine() has been called.
795   bool create_trials_from_command_line_called_ = false;
796 
797   DISALLOW_COPY_AND_ASSIGN(FieldTrialList);
798 };
799 
800 }  // namespace base
801 
802 #endif  // BASE_METRICS_FIELD_TRIAL_H_
803