- add sources.
[platform/framework/web/crosswalk.git] / src / base / tracked_objects.cc
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.
4
5 #include "base/tracked_objects.h"
6
7 #include <limits.h>
8 #include <stdlib.h>
9
10 #include "base/compiler_specific.h"
11 #include "base/debug/leak_annotations.h"
12 #include "base/logging.h"
13 #include "base/process/process_handle.h"
14 #include "base/profiler/alternate_timer.h"
15 #include "base/strings/stringprintf.h"
16 #include "base/third_party/valgrind/memcheck.h"
17 #include "base/tracking_info.h"
18
19 using base::TimeDelta;
20
21 namespace base {
22 class TimeDelta;
23 }
24
25 namespace tracked_objects {
26
27 namespace {
28 // Flag to compile out almost all of the task tracking code.
29 const bool kTrackAllTaskObjects = true;
30
31 // TODO(jar): Evaluate the perf impact of enabling this.  If the perf impact is
32 // negligible, enable by default.
33 // Flag to compile out parent-child link recording.
34 const bool kTrackParentChildLinks = false;
35
36 // When ThreadData is first initialized, should we start in an ACTIVE state to
37 // record all of the startup-time tasks, or should we start up DEACTIVATED, so
38 // that we only record after parsing the command line flag --enable-tracking.
39 // Note that the flag may force either state, so this really controls only the
40 // period of time up until that flag is parsed. If there is no flag seen, then
41 // this state may prevail for much or all of the process lifetime.
42 const ThreadData::Status kInitialStartupState =
43     ThreadData::PROFILING_CHILDREN_ACTIVE;
44
45 // Control whether an alternate time source (Now() function) is supported by
46 // the ThreadData class.  This compile time flag should be set to true if we
47 // want other modules (such as a memory allocator, or a thread-specific CPU time
48 // clock) to be able to provide a thread-specific Now() function.  Without this
49 // compile-time flag, the code will only support the wall-clock time.  This flag
50 // can be flipped to efficiently disable this path (if there is a performance
51 // problem with its presence).
52 static const bool kAllowAlternateTimeSourceHandling = true;
53
54 }  // namespace
55
56 //------------------------------------------------------------------------------
57 // DeathData tallies durations when a death takes place.
58
59 DeathData::DeathData() {
60   Clear();
61 }
62
63 DeathData::DeathData(int count) {
64   Clear();
65   count_ = count;
66 }
67
68 // TODO(jar): I need to see if this macro to optimize branching is worth using.
69 //
70 // This macro has no branching, so it is surely fast, and is equivalent to:
71 //             if (assign_it)
72 //               target = source;
73 // We use a macro rather than a template to force this to inline.
74 // Related code for calculating max is discussed on the web.
75 #define CONDITIONAL_ASSIGN(assign_it, target, source) \
76     ((target) ^= ((target) ^ (source)) & -static_cast<int32>(assign_it))
77
78 void DeathData::RecordDeath(const int32 queue_duration,
79                             const int32 run_duration,
80                             int32 random_number) {
81   // We'll just clamp at INT_MAX, but we should note this in the UI as such.
82   if (count_ < INT_MAX)
83     ++count_;
84   queue_duration_sum_ += queue_duration;
85   run_duration_sum_ += run_duration;
86
87   if (queue_duration_max_ < queue_duration)
88     queue_duration_max_ = queue_duration;
89   if (run_duration_max_ < run_duration)
90     run_duration_max_ = run_duration;
91
92   // Take a uniformly distributed sample over all durations ever supplied.
93   // The probability that we (instead) use this new sample is 1/count_.  This
94   // results in a completely uniform selection of the sample (at least when we
95   // don't clamp count_... but that should be inconsequentially likely).
96   // We ignore the fact that we correlated our selection of a sample to the run
97   // and queue times (i.e., we used them to generate random_number).
98   CHECK_GT(count_, 0);
99   if (0 == (random_number % count_)) {
100     queue_duration_sample_ = queue_duration;
101     run_duration_sample_ = run_duration;
102   }
103 }
104
105 int DeathData::count() const { return count_; }
106
107 int32 DeathData::run_duration_sum() const { return run_duration_sum_; }
108
109 int32 DeathData::run_duration_max() const { return run_duration_max_; }
110
111 int32 DeathData::run_duration_sample() const {
112   return run_duration_sample_;
113 }
114
115 int32 DeathData::queue_duration_sum() const {
116   return queue_duration_sum_;
117 }
118
119 int32 DeathData::queue_duration_max() const {
120   return queue_duration_max_;
121 }
122
123 int32 DeathData::queue_duration_sample() const {
124   return queue_duration_sample_;
125 }
126
127 void DeathData::ResetMax() {
128   run_duration_max_ = 0;
129   queue_duration_max_ = 0;
130 }
131
132 void DeathData::Clear() {
133   count_ = 0;
134   run_duration_sum_ = 0;
135   run_duration_max_ = 0;
136   run_duration_sample_ = 0;
137   queue_duration_sum_ = 0;
138   queue_duration_max_ = 0;
139   queue_duration_sample_ = 0;
140 }
141
142 //------------------------------------------------------------------------------
143 DeathDataSnapshot::DeathDataSnapshot()
144     : count(-1),
145       run_duration_sum(-1),
146       run_duration_max(-1),
147       run_duration_sample(-1),
148       queue_duration_sum(-1),
149       queue_duration_max(-1),
150       queue_duration_sample(-1) {
151 }
152
153 DeathDataSnapshot::DeathDataSnapshot(
154     const tracked_objects::DeathData& death_data)
155     : count(death_data.count()),
156       run_duration_sum(death_data.run_duration_sum()),
157       run_duration_max(death_data.run_duration_max()),
158       run_duration_sample(death_data.run_duration_sample()),
159       queue_duration_sum(death_data.queue_duration_sum()),
160       queue_duration_max(death_data.queue_duration_max()),
161       queue_duration_sample(death_data.queue_duration_sample()) {
162 }
163
164 DeathDataSnapshot::~DeathDataSnapshot() {
165 }
166
167 //------------------------------------------------------------------------------
168 BirthOnThread::BirthOnThread(const Location& location,
169                              const ThreadData& current)
170     : location_(location),
171       birth_thread_(&current) {
172 }
173
174 //------------------------------------------------------------------------------
175 BirthOnThreadSnapshot::BirthOnThreadSnapshot() {
176 }
177
178 BirthOnThreadSnapshot::BirthOnThreadSnapshot(
179     const tracked_objects::BirthOnThread& birth)
180     : location(birth.location()),
181       thread_name(birth.birth_thread()->thread_name()) {
182 }
183
184 BirthOnThreadSnapshot::~BirthOnThreadSnapshot() {
185 }
186
187 //------------------------------------------------------------------------------
188 Births::Births(const Location& location, const ThreadData& current)
189     : BirthOnThread(location, current),
190       birth_count_(1) { }
191
192 int Births::birth_count() const { return birth_count_; }
193
194 void Births::RecordBirth() { ++birth_count_; }
195
196 void Births::ForgetBirth() { --birth_count_; }
197
198 void Births::Clear() { birth_count_ = 0; }
199
200 //------------------------------------------------------------------------------
201 // ThreadData maintains the central data for all births and deaths on a single
202 // thread.
203
204 // TODO(jar): We should pull all these static vars together, into a struct, and
205 // optimize layout so that we benefit from locality of reference during accesses
206 // to them.
207
208 // static
209 NowFunction* ThreadData::now_function_ = NULL;
210
211 // A TLS slot which points to the ThreadData instance for the current thread. We
212 // do a fake initialization here (zeroing out data), and then the real in-place
213 // construction happens when we call tls_index_.Initialize().
214 // static
215 base::ThreadLocalStorage::StaticSlot ThreadData::tls_index_ = TLS_INITIALIZER;
216
217 // static
218 int ThreadData::worker_thread_data_creation_count_ = 0;
219
220 // static
221 int ThreadData::cleanup_count_ = 0;
222
223 // static
224 int ThreadData::incarnation_counter_ = 0;
225
226 // static
227 ThreadData* ThreadData::all_thread_data_list_head_ = NULL;
228
229 // static
230 ThreadData* ThreadData::first_retired_worker_ = NULL;
231
232 // static
233 base::LazyInstance<base::Lock>::Leaky
234     ThreadData::list_lock_ = LAZY_INSTANCE_INITIALIZER;
235
236 // static
237 ThreadData::Status ThreadData::status_ = ThreadData::UNINITIALIZED;
238
239 ThreadData::ThreadData(const std::string& suggested_name)
240     : next_(NULL),
241       next_retired_worker_(NULL),
242       worker_thread_number_(0),
243       incarnation_count_for_pool_(-1) {
244   DCHECK_GE(suggested_name.size(), 0u);
245   thread_name_ = suggested_name;
246   PushToHeadOfList();  // Which sets real incarnation_count_for_pool_.
247 }
248
249 ThreadData::ThreadData(int thread_number)
250     : next_(NULL),
251       next_retired_worker_(NULL),
252       worker_thread_number_(thread_number),
253       incarnation_count_for_pool_(-1)  {
254   CHECK_GT(thread_number, 0);
255   base::StringAppendF(&thread_name_, "WorkerThread-%d", thread_number);
256   PushToHeadOfList();  // Which sets real incarnation_count_for_pool_.
257 }
258
259 ThreadData::~ThreadData() {}
260
261 void ThreadData::PushToHeadOfList() {
262   // Toss in a hint of randomness (atop the uniniitalized value).
263   (void)VALGRIND_MAKE_MEM_DEFINED_IF_ADDRESSABLE(&random_number_,
264                                                  sizeof(random_number_));
265   MSAN_UNPOISON(&random_number_, sizeof(random_number_));
266   random_number_ += static_cast<int32>(this - static_cast<ThreadData*>(0));
267   random_number_ ^= (Now() - TrackedTime()).InMilliseconds();
268
269   DCHECK(!next_);
270   base::AutoLock lock(*list_lock_.Pointer());
271   incarnation_count_for_pool_ = incarnation_counter_;
272   next_ = all_thread_data_list_head_;
273   all_thread_data_list_head_ = this;
274 }
275
276 // static
277 ThreadData* ThreadData::first() {
278   base::AutoLock lock(*list_lock_.Pointer());
279   return all_thread_data_list_head_;
280 }
281
282 ThreadData* ThreadData::next() const { return next_; }
283
284 // static
285 void ThreadData::InitializeThreadContext(const std::string& suggested_name) {
286   if (!Initialize())  // Always initialize if needed.
287     return;
288   ThreadData* current_thread_data =
289       reinterpret_cast<ThreadData*>(tls_index_.Get());
290   if (current_thread_data)
291     return;  // Browser tests instigate this.
292   current_thread_data = new ThreadData(suggested_name);
293   tls_index_.Set(current_thread_data);
294 }
295
296 // static
297 ThreadData* ThreadData::Get() {
298   if (!tls_index_.initialized())
299     return NULL;  // For unittests only.
300   ThreadData* registered = reinterpret_cast<ThreadData*>(tls_index_.Get());
301   if (registered)
302     return registered;
303
304   // We must be a worker thread, since we didn't pre-register.
305   ThreadData* worker_thread_data = NULL;
306   int worker_thread_number = 0;
307   {
308     base::AutoLock lock(*list_lock_.Pointer());
309     if (first_retired_worker_) {
310       worker_thread_data = first_retired_worker_;
311       first_retired_worker_ = first_retired_worker_->next_retired_worker_;
312       worker_thread_data->next_retired_worker_ = NULL;
313     } else {
314       worker_thread_number = ++worker_thread_data_creation_count_;
315     }
316   }
317
318   // If we can't find a previously used instance, then we have to create one.
319   if (!worker_thread_data) {
320     DCHECK_GT(worker_thread_number, 0);
321     worker_thread_data = new ThreadData(worker_thread_number);
322   }
323   DCHECK_GT(worker_thread_data->worker_thread_number_, 0);
324
325   tls_index_.Set(worker_thread_data);
326   return worker_thread_data;
327 }
328
329 // static
330 void ThreadData::OnThreadTermination(void* thread_data) {
331   DCHECK(thread_data);  // TLS should *never* call us with a NULL.
332   // We must NOT do any allocations during this callback. There is a chance
333   // that the allocator is no longer active on this thread.
334   if (!kTrackAllTaskObjects)
335     return;  // Not compiled in.
336   reinterpret_cast<ThreadData*>(thread_data)->OnThreadTerminationCleanup();
337 }
338
339 void ThreadData::OnThreadTerminationCleanup() {
340   // The list_lock_ was created when we registered the callback, so it won't be
341   // allocated here despite the lazy reference.
342   base::AutoLock lock(*list_lock_.Pointer());
343   if (incarnation_counter_ != incarnation_count_for_pool_)
344     return;  // ThreadData was constructed in an earlier unit test.
345   ++cleanup_count_;
346   // Only worker threads need to be retired and reused.
347   if (!worker_thread_number_) {
348     return;
349   }
350   // We must NOT do any allocations during this callback.
351   // Using the simple linked lists avoids all allocations.
352   DCHECK_EQ(this->next_retired_worker_, reinterpret_cast<ThreadData*>(NULL));
353   this->next_retired_worker_ = first_retired_worker_;
354   first_retired_worker_ = this;
355 }
356
357 // static
358 void ThreadData::Snapshot(bool reset_max, ProcessDataSnapshot* process_data) {
359   // Add births that have run to completion to |collected_data|.
360   // |birth_counts| tracks the total number of births recorded at each location
361   // for which we have not seen a death count.
362   BirthCountMap birth_counts;
363   ThreadData::SnapshotAllExecutedTasks(reset_max, process_data, &birth_counts);
364
365   // Add births that are still active -- i.e. objects that have tallied a birth,
366   // but have not yet tallied a matching death, and hence must be either
367   // running, queued up, or being held in limbo for future posting.
368   for (BirthCountMap::const_iterator it = birth_counts.begin();
369        it != birth_counts.end(); ++it) {
370     if (it->second > 0) {
371       process_data->tasks.push_back(
372           TaskSnapshot(*it->first, DeathData(it->second), "Still_Alive"));
373     }
374   }
375 }
376
377 Births* ThreadData::TallyABirth(const Location& location) {
378   BirthMap::iterator it = birth_map_.find(location);
379   Births* child;
380   if (it != birth_map_.end()) {
381     child =  it->second;
382     child->RecordBirth();
383   } else {
384     child = new Births(location, *this);  // Leak this.
385     // Lock since the map may get relocated now, and other threads sometimes
386     // snapshot it (but they lock before copying it).
387     base::AutoLock lock(map_lock_);
388     birth_map_[location] = child;
389   }
390
391   if (kTrackParentChildLinks && status_ > PROFILING_ACTIVE &&
392       !parent_stack_.empty()) {
393     const Births* parent = parent_stack_.top();
394     ParentChildPair pair(parent, child);
395     if (parent_child_set_.find(pair) == parent_child_set_.end()) {
396       // Lock since the map may get relocated now, and other threads sometimes
397       // snapshot it (but they lock before copying it).
398       base::AutoLock lock(map_lock_);
399       parent_child_set_.insert(pair);
400     }
401   }
402
403   return child;
404 }
405
406 void ThreadData::TallyADeath(const Births& birth,
407                              int32 queue_duration,
408                              int32 run_duration) {
409   // Stir in some randomness, plus add constant in case durations are zero.
410   const int32 kSomePrimeNumber = 2147483647;
411   random_number_ += queue_duration + run_duration + kSomePrimeNumber;
412   // An address is going to have some randomness to it as well ;-).
413   random_number_ ^= static_cast<int32>(&birth - reinterpret_cast<Births*>(0));
414
415   // We don't have queue durations without OS timer. OS timer is automatically
416   // used for task-post-timing, so the use of an alternate timer implies all
417   // queue times are invalid.
418   if (kAllowAlternateTimeSourceHandling && now_function_)
419     queue_duration = 0;
420
421   DeathMap::iterator it = death_map_.find(&birth);
422   DeathData* death_data;
423   if (it != death_map_.end()) {
424     death_data = &it->second;
425   } else {
426     base::AutoLock lock(map_lock_);  // Lock as the map may get relocated now.
427     death_data = &death_map_[&birth];
428   }  // Release lock ASAP.
429   death_data->RecordDeath(queue_duration, run_duration, random_number_);
430
431   if (!kTrackParentChildLinks)
432     return;
433   if (!parent_stack_.empty()) {  // We might get turned off.
434     DCHECK_EQ(parent_stack_.top(), &birth);
435     parent_stack_.pop();
436   }
437 }
438
439 // static
440 Births* ThreadData::TallyABirthIfActive(const Location& location) {
441   if (!kTrackAllTaskObjects)
442     return NULL;  // Not compiled in.
443
444   if (!TrackingStatus())
445     return NULL;
446   ThreadData* current_thread_data = Get();
447   if (!current_thread_data)
448     return NULL;
449   return current_thread_data->TallyABirth(location);
450 }
451
452 // static
453 void ThreadData::TallyRunOnNamedThreadIfTracking(
454     const base::TrackingInfo& completed_task,
455     const TrackedTime& start_of_run,
456     const TrackedTime& end_of_run) {
457   if (!kTrackAllTaskObjects)
458     return;  // Not compiled in.
459
460   // Even if we have been DEACTIVATED, we will process any pending births so
461   // that our data structures (which counted the outstanding births) remain
462   // consistent.
463   const Births* birth = completed_task.birth_tally;
464   if (!birth)
465     return;
466   ThreadData* current_thread_data = Get();
467   if (!current_thread_data)
468     return;
469
470   // Watch out for a race where status_ is changing, and hence one or both
471   // of start_of_run or end_of_run is zero.  In that case, we didn't bother to
472   // get a time value since we "weren't tracking" and we were trying to be
473   // efficient by not calling for a genuine time value. For simplicity, we'll
474   // use a default zero duration when we can't calculate a true value.
475   int32 queue_duration = 0;
476   int32 run_duration = 0;
477   if (!start_of_run.is_null()) {
478     queue_duration = (start_of_run - completed_task.EffectiveTimePosted())
479         .InMilliseconds();
480     if (!end_of_run.is_null())
481       run_duration = (end_of_run - start_of_run).InMilliseconds();
482   }
483   current_thread_data->TallyADeath(*birth, queue_duration, run_duration);
484 }
485
486 // static
487 void ThreadData::TallyRunOnWorkerThreadIfTracking(
488     const Births* birth,
489     const TrackedTime& time_posted,
490     const TrackedTime& start_of_run,
491     const TrackedTime& end_of_run) {
492   if (!kTrackAllTaskObjects)
493     return;  // Not compiled in.
494
495   // Even if we have been DEACTIVATED, we will process any pending births so
496   // that our data structures (which counted the outstanding births) remain
497   // consistent.
498   if (!birth)
499     return;
500
501   // TODO(jar): Support the option to coalesce all worker-thread activity under
502   // one ThreadData instance that uses locks to protect *all* access.  This will
503   // reduce memory (making it provably bounded), but run incrementally slower
504   // (since we'll use locks on TallyABirth and TallyADeath).  The good news is
505   // that the locks on TallyADeath will be *after* the worker thread has run,
506   // and hence nothing will be waiting for the completion (... besides some
507   // other thread that might like to run).  Also, the worker threads tasks are
508   // generally longer, and hence the cost of the lock may perchance be amortized
509   // over the long task's lifetime.
510   ThreadData* current_thread_data = Get();
511   if (!current_thread_data)
512     return;
513
514   int32 queue_duration = 0;
515   int32 run_duration = 0;
516   if (!start_of_run.is_null()) {
517     queue_duration = (start_of_run - time_posted).InMilliseconds();
518     if (!end_of_run.is_null())
519       run_duration = (end_of_run - start_of_run).InMilliseconds();
520   }
521   current_thread_data->TallyADeath(*birth, queue_duration, run_duration);
522 }
523
524 // static
525 void ThreadData::TallyRunInAScopedRegionIfTracking(
526     const Births* birth,
527     const TrackedTime& start_of_run,
528     const TrackedTime& end_of_run) {
529   if (!kTrackAllTaskObjects)
530     return;  // Not compiled in.
531
532   // Even if we have been DEACTIVATED, we will process any pending births so
533   // that our data structures (which counted the outstanding births) remain
534   // consistent.
535   if (!birth)
536     return;
537
538   ThreadData* current_thread_data = Get();
539   if (!current_thread_data)
540     return;
541
542   int32 queue_duration = 0;
543   int32 run_duration = 0;
544   if (!start_of_run.is_null() && !end_of_run.is_null())
545     run_duration = (end_of_run - start_of_run).InMilliseconds();
546   current_thread_data->TallyADeath(*birth, queue_duration, run_duration);
547 }
548
549 // static
550 void ThreadData::SnapshotAllExecutedTasks(bool reset_max,
551                                           ProcessDataSnapshot* process_data,
552                                           BirthCountMap* birth_counts) {
553   if (!kTrackAllTaskObjects)
554     return;  // Not compiled in.
555
556   // Get an unchanging copy of a ThreadData list.
557   ThreadData* my_list = ThreadData::first();
558
559   // Gather data serially.
560   // This hackish approach *can* get some slighly corrupt tallies, as we are
561   // grabbing values without the protection of a lock, but it has the advantage
562   // of working even with threads that don't have message loops.  If a user
563   // sees any strangeness, they can always just run their stats gathering a
564   // second time.
565   for (ThreadData* thread_data = my_list;
566        thread_data;
567        thread_data = thread_data->next()) {
568     thread_data->SnapshotExecutedTasks(reset_max, process_data, birth_counts);
569   }
570 }
571
572 void ThreadData::SnapshotExecutedTasks(bool reset_max,
573                                        ProcessDataSnapshot* process_data,
574                                        BirthCountMap* birth_counts) {
575   // Get copy of data, so that the data will not change during the iterations
576   // and processing.
577   ThreadData::BirthMap birth_map;
578   ThreadData::DeathMap death_map;
579   ThreadData::ParentChildSet parent_child_set;
580   SnapshotMaps(reset_max, &birth_map, &death_map, &parent_child_set);
581
582   for (ThreadData::DeathMap::const_iterator it = death_map.begin();
583        it != death_map.end(); ++it) {
584     process_data->tasks.push_back(
585         TaskSnapshot(*it->first, it->second, thread_name()));
586     (*birth_counts)[it->first] -= it->first->birth_count();
587   }
588
589   for (ThreadData::BirthMap::const_iterator it = birth_map.begin();
590        it != birth_map.end(); ++it) {
591     (*birth_counts)[it->second] += it->second->birth_count();
592   }
593
594   if (!kTrackParentChildLinks)
595     return;
596
597   for (ThreadData::ParentChildSet::const_iterator it = parent_child_set.begin();
598        it != parent_child_set.end(); ++it) {
599     process_data->descendants.push_back(ParentChildPairSnapshot(*it));
600   }
601 }
602
603 // This may be called from another thread.
604 void ThreadData::SnapshotMaps(bool reset_max,
605                               BirthMap* birth_map,
606                               DeathMap* death_map,
607                               ParentChildSet* parent_child_set) {
608   base::AutoLock lock(map_lock_);
609   for (BirthMap::const_iterator it = birth_map_.begin();
610        it != birth_map_.end(); ++it)
611     (*birth_map)[it->first] = it->second;
612   for (DeathMap::iterator it = death_map_.begin();
613        it != death_map_.end(); ++it) {
614     (*death_map)[it->first] = it->second;
615     if (reset_max)
616       it->second.ResetMax();
617   }
618
619   if (!kTrackParentChildLinks)
620     return;
621
622   for (ParentChildSet::iterator it = parent_child_set_.begin();
623        it != parent_child_set_.end(); ++it)
624     parent_child_set->insert(*it);
625 }
626
627 // static
628 void ThreadData::ResetAllThreadData() {
629   ThreadData* my_list = first();
630
631   for (ThreadData* thread_data = my_list;
632        thread_data;
633        thread_data = thread_data->next())
634     thread_data->Reset();
635 }
636
637 void ThreadData::Reset() {
638   base::AutoLock lock(map_lock_);
639   for (DeathMap::iterator it = death_map_.begin();
640        it != death_map_.end(); ++it)
641     it->second.Clear();
642   for (BirthMap::iterator it = birth_map_.begin();
643        it != birth_map_.end(); ++it)
644     it->second->Clear();
645 }
646
647 static void OptionallyInitializeAlternateTimer() {
648   NowFunction* alternate_time_source = GetAlternateTimeSource();
649   if (alternate_time_source)
650     ThreadData::SetAlternateTimeSource(alternate_time_source);
651 }
652
653 bool ThreadData::Initialize() {
654   if (!kTrackAllTaskObjects)
655     return false;  // Not compiled in.
656   if (status_ >= DEACTIVATED)
657     return true;  // Someone else did the initialization.
658   // Due to racy lazy initialization in tests, we'll need to recheck status_
659   // after we acquire the lock.
660
661   // Ensure that we don't double initialize tls.  We are called when single
662   // threaded in the product, but some tests may be racy and lazy about our
663   // initialization.
664   base::AutoLock lock(*list_lock_.Pointer());
665   if (status_ >= DEACTIVATED)
666     return true;  // Someone raced in here and beat us.
667
668   // Put an alternate timer in place if the environment calls for it, such as
669   // for tracking TCMalloc allocations.  This insertion is idempotent, so we
670   // don't mind if there is a race, and we'd prefer not to be in a lock while
671   // doing this work.
672   if (kAllowAlternateTimeSourceHandling)
673     OptionallyInitializeAlternateTimer();
674
675   // Perform the "real" TLS initialization now, and leave it intact through
676   // process termination.
677   if (!tls_index_.initialized()) {  // Testing may have initialized this.
678     DCHECK_EQ(status_, UNINITIALIZED);
679     tls_index_.Initialize(&ThreadData::OnThreadTermination);
680     if (!tls_index_.initialized())
681       return false;
682   } else {
683     // TLS was initialzed for us earlier.
684     DCHECK_EQ(status_, DORMANT_DURING_TESTS);
685   }
686
687   // Incarnation counter is only significant to testing, as it otherwise will
688   // never again change in this process.
689   ++incarnation_counter_;
690
691   // The lock is not critical for setting status_, but it doesn't hurt. It also
692   // ensures that if we have a racy initialization, that we'll bail as soon as
693   // we get the lock earlier in this method.
694   status_ = kInitialStartupState;
695   if (!kTrackParentChildLinks &&
696       kInitialStartupState == PROFILING_CHILDREN_ACTIVE)
697     status_ = PROFILING_ACTIVE;
698   DCHECK(status_ != UNINITIALIZED);
699   return true;
700 }
701
702 // static
703 bool ThreadData::InitializeAndSetTrackingStatus(Status status) {
704   DCHECK_GE(status, DEACTIVATED);
705   DCHECK_LE(status, PROFILING_CHILDREN_ACTIVE);
706
707   if (!Initialize())  // No-op if already initialized.
708     return false;  // Not compiled in.
709
710   if (!kTrackParentChildLinks && status > DEACTIVATED)
711     status = PROFILING_ACTIVE;
712   status_ = status;
713   return true;
714 }
715
716 // static
717 ThreadData::Status ThreadData::status() {
718   return status_;
719 }
720
721 // static
722 bool ThreadData::TrackingStatus() {
723   return status_ > DEACTIVATED;
724 }
725
726 // static
727 bool ThreadData::TrackingParentChildStatus() {
728   return status_ >= PROFILING_CHILDREN_ACTIVE;
729 }
730
731 // static
732 TrackedTime ThreadData::NowForStartOfRun(const Births* parent) {
733   if (kTrackParentChildLinks && parent && status_ > PROFILING_ACTIVE) {
734     ThreadData* current_thread_data = Get();
735     if (current_thread_data)
736       current_thread_data->parent_stack_.push(parent);
737   }
738   return Now();
739 }
740
741 // static
742 TrackedTime ThreadData::NowForEndOfRun() {
743   return Now();
744 }
745
746 // static
747 void ThreadData::SetAlternateTimeSource(NowFunction* now_function) {
748   DCHECK(now_function);
749   if (kAllowAlternateTimeSourceHandling)
750     now_function_ = now_function;
751 }
752
753 // static
754 TrackedTime ThreadData::Now() {
755   if (kAllowAlternateTimeSourceHandling && now_function_)
756     return TrackedTime::FromMilliseconds((*now_function_)());
757   if (kTrackAllTaskObjects && TrackingStatus())
758     return TrackedTime::Now();
759   return TrackedTime();  // Super fast when disabled, or not compiled.
760 }
761
762 // static
763 void ThreadData::EnsureCleanupWasCalled(int major_threads_shutdown_count) {
764   base::AutoLock lock(*list_lock_.Pointer());
765   if (worker_thread_data_creation_count_ == 0)
766     return;  // We haven't really run much, and couldn't have leaked.
767   // Verify that we've at least shutdown/cleanup the major namesd threads.  The
768   // caller should tell us how many thread shutdowns should have taken place by
769   // now.
770   return;  // TODO(jar): until this is working on XP, don't run the real test.
771   CHECK_GT(cleanup_count_, major_threads_shutdown_count);
772 }
773
774 // static
775 void ThreadData::ShutdownSingleThreadedCleanup(bool leak) {
776   // This is only called from test code, where we need to cleanup so that
777   // additional tests can be run.
778   // We must be single threaded... but be careful anyway.
779   if (!InitializeAndSetTrackingStatus(DEACTIVATED))
780     return;
781   ThreadData* thread_data_list;
782   {
783     base::AutoLock lock(*list_lock_.Pointer());
784     thread_data_list = all_thread_data_list_head_;
785     all_thread_data_list_head_ = NULL;
786     ++incarnation_counter_;
787     // To be clean, break apart the retired worker list (though we leak them).
788     while (first_retired_worker_) {
789       ThreadData* worker = first_retired_worker_;
790       CHECK_GT(worker->worker_thread_number_, 0);
791       first_retired_worker_ = worker->next_retired_worker_;
792       worker->next_retired_worker_ = NULL;
793     }
794   }
795
796   // Put most global static back in pristine shape.
797   worker_thread_data_creation_count_ = 0;
798   cleanup_count_ = 0;
799   tls_index_.Set(NULL);
800   status_ = DORMANT_DURING_TESTS;  // Almost UNINITIALIZED.
801
802   // To avoid any chance of racing in unit tests, which is the only place we
803   // call this function, we may sometimes leak all the data structures we
804   // recovered, as they may still be in use on threads from prior tests!
805   if (leak) {
806     ThreadData* thread_data = thread_data_list;
807     while (thread_data) {
808       ANNOTATE_LEAKING_OBJECT_PTR(thread_data);
809       thread_data = thread_data->next();
810     }
811     return;
812   }
813
814   // When we want to cleanup (on a single thread), here is what we do.
815
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();
820
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.
825   }
826 }
827
828 //------------------------------------------------------------------------------
829 TaskSnapshot::TaskSnapshot() {
830 }
831
832 TaskSnapshot::TaskSnapshot(const BirthOnThread& birth,
833                            const DeathData& death_data,
834                            const std::string& death_thread_name)
835     : birth(birth),
836       death_data(death_data),
837       death_thread_name(death_thread_name) {
838 }
839
840 TaskSnapshot::~TaskSnapshot() {
841 }
842
843 //------------------------------------------------------------------------------
844 // ParentChildPairSnapshot
845
846 ParentChildPairSnapshot::ParentChildPairSnapshot() {
847 }
848
849 ParentChildPairSnapshot::ParentChildPairSnapshot(
850     const ThreadData::ParentChildPair& parent_child)
851     : parent(*parent_child.first),
852       child(*parent_child.second) {
853 }
854
855 ParentChildPairSnapshot::~ParentChildPairSnapshot() {
856 }
857
858 //------------------------------------------------------------------------------
859 // ProcessDataSnapshot
860
861 ProcessDataSnapshot::ProcessDataSnapshot()
862 #if !defined(OS_NACL)
863     : process_id(base::GetCurrentProcId()) {
864 #else
865     : process_id(0) {
866 #endif
867 }
868
869 ProcessDataSnapshot::~ProcessDataSnapshot() {
870 }
871
872 }  // namespace tracked_objects