blob: ac492254ff0995c2be2b1250d2350078037d1413 [file] [log] [blame]
[email protected]a502bbe72011-01-07 18:06:451// Copyright (c) 2011 The Chromium Authors. All rights reserved.
license.botbf09a502008-08-24 00:55:552// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
initial.commitd7cae122008-07-26 21:49:384
5#ifndef BASE_TRACKED_OBJECTS_H_
6#define BASE_TRACKED_OBJECTS_H_
[email protected]32b76ef2010-07-26 23:08:247#pragma once
initial.commitd7cae122008-07-26 21:49:388
initial.commitd7cae122008-07-26 21:49:389#include <map>
10#include <string>
11#include <vector>
12
[email protected]20305ec2011-01-21 04:55:5213#include "base/synchronization/lock.h"
initial.commitd7cae122008-07-26 21:49:3814#include "base/tracked.h"
[email protected]1357c322010-12-30 22:18:5615#include "base/threading/thread_local_storage.h"
initial.commitd7cae122008-07-26 21:49:3816
[email protected]75b79202009-12-30 07:31:4517// TrackedObjects provides a database of stats about objects (generally Tasks)
18// that are tracked. Tracking means their birth, death, duration, birth thread,
19// death thread, and birth place are recorded. This data is carefully spread
20// across a series of objects so that the counts and times can be rapidly
21// updated without (usually) having to lock the data, and hence there is usually
22// very little contention caused by the tracking. The data can be viewed via
[email protected]ea319e42010-11-08 21:47:2423// the about:tasks URL, with a variety of sorting and filtering choices.
[email protected]75b79202009-12-30 07:31:4524//
[email protected]ea319e42010-11-08 21:47:2425// These classes serve as the basis of a profiler of sorts for the Tasks system.
26// As a result, design decisions were made to maximize speed, by minimizing
27// recurring allocation/deallocation, lock contention and data copying. In the
28// "stable" state, which is reached relatively quickly, there is no separate
29// marginal allocation cost associated with construction or destruction of
30// tracked objects, no locks are generally employed, and probably the largest
31// computational cost is associated with obtaining start and stop times for
32// instances as they are created and destroyed. The introduction of worker
33// threads had a slight impact on this approach, and required use of some locks
34// when accessing data from the worker threads.
[email protected]75b79202009-12-30 07:31:4535//
36// The following describes the lifecycle of tracking an instance.
37//
38// First off, when the instance is created, the FROM_HERE macro is expanded
39// to specify the birth place (file, line, function) where the instance was
40// created. That data is used to create a transient Location instance
41// encapsulating the above triple of information. The strings (like __FILE__)
42// are passed around by reference, with the assumption that they are static, and
43// will never go away. This ensures that the strings can be dealt with as atoms
44// with great efficiency (i.e., copying of strings is never needed, and
45// comparisons for equality can be based on pointer comparisons).
46//
47// Next, a Births instance is created for use ONLY on the thread where this
48// instance was created. That Births instance records (in a base class
49// BirthOnThread) references to the static data provided in a Location instance,
50// as well as a pointer specifying the thread on which the birth takes place.
51// Hence there is at most one Births instance for each Location on each thread.
52// The derived Births class contains slots for recording statistics about all
53// instances born at the same location. Statistics currently include only the
54// count of instances constructed.
55// Since the base class BirthOnThread contains only constant data, it can be
56// freely accessed by any thread at any time (i.e., only the statistic needs to
57// be handled carefully, and it is ONLY read or written by the birth thread).
58//
59// Having now either constructed or found the Births instance described above, a
60// pointer to the Births instance is then embedded in a base class of the
61// instance we're tracking (usually a Task). This fact alone is very useful in
62// debugging, when there is a question of where an instance came from. In
63// addition, the birth time is also embedded in the base class Tracked (see
64// tracked.h), and used to later evaluate the lifetime duration.
65// As a result of the above embedding, we can (for any tracked instance) find
66// out its location of birth, and thread of birth, without using any locks, as
67// all that data is constant across the life of the process.
68//
69// The amount of memory used in the above data structures depends on how many
70// threads there are, and how many Locations of construction there are.
71// Fortunately, we don't use memory that is the product of those two counts, but
72// rather we only need one Births instance for each thread that constructs an
73// instance at a Location. In many cases, instances (such as Tasks) are only
74// created on one thread, so the memory utilization is actually fairly
75// restrained.
76//
77// Lastly, when an instance is deleted, the final tallies of statistics are
78// carefully accumulated. That tallying wrties into slots (members) in a
79// collection of DeathData instances. For each birth place Location that is
80// destroyed on a thread, there is a DeathData instance to record the additional
81// death count, as well as accumulate the lifetime duration of the instance as
82// it is destroyed (dies). By maintaining a single place to aggregate this
83// addition *only* for the given thread, we avoid the need to lock such
84// DeathData instances.
85//
86// With the above lifecycle description complete, the major remaining detail is
87// explaining how each thread maintains a list of DeathData instances, and of
88// Births instances, and is able to avoid additional (redundant/unnecessary)
89// allocations.
90//
91// Each thread maintains a list of data items specific to that thread in a
92// ThreadData instance (for that specific thread only). The two critical items
93// are lists of DeathData and Births instances. These lists are maintained in
94// STL maps, which are indexed by Location. As noted earlier, we can compare
95// locations very efficiently as we consider the underlying data (file,
96// function, line) to be atoms, and hence pointer comparison is used rather than
97// (slow) string comparisons.
98//
99// To provide a mechanism for iterating over all "known threads," which means
100// threads that have recorded a birth or a death, we create a singly linked list
101// of ThreadData instances. Each such instance maintains a pointer to the next
102// one. A static member of ThreadData provides a pointer to the first_ item on
103// this global list, and access to that first_ item requires the use of a lock_.
104// When new ThreadData instances is added to the global list, it is pre-pended,
105// which ensures that any prior acquisition of the list is valid (i.e., the
106// holder can iterate over it without fear of it changing, or the necessity of
107// using an additional lock. Iterations are actually pretty rare (used
108// primarilly for cleanup, or snapshotting data for display), so this lock has
109// very little global performance impact.
110//
111// The above description tries to define the high performance (run time)
112// portions of these classes. After gathering statistics, calls instigated
[email protected]ea319e42010-11-08 21:47:24113// by visiting about:tasks will assemble and aggregate data for display. The
[email protected]75b79202009-12-30 07:31:45114// following data structures are used for producing such displays. They are
115// not performance critical, and their only major constraint is that they should
116// be able to run concurrently with ongoing augmentation of the birth and death
117// data.
118//
119// For a given birth location, information about births are spread across data
120// structures that are asynchronously changing on various threads. For display
121// purposes, we need to construct Snapshot instances for each combination of
122// birth thread, death thread, and location, along with the count of such
123// lifetimes. We gather such data into a Snapshot instances, so that such
124// instances can be sorted and aggregated (and remain frozen during our
125// processing). Snapshot instances use pointers to constant portions of the
126// birth and death datastructures, but have local (frozen) copies of the actual
127// statistics (birth count, durations, etc. etc.).
128//
129// A DataCollector is a container object that holds a set of Snapshots. A
130// DataCollector can be passed from thread to thread, and each thread
131// contributes to it by adding or updating Snapshot instances. DataCollector
132// instances are thread safe containers which are passed to various threads to
133// accumulate all Snapshot instances.
134//
135// After an array of Snapshots instances are colleted into a DataCollector, they
136// need to be sorted, and possibly aggregated (example: how many threads are in
137// a specific consecutive set of Snapshots? What was the total birth count for
138// that set? etc.). Aggregation instances collect running sums of any set of
[email protected]ea319e42010-11-08 21:47:24139// snapshot instances, and are used to print sub-totals in an about:tasks page.
[email protected]75b79202009-12-30 07:31:45140//
141// TODO(jar): I need to store DataCollections, and provide facilities for taking
142// the difference between two gathered DataCollections. For now, I'm just
143// adding a hack that Reset()'s to zero all counts and stats. This is also
144// done in a slighly thread-unsafe fashion, as the reseting is done
145// asynchronously relative to ongoing updates, and worse yet, some data fields
146// are 64bit quantities, and are not atomicly accessed (reset or incremented
147// etc.). For basic profiling, this will work "most of the time," and should be
148// sufficient... but storing away DataCollections is the "right way" to do this.
149//
[email protected]f5393332009-06-03 15:01:29150class MessageLoop;
initial.commitd7cae122008-07-26 21:49:38151
[email protected]75b79202009-12-30 07:31:45152
initial.commitd7cae122008-07-26 21:49:38153namespace tracked_objects {
154
155//------------------------------------------------------------------------------
156// For a specific thread, and a specific birth place, the collection of all
157// death info (with tallies for each death thread, to prevent access conflicts).
158class ThreadData;
159class BirthOnThread {
160 public:
161 explicit BirthOnThread(const Location& location);
162
163 const Location location() const { return location_; }
164 const ThreadData* birth_thread() const { return birth_thread_; }
165
166 private:
167 // File/lineno of birth. This defines the essence of the type, as the context
168 // of the birth (construction) often tell what the item is for. This field
169 // is const, and hence safe to access from any thread.
170 const Location location_;
171
172 // The thread that records births into this object. Only this thread is
173 // allowed to access birth_count_ (which changes over time).
174 const ThreadData* birth_thread_; // The thread this birth took place on.
175
[email protected]022614ef92008-12-30 20:50:01176 DISALLOW_COPY_AND_ASSIGN(BirthOnThread);
initial.commitd7cae122008-07-26 21:49:38177};
178
179//------------------------------------------------------------------------------
180// A class for accumulating counts of births (without bothering with a map<>).
181
182class Births: public BirthOnThread {
183 public:
184 explicit Births(const Location& location);
185
186 int birth_count() const { return birth_count_; }
187
188 // When we have a birth we update the count for this BirhPLace.
189 void RecordBirth() { ++birth_count_; }
190
191 // When a birthplace is changed (updated), we need to decrement the counter
192 // for the old instance.
193 void ForgetBirth() { --birth_count_; } // We corrected a birth place.
194
[email protected]75b79202009-12-30 07:31:45195 // Hack to quickly reset all counts to zero.
196 void Clear() { birth_count_ = 0; }
197
initial.commitd7cae122008-07-26 21:49:38198 private:
199 // The number of births on this thread for our location_.
200 int birth_count_;
201
[email protected]022614ef92008-12-30 20:50:01202 DISALLOW_COPY_AND_ASSIGN(Births);
initial.commitd7cae122008-07-26 21:49:38203};
204
205//------------------------------------------------------------------------------
206// Basic info summarizing multiple destructions of an object with a single
207// birthplace (fixed Location). Used both on specific threads, and also used
208// in snapshots when integrating assembled data.
209
210class DeathData {
211 public:
212 // Default initializer.
213 DeathData() : count_(0), square_duration_(0) {}
214
215 // When deaths have not yet taken place, and we gather data from all the
216 // threads, we create DeathData stats that tally the number of births without
217 // a corrosponding death.
218 explicit DeathData(int count) : count_(count), square_duration_(0) {}
219
[email protected]e1acf6f2008-10-27 20:43:33220 void RecordDeath(const base::TimeDelta& duration);
initial.commitd7cae122008-07-26 21:49:38221
222 // Metrics accessors.
223 int count() const { return count_; }
[email protected]e1acf6f2008-10-27 20:43:33224 base::TimeDelta life_duration() const { return life_duration_; }
initial.commitd7cae122008-07-26 21:49:38225 int64 square_duration() const { return square_duration_; }
226 int AverageMsDuration() const;
227 double StandardDeviation() const;
228
229 // Accumulate metrics from other into this.
230 void AddDeathData(const DeathData& other);
231
232 // Simple print of internal state.
233 void Write(std::string* output) const;
234
[email protected]75b79202009-12-30 07:31:45235 // Reset all tallies to zero.
initial.commitd7cae122008-07-26 21:49:38236 void Clear();
237
238 private:
239 int count_; // Number of destructions.
[email protected]e1acf6f2008-10-27 20:43:33240 base::TimeDelta life_duration_; // Sum of all lifetime durations.
initial.commitd7cae122008-07-26 21:49:38241 int64 square_duration_; // Sum of squares in milliseconds.
242};
243
244//------------------------------------------------------------------------------
245// A temporary collection of data that can be sorted and summarized. It is
246// gathered (carefully) from many threads. Instances are held in arrays and
247// processed, filtered, and rendered.
248// The source of this data was collected on many threads, and is asynchronously
249// changing. The data in this instance is not asynchronously changing.
250
251class Snapshot {
252 public:
253 // When snapshotting a full life cycle set (birth-to-death), use this:
254 Snapshot(const BirthOnThread& birth_on_thread, const ThreadData& death_thread,
255 const DeathData& death_data);
256
257 // When snapshotting a birth, with no death yet, use this:
258 Snapshot(const BirthOnThread& birth_on_thread, int count);
259
260
261 const ThreadData* birth_thread() const { return birth_->birth_thread(); }
262 const Location location() const { return birth_->location(); }
263 const BirthOnThread& birth() const { return *birth_; }
264 const ThreadData* death_thread() const {return death_thread_; }
265 const DeathData& death_data() const { return death_data_; }
266 const std::string DeathThreadName() const;
267
268 int count() const { return death_data_.count(); }
[email protected]e1acf6f2008-10-27 20:43:33269 base::TimeDelta life_duration() const { return death_data_.life_duration(); }
initial.commitd7cae122008-07-26 21:49:38270 int64 square_duration() const { return death_data_.square_duration(); }
271 int AverageMsDuration() const { return death_data_.AverageMsDuration(); }
272
[email protected]f0d930a2008-08-13 19:38:25273 void Write(std::string* output) const;
initial.commitd7cae122008-07-26 21:49:38274
275 void Add(const Snapshot& other);
276
277 private:
278 const BirthOnThread* birth_; // Includes Location and birth_thread.
279 const ThreadData* death_thread_;
280 DeathData death_data_;
281};
282//------------------------------------------------------------------------------
283// DataCollector is a container class for Snapshot and BirthOnThread count
284// items. It protects the gathering under locks, so that it could be called via
[email protected]75b79202009-12-30 07:31:45285// Posttask on any threads, or passed to all the target threads in parallel.
initial.commitd7cae122008-07-26 21:49:38286
287class DataCollector {
288 public:
[email protected]764be58b2008-08-08 20:03:42289 typedef std::vector<Snapshot> Collection;
initial.commitd7cae122008-07-26 21:49:38290
291 // Construct with a list of how many threads should contribute. This helps us
292 // determine (in the async case) when we are done with all contributions.
293 DataCollector();
[email protected]d4799a32010-09-28 22:54:58294 ~DataCollector();
initial.commitd7cae122008-07-26 21:49:38295
296 // Add all stats from the indicated thread into our arrays. This function is
297 // mutex protected, and *could* be called from any threads (although current
298 // implementation serialized calls to Append).
299 void Append(const ThreadData& thread_data);
300
[email protected]75b79202009-12-30 07:31:45301 // After the accumulation phase, the following accessor is used to process the
302 // data.
initial.commitd7cae122008-07-26 21:49:38303 Collection* collection();
304
305 // After collection of death data is complete, we can add entries for all the
306 // remaining living objects.
307 void AddListOfLivingObjects();
308
309 private:
[email protected]a502bbe72011-01-07 18:06:45310 typedef std::map<const BirthOnThread*, int> BirthCount;
311
initial.commitd7cae122008-07-26 21:49:38312 // This instance may be provided to several threads to contribute data. The
313 // following counter tracks how many more threads will contribute. When it is
314 // zero, then all asynchronous contributions are complete, and locked access
315 // is no longer needed.
316 int count_of_contributing_threads_;
317
318 // The array that we collect data into.
319 Collection collection_;
320
321 // The total number of births recorded at each location for which we have not
322 // seen a death count.
initial.commitd7cae122008-07-26 21:49:38323 BirthCount global_birth_count_;
324
[email protected]20305ec2011-01-21 04:55:52325 base::Lock accumulation_lock_; // Protects access during accumulation phase.
initial.commitd7cae122008-07-26 21:49:38326
[email protected]022614ef92008-12-30 20:50:01327 DISALLOW_COPY_AND_ASSIGN(DataCollector);
initial.commitd7cae122008-07-26 21:49:38328};
329
330//------------------------------------------------------------------------------
331// Aggregation contains summaries (totals and subtotals) of groups of Snapshot
332// instances to provide printing of these collections on a single line.
333
334class Aggregation: public DeathData {
335 public:
[email protected]d4799a32010-09-28 22:54:58336 Aggregation();
337 ~Aggregation();
initial.commitd7cae122008-07-26 21:49:38338
339 void AddDeathSnapshot(const Snapshot& snapshot);
340 void AddBirths(const Births& births);
341 void AddBirth(const BirthOnThread& birth);
342 void AddBirthPlace(const Location& location);
343 void Write(std::string* output) const;
344 void Clear();
345
346 private:
347 int birth_count_;
348 std::map<std::string, int> birth_files_;
349 std::map<Location, int> locations_;
350 std::map<const ThreadData*, int> birth_threads_;
351 DeathData death_data_;
352 std::map<const ThreadData*, int> death_threads_;
353
[email protected]022614ef92008-12-30 20:50:01354 DISALLOW_COPY_AND_ASSIGN(Aggregation);
initial.commitd7cae122008-07-26 21:49:38355};
356
357//------------------------------------------------------------------------------
[email protected]75b79202009-12-30 07:31:45358// Comparator is a class that supports the comparison of Snapshot instances.
359// An instance is actually a list of chained Comparitors, that can provide for
360// arbitrary ordering. The path portion of an about:objects URL is translated
361// into such a chain, which is then used to order Snapshot instances in a
362// vector. It orders them into groups (for aggregation), and can also order
363// instances within the groups (for detailed rendering of the instances in an
364// aggregation).
initial.commitd7cae122008-07-26 21:49:38365
366class Comparator {
367 public:
[email protected]75b79202009-12-30 07:31:45368 // Selector enum is the token identifier for each parsed keyword, most of
369 // which specify a sort order.
370 // Since it is not meaningful to sort more than once on a specific key, we
371 // use bitfields to accumulate what we have sorted on so far.
initial.commitd7cae122008-07-26 21:49:38372 enum Selector {
[email protected]75b79202009-12-30 07:31:45373 // Sort orders.
initial.commitd7cae122008-07-26 21:49:38374 NIL = 0,
375 BIRTH_THREAD = 1,
376 DEATH_THREAD = 2,
377 BIRTH_FILE = 4,
378 BIRTH_FUNCTION = 8,
379 BIRTH_LINE = 16,
380 COUNT = 32,
381 AVERAGE_DURATION = 64,
382 TOTAL_DURATION = 128,
[email protected]75b79202009-12-30 07:31:45383
384 // Imediate action keywords.
385 RESET_ALL_DATA = -1,
initial.commitd7cae122008-07-26 21:49:38386 };
387
388 explicit Comparator();
389
[email protected]75b79202009-12-30 07:31:45390 // Reset the comparator to a NIL selector. Clear() and recursively delete any
initial.commitd7cae122008-07-26 21:49:38391 // tiebreaker_ entries. NOTE: We can't use a standard destructor, because
392 // the sort algorithm makes copies of this object, and then deletes them,
393 // which would cause problems (either we'd make expensive deep copies, or we'd
394 // do more thna one delete on a tiebreaker_.
395 void Clear();
396
397 // The less() operator for sorting the array via std::sort().
398 bool operator()(const Snapshot& left, const Snapshot& right) const;
399
400 void Sort(DataCollector::Collection* collection) const;
401
402 // Check to see if the items are sort equivalents (should be aggregated).
403 bool Equivalent(const Snapshot& left, const Snapshot& right) const;
404
405 // Check to see if all required fields are present in the given sample.
406 bool Acceptable(const Snapshot& sample) const;
407
408 // A comparator can be refined by specifying what to do if the selected basis
409 // for comparison is insufficient to establish an ordering. This call adds
410 // the indicated attribute as the new "least significant" basis of comparison.
[email protected]2bce0352009-07-06 20:11:00411 void SetTiebreaker(Selector selector, const std::string& required);
initial.commitd7cae122008-07-26 21:49:38412
413 // Indicate if this instance is set up to sort by the given Selector, thereby
414 // putting that information in the SortGrouping, so it is not needed in each
415 // printed line.
416 bool IsGroupedBy(Selector selector) const;
417
418 // Using the tiebreakers as set above, we mostly get an ordering, which
419 // equivalent groups. If those groups are displayed (rather than just being
420 // aggregated, then the following is used to order them (within the group).
421 void SetSubgroupTiebreaker(Selector selector);
422
423 // Translate a keyword and restriction in URL path to a selector for sorting.
[email protected]2bce0352009-07-06 20:11:00424 void ParseKeyphrase(const std::string& key_phrase);
initial.commitd7cae122008-07-26 21:49:38425
426 // Parse a query in an about:objects URL to decide on sort ordering.
[email protected]2bce0352009-07-06 20:11:00427 bool ParseQuery(const std::string& query);
initial.commitd7cae122008-07-26 21:49:38428
429 // Output a header line that can be used to indicated what items will be
430 // collected in the group. It lists all (potentially) tested attributes and
431 // their values (in the sample item).
432 bool WriteSortGrouping(const Snapshot& sample, std::string* output) const;
433
434 // Output a sample, with SortGroup details not displayed.
435 void WriteSnapshot(const Snapshot& sample, std::string* output) const;
436
437 private:
438 // The selector directs this instance to compare based on the specified
439 // members of the tested elements.
440 enum Selector selector_;
441
442 // For filtering into acceptable and unacceptable snapshot instance, the
443 // following is required to be a substring of the selector_ field.
444 std::string required_;
445
446 // If this instance can't decide on an ordering, we can consult a tie-breaker
447 // which may have a different basis of comparison.
448 Comparator* tiebreaker_;
449
450 // We or together all the selectors we sort on (not counting sub-group
451 // selectors), so that we can tell if we've decided to group on any given
452 // criteria.
453 int combined_selectors_;
454
455 // Some tiebreakrs are for subgroup ordering, and not for basic ordering (in
456 // preparation for aggregation). The subgroup tiebreakers are not consulted
457 // when deciding if two items are in equivalent groups. This flag tells us
458 // to ignore the tiebreaker when doing Equivalent() testing.
459 bool use_tiebreaker_for_sort_only_;
460};
461
462
463//------------------------------------------------------------------------------
464// For each thread, we have a ThreadData that stores all tracking info generated
465// on this thread. This prevents the need for locking as data accumulates.
466
467class ThreadData {
468 public:
469 typedef std::map<Location, Births*> BirthMap;
470 typedef std::map<const Births*, DeathData> DeathMap;
471
472 ThreadData();
[email protected]d4799a32010-09-28 22:54:58473 ~ThreadData();
initial.commitd7cae122008-07-26 21:49:38474
475 // Using Thread Local Store, find the current instance for collecting data.
476 // If an instance does not exist, construct one (and remember it for use on
477 // this thread.
478 // If shutdown has already started, and we don't yet have an instance, then
479 // return null.
480 static ThreadData* current();
481
482 // For a given about:objects URL, develop resulting HTML, and append to
483 // output.
484 static void WriteHTML(const std::string& query, std::string* output);
485
486 // For a given accumulated array of results, use the comparator to sort and
487 // subtotal, writing the results to the output.
488 static void WriteHTMLTotalAndSubtotals(
489 const DataCollector::Collection& match_array,
490 const Comparator& comparator, std::string* output);
491
[email protected]75b79202009-12-30 07:31:45492 // In this thread's data, record a new birth.
493 Births* TallyABirth(const Location& location);
initial.commitd7cae122008-07-26 21:49:38494
495 // Find a place to record a death on this thread.
[email protected]e1acf6f2008-10-27 20:43:33496 void TallyADeath(const Births& lifetimes, const base::TimeDelta& duration);
initial.commitd7cae122008-07-26 21:49:38497
498 // (Thread safe) Get start of list of instances.
499 static ThreadData* first();
500 // Iterate through the null terminated list of instances.
501 ThreadData* next() const { return next_; }
502
503 MessageLoop* message_loop() const { return message_loop_; }
504 const std::string ThreadName() const;
505
506 // Using our lock, make a copy of the specified maps. These calls may arrive
[email protected]75b79202009-12-30 07:31:45507 // from non-local threads, and are used to quickly scan data from all threads
508 // in order to build an HTML page for about:objects.
initial.commitd7cae122008-07-26 21:49:38509 void SnapshotBirthMap(BirthMap *output) const;
510 void SnapshotDeathMap(DeathMap *output) const;
511
[email protected]75b79202009-12-30 07:31:45512 // Hack: asynchronously clear all birth counts and death tallies data values
513 // in all ThreadData instances. The numerical (zeroing) part is done without
514 // use of a locks or atomics exchanges, and may (for int64 values) produce
515 // bogus counts VERY rarely.
516 static void ResetAllThreadData();
517
518 // Using our lock to protect the iteration, Clear all birth and death data.
519 void Reset();
520
521 // Using the "known list of threads" gathered during births and deaths, the
522 // following attempts to run the given function once all all such threads.
523 // Note that the function can only be run on threads which have a message
524 // loop!
initial.commitd7cae122008-07-26 21:49:38525 static void RunOnAllThreads(void (*Func)());
526
527 // Set internal status_ to either become ACTIVE, or later, to be SHUTDOWN,
528 // based on argument being true or false respectively.
529 // IF tracking is not compiled in, this function will return false.
530 static bool StartTracking(bool status);
531 static bool IsActive();
532
[email protected]764be58b2008-08-08 20:03:42533#ifdef OS_WIN
initial.commitd7cae122008-07-26 21:49:38534 // WARNING: ONLY call this function when all MessageLoops are still intact for
535 // all registered threads. IF you call it later, you will crash.
536 // Note: You don't need to call it at all, and you can wait till you are
537 // single threaded (again) to do the cleanup via
538 // ShutdownSingleThreadedCleanup().
539 // Start the teardown (shutdown) process in a multi-thread mode by disabling
540 // further additions to thread database on all threads. First it makes a
541 // local (locked) change to prevent any more threads from registering. Then
542 // it Posts a Task to all registered threads to be sure they are aware that no
543 // more accumulation can take place.
544 static void ShutdownMultiThreadTracking();
[email protected]764be58b2008-08-08 20:03:42545#endif
initial.commitd7cae122008-07-26 21:49:38546
547 // WARNING: ONLY call this function when you are running single threaded
548 // (again) and all message loops and threads have terminated. Until that
549 // point some threads may still attempt to write into our data structures.
550 // Delete recursively all data structures, starting with the list of
551 // ThreadData instances.
552 static void ShutdownSingleThreadedCleanup();
553
554 private:
555 // Current allowable states of the tracking system. The states always
556 // proceed towards SHUTDOWN, and never go backwards.
557 enum Status {
558 UNINITIALIZED,
559 ACTIVE,
560 SHUTDOWN,
561 };
562
[email protected]e7af5962010-08-05 22:36:04563#if defined(OS_WIN)
564 class ThreadSafeDownCounter;
565 class RunTheStatic;
[email protected]764be58b2008-08-08 20:03:42566#endif
initial.commitd7cae122008-07-26 21:49:38567
568 // Each registered thread is called to set status_ to SHUTDOWN.
569 // This is done redundantly on every registered thread because it is not
570 // protected by a mutex. Running on all threads guarantees we get the
571 // notification into the memory cache of all possible threads.
572 static void ShutdownDisablingFurtherTracking();
573
574 // We use thread local store to identify which ThreadData to interact with.
[email protected]1357c322010-12-30 22:18:56575 static base::ThreadLocalStorage::Slot tls_index_;
initial.commitd7cae122008-07-26 21:49:38576
577 // Link to the most recently created instance (starts a null terminated list).
578 static ThreadData* first_;
579 // Protection for access to first_.
[email protected]20305ec2011-01-21 04:55:52580 static base::Lock list_lock_;
initial.commitd7cae122008-07-26 21:49:38581
initial.commitd7cae122008-07-26 21:49:38582 // We set status_ to SHUTDOWN when we shut down the tracking service. This
[email protected]75b79202009-12-30 07:31:45583 // setting is redundantly established by all participating threads so that we
584 // are *guaranteed* (without locking) that all threads can "see" the status
585 // and avoid additional calls into the service.
initial.commitd7cae122008-07-26 21:49:38586 static Status status_;
587
588 // Link to next instance (null terminated list). Used to globally track all
589 // registered instances (corresponds to all registered threads where we keep
590 // data).
591 ThreadData* next_;
592
593 // The message loop where tasks needing to access this instance's private data
594 // should be directed. Since some threads have no message loop, some
595 // instances have data that can't be (safely) modified externally.
596 MessageLoop* message_loop_;
597
598 // A map used on each thread to keep track of Births on this thread.
599 // This map should only be accessed on the thread it was constructed on.
600 // When a snapshot is needed, this structure can be locked in place for the
601 // duration of the snapshotting activity.
602 BirthMap birth_map_;
603
604 // Similar to birth_map_, this records informations about death of tracked
605 // instances (i.e., when a tracked instance was destroyed on this thread).
[email protected]75b79202009-12-30 07:31:45606 // It is locked before changing, and hence other threads may access it by
607 // locking before reading it.
initial.commitd7cae122008-07-26 21:49:38608 DeathMap death_map_;
609
[email protected]75b79202009-12-30 07:31:45610 // Lock to protect *some* access to BirthMap and DeathMap. The maps are
611 // regularly read and written on this thread, but may only be read from other
612 // threads. To support this, we acquire this lock if we are writing from this
613 // thread, or reading from another thread. For reading from this thread we
614 // don't need a lock, as there is no potential for a conflict since the
615 // writing is only done from this thread.
[email protected]20305ec2011-01-21 04:55:52616 mutable base::Lock lock_;
initial.commitd7cae122008-07-26 21:49:38617
[email protected]022614ef92008-12-30 20:50:01618 DISALLOW_COPY_AND_ASSIGN(ThreadData);
initial.commitd7cae122008-07-26 21:49:38619};
620
[email protected]022614ef92008-12-30 20:50:01621
622//------------------------------------------------------------------------------
623// Provide simple way to to start global tracking, and to tear down tracking
624// when done. Note that construction and destruction of this object must be
[email protected]862aa2f02009-12-31 07:26:16625// done when running in threaded mode (before spawning a lot of threads
[email protected]022614ef92008-12-30 20:50:01626// for construction, and after shutting down all the threads for destruction).
627
[email protected]862aa2f02009-12-31 07:26:16628// To prevent grabbing thread local store resources time and again if someone
629// chooses to try to re-run the browser many times, we maintain global state and
630// only allow the tracking system to be started up at most once, and shutdown
631// at most once. See bug 31344 for an example.
632
[email protected]022614ef92008-12-30 20:50:01633class AutoTracking {
634 public:
[email protected]862aa2f02009-12-31 07:26:16635 AutoTracking() {
636 if (state_ != kNeverBeenRun)
637 return;
638 ThreadData::StartTracking(true);
639 state_ = kRunning;
640 }
[email protected]022614ef92008-12-30 20:50:01641
642 ~AutoTracking() {
[email protected]862aa2f02009-12-31 07:26:16643#ifndef NDEBUG
644 if (state_ != kRunning)
645 return;
[email protected]237511822011-03-01 21:56:30646 // We don't do cleanup of any sort in Release build because it is a
647 // complete waste of time. Since Chromium doesn't join all its thread and
648 // guarantee we're in a single threaded mode, we don't even do cleanup in
649 // debug mode, as it will generate race-checker warnings.
[email protected]022614ef92008-12-30 20:50:01650#endif
651 }
652
653 private:
[email protected]862aa2f02009-12-31 07:26:16654 enum State {
655 kNeverBeenRun,
656 kRunning,
657 kTornDownAndStopped,
658 };
659 static State state_;
660
[email protected]022614ef92008-12-30 20:50:01661 DISALLOW_COPY_AND_ASSIGN(AutoTracking);
662};
663
664
initial.commitd7cae122008-07-26 21:49:38665} // namespace tracked_objects
666
667#endif // BASE_TRACKED_OBJECTS_H_