1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/tracked_objects.h"
10 #include "base/format_macros.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/process_util.h"
13 #include "base/profiler/alternate_timer.h"
14 #include "base/stringprintf.h"
15 #include "base/third_party/valgrind/memcheck.h"
16 #include "base/threading/thread_restrictions.h"
17 #include "base/port.h"
19 using base::TimeDelta
;
21 namespace tracked_objects
{
24 // Flag to compile out almost all of the task tracking code.
25 const bool kTrackAllTaskObjects
= true;
27 // TODO(jar): Evaluate the perf impact of enabling this. If the perf impact is
28 // negligible, enable by default.
29 // Flag to compile out parent-child link recording.
30 const bool kTrackParentChildLinks
= false;
32 // When ThreadData is first initialized, should we start in an ACTIVE state to
33 // record all of the startup-time tasks, or should we start up DEACTIVATED, so
34 // that we only record after parsing the command line flag --enable-tracking.
35 // Note that the flag may force either state, so this really controls only the
36 // period of time up until that flag is parsed. If there is no flag seen, then
37 // this state may prevail for much or all of the process lifetime.
38 const ThreadData::Status kInitialStartupState
=
39 ThreadData::PROFILING_CHILDREN_ACTIVE
;
41 // Control whether an alternate time source (Now() function) is supported by
42 // the ThreadData class. This compile time flag should be set to true if we
43 // want other modules (such as a memory allocator, or a thread-specific CPU time
44 // clock) to be able to provide a thread-specific Now() function. Without this
45 // compile-time flag, the code will only support the wall-clock time. This flag
46 // can be flipped to efficiently disable this path (if there is a performance
47 // problem with its presence).
48 static const bool kAllowAlternateTimeSourceHandling
= true;
52 //------------------------------------------------------------------------------
53 // DeathData tallies durations when a death takes place.
55 DeathData::DeathData() {
59 DeathData::DeathData(int count
) {
64 // TODO(jar): I need to see if this macro to optimize branching is worth using.
66 // This macro has no branching, so it is surely fast, and is equivalent to:
69 // We use a macro rather than a template to force this to inline.
70 // Related code for calculating max is discussed on the web.
71 #define CONDITIONAL_ASSIGN(assign_it, target, source) \
72 ((target) ^= ((target) ^ (source)) & -static_cast<int32>(assign_it))
74 void DeathData::RecordDeath(const int32 queue_duration
,
75 const int32 run_duration
,
76 int32 random_number
) {
78 queue_duration_sum_
+= queue_duration
;
79 run_duration_sum_
+= run_duration
;
81 if (queue_duration_max_
< queue_duration
)
82 queue_duration_max_
= queue_duration
;
83 if (run_duration_max_
< run_duration
)
84 run_duration_max_
= run_duration
;
86 // Take a uniformly distributed sample over all durations ever supplied.
87 // The probability that we (instead) use this new sample is 1/count_. This
88 // results in a completely uniform selection of the sample (at least when we
89 // don't clamp count_... but that should be inconsequentially likely).
90 // We ignore the fact that we correlated our selection of a sample to the run
91 // and queue times (i.e., we used them to generate random_number).
92 if (count_
<= 0) { // Handle wrapping of count_, such as in bug 138961.
93 CHECK_GE(count_
- 1, 0); // Detect memory corruption.
94 // We'll just clamp at INT_MAX, but we should note this in the UI as such.
97 if (0 == (random_number
% count_
)) {
98 queue_duration_sample_
= queue_duration
;
99 run_duration_sample_
= run_duration
;
103 int DeathData::count() const { return count_
; }
105 int32
DeathData::run_duration_sum() const { return run_duration_sum_
; }
107 int32
DeathData::run_duration_max() const { return run_duration_max_
; }
109 int32
DeathData::run_duration_sample() const {
110 return run_duration_sample_
;
113 int32
DeathData::queue_duration_sum() const {
114 return queue_duration_sum_
;
117 int32
DeathData::queue_duration_max() const {
118 return queue_duration_max_
;
121 int32
DeathData::queue_duration_sample() const {
122 return queue_duration_sample_
;
125 void DeathData::ResetMax() {
126 run_duration_max_
= 0;
127 queue_duration_max_
= 0;
130 void DeathData::Clear() {
132 run_duration_sum_
= 0;
133 run_duration_max_
= 0;
134 run_duration_sample_
= 0;
135 queue_duration_sum_
= 0;
136 queue_duration_max_
= 0;
137 queue_duration_sample_
= 0;
140 //------------------------------------------------------------------------------
141 DeathDataSnapshot::DeathDataSnapshot()
143 run_duration_sum(-1),
144 run_duration_max(-1),
145 run_duration_sample(-1),
146 queue_duration_sum(-1),
147 queue_duration_max(-1),
148 queue_duration_sample(-1) {
151 DeathDataSnapshot::DeathDataSnapshot(
152 const tracked_objects::DeathData
& death_data
)
153 : count(death_data
.count()),
154 run_duration_sum(death_data
.run_duration_sum()),
155 run_duration_max(death_data
.run_duration_max()),
156 run_duration_sample(death_data
.run_duration_sample()),
157 queue_duration_sum(death_data
.queue_duration_sum()),
158 queue_duration_max(death_data
.queue_duration_max()),
159 queue_duration_sample(death_data
.queue_duration_sample()) {
162 DeathDataSnapshot::~DeathDataSnapshot() {
165 //------------------------------------------------------------------------------
166 BirthOnThread::BirthOnThread(const Location
& location
,
167 const ThreadData
& current
)
168 : location_(location
),
169 birth_thread_(¤t
) {
172 //------------------------------------------------------------------------------
173 BirthOnThreadSnapshot::BirthOnThreadSnapshot() {
176 BirthOnThreadSnapshot::BirthOnThreadSnapshot(
177 const tracked_objects::BirthOnThread
& birth
)
178 : location(birth
.location()),
179 thread_name(birth
.birth_thread()->thread_name()) {
182 BirthOnThreadSnapshot::~BirthOnThreadSnapshot() {
185 //------------------------------------------------------------------------------
186 Births::Births(const Location
& location
, const ThreadData
& current
)
187 : BirthOnThread(location
, current
),
190 int Births::birth_count() const { return birth_count_
; }
192 void Births::RecordBirth() { ++birth_count_
; }
194 void Births::ForgetBirth() { --birth_count_
; }
196 void Births::Clear() { birth_count_
= 0; }
198 //------------------------------------------------------------------------------
199 // ThreadData maintains the central data for all births and deaths on a single
202 // TODO(jar): We should pull all these static vars together, into a struct, and
203 // optimize layout so that we benefit from locality of reference during accesses
207 NowFunction
* ThreadData::now_function_
= NULL
;
209 // A TLS slot which points to the ThreadData instance for the current thread. We
210 // do a fake initialization here (zeroing out data), and then the real in-place
211 // construction happens when we call tls_index_.Initialize().
213 base::ThreadLocalStorage::StaticSlot
ThreadData::tls_index_
= TLS_INITIALIZER
;
216 int ThreadData::worker_thread_data_creation_count_
= 0;
219 int ThreadData::cleanup_count_
= 0;
222 int ThreadData::incarnation_counter_
= 0;
225 ThreadData
* ThreadData::all_thread_data_list_head_
= NULL
;
228 ThreadData
* ThreadData::first_retired_worker_
= NULL
;
231 base::LazyInstance
<base::Lock
>::Leaky
232 ThreadData::list_lock_
= LAZY_INSTANCE_INITIALIZER
;
235 ThreadData::Status
ThreadData::status_
= ThreadData::UNINITIALIZED
;
237 ThreadData::ThreadData(const std::string
& suggested_name
)
239 next_retired_worker_(NULL
),
240 worker_thread_number_(0),
241 incarnation_count_for_pool_(-1) {
242 DCHECK_GE(suggested_name
.size(), 0u);
243 thread_name_
= suggested_name
;
244 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
247 ThreadData::ThreadData(int thread_number
)
249 next_retired_worker_(NULL
),
250 worker_thread_number_(thread_number
),
251 incarnation_count_for_pool_(-1) {
252 CHECK_GT(thread_number
, 0);
253 base::StringAppendF(&thread_name_
, "WorkerThread-%d", thread_number
);
254 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
257 ThreadData::~ThreadData() {}
259 void ThreadData::PushToHeadOfList() {
260 // Toss in a hint of randomness (atop the uniniitalized value).
261 (void)VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(&random_number_
,
262 sizeof(random_number_
));
263 random_number_
+= static_cast<int32
>(this - static_cast<ThreadData
*>(0));
264 random_number_
^= (Now() - TrackedTime()).InMilliseconds();
267 base::AutoLock
lock(*list_lock_
.Pointer());
268 incarnation_count_for_pool_
= incarnation_counter_
;
269 next_
= all_thread_data_list_head_
;
270 all_thread_data_list_head_
= this;
274 ThreadData
* ThreadData::first() {
275 base::AutoLock
lock(*list_lock_
.Pointer());
276 return all_thread_data_list_head_
;
279 ThreadData
* ThreadData::next() const { return next_
; }
282 void ThreadData::InitializeThreadContext(const std::string
& suggested_name
) {
283 if (!Initialize()) // Always initialize if needed.
285 ThreadData
* current_thread_data
=
286 reinterpret_cast<ThreadData
*>(tls_index_
.Get());
287 if (current_thread_data
)
288 return; // Browser tests instigate this.
289 current_thread_data
= new ThreadData(suggested_name
);
290 tls_index_
.Set(current_thread_data
);
294 ThreadData
* ThreadData::Get() {
295 if (!tls_index_
.initialized())
296 return NULL
; // For unittests only.
297 ThreadData
* registered
= reinterpret_cast<ThreadData
*>(tls_index_
.Get());
301 // We must be a worker thread, since we didn't pre-register.
302 ThreadData
* worker_thread_data
= NULL
;
303 int worker_thread_number
= 0;
305 base::AutoLock
lock(*list_lock_
.Pointer());
306 if (first_retired_worker_
) {
307 worker_thread_data
= first_retired_worker_
;
308 first_retired_worker_
= first_retired_worker_
->next_retired_worker_
;
309 worker_thread_data
->next_retired_worker_
= NULL
;
311 worker_thread_number
= ++worker_thread_data_creation_count_
;
315 // If we can't find a previously used instance, then we have to create one.
316 if (!worker_thread_data
) {
317 DCHECK_GT(worker_thread_number
, 0);
318 worker_thread_data
= new ThreadData(worker_thread_number
);
320 DCHECK_GT(worker_thread_data
->worker_thread_number_
, 0);
322 tls_index_
.Set(worker_thread_data
);
323 return worker_thread_data
;
327 void ThreadData::OnThreadTermination(void* thread_data
) {
328 DCHECK(thread_data
); // TLS should *never* call us with a NULL.
329 // We must NOT do any allocations during this callback. There is a chance
330 // that the allocator is no longer active on this thread.
331 if (!kTrackAllTaskObjects
)
332 return; // Not compiled in.
333 reinterpret_cast<ThreadData
*>(thread_data
)->OnThreadTerminationCleanup();
336 void ThreadData::OnThreadTerminationCleanup() {
337 // The list_lock_ was created when we registered the callback, so it won't be
338 // allocated here despite the lazy reference.
339 base::AutoLock
lock(*list_lock_
.Pointer());
340 if (incarnation_counter_
!= incarnation_count_for_pool_
)
341 return; // ThreadData was constructed in an earlier unit test.
343 // Only worker threads need to be retired and reused.
344 if (!worker_thread_number_
) {
347 // We must NOT do any allocations during this callback.
348 // Using the simple linked lists avoids all allocations.
349 DCHECK_EQ(this->next_retired_worker_
, reinterpret_cast<ThreadData
*>(NULL
));
350 this->next_retired_worker_
= first_retired_worker_
;
351 first_retired_worker_
= this;
355 void ThreadData::Snapshot(bool reset_max
, ProcessDataSnapshot
* process_data
) {
356 // Add births that have run to completion to |collected_data|.
357 // |birth_counts| tracks the total number of births recorded at each location
358 // for which we have not seen a death count.
359 BirthCountMap birth_counts
;
360 ThreadData::SnapshotAllExecutedTasks(reset_max
, process_data
, &birth_counts
);
362 // Add births that are still active -- i.e. objects that have tallied a birth,
363 // but have not yet tallied a matching death, and hence must be either
364 // running, queued up, or being held in limbo for future posting.
365 for (BirthCountMap::const_iterator it
= birth_counts
.begin();
366 it
!= birth_counts
.end(); ++it
) {
367 if (it
->second
> 0) {
368 process_data
->tasks
.push_back(
369 TaskSnapshot(*it
->first
, DeathData(it
->second
), "Still_Alive"));
374 Births
* ThreadData::TallyABirth(const Location
& location
) {
375 BirthMap::iterator it
= birth_map_
.find(location
);
377 if (it
!= birth_map_
.end()) {
379 child
->RecordBirth();
381 child
= new Births(location
, *this); // Leak this.
382 // Lock since the map may get relocated now, and other threads sometimes
383 // snapshot it (but they lock before copying it).
384 base::AutoLock
lock(map_lock_
);
385 birth_map_
[location
] = child
;
388 if (kTrackParentChildLinks
&& status_
> PROFILING_ACTIVE
&&
389 !parent_stack_
.empty()) {
390 const Births
* parent
= parent_stack_
.top();
391 ParentChildPair
pair(parent
, child
);
392 if (parent_child_set_
.find(pair
) == parent_child_set_
.end()) {
393 // Lock since the map may get relocated now, and other threads sometimes
394 // snapshot it (but they lock before copying it).
395 base::AutoLock
lock(map_lock_
);
396 parent_child_set_
.insert(pair
);
403 void ThreadData::TallyADeath(const Births
& birth
,
404 int32 queue_duration
,
405 int32 run_duration
) {
406 // Stir in some randomness, plus add constant in case durations are zero.
407 const int32 kSomePrimeNumber
= 2147483647;
408 random_number_
+= queue_duration
+ run_duration
+ kSomePrimeNumber
;
409 // An address is going to have some randomness to it as well ;-).
410 random_number_
^= static_cast<int32
>(&birth
- reinterpret_cast<Births
*>(0));
412 // We don't have queue durations without OS timer. OS timer is automatically
413 // used for task-post-timing, so the use of an alternate timer implies all
414 // queue times are invalid.
415 if (kAllowAlternateTimeSourceHandling
&& now_function_
)
418 DeathMap::iterator it
= death_map_
.find(&birth
);
419 DeathData
* death_data
;
420 if (it
!= death_map_
.end()) {
421 death_data
= &it
->second
;
423 base::AutoLock
lock(map_lock_
); // Lock as the map may get relocated now.
424 death_data
= &death_map_
[&birth
];
425 } // Release lock ASAP.
426 death_data
->RecordDeath(queue_duration
, run_duration
, random_number_
);
428 if (!kTrackParentChildLinks
)
430 if (!parent_stack_
.empty()) { // We might get turned off.
431 DCHECK_EQ(parent_stack_
.top(), &birth
);
437 Births
* ThreadData::TallyABirthIfActive(const Location
& location
) {
438 if (!kTrackAllTaskObjects
)
439 return NULL
; // Not compiled in.
441 if (!TrackingStatus())
443 ThreadData
* current_thread_data
= Get();
444 if (!current_thread_data
)
446 return current_thread_data
->TallyABirth(location
);
450 void ThreadData::TallyRunOnNamedThreadIfTracking(
451 const base::TrackingInfo
& completed_task
,
452 const TrackedTime
& start_of_run
,
453 const TrackedTime
& end_of_run
) {
454 if (!kTrackAllTaskObjects
)
455 return; // Not compiled in.
457 // Even if we have been DEACTIVATED, we will process any pending births so
458 // that our data structures (which counted the outstanding births) remain
460 const Births
* birth
= completed_task
.birth_tally
;
463 ThreadData
* current_thread_data
= Get();
464 if (!current_thread_data
)
467 // To avoid conflating our stats with the delay duration in a PostDelayedTask,
468 // we identify such tasks, and replace their post_time with the time they
469 // were scheduled (requested?) to emerge from the delayed task queue. This
470 // means that queueing delay for such tasks will show how long they went
471 // unserviced, after they *could* be serviced. This is the same stat as we
472 // have for non-delayed tasks, and we consistently call it queueing delay.
473 TrackedTime effective_post_time
= completed_task
.delayed_run_time
.is_null()
474 ? tracked_objects::TrackedTime(completed_task
.time_posted
)
475 : tracked_objects::TrackedTime(completed_task
.delayed_run_time
);
477 // Watch out for a race where status_ is changing, and hence one or both
478 // of start_of_run or end_of_run is zero. In that case, we didn't bother to
479 // get a time value since we "weren't tracking" and we were trying to be
480 // efficient by not calling for a genuine time value. For simplicity, we'll
481 // use a default zero duration when we can't calculate a true value.
482 int32 queue_duration
= 0;
483 int32 run_duration
= 0;
484 if (!start_of_run
.is_null()) {
485 queue_duration
= (start_of_run
- effective_post_time
).InMilliseconds();
486 if (!end_of_run
.is_null())
487 run_duration
= (end_of_run
- start_of_run
).InMilliseconds();
489 current_thread_data
->TallyADeath(*birth
, queue_duration
, run_duration
);
493 void ThreadData::TallyRunOnWorkerThreadIfTracking(
495 const TrackedTime
& time_posted
,
496 const TrackedTime
& start_of_run
,
497 const TrackedTime
& end_of_run
) {
498 if (!kTrackAllTaskObjects
)
499 return; // Not compiled in.
501 // Even if we have been DEACTIVATED, we will process any pending births so
502 // that our data structures (which counted the outstanding births) remain
507 // TODO(jar): Support the option to coalesce all worker-thread activity under
508 // one ThreadData instance that uses locks to protect *all* access. This will
509 // reduce memory (making it provably bounded), but run incrementally slower
510 // (since we'll use locks on TallyBirth and TallyDeath). The good news is
511 // that the locks on TallyDeath will be *after* the worker thread has run, and
512 // hence nothing will be waiting for the completion (... besides some other
513 // thread that might like to run). Also, the worker threads tasks are
514 // generally longer, and hence the cost of the lock may perchance be amortized
515 // over the long task's lifetime.
516 ThreadData
* current_thread_data
= Get();
517 if (!current_thread_data
)
520 int32 queue_duration
= 0;
521 int32 run_duration
= 0;
522 if (!start_of_run
.is_null()) {
523 queue_duration
= (start_of_run
- time_posted
).InMilliseconds();
524 if (!end_of_run
.is_null())
525 run_duration
= (end_of_run
- start_of_run
).InMilliseconds();
527 current_thread_data
->TallyADeath(*birth
, queue_duration
, run_duration
);
531 void ThreadData::TallyRunInAScopedRegionIfTracking(
533 const TrackedTime
& start_of_run
,
534 const TrackedTime
& end_of_run
) {
535 if (!kTrackAllTaskObjects
)
536 return; // Not compiled in.
538 // Even if we have been DEACTIVATED, we will process any pending births so
539 // that our data structures (which counted the outstanding births) remain
544 ThreadData
* current_thread_data
= Get();
545 if (!current_thread_data
)
548 int32 queue_duration
= 0;
549 int32 run_duration
= 0;
550 if (!start_of_run
.is_null() && !end_of_run
.is_null())
551 run_duration
= (end_of_run
- start_of_run
).InMilliseconds();
552 current_thread_data
->TallyADeath(*birth
, queue_duration
, run_duration
);
555 const std::string
ThreadData::thread_name() const { return thread_name_
; }
558 void ThreadData::SnapshotAllExecutedTasks(bool reset_max
,
559 ProcessDataSnapshot
* process_data
,
560 BirthCountMap
* birth_counts
) {
561 if (!kTrackAllTaskObjects
)
562 return; // Not compiled in.
564 // Get an unchanging copy of a ThreadData list.
565 ThreadData
* my_list
= ThreadData::first();
567 // Gather data serially.
568 // This hackish approach *can* get some slighly corrupt tallies, as we are
569 // grabbing values without the protection of a lock, but it has the advantage
570 // of working even with threads that don't have message loops. If a user
571 // sees any strangeness, they can always just run their stats gathering a
573 for (ThreadData
* thread_data
= my_list
;
575 thread_data
= thread_data
->next()) {
576 thread_data
->SnapshotExecutedTasks(reset_max
, process_data
, birth_counts
);
580 void ThreadData::SnapshotExecutedTasks(bool reset_max
,
581 ProcessDataSnapshot
* process_data
,
582 BirthCountMap
* birth_counts
) {
583 // Get copy of data, so that the data will not change during the iterations
585 ThreadData::BirthMap birth_map
;
586 ThreadData::DeathMap death_map
;
587 ThreadData::ParentChildSet parent_child_set
;
588 SnapshotMaps(reset_max
, &birth_map
, &death_map
, &parent_child_set
);
590 for (ThreadData::DeathMap::const_iterator it
= death_map
.begin();
591 it
!= death_map
.end(); ++it
) {
592 process_data
->tasks
.push_back(
593 TaskSnapshot(*it
->first
, it
->second
, thread_name()));
594 (*birth_counts
)[it
->first
] -= it
->first
->birth_count();
597 for (ThreadData::BirthMap::const_iterator it
= birth_map
.begin();
598 it
!= birth_map
.end(); ++it
) {
599 (*birth_counts
)[it
->second
] += it
->second
->birth_count();
602 if (!kTrackParentChildLinks
)
605 for (ThreadData::ParentChildSet::const_iterator it
= parent_child_set
.begin();
606 it
!= parent_child_set
.end(); ++it
) {
607 process_data
->descendants
.push_back(ParentChildPairSnapshot(*it
));
611 // This may be called from another thread.
612 void ThreadData::SnapshotMaps(bool reset_max
,
615 ParentChildSet
* parent_child_set
) {
616 base::AutoLock
lock(map_lock_
);
617 for (BirthMap::const_iterator it
= birth_map_
.begin();
618 it
!= birth_map_
.end(); ++it
)
619 (*birth_map
)[it
->first
] = it
->second
;
620 for (DeathMap::iterator it
= death_map_
.begin();
621 it
!= death_map_
.end(); ++it
) {
622 (*death_map
)[it
->first
] = it
->second
;
624 it
->second
.ResetMax();
627 if (!kTrackParentChildLinks
)
630 for (ParentChildSet::iterator it
= parent_child_set_
.begin();
631 it
!= parent_child_set_
.end(); ++it
)
632 parent_child_set
->insert(*it
);
636 void ThreadData::ResetAllThreadData() {
637 ThreadData
* my_list
= first();
639 for (ThreadData
* thread_data
= my_list
;
641 thread_data
= thread_data
->next())
642 thread_data
->Reset();
645 void ThreadData::Reset() {
646 base::AutoLock
lock(map_lock_
);
647 for (DeathMap::iterator it
= death_map_
.begin();
648 it
!= death_map_
.end(); ++it
)
650 for (BirthMap::iterator it
= birth_map_
.begin();
651 it
!= birth_map_
.end(); ++it
)
655 static void OptionallyInitializeAlternateTimer() {
656 NowFunction
* alternate_time_source
= GetAlternateTimeSource();
657 if (alternate_time_source
)
658 ThreadData::SetAlternateTimeSource(alternate_time_source
);
661 bool ThreadData::Initialize() {
662 if (!kTrackAllTaskObjects
)
663 return false; // Not compiled in.
664 if (status_
>= DEACTIVATED
)
665 return true; // Someone else did the initialization.
666 // Due to racy lazy initialization in tests, we'll need to recheck status_
667 // after we acquire the lock.
669 // Ensure that we don't double initialize tls. We are called when single
670 // threaded in the product, but some tests may be racy and lazy about our
672 base::AutoLock
lock(*list_lock_
.Pointer());
673 if (status_
>= DEACTIVATED
)
674 return true; // Someone raced in here and beat us.
676 // Put an alternate timer in place if the environment calls for it, such as
677 // for tracking TCMalloc allocations. This insertion is idempotent, so we
678 // don't mind if there is a race, and we'd prefer not to be in a lock while
680 if (kAllowAlternateTimeSourceHandling
)
681 OptionallyInitializeAlternateTimer();
683 // Perform the "real" TLS initialization now, and leave it intact through
684 // process termination.
685 if (!tls_index_
.initialized()) { // Testing may have initialized this.
686 DCHECK_EQ(status_
, UNINITIALIZED
);
687 tls_index_
.Initialize(&ThreadData::OnThreadTermination
);
688 if (!tls_index_
.initialized())
691 // TLS was initialzed for us earlier.
692 DCHECK_EQ(status_
, DORMANT_DURING_TESTS
);
695 // Incarnation counter is only significant to testing, as it otherwise will
696 // never again change in this process.
697 ++incarnation_counter_
;
699 // The lock is not critical for setting status_, but it doesn't hurt. It also
700 // ensures that if we have a racy initialization, that we'll bail as soon as
701 // we get the lock earlier in this method.
702 status_
= kInitialStartupState
;
703 if (!kTrackParentChildLinks
&&
704 kInitialStartupState
== PROFILING_CHILDREN_ACTIVE
)
705 status_
= PROFILING_ACTIVE
;
706 DCHECK(status_
!= UNINITIALIZED
);
711 bool ThreadData::InitializeAndSetTrackingStatus(Status status
) {
712 DCHECK_GE(status
, DEACTIVATED
);
713 DCHECK_LE(status
, PROFILING_CHILDREN_ACTIVE
);
715 if (!Initialize()) // No-op if already initialized.
716 return false; // Not compiled in.
718 if (!kTrackParentChildLinks
&& status
> DEACTIVATED
)
719 status
= PROFILING_ACTIVE
;
725 ThreadData::Status
ThreadData::status() {
730 bool ThreadData::TrackingStatus() {
731 return status_
> DEACTIVATED
;
735 bool ThreadData::TrackingParentChildStatus() {
736 return status_
>= PROFILING_CHILDREN_ACTIVE
;
740 TrackedTime
ThreadData::NowForStartOfRun(const Births
* parent
) {
741 if (kTrackParentChildLinks
&& parent
&& status_
> PROFILING_ACTIVE
) {
742 ThreadData
* current_thread_data
= Get();
743 if (current_thread_data
)
744 current_thread_data
->parent_stack_
.push(parent
);
750 TrackedTime
ThreadData::NowForEndOfRun() {
755 void ThreadData::SetAlternateTimeSource(NowFunction
* now_function
) {
756 DCHECK(now_function
);
757 if (kAllowAlternateTimeSourceHandling
)
758 now_function_
= now_function
;
762 TrackedTime
ThreadData::Now() {
763 if (kAllowAlternateTimeSourceHandling
&& now_function_
)
764 return TrackedTime::FromMilliseconds((*now_function_
)());
765 if (kTrackAllTaskObjects
&& TrackingStatus())
766 return TrackedTime::Now();
767 return TrackedTime(); // Super fast when disabled, or not compiled.
771 void ThreadData::EnsureCleanupWasCalled(int major_threads_shutdown_count
) {
772 base::AutoLock
lock(*list_lock_
.Pointer());
773 if (worker_thread_data_creation_count_
== 0)
774 return; // We haven't really run much, and couldn't have leaked.
775 // Verify that we've at least shutdown/cleanup the major namesd threads. The
776 // caller should tell us how many thread shutdowns should have taken place by
778 return; // TODO(jar): until this is working on XP, don't run the real test.
779 CHECK_GT(cleanup_count_
, major_threads_shutdown_count
);
783 void ThreadData::ShutdownSingleThreadedCleanup(bool leak
) {
784 // This is only called from test code, where we need to cleanup so that
785 // additional tests can be run.
786 // We must be single threaded... but be careful anyway.
787 if (!InitializeAndSetTrackingStatus(DEACTIVATED
))
789 ThreadData
* thread_data_list
;
791 base::AutoLock
lock(*list_lock_
.Pointer());
792 thread_data_list
= all_thread_data_list_head_
;
793 all_thread_data_list_head_
= NULL
;
794 ++incarnation_counter_
;
795 // To be clean, break apart the retired worker list (though we leak them).
796 while (first_retired_worker_
) {
797 ThreadData
* worker
= first_retired_worker_
;
798 CHECK_GT(worker
->worker_thread_number_
, 0);
799 first_retired_worker_
= worker
->next_retired_worker_
;
800 worker
->next_retired_worker_
= NULL
;
804 // Put most global static back in pristine shape.
805 worker_thread_data_creation_count_
= 0;
807 tls_index_
.Set(NULL
);
808 status_
= DORMANT_DURING_TESTS
; // Almost UNINITIALIZED.
810 // To avoid any chance of racing in unit tests, which is the only place we
811 // call this function, we may sometimes leak all the data structures we
812 // recovered, as they may still be in use on threads from prior tests!
816 // When we want to cleanup (on a single thread), here is what we do.
818 // Do actual recursive delete in all ThreadData instances.
819 while (thread_data_list
) {
820 ThreadData
* next_thread_data
= thread_data_list
;
821 thread_data_list
= thread_data_list
->next();
823 for (BirthMap::iterator it
= next_thread_data
->birth_map_
.begin();
824 next_thread_data
->birth_map_
.end() != it
; ++it
)
825 delete it
->second
; // Delete the Birth Records.
826 delete next_thread_data
; // Includes all Death Records.
830 //------------------------------------------------------------------------------
831 TaskSnapshot::TaskSnapshot() {
834 TaskSnapshot::TaskSnapshot(const BirthOnThread
& birth
,
835 const DeathData
& death_data
,
836 const std::string
& death_thread_name
)
838 death_data(death_data
),
839 death_thread_name(death_thread_name
) {
842 TaskSnapshot::~TaskSnapshot() {
845 //------------------------------------------------------------------------------
846 // ParentChildPairSnapshot
848 ParentChildPairSnapshot::ParentChildPairSnapshot() {
851 ParentChildPairSnapshot::ParentChildPairSnapshot(
852 const ThreadData::ParentChildPair
& parent_child
)
853 : parent(*parent_child
.first
),
854 child(*parent_child
.second
) {
857 ParentChildPairSnapshot::~ParentChildPairSnapshot() {
860 //------------------------------------------------------------------------------
861 // ProcessDataSnapshot
863 ProcessDataSnapshot::ProcessDataSnapshot()
864 #if !defined(OS_NACL)
865 : process_id(base::GetCurrentProcId()) {
871 ProcessDataSnapshot::~ProcessDataSnapshot() {
874 } // namespace tracked_objects