Updating trunk VERSION from 1010.0 to 1011.0
[chromium-blink-merge.git] / base / tracked_objects.h
bloba088ee201bac95b754e36dff68bfe17f219134e4
1 // Copyright (c) 2011 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 #ifndef BASE_TRACKED_OBJECTS_H_
6 #define BASE_TRACKED_OBJECTS_H_
7 #pragma once
9 #include <map>
10 #include <set>
11 #include <stack>
12 #include <string>
13 #include <utility>
14 #include <vector>
16 #include "base/base_export.h"
17 #include "base/gtest_prod_util.h"
18 #include "base/lazy_instance.h"
19 #include "base/location.h"
20 #include "base/profiler/tracked_time.h"
21 #include "base/time.h"
22 #include "base/synchronization/lock.h"
23 #include "base/threading/thread_local_storage.h"
24 #include "base/tracking_info.h"
25 #include "base/values.h"
27 // TrackedObjects provides a database of stats about objects (generally Tasks)
28 // that are tracked. Tracking means their birth, death, duration, birth thread,
29 // death thread, and birth place are recorded. This data is carefully spread
30 // across a series of objects so that the counts and times can be rapidly
31 // updated without (usually) having to lock the data, and hence there is usually
32 // very little contention caused by the tracking. The data can be viewed via
33 // the about:profiler URL, with a variety of sorting and filtering choices.
35 // These classes serve as the basis of a profiler of sorts for the Tasks system.
36 // As a result, design decisions were made to maximize speed, by minimizing
37 // recurring allocation/deallocation, lock contention and data copying. In the
38 // "stable" state, which is reached relatively quickly, there is no separate
39 // marginal allocation cost associated with construction or destruction of
40 // tracked objects, no locks are generally employed, and probably the largest
41 // computational cost is associated with obtaining start and stop times for
42 // instances as they are created and destroyed.
44 // The following describes the lifecycle of tracking an instance.
46 // First off, when the instance is created, the FROM_HERE macro is expanded
47 // to specify the birth place (file, line, function) where the instance was
48 // created. That data is used to create a transient Location instance
49 // encapsulating the above triple of information. The strings (like __FILE__)
50 // are passed around by reference, with the assumption that they are static, and
51 // will never go away. This ensures that the strings can be dealt with as atoms
52 // with great efficiency (i.e., copying of strings is never needed, and
53 // comparisons for equality can be based on pointer comparisons).
55 // Next, a Births instance is created for use ONLY on the thread where this
56 // instance was created. That Births instance records (in a base class
57 // BirthOnThread) references to the static data provided in a Location instance,
58 // as well as a pointer specifying the thread on which the birth takes place.
59 // Hence there is at most one Births instance for each Location on each thread.
60 // The derived Births class contains slots for recording statistics about all
61 // instances born at the same location. Statistics currently include only the
62 // count of instances constructed.
64 // Since the base class BirthOnThread contains only constant data, it can be
65 // freely accessed by any thread at any time (i.e., only the statistic needs to
66 // be handled carefully, and stats are updated exclusively on the birth thread).
68 // For Tasks, having now either constructed or found the Births instance
69 // described above, a pointer to the Births instance is then recorded into the
70 // PendingTask structure in MessageLoop. This fact alone is very useful in
71 // debugging, when there is a question of where an instance came from. In
72 // addition, the birth time is also recorded and used to later evaluate the
73 // lifetime duration of the whole Task. As a result of the above embedding, we
74 // can find out a Task's location of birth, and thread of birth, without using
75 // any locks, as all that data is constant across the life of the process.
77 // The above work *could* also be done for any other object as well by calling
78 // TallyABirthIfActive() and TallyRunOnNamedThreadIfTracking() as appropriate.
80 // The amount of memory used in the above data structures depends on how many
81 // threads there are, and how many Locations of construction there are.
82 // Fortunately, we don't use memory that is the product of those two counts, but
83 // rather we only need one Births instance for each thread that constructs an
84 // instance at a Location. In many cases, instances are only created on one
85 // thread, so the memory utilization is actually fairly restrained.
87 // Lastly, when an instance is deleted, the final tallies of statistics are
88 // carefully accumulated. That tallying writes into slots (members) in a
89 // collection of DeathData instances. For each birth place Location that is
90 // destroyed on a thread, there is a DeathData instance to record the additional
91 // death count, as well as accumulate the run-time and queue-time durations for
92 // the instance as it is destroyed (dies). By maintaining a single place to
93 // aggregate this running sum *only* for the given thread, we avoid the need to
94 // lock such DeathData instances. (i.e., these accumulated stats in a DeathData
95 // instance are exclusively updated by the singular owning thread).
97 // With the above lifecycle description complete, the major remaining detail is
98 // explaining how each thread maintains a list of DeathData instances, and of
99 // Births instances, and is able to avoid additional (redundant/unnecessary)
100 // allocations.
102 // Each thread maintains a list of data items specific to that thread in a
103 // ThreadData instance (for that specific thread only). The two critical items
104 // are lists of DeathData and Births instances. These lists are maintained in
105 // STL maps, which are indexed by Location. As noted earlier, we can compare
106 // locations very efficiently as we consider the underlying data (file,
107 // function, line) to be atoms, and hence pointer comparison is used rather than
108 // (slow) string comparisons.
110 // To provide a mechanism for iterating over all "known threads," which means
111 // threads that have recorded a birth or a death, we create a singly linked list
112 // of ThreadData instances. Each such instance maintains a pointer to the next
113 // one. A static member of ThreadData provides a pointer to the first item on
114 // this global list, and access via that all_thread_data_list_head_ item
115 // requires the use of the list_lock_.
116 // When new ThreadData instances is added to the global list, it is pre-pended,
117 // which ensures that any prior acquisition of the list is valid (i.e., the
118 // holder can iterate over it without fear of it changing, or the necessity of
119 // using an additional lock. Iterations are actually pretty rare (used
120 // primarilly for cleanup, or snapshotting data for display), so this lock has
121 // very little global performance impact.
123 // The above description tries to define the high performance (run time)
124 // portions of these classes. After gathering statistics, calls instigated
125 // by visiting about:profiler will assemble and aggregate data for display. The
126 // following data structures are used for producing such displays. They are
127 // not performance critical, and their only major constraint is that they should
128 // be able to run concurrently with ongoing augmentation of the birth and death
129 // data.
131 // For a given birth location, information about births is spread across data
132 // structures that are asynchronously changing on various threads. For display
133 // purposes, we need to construct Snapshot instances for each combination of
134 // birth thread, death thread, and location, along with the count of such
135 // lifetimes. We gather such data into a Snapshot instances, so that such
136 // instances can be sorted and aggregated (and remain frozen during our
137 // processing). Snapshot instances use pointers to constant portions of the
138 // birth and death datastructures, but have local (frozen) copies of the actual
139 // statistics (birth count, durations, etc. etc.).
141 // A DataCollector is a container object that holds a set of Snapshots. The
142 // statistics in a snapshot are gathered asynhcronously relative to their
143 // ongoing updates. It is possible, though highly unlikely, that stats could be
144 // incorrectly recorded by this process (all data is held in 32 bit ints, but we
145 // are not atomically collecting all data, so we could have count that does not,
146 // for example, match with the number of durations we accumulated). The
147 // advantage to having fast (non-atomic) updates of the data outweighs the
148 // minimal risk of a singular corrupt statistic snapshot (only the snapshot
149 // could be corrupt, not the underlying and ongoing statistic). In constrast,
150 // pointer data that is accessed during snapshotting is completely invariant,
151 // and hence is perfectly acquired (i.e., no potential corruption, and no risk
152 // of a bad memory reference).
154 // After an array of Snapshots instances are collected into a DataCollector,
155 // they need to be prepared for displaying our output. We currently implement a
156 // serialization into a Value hierarchy, which is automatically translated to
157 // JSON when supplied to rendering Java Scirpt.
159 // TODO(jar): We can implement a Snapshot system that *tries* to grab the
160 // snapshots on the source threads *when* they have MessageLoops available
161 // (worker threads don't have message loops generally, and hence gathering from
162 // them will continue to be asynchronous). We had an implementation of this in
163 // the past, but the difficulty is dealing with message loops being terminated.
164 // We can *try* to spam the available threads via some message loop proxy to
165 // achieve this feat, and it *might* be valuable when we are colecting data for
166 // upload via UMA (where correctness of data may be more significant than for a
167 // single screen of about:profiler).
169 // TODO(jar): We should support (optionally) the recording of parent-child
170 // relationships for tasks. This should be done by detecting what tasks are
171 // Born during the running of a parent task. The resulting data can be used by
172 // a smarter profiler to aggregate the cost of a series of child tasks into
173 // the ancestor task. It can also be used to illuminate what child or parent is
174 // related to each task.
176 // TODO(jar): We need to store DataCollections, and provide facilities for
177 // taking the difference between two gathered DataCollections. For now, we're
178 // just adding a hack that Reset()s to zero all counts and stats. This is also
179 // done in a slighly thread-unsafe fashion, as the resetting is done
180 // asynchronously relative to ongoing updates (but all data is 32 bit in size).
181 // For basic profiling, this will work "most of the time," and should be
182 // sufficient... but storing away DataCollections is the "right way" to do this.
183 // We'll accomplish this via JavaScript storage of snapshots, and then we'll
184 // remove the Reset() methods. We may also need a short-term-max value in
185 // DeathData that is reset (as synchronously as possible) during each snapshot.
186 // This will facilitate displaying a max value for each snapshot period.
188 class MessageLoop;
190 namespace tracked_objects {
192 //------------------------------------------------------------------------------
193 // For a specific thread, and a specific birth place, the collection of all
194 // death info (with tallies for each death thread, to prevent access conflicts).
195 class ThreadData;
196 class BASE_EXPORT BirthOnThread {
197 public:
198 BirthOnThread(const Location& location, const ThreadData& current);
200 const Location location() const;
201 const ThreadData* birth_thread() const;
203 // Insert our state (location, and thread name) into the dictionary.
204 // Use the supplied |prefix| in front of "thread_name" and "location"
205 // respectively when defining keys.
206 void ToValue(const std::string& prefix,
207 base::DictionaryValue* dictionary) const;
209 private:
210 // File/lineno of birth. This defines the essence of the task, as the context
211 // of the birth (construction) often tell what the item is for. This field
212 // is const, and hence safe to access from any thread.
213 const Location location_;
215 // The thread that records births into this object. Only this thread is
216 // allowed to update birth_count_ (which changes over time).
217 const ThreadData* const birth_thread_;
219 DISALLOW_COPY_AND_ASSIGN(BirthOnThread);
222 //------------------------------------------------------------------------------
223 // A class for accumulating counts of births (without bothering with a map<>).
225 class BASE_EXPORT Births: public BirthOnThread {
226 public:
227 Births(const Location& location, const ThreadData& current);
229 int birth_count() const;
231 // When we have a birth we update the count for this BirhPLace.
232 void RecordBirth();
234 // When a birthplace is changed (updated), we need to decrement the counter
235 // for the old instance.
236 void ForgetBirth();
238 // Hack to quickly reset all counts to zero.
239 void Clear();
241 private:
242 // The number of births on this thread for our location_.
243 int birth_count_;
245 DISALLOW_COPY_AND_ASSIGN(Births);
248 //------------------------------------------------------------------------------
249 // Basic info summarizing multiple destructions of a tracked object with a
250 // single birthplace (fixed Location). Used both on specific threads, and also
251 // in snapshots when integrating assembled data.
253 class BASE_EXPORT DeathData {
254 public:
255 // Default initializer.
256 DeathData();
258 // When deaths have not yet taken place, and we gather data from all the
259 // threads, we create DeathData stats that tally the number of births without
260 // a corresponding death.
261 explicit DeathData(int count);
263 // Update stats for a task destruction (death) that had a Run() time of
264 // |duration|, and has had a queueing delay of |queue_duration|.
265 void RecordDeath(const DurationInt queue_duration,
266 const DurationInt run_duration,
267 int random_number);
269 // Metrics accessors, used only in tests.
270 int count() const;
271 DurationInt run_duration_sum() const;
272 DurationInt run_duration_max() const;
273 DurationInt run_duration_sample() const;
274 DurationInt queue_duration_sum() const;
275 DurationInt queue_duration_max() const;
276 DurationInt queue_duration_sample() const;
278 // Construct a DictionaryValue instance containing all our stats. The caller
279 // assumes ownership of the returned instance.
280 base::DictionaryValue* ToValue() const;
282 // Reset the max values to zero.
283 void ResetMax();
285 // Reset all tallies to zero. This is used as a hack on realtime data.
286 void Clear();
288 private:
289 // Members are ordered from most regularly read and updated, to least
290 // frequently used. This might help a bit with cache lines.
291 // Number of runs seen (divisor for calculating averages).
292 int count_;
293 // Basic tallies, used to compute averages.
294 DurationInt run_duration_sum_;
295 DurationInt queue_duration_sum_;
296 // Max values, used by local visualization routines. These are often read,
297 // but rarely updated.
298 DurationInt run_duration_max_;
299 DurationInt queue_duration_max_;
300 // Samples, used by by crowd sourcing gatherers. These are almost never read,
301 // and rarely updated.
302 DurationInt run_duration_sample_;
303 DurationInt queue_duration_sample_;
306 //------------------------------------------------------------------------------
307 // A temporary collection of data that can be sorted and summarized. It is
308 // gathered (carefully) from many threads. Instances are held in arrays and
309 // processed, filtered, and rendered.
310 // The source of this data was collected on many threads, and is asynchronously
311 // changing. The data in this instance is not asynchronously changing.
313 class BASE_EXPORT Snapshot {
314 public:
315 // When snapshotting a full life cycle set (birth-to-death), use this:
316 Snapshot(const BirthOnThread& birth_on_thread,
317 const ThreadData& death_thread,
318 const DeathData& death_data);
320 // When snapshotting a birth, with no death yet, use this:
321 Snapshot(const BirthOnThread& birth_on_thread, int count);
323 // Accessor, that provides default value when there is no death thread.
324 const std::string DeathThreadName() const;
326 // Construct a DictionaryValue instance containing all our data recursively.
327 // The caller assumes ownership of the memory in the returned instance.
328 base::DictionaryValue* ToValue() const;
330 private:
331 const BirthOnThread* birth_; // Includes Location and birth_thread.
332 const ThreadData* death_thread_;
333 DeathData death_data_;
336 //------------------------------------------------------------------------------
337 // For each thread, we have a ThreadData that stores all tracking info generated
338 // on this thread. This prevents the need for locking as data accumulates.
339 // We use ThreadLocalStorage to quickly identfy the current ThreadData context.
340 // We also have a linked list of ThreadData instances, and that list is used to
341 // harvest data from all existing instances.
343 class BASE_EXPORT ThreadData {
344 public:
345 // Current allowable states of the tracking system. The states can vary
346 // between ACTIVE and DEACTIVATED, but can never go back to UNINITIALIZED.
347 enum Status {
348 UNINITIALIZED, // PRistine, link-time state before running.
349 DORMANT_DURING_TESTS, // Only used during testing.
350 DEACTIVATED, // No longer recording profling.
351 PROFILING_ACTIVE, // Recording profiles (no parent-child links).
352 PROFILING_CHILDREN_ACTIVE, // Fully active, recording parent-child links.
355 typedef std::map<Location, Births*> BirthMap;
356 typedef std::map<const Births*, DeathData> DeathMap;
357 typedef std::pair<const Births*, const Births*> ParentChildPair;
358 typedef std::set<ParentChildPair> ParentChildSet;
359 typedef std::stack<const Births*> ParentStack;
361 // Initialize the current thread context with a new instance of ThreadData.
362 // This is used by all threads that have names, and should be explicitly
363 // set *before* any births on the threads have taken place. It is generally
364 // only used by the message loop, which has a well defined thread name.
365 static void InitializeThreadContext(const std::string& suggested_name);
367 // Using Thread Local Store, find the current instance for collecting data.
368 // If an instance does not exist, construct one (and remember it for use on
369 // this thread.
370 // This may return NULL if the system is disabled for any reason.
371 static ThreadData* Get();
373 // Constructs a DictionaryValue instance containing all recursive results in
374 // our process. The caller assumes ownership of the memory in the returned
375 // instance. During the scavenging, if |reset_max| is true, then the
376 // DeathData instances max-values are reset to zero during this scan.
377 static base::DictionaryValue* ToValue(bool reset_max);
379 // Finds (or creates) a place to count births from the given location in this
380 // thread, and increment that tally.
381 // TallyABirthIfActive will returns NULL if the birth cannot be tallied.
382 static Births* TallyABirthIfActive(const Location& location);
384 // Records the end of a timed run of an object. The |completed_task| contains
385 // a pointer to a Births, the time_posted, and a delayed_start_time if any.
386 // The |start_of_run| indicates when we started to perform the run of the
387 // task. The delayed_start_time is non-null for tasks that were posted as
388 // delayed tasks, and it indicates when the task should have run (i.e., when
389 // it should have posted out of the timer queue, and into the work queue.
390 // The |end_of_run| was just obtained by a call to Now() (just after the task
391 // finished). It is provided as an argument to help with testing.
392 static void TallyRunOnNamedThreadIfTracking(
393 const base::TrackingInfo& completed_task,
394 const TrackedTime& start_of_run,
395 const TrackedTime& end_of_run);
397 // Record the end of a timed run of an object. The |birth| is the record for
398 // the instance, the |time_posted| records that instant, which is presumed to
399 // be when the task was posted into a queue to run on a worker thread.
400 // The |start_of_run| is when the worker thread started to perform the run of
401 // the task.
402 // The |end_of_run| was just obtained by a call to Now() (just after the task
403 // finished).
404 static void TallyRunOnWorkerThreadIfTracking(
405 const Births* birth,
406 const TrackedTime& time_posted,
407 const TrackedTime& start_of_run,
408 const TrackedTime& end_of_run);
410 // Record the end of execution in region, generally corresponding to a scope
411 // being exited.
412 static void TallyRunInAScopedRegionIfTracking(
413 const Births* birth,
414 const TrackedTime& start_of_run,
415 const TrackedTime& end_of_run);
417 const std::string thread_name() const;
419 // Snapshot (under a lock) copies of the maps in each ThreadData instance. For
420 // each set of maps (BirthMap, DeathMap, and ParentChildSet) call the Append()
421 // method of the |target| DataCollector. If |reset_max| is true, then the max
422 // values in each DeathData instance should be reset during the scan.
423 static void SendAllMaps(bool reset_max, class DataCollector* target);
425 // Hack: asynchronously clear all birth counts and death tallies data values
426 // in all ThreadData instances. The numerical (zeroing) part is done without
427 // use of a locks or atomics exchanges, and may (for int64 values) produce
428 // bogus counts VERY rarely.
429 static void ResetAllThreadData();
431 // Initializes all statics if needed (this initialization call should be made
432 // while we are single threaded). Returns false if unable to initialize.
433 static bool Initialize();
435 // Sets internal status_.
436 // If |status| is false, then status_ is set to DEACTIVATED.
437 // If |status| is true, then status_ is set to, PROFILING_ACTIVE, or
438 // PROFILING_CHILDREN_ACTIVE.
439 // If tracking is not compiled in, this function will return false.
440 // If parent-child tracking is not compiled in, then an attempt to set the
441 // status to PROFILING_CHILDREN_ACTIVE will only result in a status of
442 // PROFILING_ACTIVE (i.e., it can't be set to a higher level than what is
443 // compiled into the binary, and parent-child tracking at the
444 // PROFILING_CHILDREN_ACTIVE level might not be compiled in).
445 static bool InitializeAndSetTrackingStatus(bool status);
447 // Indicate if any sort of profiling is being done (i.e., we are more than
448 // DEACTIVATED).
449 static bool tracking_status();
451 // For testing only, indicate if the status of parent-child tracking is turned
452 // on. This is currently a compiled option, atop tracking_status().
453 static bool tracking_parent_child_status();
455 // Special versions of Now() for getting times at start and end of a tracked
456 // run. They are super fast when tracking is disabled, and have some internal
457 // side effects when we are tracking, so that we can deduce the amount of time
458 // accumulated outside of execution of tracked runs.
459 // The task that will be tracked is passed in as |parent| so that parent-child
460 // relationships can be (optionally) calculated.
461 static TrackedTime NowForStartOfRun(const Births* parent);
462 static TrackedTime NowForEndOfRun();
464 // Provide a time function that does nothing (runs fast) when we don't have
465 // the profiler enabled. It will generally be optimized away when it is
466 // ifdef'ed to be small enough (allowing the profiler to be "compiled out" of
467 // the code).
468 static TrackedTime Now();
470 // This function can be called at process termination to validate that thread
471 // cleanup routines have been called for at least some number of named
472 // threads.
473 static void EnsureCleanupWasCalled(int major_threads_shutdown_count);
475 private:
476 // Allow only tests to call ShutdownSingleThreadedCleanup. We NEVER call it
477 // in production code.
478 // TODO(jar): Make this a friend in DEBUG only, so that the optimizer has a
479 // better change of optimizing (inlining? etc.) private methods (knowing that
480 // there will be no need for an external entry point).
481 friend class TrackedObjectsTest;
482 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, MinimalStartupShutdown);
483 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, TinyStartupShutdown);
484 FRIEND_TEST_ALL_PREFIXES(TrackedObjectsTest, ParentChildTest);
486 // Worker thread construction creates a name since there is none.
487 explicit ThreadData(int thread_number);
489 // Message loop based construction should provide a name.
490 explicit ThreadData(const std::string& suggested_name);
492 ~ThreadData();
494 // Push this instance to the head of all_thread_data_list_head_, linking it to
495 // the previous head. This is performed after each construction, and leaves
496 // the instance permanently on that list.
497 void PushToHeadOfList();
499 // (Thread safe) Get start of list of all ThreadData instances using the lock.
500 static ThreadData* first();
502 // Iterate through the null terminated list of ThreadData instances.
503 ThreadData* next() const;
506 // In this thread's data, record a new birth.
507 Births* TallyABirth(const Location& location);
509 // Find a place to record a death on this thread.
510 void TallyADeath(const Births& birth,
511 DurationInt queue_duration,
512 DurationInt duration);
514 // Using our lock, make a copy of the specified maps. This call may be made
515 // on non-local threads, which necessitate the use of the lock to prevent
516 // the map(s) from being reallocaed while they are copied. If |reset_max| is
517 // true, then, just after we copy the DeathMap, we will set the max values to
518 // zero in the active DeathMap (not the snapshot).
519 void SnapshotMaps(bool reset_max,
520 BirthMap* birth_map,
521 DeathMap* death_map,
522 ParentChildSet* parent_child_set);
524 // Using our lock to protect the iteration, Clear all birth and death data.
525 void Reset();
527 // This method is called by the TLS system when a thread terminates.
528 // The argument may be NULL if this thread has never tracked a birth or death.
529 static void OnThreadTermination(void* thread_data);
531 // This method should be called when a worker thread terminates, so that we
532 // can save all the thread data into a cache of reusable ThreadData instances.
533 void OnThreadTerminationCleanup();
535 // Cleans up data structures, and returns statics to near pristine (mostly
536 // uninitialized) state. If there is any chance that other threads are still
537 // using the data structures, then the |leak| argument should be passed in as
538 // true, and the data structures (birth maps, death maps, ThreadData
539 // insntances, etc.) will be leaked and not deleted. If you have joined all
540 // threads since the time that InitializeAndSetTrackingStatus() was called,
541 // then you can pass in a |leak| value of false, and this function will
542 // delete recursively all data structures, starting with the list of
543 // ThreadData instances.
544 static void ShutdownSingleThreadedCleanup(bool leak);
546 // We use thread local store to identify which ThreadData to interact with.
547 static base::ThreadLocalStorage::Slot tls_index_;
549 // List of ThreadData instances for use with worker threads. When a worker
550 // thread is done (terminated), we push it onto this llist. When a new worker
551 // thread is created, we first try to re-use a ThreadData instance from the
552 // list, and if none are available, construct a new one.
553 // This is only accessed while list_lock_ is held.
554 static ThreadData* first_retired_worker_;
556 // Link to the most recently created instance (starts a null terminated list).
557 // The list is traversed by about:profiler when it needs to snapshot data.
558 // This is only accessed while list_lock_ is held.
559 static ThreadData* all_thread_data_list_head_;
561 // The next available worker thread number. This should only be accessed when
562 // the list_lock_ is held.
563 static int worker_thread_data_creation_count_;
565 // The number of times TLS has called us back to cleanup a ThreadData
566 // instance. This is only accessed while list_lock_ is held.
567 static int cleanup_count_;
569 // Incarnation sequence number, indicating how many times (during unittests)
570 // we've either transitioned out of UNINITIALIZED, or into that state. This
571 // value is only accessed while the list_lock_ is held.
572 static int incarnation_counter_;
574 // Protection for access to all_thread_data_list_head_, and to
575 // unregistered_thread_data_pool_. This lock is leaked at shutdown.
576 // The lock is very infrequently used, so we can afford to just make a lazy
577 // instance and be safe.
578 static base::LazyInstance<base::Lock,
579 base::LeakyLazyInstanceTraits<base::Lock> > list_lock_;
581 // We set status_ to SHUTDOWN when we shut down the tracking service.
582 static Status status_;
584 // Link to next instance (null terminated list). Used to globally track all
585 // registered instances (corresponds to all registered threads where we keep
586 // data).
587 ThreadData* next_;
589 // Pointer to another ThreadData instance for a Worker-Thread that has been
590 // retired (its thread was terminated). This value is non-NULL only for a
591 // retired ThreadData associated with a Worker-Thread.
592 ThreadData* next_retired_worker_;
594 // The name of the thread that is being recorded. If this thread has no
595 // message_loop, then this is a worker thread, with a sequence number postfix.
596 std::string thread_name_;
598 // Indicate if this is a worker thread, and the ThreadData contexts should be
599 // stored in the unregistered_thread_data_pool_ when not in use.
600 // Value is zero when it is not a worker thread. Value is a positive integer
601 // corresponding to the created thread name if it is a worker thread.
602 int worker_thread_number_;
604 // A map used on each thread to keep track of Births on this thread.
605 // This map should only be accessed on the thread it was constructed on.
606 // When a snapshot is needed, this structure can be locked in place for the
607 // duration of the snapshotting activity.
608 BirthMap birth_map_;
610 // Similar to birth_map_, this records informations about death of tracked
611 // instances (i.e., when a tracked instance was destroyed on this thread).
612 // It is locked before changing, and hence other threads may access it by
613 // locking before reading it.
614 DeathMap death_map_;
616 // A set of parents that created children tasks on this thread. Each pair
617 // corresponds to potentially non-local Births (location and thread), and a
618 // local Births (that took place on this thread).
619 ParentChildSet parent_child_set_;
621 // Lock to protect *some* access to BirthMap and DeathMap. The maps are
622 // regularly read and written on this thread, but may only be read from other
623 // threads. To support this, we acquire this lock if we are writing from this
624 // thread, or reading from another thread. For reading from this thread we
625 // don't need a lock, as there is no potential for a conflict since the
626 // writing is only done from this thread.
627 mutable base::Lock map_lock_;
629 // The stack of parents that are currently being profiled. This includes only
630 // tasks that have started a timer recently via NowForStartOfRun(), but not
631 // yet concluded with a NowForEndOfRun(). Usually this stack is one deep, but
632 // if a scoped region is profiled, or <sigh> a task runs a nested-message
633 // loop, then the stack can grow larger. Note that we don't try to deduct
634 // time in nested porfiles, as our current timer is based on wall-clock time,
635 // and not CPU time (and we're hopeful that nested timing won't be a
636 // significant additional cost).
637 ParentStack parent_stack_;
639 // A random number that we used to select decide which sample to keep as a
640 // representative sample in each DeathData instance. We can't start off with
641 // much randomness (because we can't call RandInt() on all our threads), so
642 // we stir in more and more as we go.
643 int32 random_number_;
645 // Record of what the incarnation_counter_ was when this instance was created.
646 // If the incarnation_counter_ has changed, then we avoid pushing into the
647 // pool (this is only critical in tests which go through multiple
648 // incarnations).
649 int incarnation_count_for_pool_;
651 DISALLOW_COPY_AND_ASSIGN(ThreadData);
654 //------------------------------------------------------------------------------
655 // DataCollector is a container class for Snapshot and BirthOnThread count
656 // items.
658 class BASE_EXPORT DataCollector {
659 public:
660 typedef std::vector<Snapshot> Collection;
662 // Construct with a list of how many threads should contribute. This helps us
663 // determine (in the async case) when we are done with all contributions.
664 DataCollector();
665 ~DataCollector();
667 // Adds all stats from the indicated thread into our arrays. Accepts copies
668 // of the birth_map and death_map, so that the data will not change during the
669 // iterations and processing.
670 void Append(const ThreadData &thread_data,
671 const ThreadData::BirthMap& birth_map,
672 const ThreadData::DeathMap& death_map,
673 const ThreadData::ParentChildSet& parent_child_set);
675 // After the accumulation phase, the following accessor is used to process the
676 // data (i.e., sort it, filter it, etc.).
677 Collection* collection();
679 // Adds entries for all the remaining living objects (objects that have
680 // tallied a birth, but have not yet tallied a matching death, and hence must
681 // be either running, queued up, or being held in limbo for future posting).
682 // This should be called after all known ThreadData instances have been
683 // processed using Append().
684 void AddListOfLivingObjects();
686 // Generates a ListValue representation of the vector of snapshots, and
687 // inserts the results into |dictionary|.
688 void ToValue(base::DictionaryValue* dictionary) const;
690 private:
691 typedef std::map<const BirthOnThread*, int> BirthCount;
693 // The array that we collect data into.
694 Collection collection_;
696 // The total number of births recorded at each location for which we have not
697 // seen a death count. This map changes as we do Append() calls, and is later
698 // used by AddListOfLivingObjects() to gather up unaccounted for births.
699 BirthCount global_birth_count_;
701 // The complete list of parent-child relationships among tasks.
702 ThreadData::ParentChildSet parent_child_set_;
704 DISALLOW_COPY_AND_ASSIGN(DataCollector);
707 //------------------------------------------------------------------------------
708 // Provide simple way to to start global tracking, and to tear down tracking
709 // when done. The design has evolved to *not* do any teardown (and just leak
710 // all allocated data structures). As a result, we don't have any code in this
711 // destructor, and perhaps this whole class should go away.
713 class BASE_EXPORT AutoTracking {
714 public:
715 AutoTracking() {
716 ThreadData::Initialize();
719 ~AutoTracking() {
720 // TODO(jar): Consider emitting a CSV dump of the data at this point. This
721 // should be called after the message loops have all terminated (or at least
722 // the main message loop is gone), so there is little chance for additional
723 // tasks to be Run.
726 private:
728 DISALLOW_COPY_AND_ASSIGN(AutoTracking);
731 } // namespace tracked_objects
733 #endif // BASE_TRACKED_OBJECTS_H_