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