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

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

Powered by Google App Engine
This is Rietveld 408576698