Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / base / profiler / stack_sampling_profiler.cc
blobf2467c332d86a81df38239a89d7491615129e8c2
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 void StackSamplingProfiler::SamplingThread::CollectProfile(
145 CallStackProfile* profile,
146 TimeDelta* elapsed_time,
147 bool* was_stopped) {
148 ElapsedTimer profile_timer;
149 native_sampler_->ProfileRecordingStarting(&profile->modules);
150 profile->sampling_period = params_.sampling_interval;
151 *was_stopped = false;
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 *was_stopped = true;
161 break;
164 ElapsedTimer sample_timer;
165 profile->samples.push_back(Sample());
166 native_sampler_->RecordStackSample(&profile->samples.back());
167 previous_elapsed_sample_time = sample_timer.Elapsed();
170 *elapsed_time = profile_timer.Elapsed();
171 profile->profile_duration = *elapsed_time;
172 native_sampler_->ProfileRecordingStopped();
175 // In an analogous manner to CollectProfile() and samples exceeding the expected
176 // total sampling time, bursts may also exceed the burst_interval. We adopt the
177 // same wait-and-see approach here.
178 void StackSamplingProfiler::SamplingThread::CollectProfiles(
179 CallStackProfiles* profiles) {
180 if (stop_event_.TimedWait(params_.initial_delay))
181 return;
183 TimeDelta previous_elapsed_profile_time;
184 for (int i = 0; i < params_.bursts; ++i) {
185 if (i != 0) {
186 // Always wait, even if for 0 seconds, so we can observe a signal on
187 // stop_event_.
188 if (stop_event_.TimedWait(
189 std::max(params_.burst_interval - previous_elapsed_profile_time,
190 TimeDelta())))
191 return;
194 CallStackProfile profile;
195 bool was_stopped = false;
196 CollectProfile(&profile, &previous_elapsed_profile_time, &was_stopped);
197 if (!profile.samples.empty())
198 profiles->push_back(profile);
200 if (was_stopped)
201 return;
205 void StackSamplingProfiler::SamplingThread::Stop() {
206 stop_event_.Signal();
209 // StackSamplingProfiler ------------------------------------------------------
211 StackSamplingProfiler::SamplingParams::SamplingParams()
212 : initial_delay(TimeDelta::FromMilliseconds(0)),
213 bursts(1),
214 burst_interval(TimeDelta::FromMilliseconds(10000)),
215 samples_per_burst(300),
216 sampling_interval(TimeDelta::FromMilliseconds(100)) {
219 StackSamplingProfiler::StackSamplingProfiler(PlatformThreadId thread_id,
220 const SamplingParams& params,
221 const CompletedCallback& callback)
222 : thread_id_(thread_id), params_(params), completed_callback_(callback) {}
224 StackSamplingProfiler::~StackSamplingProfiler() {
225 Stop();
226 if (!sampling_thread_handle_.is_null())
227 PlatformThread::Join(sampling_thread_handle_);
230 // static
231 void StackSamplingProfiler::StartAndRunAsync(
232 PlatformThreadId thread_id,
233 const SamplingParams& params,
234 const CompletedCallback& callback) {
235 CHECK(ThreadTaskRunnerHandle::Get());
236 AsyncRunner::Run(thread_id, params, callback);
239 void StackSamplingProfiler::Start() {
240 if (completed_callback_.is_null())
241 return;
243 scoped_ptr<NativeStackSampler> native_sampler =
244 NativeStackSampler::Create(thread_id_);
245 if (!native_sampler)
246 return;
248 sampling_thread_.reset(
249 new SamplingThread(native_sampler.Pass(), params_, completed_callback_));
250 if (!PlatformThread::Create(0, sampling_thread_.get(),
251 &sampling_thread_handle_))
252 sampling_thread_.reset();
255 void StackSamplingProfiler::Stop() {
256 if (sampling_thread_)
257 sampling_thread_->Stop();
260 // StackSamplingProfiler::Frame global functions ------------------------------
262 bool operator==(const StackSamplingProfiler::Frame &a,
263 const StackSamplingProfiler::Frame &b) {
264 return a.instruction_pointer == b.instruction_pointer &&
265 a.module_index == b.module_index;
268 bool operator<(const StackSamplingProfiler::Frame &a,
269 const StackSamplingProfiler::Frame &b) {
270 return (a.module_index < b.module_index) ||
271 (a.module_index == b.module_index &&
272 a.instruction_pointer < b.instruction_pointer);
275 } // namespace base