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