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(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;
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
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);
75 kernel_supports_rss_peak_reset
= false;
79 #endif // defined(OS_LINUX) || defined(OS_ANDROID)
80 #endif // !defined(OS_IOS)
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();
92 } // namespace trace_event