1 /*
2  * Copyright (C) 2018 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <errno.h>
18 #include <inttypes.h>
19 #include <stdlib.h>
20 #include <sys/mman.h>
21 #include <unistd.h>
22 
23 #include <iostream>
24 #include <sstream>
25 #include <string>
26 #include <vector>
27 
28 #include <android-base/stringprintf.h>
29 #include <meminfo/procmeminfo.h>
30 
31 using Vma = ::android::meminfo::Vma;
32 using ProcMemInfo = ::android::meminfo::ProcMemInfo;
33 using MemUsage = ::android::meminfo::MemUsage;
34 
35 // Global flags to control procmem output
36 
37 // Set to use page idle bits for working set detection
38 bool use_pageidle = false;
39 // hides map entries with zero rss
40 bool hide_zeroes = false;
41 // Reset working set and exit
42 bool reset_wss = false;
43 // Show working set, mutually exclusive with reset_wss;
44 bool show_wss = false;
45 
usage(int exit_status)46 [[noreturn]] static void usage(int exit_status) {
47     fprintf(stderr,
48             "Usage: %s [-i] [ -w | -W ] [ -p | -m ] [ -h ] pid\n"
49             "    -i  Uses idle page tracking for working set statistics.\n"
50             "    -w  Displays statistics for the working set only.\n"
51             "    -W  Resets the working set of the process.\n"
52             "    -p  Sort by PSS.\n"
53             "    -u  Sort by USS.\n"
54             "    -m  Sort by mapping order (as read from /proc).\n"
55             "    -h  Hide maps with no RSS.\n",
56             getprogname());
57 
58     exit(exit_status);
59 }
60 
print_separator(std::stringstream & ss)61 static void print_separator(std::stringstream& ss) {
62     if (show_wss) {
63         ss << ::android::base::StringPrintf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
64                                             "-------", "-------", "-------", "-------", "-------",
65                                             "-------", "-------", "-------", "-------", "");
66         return;
67     }
68     ss << ::android::base::StringPrintf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
69                                         "-------", "-------", "-------", "-------", "-------",
70                                         "-------", "-------", "-------", "-------", "-------", "");
71 }
72 
print_header(std::stringstream & ss)73 static void print_header(std::stringstream& ss) {
74     if (show_wss) {
75         ss << ::android::base::StringPrintf("%7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n",
76                                             "WRss", "WPss", "WUss", "WShCl", "WShDi", "WPrCl",
77                                             "WPrDi", "THP", "Flags", "Name");
78     } else {
79         ss << ::android::base::StringPrintf(
80                 "%7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %7s  %s\n", "Vss", "Rss", "Pss",
81                 "Uss", "ShCl", "ShDi", "PrCl", "PrDi", "THP", "Flags", "Name");
82     }
83     print_separator(ss);
84 }
85 
print_stats(std::stringstream & ss,const MemUsage & stats)86 static void print_stats(std::stringstream& ss, const MemUsage& stats) {
87     if (!show_wss) {
88         ss << ::android::base::StringPrintf("%6" PRIu64 "K  ", stats.vss / 1024);
89     }
90 
91     ss << ::android::base::StringPrintf(
92             "%6" PRIu64 "K  %6" PRIu64 "K  %6" PRIu64 "K  %6" PRIu64 "K  %6" PRIu64 "K  %6" PRIu64
93             "K  %6" PRIu64 "K  %6" PRIu64 "K ",
94             stats.rss / 1024, stats.pss / 1024, stats.uss / 1024, stats.shared_clean / 1024,
95             stats.shared_dirty / 1024, stats.private_clean / 1024, stats.private_dirty / 1024,
96             stats.thp / 1024);
97 }
98 
show(const MemUsage & proc_stats,const std::vector<Vma> & maps)99 static int show(const MemUsage& proc_stats, const std::vector<Vma>& maps) {
100     std::stringstream ss;
101     print_header(ss);
102     for (auto& vma : maps) {
103         const MemUsage& vma_stats = vma.usage;
104         if (hide_zeroes && vma_stats.rss == 0) {
105             continue;
106         }
107         print_stats(ss, vma_stats);
108 
109         // TODO: b/141711064 fix libprocinfo to record (p)rivate or (s)hared flag
110         // for now always report as private
111         std::string flags_str("---p");
112         if (vma.flags & PROT_READ) flags_str[0] = 'r';
113         if (vma.flags & PROT_WRITE) flags_str[1] = 'w';
114         if (vma.flags & PROT_EXEC) flags_str[2] = 'x';
115 
116         ss << ::android::base::StringPrintf("%7s  ", flags_str.c_str()) << vma.name << std::endl;
117     }
118     print_separator(ss);
119     print_stats(ss, proc_stats);
120     ss << "TOTAL" << std::endl;
121     std::cout << ss.str();
122 
123     return 0;
124 }
125 
main(int argc,char * argv[])126 int main(int argc, char* argv[]) {
127     int opt;
128     auto pss_sort = [](const Vma& a, const Vma& b) {
129         uint64_t pss_a = a.usage.pss;
130         uint64_t pss_b = b.usage.pss;
131         return pss_a > pss_b;
132     };
133 
134     auto uss_sort = [](const Vma& a, const Vma& b) {
135         uint64_t uss_a = a.usage.uss;
136         uint64_t uss_b = b.usage.uss;
137         return uss_a > uss_b;
138     };
139 
140     std::function<bool(const Vma& a, const Vma& b)> sort_func = nullptr;
141     while ((opt = getopt(argc, argv, "himpuWw")) != -1) {
142         switch (opt) {
143             case 'h':
144                 hide_zeroes = true;
145                 break;
146             case 'i':
147                 // TODO: libmeminfo doesn't support the flag to chose
148                 // between idle page tracking vs clear_refs. So for now,
149                 // this flag is unused and the library defaults to using
150                 // /proc/<pid>/clear_refs for finding the working set.
151                 use_pageidle = true;
152                 break;
153             case 'm':
154                 // this is the default
155                 break;
156             case 'p':
157                 sort_func = pss_sort;
158                 break;
159             case 'u':
160                 sort_func = uss_sort;
161                 break;
162             case 'W':
163                 reset_wss = true;
164                 break;
165             case 'w':
166                 show_wss = true;
167                 break;
168             case '?':
169                 usage(EXIT_SUCCESS);
170             default:
171                 usage(EXIT_FAILURE);
172         }
173     }
174 
175     if (optind != (argc - 1)) {
176         fprintf(stderr, "Need exactly one pid at the end\n");
177         usage(EXIT_FAILURE);
178     }
179 
180     pid_t pid = atoi(argv[optind]);
181     if (pid == 0) {
182         std::cerr << "Invalid process id" << std::endl;
183         exit(EXIT_FAILURE);
184     }
185 
186     if (reset_wss) {
187         if (!ProcMemInfo::ResetWorkingSet(pid)) {
188             std::cerr << "Failed to reset working set of pid : " << pid << std::endl;
189             exit(EXIT_FAILURE);
190         }
191         return 0;
192     }
193 
194     ProcMemInfo proc(pid, show_wss);
195     const MemUsage& proc_stats = proc.Usage();
196     std::vector<Vma> maps(proc.Maps());
197     if (sort_func != nullptr) {
198         std::sort(maps.begin(), maps.end(), sort_func);
199     }
200 
201     return show(proc_stats, maps);
202 }
203