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

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

Issue 2412113002: Use SharedPersistentMemoryAllocator to share field trial state (Closed)
Patch Set: gclient sync Created 4 years, 1 month 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
« no previous file with comments | « base/metrics/field_trial.h ('k') | base/metrics/field_trial_unittest.cc » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
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"
11 #include "base/build_time.h" 11 #include "base/build_time.h"
12 #include "base/command_line.h" 12 #include "base/command_line.h"
13 #include "base/feature_list.h" 13 #include "base/feature_list.h"
14 #include "base/logging.h" 14 #include "base/logging.h"
15 #include "base/process/memory.h"
15 #include "base/rand_util.h" 16 #include "base/rand_util.h"
16 #include "base/strings/string_number_conversions.h" 17 #include "base/strings/string_number_conversions.h"
17 #include "base/strings/string_util.h" 18 #include "base/strings/string_util.h"
18 #include "base/strings/stringprintf.h" 19 #include "base/strings/stringprintf.h"
19 #include "base/strings/utf_string_conversions.h" 20 #include "base/strings/utf_string_conversions.h"
20 21
21 namespace base { 22 namespace base {
22 23
23 namespace { 24 namespace {
24 25
25 // Define a separator character to use when creating a persistent form of an 26 // Define a separator character to use when creating a persistent form of an
26 // instance. This is intended for use as a command line argument, passed to a 27 // instance. This is intended for use as a command line argument, passed to a
27 // second process to mimic our state (i.e., provide the same group name). 28 // second process to mimic our state (i.e., provide the same group name).
28 const char kPersistentStringSeparator = '/'; // Currently a slash. 29 const char kPersistentStringSeparator = '/'; // Currently a slash.
29 30
30 // Define a marker character to be used as a prefix to a trial name on the 31 // Define a marker character to be used as a prefix to a trial name on the
31 // command line which forces its activation. 32 // command line which forces its activation.
32 const char kActivationMarker = '*'; 33 const char kActivationMarker = '*';
33 34
34 // Use shared memory to communicate field trial (experiment) state. Set to false 35 // 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 36 // for now while the implementation is fleshed out (e.g. data format, single
36 // shared memory segment). See https://codereview.chromium.org/2365273004/ and 37 // shared memory segment). See https://codereview.chromium.org/2365273004/ and
37 // crbug.com/653874 38 // crbug.com/653874
38 #if defined(OS_WIN)
39 const bool kUseSharedMemoryForFieldTrials = false; 39 const bool kUseSharedMemoryForFieldTrials = false;
40
41 // Constants for the field trial allocator.
42 const char kAllocatorName[] = "FieldTrialAllocator";
43 const uint32_t kFieldTrialType = 0xABA17E13 + 1; // SHA1(FieldTrialEntry) v1
44 #if !defined(OS_NACL)
45 const size_t kFieldTrialAllocationSize = 4 << 10; // 4 KiB = one page
40 #endif 46 #endif
41 47
48 // We create one FieldTrialEntry struct per field trial in shared memory (via
49 // field_trial_allocator_). It contains whether or not it's activated, and the
50 // offset from the start of the allocated memory to the group name. We don't
51 // need the offset into the trial name because that's always a fixed position
52 // from the start of the struct. Two strings will be appended to the end of this
53 // structure in allocated memory, so the result will look like this:
54 // ---------------------------------
55 // | fte | trial_name | group_name |
56 // ---------------------------------
57 // TODO(lawrencewu): Actually update the activated flag.
58 struct FieldTrialEntry {
59 bool activated;
60 uint32_t group_name_offset;
61
62 const char* GetTrialName() const {
63 const char* src =
64 reinterpret_cast<char*>(const_cast<FieldTrialEntry*>(this));
65 return src + sizeof(FieldTrialEntry);
66 }
67
68 const char* GetGroupName() const {
69 const char* src =
70 reinterpret_cast<char*>(const_cast<FieldTrialEntry*>(this));
71 return src + this->group_name_offset;
72 }
73 };
74
42 // Created a time value based on |year|, |month| and |day_of_month| parameters. 75 // Created a time value based on |year|, |month| and |day_of_month| parameters.
43 Time CreateTimeFromParams(int year, int month, int day_of_month) { 76 Time CreateTimeFromParams(int year, int month, int day_of_month) {
44 DCHECK_GT(year, 1970); 77 DCHECK_GT(year, 1970);
45 DCHECK_GT(month, 0); 78 DCHECK_GT(month, 0);
46 DCHECK_LT(month, 13); 79 DCHECK_LT(month, 13);
47 DCHECK_GT(day_of_month, 0); 80 DCHECK_GT(day_of_month, 0);
48 DCHECK_LT(day_of_month, 32); 81 DCHECK_LT(day_of_month, 32);
49 82
50 Time::Exploded exploded; 83 Time::Exploded exploded;
51 exploded.year = year; 84 exploded.year = year;
(...skipping 65 matching lines...) Expand 10 before | Expand all | Expand 10 after
117 trials_string_piece.substr(next_item, name_end - next_item); 150 trials_string_piece.substr(next_item, name_end - next_item);
118 entry.group_name = 151 entry.group_name =
119 trials_string_piece.substr(name_end + 1, group_name_end - name_end - 1); 152 trials_string_piece.substr(name_end + 1, group_name_end - name_end - 1);
120 next_item = group_name_end + 1; 153 next_item = group_name_end + 1;
121 154
122 entries->push_back(entry); 155 entries->push_back(entry);
123 } 156 }
124 return true; 157 return true;
125 } 158 }
126 159
160 void AddForceFieldTrialsFlag(CommandLine* cmd_line) {
161 std::string field_trial_states;
162 FieldTrialList::AllStatesToString(&field_trial_states);
163 if (!field_trial_states.empty()) {
164 cmd_line->AppendSwitchASCII(switches::kForceFieldTrials,
165 field_trial_states);
166 }
167 }
168
169 #if defined(OS_WIN)
170 HANDLE CreateReadOnlyHandle(SharedPersistentMemoryAllocator* allocator) {
171 HANDLE src = allocator->shared_memory()->handle().GetHandle();
172 ProcessHandle process = GetCurrentProcess();
173 DWORD access = SECTION_MAP_READ | SECTION_QUERY;
174 HANDLE dst;
175 if (!::DuplicateHandle(process, src, process, &dst, access, true, 0))
176 return nullptr;
177 return dst;
178 }
179 #endif
180
127 } // namespace 181 } // namespace
128 182
129 // statics 183 // statics
130 const int FieldTrial::kNotFinalized = -1; 184 const int FieldTrial::kNotFinalized = -1;
131 const int FieldTrial::kDefaultGroupNumber = 0; 185 const int FieldTrial::kDefaultGroupNumber = 0;
132 bool FieldTrial::enable_benchmarking_ = false; 186 bool FieldTrial::enable_benchmarking_ = false;
133 187
134 int FieldTrialList::kNoExpirationYear = 0; 188 int FieldTrialList::kNoExpirationYear = 0;
135 189
136 //------------------------------------------------------------------------------ 190 //------------------------------------------------------------------------------
(...skipping 426 matching lines...) Expand 10 before | Expand all | Expand 10 after
563 // any. This is useful to ensure that field trials created in child 617 // any. This is useful to ensure that field trials created in child
564 // processes are properly reported in crash reports. 618 // processes are properly reported in crash reports.
565 trial->group(); 619 trial->group();
566 } 620 }
567 } 621 }
568 return true; 622 return true;
569 } 623 }
570 624
571 // static 625 // static
572 void FieldTrialList::CreateTrialsFromCommandLine( 626 void FieldTrialList::CreateTrialsFromCommandLine(
573 const base::CommandLine& cmd_line, 627 const CommandLine& cmd_line,
574 const char* field_trial_handle_switch) { 628 const char* field_trial_handle_switch) {
575 DCHECK(global_); 629 DCHECK(global_);
576 630
577 #if defined(OS_WIN) 631 #if defined(OS_WIN) && !defined(OS_NACL)
578 if (cmd_line.HasSwitch(field_trial_handle_switch)) { 632 if (cmd_line.HasSwitch(field_trial_handle_switch)) {
579 std::string arg = cmd_line.GetSwitchValueASCII(field_trial_handle_switch); 633 std::string arg = cmd_line.GetSwitchValueASCII(field_trial_handle_switch);
580 size_t token = arg.find(","); 634 size_t token = arg.find(",");
581 int field_trial_handle = std::stoi(arg.substr(0, token)); 635 int field_trial_handle = std::stoi(arg.substr(0, token));
582 int field_trial_length = std::stoi(arg.substr(token + 1, arg.length())); 636 size_t field_trial_length = std::stoi(arg.substr(token + 1, arg.length()));
583 637
584 HANDLE handle = reinterpret_cast<HANDLE>(field_trial_handle); 638 HANDLE handle = reinterpret_cast<HANDLE>(field_trial_handle);
585 base::SharedMemoryHandle shm_handle = 639 SharedMemoryHandle shm_handle =
586 base::SharedMemoryHandle(handle, base::GetCurrentProcId()); 640 SharedMemoryHandle(handle, GetCurrentProcId());
587 641
588 // Gets deleted when it gets out of scope, but that's OK because we need it 642 // 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. 643 // only for the duration of this method.
590 base::SharedMemory shared_memory(shm_handle, false); 644 std::unique_ptr<SharedMemory> shm(new SharedMemory(shm_handle, true));
591 shared_memory.Map(field_trial_length); 645 if (!shm.get()->Map(field_trial_length))
646 TerminateBecauseOutOfMemory(field_trial_length);
592 647
593 char* field_trial_state = static_cast<char*>(shared_memory.memory()); 648 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; 649 return;
598 } 650 }
599 #endif 651 #endif
600 652
601 if (cmd_line.HasSwitch(switches::kForceFieldTrials)) { 653 if (cmd_line.HasSwitch(switches::kForceFieldTrials)) {
602 bool result = FieldTrialList::CreateTrialsFromString( 654 bool result = FieldTrialList::CreateTrialsFromString(
603 cmd_line.GetSwitchValueASCII(switches::kForceFieldTrials), 655 cmd_line.GetSwitchValueASCII(switches::kForceFieldTrials),
604 std::set<std::string>()); 656 std::set<std::string>());
605 DCHECK(result); 657 DCHECK(result);
606 } 658 }
607 } 659 }
608 660
661 #if defined(OS_WIN)
662 // static
663 void FieldTrialList::AppendFieldTrialHandleIfNeeded(
664 HandlesToInheritVector* handles) {
665 if (!global_)
666 return;
667 if (kUseSharedMemoryForFieldTrials) {
668 InstantiateFieldTrialAllocatorIfNeeded();
669 if (global_->readonly_allocator_handle_)
670 handles->push_back(global_->readonly_allocator_handle_);
671 }
672 }
673 #endif
674
675 // static
676 void FieldTrialList::CreateTrialsFromSharedMemory(
677 std::unique_ptr<SharedMemory> shm) {
678 const SharedPersistentMemoryAllocator shalloc(std::move(shm), 0,
679 kAllocatorName, true);
680 PersistentMemoryAllocator::Iterator iter(&shalloc);
681
682 SharedPersistentMemoryAllocator::Reference ref;
683 while ((ref = iter.GetNextOfType(kFieldTrialType)) !=
684 SharedPersistentMemoryAllocator::kReferenceNull) {
685 const FieldTrialEntry* entry =
686 shalloc.GetAsObject<const FieldTrialEntry>(ref, kFieldTrialType);
687 FieldTrial* trial =
688 CreateFieldTrial(entry->GetTrialName(), entry->GetGroupName());
689
690 if (entry->activated) {
691 // Call |group()| to mark the trial as "used" and notify observers, if
692 // any. This is useful to ensure that field trials created in child
693 // processes are properly reported in crash reports.
694 trial->group();
695 }
696 }
697 }
698
609 // static 699 // static
610 std::unique_ptr<base::SharedMemory> FieldTrialList::CopyFieldTrialStateToFlags( 700 void FieldTrialList::CopyFieldTrialStateToFlags(
611 const char* field_trial_handle_switch, 701 const char* field_trial_handle_switch,
612 base::CommandLine* cmd_line) { 702 CommandLine* cmd_line) {
613 std::string field_trial_states;
614 base::FieldTrialList::AllStatesToString(&field_trial_states);
615 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) 703 #if defined(OS_WIN)
619 if (kUseSharedMemoryForFieldTrials) { 704 // Use shared memory to pass the state if the feature is enabled, otherwise
620 std::unique_ptr<base::SharedMemory> shm(new base::SharedMemory()); 705 // fallback to passing it via the command line as a string.
621 size_t length = field_trial_states.size() + 1; 706 if (kUseSharedMemoryForFieldTrials) {
622 shm->CreateAndMapAnonymous(length); 707 InstantiateFieldTrialAllocatorIfNeeded();
623 memcpy(shm->memory(), field_trial_states.c_str(), length); 708 // If the readonly handle didn't get duplicated properly, then fallback to
709 // original behavior.
710 if (!global_->readonly_allocator_handle_) {
711 AddForceFieldTrialsFlag(cmd_line);
712 return;
713 }
624 714
625 // HANDLE is just typedef'd to void * 715 // HANDLE is just typedef'd to void *. We basically cast the handle into an
626 auto uintptr_handle = 716 // int (uintptr_t, to be exact), stringify the int, and pass it as a
627 reinterpret_cast<std::uintptr_t>(shm->handle().GetHandle()); 717 // command-line flag. The child process will do the reverse conversions to
628 std::string field_trial_handle = 718 // retrieve the handle. See http://stackoverflow.com/a/153077
629 std::to_string(uintptr_handle) + "," + std::to_string(length); 719 auto uintptr_handle =
720 reinterpret_cast<uintptr_t>(global_->readonly_allocator_handle_);
721 size_t field_trial_length =
722 global_->field_trial_allocator_->shared_memory()->mapped_size();
723 std::string field_trial_handle = std::to_string(uintptr_handle) + "," +
724 std::to_string(field_trial_length);
630 725
631 cmd_line->AppendSwitchASCII(field_trial_handle_switch, 726 cmd_line->AppendSwitchASCII(field_trial_handle_switch, field_trial_handle);
632 field_trial_handle); 727 return;
633 return shm; 728 }
634 }
635 #endif 729 #endif
636 cmd_line->AppendSwitchASCII(switches::kForceFieldTrials, 730
637 field_trial_states); 731 AddForceFieldTrialsFlag(cmd_line);
638 }
639 return std::unique_ptr<base::SharedMemory>(nullptr);
640 } 732 }
641 733
642 // static 734 // static
643 FieldTrial* FieldTrialList::CreateFieldTrial( 735 FieldTrial* FieldTrialList::CreateFieldTrial(
644 const std::string& name, 736 const std::string& name,
645 const std::string& group_name) { 737 const std::string& group_name) {
646 DCHECK(global_); 738 DCHECK(global_);
647 DCHECK_GE(name.size(), 0u); 739 DCHECK_GE(name.size(), 0u);
648 DCHECK_GE(group_name.size(), 0u); 740 DCHECK_GE(group_name.size(), 0u);
649 if (name.empty() || group_name.empty() || !global_) 741 if (name.empty() || group_name.empty() || !global_)
(...skipping 32 matching lines...) Expand 10 before | Expand all | Expand 10 after
682 // static 774 // static
683 void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial* field_trial) { 775 void FieldTrialList::NotifyFieldTrialGroupSelection(FieldTrial* field_trial) {
684 if (!global_) 776 if (!global_)
685 return; 777 return;
686 778
687 { 779 {
688 AutoLock auto_lock(global_->lock_); 780 AutoLock auto_lock(global_->lock_);
689 if (field_trial->group_reported_) 781 if (field_trial->group_reported_)
690 return; 782 return;
691 field_trial->group_reported_ = true; 783 field_trial->group_reported_ = true;
784
785 if (!field_trial->enable_field_trial_)
786 return;
787
788 if (kUseSharedMemoryForFieldTrials) {
789 field_trial->AddToAllocatorWhileLocked(
790 global_->field_trial_allocator_.get());
791 }
692 } 792 }
693 793
694 if (!field_trial->enable_field_trial_)
695 return;
696
697 global_->observer_list_->Notify( 794 global_->observer_list_->Notify(
698 FROM_HERE, &FieldTrialList::Observer::OnFieldTrialGroupFinalized, 795 FROM_HERE, &FieldTrialList::Observer::OnFieldTrialGroupFinalized,
699 field_trial->trial_name(), field_trial->group_name_internal()); 796 field_trial->trial_name(), field_trial->group_name_internal());
700 } 797 }
701 798
799 #if !defined(OS_NACL)
800 // static
801 void FieldTrialList::InstantiateFieldTrialAllocatorIfNeeded() {
802 AutoLock auto_lock(global_->lock_);
803 // Create the allocator if not already created and add all existing trials.
804 if (global_->field_trial_allocator_ != nullptr)
805 return;
806
807 std::unique_ptr<SharedMemory> shm(new SharedMemory());
808 if (!shm->CreateAndMapAnonymous(kFieldTrialAllocationSize))
809 TerminateBecauseOutOfMemory(kFieldTrialAllocationSize);
810
811 // TODO(lawrencewu): call UpdateTrackingHistograms() when all field trials
812 // have been registered (perhaps in the destructor?)
813 global_->field_trial_allocator_.reset(new SharedPersistentMemoryAllocator(
814 std::move(shm), 0, kAllocatorName, false));
815 global_->field_trial_allocator_->CreateTrackingHistograms(kAllocatorName);
816
817 // Add all existing field trials.
818 for (const auto& registered : global_->registered_) {
819 registered.second->AddToAllocatorWhileLocked(
820 global_->field_trial_allocator_.get());
821 }
822
823 #if defined(OS_WIN)
824 // Set |readonly_allocator_handle_| so we can pass it to be inherited and via
825 // the command line.
826 global_->readonly_allocator_handle_ =
827 CreateReadOnlyHandle(global_->field_trial_allocator_.get());
828 #endif
829 }
830 #endif
831
832 void FieldTrial::AddToAllocatorWhileLocked(
833 SharedPersistentMemoryAllocator* allocator) {
834 // Don't do anything if the allocator hasn't been instantiated yet.
835 if (allocator == nullptr)
836 return;
837
838 State trial_state;
839 if (!GetState(&trial_state))
840 return;
841
842 size_t trial_name_size = trial_state.trial_name.size() + 1;
843 size_t group_name_size = trial_state.group_name.size() + 1;
844 size_t size = sizeof(FieldTrialEntry) + trial_name_size + group_name_size;
845
846 // Allocate just enough memory to fit the FieldTrialEntry struct, trial name,
847 // and group name.
848 SharedPersistentMemoryAllocator::Reference ref =
849 allocator->Allocate(size, kFieldTrialType);
850 if (ref == SharedPersistentMemoryAllocator::kReferenceNull)
851 return;
852
853 // Calculate offsets into the shared memory segment.
854 FieldTrialEntry* entry =
855 allocator->GetAsObject<FieldTrialEntry>(ref, kFieldTrialType);
856 uint32_t trial_name_offset = sizeof(FieldTrialEntry);
857 uint32_t group_name_offset = trial_name_offset + trial_name_size;
858
859 // Copy over the data.
860 entry->activated = trial_state.activated;
861 entry->group_name_offset = group_name_offset;
862 char* trial_name = reinterpret_cast<char*>(entry) + trial_name_offset;
863 char* group_name = reinterpret_cast<char*>(entry) + group_name_offset;
864 memcpy(trial_name, trial_state.trial_name.data(), trial_name_size);
865 memcpy(group_name, trial_state.group_name.data(), group_name_size);
866
867 // Null terminate the strings.
868 trial_name[trial_state.trial_name.size()] = '\0';
869 group_name[trial_state.group_name.size()] = '\0';
870
871 allocator->MakeIterable(ref);
872 }
873
702 // static 874 // static
703 size_t FieldTrialList::GetFieldTrialCount() { 875 size_t FieldTrialList::GetFieldTrialCount() {
704 if (!global_) 876 if (!global_)
705 return 0; 877 return 0;
706 AutoLock auto_lock(global_->lock_); 878 AutoLock auto_lock(global_->lock_);
707 return global_->registered_.size(); 879 return global_->registered_.size();
708 } 880 }
709 881
710 // static 882 // static
711 const FieldTrial::EntropyProvider* 883 const FieldTrial::EntropyProvider*
(...skipping 20 matching lines...) Expand all
732 return; 904 return;
733 } 905 }
734 AutoLock auto_lock(global_->lock_); 906 AutoLock auto_lock(global_->lock_);
735 CHECK(!global_->PreLockedFind(trial->trial_name())) << trial->trial_name(); 907 CHECK(!global_->PreLockedFind(trial->trial_name())) << trial->trial_name();
736 trial->AddRef(); 908 trial->AddRef();
737 trial->SetTrialRegistered(); 909 trial->SetTrialRegistered();
738 global_->registered_[trial->trial_name()] = trial; 910 global_->registered_[trial->trial_name()] = trial;
739 } 911 }
740 912
741 } // namespace base 913 } // namespace base
OLDNEW
« no previous file with comments | « base/metrics/field_trial.h ('k') | base/metrics/field_trial_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698