Updating XTBs based on .GRDs from branch master
[chromium-blink-merge.git] / base / profiler / stack_sampling_profiler.cc
blob00a79b55bd7fd465f423fa3202bb48661d26e96a
1 // Copyright 2015 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/profiler/stack_sampling_profiler.h"
7 #include <algorithm>
9 #include "base/bind.h"
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/lazy_instance.h"
13 #include "base/location.h"
14 #include "base/profiler/native_stack_sampler.h"
15 #include "base/synchronization/lock.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "base/timer/elapsed_timer.h"
19 namespace base {
21 namespace {
23 // Used to ensure only one profiler is running at a time.
24 LazyInstance<Lock> concurrent_profiling_lock = LAZY_INSTANCE_INITIALIZER;
26 // AsyncRunner ----------------------------------------------------------------
28 // Helper class to allow a profiler to be run completely asynchronously from the
29 // initiator, without being concerned with the profiler's lifetime.
30 class AsyncRunner {
31 public:
32 // Sets up a profiler and arranges for it to be deleted on its completed
33 // callback.
34 static void Run(PlatformThreadId thread_id,
35 const StackSamplingProfiler::SamplingParams& params,
36 const StackSamplingProfiler::CompletedCallback& callback);
38 private:
39 AsyncRunner();
41 // Runs the callback and deletes the AsyncRunner instance.
42 static void RunCallbackAndDeleteInstance(
43 scoped_ptr<AsyncRunner> object_to_be_deleted,
44 const StackSamplingProfiler::CompletedCallback& callback,
45 scoped_refptr<SingleThreadTaskRunner> task_runner,
46 const StackSamplingProfiler::CallStackProfiles& profiles);
48 scoped_ptr<StackSamplingProfiler> profiler_;
50 DISALLOW_COPY_AND_ASSIGN(AsyncRunner);
53 // static
54 void AsyncRunner::Run(
55 PlatformThreadId thread_id,
56 const StackSamplingProfiler::SamplingParams& params,
57 const StackSamplingProfiler::CompletedCallback &callback) {
58 scoped_ptr<AsyncRunner> runner(new AsyncRunner);
59 AsyncRunner* temp_ptr = runner.get();
60 temp_ptr->profiler_.reset(
61 new StackSamplingProfiler(thread_id, params,
62 Bind(&AsyncRunner::RunCallbackAndDeleteInstance,
63 Passed(&runner), callback,
64 ThreadTaskRunnerHandle::Get())));
65 // The callback won't be called until after Start(), so temp_ptr will still
66 // be valid here.
67 temp_ptr->profiler_->Start();
70 AsyncRunner::AsyncRunner() {}
72 void AsyncRunner::RunCallbackAndDeleteInstance(
73 scoped_ptr<AsyncRunner> object_to_be_deleted,
74 const StackSamplingProfiler::CompletedCallback& callback,
75 scoped_refptr<SingleThreadTaskRunner> task_runner,
76 const StackSamplingProfiler::CallStackProfiles& profiles) {
77 callback.Run(profiles);
78 // Delete the instance on the original calling thread.
79 task_runner->DeleteSoon(FROM_HERE, object_to_be_deleted.release());
82 } // namespace
84 // StackSamplingProfiler::Module ----------------------------------------------
86 StackSamplingProfiler::Module::Module() : base_address(nullptr) {}
87 StackSamplingProfiler::Module::Module(const void* base_address,
88 const std::string& id,
89 const FilePath& filename)
90 : base_address(base_address), id(id), filename(filename) {}
92 StackSamplingProfiler::Module::~Module() {}
94 // StackSamplingProfiler::Frame -----------------------------------------------
96 StackSamplingProfiler::Frame::Frame(const void* instruction_pointer,
97 size_t module_index)
98 : instruction_pointer(instruction_pointer),
99 module_index(module_index) {}
101 StackSamplingProfiler::Frame::~Frame() {}
103 // StackSamplingProfiler::CallStackProfile ------------------------------------
105 StackSamplingProfiler::CallStackProfile::CallStackProfile() {}
107 StackSamplingProfiler::CallStackProfile::~CallStackProfile() {}
109 // StackSamplingProfiler::SamplingThread --------------------------------------
111 StackSamplingProfiler::SamplingThread::SamplingThread(
112 scoped_ptr<NativeStackSampler> native_sampler,
113 const SamplingParams& params,
114 const CompletedCallback& completed_callback)
115 : native_sampler_(native_sampler.Pass()),
116 params_(params),
117 stop_event_(false, false),
118 completed_callback_(completed_callback) {
121 StackSamplingProfiler::SamplingThread::~SamplingThread() {}
123 void StackSamplingProfiler::SamplingThread::ThreadMain() {
124 PlatformThread::SetName("Chrome_SamplingProfilerThread");
126 // For now, just ignore any requests to profile while another profiler is
127 // working.
128 if (!concurrent_profiling_lock.Get().Try())
129 return;
131 CallStackProfiles profiles;
132 CollectProfiles(&profiles);
133 concurrent_profiling_lock.Get().Release();
134 completed_callback_.Run(profiles);
137 // Depending on how long the sampling takes and the length of the sampling
138 // interval, a burst of samples could take arbitrarily longer than
139 // samples_per_burst * sampling_interval. In this case, we (somewhat
140 // arbitrarily) honor the number of samples requested rather than strictly
141 // adhering to the sampling intervals. Once we have established users for the
142 // StackSamplingProfiler and the collected data to judge, we may go the other
143 // way or make this behavior configurable.
144 bool StackSamplingProfiler::SamplingThread::CollectProfile(
145 CallStackProfile* profile,
146 TimeDelta* elapsed_time) {
147 ElapsedTimer profile_timer;
148 CallStackProfile current_profile;
149 native_sampler_->ProfileRecordingStarting(&current_profile.modules);
150 current_profile.sampling_period = params_.sampling_interval;
151 bool burst_completed = true;
152 TimeDelta previous_elapsed_sample_time;
153 for (int i = 0; i < params_.samples_per_burst; ++i) {
154 if (i != 0) {
155 // Always wait, even if for 0 seconds, so we can observe a signal on
156 // stop_event_.
157 if (stop_event_.TimedWait(
158 std::max(params_.sampling_interval - previous_elapsed_sample_time,
159 TimeDelta()))) {
160 burst_completed = false;
161 break;
164 ElapsedTimer sample_timer;
165 current_profile.samples.push_back(Sample());
166 native_sampler_->RecordStackSample(&current_profile.samples.back());
167 previous_elapsed_sample_time = sample_timer.Elapsed();
170 *elapsed_time = profile_timer.Elapsed();
171 current_profile.profile_duration = *elapsed_time;
172 native_sampler_->ProfileRecordingStopped();
174 if (burst_completed)
175 *profile = current_profile;
177 return burst_completed;
180 // In an analogous manner to CollectProfile() and samples exceeding the expected
181 // total sampling time, bursts may also exceed the burst_interval. We adopt the
182 // same wait-and-see approach here.
183 void StackSamplingProfiler::SamplingThread::CollectProfiles(
184 CallStackProfiles* profiles) {
185 if (stop_event_.TimedWait(params_.initial_delay))
186 return;
188 TimeDelta previous_elapsed_profile_time;
189 for (int i = 0; i < params_.bursts; ++i) {
190 if (i != 0) {
191 // Always wait, even if for 0 seconds, so we can observe a signal on
192 // stop_event_.
193 if (stop_event_.TimedWait(
194 std::max(params_.burst_interval - previous_elapsed_profile_time,
195 TimeDelta())))
196 return;
199 CallStackProfile profile;
200 if (!CollectProfile(&profile, &previous_elapsed_profile_time))
201 return;
202 profiles->push_back(profile);
206 void StackSamplingProfiler::SamplingThread::Stop() {
207 stop_event_.Signal();
210 // StackSamplingProfiler ------------------------------------------------------
212 StackSamplingProfiler::SamplingParams::SamplingParams()
213 : initial_delay(TimeDelta::FromMilliseconds(0)),
214 bursts(1),
215 burst_interval(TimeDelta::FromMilliseconds(10000)),
216 samples_per_burst(300),
217 sampling_interval(TimeDelta::FromMilliseconds(100)) {
220 StackSamplingProfiler::StackSamplingProfiler(PlatformThreadId thread_id,
221 const SamplingParams& params,
222 const CompletedCallback& callback)
223 : thread_id_(thread_id), params_(params), completed_callback_(callback) {}
225 StackSamplingProfiler::~StackSamplingProfiler() {
226 Stop();
227 if (!sampling_thread_handle_.is_null())
228 PlatformThread::Join(sampling_thread_handle_);
231 // static
232 void StackSamplingProfiler::StartAndRunAsync(
233 PlatformThreadId thread_id,
234 const SamplingParams& params,
235 const CompletedCallback& callback) {
236 CHECK(ThreadTaskRunnerHandle::Get());
237 AsyncRunner::Run(thread_id, params, callback);
240 void StackSamplingProfiler::Start() {
241 if (completed_callback_.is_null())
242 return;
244 scoped_ptr<NativeStackSampler> native_sampler =
245 NativeStackSampler::Create(thread_id_);
246 if (!native_sampler)
247 return;
249 sampling_thread_.reset(
250 new SamplingThread(native_sampler.Pass(), params_, completed_callback_));
251 if (!PlatformThread::Create(0, sampling_thread_.get(),
252 &sampling_thread_handle_))
253 sampling_thread_.reset();
256 void StackSamplingProfiler::Stop() {
257 if (sampling_thread_)
258 sampling_thread_->Stop();
261 // StackSamplingProfiler::Frame global functions ------------------------------
263 bool operator==(const StackSamplingProfiler::Frame &a,
264 const StackSamplingProfiler::Frame &b) {
265 return a.instruction_pointer == b.instruction_pointer &&
266 a.module_index == b.module_index;
269 bool operator<(const StackSamplingProfiler::Frame &a,
270 const StackSamplingProfiler::Frame &b) {
271 return (a.module_index < b.module_index) ||
272 (a.module_index == b.module_index &&
273 a.instruction_pointer < b.instruction_pointer);
276 } // namespace base