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/compiler_specific.h"
11 #include "base/format_macros.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/process_util.h"
14 #include "base/profiler/alternate_timer.h"
15 #include "base/stringprintf.h"
16 #include "base/third_party/valgrind/memcheck.h"
17 #include "base/threading/thread_restrictions.h"
18 #include "base/port.h"
20 using base::TimeDelta
;
22 namespace tracked_objects
{
25 // Flag to compile out almost all of the task tracking code.
26 const bool kTrackAllTaskObjects
= true;
28 // TODO(jar): Evaluate the perf impact of enabling this. If the perf impact is
29 // negligible, enable by default.
30 // Flag to compile out parent-child link recording.
31 const bool kTrackParentChildLinks
= false;
33 // When ThreadData is first initialized, should we start in an ACTIVE state to
34 // record all of the startup-time tasks, or should we start up DEACTIVATED, so
35 // that we only record after parsing the command line flag --enable-tracking.
36 // Note that the flag may force either state, so this really controls only the
37 // period of time up until that flag is parsed. If there is no flag seen, then
38 // this state may prevail for much or all of the process lifetime.
39 const ThreadData::Status kInitialStartupState
=
40 ThreadData::PROFILING_CHILDREN_ACTIVE
;
42 // Control whether an alternate time source (Now() function) is supported by
43 // the ThreadData class. This compile time flag should be set to true if we
44 // want other modules (such as a memory allocator, or a thread-specific CPU time
45 // clock) to be able to provide a thread-specific Now() function. Without this
46 // compile-time flag, the code will only support the wall-clock time. This flag
47 // can be flipped to efficiently disable this path (if there is a performance
48 // problem with its presence).
49 static const bool kAllowAlternateTimeSourceHandling
= true;
53 //------------------------------------------------------------------------------
54 // DeathData tallies durations when a death takes place.
56 DeathData::DeathData() {
60 DeathData::DeathData(int count
) {
65 // TODO(jar): I need to see if this macro to optimize branching is worth using.
67 // This macro has no branching, so it is surely fast, and is equivalent to:
70 // We use a macro rather than a template to force this to inline.
71 // Related code for calculating max is discussed on the web.
72 #define CONDITIONAL_ASSIGN(assign_it, target, source) \
73 ((target) ^= ((target) ^ (source)) & -static_cast<int32>(assign_it))
75 void DeathData::RecordDeath(const int32 queue_duration
,
76 const int32 run_duration
,
77 int32 random_number
) {
78 // We'll just clamp at INT_MAX, but we should note this in the UI as such.
81 queue_duration_sum_
+= queue_duration
;
82 run_duration_sum_
+= run_duration
;
84 if (queue_duration_max_
< queue_duration
)
85 queue_duration_max_
= queue_duration
;
86 if (run_duration_max_
< run_duration
)
87 run_duration_max_
= run_duration
;
89 // Take a uniformly distributed sample over all durations ever supplied.
90 // The probability that we (instead) use this new sample is 1/count_. This
91 // results in a completely uniform selection of the sample (at least when we
92 // don't clamp count_... but that should be inconsequentially likely).
93 // We ignore the fact that we correlated our selection of a sample to the run
94 // and queue times (i.e., we used them to generate random_number).
96 if (0 == (random_number
% count_
)) {
97 queue_duration_sample_
= queue_duration
;
98 run_duration_sample_
= run_duration
;
102 int DeathData::count() const { return count_
; }
104 int32
DeathData::run_duration_sum() const { return run_duration_sum_
; }
106 int32
DeathData::run_duration_max() const { return run_duration_max_
; }
108 int32
DeathData::run_duration_sample() const {
109 return run_duration_sample_
;
112 int32
DeathData::queue_duration_sum() const {
113 return queue_duration_sum_
;
116 int32
DeathData::queue_duration_max() const {
117 return queue_duration_max_
;
120 int32
DeathData::queue_duration_sample() const {
121 return queue_duration_sample_
;
124 void DeathData::ResetMax() {
125 run_duration_max_
= 0;
126 queue_duration_max_
= 0;
129 void DeathData::Clear() {
131 run_duration_sum_
= 0;
132 run_duration_max_
= 0;
133 run_duration_sample_
= 0;
134 queue_duration_sum_
= 0;
135 queue_duration_max_
= 0;
136 queue_duration_sample_
= 0;
139 //------------------------------------------------------------------------------
140 DeathDataSnapshot::DeathDataSnapshot()
142 run_duration_sum(-1),
143 run_duration_max(-1),
144 run_duration_sample(-1),
145 queue_duration_sum(-1),
146 queue_duration_max(-1),
147 queue_duration_sample(-1) {
150 DeathDataSnapshot::DeathDataSnapshot(
151 const tracked_objects::DeathData
& death_data
)
152 : count(death_data
.count()),
153 run_duration_sum(death_data
.run_duration_sum()),
154 run_duration_max(death_data
.run_duration_max()),
155 run_duration_sample(death_data
.run_duration_sample()),
156 queue_duration_sum(death_data
.queue_duration_sum()),
157 queue_duration_max(death_data
.queue_duration_max()),
158 queue_duration_sample(death_data
.queue_duration_sample()) {
161 DeathDataSnapshot::~DeathDataSnapshot() {
164 //------------------------------------------------------------------------------
165 BirthOnThread::BirthOnThread(const Location
& location
,
166 const ThreadData
& current
)
167 : location_(location
),
168 birth_thread_(¤t
) {
171 //------------------------------------------------------------------------------
172 BirthOnThreadSnapshot::BirthOnThreadSnapshot() {
175 BirthOnThreadSnapshot::BirthOnThreadSnapshot(
176 const tracked_objects::BirthOnThread
& birth
)
177 : location(birth
.location()),
178 thread_name(birth
.birth_thread()->thread_name()) {
181 BirthOnThreadSnapshot::~BirthOnThreadSnapshot() {
184 //------------------------------------------------------------------------------
185 Births::Births(const Location
& location
, const ThreadData
& current
)
186 : BirthOnThread(location
, current
),
189 int Births::birth_count() const { return birth_count_
; }
191 void Births::RecordBirth() { ++birth_count_
; }
193 void Births::ForgetBirth() { --birth_count_
; }
195 void Births::Clear() { birth_count_
= 0; }
197 //------------------------------------------------------------------------------
198 // ThreadData maintains the central data for all births and deaths on a single
201 // TODO(jar): We should pull all these static vars together, into a struct, and
202 // optimize layout so that we benefit from locality of reference during accesses
206 NowFunction
* ThreadData::now_function_
= NULL
;
208 // A TLS slot which points to the ThreadData instance for the current thread. We
209 // do a fake initialization here (zeroing out data), and then the real in-place
210 // construction happens when we call tls_index_.Initialize().
212 base::ThreadLocalStorage::StaticSlot
ThreadData::tls_index_
= TLS_INITIALIZER
;
215 int ThreadData::worker_thread_data_creation_count_
= 0;
218 int ThreadData::cleanup_count_
= 0;
221 int ThreadData::incarnation_counter_
= 0;
224 ThreadData
* ThreadData::all_thread_data_list_head_
= NULL
;
227 ThreadData
* ThreadData::first_retired_worker_
= NULL
;
230 base::LazyInstance
<base::Lock
>::Leaky
231 ThreadData::list_lock_
= LAZY_INSTANCE_INITIALIZER
;
234 ThreadData::Status
ThreadData::status_
= ThreadData::UNINITIALIZED
;
236 ThreadData::ThreadData(const std::string
& suggested_name
)
238 next_retired_worker_(NULL
),
239 worker_thread_number_(0),
240 incarnation_count_for_pool_(-1) {
241 DCHECK_GE(suggested_name
.size(), 0u);
242 thread_name_
= suggested_name
;
243 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
246 ThreadData::ThreadData(int thread_number
)
248 next_retired_worker_(NULL
),
249 worker_thread_number_(thread_number
),
250 incarnation_count_for_pool_(-1) {
251 CHECK_GT(thread_number
, 0);
252 base::StringAppendF(&thread_name_
, "WorkerThread-%d", thread_number
);
253 PushToHeadOfList(); // Which sets real incarnation_count_for_pool_.
256 ThreadData::~ThreadData() {}
258 void ThreadData::PushToHeadOfList() {
259 // Toss in a hint of randomness (atop the uniniitalized value).
260 (void)VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(&random_number_
,
261 sizeof(random_number_
));
262 MSAN_UNPOISON(&random_number_
, 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
);
556 void ThreadData::SnapshotAllExecutedTasks(bool reset_max
,
557 ProcessDataSnapshot
* process_data
,
558 BirthCountMap
* birth_counts
) {
559 if (!kTrackAllTaskObjects
)
560 return; // Not compiled in.
562 // Get an unchanging copy of a ThreadData list.
563 ThreadData
* my_list
= ThreadData::first();
565 // Gather data serially.
566 // This hackish approach *can* get some slighly corrupt tallies, as we are
567 // grabbing values without the protection of a lock, but it has the advantage
568 // of working even with threads that don't have message loops. If a user
569 // sees any strangeness, they can always just run their stats gathering a
571 for (ThreadData
* thread_data
= my_list
;
573 thread_data
= thread_data
->next()) {
574 thread_data
->SnapshotExecutedTasks(reset_max
, process_data
, birth_counts
);
578 void ThreadData::SnapshotExecutedTasks(bool reset_max
,
579 ProcessDataSnapshot
* process_data
,
580 BirthCountMap
* birth_counts
) {
581 // Get copy of data, so that the data will not change during the iterations
583 ThreadData::BirthMap birth_map
;
584 ThreadData::DeathMap death_map
;
585 ThreadData::ParentChildSet parent_child_set
;
586 SnapshotMaps(reset_max
, &birth_map
, &death_map
, &parent_child_set
);
588 for (ThreadData::DeathMap::const_iterator it
= death_map
.begin();
589 it
!= death_map
.end(); ++it
) {
590 process_data
->tasks
.push_back(
591 TaskSnapshot(*it
->first
, it
->second
, thread_name()));
592 (*birth_counts
)[it
->first
] -= it
->first
->birth_count();
595 for (ThreadData::BirthMap::const_iterator it
= birth_map
.begin();
596 it
!= birth_map
.end(); ++it
) {
597 (*birth_counts
)[it
->second
] += it
->second
->birth_count();
600 if (!kTrackParentChildLinks
)
603 for (ThreadData::ParentChildSet::const_iterator it
= parent_child_set
.begin();
604 it
!= parent_child_set
.end(); ++it
) {
605 process_data
->descendants
.push_back(ParentChildPairSnapshot(*it
));
609 // This may be called from another thread.
610 void ThreadData::SnapshotMaps(bool reset_max
,
613 ParentChildSet
* parent_child_set
) {
614 base::AutoLock
lock(map_lock_
);
615 for (BirthMap::const_iterator it
= birth_map_
.begin();
616 it
!= birth_map_
.end(); ++it
)
617 (*birth_map
)[it
->first
] = it
->second
;
618 for (DeathMap::iterator it
= death_map_
.begin();
619 it
!= death_map_
.end(); ++it
) {
620 (*death_map
)[it
->first
] = it
->second
;
622 it
->second
.ResetMax();
625 if (!kTrackParentChildLinks
)
628 for (ParentChildSet::iterator it
= parent_child_set_
.begin();
629 it
!= parent_child_set_
.end(); ++it
)
630 parent_child_set
->insert(*it
);
634 void ThreadData::ResetAllThreadData() {
635 ThreadData
* my_list
= first();
637 for (ThreadData
* thread_data
= my_list
;
639 thread_data
= thread_data
->next())
640 thread_data
->Reset();
643 void ThreadData::Reset() {
644 base::AutoLock
lock(map_lock_
);
645 for (DeathMap::iterator it
= death_map_
.begin();
646 it
!= death_map_
.end(); ++it
)
648 for (BirthMap::iterator it
= birth_map_
.begin();
649 it
!= birth_map_
.end(); ++it
)
653 static void OptionallyInitializeAlternateTimer() {
654 NowFunction
* alternate_time_source
= GetAlternateTimeSource();
655 if (alternate_time_source
)
656 ThreadData::SetAlternateTimeSource(alternate_time_source
);
659 bool ThreadData::Initialize() {
660 if (!kTrackAllTaskObjects
)
661 return false; // Not compiled in.
662 if (status_
>= DEACTIVATED
)
663 return true; // Someone else did the initialization.
664 // Due to racy lazy initialization in tests, we'll need to recheck status_
665 // after we acquire the lock.
667 // Ensure that we don't double initialize tls. We are called when single
668 // threaded in the product, but some tests may be racy and lazy about our
670 base::AutoLock
lock(*list_lock_
.Pointer());
671 if (status_
>= DEACTIVATED
)
672 return true; // Someone raced in here and beat us.
674 // Put an alternate timer in place if the environment calls for it, such as
675 // for tracking TCMalloc allocations. This insertion is idempotent, so we
676 // don't mind if there is a race, and we'd prefer not to be in a lock while
678 if (kAllowAlternateTimeSourceHandling
)
679 OptionallyInitializeAlternateTimer();
681 // Perform the "real" TLS initialization now, and leave it intact through
682 // process termination.
683 if (!tls_index_
.initialized()) { // Testing may have initialized this.
684 DCHECK_EQ(status_
, UNINITIALIZED
);
685 tls_index_
.Initialize(&ThreadData::OnThreadTermination
);
686 if (!tls_index_
.initialized())
689 // TLS was initialzed for us earlier.
690 DCHECK_EQ(status_
, DORMANT_DURING_TESTS
);
693 // Incarnation counter is only significant to testing, as it otherwise will
694 // never again change in this process.
695 ++incarnation_counter_
;
697 // The lock is not critical for setting status_, but it doesn't hurt. It also
698 // ensures that if we have a racy initialization, that we'll bail as soon as
699 // we get the lock earlier in this method.
700 status_
= kInitialStartupState
;
701 if (!kTrackParentChildLinks
&&
702 kInitialStartupState
== PROFILING_CHILDREN_ACTIVE
)
703 status_
= PROFILING_ACTIVE
;
704 DCHECK(status_
!= UNINITIALIZED
);
709 bool ThreadData::InitializeAndSetTrackingStatus(Status status
) {
710 DCHECK_GE(status
, DEACTIVATED
);
711 DCHECK_LE(status
, PROFILING_CHILDREN_ACTIVE
);
713 if (!Initialize()) // No-op if already initialized.
714 return false; // Not compiled in.
716 if (!kTrackParentChildLinks
&& status
> DEACTIVATED
)
717 status
= PROFILING_ACTIVE
;
723 ThreadData::Status
ThreadData::status() {
728 bool ThreadData::TrackingStatus() {
729 return status_
> DEACTIVATED
;
733 bool ThreadData::TrackingParentChildStatus() {
734 return status_
>= PROFILING_CHILDREN_ACTIVE
;
738 TrackedTime
ThreadData::NowForStartOfRun(const Births
* parent
) {
739 if (kTrackParentChildLinks
&& parent
&& status_
> PROFILING_ACTIVE
) {
740 ThreadData
* current_thread_data
= Get();
741 if (current_thread_data
)
742 current_thread_data
->parent_stack_
.push(parent
);
748 TrackedTime
ThreadData::NowForEndOfRun() {
753 void ThreadData::SetAlternateTimeSource(NowFunction
* now_function
) {
754 DCHECK(now_function
);
755 if (kAllowAlternateTimeSourceHandling
)
756 now_function_
= now_function
;
760 TrackedTime
ThreadData::Now() {
761 if (kAllowAlternateTimeSourceHandling
&& now_function_
)
762 return TrackedTime::FromMilliseconds((*now_function_
)());
763 if (kTrackAllTaskObjects
&& TrackingStatus())
764 return TrackedTime::Now();
765 return TrackedTime(); // Super fast when disabled, or not compiled.
769 void ThreadData::EnsureCleanupWasCalled(int major_threads_shutdown_count
) {
770 base::AutoLock
lock(*list_lock_
.Pointer());
771 if (worker_thread_data_creation_count_
== 0)
772 return; // We haven't really run much, and couldn't have leaked.
773 // Verify that we've at least shutdown/cleanup the major namesd threads. The
774 // caller should tell us how many thread shutdowns should have taken place by
776 return; // TODO(jar): until this is working on XP, don't run the real test.
777 CHECK_GT(cleanup_count_
, major_threads_shutdown_count
);
781 void ThreadData::ShutdownSingleThreadedCleanup(bool leak
) {
782 // This is only called from test code, where we need to cleanup so that
783 // additional tests can be run.
784 // We must be single threaded... but be careful anyway.
785 if (!InitializeAndSetTrackingStatus(DEACTIVATED
))
787 ThreadData
* thread_data_list
;
789 base::AutoLock
lock(*list_lock_
.Pointer());
790 thread_data_list
= all_thread_data_list_head_
;
791 all_thread_data_list_head_
= NULL
;
792 ++incarnation_counter_
;
793 // To be clean, break apart the retired worker list (though we leak them).
794 while (first_retired_worker_
) {
795 ThreadData
* worker
= first_retired_worker_
;
796 CHECK_GT(worker
->worker_thread_number_
, 0);
797 first_retired_worker_
= worker
->next_retired_worker_
;
798 worker
->next_retired_worker_
= NULL
;
802 // Put most global static back in pristine shape.
803 worker_thread_data_creation_count_
= 0;
805 tls_index_
.Set(NULL
);
806 status_
= DORMANT_DURING_TESTS
; // Almost UNINITIALIZED.
808 // To avoid any chance of racing in unit tests, which is the only place we
809 // call this function, we may sometimes leak all the data structures we
810 // recovered, as they may still be in use on threads from prior tests!
814 // When we want to cleanup (on a single thread), here is what we do.
816 // Do actual recursive delete in all ThreadData instances.
817 while (thread_data_list
) {
818 ThreadData
* next_thread_data
= thread_data_list
;
819 thread_data_list
= thread_data_list
->next();
821 for (BirthMap::iterator it
= next_thread_data
->birth_map_
.begin();
822 next_thread_data
->birth_map_
.end() != it
; ++it
)
823 delete it
->second
; // Delete the Birth Records.
824 delete next_thread_data
; // Includes all Death Records.
828 //------------------------------------------------------------------------------
829 TaskSnapshot::TaskSnapshot() {
832 TaskSnapshot::TaskSnapshot(const BirthOnThread
& birth
,
833 const DeathData
& death_data
,
834 const std::string
& death_thread_name
)
836 death_data(death_data
),
837 death_thread_name(death_thread_name
) {
840 TaskSnapshot::~TaskSnapshot() {
843 //------------------------------------------------------------------------------
844 // ParentChildPairSnapshot
846 ParentChildPairSnapshot::ParentChildPairSnapshot() {
849 ParentChildPairSnapshot::ParentChildPairSnapshot(
850 const ThreadData::ParentChildPair
& parent_child
)
851 : parent(*parent_child
.first
),
852 child(*parent_child
.second
) {
855 ParentChildPairSnapshot::~ParentChildPairSnapshot() {
858 //------------------------------------------------------------------------------
859 // ProcessDataSnapshot
861 ProcessDataSnapshot::ProcessDataSnapshot()
862 #if !defined(OS_NACL)
863 : process_id(base::GetCurrentProcId()) {
869 ProcessDataSnapshot::~ProcessDataSnapshot() {
872 } // namespace tracked_objects