blob: 6f68ab464bfda0e79722a2f76a367f63763372b7 [file] [log] [blame]
Sandeep Patil54d87212018-08-29 17:10:47 -07001/*
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 <fcntl.h>
19#include <inttypes.h>
20#include <linux/kernel-page-flags.h>
21#include <stdio.h>
22#include <unistd.h>
23
Sandeep Patildfd34be2019-01-13 17:39:08 -080024#include <atomic>
Sandeep Patil54d87212018-08-29 17:10:47 -070025#include <fstream>
26#include <iostream>
27#include <memory>
28#include <string>
29#include <utility>
Christopher Ferris7f8915c2019-06-25 17:30:56 -070030#include <vector>
Sandeep Patil54d87212018-08-29 17:10:47 -070031
32#include <android-base/file.h>
33#include <android-base/logging.h>
34#include <android-base/stringprintf.h>
Sandeep Patilfa2d8d52018-12-29 21:05:38 -080035#include <android-base/strings.h>
Sandeep Patil54d87212018-08-29 17:10:47 -070036#include <android-base/unique_fd.h>
37#include <procinfo/process_map.h>
38
39#include "meminfo_private.h"
40
41namespace android {
42namespace meminfo {
43
44static void add_mem_usage(MemUsage* to, const MemUsage& from) {
45 to->vss += from.vss;
46 to->rss += from.rss;
47 to->pss += from.pss;
48 to->uss += from.uss;
49
Sandeep Patil2259fdf2018-11-09 16:42:45 -080050 to->swap += from.swap;
51
Sandeep Patil54d87212018-08-29 17:10:47 -070052 to->private_clean += from.private_clean;
53 to->private_dirty += from.private_dirty;
54
55 to->shared_clean += from.shared_clean;
56 to->shared_dirty += from.shared_dirty;
57}
58
Sandeep Patil82a48b12019-01-01 16:04:04 -080059// Returns true if the line was valid smaps stats line false otherwise.
60static bool parse_smaps_field(const char* line, MemUsage* stats) {
61 char field[64];
62 int len;
63 if (sscanf(line, "%63s %n", field, &len) == 1 && *field && field[strlen(field) - 1] == ':') {
64 const char* c = line + len;
65 switch (field[0]) {
66 case 'P':
67 if (strncmp(field, "Pss:", 4) == 0) {
68 stats->pss = strtoull(c, nullptr, 10);
69 } else if (strncmp(field, "Private_Clean:", 14) == 0) {
70 uint64_t prcl = strtoull(c, nullptr, 10);
71 stats->private_clean = prcl;
72 stats->uss += prcl;
73 } else if (strncmp(field, "Private_Dirty:", 14) == 0) {
74 uint64_t prdi = strtoull(c, nullptr, 10);
75 stats->private_dirty = prdi;
76 stats->uss += prdi;
77 }
78 break;
79 case 'S':
80 if (strncmp(field, "Size:", 5) == 0) {
81 stats->vss = strtoull(c, nullptr, 10);
82 } else if (strncmp(field, "Shared_Clean:", 13) == 0) {
83 stats->shared_clean = strtoull(c, nullptr, 10);
84 } else if (strncmp(field, "Shared_Dirty:", 13) == 0) {
85 stats->shared_dirty = strtoull(c, nullptr, 10);
86 } else if (strncmp(field, "Swap:", 5) == 0) {
87 stats->swap = strtoull(c, nullptr, 10);
88 } else if (strncmp(field, "SwapPss:", 8) == 0) {
89 stats->swap_pss = strtoull(c, nullptr, 10);
90 }
91 break;
92 case 'R':
93 if (strncmp(field, "Rss:", 4) == 0) {
94 stats->rss = strtoull(c, nullptr, 10);
95 }
96 break;
97 }
98 return true;
99 }
100
101 return false;
102}
103
Sandeep Patilf1291992018-11-19 15:25:18 -0800104bool ProcMemInfo::ResetWorkingSet(pid_t pid) {
105 std::string clear_refs_path = ::android::base::StringPrintf("/proc/%d/clear_refs", pid);
106 if (!::android::base::WriteStringToFile("1\n", clear_refs_path)) {
107 PLOG(ERROR) << "Failed to write to " << clear_refs_path;
108 return false;
109 }
110
111 return true;
112}
113
Sandeep Patil549feab2018-11-19 11:38:40 -0800114ProcMemInfo::ProcMemInfo(pid_t pid, bool get_wss, uint64_t pgflags, uint64_t pgflags_mask)
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800115 : pid_(pid), get_wss_(get_wss), pgflags_(pgflags), pgflags_mask_(pgflags_mask) {}
Sandeep Patil54d87212018-08-29 17:10:47 -0700116
117const std::vector<Vma>& ProcMemInfo::Maps() {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800118 if (maps_.empty() && !ReadMaps(get_wss_)) {
119 LOG(ERROR) << "Failed to read maps for Process " << pid_;
120 }
121
Sandeep Patil54d87212018-08-29 17:10:47 -0700122 return maps_;
123}
124
Sandeep Patil061b7132019-01-19 21:11:01 -0800125const std::vector<Vma>& ProcMemInfo::MapsWithPageIdle() {
126 if (maps_.empty() && !ReadMaps(get_wss_, true)) {
127 LOG(ERROR) << "Failed to read maps with page idle for Process " << pid_;
128 }
129
130 return maps_;
131}
132
Christopher Ferris504d2cc2019-07-12 14:25:48 -0700133const std::vector<Vma>& ProcMemInfo::MapsWithoutUsageStats() {
134 if (maps_.empty() && !ReadMaps(get_wss_, false, false)) {
135 LOG(ERROR) << "Failed to read maps for Process " << pid_;
136 }
137
138 return maps_;
139}
140
Sandeep Patil82a48b12019-01-01 16:04:04 -0800141const std::vector<Vma>& ProcMemInfo::Smaps(const std::string& path) {
142 if (!maps_.empty()) {
143 return maps_;
144 }
145
146 auto collect_vmas = [&](const Vma& vma) { maps_.emplace_back(vma); };
147 if (path.empty() && !ForEachVma(collect_vmas)) {
148 LOG(ERROR) << "Failed to read smaps for Process " << pid_;
149 maps_.clear();
150 }
151
152 if (!path.empty() && !ForEachVmaFromFile(path, collect_vmas)) {
153 LOG(ERROR) << "Failed to read smaps from file " << path;
154 maps_.clear();
155 }
156
157 return maps_;
158}
159
Sandeep Patil54d87212018-08-29 17:10:47 -0700160const MemUsage& ProcMemInfo::Usage() {
161 if (get_wss_) {
Sandeep Patilf1291992018-11-19 15:25:18 -0800162 LOG(WARNING) << "Trying to read process memory usage for " << pid_
163 << " using invalid object";
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800164 return usage_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700165 }
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800166
167 if (maps_.empty() && !ReadMaps(get_wss_)) {
168 LOG(ERROR) << "Failed to get memory usage for Process " << pid_;
169 }
170
Sandeep Patil54d87212018-08-29 17:10:47 -0700171 return usage_;
172}
173
174const MemUsage& ProcMemInfo::Wss() {
175 if (!get_wss_) {
Sandeep Patilf1291992018-11-19 15:25:18 -0800176 LOG(WARNING) << "Trying to read process working set for " << pid_
177 << " using invalid object";
Sandeep Patil56c414e2019-01-12 21:29:19 -0800178 return usage_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800179 }
180
181 if (maps_.empty() && !ReadMaps(get_wss_)) {
182 LOG(ERROR) << "Failed to get working set for Process " << pid_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700183 }
184
Sandeep Patil56c414e2019-01-12 21:29:19 -0800185 return usage_;
Sandeep Patil54d87212018-08-29 17:10:47 -0700186}
187
Sandeep Patil82a48b12019-01-01 16:04:04 -0800188bool ProcMemInfo::ForEachVma(const VmaCallback& callback) {
189 std::string path = ::android::base::StringPrintf("/proc/%d/smaps", pid_);
190 return ForEachVmaFromFile(path, callback);
191}
192
Sandeep Patildfd34be2019-01-13 17:39:08 -0800193bool ProcMemInfo::SmapsOrRollup(MemUsage* stats) const {
194 std::string path = ::android::base::StringPrintf(
195 "/proc/%d/%s", pid_, IsSmapsRollupSupported(pid_) ? "smaps_rollup" : "smaps");
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800196 return SmapsOrRollupFromFile(path, stats);
Sandeep Patildfd34be2019-01-13 17:39:08 -0800197}
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800198
Sandeep Patildfd34be2019-01-13 17:39:08 -0800199bool ProcMemInfo::SmapsOrRollupPss(uint64_t* pss) const {
200 std::string path = ::android::base::StringPrintf(
201 "/proc/%d/%s", pid_, IsSmapsRollupSupported(pid_) ? "smaps_rollup" : "smaps");
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800202 return SmapsOrRollupPssFromFile(path, pss);
203}
204
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800205const std::vector<uint16_t>& ProcMemInfo::SwapOffsets() {
206 if (get_wss_) {
207 LOG(WARNING) << "Trying to read process swap offsets for " << pid_
208 << " using invalid object";
209 return swap_offsets_;
210 }
211
212 if (maps_.empty() && !ReadMaps(get_wss_)) {
213 LOG(ERROR) << "Failed to get swap offsets for Process " << pid_;
214 }
215
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800216 return swap_offsets_;
217}
218
Sandeep Patilcbc8f122019-01-21 16:47:24 -0800219bool ProcMemInfo::PageMap(const Vma& vma, std::vector<uint64_t>* pagemap) {
220 pagemap->clear();
221 std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
222 ::android::base::unique_fd pagemap_fd(
223 TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
Christopher Ferris504d2cc2019-07-12 14:25:48 -0700224 if (pagemap_fd == -1) {
Sandeep Patilcbc8f122019-01-21 16:47:24 -0800225 PLOG(ERROR) << "Failed to open " << pagemap_file;
226 return false;
227 }
228
229 uint64_t nr_pages = (vma.end - vma.start) / getpagesize();
Christopher Ferris504d2cc2019-07-12 14:25:48 -0700230 pagemap->resize(nr_pages);
Sandeep Patilcbc8f122019-01-21 16:47:24 -0800231
Christopher Ferris504d2cc2019-07-12 14:25:48 -0700232 size_t bytes_to_read = sizeof(uint64_t) * nr_pages;
233 off64_t start_addr = (vma.start / getpagesize()) * sizeof(uint64_t);
234 ssize_t bytes_read = pread64(pagemap_fd, pagemap->data(), bytes_to_read, start_addr);
235 if (bytes_read == -1) {
236 PLOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_;
237 return false;
238 } else if (static_cast<size_t>(bytes_read) != bytes_to_read) {
239 LOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_
240 << ": read bytes " << bytes_read << " expected bytes " << bytes_to_read;
241 return false;
Sandeep Patilcbc8f122019-01-21 16:47:24 -0800242 }
243
244 return true;
245}
246
Christopher Ferris504d2cc2019-07-12 14:25:48 -0700247bool ProcMemInfo::ReadMaps(bool get_wss, bool use_pageidle, bool get_usage_stats) {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800248 // Each object reads /proc/<pid>/maps only once. This is done to make sure programs that are
249 // running for the lifetime of the system can recycle the objects and don't have to
250 // unnecessarily retain and update this object in memory (which can get significantly large).
251 // E.g. A program that only needs to reset the working set will never all ->Maps(), ->Usage().
252 // E.g. A program that is monitoring smaps_rollup, may never call ->maps(), Usage(), so it
253 // doesn't make sense for us to parse and retain unnecessary memory accounting stats by default.
254 if (!maps_.empty()) return true;
255
Sandeep Patil54d87212018-08-29 17:10:47 -0700256 // parse and read /proc/<pid>/maps
257 std::string maps_file = ::android::base::StringPrintf("/proc/%d/maps", pid_);
258 if (!::android::procinfo::ReadMapFile(
Sandeep Patilf31c7092019-01-30 17:43:22 -0800259 maps_file, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff, ino_t,
Sandeep Patil54d87212018-08-29 17:10:47 -0700260 const char* name) {
261 maps_.emplace_back(Vma(start, end, pgoff, flags, name));
262 })) {
263 LOG(ERROR) << "Failed to parse " << maps_file;
264 maps_.clear();
265 return false;
266 }
267
Christopher Ferris504d2cc2019-07-12 14:25:48 -0700268 if (!get_usage_stats) {
269 return true;
270 }
271
Sandeep Patil54d87212018-08-29 17:10:47 -0700272 std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
273 ::android::base::unique_fd pagemap_fd(
274 TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
275 if (pagemap_fd < 0) {
276 PLOG(ERROR) << "Failed to open " << pagemap_file;
277 return false;
278 }
279
280 for (auto& vma : maps_) {
Sandeep Patil061b7132019-01-19 21:11:01 -0800281 if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss, use_pageidle)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800282 LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
283 << vma.end << "]";
Sandeep Patil54d87212018-08-29 17:10:47 -0700284 maps_.clear();
285 return false;
286 }
Sandeep Patil56c414e2019-01-12 21:29:19 -0800287 add_mem_usage(&usage_, vma.usage);
Sandeep Patil54d87212018-08-29 17:10:47 -0700288 }
289
290 return true;
291}
292
Sandeep Patil061b7132019-01-19 21:11:01 -0800293bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss, bool use_pageidle) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700294 PageAcct& pinfo = PageAcct::Instance();
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700295 if (get_wss && use_pageidle && !pinfo.InitPageAcct(true)) {
296 LOG(ERROR) << "Failed to init idle page accounting";
Sandeep Patil54d87212018-08-29 17:10:47 -0700297 return false;
298 }
299
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700300 uint64_t pagesz = getpagesize();
301 size_t num_pages = (vma.end - vma.start) / pagesz;
302 size_t first_page = vma.start / pagesz;
Sandeep Patil061b7132019-01-19 21:11:01 -0800303
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700304 std::vector<uint64_t> page_cache;
305 size_t cur_page_cache_index = 0;
306 size_t num_in_page_cache = 0;
307 size_t num_leftover_pages = num_pages;
308 for (size_t cur_page = first_page; cur_page < first_page + num_pages; ++cur_page) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700309 if (!get_wss) {
310 vma.usage.vss += pagesz;
311 }
Sandeep Patil54d87212018-08-29 17:10:47 -0700312
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700313 // Cache page map data.
314 if (cur_page_cache_index == num_in_page_cache) {
315 static constexpr size_t kMaxPages = 2048;
316 num_leftover_pages -= num_in_page_cache;
317 if (num_leftover_pages > kMaxPages) {
318 num_in_page_cache = kMaxPages;
319 } else {
320 num_in_page_cache = num_leftover_pages;
321 }
322 page_cache.resize(num_in_page_cache);
323 size_t total_bytes = page_cache.size() * sizeof(uint64_t);
324 ssize_t bytes = pread64(pagemap_fd, page_cache.data(), total_bytes,
325 cur_page * sizeof(uint64_t));
326 if (bytes != total_bytes) {
327 if (bytes == -1) {
Christopher Ferrisd9433012019-06-28 11:24:30 -0700328 PLOG(ERROR) << "Failed to read page data at offset 0x" << std::hex
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700329 << cur_page * sizeof(uint64_t);
330 } else {
Christopher Ferrisd9433012019-06-28 11:24:30 -0700331 LOG(ERROR) << "Failed to read page data at offset 0x" << std::hex
332 << cur_page * sizeof(uint64_t) << std::dec << " read bytes " << bytes
333 << " expected bytes " << total_bytes;
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700334 }
335 return false;
336 }
337 cur_page_cache_index = 0;
338 }
339
340 uint64_t page_info = page_cache[cur_page_cache_index++];
341 if (!PAGE_PRESENT(page_info) && !PAGE_SWAPPED(page_info)) continue;
342
343 if (PAGE_SWAPPED(page_info)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800344 vma.usage.swap += pagesz;
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700345 swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(page_info));
Sandeep Patil54d87212018-08-29 17:10:47 -0700346 continue;
347 }
348
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700349 uint64_t page_frame = PAGE_PFN(page_info);
350 uint64_t cur_page_flags;
351 if (!pinfo.PageFlags(page_frame, &cur_page_flags)) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700352 LOG(ERROR) << "Failed to get page flags for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800353 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700354 return false;
355 }
356
Sandeep Patil549feab2018-11-19 11:38:40 -0800357 // skip unwanted pages from the count
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700358 if ((cur_page_flags & pgflags_mask_) != pgflags_) continue;
Sandeep Patil549feab2018-11-19 11:38:40 -0800359
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700360 uint64_t cur_page_counts;
361 if (!pinfo.PageMapCount(page_frame, &cur_page_counts)) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700362 LOG(ERROR) << "Failed to get page count for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800363 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700364 return false;
365 }
366
367 // Page was unmapped between the presence check at the beginning of the loop and here.
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700368 if (cur_page_counts == 0) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700369 continue;
370 }
371
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700372 bool is_dirty = !!(cur_page_flags & (1 << KPF_DIRTY));
373 bool is_private = (cur_page_counts == 1);
Sandeep Patil54d87212018-08-29 17:10:47 -0700374 // Working set
375 if (get_wss) {
Sandeep Patil061b7132019-01-19 21:11:01 -0800376 bool is_referenced = use_pageidle ? (pinfo.IsPageIdle(page_frame) == 1)
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700377 : !!(cur_page_flags & (1 << KPF_REFERENCED));
Sandeep Patil54d87212018-08-29 17:10:47 -0700378 if (!is_referenced) {
379 continue;
380 }
381 // This effectively makes vss = rss for the working set is requested.
382 // The libpagemap implementation returns vss > rss for
383 // working set, which doesn't make sense.
Sandeep Patil56c414e2019-01-12 21:29:19 -0800384 vma.usage.vss += pagesz;
385 }
386
387 vma.usage.rss += pagesz;
388 vma.usage.uss += is_private ? pagesz : 0;
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700389 vma.usage.pss += pagesz / cur_page_counts;
Sandeep Patil56c414e2019-01-12 21:29:19 -0800390 if (is_private) {
391 vma.usage.private_dirty += is_dirty ? pagesz : 0;
392 vma.usage.private_clean += is_dirty ? 0 : pagesz;
Sandeep Patil54d87212018-08-29 17:10:47 -0700393 } else {
Sandeep Patil56c414e2019-01-12 21:29:19 -0800394 vma.usage.shared_dirty += is_dirty ? pagesz : 0;
395 vma.usage.shared_clean += is_dirty ? 0 : pagesz;
Sandeep Patil54d87212018-08-29 17:10:47 -0700396 }
397 }
Sandeep Patil54d87212018-08-29 17:10:47 -0700398 return true;
399}
400
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800401// Public APIs
Sandeep Patil82a48b12019-01-01 16:04:04 -0800402bool ForEachVmaFromFile(const std::string& path, const VmaCallback& callback) {
403 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
404 if (fp == nullptr) {
405 return false;
406 }
407
408 char* line = nullptr;
409 bool parsing_vma = false;
410 ssize_t line_len;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800411 size_t line_alloc = 0;
Sandeep Patil82a48b12019-01-01 16:04:04 -0800412 Vma vma;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800413 while ((line_len = getline(&line, &line_alloc, fp.get())) > 0) {
Sandeep Patil82a48b12019-01-01 16:04:04 -0800414 // Make sure the line buffer terminates like a C string for ReadMapFile
415 line[line_len] = '\0';
416
417 if (parsing_vma) {
418 if (parse_smaps_field(line, &vma.usage)) {
419 // This was a stats field
420 continue;
421 }
422
423 // Done collecting stats, make the call back
424 callback(vma);
425 parsing_vma = false;
426 }
427
428 vma.clear();
429 // If it has, we are looking for the vma stats
430 // 00400000-00409000 r-xp 00000000 fc:00 426998 /usr/lib/gvfs/gvfsd-http
431 if (!::android::procinfo::ReadMapFileContent(
Sandeep Patilf31c7092019-01-30 17:43:22 -0800432 line, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff, ino_t,
Sandeep Patil82a48b12019-01-01 16:04:04 -0800433 const char* name) {
434 vma.start = start;
435 vma.end = end;
436 vma.flags = flags;
437 vma.offset = pgoff;
438 vma.name = name;
439 })) {
440 LOG(ERROR) << "Failed to parse " << path;
441 return false;
442 }
443 parsing_vma = true;
444 }
445
446 // free getline() managed buffer
447 free(line);
448
449 if (parsing_vma) {
450 callback(vma);
451 }
452
453 return true;
454}
455
Sandeep Patildfd34be2019-01-13 17:39:08 -0800456enum smaps_rollup_support { UNTRIED, SUPPORTED, UNSUPPORTED };
457
458static std::atomic<smaps_rollup_support> g_rollup_support = UNTRIED;
459
460bool IsSmapsRollupSupported(pid_t pid) {
461 // Similar to OpenSmapsOrRollup checks from android_os_Debug.cpp, except
462 // the method only checks if rollup is supported and returns the status
463 // right away.
464 enum smaps_rollup_support rollup_support = g_rollup_support.load(std::memory_order_relaxed);
465 if (rollup_support != UNTRIED) {
466 return rollup_support == SUPPORTED;
467 }
468 std::string rollup_file = ::android::base::StringPrintf("/proc/%d/smaps_rollup", pid);
469 if (access(rollup_file.c_str(), F_OK | R_OK)) {
470 // No check for errno = ENOENT necessary here. The caller MUST fallback to
471 // using /proc/<pid>/smaps instead anyway.
472 g_rollup_support.store(UNSUPPORTED, std::memory_order_relaxed);
473 return false;
474 }
475
476 g_rollup_support.store(SUPPORTED, std::memory_order_relaxed);
477 LOG(INFO) << "Using smaps_rollup for pss collection";
478 return true;
479}
480
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800481bool SmapsOrRollupFromFile(const std::string& path, MemUsage* stats) {
482 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
483 if (fp == nullptr) {
484 return false;
485 }
486
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800487 char* line = nullptr;
488 size_t line_alloc = 0;
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800489 stats->clear();
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800490 while (getline(&line, &line_alloc, fp.get()) > 0) {
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800491 switch (line[0]) {
492 case 'P':
493 if (strncmp(line, "Pss:", 4) == 0) {
494 char* c = line + 4;
495 stats->pss += strtoull(c, nullptr, 10);
496 } else if (strncmp(line, "Private_Clean:", 14) == 0) {
497 char* c = line + 14;
498 uint64_t prcl = strtoull(c, nullptr, 10);
499 stats->private_clean += prcl;
500 stats->uss += prcl;
501 } else if (strncmp(line, "Private_Dirty:", 14) == 0) {
502 char* c = line + 14;
503 uint64_t prdi = strtoull(c, nullptr, 10);
504 stats->private_dirty += prdi;
505 stats->uss += prdi;
506 }
507 break;
508 case 'R':
509 if (strncmp(line, "Rss:", 4) == 0) {
510 char* c = line + 4;
511 stats->rss += strtoull(c, nullptr, 10);
512 }
513 break;
514 case 'S':
515 if (strncmp(line, "SwapPss:", 8) == 0) {
516 char* c = line + 8;
517 stats->swap_pss += strtoull(c, nullptr, 10);
518 }
519 break;
520 }
521 }
522
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800523 // free getline() managed buffer
524 free(line);
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800525 return true;
526}
527
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800528bool SmapsOrRollupPssFromFile(const std::string& path, uint64_t* pss) {
529 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
530 if (fp == nullptr) {
531 return false;
532 }
533 *pss = 0;
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800534 char* line = nullptr;
535 size_t line_alloc = 0;
536 while (getline(&line, &line_alloc, fp.get()) > 0) {
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800537 uint64_t v;
538 if (sscanf(line, "Pss: %" SCNu64 " kB", &v) == 1) {
539 *pss += v;
540 }
541 }
542
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800543 // free getline() managed buffer
544 free(line);
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800545 return true;
546}
547
Sandeep Patil54d87212018-08-29 17:10:47 -0700548} // namespace meminfo
549} // namespace android