OLD | NEW |
---|---|
(Empty) | |
1 // Copyright 2016 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 // Activity tracking provides a low-overhead method of collecting information | |
6 // about the state of the application for analysis both while it is running | |
7 // and after it has terminated. Its primary purpose is to help locate reasons | |
8 // the browser becomes unresponsive by providing insight into what all the | |
9 // various threads and processes are (or were) doing. | |
10 | |
11 #ifndef BASE_METRICS_ACTIVITY_TRACKER_H_ | |
12 #define BASE_METRICS_ACTIVITY_TRACKER_H_ | |
13 | |
14 #include <atomic> | |
15 #include <memory> | |
16 | |
17 #include "base/base_export.h" | |
18 #include "base/location.h" | |
19 #include "base/metrics/persistent_memory_allocator.h" | |
20 #include "base/threading/thread_checker.h" | |
21 #include "base/threading/thread_local_storage.h" | |
22 | |
23 namespace base { | |
24 | |
25 struct PendingTask; | |
26 | |
27 class FilePath; | |
28 class Lock; | |
29 class MemoryMappedFile; | |
30 class PlatformThreadHandle; | |
31 class Process; | |
32 class WaitableEvent; | |
33 | |
34 namespace debug { | |
35 | |
36 #if !defined(OS_NACL) // NACL doesn't support any kind of file access in build. | |
37 // Enables the global activity tracker according to a field trial setting, | |
38 // using the specified |file| (without extension) for storing information | |
39 // from this run. | |
40 BASE_EXPORT void SetupGlobalActivityTrackerFieldTrial(const FilePath& file); | |
41 #endif // !defined(OS_NACL) | |
42 | |
43 | |
44 // This class manages tracking a stack of activities for a single thread in | |
45 // a persistent manner. In order to support an operational mode where another | |
Sigurður Ásgeirsson
2016/06/14 15:28:13
it implements a bounded-size stack in a fixed-size
bcwhite
2016/06/14 19:48:46
Done.
| |
46 // thread is analyzing this data in real-time, atomic operations are used | |
47 // where necessary to guarantee a consistent view from the outside. | |
48 // | |
49 // This class is not generally used directly but instead managed by the | |
50 // GlobalActivityTracker instance and updated using Scoped*Activity local | |
51 // objects. | |
52 class BASE_EXPORT ThreadActivityTracker { | |
53 public: | |
54 // The type of an activity on the stack. Activities are broken into | |
55 // categories with the category ID taking the top 4 bits and the lower | |
56 // bits representing an action within that category. This combination | |
57 // makes it easy to "switch" based on the type during analysis. | |
58 enum ActivityType : uint8_t { | |
59 // This "null" constant is used to indicate "do not change" in calls. | |
60 ACT_NULL = 0, | |
61 | |
62 // Task activities involve callbacks posted to a thread or thread-pool | |
63 // using the PostTask() method or any of its friends. | |
64 ACT_TASK = 1 << 4, | |
65 ACT_TASK_RUN = ACT_TASK, | |
66 | |
67 // Lock activities involve the acquisition of "mutex" locks. | |
68 ACT_LOCK = 2 << 4, | |
69 ACT_LOCK_ACQUIRE = ACT_LOCK, | |
70 ACT_LOCK_RELEASE, | |
71 | |
72 // Event activities involve operations on a WaitableEvent. | |
73 ACT_EVENT = 3 << 4, | |
74 ACT_EVENT_WAIT = ACT_EVENT, | |
75 ACT_EVENT_SIGNAL, | |
76 | |
77 // Thread activities involve the life management of threads. | |
78 ACT_THREAD = 4 << 4, | |
79 ACT_THREAD_START = ACT_THREAD, | |
80 ACT_THREAD_JOIN, | |
81 | |
82 // Process activities involve the life management of processes. | |
83 ACT_PROCESS = 5 << 4, | |
84 ACT_PROCESS_START = ACT_PROCESS, | |
85 ACT_PROCESS_WAIT, | |
86 | |
87 // Generic activities are user defined and can be anything. | |
88 ACT_GENERIC = 15 << 4, | |
89 | |
90 // These constants can be used to separate the category and action from | |
91 // a combined activity type. | |
92 ACT_CATEGORY_MASK = 0xF << 4, | |
93 ACT_ACTION_MASK = 0xF | |
94 }; | |
95 | |
96 // The data associated with an activity is dependent upon the activity type. | |
97 // This union defines all of the various fields. All fields must be explicitly | |
98 // sized types to ensure no interoperability problems between 32-bit and | |
99 // 64-bit systems. | |
100 union ActivityData { | |
101 // Generic activities don't have any defined structure. | |
102 struct { | |
103 uint32_t id; // An arbitrary identifier used for association. | |
104 uint32_t info; // An arbitrary value used for information purposes. | |
105 } generic; | |
106 struct { | |
107 uint64_t sequence_id; // The sequience identifier of the posted task. | |
108 } task; | |
109 struct { | |
110 uint64_t lock_address; // The memory address of the lock object. | |
111 } lock; | |
112 struct { | |
113 uint64_t event_address; // The memory address of the event object. | |
114 } event; | |
115 struct { | |
116 int64_t thread_id; // A unique identifier for a thread within a process. | |
117 } thread; | |
118 struct { | |
119 int64_t process_id; // A unique identifier for a process. | |
120 } process; | |
121 | |
122 // These methods create an ActivityData object from the appropriate | |
123 // parameters. Objects of this type should always be created this way to | |
124 // ensure that no fields remain unpopulated should the set of recorded | |
125 // fields change. They're defined inline where practical because they | |
126 // reduce to loading a small local structure with a few values, roughly | |
127 // the same as loading all those values into parameters. | |
128 | |
129 static ActivityData ForGeneric(uint32_t id, uint32_t info) { | |
130 ActivityData data; | |
131 data.generic.id = id; | |
132 data.generic.info = info; | |
133 return data; | |
134 } | |
135 | |
136 static ActivityData ForTask(uint64_t sequence) { | |
137 ActivityData data; | |
138 data.task.sequence_id = sequence; | |
139 return data; | |
140 } | |
141 | |
142 static ActivityData ForLock(const void* lock) { | |
143 ActivityData data; | |
144 data.lock.lock_address = reinterpret_cast<uintptr_t>(lock); | |
145 return data; | |
146 } | |
147 | |
148 static ActivityData ForEvent(const void* event) { | |
149 ActivityData data; | |
150 data.event.event_address = reinterpret_cast<uintptr_t>(event); | |
151 return data; | |
152 } | |
153 | |
154 static ActivityData ForThread(const PlatformThreadHandle& handle); | |
155 static ActivityData ForThread(const int64_t id) { | |
156 ActivityData data; | |
157 data.thread.thread_id = id; | |
158 return data; | |
159 } | |
160 | |
161 static ActivityData ForProcess(const int64_t id) { | |
162 ActivityData data; | |
163 data.process.process_id = id; | |
164 return data; | |
165 } | |
166 }; | |
167 | |
168 // This structure is the full contents recorded for every activity pushed | |
169 // onto the stack. The |activity_type| indicates what is actually stored in | |
170 // the |data| field. All fields must be explicitly sized types to ensure no | |
171 // interoperability problems between 32-bit and 64-bit systems. | |
172 struct Activity { | |
173 int64_t time_internal; | |
174 uint64_t source_address; | |
175 uint8_t activity_type; | |
176 ActivityData data; | |
177 }; | |
178 | |
179 // This structure holds a copy of all the internal data at the moment the | |
180 // "snapshot" operation is done. It is disconnected from the live tracker | |
181 // so that continued operation of the thread will not cause changes here. | |
182 struct BASE_EXPORT ActivitySnapshot { | |
183 // The name of the thread. | |
184 std::string thread_name; | |
185 | |
186 // The process and thread IDs. | |
187 int64_t process_id = 0; | |
188 int64_t thread_id = 0; | |
189 | |
190 // The current set of activities that are underway for this thread. It is | |
191 // limited in its maximum size with later entries being left off. | |
192 std::vector<Activity> activity_stack; | |
193 | |
194 // The current total depth of the activity stack, including those later | |
195 // entries not recorded in the |activity_stack| vector. | |
196 uint32_t activity_stack_depth = 0; | |
197 | |
198 // Explicit constructor/destructor are needed because of complex types | |
199 // with non-trivial default constructors and destructors. | |
200 ActivitySnapshot(); | |
201 ~ActivitySnapshot(); | |
202 }; | |
203 | |
204 // This is the base class for having the compiler manage an activity on the | |
205 // tracker's stack. It does nothing but call methods on the passed |tracker| | |
206 // if it is not null, making it safe (and cheap) to create these objects | |
207 // even if activity tracking is not enabled. | |
208 class BASE_EXPORT ScopedActivity { | |
209 public: | |
210 ScopedActivity(ThreadActivityTracker* tracker, | |
211 const void* source, | |
212 ActivityType type, | |
213 const ActivityData& data) | |
214 : tracker_(tracker), source_(source) { | |
215 if (tracker_) | |
216 tracker_->PushActivity(source, type, data); | |
217 } | |
218 | |
219 ~ScopedActivity() { | |
220 if (tracker_) | |
221 tracker_->PopActivity(source_); | |
222 } | |
223 | |
224 void ChangeTypeAndData(ActivityType type, const ActivityData& data) { | |
225 if (tracker_) | |
226 tracker_->ChangeActivity(source_, type, data); | |
227 } | |
228 | |
229 private: | |
230 // The thread tracker to which this object reports. It can be null if | |
231 // activity tracking is not (yet) enabled. | |
232 ThreadActivityTracker* const tracker_; | |
233 | |
234 // An identifier for the source at which this object was created. It is | |
235 // held and passed so the tracker can do run-time checks to ensure that | |
236 // somehow objects don't get popped in an order different than they | |
237 // were pushed. | |
238 const void* const source_; | |
239 }; | |
240 | |
241 // A ThreadActivityTracker runs on top of memory that is managed externally. | |
242 // It must be large enough for the internal header and a few Activity | |
243 // blocks. See SizeForStackDepth(). | |
244 ThreadActivityTracker(void* base, size_t size); | |
245 virtual ~ThreadActivityTracker(); | |
246 | |
247 // Indicates that an activity has started from a given |source| address in | |
248 // the code, though it can be null if the creator's address is not known. | |
249 // The |type| and |data| describe the activity. | |
250 void PushActivity(const void* source, | |
251 ActivityType type, | |
252 const ActivityData& data); | |
253 | |
254 // Changes the activity |type| and |data| of the top-most entry on the stack. | |
255 // This is useful if the information has changed and it is desireable to | |
256 // track that change without creating a new stack entry. If the type is | |
257 // ACT_NULL or the data is kNullActivityData then that value will remain | |
258 // unchanged. The type, if changed, must remain in the same category. | |
259 void ChangeActivity(const void* source, | |
260 ActivityType type, | |
261 const ActivityData& data); | |
262 | |
263 // Indicates that an activity started from |source| has completed. | |
264 void PopActivity(const void* source); | |
265 | |
266 // Returns whether the current data is valid or not. It is not valid if | |
267 // corruption has been detected in the header or other data structures. | |
268 bool IsValid() const; | |
269 | |
270 // Gets a copy of the tracker contents for analysis. Returns false if a | |
271 // snapshot was not possible, perhaps because the data is not valid; the | |
272 // contents of |output_snapshot| are undefined in that case. | |
273 bool Snapshot(ActivitySnapshot* output_snapshot) const; | |
Sigurður Ásgeirsson
2016/06/14 15:53:26
this is IMHO out of place in the public interface
bcwhite
2016/06/14 19:48:46
You can request a snapshot from the same instance
| |
274 | |
275 // Calculates the memory size required for a given stack depth, including | |
276 // the internal header structure for the stack. | |
277 static size_t SizeForStackDepth(int stack_depth); | |
278 | |
279 // A "null" activity-data that can be passed to indicate "do not change". | |
280 static const ActivityData kNullActivityData; | |
281 | |
282 private: | |
283 friend class ActivityTrackerTest; | |
284 | |
285 // This structure contains all the common information about the thread so | |
286 // it doesn't have to be repeated in every entry on the stack. It is defined | |
287 // and used completely within the .cc file. | |
288 struct Header; | |
289 | |
290 Header* const header_; // Pointer to the Header structure. | |
291 Activity* const stack_; // The stack of activities. | |
292 const uint32_t stack_slots_; // The total number of stack slots. | |
293 | |
294 bool valid_ = false; // Tracks whether the data is valid or not. | |
295 | |
296 base::ThreadChecker thread_checker_; | |
297 | |
298 DISALLOW_COPY_AND_ASSIGN(ThreadActivityTracker); | |
299 }; | |
300 | |
301 | |
302 // The global tracker manages all the individual thread trackers. Memory for | |
303 // the thread trackers is taken from a PersistentMemoryAllocator which allows | |
304 // for the data to be analyzed by a parallel process or even post-mortem. | |
305 class BASE_EXPORT GlobalActivityTracker { | |
306 public: | |
307 // Type identifiers used when storing in persistent memory so they can be | |
308 // identified during extraction; the first 4 bytes of the SHA1 of the name | |
309 // is used as a unique integer. A "version number" is added to the base | |
310 // so that, if the structure of that object changes, stored older versions | |
311 // will be safely ignored. These are public so that an external process | |
312 // can recognize records of this type within an allocator. | |
313 enum : uint32_t { | |
314 kTypeIdActivityTracker = 0x5D7381AF + 1, // SHA1(ActivityTracker) v1 | |
315 kTypeIdActivityTrackerFree = 0x3F0272FB, // SHA1(ActivityTrackerFree) | |
316 }; | |
317 | |
318 // This is a thin wrapper around the thread-tracker's ScopedActivity that | |
319 // accesses the global tracker to provide some of the information, notably | |
320 // which thread-tracker to use. It is safe to create even if activity | |
321 // tracking is not enabled. | |
322 class BASE_EXPORT ScopedThreadActivity | |
323 : public ThreadActivityTracker::ScopedActivity { | |
324 public: | |
325 ScopedThreadActivity(const void* source, | |
326 ThreadActivityTracker::ActivityType type, | |
327 const ThreadActivityTracker::ActivityData& data, | |
328 bool lock_allowed) | |
329 : ThreadActivityTracker::ScopedActivity( | |
330 GetOrCreateTracker(lock_allowed), | |
331 source, | |
332 type, | |
333 data) {} | |
334 | |
335 private: | |
336 // Gets (or creates) a tracker for the current thread. If locking is not | |
337 // allowed (because a lock is being tracked which would cause recursion) | |
338 // then the attempt to create one if none found will be skipped. Once | |
339 // the tracker for this thread has been created for other reasons, locks | |
340 // will be tracked. | |
341 static ThreadActivityTracker* GetOrCreateTracker(bool lock_allowed) { | |
342 GlobalActivityTracker* global_tracker = Get(); | |
343 if (!global_tracker) | |
344 return nullptr; | |
345 if (lock_allowed) | |
346 return global_tracker->GetOrCreateTrackerForCurrentThread(); | |
347 else | |
348 return global_tracker->GetTrackerForCurrentThread(); | |
349 } | |
350 }; | |
351 | |
352 ~GlobalActivityTracker(); | |
353 | |
354 // Creates a global tracker using a given persistent-memory |allocator| and | |
355 // providing the given |stack_depth| to each thread tracker it manages. The | |
356 // created object is activated so tracking will begin immediately upon return. | |
357 static void CreateWithAllocator( | |
358 std::unique_ptr<PersistentMemoryAllocator> allocator, | |
359 int stack_depth); | |
360 | |
361 #if !defined(OS_NACL) | |
362 // Like above but internally creates an allocator around a disk file with | |
363 // the specified |size| at the given |file_path|. Any existing file will be | |
364 // overwritten. The |id| and |name| are arbitrary and stored in the allocator | |
365 // for referece by whatever process reads it. | |
366 static void CreateWithFile(const FilePath& file_path, | |
367 size_t size, | |
368 uint64_t id, | |
369 StringPiece name, | |
370 int stack_depth); | |
371 #endif // !defined(OS_NACL) | |
372 | |
373 // Like above but internally creates an allocator using local heap memory of | |
374 // the specified size. This is used primarily for unit tests. | |
375 static void CreateWithLocalMemory(size_t size, | |
376 uint64_t id, | |
377 StringPiece name, | |
378 int stack_depth); | |
379 | |
380 // Gets the global activity-tracker or null if none exists. | |
381 static GlobalActivityTracker* Get() { return g_tracker_; } | |
382 | |
383 // Gets the persistent-memory-allocator in which data is stored. Callers | |
384 // can store additional records here to pass more information to the | |
385 // analysis process. | |
386 PersistentMemoryAllocator* allocator() { return allocator_.get(); } | |
387 | |
388 // Gets the thread's activity-tracker if it exists. This is inline for | |
389 // performance reasons and it uses thread-local-storage (TLS) so that there | |
390 // is no significant lookup time required to find the one for the calling | |
391 // thread. Ownership remains with the global tracker. | |
392 ThreadActivityTracker* GetTrackerForCurrentThread() { | |
393 return reinterpret_cast<ThreadActivityTracker*>(this_thread_tracker_.Get()); | |
394 } | |
395 | |
396 // Gets the thread's activity-tracker or creates one if none exists. This | |
397 // is inline for performance reasons. Ownership remains with the global | |
398 // tracker. | |
399 ThreadActivityTracker* GetOrCreateTrackerForCurrentThread() { | |
400 ThreadActivityTracker* tracker = GetTrackerForCurrentThread(); | |
401 if (!tracker) | |
402 tracker = CreateTrackerForCurrentThread(); | |
403 return tracker; | |
404 } | |
405 | |
406 // Creates an activity-tracker for the current thread. | |
407 ThreadActivityTracker* CreateTrackerForCurrentThread(); | |
408 | |
409 // Releases the activity-tracker for the current thread (for testing only). | |
410 void ReleaseTrackerForCurrentThreadForTesting(); | |
411 | |
412 private: | |
413 friend class ActivityTrackerTest; | |
414 | |
415 enum : int { | |
416 // The maximum number of threads that can be tracked within a process. | |
417 // If more than this number gets created, tracking of them may cease. | |
418 kMaxThreadCount = 100, | |
419 }; | |
420 | |
421 // A thin wrapper around the main thread-tracker that keeps additional | |
422 // information that the global tracker needs to handle joined threads. | |
423 class ManagedActivityTracker : public ThreadActivityTracker { | |
424 public: | |
425 ManagedActivityTracker(PersistentMemoryAllocator::Reference mem_reference, | |
426 void* base, | |
427 size_t size); | |
428 ~ManagedActivityTracker() override; | |
429 | |
430 // The reference into persistent memory from which this the tread-tracker's | |
431 // memory was created. | |
432 const PersistentMemoryAllocator::Reference mem_reference_; | |
433 | |
434 // The physical address used for the thread-tracker's memory. | |
435 void* const mem_base_; | |
436 }; | |
437 | |
438 // Creates a global tracker using a given persistent-memory |allocator| and | |
439 // providing the given |stack_depth| to each thread tracker it manages. The | |
440 // created object is activated so tracking will begin immediately upon return. | |
441 GlobalActivityTracker(std::unique_ptr<PersistentMemoryAllocator> allocator, | |
442 int stack_depth); | |
443 | |
444 // Returns the memory used by an activity-tracker managed by this class. | |
445 void ReturnTrackerMemory(ManagedActivityTracker* tracker); | |
446 | |
447 // Releases the activity-tracker associcated with thread. It is called | |
448 // automatically when a thread is joined and thus there is nothing more to | |
449 // be tracked. |value| is a pointer to a ManagedActivityTracker. | |
450 static void OnTLSDestroy(void* value); | |
451 | |
452 // The persistent-memory allocator from which the memory for all trackers | |
453 // is taken. | |
454 std::unique_ptr<PersistentMemoryAllocator> allocator_; | |
455 | |
456 // The size (in bytes) of memory required by a ThreadActivityTracker to | |
457 // provide stack-depth requsted during construction. | |
Sigurður Ásgeirsson
2016/06/14 15:28:13
nit: the ... requested
bcwhite
2016/06/14 19:48:46
Done.
| |
458 const size_t stack_memory_size_; | |
459 | |
460 // The activity tracker for the currently executing thread. | |
461 base::ThreadLocalStorage::Slot this_thread_tracker_; | |
462 | |
463 // These have to be lock-free because lock activity is tracked and causes | |
464 // re-entry problems. | |
465 std::atomic<int> thread_tracker_count_; | |
466 std::atomic<int> available_memories_count_; | |
467 std::atomic<PersistentMemoryAllocator::Reference> | |
468 available_memories_[kMaxThreadCount]; | |
469 | |
470 // The active global activity tracker. | |
471 static GlobalActivityTracker* g_tracker_; | |
472 }; | |
473 | |
474 | |
475 // Record entry in to and out of an arbitrary block of code. | |
476 class BASE_EXPORT ScopedActivity | |
477 : public GlobalActivityTracker::ScopedThreadActivity { | |
478 public: | |
479 // Track activity at the specified FROM_HERE location for an arbitrary | |
480 // 4-bit |action|, an arbitrary 32-bit |id|, and 32-bits of arbitrary | |
481 // |info|. None of these values affect operation; they're all purely | |
482 // for association and analysis. To have unique identifiers across a | |
483 // diverse code-base, create the number by taking the first 8 characters | |
484 // of the hash of the activity being tracked. | |
485 // | |
486 // For example: | |
487 // Tracking method: void MayNeverExit(uint32_t foo) {...} | |
488 // echo -n "MayNeverExit" | sha1sum => e44873ccab21e2b71270da24aa1... | |
489 // | |
490 // void MayNeverExit(uint32_t foo) { | |
491 // base::debug::ScopedActivity track_me(FROM_HERE, 0, 0xE44873CC, foo); | |
492 // ... | |
493 // } | |
494 ScopedActivity(const tracked_objects::Location& location, | |
495 uint8_t action, | |
496 uint32_t id, | |
497 uint32_t info); | |
498 | |
499 // Because this is inline, the FROM_HERE macro will resolve the current | |
500 // program-counter as the location in the calling code. | |
501 ScopedActivity() : ScopedActivity(FROM_HERE, 0, 0, 0) {} | |
502 | |
503 // Changes the |action| and/or |info| of this activity on the stack. This | |
504 // is useful for tracking progress through a function, updating the action | |
505 // to indicate "milestones" in the block (max 16 milestones: 0-15) or the | |
506 // info to reflect other changes. | |
507 void ChangeAction(uint8_t action); | |
508 void ChangeInfo(uint32_t info); | |
509 void ChangeActionAndInfo(uint8_t action, uint32_t info); | |
510 | |
511 private: | |
512 // A copy of the ID code so it doesn't have to be passed by the caller when | |
513 // changing the |info| field. | |
514 uint32_t id_; | |
515 }; | |
516 | |
517 | |
518 // These "scoped" classes provide easy tracking of various blocking actions. | |
519 | |
520 class BASE_EXPORT ScopedTaskRunActivity | |
521 : public GlobalActivityTracker::ScopedThreadActivity { | |
522 public: | |
523 ScopedTaskRunActivity(const base::PendingTask& task); | |
524 }; | |
525 | |
526 class BASE_EXPORT ScopedLockAcquireActivity | |
527 : public GlobalActivityTracker::ScopedThreadActivity { | |
528 public: | |
529 ScopedLockAcquireActivity(const base::internal::LockImpl* lock); | |
530 }; | |
531 | |
532 class BASE_EXPORT ScopedEventWaitActivity | |
533 : public GlobalActivityTracker::ScopedThreadActivity { | |
534 public: | |
535 ScopedEventWaitActivity(const base::WaitableEvent* event); | |
536 }; | |
537 | |
538 class BASE_EXPORT ScopedThreadJoinActivity | |
539 : public GlobalActivityTracker::ScopedThreadActivity { | |
540 public: | |
541 ScopedThreadJoinActivity(const base::PlatformThreadHandle* thread); | |
542 }; | |
543 | |
544 // Some systems don't have base::Process | |
545 #if !defined(OS_NACL) && !defined(OS_IOS) | |
546 class BASE_EXPORT ScopedProcessWaitActivity | |
547 : public GlobalActivityTracker::ScopedThreadActivity { | |
548 public: | |
549 ScopedProcessWaitActivity(const base::Process* process); | |
550 }; | |
551 #endif | |
552 | |
553 } // namespace debug | |
554 } // namespace base | |
555 | |
556 #endif // BASE_METRICS_ACTIVITY_TRACKER_H_ | |
OLD | NEW |