OLD | NEW |
---|---|
1 // Copyright 2015 The Chromium Authors. All rights reserved. | 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 | 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/profiler/stack_sampling_profiler.h" | 5 #include "base/profiler/stack_sampling_profiler.h" |
6 | 6 |
7 #include <algorithm> | 7 #include <algorithm> |
8 #include <map> | |
8 #include <utility> | 9 #include <utility> |
9 | 10 |
11 #include "base/atomic_sequence_num.h" | |
12 #include "base/atomicops.h" | |
10 #include "base/bind.h" | 13 #include "base/bind.h" |
11 #include "base/bind_helpers.h" | 14 #include "base/bind_helpers.h" |
12 #include "base/callback.h" | 15 #include "base/callback.h" |
13 #include "base/lazy_instance.h" | 16 #include "base/lazy_instance.h" |
14 #include "base/location.h" | 17 #include "base/location.h" |
15 #include "base/macros.h" | 18 #include "base/macros.h" |
19 #include "base/memory/ptr_util.h" | |
20 #include "base/memory/singleton.h" | |
16 #include "base/profiler/native_stack_sampler.h" | 21 #include "base/profiler/native_stack_sampler.h" |
17 #include "base/synchronization/lock.h" | 22 #include "base/synchronization/lock.h" |
23 #include "base/threading/thread.h" | |
24 #include "base/threading/thread_restrictions.h" | |
18 #include "base/threading/thread_task_runner_handle.h" | 25 #include "base/threading/thread_task_runner_handle.h" |
19 #include "base/timer/elapsed_timer.h" | 26 #include "base/timer/elapsed_timer.h" |
20 | 27 |
21 namespace base { | 28 namespace base { |
22 | 29 |
23 namespace { | 30 namespace { |
24 | 31 |
25 // Used to ensure only one profiler is running at a time. | 32 const int NO_ID = -1; |
Mike Wittman
2017/02/22 20:32:18
nit: how about NULL_COLLECTION_ID, so it's clear w
bcwhite
2017/02/24 20:39:24
Done.
| |
26 LazyInstance<Lock>::Leaky concurrent_profiling_lock = LAZY_INSTANCE_INITIALIZER; | |
27 | |
28 // AsyncRunner ---------------------------------------------------------------- | |
29 | |
30 // Helper class to allow a profiler to be run completely asynchronously from the | |
31 // initiator, without being concerned with the profiler's lifetime. | |
32 class AsyncRunner { | |
33 public: | |
34 // Sets up a profiler and arranges for it to be deleted on its completed | |
35 // callback. | |
36 static void Run(PlatformThreadId thread_id, | |
37 const StackSamplingProfiler::SamplingParams& params, | |
38 const StackSamplingProfiler::CompletedCallback& callback); | |
39 | |
40 private: | |
41 AsyncRunner(); | |
42 | |
43 // Runs the callback and deletes the AsyncRunner instance. |profiles| is not | |
44 // const& because it must be passed with std::move. | |
45 static void RunCallbackAndDeleteInstance( | |
46 std::unique_ptr<AsyncRunner> object_to_be_deleted, | |
47 const StackSamplingProfiler::CompletedCallback& callback, | |
48 scoped_refptr<SingleThreadTaskRunner> task_runner, | |
49 StackSamplingProfiler::CallStackProfiles profiles); | |
50 | |
51 std::unique_ptr<StackSamplingProfiler> profiler_; | |
52 | |
53 DISALLOW_COPY_AND_ASSIGN(AsyncRunner); | |
54 }; | |
55 | |
56 // static | |
57 void AsyncRunner::Run( | |
58 PlatformThreadId thread_id, | |
59 const StackSamplingProfiler::SamplingParams& params, | |
60 const StackSamplingProfiler::CompletedCallback &callback) { | |
61 std::unique_ptr<AsyncRunner> runner(new AsyncRunner); | |
62 AsyncRunner* temp_ptr = runner.get(); | |
63 temp_ptr->profiler_.reset( | |
64 new StackSamplingProfiler(thread_id, params, | |
65 Bind(&AsyncRunner::RunCallbackAndDeleteInstance, | |
66 Passed(&runner), callback, | |
67 ThreadTaskRunnerHandle::Get()))); | |
68 // The callback won't be called until after Start(), so temp_ptr will still | |
69 // be valid here. | |
70 temp_ptr->profiler_->Start(); | |
71 } | |
72 | |
73 AsyncRunner::AsyncRunner() {} | |
74 | |
75 void AsyncRunner::RunCallbackAndDeleteInstance( | |
76 std::unique_ptr<AsyncRunner> object_to_be_deleted, | |
77 const StackSamplingProfiler::CompletedCallback& callback, | |
78 scoped_refptr<SingleThreadTaskRunner> task_runner, | |
79 StackSamplingProfiler::CallStackProfiles profiles) { | |
80 callback.Run(std::move(profiles)); | |
81 // Delete the instance on the original calling thread. | |
82 task_runner->DeleteSoon(FROM_HERE, object_to_be_deleted.release()); | |
83 } | |
84 | 33 |
85 void ChangeAtomicFlags(subtle::Atomic32* flags, | 34 void ChangeAtomicFlags(subtle::Atomic32* flags, |
86 subtle::Atomic32 set, | 35 subtle::Atomic32 set, |
87 subtle::Atomic32 clear) { | 36 subtle::Atomic32 clear) { |
88 DCHECK(set != 0 || clear != 0); | 37 DCHECK(set != 0 || clear != 0); |
89 DCHECK_EQ(0, set & clear); | 38 DCHECK_EQ(0, set & clear); |
90 | 39 |
91 subtle::Atomic32 bits = subtle::NoBarrier_Load(flags); | 40 subtle::Atomic32 bits = subtle::NoBarrier_Load(flags); |
92 while (true) { | 41 while (true) { |
93 subtle::Atomic32 existing = | 42 subtle::Atomic32 existing = |
(...skipping 59 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
153 StackSamplingProfiler::CallStackProfile | 102 StackSamplingProfiler::CallStackProfile |
154 StackSamplingProfiler::CallStackProfile::CopyForTesting() const { | 103 StackSamplingProfiler::CallStackProfile::CopyForTesting() const { |
155 return CallStackProfile(*this); | 104 return CallStackProfile(*this); |
156 } | 105 } |
157 | 106 |
158 StackSamplingProfiler::CallStackProfile::CallStackProfile( | 107 StackSamplingProfiler::CallStackProfile::CallStackProfile( |
159 const CallStackProfile& other) = default; | 108 const CallStackProfile& other) = default; |
160 | 109 |
161 // StackSamplingProfiler::SamplingThread -------------------------------------- | 110 // StackSamplingProfiler::SamplingThread -------------------------------------- |
162 | 111 |
163 StackSamplingProfiler::SamplingThread::SamplingThread( | 112 class StackSamplingProfiler::SamplingThread : public Thread { |
164 std::unique_ptr<NativeStackSampler> native_sampler, | 113 public: |
165 const SamplingParams& params, | 114 class TestAPI { |
166 const CompletedCallback& completed_callback) | 115 public: |
167 : native_sampler_(std::move(native_sampler)), | 116 // Sets the number of ms to wait after becoming idle before shutting down. |
168 params_(params), | 117 // Set to zero to disable. |
169 stop_event_(WaitableEvent::ResetPolicy::AUTOMATIC, | 118 static void SetIdleShutdownTime(int shutdown_ms); |
170 WaitableEvent::InitialState::NOT_SIGNALED), | 119 |
171 completed_callback_(completed_callback) {} | 120 // Begins an idle shutdown as if the idle-timer had expired. |
172 | 121 static void ShutdownIfIdle(); |
173 StackSamplingProfiler::SamplingThread::~SamplingThread() {} | 122 }; |
174 | 123 |
175 void StackSamplingProfiler::SamplingThread::ThreadMain() { | 124 struct CollectionContext { |
176 PlatformThread::SetName("Chrome_SamplingProfilerThread"); | 125 CollectionContext(PlatformThreadId target, |
177 | 126 const SamplingParams& params, |
178 // For now, just ignore any requests to profile while another profiler is | 127 const CompletedCallback& callback, |
179 // working. | 128 WaitableEvent* finished, |
180 if (!concurrent_profiling_lock.Get().Try()) | 129 std::unique_ptr<NativeStackSampler> sampler) |
130 : collection_id(next_collection_id_.GetNext()), | |
131 target(target), | |
132 params(params), | |
133 callback(callback), | |
134 finished(finished), | |
135 native_sampler(std::move(sampler)) {} | |
136 ~CollectionContext() {} | |
137 | |
138 // An identifier for this collection, used to uniquely identify it to | |
139 // outside interests. | |
140 const int collection_id; | |
141 | |
142 const PlatformThreadId target; // ID of The thread being sampled. | |
143 const SamplingParams params; // Information about how to sample. | |
144 const CompletedCallback callback; // Callback made when sampling complete. | |
145 WaitableEvent* const finished; // Signaled when all sampling complete. | |
146 | |
147 // Platform-specific module that does the actual sampling. | |
148 std::unique_ptr<NativeStackSampler> native_sampler; | |
149 | |
150 // The absolute time for the next sample. | |
151 Time next_sample_time; | |
152 | |
153 // The time that a profile was started, for calculating the total duration. | |
154 Time profile_start_time; | |
155 | |
156 // Counters that indicate the current position along the acquisition. | |
157 int burst = 0; | |
158 int sample = 0; | |
159 | |
160 // The collected stack samples. The active profile is always at the back(). | |
161 CallStackProfiles profiles; | |
162 | |
163 private: | |
164 static StaticAtomicSequenceNumber next_collection_id_; | |
165 }; | |
166 | |
167 // Gets the single instance of this class. | |
168 static SamplingThread* GetInstance(); | |
169 | |
170 // Starts the thread. | |
171 void Start(); | |
172 | |
173 // Adds a new CollectionContext to the thread. This can be called externally | |
174 // from any thread. This returns an ID that can later be used to stop | |
175 // the sampling. | |
176 int Add(std::unique_ptr<CollectionContext> collection); | |
177 | |
178 // Removes an active collection based on its ID, forcing it to run its | |
179 // callback if any data has been collected. This can be called externally | |
180 // from any thread. | |
181 void Remove(int id); | |
182 | |
183 private: | |
184 friend class TestAPI; | |
185 friend struct DefaultSingletonTraits<SamplingThread>; | |
186 | |
187 SamplingThread(); | |
188 ~SamplingThread() override; | |
189 | |
190 // Get task runner that is usable from the outside. | |
191 scoped_refptr<SingleThreadTaskRunner> GetOrCreateTaskRunner(); | |
192 scoped_refptr<SingleThreadTaskRunner> GetTaskRunner(); | |
193 | |
194 // Get task runner that is usable from the sampling thread itself. | |
195 scoped_refptr<SingleThreadTaskRunner> GetTaskRunnerOnSamplingThread(); | |
196 | |
197 // Finishes a collection and reports collected data via callback. | |
198 void FinishCollection(CollectionContext* collection); | |
199 | |
200 // Records a single sample of a collection. | |
201 void RecordSample(CollectionContext* collection); | |
202 | |
203 // Check if the sampling thread is idle and begin a shutdown if so. | |
204 void ScheduleShutdownIfIdle(); | |
205 | |
206 // These methods are tasks that get posted to the internal message queue. | |
207 void AddCollectionTask(std::unique_ptr<CollectionContext> collection); | |
208 void RemoveCollectionTask(int id); | |
209 void PerformCollectionTask(int id); | |
210 void ShutdownTask(int add_events); | |
211 | |
212 // Updates the |next_sample_time| time based on configured parameters. | |
213 bool UpdateNextSampleTime(CollectionContext* collection); | |
214 | |
215 // Thread: | |
216 void CleanUp() override; | |
217 | |
218 // The task-runner for the sampling thread and some information about it. | |
219 // This must always be accessed while holding the lock. The saved task-runner | |
220 // can be freely used by any calling thread. | |
221 Lock task_runner_lock_; | |
222 scoped_refptr<SingleThreadTaskRunner> task_runner_; | |
223 int task_runner_create_requests_ = 0; | |
Mike Wittman
2017/02/22 20:32:18
remove
bcwhite
2017/02/24 20:39:24
Done.
| |
224 TimeDelta task_runner_idle_shutdown_time_ = TimeDelta::FromSeconds(60); | |
Mike Wittman
2017/02/22 20:32:18
If we're not supporting configurable shutdown time
bcwhite
2017/02/24 20:39:24
Done.
| |
225 | |
226 // A counter that notes adds of new collection requests. It is incremented | |
227 // when changes occur so that delayed shutdown tasks are able to detect if | |
228 // samething new has happened while it was waiting. Like all |task_runner_*| | |
229 // vars, this must be accessed while holding |task_runner_lock_|. | |
230 int task_runner_add_events_ = 0; | |
231 | |
232 // A map of IDs to collection contexts. Because this class is a singleton | |
233 // that is never destroyed, context objects will never be destructed except | |
234 // by explicit action. Thus, it's acceptable to pass unretained pointers | |
235 // to these objects when posting tasks. | |
236 std::map<int, std::unique_ptr<CollectionContext>> active_collections_; | |
237 | |
238 DISALLOW_COPY_AND_ASSIGN(SamplingThread); | |
239 }; | |
240 | |
241 void StackSamplingProfiler::SamplingThread::TestAPI::SetIdleShutdownTime( | |
242 int shutdown_ms) { | |
243 SamplingThread* sampler = SamplingThread::GetInstance(); | |
244 DCHECK(sampler); | |
245 | |
246 AutoLock lock(sampler->task_runner_lock_); | |
247 sampler->task_runner_idle_shutdown_time_ = | |
248 TimeDelta::FromMilliseconds(shutdown_ms); | |
249 } | |
250 | |
251 void StackSamplingProfiler::SamplingThread::TestAPI::ShutdownIfIdle() { | |
252 SamplingThread* sampler = SamplingThread::GetInstance(); | |
253 DCHECK(sampler); | |
254 | |
255 scoped_refptr<SingleThreadTaskRunner> task_runner = sampler->GetTaskRunner(); | |
256 if (!task_runner) | |
257 return; // Everything has already stopped. | |
258 | |
259 // ShutdownTask will check if the thread is idle and skip the shutdown if not. | |
260 AutoLock lock(sampler->task_runner_lock_); | |
261 task_runner->PostTask(FROM_HERE, | |
262 Bind(&SamplingThread::ShutdownTask, Unretained(sampler), | |
263 sampler->task_runner_add_events_)); | |
264 } | |
265 | |
266 StaticAtomicSequenceNumber StackSamplingProfiler::SamplingThread:: | |
267 CollectionContext::next_collection_id_; | |
268 | |
269 StackSamplingProfiler::SamplingThread::SamplingThread() | |
270 : Thread("Chrome_SamplingProfilerThread") {} | |
271 | |
272 StackSamplingProfiler::SamplingThread::~SamplingThread() { | |
273 Stop(); | |
274 } | |
275 | |
276 StackSamplingProfiler::SamplingThread* | |
277 StackSamplingProfiler::SamplingThread::GetInstance() { | |
278 return Singleton<SamplingThread, LeakySingletonTraits<SamplingThread>>::get(); | |
279 } | |
280 | |
281 void StackSamplingProfiler::SamplingThread::Start() { | |
282 Thread::Options options; | |
283 // Use a higher priority for a more accurate sampling interval. | |
284 options.priority = ThreadPriority::DISPLAY; | |
285 Thread::StartWithOptions(options); | |
286 } | |
287 | |
288 int StackSamplingProfiler::SamplingThread::Add( | |
289 std::unique_ptr<CollectionContext> collection) { | |
290 int id = collection->collection_id; | |
291 scoped_refptr<SingleThreadTaskRunner> task_runner = GetOrCreateTaskRunner(); | |
292 | |
293 task_runner->PostTask(FROM_HERE, Bind(&SamplingThread::AddCollectionTask, | |
294 Unretained(this), Passed(&collection))); | |
295 | |
296 return id; | |
297 } | |
298 | |
299 void StackSamplingProfiler::SamplingThread::Remove(int id) { | |
300 scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(); | |
301 if (!task_runner) | |
302 return; // Everything has already stopped. | |
303 | |
304 // This can fail if the thread were to exit between acquisition of the task | |
305 // runner above and the call below. In that case, however, everything has | |
306 // stopped so there's no need to try to stop it. | |
307 task_runner->PostTask(FROM_HERE, Bind(&SamplingThread::RemoveCollectionTask, | |
308 Unretained(this), id)); | |
309 } | |
310 | |
311 scoped_refptr<SingleThreadTaskRunner> | |
312 StackSamplingProfiler::SamplingThread::GetOrCreateTaskRunner() { | |
313 AutoLock lock(task_runner_lock_); | |
314 ++task_runner_add_events_; | |
315 if (!task_runner_) { | |
316 // If this is not the first time the sampling thread has been launched, the | |
317 // previous instance has only been partially cleaned up. It is necessary | |
318 // to call Stop() before Start(). This is safe even the thread has never | |
319 // been started. | |
320 Stop(); | |
321 // The thread is not running. Start it and get associated runner. The task- | |
322 // runner has to be saved for future use because though it can be used from | |
323 // any thread, it can be acquired via task_runner() only on the created | |
324 // thread and the thread that creates it (i.e. this thread). | |
325 Start(); | |
326 task_runner_ = Thread::task_runner(); | |
327 // Detach the sampling thread from the "sequence" (i.e. thread) that | |
328 // started it so that it can be self-managed or stopped by another thread. | |
329 DetachFromSequence(); | |
330 } else { | |
331 // This shouldn't be called from the sampling thread as it's inefficient. | |
332 // Use GetTaskRunnerOnSamplingThread() instead. | |
333 DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); | |
334 } | |
335 | |
336 return task_runner_; | |
337 } | |
338 | |
339 scoped_refptr<SingleThreadTaskRunner> | |
340 StackSamplingProfiler::SamplingThread::GetTaskRunner() { | |
341 AutoLock lock(task_runner_lock_); | |
342 | |
343 // GetThreadId() will block for the thread to start so don't check if there | |
344 // is no task-runner. Otherwise, methods like Remove() will wait forever if | |
345 // the thread isn't already running when they could just return. | |
346 if (task_runner_) { | |
347 // This shouldn't be called from the sampling thread as it's inefficient. | |
348 // Use GetTaskRunnerOnSamplingThread() instead. | |
349 DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); | |
350 } | |
351 | |
352 return task_runner_; | |
353 } | |
354 | |
355 scoped_refptr<SingleThreadTaskRunner> | |
356 StackSamplingProfiler::SamplingThread::GetTaskRunnerOnSamplingThread() { | |
357 // This should be called only from the sampling thread as it has limited | |
358 // accessibility. | |
359 DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); | |
360 | |
361 return Thread::task_runner(); | |
362 } | |
363 | |
364 void StackSamplingProfiler::SamplingThread::FinishCollection( | |
365 CollectionContext* collection) { | |
366 // If there is no duration for the final profile (because it was stopped), | |
367 // calculate it now. | |
368 if (!collection->profiles.empty() && | |
369 collection->profiles.back().profile_duration == TimeDelta()) { | |
370 collection->profiles.back().profile_duration = | |
371 Time::Now() - collection->profile_start_time; | |
372 } | |
373 | |
374 // Run the associated callback, passing the collected profiles. It's okay to | |
375 // move them because this collection is about to be deleted. | |
376 collection->callback.Run(std::move(collection->profiles)); | |
377 | |
378 // Signal that this collection is finished. | |
379 collection->finished->Signal(); | |
380 | |
381 // Remove this collection from the map of known ones. This must be done | |
382 // last as the |collection| parameter is invalid after this point. | |
383 size_t count = active_collections_.erase(collection->collection_id); | |
384 DCHECK_EQ(1U, count); | |
385 } | |
386 | |
387 void StackSamplingProfiler::SamplingThread::RecordSample( | |
388 CollectionContext* collection) { | |
389 DCHECK(collection->native_sampler); | |
390 | |
391 // If this is the first sample of a burst, a new Profile needs to be created | |
392 // and filled. | |
393 if (collection->sample == 0) { | |
394 collection->profiles.push_back(CallStackProfile()); | |
395 CallStackProfile& profile = collection->profiles.back(); | |
396 profile.sampling_period = collection->params.sampling_interval; | |
397 collection->profile_start_time = Time::Now(); | |
398 collection->native_sampler->ProfileRecordingStarting(&profile.modules); | |
399 } | |
400 | |
401 // The currently active profile being captured. | |
402 CallStackProfile& profile = collection->profiles.back(); | |
403 | |
404 // Record a single sample. | |
405 profile.samples.push_back(Sample()); | |
406 collection->native_sampler->RecordStackSample(&profile.samples.back()); | |
407 | |
408 // If this is the last sample of a burst, record the total time. | |
409 if (collection->sample == collection->params.samples_per_burst - 1) { | |
410 profile.profile_duration = Time::Now() - collection->profile_start_time; | |
411 collection->native_sampler->ProfileRecordingStopped(); | |
412 } | |
413 } | |
414 | |
415 void StackSamplingProfiler::SamplingThread::ScheduleShutdownIfIdle() { | |
416 if (!active_collections_.empty()) | |
181 return; | 417 return; |
182 | 418 |
183 CallStackProfiles profiles; | 419 AutoLock lock(task_runner_lock_); |
184 CollectProfiles(&profiles); | 420 if (!task_runner_idle_shutdown_time_.is_zero()) { |
185 concurrent_profiling_lock.Get().Release(); | 421 GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
186 completed_callback_.Run(std::move(profiles)); | 422 FROM_HERE, Bind(&SamplingThread::ShutdownTask, Unretained(this), |
187 } | 423 task_runner_add_events_), |
188 | 424 task_runner_idle_shutdown_time_); |
189 // Depending on how long the sampling takes and the length of the sampling | 425 } |
190 // interval, a burst of samples could take arbitrarily longer than | 426 } |
191 // samples_per_burst * sampling_interval. In this case, we (somewhat | 427 |
192 // arbitrarily) honor the number of samples requested rather than strictly | 428 void StackSamplingProfiler::SamplingThread::AddCollectionTask( |
193 // adhering to the sampling intervals. Once we have established users for the | 429 std::unique_ptr<CollectionContext> collection) { |
194 // StackSamplingProfiler and the collected data to judge, we may go the other | 430 const int collection_id = collection->collection_id; |
195 // way or make this behavior configurable. | 431 const TimeDelta initial_delay = collection->params.initial_delay; |
196 void StackSamplingProfiler::SamplingThread::CollectProfile( | 432 |
197 CallStackProfile* profile, | 433 active_collections_.insert( |
198 TimeDelta* elapsed_time, | 434 std::make_pair(collection_id, std::move(collection))); |
199 bool* was_stopped) { | 435 |
200 ElapsedTimer profile_timer; | 436 GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
201 native_sampler_->ProfileRecordingStarting(&profile->modules); | 437 FROM_HERE, Bind(&SamplingThread::PerformCollectionTask, Unretained(this), |
202 profile->sampling_period = params_.sampling_interval; | 438 collection_id), |
203 *was_stopped = false; | 439 initial_delay); |
204 TimeDelta previous_elapsed_sample_time; | 440 |
205 for (int i = 0; i < params_.samples_per_burst; ++i) { | 441 // Another increment of "create requests" serves to invalidate any pending |
206 if (i != 0) { | 442 // shutdown tasks that may have been initiated between the Add() and this |
207 // Always wait, even if for 0 seconds, so we can observe a signal on | 443 // task running. |
208 // stop_event_. | 444 { |
209 if (stop_event_.TimedWait( | 445 AutoLock lock(task_runner_lock_); |
210 std::max(params_.sampling_interval - previous_elapsed_sample_time, | 446 ++task_runner_add_events_; |
211 TimeDelta()))) { | 447 } |
212 *was_stopped = true; | 448 } |
213 break; | 449 |
214 } | 450 void StackSamplingProfiler::SamplingThread::RemoveCollectionTask(int id) { |
215 } | 451 auto found = active_collections_.find(id); |
216 ElapsedTimer sample_timer; | 452 if (found == active_collections_.end()) |
217 profile->samples.push_back(Sample()); | |
218 native_sampler_->RecordStackSample(&profile->samples.back()); | |
219 previous_elapsed_sample_time = sample_timer.Elapsed(); | |
220 } | |
221 | |
222 *elapsed_time = profile_timer.Elapsed(); | |
223 profile->profile_duration = *elapsed_time; | |
224 native_sampler_->ProfileRecordingStopped(); | |
225 } | |
226 | |
227 // In an analogous manner to CollectProfile() and samples exceeding the expected | |
228 // total sampling time, bursts may also exceed the burst_interval. We adopt the | |
229 // same wait-and-see approach here. | |
230 void StackSamplingProfiler::SamplingThread::CollectProfiles( | |
231 CallStackProfiles* profiles) { | |
232 if (stop_event_.TimedWait(params_.initial_delay)) | |
233 return; | 453 return; |
234 | 454 |
235 TimeDelta previous_elapsed_profile_time; | 455 FinishCollection(found->second.get()); |
236 for (int i = 0; i < params_.bursts; ++i) { | 456 ScheduleShutdownIfIdle(); |
237 if (i != 0) { | 457 } |
238 // Always wait, even if for 0 seconds, so we can observe a signal on | 458 |
239 // stop_event_. | 459 void StackSamplingProfiler::SamplingThread::PerformCollectionTask(int id) { |
240 if (stop_event_.TimedWait( | 460 auto found = active_collections_.find(id); |
241 std::max(params_.burst_interval - previous_elapsed_profile_time, | 461 |
242 TimeDelta()))) | 462 // The task won't be found if it has been stopped. |
243 return; | 463 if (found == active_collections_.end()) |
244 } | 464 return; |
245 | 465 |
246 CallStackProfile profile; | 466 CollectionContext* collection = found->second.get(); |
247 bool was_stopped = false; | 467 |
248 CollectProfile(&profile, &previous_elapsed_profile_time, &was_stopped); | 468 // Handle first-run with no "next time". |
249 if (!profile.samples.empty()) | 469 if (collection->next_sample_time == Time()) |
250 profiles->push_back(std::move(profile)); | 470 collection->next_sample_time = Time::Now(); |
251 | 471 |
252 if (was_stopped) | 472 // Do the collection of a single sample. |
253 return; | 473 RecordSample(collection); |
254 } | 474 |
255 } | 475 // Update the time of the next sample recording. |
256 | 476 if (UpdateNextSampleTime(collection)) { |
257 void StackSamplingProfiler::SamplingThread::Stop() { | 477 bool success = GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
258 stop_event_.Signal(); | 478 FROM_HERE, |
479 Bind(&SamplingThread::PerformCollectionTask, Unretained(this), id), | |
480 std::max(collection->next_sample_time - Time::Now(), TimeDelta())); | |
481 DCHECK(success); | |
482 } else { | |
483 // All capturing has completed so finish the collection. Let object expire. | |
484 // The |collection| variable will be invalid after this call. | |
485 FinishCollection(collection); | |
486 ScheduleShutdownIfIdle(); | |
487 } | |
488 } | |
489 | |
490 void StackSamplingProfiler::SamplingThread::ShutdownTask(int add_events) { | |
491 // Holding this lock ensures that any attempt to start another job will | |
492 // get postponed until task_runner_ is cleared, thus eliminating the race. | |
493 AutoLock lock(task_runner_lock_); | |
494 | |
495 // If the current count of creation requests doesn't match the passed count | |
496 // then other tasks have been created since this was posted. Abort shutdown. | |
497 if (task_runner_add_events_ != add_events) | |
498 return; | |
499 | |
500 // There can be no new AddCollectionTasks at this point because creating | |
501 // those always increments "create requests". There may be other requests, | |
502 // like Remove, but it's okay to schedule the thread to stop once they've | |
503 // been executed (i.e. "soon"). | |
504 StopSoon(); | |
505 | |
506 // StopSoon will have set the owning sequence (again) so it must be detached | |
507 // (again) in order for Stop/Start to be called (again) should more work | |
508 // come in. Holding the |task_runner_lock_| ensures the necessary happens- | |
509 // after with regard to this detach and future Thread API calls. | |
510 DetachFromSequence(); | |
511 | |
512 // Clear the task_runner_ variable so the thread will be restarted when | |
513 // new work comes in. | |
514 task_runner_ = nullptr; | |
515 } | |
516 | |
517 bool StackSamplingProfiler::SamplingThread::UpdateNextSampleTime( | |
518 CollectionContext* collection) { | |
519 // This will keep a consistent average interval between samples but will | |
520 // result in constant series of acquisitions, thus nearly locking out the | |
521 // target thread, if the interval is smaller than the time it takes to | |
522 // actually acquire the sample. Anything sampling that quickly is going | |
523 // to be a problem anyway so don't worry about it. | |
524 if (++collection->sample < collection->params.samples_per_burst) { | |
525 collection->next_sample_time += collection->params.sampling_interval; | |
526 return true; | |
527 } | |
528 | |
529 if (++collection->burst < collection->params.bursts) { | |
530 collection->sample = 0; | |
531 collection->next_sample_time += collection->params.burst_interval; | |
532 return true; | |
533 } | |
534 | |
535 return false; | |
536 } | |
537 | |
538 void StackSamplingProfiler::SamplingThread::CleanUp() { | |
539 // There should be no collections remaining when the thread stops. | |
540 DCHECK(active_collections_.empty()); | |
541 | |
542 // Let the parent clean up. | |
543 Thread::CleanUp(); | |
259 } | 544 } |
260 | 545 |
261 // StackSamplingProfiler ------------------------------------------------------ | 546 // StackSamplingProfiler ------------------------------------------------------ |
262 | 547 |
548 // static | |
549 bool StackSamplingProfiler::TestAPI::IsSamplingThreadRunning() { | |
550 return SamplingThread::GetInstance()->IsRunning(); | |
551 } | |
552 | |
553 // static | |
554 void StackSamplingProfiler::TestAPI::SetSamplingThreadIdleShutdownTime( | |
555 int shutdown_ms) { | |
556 SamplingThread::TestAPI::SetIdleShutdownTime(shutdown_ms); | |
557 } | |
558 | |
559 // static | |
560 void StackSamplingProfiler::TestAPI::InitiateSamplingThreadIdleShutdown() { | |
561 SamplingThread::TestAPI::ShutdownIfIdle(); | |
562 } | |
563 | |
263 subtle::Atomic32 StackSamplingProfiler::process_milestones_ = 0; | 564 subtle::Atomic32 StackSamplingProfiler::process_milestones_ = 0; |
264 | 565 |
265 StackSamplingProfiler::SamplingParams::SamplingParams() | 566 StackSamplingProfiler::SamplingParams::SamplingParams() |
266 : initial_delay(TimeDelta::FromMilliseconds(0)), | 567 : initial_delay(TimeDelta::FromMilliseconds(0)), |
267 bursts(1), | 568 bursts(1), |
268 burst_interval(TimeDelta::FromMilliseconds(10000)), | 569 burst_interval(TimeDelta::FromMilliseconds(10000)), |
269 samples_per_burst(300), | 570 samples_per_burst(300), |
270 sampling_interval(TimeDelta::FromMilliseconds(100)) { | 571 sampling_interval(TimeDelta::FromMilliseconds(100)) { |
271 } | 572 } |
272 | 573 |
273 StackSamplingProfiler::StackSamplingProfiler( | 574 StackSamplingProfiler::StackSamplingProfiler( |
274 PlatformThreadId thread_id, | |
275 const SamplingParams& params, | 575 const SamplingParams& params, |
276 const CompletedCallback& callback) | 576 const CompletedCallback& callback, |
277 : StackSamplingProfiler(thread_id, params, callback, nullptr) {} | 577 NativeStackSamplerTestDelegate* test_delegate) |
578 : StackSamplingProfiler(base::PlatformThread::CurrentId(), | |
579 params, | |
580 callback, | |
581 test_delegate) {} | |
278 | 582 |
279 StackSamplingProfiler::StackSamplingProfiler( | 583 StackSamplingProfiler::StackSamplingProfiler( |
280 PlatformThreadId thread_id, | 584 PlatformThreadId thread_id, |
281 const SamplingParams& params, | 585 const SamplingParams& params, |
282 const CompletedCallback& callback, | 586 const CompletedCallback& callback, |
283 NativeStackSamplerTestDelegate* test_delegate) | 587 NativeStackSamplerTestDelegate* test_delegate) |
284 : thread_id_(thread_id), params_(params), completed_callback_(callback), | 588 : thread_id_(thread_id), |
285 test_delegate_(test_delegate) { | 589 params_(params), |
286 } | 590 completed_callback_(callback), |
591 finished_event_(WaitableEvent::ResetPolicy::MANUAL, | |
592 WaitableEvent::InitialState::SIGNALED), | |
Mike Wittman
2017/02/22 20:32:18
Comment on why the initial state is signaled.
bcwhite
2017/02/24 20:39:24
Done.
| |
593 collection_id_(NO_ID), | |
594 test_delegate_(test_delegate) {} | |
287 | 595 |
288 StackSamplingProfiler::~StackSamplingProfiler() { | 596 StackSamplingProfiler::~StackSamplingProfiler() { |
597 // Stop is immediate but asynchronous. There is a non-zero probability that | |
598 // one more sample will be taken after this call returns. | |
289 Stop(); | 599 Stop(); |
290 if (!sampling_thread_handle_.is_null()) | |
291 PlatformThread::Join(sampling_thread_handle_); | |
292 } | |
293 | 600 |
294 // static | 601 // The behavior of sampling a thread that has exited is undefined and could |
295 void StackSamplingProfiler::StartAndRunAsync( | 602 // cause Bad Things(tm) to occur. The safety model provided by this class is |
296 PlatformThreadId thread_id, | 603 // that an instance of this object is expected to live at least as long as |
297 const SamplingParams& params, | 604 // the thread it is sampling. However, because the sampling is performed |
298 const CompletedCallback& callback) { | 605 // asynchronously by the SamplingThread, there is no way to guarantee this |
299 CHECK(ThreadTaskRunnerHandle::Get()); | 606 // is true without waiting for it to signal that it has finished. |
300 AsyncRunner::Run(thread_id, params, callback); | 607 // |
608 // The wait time should, at most, be only as long as it takes to collect one | |
609 // sample (~200us) or none at all if sampling has already completed. | |
610 ThreadRestrictions::ScopedAllowWait allow_wait; | |
611 finished_event_.Wait(); | |
301 } | 612 } |
302 | 613 |
303 void StackSamplingProfiler::Start() { | 614 void StackSamplingProfiler::Start() { |
304 if (completed_callback_.is_null()) | 615 if (completed_callback_.is_null()) |
305 return; | 616 return; |
306 | 617 |
307 std::unique_ptr<NativeStackSampler> native_sampler = | 618 std::unique_ptr<NativeStackSampler> native_sampler = |
308 NativeStackSampler::Create(thread_id_, &RecordAnnotations, | 619 NativeStackSampler::Create(thread_id_, &RecordAnnotations, |
309 test_delegate_); | 620 test_delegate_); |
621 | |
310 if (!native_sampler) | 622 if (!native_sampler) |
311 return; | 623 return; |
312 | 624 |
313 sampling_thread_.reset(new SamplingThread(std::move(native_sampler), params_, | 625 // If the finished-event is not signalled (default state is signalled) then |
314 completed_callback_)); | 626 // profiling has been previously started but has not completed. Wait for it |
315 if (!PlatformThread::Create(0, sampling_thread_.get(), | 627 // to do so and then reset it for this run. |
316 &sampling_thread_handle_)) | 628 if (!finished_event_.IsSignaled()) |
317 sampling_thread_.reset(); | 629 finished_event_.Wait(); |
630 finished_event_.Reset(); | |
Mike Wittman
2017/02/22 20:32:18
This code is equivalent to just:
finished_event_
bcwhite
2017/02/24 20:39:24
Done.
| |
631 | |
632 DCHECK_EQ(NO_ID, collection_id_); | |
633 collection_id_ = SamplingThread::GetInstance()->Add( | |
634 MakeUnique<SamplingThread::CollectionContext>( | |
635 thread_id_, params_, completed_callback_, &finished_event_, | |
636 std::move(native_sampler))); | |
637 DCHECK_NE(NO_ID, collection_id_); | |
318 } | 638 } |
319 | 639 |
320 void StackSamplingProfiler::Stop() { | 640 void StackSamplingProfiler::Stop() { |
321 if (sampling_thread_) | 641 if (collection_id_ == NO_ID) { |
322 sampling_thread_->Stop(); | 642 finished_event_.Signal(); |
Mike Wittman
2017/02/22 20:32:17
This is no longer necessary.
bcwhite
2017/02/24 20:39:24
Done.
| |
643 return; | |
644 } | |
645 | |
646 SamplingThread::GetInstance()->Remove(collection_id_); | |
647 collection_id_ = NO_ID; | |
323 } | 648 } |
324 | 649 |
325 // static | 650 // static |
326 void StackSamplingProfiler::SetProcessMilestone(int milestone) { | 651 void StackSamplingProfiler::SetProcessMilestone(int milestone) { |
327 DCHECK_LE(0, milestone); | 652 DCHECK_LE(0, milestone); |
328 DCHECK_GT(static_cast<int>(sizeof(process_milestones_) * 8), milestone); | 653 DCHECK_GT(static_cast<int>(sizeof(process_milestones_) * 8), milestone); |
329 DCHECK_EQ(0, subtle::NoBarrier_Load(&process_milestones_) & (1 << milestone)); | 654 DCHECK_EQ(0, subtle::NoBarrier_Load(&process_milestones_) & (1 << milestone)); |
330 ChangeAtomicFlags(&process_milestones_, 1 << milestone, 0); | 655 ChangeAtomicFlags(&process_milestones_, 1 << milestone, 0); |
331 } | 656 } |
332 | 657 |
(...skipping 45 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
378 } | 703 } |
379 | 704 |
380 bool operator<(const StackSamplingProfiler::Frame &a, | 705 bool operator<(const StackSamplingProfiler::Frame &a, |
381 const StackSamplingProfiler::Frame &b) { | 706 const StackSamplingProfiler::Frame &b) { |
382 return (a.module_index < b.module_index) || | 707 return (a.module_index < b.module_index) || |
383 (a.module_index == b.module_index && | 708 (a.module_index == b.module_index && |
384 a.instruction_pointer < b.instruction_pointer); | 709 a.instruction_pointer < b.instruction_pointer); |
385 } | 710 } |
386 | 711 |
387 } // namespace base | 712 } // namespace base |
OLD | NEW |