Revert "Fix broken channel icon in chrome://help on CrOS" and try again
[chromium-blink-merge.git] / base / trace_event / memory_dump_manager.h
blob305ec5980767c0c9de9d70029b739340fdcc9cb0
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_
8 #include <set>
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"
20 namespace base {
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 {
34 public:
35 static const char* const kTraceCategory;
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.
44 void Initialize();
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
67 // successful).
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
82 // session lifetime.
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_;
100 // Tells the initialization phase to skip scheduling periodic memory dumps.
101 void DisablePeriodicDumpsForTesting() {
102 disable_periodic_dumps_for_testing_ = true;
105 private:
106 friend struct DefaultDeleter<MemoryDumpManager>; // For the testing instance.
107 friend struct DefaultSingletonTraits<MemoryDumpManager>;
108 friend class MemoryDumpManagerDelegate;
109 friend class MemoryDumpManagerTest;
110 FRIEND_TEST_ALL_PREFIXES(MemoryDumpManagerTest, DisableFailingDumpers);
111 FRIEND_TEST_ALL_PREFIXES(MemoryDumpManagerTest,
112 UnregisterDumperFromThreadWhileDumping);
114 // Descriptor struct used to hold information about registered MDPs. It is
115 // deliberately copyable, in order to allow it to be used as std::set value.
116 struct MemoryDumpProviderInfo {
117 MemoryDumpProviderInfo(
118 MemoryDumpProvider* dump_provider,
119 const scoped_refptr<SingleThreadTaskRunner>& task_runner);
120 ~MemoryDumpProviderInfo();
122 // Define a total order based on the thread (i.e. |task_runner|) affinity,
123 // so that all MDP belonging to the same thread are adjacent in the set.
124 bool operator<(const MemoryDumpProviderInfo& other) const;
126 MemoryDumpProvider* const dump_provider;
127 scoped_refptr<SingleThreadTaskRunner> task_runner; // Optional.
129 // For fail-safe logic (auto-disable failing MDPs). These fields are mutable
130 // as can be safely changed without impacting the order within the set.
131 mutable int consecutive_failures;
132 mutable bool disabled;
134 // When a dump provider unregisters, it is flagged as |unregistered| and it
135 // is removed only upon the next memory dump. This is to avoid altering the
136 // |dump_providers_| collection while a dump is in progress.
137 mutable bool unregistered;
140 using MemoryDumpProviderInfoSet = std::set<MemoryDumpProviderInfo>;
142 // Holds the state of a process memory dump that needs to be carried over
143 // across threads in order to fulfil an asynchronous CreateProcessDump()
144 // request. At any time exactly one thread owns a ProcessMemoryDumpAsyncState.
145 struct ProcessMemoryDumpAsyncState {
146 ProcessMemoryDumpAsyncState(
147 MemoryDumpRequestArgs req_args,
148 MemoryDumpProviderInfoSet::iterator next_dump_provider,
149 const scoped_refptr<MemoryDumpSessionState>& session_state,
150 MemoryDumpCallback callback);
151 ~ProcessMemoryDumpAsyncState();
153 // The ProcessMemoryDump container, where each dump provider will dump its
154 // own MemoryAllocatorDump(s) upon the OnMemoryDump() call.
155 ProcessMemoryDump process_memory_dump;
157 // The arguments passed to the initial CreateProcessDump() request.
158 const MemoryDumpRequestArgs req_args;
160 // The |dump_providers_| iterator to the next dump provider that should be
161 // invoked (or dump_providers_.end() if at the end of the sequence).
162 MemoryDumpProviderInfoSet::iterator next_dump_provider;
164 // Callback passed to the initial call to CreateProcessDump().
165 MemoryDumpCallback callback;
167 // The thread on which FinalizeDumpAndAddToTrace() (and hence |callback|)
168 // should be invoked. This is the thread on which the initial
169 // CreateProcessDump() request was called.
170 const scoped_refptr<SingleThreadTaskRunner> task_runner;
172 private:
173 DISALLOW_COPY_AND_ASSIGN(ProcessMemoryDumpAsyncState);
176 static const int kMaxConsecutiveFailuresCount;
178 MemoryDumpManager();
179 ~MemoryDumpManager() override;
181 static void SetInstanceForTesting(MemoryDumpManager* instance);
182 static void FinalizeDumpAndAddToTrace(
183 scoped_ptr<ProcessMemoryDumpAsyncState> pmd_async_state);
184 static void AbortDumpLocked(MemoryDumpCallback callback,
185 scoped_refptr<SingleThreadTaskRunner> task_runner,
186 uint64 dump_guid);
188 // Internal, used only by MemoryDumpManagerDelegate.
189 // Creates a memory dump for the current process and appends it to the trace.
190 // |callback| will be invoked asynchronously upon completion on the same
191 // thread on which CreateProcessDump() was called.
192 void CreateProcessDump(const MemoryDumpRequestArgs& args,
193 const MemoryDumpCallback& callback);
195 // Continues the ProcessMemoryDump started by CreateProcessDump(), hopping
196 // across threads as needed as specified by MDPs in RegisterDumpProvider().
197 void ContinueAsyncProcessDump(
198 scoped_ptr<ProcessMemoryDumpAsyncState> pmd_async_state);
200 // An ordererd set of registered MemoryDumpProviderInfo(s), sorted by thread
201 // affinity (MDPs belonging to the same thread are adjacent).
202 MemoryDumpProviderInfoSet dump_providers_;
204 // Shared among all the PMDs to keep state scoped to the tracing session.
205 scoped_refptr<MemoryDumpSessionState> session_state_;
207 MemoryDumpManagerDelegate* delegate_; // Not owned.
209 // Protects from concurrent accesses to the |dump_providers_*| and |delegate_|
210 // to guard against disabling logging while dumping on another thread.
211 Lock lock_;
213 // Optimization to avoid attempting any memory dump (i.e. to not walk an empty
214 // dump_providers_enabled_ list) when tracing is not enabled.
215 subtle::AtomicWord memory_tracing_enabled_;
217 // For time-triggered periodic dumps.
218 RepeatingTimer<MemoryDumpManager> periodic_dump_timer_;
220 // The unique id of the child process. This is created only for tracing and is
221 // expected to be valid only when tracing is enabled.
222 uint64 tracing_process_id_;
224 // Name of the allocated_objects dump.
225 const char* system_allocator_pool_name_;
227 // Skips the auto-registration of the core dumpers during Initialize().
228 bool skip_core_dumpers_auto_registration_for_testing_;
230 // When true, the initialization phase does not start the periodic memory
231 // dumps.
232 // TODO(primiano): This should go into TraceConfig. https://goo.gl/5Hj3o0.
233 bool disable_periodic_dumps_for_testing_;
235 DISALLOW_COPY_AND_ASSIGN(MemoryDumpManager);
238 // The delegate is supposed to be long lived (read: a Singleton) and thread
239 // safe (i.e. should expect calls from any thread and handle thread hopping).
240 class BASE_EXPORT MemoryDumpManagerDelegate {
241 public:
242 virtual void RequestGlobalMemoryDump(const MemoryDumpRequestArgs& args,
243 const MemoryDumpCallback& callback) = 0;
245 // Determines whether the MemoryDumpManager instance should be the master
246 // (the ones which initiates and coordinates the multiprocess dumps) or not.
247 virtual bool IsCoordinatorProcess() const = 0;
249 // Returns tracing process id of the current process. This is used by
250 // MemoryDumpManager::GetTracingProcessId.
251 virtual uint64 GetTracingProcessId() const = 0;
253 protected:
254 MemoryDumpManagerDelegate() {}
255 virtual ~MemoryDumpManagerDelegate() {}
257 void CreateProcessDump(const MemoryDumpRequestArgs& args,
258 const MemoryDumpCallback& callback) {
259 MemoryDumpManager::GetInstance()->CreateProcessDump(args, callback);
262 private:
263 DISALLOW_COPY_AND_ASSIGN(MemoryDumpManagerDelegate);
266 } // namespace trace_event
267 } // namespace base
269 #endif // BASE_TRACE_EVENT_MEMORY_DUMP_MANAGER_H_