Pin Chrome's shortcut to the Win10 Start menu on install and OS upgrade.
[chromium-blink-merge.git] / base / trace_event / process_memory_totals_dump_provider.cc
blob37f9bed68c9b2b4e59e8b83b70fc776c5117906a
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/process_memory_totals_dump_provider.h"
7 #include "base/process/process_metrics.h"
8 #include "base/trace_event/process_memory_dump.h"
9 #include "base/trace_event/process_memory_totals.h"
11 #if defined(OS_LINUX) || defined(OS_ANDROID)
12 #include <fcntl.h>
14 #include "base/files/file_util.h"
16 namespace {
17 bool kernel_supports_rss_peak_reset = true;
18 const char kClearPeakRssCommand[] = "5";
20 #endif
22 namespace base {
23 namespace trace_event {
25 // static
26 uint64 ProcessMemoryTotalsDumpProvider::rss_bytes_for_testing = 0;
28 namespace {
30 ProcessMetrics* CreateProcessMetricsForCurrentProcess() {
31 #if !defined(OS_MACOSX) || defined(OS_IOS)
32 return ProcessMetrics::CreateProcessMetrics(GetCurrentProcessHandle());
33 #else
34 return ProcessMetrics::CreateProcessMetrics(GetCurrentProcessHandle(), NULL);
35 #endif
37 } // namespace
39 // static
40 ProcessMemoryTotalsDumpProvider*
41 ProcessMemoryTotalsDumpProvider::GetInstance() {
42 return Singleton<
43 ProcessMemoryTotalsDumpProvider,
44 LeakySingletonTraits<ProcessMemoryTotalsDumpProvider>>::get();
47 ProcessMemoryTotalsDumpProvider::ProcessMemoryTotalsDumpProvider()
48 : process_metrics_(CreateProcessMetricsForCurrentProcess()) {
51 ProcessMemoryTotalsDumpProvider::~ProcessMemoryTotalsDumpProvider() {
54 // Called at trace dump point time. Creates a snapshot the memory counters for
55 // the current process.
56 bool ProcessMemoryTotalsDumpProvider::OnMemoryDump(ProcessMemoryDump* pmd) {
57 const uint64 rss_bytes = rss_bytes_for_testing
58 ? rss_bytes_for_testing
59 : process_metrics_->GetWorkingSetSize();
61 uint64 peak_rss_bytes = 0;
63 #if !defined(OS_IOS)
64 peak_rss_bytes = process_metrics_->GetPeakWorkingSetSize();
65 #if defined(OS_LINUX) || defined(OS_ANDROID)
66 if (kernel_supports_rss_peak_reset) {
67 // TODO(ssid): Fix crbug.com/461788 to write to the file from sandboxed
68 // processes.
69 int clear_refs_fd = open("/proc/self/clear_refs", O_WRONLY);
70 if (clear_refs_fd > 0 &&
71 WriteFileDescriptor(clear_refs_fd, kClearPeakRssCommand,
72 sizeof(kClearPeakRssCommand))) {
73 pmd->process_totals()->set_is_peak_rss_resetable(true);
74 } else {
75 kernel_supports_rss_peak_reset = false;
77 close(clear_refs_fd);
79 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
80 #endif // !defined(OS_IOS)
82 if (rss_bytes > 0) {
83 pmd->process_totals()->set_resident_set_bytes(rss_bytes);
84 pmd->process_totals()->set_peak_resident_set_bytes(peak_rss_bytes);
85 pmd->set_has_process_totals();
86 return true;
89 return false;
92 } // namespace trace_event
93 } // namespace base