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

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

Powered by Google App Engine
This is Rietveld 408576698