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

Side by Side Diff: base/profiler/stack_sampling_profiler.cc

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

Powered by Google App Engine
This is Rietveld 408576698