1 // Copyright 2015 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.
5 #ifndef BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_H_
6 #define BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_H_
10 #include "base/atomicops.h"
11 #include "base/containers/hash_tables.h"
12 #include "base/memory/ref_counted.h"
13 #include "base/memory/singleton.h"
14 #include "base/synchronization/lock.h"
15 #include "base/timer/timer.h"
16 #include "base/trace_event/memory_dump_request_args.h"
17 #include "base/trace_event/process_memory_dump.h"
18 #include "base/trace_event/trace_event.h"
22 class SingleThreadTaskRunner
;
24 namespace trace_event
{
26 class MemoryDumpManagerDelegate
;
27 class MemoryDumpProvider
;
28 class MemoryDumpSessionState
;
30 // This is the interface exposed to the rest of the codebase to deal with
31 // memory tracing. The main entry point for clients is represented by
32 // RequestDumpPoint(). The extension by Un(RegisterDumpProvider).
33 class BASE_EXPORT MemoryDumpManager
: public TraceLog::EnabledStateObserver
{
35 static const char* const kTraceCategoryForTesting
;
37 // This value is returned as the tracing id of the child processes by
38 // GetTracingProcessId() when tracing is not enabled.
39 static const uint64 kInvalidTracingProcessId
;
41 static MemoryDumpManager
* GetInstance();
43 // Invoked once per process to register the TraceLog observer.
46 // See the lifetime and thread-safety requirements on the delegate below in
47 // the |MemoryDumpManagerDelegate| docstring.
48 void SetDelegate(MemoryDumpManagerDelegate
* delegate
);
50 // MemoryDumpManager does NOT take memory ownership of |mdp|, which is
51 // expected to either be a singleton or unregister itself.
52 // If the optional |task_runner| argument is non-null, all the calls to the
53 // |mdp| will be issues on the given thread. Otherwise, the |mdp| should be
54 // able to handle calls on arbitrary threads.
55 void RegisterDumpProvider(
56 MemoryDumpProvider
* mdp
,
57 const scoped_refptr
<SingleThreadTaskRunner
>& task_runner
);
58 void RegisterDumpProvider(MemoryDumpProvider
* mdp
);
59 void UnregisterDumpProvider(MemoryDumpProvider
* mdp
);
61 // Requests a memory dump. The dump might happen or not depending on the
62 // filters and categories specified when enabling tracing.
63 // The |dump_args| is used to specify the dump's level of detail.
64 // The optional |callback| is executed asynchronously, on an arbitrary thread,
65 // to notify about the completion of the global dump (i.e. after all the
66 // processes have dumped) and its success (true iff all the dumps were
68 void RequestGlobalDump(MemoryDumpType dump_type
,
69 const MemoryDumpArgs
& dump_args
,
70 const MemoryDumpCallback
& callback
);
72 // Same as above (still asynchronous), but without callback.
73 void RequestGlobalDump(MemoryDumpType dump_type
,
74 const MemoryDumpArgs
& dump_args
);
76 // TraceLog::EnabledStateObserver implementation.
77 void OnTraceLogEnabled() override
;
78 void OnTraceLogDisabled() override
;
80 // Returns the MemoryDumpSessionState object, which is shared by all the
81 // ProcessMemoryDump and MemoryAllocatorDump instances through all the tracing
83 const scoped_refptr
<MemoryDumpSessionState
>& session_state() const {
84 return session_state_
;
87 // Returns a unique id for identifying the processes. The id can be
88 // retrieved by child processes only when tracing is enabled. This is
89 // intended to express cross-process sharing of memory dumps on the
90 // child-process side, without having to know its own child process id.
91 uint64
GetTracingProcessId() const;
93 // Returns the name for a the allocated_objects dump. Use this to declare
94 // suballocator dumps from other dump providers.
95 // It should not return nullptr after the manager has been initialized.
96 const char* system_allocator_pool_name() const {
97 return system_allocator_pool_name_
;
101 friend struct DefaultDeleter
<MemoryDumpManager
>; // For the testing instance.
102 friend struct DefaultSingletonTraits
<MemoryDumpManager
>;
103 friend class MemoryDumpManagerDelegate
;
104 friend class MemoryDumpManagerTest
;
105 FRIEND_TEST_ALL_PREFIXES(MemoryDumpManagerTest
, DisableFailingDumpers
);
107 // Descriptor struct used to hold information about registered MDPs. It is
108 // deliberately copyable, in order to allow it to be used as std::set value.
109 struct MemoryDumpProviderInfo
{
110 MemoryDumpProviderInfo(
111 MemoryDumpProvider
* dump_provider
,
112 const scoped_refptr
<SingleThreadTaskRunner
>& task_runner
);
113 ~MemoryDumpProviderInfo();
115 // Define a total order based on the thread (i.e. |task_runner|) affinity,
116 // so that all MDP belonging to the same thread are adjacent in the set.
117 bool operator<(const MemoryDumpProviderInfo
& other
) const;
119 MemoryDumpProvider
* const dump_provider
;
120 scoped_refptr
<SingleThreadTaskRunner
> task_runner
; // Optional.
122 // For fail-safe logic (auto-disable failing MDPs). These fields are mutable
123 // as can be safely changed without impacting the order within the set.
124 mutable int consecutive_failures
;
125 mutable bool disabled
;
128 using MemoryDumpProviderInfoSet
= std::set
<MemoryDumpProviderInfo
>;
130 // Holds the state of a process memory dump that needs to be carried over
131 // across threads in order to fulfil an asynchronous CreateProcessDump()
132 // request. At any time exactly one thread owns a ProcessMemoryDumpAsyncState.
133 struct ProcessMemoryDumpAsyncState
{
134 ProcessMemoryDumpAsyncState(
135 MemoryDumpRequestArgs req_args
,
136 MemoryDumpProviderInfoSet::iterator next_dump_provider
,
137 const scoped_refptr
<MemoryDumpSessionState
>& session_state
,
138 MemoryDumpCallback callback
);
139 ~ProcessMemoryDumpAsyncState();
141 // The ProcessMemoryDump container, where each dump provider will dump its
142 // own MemoryAllocatorDump(s) upon the OnMemoryDump() call.
143 ProcessMemoryDump process_memory_dump
;
145 // The arguments passed to the initial CreateProcessDump() request.
146 const MemoryDumpRequestArgs req_args
;
148 // The |dump_providers_| iterator to the next dump provider that should be
149 // invoked (or dump_providers_.end() if at the end of the sequence).
150 MemoryDumpProviderInfoSet::iterator next_dump_provider
;
152 // Callback passed to the initial call to CreateProcessDump().
153 MemoryDumpCallback callback
;
155 // The thread on which FinalizeDumpAndAddToTrace() (and hence |callback|)
156 // should be invoked. This is the thread on which the initial
157 // CreateProcessDump() request was called.
158 const scoped_refptr
<SingleThreadTaskRunner
> task_runner
;
161 DISALLOW_COPY_AND_ASSIGN(ProcessMemoryDumpAsyncState
);
164 static const int kMaxConsecutiveFailuresCount
;
167 ~MemoryDumpManager() override
;
169 static void SetInstanceForTesting(MemoryDumpManager
* instance
);
170 static void FinalizeDumpAndAddToTrace(
171 scoped_ptr
<ProcessMemoryDumpAsyncState
> pmd_async_state
);
172 static void AbortDumpLocked(MemoryDumpCallback callback
,
173 scoped_refptr
<SingleThreadTaskRunner
> task_runner
,
176 // Internal, used only by MemoryDumpManagerDelegate.
177 // Creates a memory dump for the current process and appends it to the trace.
178 // |callback| will be invoked asynchronously upon completion on the same
179 // thread on which CreateProcessDump() was called.
180 void CreateProcessDump(const MemoryDumpRequestArgs
& args
,
181 const MemoryDumpCallback
& callback
);
183 // Continues the ProcessMemoryDump started by CreateProcessDump(), hopping
184 // across threads as needed as specified by MDPs in RegisterDumpProvider().
185 void ContinueAsyncProcessDump(
186 scoped_ptr
<ProcessMemoryDumpAsyncState
> pmd_async_state
);
188 // An ordererd set of registered MemoryDumpProviderInfo(s), sorted by thread
189 // affinity (MDPs belonging to the same thread are adjacent).
190 MemoryDumpProviderInfoSet dump_providers_
;
192 // Flag used to signal that some provider was removed from |dump_providers_|
193 // and therefore the current memory dump (if any) should be aborted.
194 bool did_unregister_dump_provider_
;
196 // Shared among all the PMDs to keep state scoped to the tracing session.
197 scoped_refptr
<MemoryDumpSessionState
> session_state_
;
199 MemoryDumpManagerDelegate
* delegate_
; // Not owned.
201 // Protects from concurrent accesses to the |dump_providers_*| and |delegate_|
202 // to guard against disabling logging while dumping on another thread.
205 // Optimization to avoid attempting any memory dump (i.e. to not walk an empty
206 // dump_providers_enabled_ list) when tracing is not enabled.
207 subtle::AtomicWord memory_tracing_enabled_
;
209 // For time-triggered periodic dumps.
210 RepeatingTimer
<MemoryDumpManager
> periodic_dump_timer_
;
212 // The unique id of the child process. This is created only for tracing and is
213 // expected to be valid only when tracing is enabled.
214 uint64 tracing_process_id_
;
216 // Name of the allocated_objects dump.
217 const char* system_allocator_pool_name_
;
219 // Skips the auto-registration of the core dumpers during Initialize().
220 bool skip_core_dumpers_auto_registration_for_testing_
;
222 DISALLOW_COPY_AND_ASSIGN(MemoryDumpManager
);
225 // The delegate is supposed to be long lived (read: a Singleton) and thread
226 // safe (i.e. should expect calls from any thread and handle thread hopping).
227 class BASE_EXPORT MemoryDumpManagerDelegate
{
229 virtual void RequestGlobalMemoryDump(const MemoryDumpRequestArgs
& args
,
230 const MemoryDumpCallback
& callback
) = 0;
232 // Determines whether the MemoryDumpManager instance should be the master
233 // (the ones which initiates and coordinates the multiprocess dumps) or not.
234 virtual bool IsCoordinatorProcess() const = 0;
236 // Returns tracing process id of the current process. This is used by
237 // MemoryDumpManager::GetTracingProcessId.
238 virtual uint64
GetTracingProcessId() const = 0;
241 MemoryDumpManagerDelegate() {}
242 virtual ~MemoryDumpManagerDelegate() {}
244 void CreateProcessDump(const MemoryDumpRequestArgs
& args
,
245 const MemoryDumpCallback
& callback
) {
246 MemoryDumpManager::GetInstance()->CreateProcessDump(args
, callback
);
250 DISALLOW_COPY_AND_ASSIGN(MemoryDumpManagerDelegate
);
253 } // namespace trace_event
256 #endif // BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_H_