Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(46)

Side by Side Diff: base/debug/activity_tracker.h

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

Powered by Google App Engine
This is Rietveld 408576698