OLD | NEW |
---|---|
1 // Copyright 2015 The Chromium Authors. All rights reserved. | 1 // Copyright 2015 The Chromium Authors. All rights reserved. |
2 // Use of this source code is governed by a BSD-style license that can be | 2 // Use of this source code is governed by a BSD-style license that can be |
3 // found in the LICENSE file. | 3 // found in the LICENSE file. |
4 | 4 |
5 #include "base/profiler/stack_sampling_profiler.h" | 5 #include "base/profiler/stack_sampling_profiler.h" |
6 | 6 |
7 #include <algorithm> | 7 #include <algorithm> |
8 #include <map> | |
8 #include <utility> | 9 #include <utility> |
9 | 10 |
11 #include "base/atomic_sequence_num.h" | |
12 #include "base/atomicops.h" | |
10 #include "base/bind.h" | 13 #include "base/bind.h" |
11 #include "base/bind_helpers.h" | 14 #include "base/bind_helpers.h" |
12 #include "base/callback.h" | 15 #include "base/callback.h" |
13 #include "base/lazy_instance.h" | 16 #include "base/lazy_instance.h" |
14 #include "base/location.h" | 17 #include "base/location.h" |
15 #include "base/macros.h" | 18 #include "base/macros.h" |
19 #include "base/memory/ptr_util.h" | |
20 #include "base/memory/singleton.h" | |
16 #include "base/profiler/native_stack_sampler.h" | 21 #include "base/profiler/native_stack_sampler.h" |
17 #include "base/synchronization/lock.h" | 22 #include "base/synchronization/lock.h" |
23 #include "base/threading/thread.h" | |
24 #include "base/threading/thread_restrictions.h" | |
18 #include "base/threading/thread_task_runner_handle.h" | 25 #include "base/threading/thread_task_runner_handle.h" |
19 #include "base/timer/elapsed_timer.h" | 26 #include "base/timer/elapsed_timer.h" |
20 | 27 |
21 namespace base { | 28 namespace base { |
22 | 29 |
23 namespace { | 30 namespace { |
24 | 31 |
25 // Used to ensure only one profiler is running at a time. | |
26 LazyInstance<Lock>::Leaky concurrent_profiling_lock = LAZY_INSTANCE_INITIALIZER; | |
27 | |
28 // AsyncRunner ---------------------------------------------------------------- | |
29 | |
30 // Helper class to allow a profiler to be run completely asynchronously from the | |
31 // initiator, without being concerned with the profiler's lifetime. | |
32 class AsyncRunner { | |
33 public: | |
34 // Sets up a profiler and arranges for it to be deleted on its completed | |
35 // callback. | |
36 static void Run(PlatformThreadId thread_id, | |
37 const StackSamplingProfiler::SamplingParams& params, | |
38 const StackSamplingProfiler::CompletedCallback& callback); | |
39 | |
40 private: | |
41 AsyncRunner(); | |
42 | |
43 // Runs the callback and deletes the AsyncRunner instance. |profiles| is not | |
44 // const& because it must be passed with std::move. | |
45 static void RunCallbackAndDeleteInstance( | |
46 std::unique_ptr<AsyncRunner> object_to_be_deleted, | |
47 const StackSamplingProfiler::CompletedCallback& callback, | |
48 scoped_refptr<SingleThreadTaskRunner> task_runner, | |
49 StackSamplingProfiler::CallStackProfiles profiles); | |
50 | |
51 std::unique_ptr<StackSamplingProfiler> profiler_; | |
52 | |
53 DISALLOW_COPY_AND_ASSIGN(AsyncRunner); | |
54 }; | |
55 | |
56 // static | |
57 void AsyncRunner::Run( | |
58 PlatformThreadId thread_id, | |
59 const StackSamplingProfiler::SamplingParams& params, | |
60 const StackSamplingProfiler::CompletedCallback &callback) { | |
61 std::unique_ptr<AsyncRunner> runner(new AsyncRunner); | |
62 AsyncRunner* temp_ptr = runner.get(); | |
63 temp_ptr->profiler_.reset( | |
64 new StackSamplingProfiler(thread_id, params, | |
65 Bind(&AsyncRunner::RunCallbackAndDeleteInstance, | |
66 Passed(&runner), callback, | |
67 ThreadTaskRunnerHandle::Get()))); | |
68 // The callback won't be called until after Start(), so temp_ptr will still | |
69 // be valid here. | |
70 temp_ptr->profiler_->Start(); | |
71 } | |
72 | |
73 AsyncRunner::AsyncRunner() {} | |
74 | |
75 void AsyncRunner::RunCallbackAndDeleteInstance( | |
76 std::unique_ptr<AsyncRunner> object_to_be_deleted, | |
77 const StackSamplingProfiler::CompletedCallback& callback, | |
78 scoped_refptr<SingleThreadTaskRunner> task_runner, | |
79 StackSamplingProfiler::CallStackProfiles profiles) { | |
80 callback.Run(std::move(profiles)); | |
81 // Delete the instance on the original calling thread. | |
82 task_runner->DeleteSoon(FROM_HERE, object_to_be_deleted.release()); | |
83 } | |
84 | |
85 void ChangeAtomicFlags(subtle::Atomic32* flags, | 32 void ChangeAtomicFlags(subtle::Atomic32* flags, |
86 subtle::Atomic32 set, | 33 subtle::Atomic32 set, |
87 subtle::Atomic32 clear) { | 34 subtle::Atomic32 clear) { |
88 DCHECK(set != 0 || clear != 0); | 35 DCHECK(set != 0 || clear != 0); |
89 DCHECK_EQ(0, set & clear); | 36 DCHECK_EQ(0, set & clear); |
90 | 37 |
91 subtle::Atomic32 bits = subtle::NoBarrier_Load(flags); | 38 subtle::Atomic32 bits = subtle::NoBarrier_Load(flags); |
92 while (true) { | 39 while (true) { |
93 subtle::Atomic32 existing = | 40 subtle::Atomic32 existing = |
94 subtle::NoBarrier_CompareAndSwap(flags, bits, (bits | set) & ~clear); | 41 subtle::NoBarrier_CompareAndSwap(flags, bits, (bits | set) & ~clear); |
(...skipping 58 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
153 StackSamplingProfiler::CallStackProfile | 100 StackSamplingProfiler::CallStackProfile |
154 StackSamplingProfiler::CallStackProfile::CopyForTesting() const { | 101 StackSamplingProfiler::CallStackProfile::CopyForTesting() const { |
155 return CallStackProfile(*this); | 102 return CallStackProfile(*this); |
156 } | 103 } |
157 | 104 |
158 StackSamplingProfiler::CallStackProfile::CallStackProfile( | 105 StackSamplingProfiler::CallStackProfile::CallStackProfile( |
159 const CallStackProfile& other) = default; | 106 const CallStackProfile& other) = default; |
160 | 107 |
161 // StackSamplingProfiler::SamplingThread -------------------------------------- | 108 // StackSamplingProfiler::SamplingThread -------------------------------------- |
162 | 109 |
163 StackSamplingProfiler::SamplingThread::SamplingThread( | 110 class StackSamplingProfiler::SamplingThread : public Thread { |
164 std::unique_ptr<NativeStackSampler> native_sampler, | 111 public: |
165 const SamplingParams& params, | 112 struct CollectionContext { |
166 const CompletedCallback& completed_callback) | 113 CollectionContext(PlatformThreadId target, |
167 : native_sampler_(std::move(native_sampler)), | 114 const SamplingParams& params, |
168 params_(params), | 115 const CompletedCallback& callback, |
169 stop_event_(WaitableEvent::ResetPolicy::AUTOMATIC, | 116 WaitableEvent* finished, |
170 WaitableEvent::InitialState::NOT_SIGNALED), | 117 std::unique_ptr<NativeStackSampler> sampler) |
171 completed_callback_(completed_callback) {} | 118 : collection_id(next_collection_id_.GetNext()), |
172 | 119 target(target), |
173 StackSamplingProfiler::SamplingThread::~SamplingThread() {} | 120 params(params), |
174 | 121 callback(callback), |
175 void StackSamplingProfiler::SamplingThread::ThreadMain() { | 122 finished(finished), |
176 PlatformThread::SetName("Chrome_SamplingProfilerThread"); | 123 native_sampler(std::move(sampler)) {} |
177 | 124 ~CollectionContext() {} |
178 // For now, just ignore any requests to profile while another profiler is | 125 |
179 // working. | 126 // An identifier for this collection, used to uniquely identify it to |
180 if (!concurrent_profiling_lock.Get().Try()) | 127 // outside interests. |
128 const int collection_id; | |
129 | |
130 const PlatformThreadId target; // ID of The thread being sampled. | |
131 const SamplingParams params; // Information about how to sample. | |
132 const CompletedCallback callback; // Callback made when sampling complete. | |
133 WaitableEvent* const finished; // Signaled when all sampling complete. | |
134 | |
135 // Platform-specific module that does the actual sampling. | |
136 const std::unique_ptr<NativeStackSampler> native_sampler; | |
137 | |
138 // The absolute time for the next sample. | |
139 Time next_sample_time; | |
140 | |
141 // The time that a profile was started, for calculating the total duration. | |
142 Time profile_start_time; | |
143 | |
144 // Counters that indicate the current position along the acquisition. | |
145 int burst = 0; | |
146 int sample = 0; | |
147 | |
148 // The collected stack samples. The active profile is always at the back(). | |
149 CallStackProfiles profiles; | |
150 | |
151 private: | |
152 static StaticAtomicSequenceNumber next_collection_id_; | |
153 }; | |
154 | |
155 // Gets the single instance of this class. | |
156 static SamplingThread* GetInstance(); | |
157 | |
158 // Starts the thread. | |
159 void Start(); | |
160 | |
161 // Adds a new CollectionContext to the thread. This can be called externally | |
162 // from any thread. This returns an ID that can later be used to stop | |
163 // the sampling. | |
164 int Add(std::unique_ptr<CollectionContext> collection); | |
165 | |
166 // Removes an active collection based on its ID, forcing it to run its | |
167 // callback if any data has been collected. This can be called externally | |
168 // from any thread. | |
169 void Remove(int id); | |
170 | |
171 // Begins an idle shutdown as if the idle-timer had expired. | |
172 void ShutdownIfIdle(); | |
173 | |
174 // Sets the number of ms to wait after becoming idle before shutting down. | |
175 // Set to zero to disable. | |
176 void SetIdleShutdownTime(int shutdown_ms); | |
177 | |
178 private: | |
179 SamplingThread(); | |
180 ~SamplingThread() override; | |
181 friend struct DefaultSingletonTraits<SamplingThread>; | |
182 | |
183 // Get task runner that is usable from the outside. | |
184 scoped_refptr<SingleThreadTaskRunner> GetOrCreateTaskRunner(); | |
185 scoped_refptr<SingleThreadTaskRunner> GetTaskRunner(); | |
186 | |
187 // Get task runner that is usable from the sampling thread itself. | |
188 scoped_refptr<SingleThreadTaskRunner> GetTaskRunnerOnSamplingThread(); | |
189 | |
190 // Finishes a collection and reports collected data via callback. | |
191 void FinishCollection(CollectionContext* collection); | |
192 | |
193 // Records a single sample of a collection. | |
194 void RecordSample(CollectionContext* collection); | |
195 | |
196 // Check if the sampling thread is idle. | |
197 void CheckForIdle(); | |
198 | |
199 // These methods are tasks that get posted to the internal message queue. | |
200 void AddCollectionTask(std::unique_ptr<CollectionContext> collection_ptr); | |
201 void RemoveCollectionTask(int id); | |
202 void PerformCollectionTask(int id); | |
203 void ShutdownTask(); | |
204 | |
205 // Updates the |next_sample_time| time based on configured parameters. | |
206 bool UpdateNextSampleTime(CollectionContext* collection); | |
207 | |
208 // Thread: | |
209 void CleanUp() override; | |
210 | |
211 // The task-runner for the sampling thread and some information about it. | |
212 // This must always be accessed while holding the lock. The saved task-runner | |
213 // can be freely used by any calling thread. | |
214 scoped_refptr<SingleThreadTaskRunner> task_runner_; | |
215 int task_runner_create_requests_ = 0; | |
216 TimeDelta task_runner_idle_shutdown_time_ = TimeDelta::FromSeconds(5); | |
Mike Wittman
2017/02/15 03:26:44
I think it's worth bumping this up to something mo
bcwhite
2017/02/15 16:17:34
Done.
| |
217 Lock task_runner_lock_; | |
218 | |
219 // A map of IDs to collection contexts. Because this class is a singleton | |
220 // that is never destroyed, context objects will never be destructed except | |
221 // by explicit action. Thus, it's acceptable to pass unretained pointers | |
222 // to these objects when posting tasks. | |
223 std::map<int, std::unique_ptr<CollectionContext>> active_collections_; | |
224 | |
225 DISALLOW_COPY_AND_ASSIGN(SamplingThread); | |
226 }; | |
227 | |
228 StaticAtomicSequenceNumber StackSamplingProfiler::SamplingThread:: | |
229 CollectionContext::next_collection_id_; | |
230 | |
231 StackSamplingProfiler::SamplingThread::SamplingThread() | |
232 : Thread("Chrome_SamplingProfilerThread") {} | |
233 | |
234 StackSamplingProfiler::SamplingThread::~SamplingThread() { | |
235 Stop(); | |
236 } | |
237 | |
238 StackSamplingProfiler::SamplingThread* | |
239 StackSamplingProfiler::SamplingThread::GetInstance() { | |
240 return Singleton<SamplingThread, LeakySingletonTraits<SamplingThread>>::get(); | |
241 } | |
242 | |
243 void StackSamplingProfiler::SamplingThread::Start() { | |
244 Thread::Options options; | |
245 // Use a higher priority for a more accurate sampling interval. | |
246 options.priority = ThreadPriority::DISPLAY; | |
247 Thread::StartWithOptions(options); | |
248 } | |
249 | |
250 int StackSamplingProfiler::SamplingThread::Add( | |
251 std::unique_ptr<CollectionContext> collection) { | |
252 int id = collection->collection_id; | |
253 scoped_refptr<SingleThreadTaskRunner> task_runner = GetOrCreateTaskRunner(); | |
254 | |
255 // There may be no task-runner if the sampling thread has been permanently | |
256 // shut down. | |
257 if (task_runner) { | |
Mike Wittman
2017/02/15 03:26:44
No need to check the task_runner anymore.
bcwhite
2017/02/15 16:17:34
Done.
| |
258 task_runner->PostTask( | |
259 FROM_HERE, Bind(&SamplingThread::AddCollectionTask, Unretained(this), | |
260 Passed(&collection))); | |
261 } | |
262 return id; | |
263 } | |
264 | |
265 void StackSamplingProfiler::SamplingThread::Remove(int id) { | |
266 scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(); | |
267 if (!task_runner) | |
268 return; // Everything has already stopped. | |
269 | |
270 // This can fail if the thread were to exit between acquisition of the task | |
271 // runner above and the call below. In that case, however, everything has | |
272 // stopped so there's no need to try to stop it. | |
273 task_runner->PostTask(FROM_HERE, Bind(&SamplingThread::RemoveCollectionTask, | |
274 Unretained(this), id)); | |
275 } | |
276 | |
277 void StackSamplingProfiler::SamplingThread::ShutdownIfIdle() { | |
278 scoped_refptr<SingleThreadTaskRunner> task_runner = GetTaskRunner(); | |
279 if (!task_runner) | |
280 return; // Everything has already stopped. | |
281 | |
282 // ShutdownTask will check if the thread is idle and skip the shutdown if not. | |
283 task_runner->PostTask(FROM_HERE, | |
284 Bind(&SamplingThread::ShutdownTask, Unretained(this))); | |
285 } | |
286 | |
287 void StackSamplingProfiler::SamplingThread::SetIdleShutdownTime( | |
288 int shutdown_ms) { | |
289 AutoLock lock(task_runner_lock_); | |
290 task_runner_idle_shutdown_time_ = TimeDelta::FromMilliseconds(shutdown_ms); | |
291 } | |
292 | |
293 scoped_refptr<SingleThreadTaskRunner> | |
294 StackSamplingProfiler::SamplingThread::GetOrCreateTaskRunner() { | |
295 AutoLock lock(task_runner_lock_); | |
296 ++task_runner_create_requests_; | |
297 if (!task_runner_) { | |
298 // If this is not the first time the sampling thread has been launched, the | |
299 // previous instance has only been partially cleaned up. It is necessary | |
300 // to call Stop() before Start(). This is safe even the thread has never | |
301 // been started. | |
302 Stop(); | |
303 // The thread is not running. Start it and get associated runner. The task- | |
304 // runner has to be saved for future use because though it can be used from | |
305 // any thread, it can be acquired via task_runner() only on the created | |
306 // thread and the thread that creates it (i.e. this thread). | |
307 Start(); | |
308 task_runner_ = Thread::task_runner(); | |
309 // Detach the sampling thread from the "sequence" (i.e. thread) that | |
310 // started it so that it can be self-managed or stopped on by another | |
Mike Wittman
2017/02/15 03:26:44
nit: stopped by
bcwhite
2017/02/15 16:17:34
Done.
| |
311 // thread. | |
312 DetachFromSequence(); | |
313 } else { | |
314 // This shouldn't be called from the sampling thread as it's inefficient. | |
315 // Use GetTaskRunnerOnSamplingThread() instead. | |
316 DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); | |
317 } | |
318 | |
319 return task_runner_; | |
320 } | |
321 | |
322 scoped_refptr<SingleThreadTaskRunner> | |
323 StackSamplingProfiler::SamplingThread::GetTaskRunner() { | |
324 AutoLock lock(task_runner_lock_); | |
325 | |
326 // GetThreadId() will block for the thread to start so don't check if there | |
327 // is no task-runner. Otherwise, methods like Remove() will wait forever if | |
328 // the thread isn't already running when they could just return. | |
329 if (task_runner_) { | |
330 // This shouldn't be called from the sampling thread as it's inefficient. | |
331 // Use GetTaskRunnerOnSamplingThread() instead. | |
332 DCHECK_NE(GetThreadId(), PlatformThread::CurrentId()); | |
333 } | |
334 | |
335 return task_runner_; | |
336 } | |
337 | |
338 scoped_refptr<SingleThreadTaskRunner> | |
339 StackSamplingProfiler::SamplingThread::GetTaskRunnerOnSamplingThread() { | |
340 // This should be called only from the sampling thread as it has limited | |
341 // accessibility. | |
342 DCHECK_EQ(GetThreadId(), PlatformThread::CurrentId()); | |
343 | |
344 return Thread::task_runner(); | |
345 } | |
346 | |
347 void StackSamplingProfiler::SamplingThread::FinishCollection( | |
348 CollectionContext* collection) { | |
349 // If there is no duration for the final profile (because it was stopped), | |
350 // calculated it now. | |
Mike Wittman
2017/02/15 03:26:44
nit: calculate
bcwhite
2017/02/15 16:17:34
Done.
| |
351 if (!collection->profiles.empty() && | |
352 collection->profiles.back().profile_duration == TimeDelta()) { | |
353 collection->profiles.back().profile_duration = | |
354 Time::Now() - collection->profile_start_time; | |
355 } | |
356 | |
357 // Run the associated callback, passing the collected profiles. It's okay to | |
358 // move them because this collection is about to be deleted. | |
359 collection->callback.Run(std::move(collection->profiles)); | |
360 | |
361 // Signal that this collection is finished. | |
362 collection->finished->Signal(); | |
363 | |
364 // Remove this collection from the map of known ones. This must be done | |
365 // last as the |collection| parameter is invalid after this point. | |
366 size_t count = active_collections_.erase(collection->collection_id); | |
367 DCHECK_EQ(1U, count); | |
368 } | |
369 | |
370 void StackSamplingProfiler::SamplingThread::RecordSample( | |
371 CollectionContext* collection) { | |
372 DCHECK(collection->native_sampler); | |
373 | |
374 // If this is the first sample of a burst, a new Profile needs to be created | |
375 // and filled. | |
376 if (collection->sample == 0) { | |
377 collection->profiles.push_back(CallStackProfile()); | |
378 CallStackProfile& profile = collection->profiles.back(); | |
379 profile.sampling_period = collection->params.sampling_interval; | |
380 collection->profile_start_time = Time::Now(); | |
381 collection->native_sampler->ProfileRecordingStarting(&profile.modules); | |
382 } | |
383 | |
384 // The currently active profile being acptured. | |
385 CallStackProfile& profile = collection->profiles.back(); | |
386 | |
387 // Record a single sample. | |
388 profile.samples.push_back(Sample()); | |
389 Sample& sample = profile.samples.back(); | |
390 collection->native_sampler->RecordStackSample(&sample); | |
Mike Wittman
2017/02/15 03:26:44
nit: RecordStackSample(&profile.samples.back()) an
bcwhite
2017/02/15 16:17:34
Done.
| |
391 | |
392 // If this is the last sample of a burst, record the total time. | |
393 if (collection->sample == collection->params.samples_per_burst - 1) { | |
394 profile.profile_duration = Time::Now() - collection->profile_start_time; | |
395 collection->native_sampler->ProfileRecordingStopped(); | |
396 } | |
397 } | |
398 | |
399 void StackSamplingProfiler::SamplingThread::CheckForIdle() { | |
Mike Wittman
2017/02/15 03:26:44
how about calling this ScheduleShutdownIfIdle, to
bcwhite
2017/02/15 16:17:35
Done.
| |
400 if (!active_collections_.empty()) | |
181 return; | 401 return; |
182 | 402 |
183 CallStackProfiles profiles; | 403 AutoLock lock(task_runner_lock_); |
184 CollectProfiles(&profiles); | 404 if (!task_runner_idle_shutdown_time_.is_zero()) { |
185 concurrent_profiling_lock.Get().Release(); | 405 GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
186 completed_callback_.Run(std::move(profiles)); | 406 FROM_HERE, Bind(&SamplingThread::ShutdownTask, Unretained(this)), |
187 } | 407 task_runner_idle_shutdown_time_); |
188 | 408 } |
189 // Depending on how long the sampling takes and the length of the sampling | 409 } |
190 // interval, a burst of samples could take arbitrarily longer than | 410 |
191 // samples_per_burst * sampling_interval. In this case, we (somewhat | 411 void StackSamplingProfiler::SamplingThread::AddCollectionTask( |
192 // arbitrarily) honor the number of samples requested rather than strictly | 412 std::unique_ptr<CollectionContext> collection_ptr) { |
193 // adhering to the sampling intervals. Once we have established users for the | 413 // Ownership of the collection is going to be given to a map but a pointer |
194 // StackSamplingProfiler and the collected data to judge, we may go the other | 414 // to it will be needed later. |
195 // way or make this behavior configurable. | 415 CollectionContext* collection = collection_ptr.get(); |
Mike Wittman
2017/02/15 03:26:44
nit: better to save off the id and initial_delay a
bcwhite
2017/02/15 16:17:34
Done.
Mike Wittman
2017/02/15 21:56:00
This is no longer potentially dangerous, so I thin
bcwhite
2017/02/16 17:39:49
Done.
| |
196 void StackSamplingProfiler::SamplingThread::CollectProfile( | 416 active_collections_.insert( |
197 CallStackProfile* profile, | 417 std::make_pair(collection->collection_id, std::move(collection_ptr))); |
198 TimeDelta* elapsed_time, | 418 |
199 bool* was_stopped) { | 419 GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
200 ElapsedTimer profile_timer; | 420 FROM_HERE, Bind(&SamplingThread::PerformCollectionTask, Unretained(this), |
201 native_sampler_->ProfileRecordingStarting(&profile->modules); | 421 collection->collection_id), |
202 profile->sampling_period = params_.sampling_interval; | 422 collection->params.initial_delay); |
203 *was_stopped = false; | 423 } |
204 TimeDelta previous_elapsed_sample_time; | 424 |
205 for (int i = 0; i < params_.samples_per_burst; ++i) { | 425 void StackSamplingProfiler::SamplingThread::RemoveCollectionTask(int id) { |
206 if (i != 0) { | 426 auto found = active_collections_.find(id); |
207 // Always wait, even if for 0 seconds, so we can observe a signal on | 427 if (found == active_collections_.end()) |
208 // stop_event_. | |
209 if (stop_event_.TimedWait( | |
210 std::max(params_.sampling_interval - previous_elapsed_sample_time, | |
211 TimeDelta()))) { | |
212 *was_stopped = true; | |
213 break; | |
214 } | |
215 } | |
216 ElapsedTimer sample_timer; | |
217 profile->samples.push_back(Sample()); | |
218 native_sampler_->RecordStackSample(&profile->samples.back()); | |
219 previous_elapsed_sample_time = sample_timer.Elapsed(); | |
220 } | |
221 | |
222 *elapsed_time = profile_timer.Elapsed(); | |
223 profile->profile_duration = *elapsed_time; | |
224 native_sampler_->ProfileRecordingStopped(); | |
225 } | |
226 | |
227 // In an analogous manner to CollectProfile() and samples exceeding the expected | |
228 // total sampling time, bursts may also exceed the burst_interval. We adopt the | |
229 // same wait-and-see approach here. | |
230 void StackSamplingProfiler::SamplingThread::CollectProfiles( | |
231 CallStackProfiles* profiles) { | |
232 if (stop_event_.TimedWait(params_.initial_delay)) | |
233 return; | 428 return; |
234 | 429 |
235 TimeDelta previous_elapsed_profile_time; | 430 FinishCollection(found->second.get()); |
236 for (int i = 0; i < params_.bursts; ++i) { | 431 CheckForIdle(); |
237 if (i != 0) { | 432 } |
238 // Always wait, even if for 0 seconds, so we can observe a signal on | 433 |
239 // stop_event_. | 434 void StackSamplingProfiler::SamplingThread::PerformCollectionTask(int id) { |
240 if (stop_event_.TimedWait( | 435 auto found = active_collections_.find(id); |
241 std::max(params_.burst_interval - previous_elapsed_profile_time, | 436 |
242 TimeDelta()))) | 437 // The task won't be found if it has been stopped. |
243 return; | 438 if (found == active_collections_.end()) |
244 } | 439 return; |
245 | 440 |
246 CallStackProfile profile; | 441 CollectionContext* collection = found->second.get(); |
247 bool was_stopped = false; | 442 |
248 CollectProfile(&profile, &previous_elapsed_profile_time, &was_stopped); | 443 // Handle first-run with no "next time". |
249 if (!profile.samples.empty()) | 444 if (collection->next_sample_time == Time()) |
250 profiles->push_back(std::move(profile)); | 445 collection->next_sample_time = Time::Now(); |
Mike Wittman
2017/02/15 03:26:44
Can we initialize this in the CollectionContext co
bcwhite
2017/02/15 16:17:34
No because it needs to be recorded when the first
Mike Wittman
2017/02/15 22:52:16
But the value recorded isn't derived from next_sam
bcwhite
2017/02/16 17:39:49
next_sample_time is persistent and all sample time
Mike Wittman
2017/02/17 16:10:19
Ah, right. Missed that all the sample times are of
| |
251 | 446 |
252 if (was_stopped) | 447 // Do the collection of a single sample. |
253 return; | 448 RecordSample(collection); |
254 } | 449 |
255 } | 450 // Update the time of the next sample recording. |
256 | 451 if (UpdateNextSampleTime(collection)) { |
257 void StackSamplingProfiler::SamplingThread::Stop() { | 452 bool success = GetTaskRunnerOnSamplingThread()->PostDelayedTask( |
258 stop_event_.Signal(); | 453 FROM_HERE, |
454 Bind(&SamplingThread::PerformCollectionTask, Unretained(this), id), | |
455 std::max(collection->next_sample_time - Time::Now(), TimeDelta())); | |
456 DCHECK(success); | |
457 } else { | |
458 // All capturing has completed so finish the collection. Let object expire. | |
459 // The |collection| variable will be invalid after this call. | |
460 FinishCollection(collection); | |
461 CheckForIdle(); | |
462 } | |
463 } | |
464 | |
465 void StackSamplingProfiler::SamplingThread::ShutdownTask() { | |
466 // Holding this lock ensures that any attempt to start another job will | |
467 // get postponed until StopSoon can run thus eliminating the race. | |
468 AutoLock lock(task_runner_lock_); | |
469 | |
470 // If active_collections_ is not empty, something new has arrived since | |
471 // this task got posted. Abort the shutdown so it can be processed. | |
472 if (!active_collections_.empty()) | |
473 return; | |
474 // It's possible that a new AddCollectionTask has been posted after this | |
475 // task. Reset the "create requests" counter and try again after any other | |
476 // pending tasks. | |
477 if (task_runner_create_requests_ > 0 && task_runner_) { | |
478 task_runner_create_requests_ = 0; | |
479 task_runner_->PostTask( | |
480 FROM_HERE, Bind(&SamplingThread::ShutdownTask, Unretained(this))); | |
481 return; | |
482 } | |
483 | |
484 // There can be no new AddCollectionTasks at this point because creating | |
485 // those always increments "create requests". There may be other requests, | |
486 // like Remove, but it's okay to schedule the thread to stop once they've | |
487 // been executed (i.e. "soon"). | |
488 StopSoon(); | |
489 | |
490 // StopSoon will have set the owning sequence (again) so it must be detached | |
491 // (again) in order for Stop/Start to be called (again) should more work | |
492 // come in. Holding the |task_runner_lock_| ensures the necessary happens- | |
493 // after with regard to this detach and future Thread API calls. | |
494 DetachFromSequence(); | |
495 | |
496 // Clear the task_runner_ variable so the thread will be restarted when | |
497 // new work comes in. | |
498 task_runner_ = nullptr; | |
499 } | |
500 | |
501 bool StackSamplingProfiler::SamplingThread::UpdateNextSampleTime( | |
502 CollectionContext* collection) { | |
503 if (++collection->sample < collection->params.samples_per_burst) { | |
504 collection->next_sample_time += collection->params.sampling_interval; | |
505 return true; | |
506 } | |
507 | |
508 // This will keep a consistent average interval between samples but will | |
Mike Wittman
2017/02/15 03:26:44
Should this comment be on the above if statement?
bcwhite
2017/02/15 16:17:34
Done.
| |
509 // result in constant series of acquisitions, thus nearly locking out the | |
510 // target thread, if the interval is smaller than the time it takes to | |
511 // actually acquire the sample. Anything sampling that quickly is going | |
512 // to be a problem anyway so don't worry about it. | |
513 if (++collection->burst < collection->params.bursts) { | |
514 collection->sample = 0; | |
515 collection->next_sample_time += collection->params.burst_interval; | |
516 return true; | |
517 } | |
518 | |
519 return false; | |
520 } | |
521 | |
522 void StackSamplingProfiler::SamplingThread::CleanUp() { | |
523 // There should be no collections remaining when the thread stops. | |
524 DCHECK(active_collections_.empty()); | |
525 | |
526 // Let the parent clean up. | |
527 Thread::CleanUp(); | |
259 } | 528 } |
260 | 529 |
261 // StackSamplingProfiler ------------------------------------------------------ | 530 // StackSamplingProfiler ------------------------------------------------------ |
262 | 531 |
263 subtle::Atomic32 StackSamplingProfiler::process_milestones_ = 0; | 532 subtle::Atomic32 StackSamplingProfiler::process_milestones_ = 0; |
264 | 533 |
265 StackSamplingProfiler::SamplingParams::SamplingParams() | 534 StackSamplingProfiler::SamplingParams::SamplingParams() |
266 : initial_delay(TimeDelta::FromMilliseconds(0)), | 535 : initial_delay(TimeDelta::FromMilliseconds(0)), |
267 bursts(1), | 536 bursts(1), |
268 burst_interval(TimeDelta::FromMilliseconds(10000)), | 537 burst_interval(TimeDelta::FromMilliseconds(10000)), |
269 samples_per_burst(300), | 538 samples_per_burst(300), |
270 sampling_interval(TimeDelta::FromMilliseconds(100)) { | 539 sampling_interval(TimeDelta::FromMilliseconds(100)) { |
271 } | 540 } |
272 | 541 |
273 StackSamplingProfiler::StackSamplingProfiler( | 542 StackSamplingProfiler::StackSamplingProfiler( |
274 PlatformThreadId thread_id, | |
275 const SamplingParams& params, | 543 const SamplingParams& params, |
276 const CompletedCallback& callback) | 544 const CompletedCallback& callback, |
277 : StackSamplingProfiler(thread_id, params, callback, nullptr) {} | 545 NativeStackSamplerTestDelegate* test_delegate) |
546 : StackSamplingProfiler(base::PlatformThread::CurrentId(), | |
547 params, | |
548 callback, | |
549 test_delegate) {} | |
278 | 550 |
279 StackSamplingProfiler::StackSamplingProfiler( | 551 StackSamplingProfiler::StackSamplingProfiler( |
280 PlatformThreadId thread_id, | 552 PlatformThreadId thread_id, |
281 const SamplingParams& params, | 553 const SamplingParams& params, |
282 const CompletedCallback& callback, | 554 const CompletedCallback& callback, |
283 NativeStackSamplerTestDelegate* test_delegate) | 555 NativeStackSamplerTestDelegate* test_delegate) |
284 : thread_id_(thread_id), params_(params), completed_callback_(callback), | 556 : thread_id_(thread_id), |
557 params_(params), | |
558 completed_callback_(callback), | |
559 finished_event_(WaitableEvent::ResetPolicy::MANUAL, | |
560 WaitableEvent::InitialState::NOT_SIGNALED), | |
285 test_delegate_(test_delegate) { | 561 test_delegate_(test_delegate) { |
562 native_sampler_ = NativeStackSampler::Create(thread_id_, &RecordAnnotations, | |
Mike Wittman
2017/02/15 03:26:44
Can we continue to use the current strategy of con
bcwhite
2017/02/15 16:17:34
I thought about that but decided to leave it this
Mike Wittman
2017/02/15 22:52:16
On second look, I think we have to create the nati
bcwhite
2017/02/16 17:39:49
That was the case but not any more. Ownership of
Mike Wittman
2017/02/17 16:10:19
I just remembered why I implemented the creation o
bcwhite
2017/02/21 16:21:19
Use will always be on a different thread that cons
Mike Wittman
2017/02/21 18:57:02
What's the risk you're concerned about in creating
bcwhite
2017/02/21 21:48:05
That's already done because destruction requires w
Mike Wittman
2017/02/22 03:06:47
That works.
| |
563 test_delegate_); | |
286 } | 564 } |
287 | 565 |
288 StackSamplingProfiler::~StackSamplingProfiler() { | 566 StackSamplingProfiler::~StackSamplingProfiler() { |
567 // Stop is immediate but asynchronous. There is a non-zero probability that | |
568 // one more sample will be taken after this call returns. | |
289 Stop(); | 569 Stop(); |
290 if (!sampling_thread_handle_.is_null()) | |
291 PlatformThread::Join(sampling_thread_handle_); | |
292 } | |
293 | 570 |
294 // static | 571 // The behavior of sampling a thread that has exited is undefined and could |
295 void StackSamplingProfiler::StartAndRunAsync( | 572 // cause Bad Things(tm) to occur. The safety model provided by this class is |
296 PlatformThreadId thread_id, | 573 // that an instance of this object is expected to live at least as long as |
297 const SamplingParams& params, | 574 // the thread it is sampling. However, because the sampling is performed |
298 const CompletedCallback& callback) { | 575 // asynchronously by the SamplingThread, there is no way to guarantee this |
299 CHECK(ThreadTaskRunnerHandle::Get()); | 576 // is true without waiting for it to signal that it has finished. |
300 AsyncRunner::Run(thread_id, params, callback); | 577 // |
578 // The wait time should, at most, be only as long as it takes to execute one | |
579 // short task or none at all if sampling has already completed. | |
Mike Wittman
2017/02/15 03:26:44
nit: ... as long as it takes to collect one sample
bcwhite
2017/02/15 16:17:34
Done.
| |
580 ThreadRestrictions::ScopedAllowWait allow_wait; | |
581 finished_event_.Wait(); | |
301 } | 582 } |
302 | 583 |
303 void StackSamplingProfiler::Start() { | 584 void StackSamplingProfiler::Start() { |
304 if (completed_callback_.is_null()) | 585 if (completed_callback_.is_null()) |
305 return; | 586 return; |
306 | 587 |
307 std::unique_ptr<NativeStackSampler> native_sampler = | 588 if (!native_sampler_) |
308 NativeStackSampler::Create(thread_id_, &RecordAnnotations, | |
309 test_delegate_); | |
310 if (!native_sampler) | |
311 return; | 589 return; |
312 | 590 |
313 sampling_thread_.reset(new SamplingThread(std::move(native_sampler), params_, | 591 DCHECK_EQ(-1, collection_id_); |
314 completed_callback_)); | 592 collection_id_ = SamplingThread::GetInstance()->Add( |
315 if (!PlatformThread::Create(0, sampling_thread_.get(), | 593 MakeUnique<SamplingThread::CollectionContext>( |
316 &sampling_thread_handle_)) | 594 thread_id_, params_, completed_callback_, &finished_event_, |
317 sampling_thread_.reset(); | 595 std::move(native_sampler_))); |
596 DCHECK_NE(-1, collection_id_); | |
318 } | 597 } |
319 | 598 |
320 void StackSamplingProfiler::Stop() { | 599 void StackSamplingProfiler::Stop() { |
321 if (sampling_thread_) | 600 SamplingThread::GetInstance()->Remove(collection_id_); |
322 sampling_thread_->Stop(); | 601 collection_id_ = -1; |
323 } | 602 } |
324 | 603 |
325 // static | 604 // static |
605 bool StackSamplingProfiler::IsSamplingThreadRunningForTesting() { | |
606 return SamplingThread::GetInstance()->IsRunning(); | |
607 } | |
608 | |
609 // static | |
610 void StackSamplingProfiler::SetSamplingThreadIdleShutdownTimeForTesting( | |
611 int shutdown_ms) { | |
612 SamplingThread::GetInstance()->SetIdleShutdownTime(shutdown_ms); | |
613 } | |
614 | |
615 // static | |
616 void StackSamplingProfiler::InitiateSamplingThreadIdleShutdownForTesting() { | |
617 SamplingThread::GetInstance()->ShutdownIfIdle(); | |
618 } | |
619 | |
620 // static | |
326 void StackSamplingProfiler::SetProcessMilestone(int milestone) { | 621 void StackSamplingProfiler::SetProcessMilestone(int milestone) { |
327 DCHECK_LE(0, milestone); | 622 DCHECK_LE(0, milestone); |
328 DCHECK_GT(static_cast<int>(sizeof(process_milestones_) * 8), milestone); | 623 DCHECK_GT(static_cast<int>(sizeof(process_milestones_) * 8), milestone); |
329 DCHECK_EQ(0, subtle::NoBarrier_Load(&process_milestones_) & (1 << milestone)); | 624 DCHECK_EQ(0, subtle::NoBarrier_Load(&process_milestones_) & (1 << milestone)); |
330 ChangeAtomicFlags(&process_milestones_, 1 << milestone, 0); | 625 ChangeAtomicFlags(&process_milestones_, 1 << milestone, 0); |
331 } | 626 } |
332 | 627 |
333 // static | 628 // static |
334 void StackSamplingProfiler::ResetAnnotationsForTesting() { | 629 void StackSamplingProfiler::ResetAnnotationsForTesting() { |
335 subtle::NoBarrier_Store(&process_milestones_, 0u); | 630 subtle::NoBarrier_Store(&process_milestones_, 0u); |
(...skipping 42 matching lines...) Expand 10 before | Expand all | Expand 10 after Loading... | |
378 } | 673 } |
379 | 674 |
380 bool operator<(const StackSamplingProfiler::Frame &a, | 675 bool operator<(const StackSamplingProfiler::Frame &a, |
381 const StackSamplingProfiler::Frame &b) { | 676 const StackSamplingProfiler::Frame &b) { |
382 return (a.module_index < b.module_index) || | 677 return (a.module_index < b.module_index) || |
383 (a.module_index == b.module_index && | 678 (a.module_index == b.module_index && |
384 a.instruction_pointer < b.instruction_pointer); | 679 a.instruction_pointer < b.instruction_pointer); |
385 } | 680 } |
386 | 681 |
387 } // namespace base | 682 } // namespace base |
OLD | NEW |