blob: 9e9a705519edc92b7ecc4a8a61ca4192f557f7dc [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 Ferris23f2a0b2019-10-10 13:25:00 -0700247static int GetPagemapFd(pid_t pid) {
248 std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid);
249 int fd = TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC));
250 if (fd == -1) {
251 PLOG(ERROR) << "Failed to open " << pagemap_file;
252 }
253 return fd;
254}
255
Christopher Ferris504d2cc2019-07-12 14:25:48 -0700256bool ProcMemInfo::ReadMaps(bool get_wss, bool use_pageidle, bool get_usage_stats) {
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800257 // Each object reads /proc/<pid>/maps only once. This is done to make sure programs that are
258 // running for the lifetime of the system can recycle the objects and don't have to
259 // unnecessarily retain and update this object in memory (which can get significantly large).
260 // E.g. A program that only needs to reset the working set will never all ->Maps(), ->Usage().
261 // E.g. A program that is monitoring smaps_rollup, may never call ->maps(), Usage(), so it
262 // doesn't make sense for us to parse and retain unnecessary memory accounting stats by default.
263 if (!maps_.empty()) return true;
264
Sandeep Patil54d87212018-08-29 17:10:47 -0700265 // parse and read /proc/<pid>/maps
266 std::string maps_file = ::android::base::StringPrintf("/proc/%d/maps", pid_);
267 if (!::android::procinfo::ReadMapFile(
Sandeep Patilf31c7092019-01-30 17:43:22 -0800268 maps_file, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff, ino_t,
Sandeep Patil54d87212018-08-29 17:10:47 -0700269 const char* name) {
270 maps_.emplace_back(Vma(start, end, pgoff, flags, name));
271 })) {
272 LOG(ERROR) << "Failed to parse " << maps_file;
273 maps_.clear();
274 return false;
275 }
276
Christopher Ferris504d2cc2019-07-12 14:25:48 -0700277 if (!get_usage_stats) {
278 return true;
279 }
280
Christopher Ferris23f2a0b2019-10-10 13:25:00 -0700281 ::android::base::unique_fd pagemap_fd(GetPagemapFd(pid_));
282 if (pagemap_fd == -1) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700283 return false;
284 }
285
286 for (auto& vma : maps_) {
Sandeep Patil061b7132019-01-19 21:11:01 -0800287 if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss, use_pageidle)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800288 LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
289 << vma.end << "]";
Sandeep Patil54d87212018-08-29 17:10:47 -0700290 maps_.clear();
291 return false;
292 }
Sandeep Patil56c414e2019-01-12 21:29:19 -0800293 add_mem_usage(&usage_, vma.usage);
Sandeep Patil54d87212018-08-29 17:10:47 -0700294 }
295
296 return true;
297}
298
Christopher Ferris23f2a0b2019-10-10 13:25:00 -0700299bool ProcMemInfo::FillInVmaStats(Vma& vma) {
300 ::android::base::unique_fd pagemap_fd(GetPagemapFd(pid_));
301 if (pagemap_fd == -1) {
302 return false;
303 }
304
305 if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss_, false)) {
306 LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
307 << vma.end << "]";
308 return false;
309 }
310 return true;
311}
312
Sandeep Patil061b7132019-01-19 21:11:01 -0800313bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss, bool use_pageidle) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700314 PageAcct& pinfo = PageAcct::Instance();
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700315 if (get_wss && use_pageidle && !pinfo.InitPageAcct(true)) {
316 LOG(ERROR) << "Failed to init idle page accounting";
Sandeep Patil54d87212018-08-29 17:10:47 -0700317 return false;
318 }
319
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700320 uint64_t pagesz = getpagesize();
321 size_t num_pages = (vma.end - vma.start) / pagesz;
322 size_t first_page = vma.start / pagesz;
Sandeep Patil061b7132019-01-19 21:11:01 -0800323
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700324 std::vector<uint64_t> page_cache;
325 size_t cur_page_cache_index = 0;
326 size_t num_in_page_cache = 0;
327 size_t num_leftover_pages = num_pages;
328 for (size_t cur_page = first_page; cur_page < first_page + num_pages; ++cur_page) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700329 if (!get_wss) {
330 vma.usage.vss += pagesz;
331 }
Sandeep Patil54d87212018-08-29 17:10:47 -0700332
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700333 // Cache page map data.
334 if (cur_page_cache_index == num_in_page_cache) {
335 static constexpr size_t kMaxPages = 2048;
336 num_leftover_pages -= num_in_page_cache;
337 if (num_leftover_pages > kMaxPages) {
338 num_in_page_cache = kMaxPages;
339 } else {
340 num_in_page_cache = num_leftover_pages;
341 }
342 page_cache.resize(num_in_page_cache);
343 size_t total_bytes = page_cache.size() * sizeof(uint64_t);
344 ssize_t bytes = pread64(pagemap_fd, page_cache.data(), total_bytes,
345 cur_page * sizeof(uint64_t));
346 if (bytes != total_bytes) {
347 if (bytes == -1) {
Christopher Ferrisd9433012019-06-28 11:24:30 -0700348 PLOG(ERROR) << "Failed to read page data at offset 0x" << std::hex
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700349 << cur_page * sizeof(uint64_t);
350 } else {
Christopher Ferrisd9433012019-06-28 11:24:30 -0700351 LOG(ERROR) << "Failed to read page data at offset 0x" << std::hex
352 << cur_page * sizeof(uint64_t) << std::dec << " read bytes " << bytes
353 << " expected bytes " << total_bytes;
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700354 }
355 return false;
356 }
357 cur_page_cache_index = 0;
358 }
359
360 uint64_t page_info = page_cache[cur_page_cache_index++];
361 if (!PAGE_PRESENT(page_info) && !PAGE_SWAPPED(page_info)) continue;
362
363 if (PAGE_SWAPPED(page_info)) {
Sandeep Patil2259fdf2018-11-09 16:42:45 -0800364 vma.usage.swap += pagesz;
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700365 swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(page_info));
Sandeep Patil54d87212018-08-29 17:10:47 -0700366 continue;
367 }
368
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700369 uint64_t page_frame = PAGE_PFN(page_info);
370 uint64_t cur_page_flags;
371 if (!pinfo.PageFlags(page_frame, &cur_page_flags)) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700372 LOG(ERROR) << "Failed to get page flags for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800373 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700374 return false;
375 }
376
Sandeep Patil549feab2018-11-19 11:38:40 -0800377 // skip unwanted pages from the count
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700378 if ((cur_page_flags & pgflags_mask_) != pgflags_) continue;
Sandeep Patil549feab2018-11-19 11:38:40 -0800379
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700380 uint64_t cur_page_counts;
381 if (!pinfo.PageMapCount(page_frame, &cur_page_counts)) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700382 LOG(ERROR) << "Failed to get page count for " << page_frame << " in process " << pid_;
Sandeep Patilc6497eb2018-11-20 09:31:36 -0800383 swap_offsets_.clear();
Sandeep Patil54d87212018-08-29 17:10:47 -0700384 return false;
385 }
386
387 // Page was unmapped between the presence check at the beginning of the loop and here.
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700388 if (cur_page_counts == 0) {
Sandeep Patil54d87212018-08-29 17:10:47 -0700389 continue;
390 }
391
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700392 bool is_dirty = !!(cur_page_flags & (1 << KPF_DIRTY));
393 bool is_private = (cur_page_counts == 1);
Sandeep Patil54d87212018-08-29 17:10:47 -0700394 // Working set
395 if (get_wss) {
Sandeep Patil061b7132019-01-19 21:11:01 -0800396 bool is_referenced = use_pageidle ? (pinfo.IsPageIdle(page_frame) == 1)
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700397 : !!(cur_page_flags & (1 << KPF_REFERENCED));
Sandeep Patil54d87212018-08-29 17:10:47 -0700398 if (!is_referenced) {
399 continue;
400 }
401 // This effectively makes vss = rss for the working set is requested.
402 // The libpagemap implementation returns vss > rss for
403 // working set, which doesn't make sense.
Sandeep Patil56c414e2019-01-12 21:29:19 -0800404 vma.usage.vss += pagesz;
405 }
406
407 vma.usage.rss += pagesz;
408 vma.usage.uss += is_private ? pagesz : 0;
Christopher Ferris7f8915c2019-06-25 17:30:56 -0700409 vma.usage.pss += pagesz / cur_page_counts;
Sandeep Patil56c414e2019-01-12 21:29:19 -0800410 if (is_private) {
411 vma.usage.private_dirty += is_dirty ? pagesz : 0;
412 vma.usage.private_clean += is_dirty ? 0 : pagesz;
Sandeep Patil54d87212018-08-29 17:10:47 -0700413 } else {
Sandeep Patil56c414e2019-01-12 21:29:19 -0800414 vma.usage.shared_dirty += is_dirty ? pagesz : 0;
415 vma.usage.shared_clean += is_dirty ? 0 : pagesz;
Sandeep Patil54d87212018-08-29 17:10:47 -0700416 }
417 }
Sandeep Patil54d87212018-08-29 17:10:47 -0700418 return true;
419}
420
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800421// Public APIs
Sandeep Patil82a48b12019-01-01 16:04:04 -0800422bool ForEachVmaFromFile(const std::string& path, const VmaCallback& callback) {
423 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
424 if (fp == nullptr) {
425 return false;
426 }
427
428 char* line = nullptr;
429 bool parsing_vma = false;
430 ssize_t line_len;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800431 size_t line_alloc = 0;
Sandeep Patil82a48b12019-01-01 16:04:04 -0800432 Vma vma;
Sandeep Patil002f02e2019-01-13 19:39:46 -0800433 while ((line_len = getline(&line, &line_alloc, fp.get())) > 0) {
Sandeep Patil82a48b12019-01-01 16:04:04 -0800434 // Make sure the line buffer terminates like a C string for ReadMapFile
435 line[line_len] = '\0';
436
437 if (parsing_vma) {
438 if (parse_smaps_field(line, &vma.usage)) {
439 // This was a stats field
440 continue;
441 }
442
443 // Done collecting stats, make the call back
444 callback(vma);
445 parsing_vma = false;
446 }
447
448 vma.clear();
449 // If it has, we are looking for the vma stats
450 // 00400000-00409000 r-xp 00000000 fc:00 426998 /usr/lib/gvfs/gvfsd-http
451 if (!::android::procinfo::ReadMapFileContent(
Sandeep Patilf31c7092019-01-30 17:43:22 -0800452 line, [&](uint64_t start, uint64_t end, uint16_t flags, uint64_t pgoff, ino_t,
Sandeep Patil82a48b12019-01-01 16:04:04 -0800453 const char* name) {
454 vma.start = start;
455 vma.end = end;
456 vma.flags = flags;
457 vma.offset = pgoff;
458 vma.name = name;
459 })) {
460 LOG(ERROR) << "Failed to parse " << path;
461 return false;
462 }
463 parsing_vma = true;
464 }
465
466 // free getline() managed buffer
467 free(line);
468
469 if (parsing_vma) {
470 callback(vma);
471 }
472
473 return true;
474}
475
Sandeep Patildfd34be2019-01-13 17:39:08 -0800476enum smaps_rollup_support { UNTRIED, SUPPORTED, UNSUPPORTED };
477
478static std::atomic<smaps_rollup_support> g_rollup_support = UNTRIED;
479
480bool IsSmapsRollupSupported(pid_t pid) {
481 // Similar to OpenSmapsOrRollup checks from android_os_Debug.cpp, except
482 // the method only checks if rollup is supported and returns the status
483 // right away.
484 enum smaps_rollup_support rollup_support = g_rollup_support.load(std::memory_order_relaxed);
485 if (rollup_support != UNTRIED) {
486 return rollup_support == SUPPORTED;
487 }
488 std::string rollup_file = ::android::base::StringPrintf("/proc/%d/smaps_rollup", pid);
489 if (access(rollup_file.c_str(), F_OK | R_OK)) {
490 // No check for errno = ENOENT necessary here. The caller MUST fallback to
491 // using /proc/<pid>/smaps instead anyway.
492 g_rollup_support.store(UNSUPPORTED, std::memory_order_relaxed);
493 return false;
494 }
495
496 g_rollup_support.store(SUPPORTED, std::memory_order_relaxed);
497 LOG(INFO) << "Using smaps_rollup for pss collection";
498 return true;
499}
500
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800501bool SmapsOrRollupFromFile(const std::string& path, MemUsage* stats) {
502 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
503 if (fp == nullptr) {
504 return false;
505 }
506
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800507 char* line = nullptr;
508 size_t line_alloc = 0;
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800509 stats->clear();
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800510 while (getline(&line, &line_alloc, fp.get()) > 0) {
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800511 switch (line[0]) {
512 case 'P':
513 if (strncmp(line, "Pss:", 4) == 0) {
514 char* c = line + 4;
515 stats->pss += strtoull(c, nullptr, 10);
516 } else if (strncmp(line, "Private_Clean:", 14) == 0) {
517 char* c = line + 14;
518 uint64_t prcl = strtoull(c, nullptr, 10);
519 stats->private_clean += prcl;
520 stats->uss += prcl;
521 } else if (strncmp(line, "Private_Dirty:", 14) == 0) {
522 char* c = line + 14;
523 uint64_t prdi = strtoull(c, nullptr, 10);
524 stats->private_dirty += prdi;
525 stats->uss += prdi;
526 }
527 break;
528 case 'R':
529 if (strncmp(line, "Rss:", 4) == 0) {
530 char* c = line + 4;
531 stats->rss += strtoull(c, nullptr, 10);
532 }
533 break;
534 case 'S':
535 if (strncmp(line, "SwapPss:", 8) == 0) {
536 char* c = line + 8;
537 stats->swap_pss += strtoull(c, nullptr, 10);
538 }
539 break;
540 }
541 }
542
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800543 // free getline() managed buffer
544 free(line);
Sandeep Patilfa2d8d52018-12-29 21:05:38 -0800545 return true;
546}
547
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800548bool SmapsOrRollupPssFromFile(const std::string& path, uint64_t* pss) {
549 auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
550 if (fp == nullptr) {
551 return false;
552 }
553 *pss = 0;
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800554 char* line = nullptr;
555 size_t line_alloc = 0;
556 while (getline(&line, &line_alloc, fp.get()) > 0) {
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800557 uint64_t v;
558 if (sscanf(line, "Pss: %" SCNu64 " kB", &v) == 1) {
559 *pss += v;
560 }
561 }
562
Sandeep Patil3fcb44b2019-01-14 17:44:34 -0800563 // free getline() managed buffer
564 free(line);
Sandeep Patil8871e7e2019-01-13 16:47:20 -0800565 return true;
566}
567
Sandeep Patil54d87212018-08-29 17:10:47 -0700568} // namespace meminfo
569} // namespace android