1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/metrics/field_trial.h"
#include <algorithm>
#include <utility>
#include "base/base_switches.h"
#include "base/build_time.h"
#include "base/command_line.h"
#include "base/debug/activity_tracker.h"
#include "base/debug/crash_logging.h"
#include "base/logging.h"
#include "base/metrics/field_trial_param_associator.h"
#include "base/process/memory.h"
#include "base/rand_util.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/strings/utf_string_conversions.h"
#include "base/unguessable_token.h"
// On POSIX, the fd is shared using the mapping in GlobalDescriptors.
#if defined(OS_POSIX) && !defined(OS_NACL)
#include "base/posix/global_descriptors.h"
#endif
namespace base {
namespace {
// Define a separator character to use when creating a persistent form of an
// instance. This is intended for use as a command line argument, passed to a
// second process to mimic our state (i.e., provide the same group name).
const char kPersistentStringSeparator = '/'; // Currently a slash.
// Define a marker character to be used as a prefix to a trial name on the
// command line which forces its activation.
const char kActivationMarker = '*';
// Use shared memory to communicate field trial (experiment) state. Set to false
// for now while the implementation is fleshed out (e.g. data format, single
// shared memory segment). See https://codereview.chromium.org/2365273004/ and
// crbug.com/653874
// The browser is the only process that has write access to the shared memory.
// This is safe from race conditions because MakeIterable is a release operation
// and GetNextOfType is an acquire operation, so memory writes before
// MakeIterable happen before memory reads after GetNextOfType.
const bool kUseSharedMemoryForFieldTrials = true;
// Constants for the field trial allocator.
const char kAllocatorName[] = "FieldTrialAllocator";
// We allocate 128 KiB to hold all the field trial data. This should be enough,
// as most people use 3 - 25 KiB for field trials (as of 11/25/2016).
// This also doesn't allocate all 128 KiB at once -- the pages only get mapped
// to physical memory when they are touched. If the size of the allocated field
// trials does get larger than 128 KiB, then we will drop some field trials in
// child processes, leading to an inconsistent view between browser and child
// processes and possibly causing crashes (see crbug.com/661617).
const size_t kFieldTrialAllocationSize = 128 << 10; // 128 KiB
// Writes out string1 and then string2 to pickle.
bool WriteStringPair(Pickle* pickle,
const StringPiece& string1,
const StringPiece& string2) {
if (!pickle->WriteString(string1))
return false;
if (!pickle->WriteString(string2))
return false;
return true;
}
// Writes out the field trial's contents (via trial_state) to the pickle. The
// format of the pickle looks like:
// TrialName, GroupName, ParamKey1, ParamValue1, ParamKey2, ParamValue2, ...
// If there are no parameters, then it just ends at GroupName.
bool PickleFieldTrial(const FieldTrial::State& trial_state, Pickle* pickle) {
if (!WriteStringPair(pickle, *trial_state.trial_name,
*trial_state.group_name)) {
return false;
}
// Get field trial params.
std::map<std::string, std::string> params;
FieldTrialParamAssociator::GetInstance()->GetFieldTrialParamsWithoutFallback(
*trial_state.trial_name, *trial_state.group_name, ¶ms);
// Write params to pickle.
for (const auto& param : params) {
if (!WriteStringPair(pickle, param.first, param.second))
return false;
}
return true;
}
// Created a time value based on |year|, |month| and |day_of_month| parameters.
Time CreateTimeFromParams(int year, int month, int day_of_month) {
DCHECK_GT(year, 1970);
DCHECK_GT(month, 0);
DCHECK_LT(month, 13);
DCHECK_GT(day_of_month, 0);
DCHECK_LT(day_of_month, 32);
Time::Exploded exploded;
exploded.year = year;
exploded.month = month;
exploded.day_of_week = 0; // Should be unused.
exploded.day_of_month = day_of_month;
exploded.hour = 0;
exploded.minute = 0;
exploded.second = 0;
exploded.millisecond = 0;
Time out_time;
if (!Time::FromLocalExploded(exploded, &out_time)) {
// TODO(maksims): implement failure handling.
// We might just return |out_time|, which is Time(0).
NOTIMPLEMENTED();
}
return out_time;
}
// Returns the boundary value for comparing against the FieldTrial's added
// groups for a given |divisor| (total probability) and |entropy_value|.
FieldTrial::Probability GetGroupBoundaryValue(
FieldTrial::Probability divisor,
double entropy_value) {
// Add a tiny epsilon value to get consistent results when converting floating
// points to int. Without it, boundary values have inconsistent results, e.g.:
//
// static_cast<FieldTrial::Probability>(100 * 0.56) == 56
// static_cast<FieldTrial::Probability>(100 * 0.57) == 56
// static_cast<FieldTrial::Probability>(100 * 0.58) == 57
// static_cast<FieldTrial::Probability>(100 * 0.59) == 59
const double kEpsilon = 1e-8;
const FieldTrial::Probability result =
static_cast<FieldTrial::Probability>(divisor * entropy_value + kEpsilon);
// Ensure that adding the epsilon still results in a value < |divisor|.
return std::min(result, divisor - 1);
}
// Separate type from FieldTrial::State so that it can use StringPieces.
struct FieldTrialStringEntry {
StringPiece trial_name;
StringPiece group_name;
bool activated = false;
};
// Parses the --force-fieldtrials string |trials_string| into |entries|.
// Returns true if the string was parsed correctly. On failure, the |entries|
// array may end up being partially filled.
bool ParseFieldTrialsString(const std::string& trials_string,
std::vector<FieldTrialStringEntry>* entries) {
const StringPiece trials_string_piece(trials_string);
size_t next_item = 0;
while (next_item < trials_string.length()) {
size_t name_end = trials_string.find(kPersistentStringSeparator, next_item);
if (name_end == trials_string.npos || next_item == name_end)
return false;
size_t group_name_end =
trials_string.find(kPersistentStringSeparator, name_end + 1);
if (name_end + 1 == group_name_end)
return false;
if (group_name_end == trials_string.npos)
group_name_end = trials_string.length();
FieldTrialStringEntry entry;
// Verify if the trial should be activated or not.
if (trials_string[next_item] == kActivationMarker) {
// Name cannot be only the indicator.
if (name_end - next_item == 1)
return false;
next_item++;
entry.activated = true;
}
entry.trial_name =
trials_string_piece.substr(next_item, name_end - next_item);
entry.group_name =
trials_string_piece.substr(name_end + 1, group_name_end - name_end - 1);
next_item = group_name_end + 1;
entries->push_back(std::move(entry));
}
return true;
}
void AddFeatureAndFieldTrialFlags(const char* enable_features_switch,
const char* disable_features_switch,
CommandLine* cmd_line) {
std::string enabled_features;
std::string disabled_features;
FeatureList::GetInstance()->GetFeatureOverrides(&enabled_features,
&disabled_features);
if (!enabled_features.empty())
cmd_line->AppendSwitchASCII(enable_features_switch, enabled_features);
if (!disabled_features.empty())
cmd_line->AppendSwitchASCII(disable_features_switch, disabled_features);
std::string field_trial_states;
FieldTrialList::AllStatesToString(&field_trial_states);
if (!field_trial_states.empty()) {
cmd_line->AppendSwitchASCII(switches::kForceFieldTrials,
field_trial_states);
}
}
void OnOutOfMemory(size_t size) {
#if defined(OS_NACL)
NOTREACHED();
#else
TerminateBecauseOutOfMemory(size);
#endif
}
#if !defined(OS_NACL)
// Returns whether the operation succeeded.
bool DeserializeGUIDFromStringPieces(base::StringPiece first,
base::StringPiece second,
base::UnguessableToken* guid) {
uint64_t high = 0;
uint64_t low = 0;
if (!base::StringToUint64(first, &high) ||
!base::StringToUint64(second, &low)) {
return false;
}
*guid = base::UnguessableToken::Deserialize(high, low);
return true;
}
#endif
} // namespace
// statics
const int FieldTrial::kNotFinalized = -1;
const int FieldTrial::kDefaultGroupNumber = 0;
bool FieldTrial::enable_benchmarking_ = false;
int FieldTrialList::kNoExpirationYear = 0;
//------------------------------------------------------------------------------
// FieldTrial methods and members.
FieldTrial::EntropyProvider::~EntropyProvider() {
}
FieldTrial::State::State() {}
FieldTrial::State::State(const State& other) = default;
FieldTrial::State::~State() {}
bool FieldTrial::FieldTrialEntry::GetTrialAndGroupName(
StringPiece* trial_name,
StringPiece* group_name) const {
PickleIterator iter = GetPickleIterator();
return ReadStringPair(&iter, trial_name, group_name);
}
bool FieldTrial::FieldTrialEntry::GetParams(
std::map<std::string, std::string>* params) const {
PickleIterator iter = GetPickleIterator();
StringPiece tmp;
// Skip reading trial and group name.
if (!ReadStringPair(&iter, &tmp, &tmp))
return false;
while (true) {
StringPiece key;
StringPiece value;
if (!ReadStringPair(&iter, &key, &value))
return key.empty(); // Non-empty is bad: got one of a pair.
(*params)[key.as_string()] = value.as_string();
}
}
PickleIterator FieldTrial::FieldTrialEntry::GetPickleIterator() const {
const char* src =
reinterpret_cast<const char*>(this) + sizeof(FieldTrialEntry);
Pickle pickle(src, pickle_size);
return PickleIterator(pickle);
}
bool FieldTrial::FieldTrialEntry::ReadStringPair(
PickleIterator* iter,
StringPiece* trial_name,
StringPiece* group_name) const {
if (!iter->ReadStringPiece(trial_name))
return false;
if (!iter->ReadStringPiece(group_name))
return false;
return true;
}
void FieldTrial::Disable() {
DCHECK(!group_reported_);
enable_field_trial_ = false;
// In case we are disabled after initialization, we need to switch
// the trial to the default group.
if (group_ != kNotFinalized) {
// Only reset when not already the default group, because in case we were
// forced to the default group, the group number may not be
// kDefaultGroupNumber, so we should keep it as is.
if (group_name_ != default_group_name_)
SetGroupChoice(default_group_name_, kDefaultGroupNumber);
}
}
int FieldTrial::AppendGroup(const std::string& name,
Probability group_probability) {
// When the group choice was previously forced, we only need to return the
// the id of the chosen group, and anything can be returned for the others.
if (forced_) {
DCHECK(!group_name_.empty());
if (name == group_name_) {
// Note that while |group_| may be equal to |kDefaultGroupNumber| on the
// forced trial, it will not have the same value as the default group
// number returned from the non-forced |FactoryGetFieldTrial()| call,
// which takes care to ensure that this does not happen.
return group_;
}
DCHECK_NE(next_group_number_, group_);
// We still return different numbers each time, in case some caller need
// them to be different.
return next_group_number_++;
}
DCHECK_LE(group_probability, divisor_);
DCHECK_GE(group_probability, 0);
if (enable_benchmarking_ || !enable_field_trial_)
group_probability = 0;
accumulated_group_probability_ += group_probability;
DCHECK_LE(accumulated_group_probability_, divisor_);
if (group_ == kNotFinalized && accumulated_group_probability_ > random_) {
// This is the group that crossed the random line, so we do the assignment.
SetGroupChoice(name, next_group_number_);
}
return next_group_number_++;
}
int FieldTrial::group() {
FinalizeGroupChoice();
if (trial_registered_)
FieldTrialList::NotifyFieldTrialGroupSelection(this);
return group_;
}
const std::string& FieldTrial::group_name() {
// Call |group()| to ensure group gets assigned and observers are notified.
group();
DCHECK(!group_name_.empty());
return group_name_;
}
const std::string& FieldTrial::GetGroupNameWithoutActivation() {
FinalizeGroupChoice();
return group_name_;
}
void FieldTrial::SetForced() {
// We might have been forced before (e.g., by CreateFieldTrial) and it's
// first come first served, e.g., command line switch has precedence.
if (forced_)
return;
// And we must finalize the group choice before we mark ourselves as forced.
FinalizeGroupChoice();
forced_ = true;
}
// static
void FieldTrial::EnableBenchmarking() {
DCHECK_EQ(0u, FieldTrialList::GetFieldTrialCount());
enable_benchmarking_ = true;
}
// static
FieldTrial* FieldTrial::CreateSimulatedFieldTrial(
const std::string& trial_name,
Probability total_probability,
const std::string& default_group_name,
double entropy_value) {
return new FieldTrial(trial_name, total_probability, default_group_name,
entropy_value);
}
FieldTrial::FieldTrial(const std::string& trial_name,
const Probability total_probability,
const std::string& default_group_name,
double entropy_value)
: trial_name_(trial_name),
divisor_(total_probability),
default_group_name_(default_group_name),
random_(GetGroupBoundaryValue(total_probability, entropy_value)),
accumulated_group_probability_(0),
next_group_number_(kDefaultGroupNumber + 1),
group_(kNotFinalized),
enable_field_trial_(true),
forced_(false),
group_reported_(false),
trial_registered_(false),
ref_(FieldTrialList::FieldTrialAllocator::kReferenceNull) {
DCHECK_GT(total_probability, 0);
DCHECK(!trial_name_.empty());
DCHECK(!default_group_name_.empty())
<< "Trial " << trial_name << " is missing a default group name.";
}
FieldTrial::~FieldTrial() {}
void FieldTrial::SetTrialRegistered() {
DCHECK_EQ(kNotFinalized, group_);
DCHECK(!trial_registered_);
trial_registered_ = true;
}
void FieldTrial::SetGroupChoice(const std::string& group_name, int number) {
group_ = number;
if (group_name.empty())
StringAppendF(&group_name_, "%d", group_);
else
group_name_ = group_name;
DVLOG(1) << "Field trial: " << trial_name_ << " Group choice:" << group_name_;
}
void FieldTrial::FinalizeGroupChoice() {
FinalizeGroupChoiceImpl(false);
}
void FieldTrial::FinalizeGroupChoiceImpl(bool is_locked) {
if (group_ != kNotFinalized)
return;
accumulated_group_probability_ = divisor_;
// Here it's OK to use |kDefaultGroupNumber| since we can't be forced and not
// finalized.
DCHECK(!forced_);
SetGroupChoice(default_group_name_, kDefaultGroupNumber);
// Add the field trial to shared memory.
if (kUseSharedMemoryForFieldTrials && trial_registered_)
FieldTrialList::OnGroupFinalized(is_locked, this);
}
bool FieldTrial::GetActiveGroup(ActiveGroup* active_group) const {
if (!group_reported_ || !enable_field_trial_)
return false;
DCHECK_NE(group_, kNotFinalized);
active_group->trial_name = trial_name_;
active_group->group_name = group_name_;
return true;
}
bool FieldTrial::GetState(State* field_trial_state) {
if (!enable_field_trial_)
return false;
FinalizeGroupChoice();
field_trial_state->trial_name = &trial_name_;
field_trial_state->group_name = &group_name_;
field_trial_state->activated = group_reported_;
return true;
}
bool FieldTrial::GetStateWhileLocked(State* field_trial_state) {
if (!enable_field_trial_)
return false;
FinalizeGroupChoiceImpl(true);
field_trial_state->trial_name = &trial_name_;
field_trial_state->group_name = &group_name_;
field_trial_state->activated = group_reported_;
return true;
}
//------------------------------------------------------------------------------
// FieldTrialList methods and members.
// static
FieldTrialList* FieldTrialList::global_ = NULL;
// static
bool FieldTrialList::used_without_global_ = false;
FieldTrialList::Observer::~Observer() {
}
FieldTrialList::FieldTrialList(
std::unique_ptr<const FieldTrial::EntropyProvider> entropy_provider)
: entropy_provider_(std::move(entropy_provider)),
observer_list_(new ObserverListThreadSafe<FieldTrialList::Observer>(
ObserverListBase<FieldTrialList::Observer>::NOTIFY_EXISTING_ONLY)) {
DCHECK(!global_);
DCHECK(!used_without_global_);
global_ = this;
Time two_years_from_build_time = GetBuildTime() + TimeDelta::FromDays(730);
Time::Exploded exploded;
two_years_from_build_time.LocalExplode(&exploded);
kNoExpirationYear = exploded.year;
}
FieldTrialList::~FieldTrialList() {
AutoLock auto_lock(lock_);
while (!registered_.empty()) {
RegistrationMap::iterator it = registered_.begin();
it->second->Release();
registered_.erase(it->first);
}
DCHECK_EQ(this, global_);
global_ = NULL;
}
// static
FieldTrial* FieldTrialList::FactoryGetFieldTrial(
const std::string& trial_name,
FieldTrial::Probability total_probability,
const std::string& default_group_name,
const int year,
const int month,
const int day_of_month,
FieldTrial::RandomizationType randomization_type,
int* default_group_number) {
return FactoryGetFieldTrialWithRandomizationSeed(
trial_name, total_probability, default_group_name, year, month,
day_of_month, randomization_type, 0, default_group_number, NULL);
}
// static
FieldTrial* FieldTrialList::FactoryGetFieldTrialWithRandomizationSeed(
const std::string& trial_name,
FieldTrial::Probability total_probability,
const std::string& default_group_name,
const int year,
const int month,
const int day_of_month,
FieldTrial::RandomizationType randomization_type,
uint32_t randomization_seed,
int* default_group_number,
const FieldTrial::EntropyProvider* override_entropy_provider) {
if (default_group_number)
*default_group_number = FieldTrial::kDefaultGroupNumber;
// Check if the field trial has already been created in some other way.
FieldTrial* existing_trial = Find(trial_name);
if (existing_trial) {
CHECK(existing_trial->forced_);
// If the default group name differs between the existing forced trial
// and this trial, then use a different value for the default group number.
if (default_group_number &&
default_group_name != existing_trial->default_group_name()) {
// If the new default group number corresponds to the group that was
// chosen for the forced trial (which has been finalized when it was
// forced), then set the default group number to that.
if (default_group_name == existing_trial->group_name_internal()) {
*default_group_number = existing_trial->group_;
} else {
// Otherwise, use |kNonConflictingGroupNumber| (-2) for the default
// group number, so that it does not conflict with the |AppendGroup()|
// result for the chosen group.
const int kNonConflictingGroupNumber = -2;
static_assert(
kNonConflictingGroupNumber != FieldTrial::kDefaultGroupNumber,
"The 'non-conflicting' group number conflicts");
static_assert(kNonConflictingGroupNumber != FieldTrial::kNotFinalized,
"The 'non-conflicting' group number conflicts");
*default_group_number = kNonConflictingGroupNumber;
}
}
return existing_trial;
}
double entropy_value;
if (randomization_type == FieldTrial::ONE_TIME_RANDOMIZED) {
// If an override entropy provider is given, use it.
const FieldTrial::EntropyProvider* entropy_provider =
override_entropy_provider ? override_entropy_provider
: GetEntropyProviderForOneTimeRandomization();
CHECK(entropy_provider);
entropy_value = entropy_provider->GetEntropyForTrial(trial_name,
randomization_seed);
} else {
DCHECK_EQ(FieldTrial::SESSION_RANDOMIZED, randomization_type);
DCHECK_EQ(0U, randomization_seed);
entropy_value = RandDouble();
}
FieldTrial* field_trial = new FieldTrial(trial_name, total_probability,
default_group_name, entropy_value);
if (GetBuildTime() > CreateTimeFromParams(year, month, day_of_month))
field_trial->Disable();
FieldTrialList::Register(field_trial);
return field_trial;
}
// static
FieldTrial* FieldTrialList::Find(const std::string& trial_name) {
if (!global_)
return NULL;
AutoLock auto_lock(global_->lock_);
return global_->PreLockedFind(trial_name);
}
// static
int FieldTrialList::FindValue(const std::string& trial_name) {
FieldTrial* field_trial = Find(trial_name);
if (field_trial)
return field_trial->group();
return FieldTrial::kNotFinalized;
}
// static
std::string FieldTrialList::FindFullName(const std::string& trial_name) {
FieldTrial* field_trial = Find(trial_name);
if (field_trial)
return field_trial->group_name();
return std::string();
}
// static
bool FieldTrialList::TrialExists(const std::string& trial_name) {
return Find(trial_name) != NULL;
}
// static
bool FieldTrialList::IsTrialActive(const std::string& trial_name) {
FieldTrial* field_trial = Find(trial_name);
FieldTrial::ActiveGroup active_group;
return field_trial && field_trial->GetActiveGroup(&active_group);
}
// static
void FieldTrialList::StatesToString(std::string* output) {
FieldTrial::ActiveGroups active_groups;
GetActiveFieldTrialGroups(&active_groups);
for (FieldTrial::ActiveGroups::const_iterator it = active_groups.begin();
it != active_groups.end(); ++it) {
DCHECK_EQ(std::string::npos,
it->trial_name.find(kPersistentStringSeparator));
DCHECK_EQ(std::string::npos,
it->group_name.find(kPersistentStringSeparator));
output->append(it->trial_name);
output->append(1, kPersistentStringSeparator);
output->append(it->group_name);
output->append(1, kPersistentStringSeparator);
}
}
// static
void FieldTrialList::AllStatesToString(std::string* output) {
if (!global_)
return;
AutoLock auto_lock(global_->lock_);
for (const auto& registered : global_->registered_) {
FieldTrial::State trial;
if (!registered.second->GetStateWhileLocked(&trial))
continue;
DCHECK_EQ(std::string::npos,
trial.trial_name->find(kPersistentStringSeparator));
DCHECK_EQ(std::string::npos,
trial.group_name->find(kPersistentStringSeparator));
if (trial.activated)
output->append(1, kActivationMarker);
output->append(*trial.trial_name);
output->append(1, kPersistentStringSeparator);
output->append(*trial.group_name);
output->append(1, kPersistentStringSeparator);
}
}
// static
void FieldTrialList::GetActiveFieldTrialGroups(
FieldTrial::ActiveGroups* active_groups) {
DCHECK(active_groups->empty());
if (!global_)
return;
AutoLock auto_lock(global_->lock_);
for (RegistrationMap::iterator it = global_->registered_.begin();
it != global_->registered_.end(); ++it) {
FieldTrial::ActiveGroup active_group;
if (it->second->GetActiveGroup(&active_group))
active_groups->push_back(active_group);
}
}
// static
void FieldTrialList::GetActiveFieldTrialGroupsFromString(
const std::string& trials_string,
FieldTrial::ActiveGroups* active_groups) {
std::vector<FieldTrialStringEntry> entries;
if (!ParseFieldTrialsString(trials_string, &entries))
return;
for (const auto& entry : entries) {
if (entry.activated) {
FieldTrial::ActiveGroup group;
group.trial_name = entry.trial_name.as_string();
group.group_name = entry.group_name.as_string();
active_groups->push_back(group);
}
}
}
// static
void FieldTrialList::GetInitiallyActiveFieldTrials(
const base::CommandLine& command_line,
FieldTrial::ActiveGroups* active_groups) {
DCHECK(global_->create_trials_from_command_line_called_);
if (!global_->field_trial_allocator_) {
GetActiveFieldTrialGroupsFromString(
command_line.GetSwitchValueASCII(switches::kForceFieldTrials),
active_groups);
return;
}
FieldTrialAllocator* allocator = global_->field_trial_allocator_.get();
FieldTrialAllocator::Iterator mem_iter(allocator);
const FieldTrial::FieldTrialEntry* entry;
while ((entry = mem_iter.GetNextOfObject<FieldTrial::FieldTrialEntry>()) !=
nullptr) {
StringPiece trial_name;
StringPiece group_name;
if (subtle::NoBarrier_Load(&entry->activated) &&
entry->GetTrialAndGroupName(&trial_name, &group_name)) {
FieldTrial::ActiveGroup group;
group.trial_name = trial_name.as_string();
group.group_name = group_name.as_string();
active_groups->push_back(group);
}
}
}
// static
bool FieldTrialList::CreateTrialsFromString(
const std::string& trials_string,
const std::set<std::string>& ignored_trial_names) {
DCHECK(global_);
if (trials_string.empty() || !global_)
return true;
std::vector<FieldTrialStringEntry> entries;
if (!ParseFieldTrialsString(trials_string, &entries))
return false;
for (const auto& entry : entries) {
const std::string trial_name = entry.trial_name.as_string();
const std::string group_name = entry.group_name.as_string();
if (ContainsKey(ignored_trial_names, trial_name))
continue;
FieldTrial* trial = CreateFieldTrial(trial_name, group_name);
if (!trial)
return false;
if (entry.activated) {
// Call |group()| to mark the trial as "used" and notify observers, if
// any. This is useful to ensure that field trials created in child
// processes are properly reported in crash reports.
trial->group();
}
}
return true;
}
// static
void FieldTrialList::CreateTrialsFromCommandLine(
const CommandLine& cmd_line,
const char* field_trial_handle_switch,
int fd_key) {
global_->create_trials_from_command_line_called_ = true;
#if defined(OS_WIN)
if (cmd_line.HasSwitch(field_trial_handle_switch)) {
std::string switch_value =
cmd_line.GetSwitchValueASCII(field_trial_handle_switch);
bool result = CreateTrialsFromSwitchValue(switch_value);
DCHECK(result);
}
#endif
#if defined(OS_POSIX) && !defined(OS_NACL)
// On POSIX, we check if the handle is valid by seeing if the browser process
// sent over the switch (we don't care about the value). Invalid handles
// occur in some browser tests which don't initialize the allocator.
if (cmd_line.HasSwitch(field_trial_handle_switch)) {
std::string switch_value =
cmd_line.GetSwitchValueASCII(field_trial_handle_switch);
bool result = CreateTrialsFromDescriptor(fd_key, switch_value);
DCHECK(result);
}
#endif
if (cmd_line.HasSwitch(switches::kForceFieldTrials)) {
bool result = FieldTrialList::CreateTrialsFromString(
cmd_line.GetSwitchValueASCII(switches::kForceFieldTrials),
std::set<std::string>());
DCHECK(result);
}
}
// static
void FieldTrialList::CreateFeaturesFromCommandLine(
const base::CommandLine& command_line,
const char* enable_features_switch,
const char* disable_features_switch,
FeatureList* feature_list) {
// Fallback to command line if not using shared memory.
if (!kUseSharedMemoryForFieldTrials ||
!global_->field_trial_allocator_.get()) {
return feature_list->InitializeFromCommandLine(
command_line.GetSwitchValueASCII(enable_features_switch),
command_line.GetSwitchValueASCII(disable_features_switch));
}
feature_list->InitializeFromSharedMemory(
global_->field_trial_allocator_.get());
}
#if defined(OS_WIN)
// static
void FieldTrialList::AppendFieldTrialHandleIfNeeded(
HandlesToInheritVector* handles) {
if (!global_)
return;
if (kUseSharedMemoryForFieldTrials) {
InstantiateFieldTrialAllocatorIfNeeded();
if (global_->readonly_allocator_handle_.IsValid())
handles->push_back(global_->readonly_allocator_handle_.GetHandle());
}
}
#endif
#if defined(OS_POSIX) && !defined(OS_NACL)
// static
SharedMemoryHandle FieldTrialList::GetFieldTrialHandle() {
if (global_ && kUseSharedMemoryForFieldTrials) {
InstantiateFieldTrialAllocatorIfNeeded();
// We check for an invalid handle where this gets called.
return global_->readonly_allocator_handle_;
}
return SharedMemoryHandle();
}
#endif
// static
void FieldTrialList::CopyFieldTrialStateToFlags(
const char* field_trial_handle_switch,
const char* enable_features_switch,
const char* disable_features_switch,
CommandLine* cmd_line) {
// TODO(lawrencewu): Ideally, having the global would be guaranteed. However,
// content browser tests currently don't create a FieldTrialList because they
// don't run ChromeBrowserMainParts code where it's done for Chrome.
// Some tests depend on the enable and disable features flag switch, though,
// so we can still add those even though AllStatesToString() will be a no-op.
if (!global_) {
AddFeatureAndFieldTrialFlags(enable_features_switch,
disable_features_switch, cmd_line);
return;
}
// Use shared memory to pass the state if the feature is enabled, otherwise
// fallback to passing it via the command line as a string.
if (kUseSharedMemoryForFieldTrials) {
InstantiateFieldTrialAllocatorIfNeeded();
// If the readonly handle didn't get duplicated properly, then fallback to
// original behavior.
if (!global_->readonly_allocator_handle_.IsValid()) {
AddFeatureAndFieldTrialFlags(enable_features_switch,
disable_features_switch, cmd_line);
return;
}
global_->field_trial_allocator_->UpdateTrackingHistograms();
std::string switch_value = SerializeSharedMemoryHandleMetadata(
global_->readonly_allocator_handle_);
cmd_line->AppendSwitchASCII(field_trial_handle_switch, switch_value);
return;
}
AddFeatureAndFieldTrialFlags(enable_features_switch, disable_features_switch,
cmd_line);
}
// static
FieldTrial* FieldTrialList::CreateFieldTrial(
const std::string& name,
const std::string& group_name) {
DCHECK(global_);
DCHECK_GE(name.size(), 0u);
DCHECK_GE(group_name.size(), 0u);
if (name.empty() || group_name.empty() || !global_)
return NULL;
FieldTrial* field_trial = FieldTrialList::Find(name);
if (field_trial) {
// In single process mode, or when we force them from the command line,
// we may have already created the field trial.
if (field_trial->group_name_internal() != group_name)
return NULL;
return field_trial;
}
const int kTotalProbability = 100;
field_trial = new FieldTrial(name, kTotalProbability, group_name, 0);
FieldTrialList::Register(field_trial);
// Force the trial, which will also finalize the group choice.
field_trial->SetForced();
return field_trial;
}
// static
void FieldTrialList::AddObserver(Observer* observer) {
if (!global_)
return;
global_->observer_list_->AddObserver(observer);
}
// static
void FieldTrialList::RemoveObserver(Observer* observer) {
if (!global_)
return;
global_->observer_list_->RemoveObserver(observer);
}
// static
void FieldTrialList::OnGroupFinalized(bool is_locked, FieldTrial* field_trial) {
if (!global_)
return;
if (is_locked) {
AddToAllocatorWhileLocked(global_->field_trial_allocator_.get(),
field_trial);
} else {
AutoLock auto_lock(global_->lock_);
AddToAllocatorWhileLocked(global_->field_trial_allocator_.get(),
field_trial);
}
}
// static
void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial* field_trial) {
if (!global_)
return;
{
AutoLock auto_lock(global_->lock_);
if (field_trial->group_reported_)
return;
field_trial->group_reported_ = true;
if (!field_trial->enable_field_trial_)
return;
if (kUseSharedMemoryForFieldTrials)
ActivateFieldTrialEntryWhileLocked(field_trial);
}
// Recording for stability debugging has to be done inline as a task posted
// to an observer may not get executed before a crash.
base::debug::GlobalActivityTracker* tracker =
base::debug::GlobalActivityTracker::Get();
if (tracker) {
tracker->RecordFieldTrial(field_trial->trial_name(),
field_trial->group_name_internal());
}
global_->observer_list_->Notify(
FROM_HERE, &FieldTrialList::Observer::OnFieldTrialGroupFinalized,
field_trial->trial_name(), field_trial->group_name_internal());
}
// static
size_t FieldTrialList::GetFieldTrialCount() {
if (!global_)
return 0;
AutoLock auto_lock(global_->lock_);
return global_->registered_.size();
}
// static
bool FieldTrialList::GetParamsFromSharedMemory(
FieldTrial* field_trial,
std::map<std::string, std::string>* params) {
DCHECK(global_);
// If the field trial allocator is not set up yet, then there are several
// cases:
// - We are in the browser process and the allocator has not been set up
// yet. If we got here, then we couldn't find the params in
// FieldTrialParamAssociator, so it's definitely not here. Return false.
// - Using shared memory for field trials is not enabled. If we got here,
// then there's nothing in shared memory. Return false.
// - We are in the child process and the allocator has not been set up yet.
// If this is the case, then you are calling this too early. The field trial
// allocator should get set up very early in the lifecycle. Try to see if
// you can call it after it's been set up.
AutoLock auto_lock(global_->lock_);
if (!global_->field_trial_allocator_)
return false;
// If ref_ isn't set, then the field trial data can't be in shared memory.
if (!field_trial->ref_)
return false;
const FieldTrial::FieldTrialEntry* entry =
global_->field_trial_allocator_->GetAsObject<FieldTrial::FieldTrialEntry>(
field_trial->ref_);
size_t allocated_size =
global_->field_trial_allocator_->GetAllocSize(field_trial->ref_);
size_t actual_size = sizeof(FieldTrial::FieldTrialEntry) + entry->pickle_size;
if (allocated_size < actual_size)
return false;
return entry->GetParams(params);
}
// static
void FieldTrialList::ClearParamsFromSharedMemoryForTesting() {
if (!global_)
return;
AutoLock auto_lock(global_->lock_);
if (!global_->field_trial_allocator_)
return;
// To clear the params, we iterate through every item in the allocator, copy
// just the trial and group name into a newly-allocated segment and then clear
// the existing item.
FieldTrialAllocator* allocator = global_->field_trial_allocator_.get();
FieldTrialAllocator::Iterator mem_iter(allocator);
// List of refs to eventually be made iterable. We can't make it in the loop,
// since it would go on forever.
std::vector<FieldTrial::FieldTrialRef> new_refs;
FieldTrial::FieldTrialRef prev_ref;
while ((prev_ref = mem_iter.GetNextOfType<FieldTrial::FieldTrialEntry>()) !=
FieldTrialAllocator::kReferenceNull) {
// Get the existing field trial entry in shared memory.
const FieldTrial::FieldTrialEntry* prev_entry =
allocator->GetAsObject<FieldTrial::FieldTrialEntry>(prev_ref);
StringPiece trial_name;
StringPiece group_name;
if (!prev_entry->GetTrialAndGroupName(&trial_name, &group_name))
continue;
// Write a new entry, minus the params.
Pickle pickle;
pickle.WriteString(trial_name);
pickle.WriteString(group_name);
size_t total_size = sizeof(FieldTrial::FieldTrialEntry) + pickle.size();
FieldTrial::FieldTrialEntry* new_entry =
allocator->New<FieldTrial::FieldTrialEntry>(total_size);
subtle::NoBarrier_Store(&new_entry->activated,
subtle::NoBarrier_Load(&prev_entry->activated));
new_entry->pickle_size = pickle.size();
// TODO(lawrencewu): Modify base::Pickle to be able to write over a section
// in memory, so we can avoid this memcpy.
char* dst = reinterpret_cast<char*>(new_entry) +
sizeof(FieldTrial::FieldTrialEntry);
memcpy(dst, pickle.data(), pickle.size());
// Update the ref on the field trial and add it to the list to be made
// iterable.
FieldTrial::FieldTrialRef new_ref = allocator->GetAsReference(new_entry);
FieldTrial* trial = global_->PreLockedFind(trial_name.as_string());
trial->ref_ = new_ref;
new_refs.push_back(new_ref);
// Mark the existing entry as unused.
allocator->ChangeType(prev_ref, 0,
FieldTrial::FieldTrialEntry::kPersistentTypeId,
/*clear=*/false);
}
for (const auto& ref : new_refs) {
allocator->MakeIterable(ref);
}
}
// static
void FieldTrialList::DumpAllFieldTrialsToPersistentAllocator(
PersistentMemoryAllocator* allocator) {
if (!global_)
return;
AutoLock auto_lock(global_->lock_);
for (const auto& registered : global_->registered_) {
AddToAllocatorWhileLocked(allocator, registered.second);
}
}
// static
std::vector<const FieldTrial::FieldTrialEntry*>
FieldTrialList::GetAllFieldTrialsFromPersistentAllocator(
PersistentMemoryAllocator const& allocator) {
std::vector<const FieldTrial::FieldTrialEntry*> entries;
FieldTrialAllocator::Iterator iter(&allocator);
const FieldTrial::FieldTrialEntry* entry;
while ((entry = iter.GetNextOfObject<FieldTrial::FieldTrialEntry>()) !=
nullptr) {
entries.push_back(entry);
}
return entries;
}
// static
std::string FieldTrialList::SerializeSharedMemoryHandleMetadata(
const SharedMemoryHandle& shm) {
std::stringstream ss;
#if defined(OS_WIN)
// Tell the child process the name of the inherited HANDLE.
uintptr_t uintptr_handle = reinterpret_cast<uintptr_t>(shm.GetHandle());
ss << uintptr_handle << ",";
#elif !defined(OS_POSIX)
#error Unsupported OS
#endif
base::UnguessableToken guid = shm.GetGUID();
ss << guid.GetHighForSerialization() << "," << guid.GetLowForSerialization();
ss << "," << shm.GetSize();
return ss.str();
}
#if defined(OS_WIN)
// static
SharedMemoryHandle FieldTrialList::DeserializeSharedMemoryHandleMetadata(
const std::string& switch_value) {
std::vector<base::StringPiece> tokens = base::SplitStringPiece(
switch_value, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
if (tokens.size() != 4)
return SharedMemoryHandle();
int field_trial_handle = 0;
if (!base::StringToInt(tokens[0], &field_trial_handle))
return SharedMemoryHandle();
HANDLE handle = reinterpret_cast<HANDLE>(field_trial_handle);
base::UnguessableToken guid;
if (!DeserializeGUIDFromStringPieces(tokens[1], tokens[2], &guid))
return SharedMemoryHandle();
int size;
if (!base::StringToInt(tokens[3], &size))
return SharedMemoryHandle();
return SharedMemoryHandle(handle, static_cast<size_t>(size), guid);
}
#endif // defined(OS_WIN)
#if defined(OS_POSIX) && !defined(OS_NACL)
// static
SharedMemoryHandle FieldTrialList::DeserializeSharedMemoryHandleMetadata(
int fd,
const std::string& switch_value) {
std::vector<base::StringPiece> tokens = base::SplitStringPiece(
switch_value, ",", base::KEEP_WHITESPACE, base::SPLIT_WANT_ALL);
if (tokens.size() != 3)
return SharedMemoryHandle();
base::UnguessableToken guid;
if (!DeserializeGUIDFromStringPieces(tokens[0], tokens[1], &guid))
return SharedMemoryHandle();
int size;
if (!base::StringToInt(tokens[2], &size))
return SharedMemoryHandle();
return SharedMemoryHandle(FileDescriptor(fd, true), static_cast<size_t>(size),
guid);
}
#endif // defined(OS_POSIX) && !defined(OS_NACL)
#if defined(OS_WIN)
// static
bool FieldTrialList::CreateTrialsFromSwitchValue(
const std::string& switch_value) {
SharedMemoryHandle shm = DeserializeSharedMemoryHandleMetadata(switch_value);
if (!shm.IsValid())
return false;
return FieldTrialList::CreateTrialsFromSharedMemoryHandle(shm);
}
#endif // defined(OS_WIN)
#if defined(OS_POSIX) && !defined(OS_NACL)
// static
bool FieldTrialList::CreateTrialsFromDescriptor(
int fd_key,
const std::string& switch_value) {
if (!kUseSharedMemoryForFieldTrials)
return false;
if (fd_key == -1)
return false;
int fd = GlobalDescriptors::GetInstance()->MaybeGet(fd_key);
if (fd == -1)
return false;
SharedMemoryHandle shm =
DeserializeSharedMemoryHandleMetadata(fd, switch_value);
if (!shm.IsValid())
return false;
bool result = FieldTrialList::CreateTrialsFromSharedMemoryHandle(shm);
DCHECK(result);
return true;
}
#endif // defined(OS_POSIX) && !defined(OS_NACL)
// static
bool FieldTrialList::CreateTrialsFromSharedMemoryHandle(
SharedMemoryHandle shm_handle) {
// shm gets deleted when it gets out of scope, but that's OK because we need
// it only for the duration of this method.
std::unique_ptr<SharedMemory> shm(new SharedMemory(shm_handle, true));
if (!shm.get()->Map(kFieldTrialAllocationSize))
OnOutOfMemory(kFieldTrialAllocationSize);
return FieldTrialList::CreateTrialsFromSharedMemory(std::move(shm));
}
// static
bool FieldTrialList::CreateTrialsFromSharedMemory(
std::unique_ptr<SharedMemory> shm) {
global_->field_trial_allocator_.reset(
new FieldTrialAllocator(std::move(shm), 0, kAllocatorName, true));
FieldTrialAllocator* shalloc = global_->field_trial_allocator_.get();
FieldTrialAllocator::Iterator mem_iter(shalloc);
const FieldTrial::FieldTrialEntry* entry;
while ((entry = mem_iter.GetNextOfObject<FieldTrial::FieldTrialEntry>()) !=
nullptr) {
StringPiece trial_name;
StringPiece group_name;
if (!entry->GetTrialAndGroupName(&trial_name, &group_name))
return false;
// TODO(lawrencewu): Convert the API for CreateFieldTrial to take
// StringPieces.
FieldTrial* trial =
CreateFieldTrial(trial_name.as_string(), group_name.as_string());
trial->ref_ = mem_iter.GetAsReference(entry);
if (subtle::NoBarrier_Load(&entry->activated)) {
// Call |group()| to mark the trial as "used" and notify observers, if
// any. This is useful to ensure that field trials created in child
// processes are properly reported in crash reports.
trial->group();
}
}
return true;
}
// static
void FieldTrialList::InstantiateFieldTrialAllocatorIfNeeded() {
if (!global_)
return;
AutoLock auto_lock(global_->lock_);
// Create the allocator if not already created and add all existing trials.
if (global_->field_trial_allocator_ != nullptr)
return;
SharedMemoryCreateOptions options;
options.size = kFieldTrialAllocationSize;
options.share_read_only = true;
#if defined(OS_MACOSX) && !defined(OS_IOS)
options.type = SharedMemoryHandle::POSIX;
#endif
std::unique_ptr<SharedMemory> shm(new SharedMemory());
if (!shm->Create(options)) {
#if !defined(OS_NACL)
// Temporary for http://crbug.com/703649.
base::debug::ScopedCrashKey crash_key(
"field_trial_shmem_create_error",
base::IntToString(static_cast<int>(shm->get_last_error())));
#endif
OnOutOfMemory(kFieldTrialAllocationSize);
}
if (!shm->Map(kFieldTrialAllocationSize)) {
#if !defined(OS_NACL)
// Temporary for http://crbug.com/703649.
base::debug::ScopedCrashKey crash_key(
"field_trial_shmem_map_error",
base::IntToString(static_cast<int>(shm->get_last_error())));
#endif
OnOutOfMemory(kFieldTrialAllocationSize);
}
global_->field_trial_allocator_.reset(
new FieldTrialAllocator(std::move(shm), 0, kAllocatorName, false));
global_->field_trial_allocator_->CreateTrackingHistograms(kAllocatorName);
// Add all existing field trials.
for (const auto& registered : global_->registered_) {
AddToAllocatorWhileLocked(global_->field_trial_allocator_.get(),
registered.second);
}
// Add all existing features.
FeatureList::GetInstance()->AddFeaturesToAllocator(
global_->field_trial_allocator_.get());
#if !defined(OS_NACL)
// Set |readonly_allocator_handle_| so we can pass it to be inherited and
// via the command line.
global_->readonly_allocator_handle_ =
global_->field_trial_allocator_->shared_memory()->GetReadOnlyHandle();
#endif
}
// static
void FieldTrialList::AddToAllocatorWhileLocked(
PersistentMemoryAllocator* allocator,
FieldTrial* field_trial) {
// Don't do anything if the allocator hasn't been instantiated yet.
if (allocator == nullptr)
return;
// Or if the allocator is read only, which means we are in a child process and
// shouldn't be writing to it.
if (allocator->IsReadonly())
return;
FieldTrial::State trial_state;
if (!field_trial->GetStateWhileLocked(&trial_state))
return;
// Or if we've already added it. We must check after GetState since it can
// also add to the allocator.
if (field_trial->ref_)
return;
Pickle pickle;
if (!PickleFieldTrial(trial_state, &pickle)) {
NOTREACHED();
return;
}
size_t total_size = sizeof(FieldTrial::FieldTrialEntry) + pickle.size();
FieldTrial::FieldTrialRef ref = allocator->Allocate(
total_size, FieldTrial::FieldTrialEntry::kPersistentTypeId);
if (ref == FieldTrialAllocator::kReferenceNull) {
NOTREACHED();
return;
}
FieldTrial::FieldTrialEntry* entry =
allocator->GetAsObject<FieldTrial::FieldTrialEntry>(ref);
subtle::NoBarrier_Store(&entry->activated, trial_state.activated);
entry->pickle_size = pickle.size();
// TODO(lawrencewu): Modify base::Pickle to be able to write over a section in
// memory, so we can avoid this memcpy.
char* dst =
reinterpret_cast<char*>(entry) + sizeof(FieldTrial::FieldTrialEntry);
memcpy(dst, pickle.data(), pickle.size());
allocator->MakeIterable(ref);
field_trial->ref_ = ref;
}
// static
void FieldTrialList::ActivateFieldTrialEntryWhileLocked(
FieldTrial* field_trial) {
FieldTrialAllocator* allocator = global_->field_trial_allocator_.get();
// Check if we're in the child process and return early if so.
if (allocator && allocator->IsReadonly())
return;
FieldTrial::FieldTrialRef ref = field_trial->ref_;
if (ref == FieldTrialAllocator::kReferenceNull) {
// It's fine to do this even if the allocator hasn't been instantiated
// yet -- it'll just return early.
AddToAllocatorWhileLocked(global_->field_trial_allocator_.get(),
field_trial);
} else {
// It's also okay to do this even though the callee doesn't have a lock --
// the only thing that happens on a stale read here is a slight performance
// hit from the child re-synchronizing activation state.
FieldTrial::FieldTrialEntry* entry =
allocator->GetAsObject<FieldTrial::FieldTrialEntry>(ref);
subtle::NoBarrier_Store(&entry->activated, 1);
}
}
// static
const FieldTrial::EntropyProvider*
FieldTrialList::GetEntropyProviderForOneTimeRandomization() {
if (!global_) {
used_without_global_ = true;
return NULL;
}
return global_->entropy_provider_.get();
}
FieldTrial* FieldTrialList::PreLockedFind(const std::string& name) {
RegistrationMap::iterator it = registered_.find(name);
if (registered_.end() == it)
return NULL;
return it->second;
}
// static
void FieldTrialList::Register(FieldTrial* trial) {
if (!global_) {
used_without_global_ = true;
return;
}
AutoLock auto_lock(global_->lock_);
CHECK(!global_->PreLockedFind(trial->trial_name())) << trial->trial_name();
trial->AddRef();
trial->SetTrialRegistered();
global_->registered_[trial->trial_name()] = trial;
}
} // namespace base
|