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