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