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 #include "base/trace_event/memory_dump_manager.h"
9 #include "base/atomic_sequence_num.h"
10 #include "base/command_line.h"
11 #include "base/compiler_specific.h"
12 #include "base/thread_task_runner_handle.h"
13 #include "base/trace_event/memory_dump_provider.h"
14 #include "base/trace_event/memory_dump_session_state.h"
15 #include "base/trace_event/process_memory_dump.h"
16 #include "base/trace_event/trace_event_argument.h"
17 #include "build/build_config.h"
20 #include "base/trace_event/process_memory_totals_dump_provider.h"
23 #if defined(OS_LINUX) || defined(OS_ANDROID)
24 #include "base/trace_event/malloc_dump_provider.h"
25 #include "base/trace_event/process_memory_maps_dump_provider.h"
28 #if defined(OS_ANDROID)
29 #include "base/trace_event/java_heap_dump_provider_android.h"
33 #include "base/trace_event/winheap_dump_provider_win.h"
37 namespace trace_event
{
41 // Throttle mmaps at a rate of once every kHeavyMmapsDumpsRate standard dumps.
42 const int kHeavyDumpsRate
= 8; // 250 ms * 8 = 2000 ms.
43 const int kDumpIntervalMs
= 250;
44 const int kTraceEventNumArgs
= 1;
45 const char* kTraceEventArgNames
[] = {"dumps"};
46 const unsigned char kTraceEventArgTypes
[] = {TRACE_VALUE_TYPE_CONVERTABLE
};
48 StaticAtomicSequenceNumber g_next_guid
;
49 uint32 g_periodic_dumps_count
= 0;
50 MemoryDumpManager
* g_instance_for_testing
= nullptr;
52 void RequestPeriodicGlobalDump() {
53 MemoryDumpArgs::LevelOfDetail dump_level_of_detail
=
54 g_periodic_dumps_count
== 0 ? MemoryDumpArgs::LevelOfDetail::HIGH
55 : MemoryDumpArgs::LevelOfDetail::LOW
;
56 if (++g_periodic_dumps_count
== kHeavyDumpsRate
)
57 g_periodic_dumps_count
= 0;
59 MemoryDumpArgs dump_args
= {dump_level_of_detail
};
60 MemoryDumpManager::GetInstance()->RequestGlobalDump(
61 MemoryDumpType::PERIODIC_INTERVAL
, dump_args
);
67 const char* const MemoryDumpManager::kTraceCategory
=
68 TRACE_DISABLED_BY_DEFAULT("memory-infra");
71 const int MemoryDumpManager::kMaxConsecutiveFailuresCount
= 3;
74 const uint64
MemoryDumpManager::kInvalidTracingProcessId
= 0;
77 MemoryDumpManager
* MemoryDumpManager::GetInstance() {
78 if (g_instance_for_testing
)
79 return g_instance_for_testing
;
81 return Singleton
<MemoryDumpManager
,
82 LeakySingletonTraits
<MemoryDumpManager
>>::get();
86 void MemoryDumpManager::SetInstanceForTesting(MemoryDumpManager
* instance
) {
88 instance
->skip_core_dumpers_auto_registration_for_testing_
= true;
89 g_instance_for_testing
= instance
;
92 MemoryDumpManager::MemoryDumpManager()
94 memory_tracing_enabled_(0),
95 tracing_process_id_(kInvalidTracingProcessId
),
96 system_allocator_pool_name_(nullptr),
97 skip_core_dumpers_auto_registration_for_testing_(false),
98 disable_periodic_dumps_for_testing_(false) {
99 g_next_guid
.GetNext(); // Make sure that first guid is not zero.
102 MemoryDumpManager::~MemoryDumpManager() {
103 base::trace_event::TraceLog::GetInstance()->RemoveEnabledStateObserver(this);
106 void MemoryDumpManager::Initialize() {
107 TRACE_EVENT0(kTraceCategory
, "init"); // Add to trace-viewer category list.
108 trace_event::TraceLog::GetInstance()->AddEnabledStateObserver(this);
110 if (skip_core_dumpers_auto_registration_for_testing_
)
113 // Enable the core dump providers.
114 #if !defined(OS_NACL)
115 RegisterDumpProvider(ProcessMemoryTotalsDumpProvider::GetInstance());
118 #if defined(OS_LINUX) || defined(OS_ANDROID)
119 RegisterDumpProvider(ProcessMemoryMapsDumpProvider::GetInstance());
120 RegisterDumpProvider(MallocDumpProvider::GetInstance());
121 system_allocator_pool_name_
= MallocDumpProvider::kAllocatedObjects
;
124 #if defined(OS_ANDROID)
125 RegisterDumpProvider(JavaHeapDumpProvider::GetInstance());
129 RegisterDumpProvider(WinHeapDumpProvider::GetInstance());
130 system_allocator_pool_name_
= WinHeapDumpProvider::kAllocatedObjects
;
134 void MemoryDumpManager::SetDelegate(MemoryDumpManagerDelegate
* delegate
) {
135 AutoLock
lock(lock_
);
136 DCHECK_EQ(static_cast<MemoryDumpManagerDelegate
*>(nullptr), delegate_
);
137 delegate_
= delegate
;
140 void MemoryDumpManager::RegisterDumpProvider(
141 MemoryDumpProvider
* mdp
,
142 const scoped_refptr
<SingleThreadTaskRunner
>& task_runner
) {
143 MemoryDumpProviderInfo
mdp_info(mdp
, task_runner
);
144 AutoLock
lock(lock_
);
145 auto iter_new
= dump_providers_
.insert(mdp_info
);
147 // If there was a previous entry, replace it with the new one. This is to deal
148 // with the case where a dump provider unregisters itself and then re-
149 // registers before a memory dump happens, so its entry was still in the
150 // collection but flagged |unregistered|.
151 if (!iter_new
.second
) {
152 dump_providers_
.erase(iter_new
.first
);
153 dump_providers_
.insert(mdp_info
);
157 void MemoryDumpManager::RegisterDumpProvider(MemoryDumpProvider
* mdp
) {
158 RegisterDumpProvider(mdp
, nullptr);
161 void MemoryDumpManager::UnregisterDumpProvider(MemoryDumpProvider
* mdp
) {
162 AutoLock
lock(lock_
);
164 auto mdp_iter
= dump_providers_
.begin();
165 for (; mdp_iter
!= dump_providers_
.end(); ++mdp_iter
) {
166 if (mdp_iter
->dump_provider
== mdp
)
170 if (mdp_iter
== dump_providers_
.end())
173 // Unregistration of a MemoryDumpProvider while tracing is ongoing is safe
174 // only if the MDP has specified a thread affinity (via task_runner()) AND
175 // the unregistration happens on the same thread (so the MDP cannot unregister
176 // and OnMemoryDump() at the same time).
177 // Otherwise, it is not possible to guarantee that its unregistration is
178 // race-free. If you hit this DCHECK, your MDP has a bug.
180 subtle::NoBarrier_Load(&memory_tracing_enabled_
),
181 mdp_iter
->task_runner
&& mdp_iter
->task_runner
->BelongsToCurrentThread())
182 << "The MemoryDumpProvider attempted to unregister itself in a racy way. "
183 << "Please file a crbug.";
185 mdp_iter
->unregistered
= true;
188 void MemoryDumpManager::RequestGlobalDump(MemoryDumpType dump_type
,
189 const MemoryDumpArgs
& dump_args
,
190 const MemoryDumpCallback
& callback
) {
191 // Bail out immediately if tracing is not enabled at all.
192 if (!UNLIKELY(subtle::NoBarrier_Load(&memory_tracing_enabled_
))) {
193 if (!callback
.is_null())
194 callback
.Run(0u /* guid */, false /* success */);
199 TraceLog::GetInstance()->MangleEventId(g_next_guid
.GetNext());
201 // The delegate_ is supposed to be thread safe, immutable and long lived.
202 // No need to keep the lock after we ensure that a delegate has been set.
203 MemoryDumpManagerDelegate
* delegate
;
205 AutoLock
lock(lock_
);
206 delegate
= delegate_
;
210 // The delegate is in charge to coordinate the request among all the
211 // processes and call the CreateLocalDumpPoint on the local process.
212 MemoryDumpRequestArgs args
= {guid
, dump_type
, dump_args
};
213 delegate
->RequestGlobalMemoryDump(args
, callback
);
214 } else if (!callback
.is_null()) {
215 callback
.Run(guid
, false /* success */);
219 void MemoryDumpManager::RequestGlobalDump(MemoryDumpType dump_type
,
220 const MemoryDumpArgs
& dump_args
) {
221 RequestGlobalDump(dump_type
, dump_args
, MemoryDumpCallback());
224 void MemoryDumpManager::CreateProcessDump(const MemoryDumpRequestArgs
& args
,
225 const MemoryDumpCallback
& callback
) {
226 scoped_ptr
<ProcessMemoryDumpAsyncState
> pmd_async_state
;
228 AutoLock
lock(lock_
);
229 pmd_async_state
.reset(new ProcessMemoryDumpAsyncState(
230 args
, dump_providers_
.begin(), session_state_
, callback
));
233 // Start the thread hop. |dump_providers_| are kept sorted by thread, so
234 // ContinueAsyncProcessDump will hop at most once per thread (w.r.t. thread
235 // affinity specified by the MemoryDumpProvider(s) in RegisterDumpProvider()).
236 ContinueAsyncProcessDump(pmd_async_state
.Pass());
239 // At most one ContinueAsyncProcessDump() can be active at any time for a given
240 // PMD, regardless of status of the |lock_|. |lock_| is used here purely to
241 // ensure consistency w.r.t. (un)registrations of |dump_providers_|.
242 // The linearization of dump providers' OnMemoryDump invocations is achieved by
243 // means of subsequent PostTask(s).
246 // - Check if the dump provider is disabled, if so skip the dump.
247 // - Check if we are on the right thread. If not hop and continue there.
248 // 2) Invoke the dump provider's OnMemoryDump() (unless skipped).
250 // - Unregister the dump provider if it failed too many times consecutively.
251 // - Advance the |next_dump_provider| iterator to the next dump provider.
252 // - If this was the last hop, create a trace event, add it to the trace
253 // and finalize (invoke callback).
255 void MemoryDumpManager::ContinueAsyncProcessDump(
256 scoped_ptr
<ProcessMemoryDumpAsyncState
> pmd_async_state
) {
257 // Initalizes the ThreadLocalEventBuffer to guarantee that the TRACE_EVENTs
258 // in the PostTask below don't end up registering their own dump providers
259 // (for discounting trace memory overhead) while holding the |lock_|.
260 TraceLog::GetInstance()->InitializeThreadLocalEventBufferIfSupported();
262 // DO NOT put any LOG() statement in the locked sections, as in some contexts
263 // (GPU process) LOG() ends up performing PostTask/IPCs.
264 MemoryDumpProvider
* mdp
;
265 bool skip_dump
= false;
267 AutoLock
lock(lock_
);
269 auto mdp_info
= pmd_async_state
->next_dump_provider
;
270 mdp
= mdp_info
->dump_provider
;
271 if (mdp_info
->disabled
|| mdp_info
->unregistered
) {
273 } else if (mdp_info
->task_runner
&&
274 !mdp_info
->task_runner
->BelongsToCurrentThread()) {
275 // It's time to hop onto another thread.
277 // Copy the callback + arguments just for the unlikley case in which
278 // PostTask fails. In such case the Bind helper will destroy the
279 // pmd_async_state and we must keep a copy of the fields to notify the
281 MemoryDumpCallback callback
= pmd_async_state
->callback
;
282 scoped_refptr
<SingleThreadTaskRunner
> callback_task_runner
=
283 pmd_async_state
->task_runner
;
284 const uint64 dump_guid
= pmd_async_state
->req_args
.dump_guid
;
286 const bool did_post_task
= mdp_info
->task_runner
->PostTask(
287 FROM_HERE
, Bind(&MemoryDumpManager::ContinueAsyncProcessDump
,
288 Unretained(this), Passed(pmd_async_state
.Pass())));
292 // The thread is gone. At this point the best thing we can do is to
293 // disable the dump provider and abort this dump.
294 mdp_info
->disabled
= true;
295 return AbortDumpLocked(callback
, callback_task_runner
, dump_guid
);
299 // Invoke the dump provider without holding the |lock_|.
300 bool finalize
= false;
301 bool dump_successful
= false;
304 dump_successful
= mdp
->OnMemoryDump(pmd_async_state
->req_args
.dump_args
,
305 &pmd_async_state
->process_memory_dump
);
309 AutoLock
lock(lock_
);
310 auto mdp_info
= pmd_async_state
->next_dump_provider
;
311 if (dump_successful
) {
312 mdp_info
->consecutive_failures
= 0;
313 } else if (!skip_dump
) {
314 ++mdp_info
->consecutive_failures
;
315 if (mdp_info
->consecutive_failures
>= kMaxConsecutiveFailuresCount
) {
316 mdp_info
->disabled
= true;
319 ++pmd_async_state
->next_dump_provider
;
320 finalize
= pmd_async_state
->next_dump_provider
== dump_providers_
.end();
322 if (mdp_info
->unregistered
)
323 dump_providers_
.erase(mdp_info
);
326 if (!skip_dump
&& !dump_successful
) {
327 LOG(ERROR
) << "A memory dumper failed, possibly due to sandboxing "
328 "(crbug.com/461788). Disabling dumper for current process. "
329 "Try restarting chrome with the --no-sandbox switch.";
333 return FinalizeDumpAndAddToTrace(pmd_async_state
.Pass());
335 ContinueAsyncProcessDump(pmd_async_state
.Pass());
339 void MemoryDumpManager::FinalizeDumpAndAddToTrace(
340 scoped_ptr
<ProcessMemoryDumpAsyncState
> pmd_async_state
) {
341 if (!pmd_async_state
->task_runner
->BelongsToCurrentThread()) {
342 scoped_refptr
<SingleThreadTaskRunner
> task_runner
=
343 pmd_async_state
->task_runner
;
344 task_runner
->PostTask(FROM_HERE
,
345 Bind(&MemoryDumpManager::FinalizeDumpAndAddToTrace
,
346 Passed(pmd_async_state
.Pass())));
350 scoped_refptr
<ConvertableToTraceFormat
> event_value(new TracedValue());
351 pmd_async_state
->process_memory_dump
.AsValueInto(
352 static_cast<TracedValue
*>(event_value
.get()));
353 const char* const event_name
=
354 MemoryDumpTypeToString(pmd_async_state
->req_args
.dump_type
);
356 TRACE_EVENT_API_ADD_TRACE_EVENT(
357 TRACE_EVENT_PHASE_MEMORY_DUMP
,
358 TraceLog::GetCategoryGroupEnabled(kTraceCategory
), event_name
,
359 pmd_async_state
->req_args
.dump_guid
, kTraceEventNumArgs
,
360 kTraceEventArgNames
, kTraceEventArgTypes
, nullptr /* arg_values */,
361 &event_value
, TRACE_EVENT_FLAG_HAS_ID
);
363 if (!pmd_async_state
->callback
.is_null()) {
364 pmd_async_state
->callback
.Run(pmd_async_state
->req_args
.dump_guid
,
366 pmd_async_state
->callback
.Reset();
371 void MemoryDumpManager::AbortDumpLocked(
372 MemoryDumpCallback callback
,
373 scoped_refptr
<SingleThreadTaskRunner
> task_runner
,
375 if (callback
.is_null())
376 return; // There is nothing to NACK.
378 // Post the callback even if we are already on the right thread to avoid
379 // invoking the callback while holding the lock_.
380 task_runner
->PostTask(FROM_HERE
,
381 Bind(callback
, dump_guid
, false /* success */));
384 void MemoryDumpManager::OnTraceLogEnabled() {
385 // TODO(primiano): at this point we query TraceLog::GetCurrentCategoryFilter
386 // to figure out (and cache) which dumpers should be enabled or not.
387 // For the moment piggy back everything on the generic "memory" category.
389 TRACE_EVENT_CATEGORY_GROUP_ENABLED(kTraceCategory
, &enabled
);
391 // Initialize the TraceLog for the current thread. This is to avoid that the
392 // TraceLog memory dump provider is registered lazily in the PostTask() below
393 // while the |lock_| is taken;
394 TraceLog::GetInstance()->InitializeThreadLocalEventBufferIfSupported();
396 AutoLock
lock(lock_
);
398 // There is no point starting the tracing without a delegate.
399 if (!enabled
|| !delegate_
) {
400 // Disable all the providers.
401 for (auto it
= dump_providers_
.begin(); it
!= dump_providers_
.end(); ++it
)
406 session_state_
= new MemoryDumpSessionState();
407 for (auto it
= dump_providers_
.begin(); it
!= dump_providers_
.end(); ++it
) {
408 it
->disabled
= false;
409 it
->consecutive_failures
= 0;
412 subtle::NoBarrier_Store(&memory_tracing_enabled_
, 1);
414 // TODO(primiano): This is a temporary hack to disable periodic memory dumps
415 // when running memory benchmarks until they can be enabled/disabled in
416 // base::trace_event::TraceConfig. See https://goo.gl/5Hj3o0.
417 // The same mechanism should be used to disable periodic dumps in tests.
418 if (delegate_
->IsCoordinatorProcess() &&
419 !CommandLine::ForCurrentProcess()->HasSwitch(
420 "enable-memory-benchmarking") &&
421 !disable_periodic_dumps_for_testing_
) {
422 g_periodic_dumps_count
= 0;
423 periodic_dump_timer_
.Start(FROM_HERE
,
424 TimeDelta::FromMilliseconds(kDumpIntervalMs
),
425 base::Bind(&RequestPeriodicGlobalDump
));
429 void MemoryDumpManager::OnTraceLogDisabled() {
430 AutoLock
lock(lock_
);
431 periodic_dump_timer_
.Stop();
432 subtle::NoBarrier_Store(&memory_tracing_enabled_
, 0);
433 session_state_
= nullptr;
436 uint64
MemoryDumpManager::GetTracingProcessId() const {
437 return delegate_
->GetTracingProcessId();
440 MemoryDumpManager::MemoryDumpProviderInfo::MemoryDumpProviderInfo(
441 MemoryDumpProvider
* dump_provider
,
442 const scoped_refptr
<SingleThreadTaskRunner
>& task_runner
)
443 : dump_provider(dump_provider
),
444 task_runner(task_runner
),
445 consecutive_failures(0),
447 unregistered(false) {}
449 MemoryDumpManager::MemoryDumpProviderInfo::~MemoryDumpProviderInfo() {
452 bool MemoryDumpManager::MemoryDumpProviderInfo::operator<(
453 const MemoryDumpProviderInfo
& other
) const {
454 if (task_runner
== other
.task_runner
)
455 return dump_provider
< other
.dump_provider
;
456 return task_runner
< other
.task_runner
;
459 MemoryDumpManager::ProcessMemoryDumpAsyncState::ProcessMemoryDumpAsyncState(
460 MemoryDumpRequestArgs req_args
,
461 MemoryDumpProviderInfoSet::iterator next_dump_provider
,
462 const scoped_refptr
<MemoryDumpSessionState
>& session_state
,
463 MemoryDumpCallback callback
)
464 : process_memory_dump(session_state
),
466 next_dump_provider(next_dump_provider
),
468 task_runner(MessageLoop::current()->task_runner()) {
471 MemoryDumpManager::ProcessMemoryDumpAsyncState::~ProcessMemoryDumpAsyncState() {
474 } // namespace trace_event