Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(276)

Side by Side Diff: base/metrics/field_trial.cc

Issue 2412113002: Use SharedPersistentMemoryAllocator to share field trial state (Closed)
Patch Set: add lock Created 4 years, 2 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include "base/metrics/field_trial.h" 5 #include "base/metrics/field_trial.h"
6 6
7 #include <algorithm> 7 #include <algorithm>
8 #include <utility> 8 #include <utility>
9 9
10 #include "base/base_switches.h" 10 #include "base/base_switches.h"
(...skipping 17 matching lines...) Expand all
28 const char kPersistentStringSeparator = '/'; // Currently a slash. 28 const char kPersistentStringSeparator = '/'; // Currently a slash.
29 29
30 // Define a marker character to be used as a prefix to a trial name on the 30 // Define a marker character to be used as a prefix to a trial name on the
31 // command line which forces its activation. 31 // command line which forces its activation.
32 const char kActivationMarker = '*'; 32 const char kActivationMarker = '*';
33 33
34 // Use shared memory to communicate field trial (experiment) state. Set to false 34 // Use shared memory to communicate field trial (experiment) state. Set to false
35 // for now while the implementation is fleshed out (e.g. data format, single 35 // for now while the implementation is fleshed out (e.g. data format, single
36 // shared memory segment). See https://codereview.chromium.org/2365273004/ and 36 // shared memory segment). See https://codereview.chromium.org/2365273004/ and
37 // crbug.com/653874 37 // crbug.com/653874
38 #if defined(OS_WIN)
39 const bool kUseSharedMemoryForFieldTrials = false; 38 const bool kUseSharedMemoryForFieldTrials = false;
40 #endif 39
40 // Constants for the field trial allocator.
41 const char kAllocatorName[] = "FieldTrialAllocator";
42 const uint32_t kFieldTrialType = 0xABA17E13 + 1; // SHA1(FieldTrialEntry) v1
43
44 // We create one FieldTrialEntry struct per field trial in shared memory (via
45 // field_trial_allocator). It contains whether or not it's activated, and the
46 // offset from the start of the allocated memory to the group name. We don't
47 // need the offset into the trial name because that's always a fixed position
48 // from the start of the struct. Two strings will be appended to the end of this
49 // structure in allocated memory, so the result will look like this:
50 // ---------------------------------
51 // | fte | trial_name | group_name |
52 // ---------------------------------
53 struct FieldTrialEntry {
54 bool activated;
55 uint32_t group_name_offset;
56
57 const char* GetTrialName() const {
58 const char* src =
59 reinterpret_cast<char*>(const_cast<FieldTrialEntry*>(this));
60 return src + sizeof(FieldTrialEntry);
61 }
62
63 const char* GetGroupName() const {
64 const char* src =
65 reinterpret_cast<char*>(const_cast<FieldTrialEntry*>(this));
66 return src + this->group_name_offset;
67 }
68 };
41 69
42 // Created a time value based on |year|, |month| and |day_of_month| parameters. 70 // Created a time value based on |year|, |month| and |day_of_month| parameters.
43 Time CreateTimeFromParams(int year, int month, int day_of_month) { 71 Time CreateTimeFromParams(int year, int month, int day_of_month) {
44 DCHECK_GT(year, 1970); 72 DCHECK_GT(year, 1970);
45 DCHECK_GT(month, 0); 73 DCHECK_GT(month, 0);
46 DCHECK_LT(month, 13); 74 DCHECK_LT(month, 13);
47 DCHECK_GT(day_of_month, 0); 75 DCHECK_GT(day_of_month, 0);
48 DCHECK_LT(day_of_month, 32); 76 DCHECK_LT(day_of_month, 32);
49 77
50 Time::Exploded exploded; 78 Time::Exploded exploded;
(...skipping 71 matching lines...) Expand 10 before | Expand all | Expand 10 after
122 entries->push_back(entry); 150 entries->push_back(entry);
123 } 151 }
124 return true; 152 return true;
125 } 153 }
126 154
127 } // namespace 155 } // namespace
128 156
129 // statics 157 // statics
130 const int FieldTrial::kNotFinalized = -1; 158 const int FieldTrial::kNotFinalized = -1;
131 const int FieldTrial::kDefaultGroupNumber = 0; 159 const int FieldTrial::kDefaultGroupNumber = 0;
160 const int kFieldTrialAllocationSize = 4 << 10; // 4 KiB = one page
132 bool FieldTrial::enable_benchmarking_ = false; 161 bool FieldTrial::enable_benchmarking_ = false;
133 162
134 int FieldTrialList::kNoExpirationYear = 0; 163 int FieldTrialList::kNoExpirationYear = 0;
135 164
136 //------------------------------------------------------------------------------ 165 //------------------------------------------------------------------------------
137 // FieldTrial methods and members. 166 // FieldTrial methods and members.
138 167
139 FieldTrial::EntropyProvider::~EntropyProvider() { 168 FieldTrial::EntropyProvider::~EntropyProvider() {
140 } 169 }
141 170
(...skipping 183 matching lines...) Expand 10 before | Expand all | Expand 10 after
325 observer_list_(new ObserverListThreadSafe<FieldTrialList::Observer>( 354 observer_list_(new ObserverListThreadSafe<FieldTrialList::Observer>(
326 ObserverListBase<FieldTrialList::Observer>::NOTIFY_EXISTING_ONLY)) { 355 ObserverListBase<FieldTrialList::Observer>::NOTIFY_EXISTING_ONLY)) {
327 DCHECK(!global_); 356 DCHECK(!global_);
328 DCHECK(!used_without_global_); 357 DCHECK(!used_without_global_);
329 global_ = this; 358 global_ = this;
330 359
331 Time two_years_from_build_time = GetBuildTime() + TimeDelta::FromDays(730); 360 Time two_years_from_build_time = GetBuildTime() + TimeDelta::FromDays(730);
332 Time::Exploded exploded; 361 Time::Exploded exploded;
333 two_years_from_build_time.LocalExplode(&exploded); 362 two_years_from_build_time.LocalExplode(&exploded);
334 kNoExpirationYear = exploded.year; 363 kNoExpirationYear = exploded.year;
364
365 field_trial_allocator = nullptr;
366 #if defined(OS_WIN)
367 readonly_allocator_handle = 0;
368 #endif
335 } 369 }
336 370
337 FieldTrialList::~FieldTrialList() { 371 FieldTrialList::~FieldTrialList() {
338 AutoLock auto_lock(lock_); 372 AutoLock auto_lock(lock_);
339 while (!registered_.empty()) { 373 while (!registered_.empty()) {
340 RegistrationMap::iterator it = registered_.begin(); 374 RegistrationMap::iterator it = registered_.begin();
341 it->second->Release(); 375 it->second->Release();
342 registered_.erase(it->first); 376 registered_.erase(it->first);
343 } 377 }
344 DCHECK_EQ(this, global_); 378 DCHECK_EQ(this, global_);
(...skipping 234 matching lines...) Expand 10 before | Expand all | Expand 10 after
579 std::string arg = cmd_line.GetSwitchValueASCII(field_trial_handle_switch); 613 std::string arg = cmd_line.GetSwitchValueASCII(field_trial_handle_switch);
580 size_t token = arg.find(","); 614 size_t token = arg.find(",");
581 int field_trial_handle = std::stoi(arg.substr(0, token)); 615 int field_trial_handle = std::stoi(arg.substr(0, token));
582 int field_trial_length = std::stoi(arg.substr(token + 1, arg.length())); 616 int field_trial_length = std::stoi(arg.substr(token + 1, arg.length()));
583 617
584 HANDLE handle = reinterpret_cast<HANDLE>(field_trial_handle); 618 HANDLE handle = reinterpret_cast<HANDLE>(field_trial_handle);
585 base::SharedMemoryHandle shm_handle = 619 base::SharedMemoryHandle shm_handle =
586 base::SharedMemoryHandle(handle, base::GetCurrentProcId()); 620 base::SharedMemoryHandle(handle, base::GetCurrentProcId());
587 621
588 // Gets deleted when it gets out of scope, but that's OK because we need it 622 // Gets deleted when it gets out of scope, but that's OK because we need it
589 // only for the duration of this call currently anyway. 623 // only for the duration of this method.
590 base::SharedMemory shared_memory(shm_handle, false); 624 std::unique_ptr<base::SharedMemory> shm(
591 shared_memory.Map(field_trial_length); 625 new base::SharedMemory(shm_handle, true));
592 626 if (shm.get()->Map(field_trial_length))
Alexei Svitkine (slow) 2016/10/21 18:20:26 I think we should treat this failure as fatal (i.e
lawrencewu 2016/10/21 20:23:13 Done.
593 char* field_trial_state = static_cast<char*>(shared_memory.memory()); 627 FieldTrialList::CreateTrialsFromSharedMemory(std::move(shm));
594 bool result = FieldTrialList::CreateTrialsFromString(
595 std::string(field_trial_state), std::set<std::string>());
596 DCHECK(result);
597 return; 628 return;
598 } 629 }
599 #endif 630 #endif
600 631
601 if (cmd_line.HasSwitch(switches::kForceFieldTrials)) { 632 if (cmd_line.HasSwitch(switches::kForceFieldTrials)) {
602 bool result = FieldTrialList::CreateTrialsFromString( 633 bool result = FieldTrialList::CreateTrialsFromString(
603 cmd_line.GetSwitchValueASCII(switches::kForceFieldTrials), 634 cmd_line.GetSwitchValueASCII(switches::kForceFieldTrials),
604 std::set<std::string>()); 635 std::set<std::string>());
605 DCHECK(result); 636 DCHECK(result);
606 } 637 }
607 } 638 }
608 639
640 #if defined(OS_WIN)
641 // static
642 void FieldTrialList::AppendFieldTrialHandleIfNeeded(
643 base::HandlesToInheritVector* handles) {
644 FieldTrialList::InstantiateFieldTrialAllocatorIfNeeded();
645
646 // Need to get a new, read-only handle to share to the child.
647 handles->push_back(global_->readonly_allocator_handle);
648 }
649 #endif
650
651 // static
652 void FieldTrialList::CreateTrialsFromSharedMemory(
653 std::unique_ptr<base::SharedMemory> shm) {
654 const base::SharedPersistentMemoryAllocator shalloc(std::move(shm), 0,
655 kAllocatorName, true);
656 base::PersistentMemoryAllocator::Iterator iter(&shalloc);
657
658 base::SharedPersistentMemoryAllocator::Reference ref;
659 while ((ref = iter.GetNextOfType(kFieldTrialType)) !=
660 base::SharedPersistentMemoryAllocator::kReferenceNull) {
661 const FieldTrialEntry* entry =
662 shalloc.GetAsObject<const FieldTrialEntry>(ref, kFieldTrialType);
663 FieldTrial* trial =
664 CreateFieldTrial(entry->GetTrialName(), entry->GetGroupName());
665
666 if (entry->activated) {
667 // Call |group()| to mark the trial as "used" and notify observers, if
668 // any. This is useful to ensure that field trials created in child
669 // processes are properly reported in crash reports.
670 trial->group();
671 }
672 }
673 }
674
609 // static 675 // static
610 std::unique_ptr<base::SharedMemory> FieldTrialList::CopyFieldTrialStateToFlags( 676 void FieldTrialList::CopyFieldTrialStateToFlags(
611 const char* field_trial_handle_switch, 677 const char* field_trial_handle_switch,
612 base::CommandLine* cmd_line) { 678 base::CommandLine* cmd_line) {
679 #if defined(OS_WIN)
680 // Use shared memory to pass the state if the feature is enabled, otherwise
681 // fallback to passing it via the command line as a string.
682 if (kUseSharedMemoryForFieldTrials) {
683 FieldTrialList::InstantiateFieldTrialAllocatorIfNeeded();
684 // HANDLE is just typedef'd to void *. We basically cast the handle into an
685 // int (uintptr_t, to be exact), stringify the int, and pass it as a
686 // command-line flag. The child process will do the reverse conversions to
687 // retrieve the handle. See http://stackoverflow.com/a/153077
688 auto uintptr_handle =
689 reinterpret_cast<uintptr_t>(global_->readonly_allocator_handle);
690 size_t field_trial_length =
691 global_->field_trial_allocator->shared_memory()->mapped_size();
692 std::string field_trial_handle = std::to_string(uintptr_handle) + "," +
693 std::to_string(field_trial_length);
694
695 cmd_line->AppendSwitchASCII(field_trial_handle_switch, field_trial_handle);
696 return;
697 }
698 #endif
699
613 std::string field_trial_states; 700 std::string field_trial_states;
614 base::FieldTrialList::AllStatesToString(&field_trial_states); 701 base::FieldTrialList::AllStatesToString(&field_trial_states);
615 if (!field_trial_states.empty()) { 702 if (!field_trial_states.empty()) {
616 // Use shared memory to pass the state if the feature is enabled, otherwise
617 // fallback to passing it via the command line as a string.
618 #if defined(OS_WIN)
619 if (kUseSharedMemoryForFieldTrials) {
620 std::unique_ptr<base::SharedMemory> shm(new base::SharedMemory());
621 size_t length = field_trial_states.size() + 1;
622 shm->CreateAndMapAnonymous(length);
623 memcpy(shm->memory(), field_trial_states.c_str(), length);
624
625 // HANDLE is just typedef'd to void *
626 auto uintptr_handle =
627 reinterpret_cast<std::uintptr_t>(shm->handle().GetHandle());
628 std::string field_trial_handle =
629 std::to_string(uintptr_handle) + "," + std::to_string(length);
630
631 cmd_line->AppendSwitchASCII(field_trial_handle_switch,
632 field_trial_handle);
633 return shm;
634 }
635 #endif
636 cmd_line->AppendSwitchASCII(switches::kForceFieldTrials, 703 cmd_line->AppendSwitchASCII(switches::kForceFieldTrials,
637 field_trial_states); 704 field_trial_states);
638 } 705 }
639 return std::unique_ptr<base::SharedMemory>(nullptr);
640 } 706 }
641 707
642 // static 708 // static
643 FieldTrial* FieldTrialList::CreateFieldTrial( 709 FieldTrial* FieldTrialList::CreateFieldTrial(
644 const std::string& name, 710 const std::string& name,
645 const std::string& group_name) { 711 const std::string& group_name) {
646 DCHECK(global_); 712 DCHECK(global_);
647 DCHECK_GE(name.size(), 0u); 713 DCHECK_GE(name.size(), 0u);
648 DCHECK_GE(group_name.size(), 0u); 714 DCHECK_GE(group_name.size(), 0u);
649 if (name.empty() || group_name.empty() || !global_) 715 if (name.empty() || group_name.empty() || !global_)
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
682 // static 748 // static
683 void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial* field_trial) { 749 void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial* field_trial) {
684 if (!global_) 750 if (!global_)
685 return; 751 return;
686 752
687 { 753 {
688 AutoLock auto_lock(global_->lock_); 754 AutoLock auto_lock(global_->lock_);
689 if (field_trial->group_reported_) 755 if (field_trial->group_reported_)
690 return; 756 return;
691 field_trial->group_reported_ = true; 757 field_trial->group_reported_ = true;
758
759 if (!field_trial->enable_field_trial_)
760 return;
761
762 if (kUseSharedMemoryForFieldTrials) {
Alexei Svitkine (slow) 2016/10/21 18:20:26 Nit: No {}'s for 1-line ifs.
lawrencewu 2016/10/21 20:23:13 Done.
763 FieldTrialList::UpdateFieldTrialAllocatorWhileLocked(field_trial);
764 }
692 } 765 }
693 766
694 if (!field_trial->enable_field_trial_)
695 return;
696
697 global_->observer_list_->Notify( 767 global_->observer_list_->Notify(
698 FROM_HERE, &FieldTrialList::Observer::OnFieldTrialGroupFinalized, 768 FROM_HERE, &FieldTrialList::Observer::OnFieldTrialGroupFinalized,
699 field_trial->trial_name(), field_trial->group_name_internal()); 769 field_trial->trial_name(), field_trial->group_name_internal());
700 } 770 }
701 771
702 // static 772 // static
773 void FieldTrialList::InstantiateFieldTrialAllocatorIfNeeded() {
774 AutoLock auto_lock(global_->lock_);
775 // Create the allocator if not already created and add all existing trials.
776 if (global_->field_trial_allocator == nullptr) {
Alexei Svitkine (slow) 2016/10/21 18:20:26 Nit: Change this to != and an early return
lawrencewu 2016/10/21 20:23:13 Done.
777 std::unique_ptr<base::SharedMemory> shm(new base::SharedMemory());
778 shm->CreateAndMapAnonymous(kFieldTrialAllocationSize);
779
780 // TODO(lawrencewu): call UpdateTrackingHistograms() when all field trials
781 // have been registered (perhaps in the destructor?)
782 global_->field_trial_allocator.reset(
783 new base::SharedPersistentMemoryAllocator(std::move(shm), 0,
784 kAllocatorName, false));
785 global_->field_trial_allocator->CreateTrackingHistograms(kAllocatorName);
786
787 // Add all existing field trials.
788 for (const auto& registered : global_->registered_) {
789 FieldTrialList::UpdateFieldTrialAllocatorWhileLocked(registered.second);
790 }
791
792 #if defined(OS_WIN)
793 // Duplicate and set |readonly_allocator_handle| so we can pass it to be
794 // inherited and via the command line.
795 HANDLE src =
Alexei Svitkine (slow) 2016/10/21 18:20:26 Can you make a helper function for this in the ano
lawrencewu 2016/10/21 20:23:13 Done.
796 global_->field_trial_allocator->shared_memory()->handle().GetHandle();
797 ProcessHandle process = GetCurrentProcess();
798 DWORD access = SECTION_MAP_READ | SECTION_QUERY;
799 ::DuplicateHandle(process, src, process,
800 &(global_->readonly_allocator_handle), access, true, 0);
Alexei Svitkine (slow) 2016/10/21 18:20:26 Nit: No need for ()'s
lawrencewu 2016/10/21 20:23:13 Acknowledged but don't need this anymore.
801 #endif
802 }
803 }
804
805 // static
806 void FieldTrialList::UpdateFieldTrialAllocatorWhileLocked(
807 FieldTrial* field_trial) {
Alexei Svitkine (slow) 2016/10/21 18:20:26 Sorry for going back and forth on this, but how ab
lawrencewu 2016/10/21 20:23:13 Done.
808 // Don't do anything if the allocator hasn't been instantiated yet.
809 if (global_->field_trial_allocator == nullptr)
810 return;
811
812 // We allocate just enough memory to fit the FTE struct, trial name, and group
813 // name. If there's no more memory available, quit early.
814 FieldTrial::State trial_state;
815 field_trial->GetState(&trial_state);
816
817 std::string trial_name;
818 trial_state.trial_name.CopyToString(&trial_name);
819 size_t trial_name_size = trial_name.size() + 1;
820
821 std::string group_name;
822 trial_state.group_name.CopyToString(&group_name);
823 size_t group_name_size = group_name.size() + 1;
824
825 uint32_t trial_name_offset = sizeof(FieldTrialEntry);
826 uint32_t group_name_offset = trial_name_offset + trial_name_size;
827 size_t size = sizeof(FieldTrialEntry) + trial_name_size + group_name_size;
828
829 base::SharedPersistentMemoryAllocator::Reference ref =
830 global_->field_trial_allocator->Allocate(size, kFieldTrialType);
831 if (ref == base::SharedPersistentMemoryAllocator::kReferenceNull)
832 return;
833
834 FieldTrialEntry* dst =
835 global_->field_trial_allocator->GetAsObject<FieldTrialEntry>(
836 ref, kFieldTrialType);
837 FieldTrialEntry entry = {trial_state.activated, group_name_offset};
838 *dst = entry;
839 memcpy(reinterpret_cast<char*>(dst) + trial_name_offset, trial_name.c_str(),
840 trial_name_size);
841 memcpy(reinterpret_cast<char*>(dst) + group_name_offset, group_name.c_str(),
842 group_name_size);
843
844 global_->field_trial_allocator->MakeIterable(ref);
845 }
846
847 // static
703 size_t FieldTrialList::GetFieldTrialCount() { 848 size_t FieldTrialList::GetFieldTrialCount() {
704 if (!global_) 849 if (!global_)
705 return 0; 850 return 0;
706 AutoLock auto_lock(global_->lock_); 851 AutoLock auto_lock(global_->lock_);
707 return global_->registered_.size(); 852 return global_->registered_.size();
708 } 853 }
709 854
710 // static 855 // static
711 const FieldTrial::EntropyProvider* 856 const FieldTrial::EntropyProvider*
712 FieldTrialList::GetEntropyProviderForOneTimeRandomization() { 857 FieldTrialList::GetEntropyProviderForOneTimeRandomization() {
(...skipping 19 matching lines...) Expand all
732 return; 877 return;
733 } 878 }
734 AutoLock auto_lock(global_->lock_); 879 AutoLock auto_lock(global_->lock_);
735 CHECK(!global_->PreLockedFind(trial->trial_name())) << trial->trial_name(); 880 CHECK(!global_->PreLockedFind(trial->trial_name())) << trial->trial_name();
736 trial->AddRef(); 881 trial->AddRef();
737 trial->SetTrialRegistered(); 882 trial->SetTrialRegistered();
738 global_->registered_[trial->trial_name()] = trial; 883 global_->registered_[trial->trial_name()] = trial;
739 } 884 }
740 885
741 } // namespace base 886 } // namespace base
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698