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)
14 #include "base/files/file_util.h"
17 bool kernel_supports_rss_peak_reset
= true;
18 const char kClearPeakRssCommand
[] = "5";
23 namespace trace_event
{
26 uint64
ProcessMemoryTotalsDumpProvider::rss_bytes_for_testing
= 0;
30 ProcessMetrics
* CreateProcessMetricsForCurrentProcess() {
31 #if !defined(OS_MACOSX) || defined(OS_IOS)
32 return ProcessMetrics::CreateProcessMetrics(GetCurrentProcessHandle());
34 return ProcessMetrics::CreateProcessMetrics(GetCurrentProcessHandle(), NULL
);
40 ProcessMemoryTotalsDumpProvider
*
41 ProcessMemoryTotalsDumpProvider::GetInstance() {
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(const MemoryDumpArgs
& args
,
57 ProcessMemoryDump
* pmd
) {
58 const uint64 rss_bytes
= rss_bytes_for_testing
59 ? rss_bytes_for_testing
60 : process_metrics_
->GetWorkingSetSize();
62 uint64 peak_rss_bytes
= 0;
65 peak_rss_bytes
= process_metrics_
->GetPeakWorkingSetSize();
66 #if defined(OS_LINUX) || defined(OS_ANDROID)
67 if (kernel_supports_rss_peak_reset
) {
68 // TODO(ssid): Fix crbug.com/461788 to write to the file from sandboxed
70 int clear_refs_fd
= open("/proc/self/clear_refs", O_WRONLY
);
71 if (clear_refs_fd
> 0 &&
72 WriteFileDescriptor(clear_refs_fd
, kClearPeakRssCommand
,
73 sizeof(kClearPeakRssCommand
))) {
74 pmd
->process_totals()->set_is_peak_rss_resetable(true);
76 kernel_supports_rss_peak_reset
= false;
80 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
81 #endif // !defined(OS_IOS)
84 pmd
->process_totals()->set_resident_set_bytes(rss_bytes
);
85 pmd
->process_totals()->set_peak_resident_set_bytes(peak_rss_bytes
);
86 pmd
->set_has_process_totals();
93 } // namespace trace_event