| 6 |
| 7 | #include <algorithm> |
| 8 | #include <map> |
| 9 | #include <utility> |
| 10 |
| 11 | #include "base/atomic_sequence_num.h" |
| 12 | #include "base/atomicops.h" |
| 13 | #include "base/bind.h" |
| 14 | #include "base/bind_helpers.h" |
| 15 | #include "base/callback.h" |
| 16 | #include "base/location.h" |
| 17 | #include "base/macros.h" |
| 18 | #include "base/memory/ptr_util.h" |
| 19 | #include "base/memory/singleton.h" |
| 20 | #include "base/profiler/stack_buffer.h" |
| 21 | #include "base/profiler/stack_sampler.h" |
| 22 | #include "base/profiler/unwinder.h" |
| 23 | #include "base/synchronization/lock.h" |
| 24 | #include "base/thread_annotations.h" |
| 25 | #include "base/threading/thread.h" |
| 26 | #include "base/threading/thread_restrictions.h" |
| 27 | #include "base/threading/thread_task_runner_handle.h" |
| 28 | #include "base/time/time.h" |
| 29 | #include "base/trace_event/trace_event.h" |
| 30 |
| 31 | namespace base { |
| 32 |
| 33 | // Allows StackSamplingProfiler to recall a thread which should already pretty |
| 34 | // much be dead (thus it should be a fast Join()). |
| 35 | class ScopedAllowThreadRecallForStackSamplingProfiler |
| 36 | : public ScopedAllowBaseSyncPrimitivesOutsideBlockingScope {}; |
| 37 |
| 38 | namespace { |
| 39 |
| 40 | // This value is used to initialize the WaitableEvent object. This MUST BE set |
| 41 | // to MANUAL for correct operation of the IsSignaled() call in Start(). See the |
| 42 | // comment there for why. |
| 43 | constexpr WaitableEvent::ResetPolicy kResetPolicy = |
| 44 | WaitableEvent::ResetPolicy::MANUAL; |
| 45 |
| 46 | // This value is used when there is no collection in progress and thus no ID |
| 47 | // for referencing the active collection to the SamplingThread. |
| 48 | const int kNullProfilerId = -1; |
| 49 |
| 50 | } // namespace |
| 51 |
| 52 | // StackSamplingProfiler::SamplingThread -------------------------------------- |
| 53 |
| 54 | class StackSamplingProfiler::SamplingThread : public Thread { |
| 55 | public: |
| 56 | class TestPeer { |
| 57 | public: |
| 58 | // Reset the existing sampler. This will unfortunately create the object |
| 59 | // unnecessarily if it doesn't already exist but there's no way around that. |
| 60 | static void Reset(); |
| 61 |
| 62 | // Disables inherent idle-shutdown behavior. |
| 63 | static void DisableIdleShutdown(); |
| 64 |
| 65 | // Begins an idle shutdown as if the idle-timer had expired and wait for |
| 66 | // it to execute. Since the timer would have only been started at a time |
| 67 | // when the sampling thread actually was idle, this must be called only |
| 68 | // when it is known that there are no active sampling threads. If |
| 69 | // |simulate_intervening_add| is true then, when executed, the shutdown |
| 70 | // task will believe that a new collection has been added since it was |
| 71 | // posted. |
| 72 | static void ShutdownAssumingIdle(bool simulate_intervening_add); |
| 73 |
| 74 | private: |
| 75 | // Calls the sampling threads ShutdownTask and then signals an event. |
| 76 | static void ShutdownTaskAndSignalEvent(SamplingThread* sampler, |
| 77 | int add_events, |
| 78 | WaitableEvent* event); |
| 79 | }; |
| 80 |
| 81 | struct CollectionContext { |
| 82 | CollectionContext(const SamplingParams& params, |
| 83 | WaitableEvent* finished, |
| 84 | std::unique_ptr<StackSampler> sampler, |
| 85 | std::unique_ptr<ProfileBuilder> profile_builder) |
| 86 | : collection_id(next_collection_id.GetNext()), |
| 87 | params(params), |
| 88 | finished(finished), |
| 89 | sampler(std::move(sampler)), |
| 90 | profile_builder(std::move(profile_builder)) {} |
| 91 | ~CollectionContext() = default; |
| 92 |
| 93 | // An identifier for this collection, used to uniquely identify the |
| 94 | // collection to outside interests. |
| 95 | const int collection_id; |
| 96 |
| 97 | const SamplingParams params; // Information about how to sample. |
| 98 | WaitableEvent* const finished; // Signaled when all sampling complete. |
| 99 |
| 100 | // Platform-specific module that does the actual sampling. |
| 101 | std::unique_ptr<StackSampler> sampler; |
| 102 |
| 103 | // Receives the sampling data and builds a CallStackProfile. |
| 104 | std::unique_ptr<ProfileBuilder> profile_builder; |
| 105 |
| 106 | // The absolute time for the next sample. |
| 107 | TimeTicks next_sample_time; |
| 108 |
| 109 | // The time that a profile was started, for calculating the total duration. |
| 110 | TimeTicks profile_start_time; |
| 111 |
| 112 | // Counter that indicates the current sample position along the acquisition. |
| 113 | int sample_count = 0; |
| 114 |
| 115 | // Sequence number for generating new collection ids. |
| 116 | static AtomicSequenceNumber next_collection_id; |
| 117 | }; |
| 118 |
| 119 | // Gets the single instance of this class. |
| 120 | static SamplingThread* GetInstance(); |
| 121 |
| 122 | // Adds a new CollectionContext to the thread. This can be called externally |
| 123 | // from any thread. This returns a collection id that can later be used to |
| 124 | // stop the sampling. |
| 125 | int Add(std::unique_ptr<CollectionContext> collection); |
| 126 |
| 127 | // Adds an auxiliary unwinder to be used for the collection, to handle |
| 128 | // additional, non-native-code unwind scenarios. |
| 129 | void AddAuxUnwinder(int collection_id, std::unique_ptr<Unwinder> unwinder); |
| 130 |
| 131 | // Applies the metadata to already recorded samples in all collections. |
| 132 | void ApplyMetadataToPastSamples(base::TimeTicks period_start, |
| 133 | base::TimeTicks period_end, |
| 134 | int64_t name_hash, |
| 135 | Optional<int64_t> key, |
| 136 | int64_t value); |
| 137 |
| 138 | // Removes an active collection based on its collection id, forcing it to run |
| 139 | // its callback if any data has been collected. This can be called externally |
| 140 | // from any thread. |
| 141 | void Remove(int collection_id); |
| 142 |
| 143 | private: |
| 144 | friend struct DefaultSingletonTraits<SamplingThread>; |
| 145 |
| 146 | // The different states in which the sampling-thread can be. |
| 147 | enum ThreadExecutionState { |
| 148 | // The thread is not running because it has never been started. It will be |
| 149 | // started when a sampling request is received. |
| 150 | NOT_STARTED, |
| 151 |
| 152 | // The thread is running and processing tasks. This is the state when any |
| 153 | // sampling requests are active and during the "idle" period afterward |
| 154 | // before the thread is stopped. |
| 155 | RUNNING, |
| 156 |
| 157 | // Once all sampling requests have finished and the "idle" period has |
| 158 | // expired, the thread will be set to this state and its shutdown |
| 159 | // initiated. A call to Stop() must be made to ensure the previous thread |
| 160 | // has completely exited before calling Start() and moving back to the |
| 161 | // RUNNING state. |
| 162 | EXITING, |
| 163 | }; |
| 164 |
| 165 | SamplingThread(); |
| 166 | ~SamplingThread() override; |
| 167 |
| 168 | // Get task runner that is usable from the outside. |
| 169 | scoped_refptr<SingleThreadTaskRunner> GetOrCreateTaskRunnerForAdd(); |
| 170 | scoped_refptr<SingleThreadTaskRunner> GetTaskRunner( |
| 171 | ThreadExecutionState* out_state); |
| 172 |
| 173 | // Get task runner that is usable from the sampling thread itself. |
| 174 | scoped_refptr<SingleThreadTaskRunner> GetTaskRunnerOnSamplingThread(); |
| 175 |
| 176 | // Finishes a collection. The collection's |finished| waitable event will be |
| 177 | // signalled. The |collection| should already have been removed from |
| 178 | // |active_collections_| by the caller, as this is needed to avoid flakiness |
| 179 | // in unit tests. |
| 180 | void FinishCollection(CollectionContext* collection); |
| 181 |
| 182 | // Check if the sampling thread is idle and begin a shutdown if it is. |
| 183 | void ScheduleShutdownIfIdle(); |
| 184 |
| 185 | // These methods are tasks that get posted to the internal message queue. |
| 186 | void AddCollectionTask(std::unique_ptr<CollectionContext> collection); |
| 187 | void AddAuxUnwinderTask(int collection_id, |
| 188 | std::unique_ptr<Unwinder> unwinder); |
| 189 | void ApplyMetadataToPastSamplesTask(base::TimeTicks period_start, |
| 190 | base::TimeTicks period_end, |
| 191 | int64_t name_hash, |
| 192 | Optional<int64_t> key, |
| 193 | int64_t value); |
| 194 | void RemoveCollectionTask(int collection_id); |
| 195 | void RecordSampleTask(int collection_id); |
| 196 | void ShutdownTask(int add_events); |
| 197 |
| 198 | // Thread: |
| 199 | void CleanUp() override; |
| 200 |
| 201 | // A stack-buffer used by the sampler for its work. This buffer is re-used |
| 202 | // across multiple sampler objects since their execution is serialized on the |
| 203 | // sampling thread. |
| 204 | std::unique_ptr<StackBuffer> stack_buffer_; |
| 205 |
| 206 | // A map of collection ids to collection contexts. Because this class is a |
| 207 | // singleton that is never destroyed, context objects will never be destructed |
| 208 | // except by explicit action. Thus, it's acceptable to pass unretained |
| 209 | // pointers to these objects when posting tasks. |
| 210 | std::map<int, std::unique_ptr<CollectionContext>> active_collections_; |
| 211 |
| 212 | // State maintained about the current execution (or non-execution) of |
| 213 | // the thread. This state must always be accessed while holding the |
| 214 | // lock. A copy of the task-runner is maintained here for use by any |
| 215 | // calling thread; this is necessary because Thread's accessor for it is |
| 216 | // not itself thread-safe. The lock is also used to order calls to the |
| 217 | // Thread API (Start, Stop, StopSoon, & DetachFromSequence) so that |
| 218 | // multiple threads may make those calls. |
| 219 | Lock thread_execution_state_lock_; // Protects all thread_execution_state_* |
| 220 | ThreadExecutionState thread_execution_state_ |
| 221 | GUARDED_BY(thread_execution_state_lock_) = NOT_STARTED; |
| 222 | scoped_refptr<SingleThreadTaskRunner> thread_execution_state_task_runner_ |
| 223 | GUARDED_BY(thread_execution_state_lock_); |
| 224 | bool thread_execution_state_disable_idle_shutdown_for_testing_ |
| 225 | GUARDED_BY(thread_execution_state_lock_) = false; |
| 226 |
| 227 | // A counter that notes adds of new collection requests. It is incremented |
| 228 | // when changes occur so that delayed shutdown tasks are able to detect if |
| 229 | // something new has happened while it was waiting. Like all "execution_state" |
| 230 | // vars, this must be accessed while holding |thread_execution_state_lock_|. |
| 231 | int thread_execution_state_add_events_ |
| 232 | GUARDED_BY(thread_execution_state_lock_) = 0; |
| 233 |
| 234 | DISALLOW_COPY_AND_ASSIGN(SamplingThread); |
| 235 | }; |
| 236 |
| 237 | // static |
| 238 | void StackSamplingProfiler::SamplingThread::TestPeer::Reset() { |
| 239 | SamplingThread* sampler = SamplingThread::GetInstance(); |
| 240 |
| 241 | ThreadExecutionState state; |
| 242 | { |
| 243 | AutoLock lock(sampler->thread_execution_state_lock_); |
| 244 | state = sampler->thread_execution_state_; |
| 245 | DCHECK(sampler->active_collections_.empty()); |
| 246 | } |
| 247 |
| 248 | // Stop the thread and wait for it to exit. This has to be done through by |
| 249 | // the thread itself because it has taken ownership of its own lifetime. |
| 250 | if (state == RUNNING) { |
| 251 | ShutdownAssumingIdle(false); |
| 252 | state = EXITING; |
| 253 | } |
| 254 | // Make sure thread is cleaned up since state will be reset to NOT_STARTED. |
| 255 | if (state == EXITING) |
| 256 | sampler->Stop(); |
| 257 |
| 258 | // Reset internal variables to the just-initialized state. |
| 259 | { |
| 260 | AutoLock lock(sampler->thread_execution_state_lock_); |
| 261 | sampler->thread_execution_state_ = NOT_STARTED; |
| 262 | sampler->thread_execution_state_task_runner_ = nullptr; |
| 263 | sampler->thread_execution_state_disable_idle_shutdown_for_testing_ = false; |
| 264 | sampler->thread_execution_state_add_events_ = 0; |
| 265 | } |
| 266 | } |
| 267 |
| 268 | // static |
| 269 | void StackSamplingProfiler::SamplingThread::TestPeer::DisableIdleShutdown() { |
| 270 | SamplingThread* sampler = SamplingThread::GetInstance(); |
| 271 |
| 272 | { |
| 273 | AutoLock lock(sampler->thread_execution_state_lock_); |
| 274 | sampler->thread_execution_state_disable_idle_shutdown_for_testing_ = true; |
| 275 | } |
| 276 | } |
| 277 |
| 278 | // static |
| 279 | void StackSamplingProfiler::SamplingThread::TestPeer::ShutdownAssumingIdle( |
| 280 | bool simulate_intervening_add) { |
| 281 | SamplingThread* sampler = SamplingThread::GetInstance(); |
| 282 |
| 283 | ThreadExecutionState state; |
| 284 | scoped_refptr<SingleThreadTaskRunner> task_runner = |
| 285 | sampler->GetTaskRunner(&state); |
| 286 | DCHECK_EQ(RUNNING, state); |
| 287 | DCHECK(task_runner); |
| 288 |
| 289 | int add_events; |
| 290 | { |
| 291 | AutoLock lock(sampler->thread_execution_state_lock_); |
| 292 | add_events = sampler->thread_execution_state_add_events_; |
| 293 | if (simulate_intervening_add) |
| 294 | ++sampler->thread_execution_state_add_events_; |
| 295 | } |
| 296 |
| 297 | WaitableEvent executed(WaitableEvent::ResetPolicy::MANUAL, |
| 298 | WaitableEvent::InitialState::NOT_SIGNALED); |
| 299 | // PostTaskAndReply won't work because thread and associated message-loop may |
| 300 | // be shut down. |
| 301 | task_runner->PostTask( |
| 302 | FROM_HERE, BindOnce(&ShutdownTaskAndSignalEvent, Unretained(sampler), |
| 303 | add_events, Unretained(&executed))); |
| 304 | executed.Wait(); |
| 305 | } |
| 306 |
| 307 | // static |
| 308 | void StackSamplingProfiler::SamplingThread::TestPeer:: |
| 309 | ShutdownTaskAndSignalEvent(SamplingThread* sampler, |
| 310 | int add_events, |
| 311 | WaitableEvent* event) { |
| 312 | sampler->ShutdownTask(add_events); |
| 313 | event->Signal(); |
| 314 | } |
| 315 |
| 316 | AtomicSequenceNumber StackSamplingProfiler::SamplingThread::CollectionContext:: |
| 317 | next_collection_id; |
| 318 |
| 319 | StackSamplingProfiler::SamplingThread::SamplingThread() |
| 320 | : Thread("StackSamplingProfiler") {} |
| 321 |
| 322 | StackSamplingProfiler::SamplingThread::~SamplingThread() = default; |
| 323 |
| 324 | StackSamplingProfiler::SamplingThread* |
| 325 | StackSamplingProfiler::SamplingThread::GetInstance() { |
| 326 | return Singleton<SamplingThread, LeakySingletonTraits<SamplingThread>>::get(); |
| 327 | } |
| 328 |
| 329 | int StackSamplingProfiler::SamplingThread::Add( |
| 330 | std::unique_ptr<CollectionContext> collection) { |
| 331 | // This is not to be run on the sampling thread. |
| 332 |
| 333 | int collection_id = collection->collection_id; |
| 334 | scoped_refptr<SingleThreadTaskRunner> task_runner = |
| 335 | GetOrCreateTaskRunnerForAdd(); |
| 336 |
| 337 | task_runner->PostTask( |
| 338 | FROM_HERE, BindOnce(&SamplingThread::AddCollectionTask, Unretained(this), |
| 339 | std::move(collection))); |
| 340 |
| 341 | return collection_id; |
| 342 | } |
| 343 |
| 344 | void StackSamplingProfiler::SamplingThread::AddAuxUnwinder( |
| 345 | int collection_id, |
| 346 | std::unique_ptr<Unwinder> unwinder) { |
| 347 | ThreadExecutionState state; |
| 348 | scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(&state); |
| 349 | if (state != RUNNING) |
| 350 | return; |
| 351 | DCHECK(task_runner); |
| 352 | task_runner->PostTask( |
| 353 | FROM_HERE, BindOnce(&SamplingThread::AddAuxUnwinderTask, Unretained(this), |
| 354 | collection_id, std::move(unwinder))); |
| 355 | } |
| 356 |
| 357 | void StackSamplingProfiler::SamplingThread::ApplyMetadataToPastSamples( |
| 358 | base::TimeTicks period_start, |
| 359 | base::TimeTicks period_end, |
| 360 | int64_t name_hash, |
| 361 | Optional<int64_t> key, |
| 362 | int64_t value) { |
| 363 | ThreadExecutionState state; |
| 364 | scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(&state); |
| 365 | if (state != RUNNING) |
| 366 | return; |
| 367 | DCHECK(task_runner); |
| 368 | task_runner->PostTask( |
| 369 | FROM_HERE, BindOnce(&SamplingThread::ApplyMetadataToPastSamplesTask, |
| 370 | Unretained(this), period_start, period_end, name_hash, |
| 371 | key, value)); |
| 372 | } |
| 373 |
| 374 | void StackSamplingProfiler::SamplingThread::Remove(int collection_id) { |
| 375 | // This is not to be run on the sampling thread. |
| 376 |
| 377 | ThreadExecutionState state; |
| 378 | scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(&state); |
| 379 | if (state != RUNNING) |
| 380 | return; |
| 381 | DCHECK(task_runner); |
| 382 |
| 383 | // This can fail if the thread were to exit between acquisition of the task |
| 384 | // runner above and the call below. In that case, however, everything has |
| 385 | // stopped so there's no need to try to stop it. |
| 386 | task_runner->PostTask(FROM_HERE, |
| 387 | BindOnce(&SamplingThread::RemoveCollectionTask, |
| 388 | Unretained(this), collection_id)); |
| 389 | } |
| 390 |
| 391 | scoped_refptr<SingleThreadTaskRunner> |
| 392 | StackSamplingProfiler::SamplingThread::GetOrCreateTaskRunnerForAdd() { |
| 393 | AutoLock lock(thread_execution_state_lock_); |
| 394 |
| 395 | // The increment of the "add events" count is why this method is to be only |
| 396 | // called from "add". |
| 397 | ++thread_execution_state_add_events_; |
| 398 |
| 399 | if (thread_execution_state_ == RUNNING) { |
| 400 | DCHECK(thread_execution_state_task_runner_); |
| 401 | // This shouldn't be called from the sampling thread as it's inefficient. |
| 402 | // Use GetTaskRunnerOnSamplingThread() instead. |
| 403 | DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); |
| 404 | return thread_execution_state_task_runner_; |
| 405 | } |
| 406 |
| 407 | if (thread_execution_state_ == EXITING) { |
| 408 | // StopSoon() was previously called to shut down the thread |
| 409 | // asynchonously. Stop() must now be called before calling Start() again to |
| 410 | // reset the thread state. |
| 411 | // |
| 412 | // We must allow blocking here to satisfy the Thread implementation, but in |
| 413 | // practice the Stop() call is unlikely to actually block. For this to |
| 414 | // happen a new profiling request would have to be made within the narrow |
| 415 | // window between StopSoon() and thread exit following the end of the 60 |
| 416 | // second idle period. |
| 417 | ScopedAllowThreadRecallForStackSamplingProfiler allow_thread_join; |
| 418 | Stop(); |
| 419 | } |
| 420 |
| 421 | DCHECK(!stack_buffer_); |
| 422 | stack_buffer_ = StackSampler::CreateStackBuffer(); |
| 423 |
| 424 | // The thread is not running. Start it and get associated runner. The task- |
| 425 | // runner has to be saved for future use because though it can be used from |
| 426 | // any thread, it can be acquired via task_runner() only on the created |
| 427 | // thread and the thread that creates it (i.e. this thread) for thread-safety |
| 428 | // reasons which are alleviated in SamplingThread by gating access to it with |
| 429 | // the |thread_execution_state_lock_|. |
| 430 | Start(); |
| 431 | thread_execution_state_ = RUNNING; |
| 432 | thread_execution_state_task_runner_ = Thread::task_runner(); |
| 433 |
| 434 | // Detach the sampling thread from the "sequence" (i.e. thread) that |
| 435 | // started it so that it can be self-managed or stopped by another thread. |
| 436 | DetachFromSequence(); |
| 437 |
| 438 | return thread_execution_state_task_runner_; |
| 439 | } |
| 440 |
| 441 | scoped_refptr<SingleThreadTaskRunner> |
| 442 | StackSamplingProfiler::SamplingThread::GetTaskRunner( |
| 443 | ThreadExecutionState* out_state) { |
| 444 | AutoLock lock(thread_execution_state_lock_); |
| 445 | if (out_state) |
| 446 | *out_state = thread_execution_state_; |
| 447 | if (thread_execution_state_ == RUNNING) { |
| 448 | // This shouldn't be called from the sampling thread as it's inefficient. |
| 449 | // Use GetTaskRunnerOnSamplingThread() instead. |
| 450 | DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); |
| 451 | DCHECK(thread_execution_state_task_runner_); |
| 452 | } else { |
| 453 | DCHECK(!thread_execution_state_task_runner_); |
| 454 | } |
| 455 |
| 456 | return thread_execution_state_task_runner_; |
| 457 | } |
| 458 |
| 459 | scoped_refptr<SingleThreadTaskRunner> |
| 460 | StackSamplingProfiler::SamplingThread::GetTaskRunnerOnSamplingThread() { |
| 461 | // This should be called only from the sampling thread as it has limited |
| 462 | // accessibility. |
| 463 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 464 |
| 465 | return Thread::task_runner(); |
| 466 | } |
| 467 |
| 468 | void StackSamplingProfiler::SamplingThread::FinishCollection( |
| 469 | CollectionContext* collection) { |
| 470 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 471 | DCHECK_EQ(0u, active_collections_.count(collection->collection_id)); |
| 472 |
| 473 | TimeDelta profile_duration = TimeTicks::Now() - |
| 474 | collection->profile_start_time + |
| 475 | collection->params.sampling_interval; |
| 476 |
| 477 | collection->profile_builder->OnProfileCompleted( |
| 478 | profile_duration, collection->params.sampling_interval); |
| 479 |
| 480 | // Signal that this collection is finished. |
| 481 | collection->finished->Signal(); |
| 482 |
| 483 | ScheduleShutdownIfIdle(); |
| 484 | } |
| 485 |
| 486 | void StackSamplingProfiler::SamplingThread::ScheduleShutdownIfIdle() { |
| 487 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 488 |
| 489 | if (!active_collections_.empty()) |
| 490 | return; |
| 491 |
| 492 | TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), |
| 493 | "StackSamplingProfiler::SamplingThread::ScheduleShutdownIfIdle"); |
| 494 |
| 495 | int add_events; |
| 496 | { |
| 497 | AutoLock lock(thread_execution_state_lock_); |
| 498 | if (thread_execution_state_disable_idle_shutdown_for_testing_) |
| 499 | return; |
| 500 | add_events = thread_execution_state_add_events_; |
| 501 | } |
| 502 |
| 503 | GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
| 504 | FROM_HERE, |
| 505 | BindOnce(&SamplingThread::ShutdownTask, Unretained(this), add_events), |
| 506 | TimeDelta::FromSeconds(60)); |
| 507 | } |
| 508 |
| 509 | void StackSamplingProfiler::SamplingThread::AddAuxUnwinderTask( |
| 510 | int collection_id, |
| 511 | std::unique_ptr<Unwinder> unwinder) { |
| 512 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 513 |
| 514 | auto loc = active_collections_.find(collection_id); |
| 515 | if (loc == active_collections_.end()) |
| 516 | return; |
| 517 |
| 518 | loc->second->sampler->AddAuxUnwinder(std::move(unwinder)); |
| 519 | } |
| 520 |
| 521 | void StackSamplingProfiler::SamplingThread::ApplyMetadataToPastSamplesTask( |
| 522 | base::TimeTicks period_start, |
| 523 | base::TimeTicks period_end, |
| 524 | int64_t name_hash, |
| 525 | Optional<int64_t> key, |
| 526 | int64_t value) { |
| 527 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 528 | ProfileBuilder::MetadataItem item(name_hash, key, value); |
| 529 | for (auto& id_collection_pair : active_collections_) { |
| 530 | id_collection_pair.second->profile_builder->ApplyMetadataRetrospectively( |
| 531 | period_start, period_end, item); |
| 532 | } |
| 533 | } |
| 534 |
| 535 | void StackSamplingProfiler::SamplingThread::AddCollectionTask( |
| 536 | std::unique_ptr<CollectionContext> collection) { |
| 537 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 538 |
| 539 | const int collection_id = collection->collection_id; |
| 540 | const TimeDelta initial_delay = collection->params.initial_delay; |
| 541 |
| 542 | active_collections_.insert( |
| 543 | std::make_pair(collection_id, std::move(collection))); |
| 544 |
| 545 | GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
| 546 | FROM_HERE, |
| 547 | BindOnce(&SamplingThread::RecordSampleTask, Unretained(this), |
| 548 | collection_id), |
| 549 | initial_delay); |
| 550 |
| 551 | // Another increment of "add events" serves to invalidate any pending |
| 552 | // shutdown tasks that may have been initiated between the Add() and this |
| 553 | // task running. |
| 554 | { |
| 555 | AutoLock lock(thread_execution_state_lock_); |
| 556 | ++thread_execution_state_add_events_; |
| 557 | } |
| 558 | } |
| 559 |
| 560 | void StackSamplingProfiler::SamplingThread::RemoveCollectionTask( |
| 561 | int collection_id) { |
| 562 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 563 |
| 564 | auto found = active_collections_.find(collection_id); |
| 565 | if (found == active_collections_.end()) |
| 566 | return; |
| 567 |
| 568 | // Remove |collection| from |active_collections_|. |
| 569 | std::unique_ptr<CollectionContext> collection = std::move(found->second); |
| 570 | size_t count = active_collections_.erase(collection_id); |
| 571 | DCHECK_EQ(1U, count); |
| 572 |
| 573 | FinishCollection(collection.get()); |
| 574 | } |
| 575 |
| 576 | void StackSamplingProfiler::SamplingThread::RecordSampleTask( |
| 577 | int collection_id) { |
| 578 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 579 |
| 580 | auto found = active_collections_.find(collection_id); |
| 581 |
| 582 | // The task won't be found if it has been stopped. |
| 583 | if (found == active_collections_.end()) |
| 584 | return; |
| 585 |
| 586 | CollectionContext* collection = found->second.get(); |
| 587 |
| 588 | // If this is the first sample, the collection params need to be filled. |
| 589 | if (collection->sample_count == 0) { |
| 590 | collection->profile_start_time = TimeTicks::Now(); |
| 591 | collection->next_sample_time = TimeTicks::Now(); |
| 592 | } |
| 593 |
| 594 | // Record a single sample. |
| 595 | collection->sampler->RecordStackFrames(stack_buffer_.get(), |
| 596 | collection->profile_builder.get()); |
| 597 |
| 598 | // Schedule the next sample recording if there is one. |
| 599 | if (++collection->sample_count < collection->params.samples_per_profile) { |
| 600 | if (!collection->params.keep_consistent_sampling_interval) |
| 601 | collection->next_sample_time = TimeTicks::Now(); |
| 602 | collection->next_sample_time += collection->params.sampling_interval; |
| 603 | bool success = GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
| 604 | FROM_HERE, |
| 605 | BindOnce(&SamplingThread::RecordSampleTask, Unretained(this), |
| 606 | collection_id), |
| 607 | std::max(collection->next_sample_time - TimeTicks::Now(), TimeDelta())); |
| 608 | DCHECK(success); |
| 609 | return; |
| 610 | } |
| 611 |
| 612 | // Take ownership of |collection| and remove it from the map. |
| 613 | std::unique_ptr<CollectionContext> owned_collection = |
| 614 | std::move(found->second); |
| 615 | size_t count = active_collections_.erase(collection_id); |
| 616 | DCHECK_EQ(1U, count); |
| 617 |
| 618 | // All capturing has completed so finish the collection. |
| 619 | FinishCollection(collection); |
| 620 | } |
| 621 |
| 622 | void StackSamplingProfiler::SamplingThread::ShutdownTask(int add_events) { |
| 623 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 624 |
| 625 | // Holding this lock ensures that any attempt to start another job will |
| 626 | // get postponed until |thread_execution_state_| is updated, thus eliminating |
| 627 | // the race in starting a new thread while the previous one is exiting. |
| 628 | AutoLock lock(thread_execution_state_lock_); |
| 629 |
| 630 | // If the current count of creation requests doesn't match the passed count |
| 631 | // then other tasks have been created since this was posted. Abort shutdown. |
| 632 | if (thread_execution_state_add_events_ != add_events) |
| 633 | return; |
| 634 |
| 635 | TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), |
| 636 | "StackSamplingProfiler::SamplingThread::ShutdownTask"); |
| 637 |
| 638 | // There can be no new AddCollectionTasks at this point because creating |
| 639 | // those always increments "add events". There may be other requests, like |
| 640 | // Remove, but it's okay to schedule the thread to stop once they've been |
| 641 | // executed (i.e. "soon"). |
| 642 | DCHECK(active_collections_.empty()); |
| 643 | StopSoon(); |
| 644 |
| 645 | // StopSoon will have set the owning sequence (again) so it must be detached |
| 646 | // (again) in order for Stop/Start to be called (again) should more work |
| 647 | // come in. Holding the |thread_execution_state_lock_| ensures the necessary |
| 648 | // happens-after with regard to this detach and future Thread API calls. |
| 649 | DetachFromSequence(); |
| 650 |
| 651 | // Set the thread_state variable so the thread will be restarted when new |
| 652 | // work comes in. Remove the |thread_execution_state_task_runner_| to avoid |
| 653 | // confusion. |
| 654 | thread_execution_state_ = EXITING; |
| 655 | thread_execution_state_task_runner_ = nullptr; |
| 656 | stack_buffer_.reset(); |
| 657 | } |
| 658 |
| 659 | void StackSamplingProfiler::SamplingThread::CleanUp() { |
| 660 | DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); |
| 661 |
| 662 | // There should be no collections remaining when the thread stops. |
| 663 | DCHECK(active_collections_.empty()); |
| 664 |
| 665 | // Let the parent clean up. |
| 666 | Thread::CleanUp(); |
| 667 | } |
| 668 |
| 669 | // StackSamplingProfiler ------------------------------------------------------ |
| 670 |
| 671 | // static |
| 672 | void StackSamplingProfiler::TestPeer::Reset() { |
| 673 | SamplingThread::TestPeer::Reset(); |
| 674 | } |
| 675 |
| 676 | // static |
| 677 | bool StackSamplingProfiler::TestPeer::IsSamplingThreadRunning() { |
| 678 | return SamplingThread::GetInstance()->IsRunning(); |
| 679 | } |
| 680 |
| 681 | // static |
| 682 | void StackSamplingProfiler::TestPeer::DisableIdleShutdown() { |
| 683 | SamplingThread::TestPeer::DisableIdleShutdown(); |
| 684 | } |
| 685 |
| 686 | // static |
| 687 | void StackSamplingProfiler::TestPeer::PerformSamplingThreadIdleShutdown( |
| 688 | bool simulate_intervening_start) { |
| 689 | SamplingThread::TestPeer::ShutdownAssumingIdle(simulate_intervening_start); |
| 690 | } |
| 691 |
| 692 | StackSamplingProfiler::StackSamplingProfiler( |
| 693 | SamplingProfilerThreadToken thread_token, |
| 694 | const SamplingParams& params, |
| 695 | std::unique_ptr<ProfileBuilder> profile_builder, |
| 696 | StackSamplerTestDelegate* test_delegate) |
| 697 | : StackSamplingProfiler(params, std::move(profile_builder), nullptr) { |
| 698 | sampler_ = StackSampler::Create( |
| 699 | thread_token, profile_builder_->GetModuleCache(), test_delegate); |
| 700 | } |
| 701 |
| 702 | StackSamplingProfiler::StackSamplingProfiler( |
| 703 | const SamplingParams& params, |
| 704 | std::unique_ptr<ProfileBuilder> profile_builder, |
| 705 | std::unique_ptr<StackSampler> sampler) |
| 706 | : params_(params), |
| 707 | profile_builder_(std::move(profile_builder)), |
| 708 | sampler_(std::move(sampler)), |
| 709 | // The event starts "signaled" so code knows it's safe to start thread |
| 710 | // and "manual" so that it can be waited in multiple places. |
| 711 | profiling_inactive_(kResetPolicy, WaitableEvent::InitialState::SIGNALED), |
| 712 | profiler_id_(kNullProfilerId) { |
| 713 | TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), |
| 714 | "StackSamplingProfiler::StackSamplingProfiler"); |
| 715 | DCHECK(profile_builder_); |
| 716 | } |
| 717 |
| 718 | StackSamplingProfiler::~StackSamplingProfiler() { |
| 719 | TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), |
| 720 | "StackSamplingProfiler::~StackSamplingProfiler"); |
| 721 |
| 722 | // Stop returns immediately but the shutdown runs asynchronously. There is a |
| 723 | // non-zero probability that one more sample will be taken after this call |
| 724 | // returns. |
| 725 | Stop(); |
| 726 |
| 727 | // The behavior of sampling a thread that has exited is undefined and could |
| 728 | // cause Bad Things(tm) to occur. The safety model provided by this class is |
| 729 | // that an instance of this object is expected to live at least as long as |
| 730 | // the thread it is sampling. However, because the sampling is performed |
| 731 | // asynchronously by the SamplingThread, there is no way to guarantee this |
| 732 | // is true without waiting for it to signal that it has finished. |
| 733 | // |
| 734 | // The wait time should, at most, be only as long as it takes to collect one |
| 735 | // sample (~200us) or none at all if sampling has already completed. |
| 736 | ScopedAllowBaseSyncPrimitivesOutsideBlockingScope allow_wait; |
| 737 | profiling_inactive_.Wait(); |
| 738 | } |
| 739 |
| 740 | void StackSamplingProfiler::Start() { |
| 741 | TRACE_EVENT0(TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), |
| 742 | "StackSamplingProfiler::Start"); |
| 743 |
| 744 | // Multiple calls to Start() for a single StackSamplingProfiler object is not |
| 745 | // allowed. If profile_builder_ is nullptr, then Start() has been called |
| 746 | // already. |
| 747 | DCHECK(profile_builder_); |
| 748 |
| 749 | // |sampler_| will be null if sampling isn't supported on the current |
| 750 | // platform. |
| 751 | if (!sampler_) |
| 752 | return; |
| 753 |
| 754 | if (pending_aux_unwinder_) |
| 755 | sampler_->AddAuxUnwinder(std::move(pending_aux_unwinder_)); |
| 756 |
| 757 | // The IsSignaled() check below requires that the WaitableEvent be manually |
| 758 | // reset, to avoid signaling the event in IsSignaled() itself. |
| 759 | static_assert(kResetPolicy == WaitableEvent::ResetPolicy::MANUAL, |
| 760 | "The reset policy must be set to MANUAL"); |
| 761 |
| 762 | // If a previous profiling phase is still winding down, wait for it to |
| 763 | // complete. We can't use task posting for this coordination because the |
| 764 | // thread owning the profiler may not have a message loop. |
| 765 | if (!profiling_inactive_.IsSignaled()) |
| 766 | profiling_inactive_.Wait(); |
| 767 | profiling_inactive_.Reset(); |
| 768 |
| 769 | DCHECK_EQ(kNullProfilerId, profiler_id_); |
| 770 | profiler_id_ = SamplingThread::GetInstance()->Add( |
| 771 | std::make_unique<SamplingThread::CollectionContext>( |
| 772 | params_, &profiling_inactive_, std::move(sampler_), |
| 773 | std::move(profile_builder_))); |
| 774 | DCHECK_NE(kNullProfilerId, profiler_id_); |
| 775 |
| 776 | TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), |
| 777 | "StackSamplingProfiler::Started", "profiler_id", profiler_id_); |
| 778 | } |
| 779 |
| 780 | void StackSamplingProfiler::Stop() { |
| 781 | TRACE_EVENT1(TRACE_DISABLED_BY_DEFAULT("cpu_profiler"), |
| 782 | "StackSamplingProfiler::Stop", "profiler_id", profiler_id_); |
| 783 |
| 784 | SamplingThread::GetInstance()->Remove(profiler_id_); |
| 785 | profiler_id_ = kNullProfilerId; |
| 786 | } |
| 787 |
| 788 | void StackSamplingProfiler::AddAuxUnwinder(std::unique_ptr<Unwinder> unwinder) { |
| 789 | if (profiler_id_ == kNullProfilerId) { |
| 790 | // We haven't started sampling, and so don't have a sampler to which we can |
| 791 | // pass the unwinder yet. Save it on the instance until we do. |
| 792 | pending_aux_unwinder_ = std::move(unwinder); |
| 793 | return; |
| 794 | } |
| 795 |
| 796 | SamplingThread::GetInstance()->AddAuxUnwinder(profiler_id_, |
| 797 | std::move(unwinder)); |
| 798 | } |
| 799 |
| 800 | // static |
| 801 | void StackSamplingProfiler::ApplyMetadataToPastSamples( |
| 802 | base::TimeTicks period_start, |
| 803 | base::TimeTicks period_end, |
| 804 | int64_t name_hash, |
| 805 | Optional<int64_t> key, |
| 806 | int64_t value) { |
| 807 | SamplingThread::GetInstance()->ApplyMetadataToPastSamples( |
| 808 | period_start, period_end, name_hash, key, value); |
| 809 | } |
| 810 |
| 811 | } // namespace base |
| 812 |