SupervisedUser SafeSites: Switch to the new SafeSearch API
[chromium-blink-merge.git] / base / trace_event / memory_dump_manager.cc
blobbafd121af1e461cc246c3664d6b269079c9b752d
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"
7 #include <algorithm>
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"
19 #if !defined(OS_NACL)
20 #include "base/trace_event/process_memory_totals_dump_provider.h"
21 #endif
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"
26 #endif
28 #if defined(OS_ANDROID)
29 #include "base/trace_event/java_heap_dump_provider_android.h"
30 #endif
32 #if defined(OS_WIN)
33 #include "base/trace_event/winheap_dump_provider_win.h"
34 #endif
36 namespace base {
37 namespace trace_event {
39 namespace {
41 // TODO(primiano): this should be smarter and should do something similar to
42 // trace event synthetic delays.
43 const char kTraceCategory[] = TRACE_DISABLED_BY_DEFAULT("memory-infra");
45 // Throttle mmaps at a rate of once every kHeavyMmapsDumpsRate standard dumps.
46 const int kHeavyDumpsRate = 8; // 250 ms * 8 = 2000 ms.
47 const int kDumpIntervalMs = 250;
48 const int kTraceEventNumArgs = 1;
49 const char* kTraceEventArgNames[] = {"dumps"};
50 const unsigned char kTraceEventArgTypes[] = {TRACE_VALUE_TYPE_CONVERTABLE};
52 StaticAtomicSequenceNumber g_next_guid;
53 uint32 g_periodic_dumps_count = 0;
54 MemoryDumpManager* g_instance_for_testing = nullptr;
56 void RequestPeriodicGlobalDump() {
57 MemoryDumpArgs::LevelOfDetail dump_level_of_detail =
58 g_periodic_dumps_count == 0 ? MemoryDumpArgs::LevelOfDetail::HIGH
59 : MemoryDumpArgs::LevelOfDetail::LOW;
60 if (++g_periodic_dumps_count == kHeavyDumpsRate)
61 g_periodic_dumps_count = 0;
63 MemoryDumpArgs dump_args = {dump_level_of_detail};
64 MemoryDumpManager::GetInstance()->RequestGlobalDump(
65 MemoryDumpType::PERIODIC_INTERVAL, dump_args);
68 } // namespace
70 // static
71 const char* const MemoryDumpManager::kTraceCategoryForTesting = kTraceCategory;
73 // static
74 const int MemoryDumpManager::kMaxConsecutiveFailuresCount = 3;
76 // static
77 const uint64 MemoryDumpManager::kInvalidTracingProcessId = 0;
79 // static
80 MemoryDumpManager* MemoryDumpManager::GetInstance() {
81 if (g_instance_for_testing)
82 return g_instance_for_testing;
84 return Singleton<MemoryDumpManager,
85 LeakySingletonTraits<MemoryDumpManager>>::get();
88 // static
89 void MemoryDumpManager::SetInstanceForTesting(MemoryDumpManager* instance) {
90 if (instance)
91 instance->skip_core_dumpers_auto_registration_for_testing_ = true;
92 g_instance_for_testing = instance;
95 MemoryDumpManager::MemoryDumpManager()
96 : did_unregister_dump_provider_(false),
97 delegate_(nullptr),
98 memory_tracing_enabled_(0),
99 tracing_process_id_(kInvalidTracingProcessId),
100 system_allocator_pool_name_(nullptr),
101 skip_core_dumpers_auto_registration_for_testing_(false) {
102 g_next_guid.GetNext(); // Make sure that first guid is not zero.
105 MemoryDumpManager::~MemoryDumpManager() {
106 base::trace_event::TraceLog::GetInstance()->RemoveEnabledStateObserver(this);
109 void MemoryDumpManager::Initialize() {
110 TRACE_EVENT0(kTraceCategory, "init"); // Add to trace-viewer category list.
111 trace_event::TraceLog::GetInstance()->AddEnabledStateObserver(this);
113 if (skip_core_dumpers_auto_registration_for_testing_)
114 return;
116 // Enable the core dump providers.
117 #if !defined(OS_NACL)
118 RegisterDumpProvider(ProcessMemoryTotalsDumpProvider::GetInstance());
119 #endif
121 #if defined(OS_LINUX) || defined(OS_ANDROID)
122 // The memory maps dump provider is currently disabled for security reasons
123 // and will be enabled once tracing is more secure (crbug.com/517906).
124 // It is still enabled for running benchmarks.
125 if (CommandLine::ForCurrentProcess()->HasSwitch(
126 "enable-memory-benchmarking")) {
127 RegisterDumpProvider(ProcessMemoryMapsDumpProvider::GetInstance());
130 RegisterDumpProvider(MallocDumpProvider::GetInstance());
131 system_allocator_pool_name_ = MallocDumpProvider::kAllocatedObjects;
132 #endif
134 #if defined(OS_ANDROID)
135 RegisterDumpProvider(JavaHeapDumpProvider::GetInstance());
136 #endif
138 #if defined(OS_WIN)
139 RegisterDumpProvider(WinHeapDumpProvider::GetInstance());
140 system_allocator_pool_name_ = WinHeapDumpProvider::kAllocatedObjects;
141 #endif
144 void MemoryDumpManager::SetDelegate(MemoryDumpManagerDelegate* delegate) {
145 AutoLock lock(lock_);
146 DCHECK_EQ(static_cast<MemoryDumpManagerDelegate*>(nullptr), delegate_);
147 delegate_ = delegate;
150 void MemoryDumpManager::RegisterDumpProvider(
151 MemoryDumpProvider* mdp,
152 const scoped_refptr<SingleThreadTaskRunner>& task_runner) {
153 MemoryDumpProviderInfo mdp_info(mdp, task_runner);
154 AutoLock lock(lock_);
155 dump_providers_.insert(mdp_info);
158 void MemoryDumpManager::RegisterDumpProvider(MemoryDumpProvider* mdp) {
159 RegisterDumpProvider(mdp, nullptr);
162 void MemoryDumpManager::UnregisterDumpProvider(MemoryDumpProvider* mdp) {
163 AutoLock lock(lock_);
165 auto mdp_iter = dump_providers_.begin();
166 for (; mdp_iter != dump_providers_.end(); ++mdp_iter) {
167 if (mdp_iter->dump_provider == mdp)
168 break;
171 if (mdp_iter == dump_providers_.end())
172 return;
174 // Unregistration of a MemoryDumpProvider while tracing is ongoing is safe
175 // only if the MDP has specified a thread affinity (via task_runner()) AND
176 // the unregistration happens on the same thread (so the MDP cannot unregister
177 // and OnMemoryDump() at the same time).
178 // Otherwise, it is not possible to guarantee that its unregistration is
179 // race-free. If you hit this DCHECK, your MDP has a bug.
180 DCHECK_IMPLIES(
181 subtle::NoBarrier_Load(&memory_tracing_enabled_),
182 mdp_iter->task_runner && mdp_iter->task_runner->BelongsToCurrentThread())
183 << "The MemoryDumpProvider attempted to unregister itself in a racy way. "
184 << "Please file a crbug.";
186 dump_providers_.erase(mdp_iter);
187 did_unregister_dump_provider_ = true;
190 void MemoryDumpManager::RequestGlobalDump(MemoryDumpType dump_type,
191 const MemoryDumpArgs& dump_args,
192 const MemoryDumpCallback& callback) {
193 // Bail out immediately if tracing is not enabled at all.
194 if (!UNLIKELY(subtle::NoBarrier_Load(&memory_tracing_enabled_))) {
195 if (!callback.is_null())
196 callback.Run(0u /* guid */, false /* success */);
197 return;
200 const uint64 guid =
201 TraceLog::GetInstance()->MangleEventId(g_next_guid.GetNext());
203 // The delegate_ is supposed to be thread safe, immutable and long lived.
204 // No need to keep the lock after we ensure that a delegate has been set.
205 MemoryDumpManagerDelegate* delegate;
207 AutoLock lock(lock_);
208 delegate = delegate_;
211 if (delegate) {
212 // The delegate is in charge to coordinate the request among all the
213 // processes and call the CreateLocalDumpPoint on the local process.
214 MemoryDumpRequestArgs args = {guid, dump_type, dump_args};
215 delegate->RequestGlobalMemoryDump(args, callback);
216 } else if (!callback.is_null()) {
217 callback.Run(guid, false /* success */);
221 void MemoryDumpManager::RequestGlobalDump(MemoryDumpType dump_type,
222 const MemoryDumpArgs& dump_args) {
223 RequestGlobalDump(dump_type, dump_args, MemoryDumpCallback());
226 void MemoryDumpManager::CreateProcessDump(const MemoryDumpRequestArgs& args,
227 const MemoryDumpCallback& callback) {
228 scoped_ptr<ProcessMemoryDumpAsyncState> pmd_async_state;
230 AutoLock lock(lock_);
231 did_unregister_dump_provider_ = false;
232 pmd_async_state.reset(new ProcessMemoryDumpAsyncState(
233 args, dump_providers_.begin(), session_state_, callback));
236 // Start the thread hop. |dump_providers_| are kept sorted by thread, so
237 // ContinueAsyncProcessDump will hop at most once per thread (w.r.t. thread
238 // affinity specified by the MemoryDumpProvider(s) in RegisterDumpProvider()).
239 ContinueAsyncProcessDump(pmd_async_state.Pass());
242 // At most one ContinueAsyncProcessDump() can be active at any time for a given
243 // PMD, regardless of status of the |lock_|. |lock_| is used here purely to
244 // ensure consistency w.r.t. (un)registrations of |dump_providers_|.
245 // The linearization of dump providers' OnMemoryDump invocations is achieved by
246 // means of subsequent PostTask(s).
248 // 1) Prologue:
249 // - Check if the dump provider is disabled, if so skip the dump.
250 // - Check if we are on the right thread. If not hop and continue there.
251 // 2) Invoke the dump provider's OnMemoryDump() (unless skipped).
252 // 3) Epilogue:
253 // - Unregister the dump provider if it failed too many times consecutively.
254 // - Advance the |next_dump_provider| iterator to the next dump provider.
255 // - If this was the last hop, create a trace event, add it to the trace
256 // and finalize (invoke callback).
258 void MemoryDumpManager::ContinueAsyncProcessDump(
259 scoped_ptr<ProcessMemoryDumpAsyncState> pmd_async_state) {
260 // Initalizes the ThreadLocalEventBuffer to guarantee that the TRACE_EVENTs
261 // in the PostTask below don't end up registering their own dump providers
262 // (for discounting trace memory overhead) while holding the |lock_|.
263 TraceLog::GetInstance()->InitializeThreadLocalEventBufferIfSupported();
265 // DO NOT put any LOG() statement in the locked sections, as in some contexts
266 // (GPU process) LOG() ends up performing PostTask/IPCs.
267 MemoryDumpProvider* mdp;
268 bool skip_dump = false;
270 AutoLock lock(lock_);
271 // In the unlikely event that a dump provider was unregistered while
272 // dumping, abort the dump, as that would make |next_dump_provider| invalid.
273 // Registration, on the other hand, is safe as per std::set<> contract.
274 if (did_unregister_dump_provider_) {
275 return AbortDumpLocked(pmd_async_state->callback,
276 pmd_async_state->task_runner,
277 pmd_async_state->req_args.dump_guid);
280 auto* mdp_info = &*pmd_async_state->next_dump_provider;
281 mdp = mdp_info->dump_provider;
282 if (mdp_info->disabled) {
283 skip_dump = true;
284 } else if (mdp_info->task_runner &&
285 !mdp_info->task_runner->BelongsToCurrentThread()) {
286 // It's time to hop onto another thread.
288 // Copy the callback + arguments just for the unlikley case in which
289 // PostTask fails. In such case the Bind helper will destroy the
290 // pmd_async_state and we must keep a copy of the fields to notify the
291 // abort.
292 MemoryDumpCallback callback = pmd_async_state->callback;
293 scoped_refptr<SingleThreadTaskRunner> callback_task_runner =
294 pmd_async_state->task_runner;
295 const uint64 dump_guid = pmd_async_state->req_args.dump_guid;
297 const bool did_post_task = mdp_info->task_runner->PostTask(
298 FROM_HERE, Bind(&MemoryDumpManager::ContinueAsyncProcessDump,
299 Unretained(this), Passed(pmd_async_state.Pass())));
300 if (did_post_task)
301 return;
303 // The thread is gone. At this point the best thing we can do is to
304 // disable the dump provider and abort this dump.
305 mdp_info->disabled = true;
306 return AbortDumpLocked(callback, callback_task_runner, dump_guid);
308 } // AutoLock(lock_)
310 // Invoke the dump provider without holding the |lock_|.
311 bool finalize = false;
312 bool dump_successful = false;
314 if (!skip_dump) {
315 dump_successful = mdp->OnMemoryDump(pmd_async_state->req_args.dump_args,
316 &pmd_async_state->process_memory_dump);
320 AutoLock lock(lock_);
321 if (did_unregister_dump_provider_) {
322 return AbortDumpLocked(pmd_async_state->callback,
323 pmd_async_state->task_runner,
324 pmd_async_state->req_args.dump_guid);
326 auto* mdp_info = &*pmd_async_state->next_dump_provider;
327 if (dump_successful) {
328 mdp_info->consecutive_failures = 0;
329 } else if (!skip_dump) {
330 ++mdp_info->consecutive_failures;
331 if (mdp_info->consecutive_failures >= kMaxConsecutiveFailuresCount) {
332 mdp_info->disabled = true;
335 ++pmd_async_state->next_dump_provider;
336 finalize = pmd_async_state->next_dump_provider == dump_providers_.end();
339 if (!skip_dump && !dump_successful) {
340 LOG(ERROR) << "A memory dumper failed, possibly due to sandboxing "
341 "(crbug.com/461788). Disabling dumper for current process. "
342 "Try restarting chrome with the --no-sandbox switch.";
345 if (finalize)
346 return FinalizeDumpAndAddToTrace(pmd_async_state.Pass());
348 ContinueAsyncProcessDump(pmd_async_state.Pass());
351 // static
352 void MemoryDumpManager::FinalizeDumpAndAddToTrace(
353 scoped_ptr<ProcessMemoryDumpAsyncState> pmd_async_state) {
354 if (!pmd_async_state->task_runner->BelongsToCurrentThread()) {
355 scoped_refptr<SingleThreadTaskRunner> task_runner =
356 pmd_async_state->task_runner;
357 task_runner->PostTask(FROM_HERE,
358 Bind(&MemoryDumpManager::FinalizeDumpAndAddToTrace,
359 Passed(pmd_async_state.Pass())));
360 return;
363 scoped_refptr<ConvertableToTraceFormat> event_value(new TracedValue());
364 pmd_async_state->process_memory_dump.AsValueInto(
365 static_cast<TracedValue*>(event_value.get()));
366 const char* const event_name =
367 MemoryDumpTypeToString(pmd_async_state->req_args.dump_type);
369 TRACE_EVENT_API_ADD_TRACE_EVENT(
370 TRACE_EVENT_PHASE_MEMORY_DUMP,
371 TraceLog::GetCategoryGroupEnabled(kTraceCategory), event_name,
372 pmd_async_state->req_args.dump_guid, kTraceEventNumArgs,
373 kTraceEventArgNames, kTraceEventArgTypes, nullptr /* arg_values */,
374 &event_value, TRACE_EVENT_FLAG_HAS_ID);
376 if (!pmd_async_state->callback.is_null()) {
377 pmd_async_state->callback.Run(pmd_async_state->req_args.dump_guid,
378 true /* success */);
379 pmd_async_state->callback.Reset();
383 // static
384 void MemoryDumpManager::AbortDumpLocked(
385 MemoryDumpCallback callback,
386 scoped_refptr<SingleThreadTaskRunner> task_runner,
387 uint64 dump_guid) {
388 if (callback.is_null())
389 return; // There is nothing to NACK.
391 // Post the callback even if we are already on the right thread to avoid
392 // invoking the callback while holding the lock_.
393 task_runner->PostTask(FROM_HERE,
394 Bind(callback, dump_guid, false /* success */));
397 void MemoryDumpManager::OnTraceLogEnabled() {
398 // TODO(primiano): at this point we query TraceLog::GetCurrentCategoryFilter
399 // to figure out (and cache) which dumpers should be enabled or not.
400 // For the moment piggy back everything on the generic "memory" category.
401 bool enabled;
402 TRACE_EVENT_CATEGORY_GROUP_ENABLED(kTraceCategory, &enabled);
404 // Initialize the TraceLog for the current thread. This is to avoid that the
405 // TraceLog memory dump provider is registered lazily in the PostTask() below
406 // while the |lock_| is taken;
407 TraceLog::GetInstance()->InitializeThreadLocalEventBufferIfSupported();
409 AutoLock lock(lock_);
411 // There is no point starting the tracing without a delegate.
412 if (!enabled || !delegate_) {
413 // Disable all the providers.
414 for (auto it = dump_providers_.begin(); it != dump_providers_.end(); ++it)
415 it->disabled = true;
416 return;
419 session_state_ = new MemoryDumpSessionState();
420 for (auto it = dump_providers_.begin(); it != dump_providers_.end(); ++it) {
421 it->disabled = false;
422 it->consecutive_failures = 0;
425 subtle::NoBarrier_Store(&memory_tracing_enabled_, 1);
427 // TODO(primiano): This is a temporary hack to disable periodic memory dumps
428 // when running memory benchmarks until they can be enabled/disabled in
429 // base::trace_event::TraceConfig. See https://goo.gl/5Hj3o0.
430 if (delegate_->IsCoordinatorProcess() &&
431 !CommandLine::ForCurrentProcess()->HasSwitch(
432 "enable-memory-benchmarking")) {
433 g_periodic_dumps_count = 0;
434 periodic_dump_timer_.Start(FROM_HERE,
435 TimeDelta::FromMilliseconds(kDumpIntervalMs),
436 base::Bind(&RequestPeriodicGlobalDump));
440 void MemoryDumpManager::OnTraceLogDisabled() {
441 AutoLock lock(lock_);
442 periodic_dump_timer_.Stop();
443 subtle::NoBarrier_Store(&memory_tracing_enabled_, 0);
444 session_state_ = nullptr;
447 uint64 MemoryDumpManager::GetTracingProcessId() const {
448 return delegate_->GetTracingProcessId();
451 MemoryDumpManager::MemoryDumpProviderInfo::MemoryDumpProviderInfo(
452 MemoryDumpProvider* dump_provider,
453 const scoped_refptr<SingleThreadTaskRunner>& task_runner)
454 : dump_provider(dump_provider),
455 task_runner(task_runner),
456 consecutive_failures(0),
457 disabled(false) {
460 MemoryDumpManager::MemoryDumpProviderInfo::~MemoryDumpProviderInfo() {
463 bool MemoryDumpManager::MemoryDumpProviderInfo::operator<(
464 const MemoryDumpProviderInfo& other) const {
465 if (task_runner == other.task_runner)
466 return dump_provider < other.dump_provider;
467 return task_runner < other.task_runner;
470 MemoryDumpManager::ProcessMemoryDumpAsyncState::ProcessMemoryDumpAsyncState(
471 MemoryDumpRequestArgs req_args,
472 MemoryDumpProviderInfoSet::iterator next_dump_provider,
473 const scoped_refptr<MemoryDumpSessionState>& session_state,
474 MemoryDumpCallback callback)
475 : process_memory_dump(session_state),
476 req_args(req_args),
477 next_dump_provider(next_dump_provider),
478 callback(callback),
479 task_runner(MessageLoop::current()->task_runner()) {
482 MemoryDumpManager::ProcessMemoryDumpAsyncState::~ProcessMemoryDumpAsyncState() {
485 } // namespace trace_event
486 } // namespace base