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