• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 <fcntl.h>
19 #include <inttypes.h>
20 #include <linux/kernel-page-flags.h>
21 #include <stdio.h>
22 #include <unistd.h>
23 
24 #include <atomic>
25 #include <fstream>
26 #include <iostream>
27 #include <memory>
28 #include <string>
29 #include <utility>
30 #include <vector>
31 
32 #include <android-base/file.h>
33 #include <android-base/logging.h>
34 #include <android-base/stringprintf.h>
35 #include <android-base/strings.h>
36 #include <android-base/unique_fd.h>
37 #include <procinfo/process_map.h>
38 
39 #include "meminfo_private.h"
40 
41 namespace android {
42 namespace meminfo {
43 
44 // List of VMA names that we don't want to process:
45 //   - On ARM32, [vectors] is a special VMA that is outside of pagemap range.
46 //   - On x86, [vsyscall] is a kernel memory that is outside of pagemap range.
47 static const std::vector<std::string> g_excluded_vmas = {
48     "[vectors]",
49 #ifdef __x86_64__
50     "[vsyscall]"
51 #endif
52 };
53 
add_mem_usage(MemUsage * to,const MemUsage & from)54 static void add_mem_usage(MemUsage* to, const MemUsage& from) {
55     to->vss += from.vss;
56     to->rss += from.rss;
57     to->pss += from.pss;
58     to->uss += from.uss;
59 
60     to->swap += from.swap;
61 
62     to->private_clean += from.private_clean;
63     to->private_dirty += from.private_dirty;
64 
65     to->shared_clean += from.shared_clean;
66     to->shared_dirty += from.shared_dirty;
67 }
68 
69 // Converts MemUsage stats from KB to B in case usage is expected in bytes.
convert_usage_kb_to_b(MemUsage & usage)70 static void convert_usage_kb_to_b(MemUsage& usage) {
71     // These stats are only populated if /proc/<pid>/smaps is read, so they are excluded:
72     // swap_pss, anon_huge_pages, shmem_pmdmapped, file_pmd_mapped, shared_hugetlb, private_hugetlb.
73     constexpr int conversion_factor = 1024;
74     usage.vss *= conversion_factor;
75     usage.rss *= conversion_factor;
76     usage.pss *= conversion_factor;
77     usage.uss *= conversion_factor;
78 
79     usage.swap *= conversion_factor;
80 
81     usage.private_clean *= conversion_factor;
82     usage.private_dirty *= conversion_factor;
83 
84     usage.shared_clean *= conversion_factor;
85     usage.shared_dirty *= conversion_factor;
86 
87     usage.thp *= conversion_factor;
88 }
89 
90 // Returns true if the line was valid smaps stats line false otherwise.
parse_smaps_field(const char * line,MemUsage * stats)91 static bool parse_smaps_field(const char* line, MemUsage* stats) {
92     const char *end = line;
93 
94     // https://lore.kernel.org/patchwork/patch/1088579/ introduced tabs. Handle this case as well.
95     while (*end && !isspace(*end)) end++;
96     if (*end && end > line && *(end - 1) == ':') {
97         const char* c = end;
98         while (isspace(*c)) c++;
99         switch (line[0]) {
100             case 'P':
101                 if (strncmp(line, "Pss:", 4) == 0) {
102                     stats->pss = strtoull(c, nullptr, 10);
103                 } else if (strncmp(line, "Private_Clean:", 14) == 0) {
104                     uint64_t prcl = strtoull(c, nullptr, 10);
105                     stats->private_clean = prcl;
106                     stats->uss += prcl;
107                 } else if (strncmp(line, "Private_Dirty:", 14) == 0) {
108                     uint64_t prdi = strtoull(c, nullptr, 10);
109                     stats->private_dirty = prdi;
110                     stats->uss += prdi;
111                 } else if (strncmp(line, "Private_Hugetlb:", 16) == 0) {
112                     stats->private_hugetlb = strtoull(c, nullptr, 10);
113                 }
114                 break;
115             case 'S':
116                 if (strncmp(line, "Size:", 5) == 0) {
117                     stats->vss = strtoull(c, nullptr, 10);
118                 } else if (strncmp(line, "Shared_Clean:", 13) == 0) {
119                     stats->shared_clean = strtoull(c, nullptr, 10);
120                 } else if (strncmp(line, "Shared_Dirty:", 13) == 0) {
121                     stats->shared_dirty = strtoull(c, nullptr, 10);
122                 } else if (strncmp(line, "Swap:", 5) == 0) {
123                     stats->swap = strtoull(c, nullptr, 10);
124                 } else if (strncmp(line, "SwapPss:", 8) == 0) {
125                     stats->swap_pss = strtoull(c, nullptr, 10);
126                 } else if (strncmp(line, "ShmemPmdMapped:", 15) == 0) {
127                     stats->shmem_pmd_mapped = strtoull(c, nullptr, 10);
128                 } else if (strncmp(line, "Shared_Hugetlb:", 15) == 0) {
129                     stats->shared_hugetlb = strtoull(c, nullptr, 10);
130                 }
131                 break;
132             case 'R':
133                 if (strncmp(line, "Rss:", 4) == 0) {
134                     stats->rss = strtoull(c, nullptr, 10);
135                 }
136                 break;
137             case 'A':
138                 if (strncmp(line, "AnonHugePages:", 14) == 0) {
139                     stats->anon_huge_pages = strtoull(c, nullptr, 10);
140                 }
141                 break;
142             case 'F':
143                 if (strncmp(line, "FilePmdMapped:", 14) == 0) {
144                     stats->file_pmd_mapped = strtoull(c, nullptr, 10);
145                 }
146                 break;
147             case 'L':
148                 if (strncmp(line, "Locked:", 7) == 0) {
149                     stats->locked = strtoull(c, nullptr, 10);
150                 }
151                 break;
152         }
153         return true;
154     }
155 
156     return false;
157 }
158 
ResetWorkingSet(pid_t pid)159 bool ProcMemInfo::ResetWorkingSet(pid_t pid) {
160     std::string clear_refs_path = ::android::base::StringPrintf("/proc/%d/clear_refs", pid);
161     if (!::android::base::WriteStringToFile("1\n", clear_refs_path)) {
162         PLOG(ERROR) << "Failed to write to " << clear_refs_path;
163         return false;
164     }
165 
166     return true;
167 }
168 
ProcMemInfo(pid_t pid,bool get_wss,uint64_t pgflags,uint64_t pgflags_mask)169 ProcMemInfo::ProcMemInfo(pid_t pid, bool get_wss, uint64_t pgflags, uint64_t pgflags_mask)
170     : pid_(pid), get_wss_(get_wss), pgflags_(pgflags), pgflags_mask_(pgflags_mask) {}
171 
Maps()172 const std::vector<Vma>& ProcMemInfo::Maps() {
173     if (maps_.empty() && !ReadMaps(get_wss_)) {
174         LOG(ERROR) << "Failed to read maps for Process " << pid_;
175     }
176 
177     return maps_;
178 }
179 
MapsWithPageIdle()180 const std::vector<Vma>& ProcMemInfo::MapsWithPageIdle() {
181     if (maps_.empty() && !ReadMaps(get_wss_, true)) {
182         LOG(ERROR) << "Failed to read maps with page idle for Process " << pid_;
183     }
184 
185     return maps_;
186 }
187 
MapsWithoutUsageStats()188 const std::vector<Vma>& ProcMemInfo::MapsWithoutUsageStats() {
189     if (maps_.empty() && !ReadMaps(get_wss_, false, false)) {
190         LOG(ERROR) << "Failed to read maps for Process " << pid_;
191     }
192 
193     return maps_;
194 }
195 
Smaps(const std::string & path,bool collect_usage)196 const std::vector<Vma>& ProcMemInfo::Smaps(const std::string& path, bool collect_usage) {
197     if (!maps_.empty()) {
198         return maps_;
199     }
200 
201     auto collect_vmas = [&](const Vma& vma) {
202         if (std::find(g_excluded_vmas.begin(), g_excluded_vmas.end(), vma.name) ==
203                 g_excluded_vmas.end()) {
204             maps_.emplace_back(vma);
205             if (collect_usage) {
206                 add_mem_usage(&usage_, vma.usage);
207             }
208         }
209     };
210     if (path.empty() && !ForEachVma(collect_vmas)) {
211         LOG(ERROR) << "Failed to read smaps for Process " << pid_;
212         maps_.clear();
213     }
214 
215     if (!path.empty() && !ForEachVmaFromFile(path, collect_vmas)) {
216         LOG(ERROR) << "Failed to read smaps from file " << path;
217         maps_.clear();
218     }
219 
220     return maps_;
221 }
222 
Usage()223 const MemUsage& ProcMemInfo::Usage() {
224     if (get_wss_) {
225         LOG(WARNING) << "Trying to read process memory usage for " << pid_
226                      << " using invalid object";
227         return usage_;
228     }
229 
230     if (maps_.empty() && !ReadMaps(get_wss_)) {
231         LOG(ERROR) << "Failed to get memory usage for Process " << pid_;
232     }
233 
234     return usage_;
235 }
236 
Wss()237 const MemUsage& ProcMemInfo::Wss() {
238     if (!get_wss_) {
239         LOG(WARNING) << "Trying to read process working set for " << pid_
240                      << " using invalid object";
241         return usage_;
242     }
243 
244     if (maps_.empty() && !ReadMaps(get_wss_)) {
245         LOG(ERROR) << "Failed to get working set for Process " << pid_;
246     }
247 
248     return usage_;
249 }
250 
ForEachVma(const VmaCallback & callback,bool use_smaps)251 bool ProcMemInfo::ForEachVma(const VmaCallback& callback, bool use_smaps) {
252     std::string path =
253             ::android::base::StringPrintf("/proc/%d/%s", pid_, use_smaps ? "smaps" : "maps");
254     return ForEachVmaFromFile(path, callback, use_smaps);
255 }
256 
ForEachExistingVma(const VmaCallback & callback)257 bool ProcMemInfo::ForEachExistingVma(const VmaCallback& callback) {
258     if (maps_.empty()) {
259         return false;
260     }
261     for (auto& vma : maps_) {
262         callback(vma);
263     }
264     return true;
265 }
266 
ForEachVmaFromMaps(const VmaCallback & callback)267 bool ProcMemInfo::ForEachVmaFromMaps(const VmaCallback& callback) {
268     Vma vma;
269     auto vmaCollect = [&callback,&vma](const uint64_t start, uint64_t end, uint16_t flags,
270                             uint64_t pgoff, ino_t inode, const char* name, bool shared) {
271         vma.start = start;
272         vma.end = end;
273         vma.flags = flags;
274         vma.offset = pgoff;
275         vma.name = name;
276         vma.inode = inode;
277         vma.is_shared = shared;
278         callback(vma);
279     };
280 
281     bool success = ::android::procinfo::ReadProcessMaps(pid_, vmaCollect);
282 
283     return success;
284 }
285 
ForEachVmaFromMaps(const VmaCallback & callback,std::string & mapsBuffer)286 bool ProcMemInfo::ForEachVmaFromMaps(const VmaCallback& callback, std::string& mapsBuffer) {
287     Vma vma;
288     vma.name.reserve(256);
289     auto vmaCollect = [&callback,&vma](const uint64_t start, uint64_t end, uint16_t flags,
290                             uint64_t pgoff, ino_t inode, const char* name, bool shared) {
291         vma.start = start;
292         vma.end = end;
293         vma.flags = flags;
294         vma.offset = pgoff;
295         vma.name = name;
296         vma.inode = inode;
297         vma.is_shared = shared;
298         callback(vma);
299     };
300 
301     bool success = ::android::procinfo::ReadProcessMaps(pid_, vmaCollect, mapsBuffer);
302 
303     return success;
304 }
305 
SmapsOrRollup(MemUsage * stats) const306 bool ProcMemInfo::SmapsOrRollup(MemUsage* stats) const {
307     std::string path = ::android::base::StringPrintf(
308             "/proc/%d/%s", pid_, IsSmapsRollupSupported() ? "smaps_rollup" : "smaps");
309     return SmapsOrRollupFromFile(path, stats);
310 }
311 
SmapsOrRollupPss(uint64_t * pss) const312 bool ProcMemInfo::SmapsOrRollupPss(uint64_t* pss) const {
313     std::string path = ::android::base::StringPrintf(
314             "/proc/%d/%s", pid_, IsSmapsRollupSupported() ? "smaps_rollup" : "smaps");
315     return SmapsOrRollupPssFromFile(path, pss);
316 }
317 
SwapOffsets()318 const std::vector<uint64_t>& ProcMemInfo::SwapOffsets() {
319     if (get_wss_) {
320         LOG(WARNING) << "Trying to read process swap offsets for " << pid_
321                      << " using invalid object";
322         return swap_offsets_;
323     }
324 
325     if (maps_.empty() && !ReadMaps(get_wss_, false, true, true)) {
326         LOG(ERROR) << "Failed to get swap offsets for Process " << pid_;
327     }
328 
329     return swap_offsets_;
330 }
331 
PageMap(const Vma & vma,std::vector<uint64_t> * pagemap)332 bool ProcMemInfo::PageMap(const Vma& vma, std::vector<uint64_t>* pagemap) {
333     pagemap->clear();
334     std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid_);
335     ::android::base::unique_fd pagemap_fd(
336             TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC)));
337     if (pagemap_fd == -1) {
338         PLOG(ERROR) << "Failed to open " << pagemap_file;
339         return false;
340     }
341 
342     uint64_t nr_pages = (vma.end - vma.start) / getpagesize();
343     pagemap->resize(nr_pages);
344 
345     size_t bytes_to_read = sizeof(uint64_t) * nr_pages;
346     off64_t start_addr = (vma.start / getpagesize()) * sizeof(uint64_t);
347     ssize_t bytes_read = pread64(pagemap_fd, pagemap->data(), bytes_to_read, start_addr);
348     if (bytes_read == -1) {
349         PLOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_;
350         return false;
351     } else if (static_cast<size_t>(bytes_read) != bytes_to_read) {
352         LOG(ERROR) << "Failed to read page frames from page map for pid: " << pid_
353                    << ": read bytes " << bytes_read << " expected bytes " << bytes_to_read;
354         return false;
355     }
356 
357     return true;
358 }
359 
GetPagemapFd(pid_t pid)360 static int GetPagemapFd(pid_t pid) {
361     std::string pagemap_file = ::android::base::StringPrintf("/proc/%d/pagemap", pid);
362     int fd = TEMP_FAILURE_RETRY(open(pagemap_file.c_str(), O_RDONLY | O_CLOEXEC));
363     if (fd == -1) {
364         PLOG(ERROR) << "Failed to open " << pagemap_file;
365     }
366     return fd;
367 }
368 
ReadMaps(bool get_wss,bool use_pageidle,bool get_usage_stats,bool swap_only)369 bool ProcMemInfo::ReadMaps(bool get_wss, bool use_pageidle, bool get_usage_stats, bool swap_only) {
370     // Each object reads /proc/<pid>/maps only once. This is done to make sure programs that are
371     // running for the lifetime of the system can recycle the objects and don't have to
372     // unnecessarily retain and update this object in memory (which can get significantly large).
373     // E.g. A program that only needs to reset the working set will never all ->Maps(), ->Usage().
374     // E.g. A program that is monitoring smaps_rollup, may never call ->maps(), Usage(), so it
375     // doesn't make sense for us to parse and retain unnecessary memory accounting stats by default.
376     if (!maps_.empty()) return true;
377 
378     // parse and read /proc/<pid>/maps
379     std::string maps_file = ::android::base::StringPrintf("/proc/%d/maps", pid_);
380     if (!::android::procinfo::ReadMapFile(
381                 maps_file, [&](const android::procinfo::MapInfo& mapinfo) {
382                     if (std::find(g_excluded_vmas.begin(), g_excluded_vmas.end(), mapinfo.name) ==
383                             g_excluded_vmas.end()) {
384                       maps_.emplace_back(Vma(mapinfo.start, mapinfo.end,
385                                              mapinfo.pgoff, mapinfo.flags,
386                                              mapinfo.name,
387                                              mapinfo.inode, mapinfo.shared));
388                     }
389                 })) {
390         LOG(ERROR) << "Failed to parse " << maps_file;
391         maps_.clear();
392         return false;
393     }
394 
395     if (!get_usage_stats) {
396         return true;
397     }
398 
399     if (!GetUsageStats(get_wss, use_pageidle, swap_only)) {
400         maps_.clear();
401         return false;
402     }
403     return true;
404 }
405 
GetUsageStats(bool get_wss,bool use_pageidle,bool swap_only)406 bool ProcMemInfo::GetUsageStats(bool get_wss, bool use_pageidle, bool swap_only) {
407     ::android::base::unique_fd pagemap_fd(GetPagemapFd(pid_));
408     if (pagemap_fd == -1) {
409         return false;
410     }
411 
412     for (auto& vma : maps_) {
413         if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss, use_pageidle, swap_only)) {
414             LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
415                        << vma.end << "]";
416             return false;
417         }
418         add_mem_usage(&usage_, vma.usage);
419     }
420 
421     return true;
422 }
423 
FillInVmaStats(Vma & vma,bool use_kb)424 bool ProcMemInfo::FillInVmaStats(Vma& vma, bool use_kb) {
425     ::android::base::unique_fd pagemap_fd(GetPagemapFd(pid_));
426     if (pagemap_fd == -1) {
427         return false;
428     }
429 
430     if (!ReadVmaStats(pagemap_fd.get(), vma, get_wss_, false, false)) {
431         LOG(ERROR) << "Failed to read page map for vma " << vma.name << "[" << vma.start << "-"
432                    << vma.end << "]";
433         return false;
434     }
435     if (!use_kb) {
436         convert_usage_kb_to_b(vma.usage);
437     }
438     return true;
439 }
440 
ReadVmaStats(int pagemap_fd,Vma & vma,bool get_wss,bool use_pageidle,bool swap_only)441 bool ProcMemInfo::ReadVmaStats(int pagemap_fd, Vma& vma, bool get_wss, bool use_pageidle,
442                                bool swap_only) {
443     PageAcct& pinfo = PageAcct::Instance();
444     if (get_wss && use_pageidle && !pinfo.InitPageAcct(true)) {
445         LOG(ERROR) << "Failed to init idle page accounting";
446         return false;
447     }
448 
449     uint64_t pagesz_kb = getpagesize() / 1024;
450     size_t num_pages = (vma.end - vma.start) / (pagesz_kb * 1024);
451     size_t first_page = vma.start / (pagesz_kb * 1024);
452 
453     std::vector<uint64_t> page_cache;
454     size_t cur_page_cache_index = 0;
455     size_t num_in_page_cache = 0;
456     size_t num_leftover_pages = num_pages;
457     for (size_t cur_page = first_page; cur_page < first_page + num_pages; ++cur_page) {
458         // Cache page map data.
459         if (cur_page_cache_index == num_in_page_cache) {
460             static constexpr size_t kMaxPages = 2048;
461             num_leftover_pages -= num_in_page_cache;
462             if (num_leftover_pages > kMaxPages) {
463                 num_in_page_cache = kMaxPages;
464             } else {
465                 num_in_page_cache = num_leftover_pages;
466             }
467             page_cache.resize(num_in_page_cache);
468             size_t total_bytes = page_cache.size() * sizeof(uint64_t);
469             ssize_t bytes = pread64(pagemap_fd, page_cache.data(), total_bytes,
470                                     cur_page * sizeof(uint64_t));
471             if (bytes != total_bytes) {
472                 if (bytes == -1) {
473                     PLOG(ERROR) << "Failed to read page data at offset 0x" << std::hex
474                                 << cur_page * sizeof(uint64_t);
475                 } else {
476                     LOG(ERROR) << "Failed to read page data at offset 0x" << std::hex
477                                << cur_page * sizeof(uint64_t) << std::dec << " read bytes " << bytes
478                                << " expected bytes " << total_bytes;
479                 }
480                 return false;
481             }
482             cur_page_cache_index = 0;
483         }
484 
485         uint64_t page_info = page_cache[cur_page_cache_index++];
486         if (!PAGE_PRESENT(page_info) && !PAGE_SWAPPED(page_info)) continue;
487 
488         if (PAGE_SWAPPED(page_info)) {
489             vma.usage.swap += pagesz_kb;
490             swap_offsets_.emplace_back(PAGE_SWAP_OFFSET(page_info));
491             continue;
492         }
493 
494         if (swap_only)
495             continue;
496 
497         uint64_t page_frame = PAGE_PFN(page_info);
498         uint64_t cur_page_flags;
499         if (!pinfo.PageFlags(page_frame, &cur_page_flags)) {
500             LOG(ERROR) << "Failed to get page flags for " << page_frame << " in process " << pid_;
501             swap_offsets_.clear();
502             return false;
503         }
504 
505         if (KPAGEFLAG_THP(cur_page_flags)) {
506             vma.usage.thp += pagesz_kb;
507         }
508 
509         // skip unwanted pages from the count
510         if ((cur_page_flags & pgflags_mask_) != pgflags_) continue;
511 
512         uint64_t cur_page_counts;
513         if (!pinfo.PageMapCount(page_frame, &cur_page_counts)) {
514             LOG(ERROR) << "Failed to get page count for " << page_frame << " in process " << pid_;
515             swap_offsets_.clear();
516             return false;
517         }
518 
519         // Page was unmapped between the presence check at the beginning of the loop and here.
520         if (cur_page_counts == 0) {
521             continue;
522         }
523 
524         bool is_dirty = !!(cur_page_flags & (1 << KPF_DIRTY));
525         bool is_private = (cur_page_counts == 1);
526         // Working set
527         if (get_wss) {
528             bool is_referenced = use_pageidle ? (pinfo.IsPageIdle(page_frame) == 1)
529                                               : !!(cur_page_flags & (1 << KPF_REFERENCED));
530             if (!is_referenced) {
531                 continue;
532             }
533             // This effectively makes vss = rss for the working set is requested.
534             // The libpagemap implementation returns vss > rss for
535             // working set, which doesn't make sense.
536             vma.usage.vss += pagesz_kb;
537         }
538 
539         vma.usage.rss += pagesz_kb;
540         vma.usage.uss += is_private ? pagesz_kb : 0;
541         vma.usage.pss += pagesz_kb / cur_page_counts;
542         if (is_private) {
543             vma.usage.private_dirty += is_dirty ? pagesz_kb : 0;
544             vma.usage.private_clean += is_dirty ? 0 : pagesz_kb;
545         } else {
546             vma.usage.shared_dirty += is_dirty ? pagesz_kb : 0;
547             vma.usage.shared_clean += is_dirty ? 0 : pagesz_kb;
548         }
549     }
550     if (!get_wss) {
551         vma.usage.vss += pagesz_kb * num_pages;
552     }
553     return true;
554 }
555 
556 // Public APIs
ForEachVmaFromFile(const std::string & path,const VmaCallback & callback,bool read_smaps_fields)557 bool ForEachVmaFromFile(const std::string& path, const VmaCallback& callback,
558                         bool read_smaps_fields) {
559     auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
560     if (fp == nullptr) {
561         return false;
562     }
563 
564     char* line = nullptr;
565     bool parsing_vma = false;
566     ssize_t line_len;
567     size_t line_alloc = 0;
568     Vma vma;
569     while ((line_len = getline(&line, &line_alloc, fp.get())) > 0) {
570         // Make sure the line buffer terminates like a C string for ReadMapFile
571         line[line_len] = '\0';
572 
573         if (parsing_vma) {
574             if (parse_smaps_field(line, &vma.usage)) {
575                 // This was a stats field
576                 continue;
577             }
578 
579             // Done collecting stats, make the call back
580             callback(vma);
581             parsing_vma = false;
582         }
583 
584         vma.clear();
585         // If it has, we are looking for the vma stats
586         // 00400000-00409000 r-xp 00000000 fc:00 426998  /usr/lib/gvfs/gvfsd-http
587         if (!::android::procinfo::ReadMapFileContent(
588                     line, [&](const android::procinfo::MapInfo& mapinfo) {
589                         vma.start = mapinfo.start;
590                         vma.end = mapinfo.end;
591                         vma.flags = mapinfo.flags;
592                         vma.offset = mapinfo.pgoff;
593                         vma.name = mapinfo.name;
594                         vma.inode = mapinfo.inode;
595                         vma.is_shared = mapinfo.shared;
596                     })) {
597             // free getline() managed buffer
598             free(line);
599             LOG(ERROR) << "Failed to parse " << path;
600             return false;
601         }
602         if (read_smaps_fields) {
603             parsing_vma = true;
604         } else {
605             // Done collecting stats, make the call back
606             callback(vma);
607         }
608     }
609 
610     // free getline() managed buffer
611     free(line);
612 
613     if (parsing_vma) {
614         callback(vma);
615     }
616 
617     return true;
618 }
619 
620 enum smaps_rollup_support { UNTRIED, SUPPORTED, UNSUPPORTED };
621 
622 static std::atomic<smaps_rollup_support> g_rollup_support = UNTRIED;
623 
IsSmapsRollupSupported()624 bool IsSmapsRollupSupported() {
625     // Similar to OpenSmapsOrRollup checks from android_os_Debug.cpp, except
626     // the method only checks if rollup is supported and returns the status
627     // right away.
628     enum smaps_rollup_support rollup_support = g_rollup_support.load(std::memory_order_relaxed);
629     if (rollup_support != UNTRIED) {
630         return rollup_support == SUPPORTED;
631     }
632 
633     // Check the calling process for smaps_rollup since it is guaranteed to be alive
634     if (access("/proc/self/smaps_rollup", F_OK | R_OK)) {
635         g_rollup_support.store(UNSUPPORTED, std::memory_order_relaxed);
636         return false;
637     }
638 
639     g_rollup_support.store(SUPPORTED, std::memory_order_relaxed);
640     LOG(INFO) << "Using smaps_rollup for pss collection";
641     return true;
642 }
643 
SmapsOrRollupFromFile(const std::string & path,MemUsage * stats)644 bool SmapsOrRollupFromFile(const std::string& path, MemUsage* stats) {
645     auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
646     if (fp == nullptr) {
647         return false;
648     }
649 
650     char* line = nullptr;
651     size_t line_alloc = 0;
652     stats->clear();
653     while (getline(&line, &line_alloc, fp.get()) > 0) {
654         switch (line[0]) {
655             case 'P':
656                 if (strncmp(line, "Pss:", 4) == 0) {
657                     char* c = line + 4;
658                     stats->pss += strtoull(c, nullptr, 10);
659                 } else if (strncmp(line, "Private_Clean:", 14) == 0) {
660                     char* c = line + 14;
661                     uint64_t prcl = strtoull(c, nullptr, 10);
662                     stats->private_clean += prcl;
663                     stats->uss += prcl;
664                 } else if (strncmp(line, "Private_Dirty:", 14) == 0) {
665                     char* c = line + 14;
666                     uint64_t prdi = strtoull(c, nullptr, 10);
667                     stats->private_dirty += prdi;
668                     stats->uss += prdi;
669                 }
670                 break;
671             case 'R':
672                 if (strncmp(line, "Rss:", 4) == 0) {
673                     char* c = line + 4;
674                     stats->rss += strtoull(c, nullptr, 10);
675                 }
676                 break;
677             case 'S':
678                 if (strncmp(line, "SwapPss:", 8) == 0) {
679                     char* c = line + 8;
680                     stats->swap_pss += strtoull(c, nullptr, 10);
681                 }
682                 break;
683         }
684     }
685 
686     // free getline() managed buffer
687     free(line);
688     return true;
689 }
690 
SmapsOrRollupPssFromFile(const std::string & path,uint64_t * pss)691 bool SmapsOrRollupPssFromFile(const std::string& path, uint64_t* pss) {
692     auto fp = std::unique_ptr<FILE, decltype(&fclose)>{fopen(path.c_str(), "re"), fclose};
693     if (fp == nullptr) {
694         return false;
695     }
696     *pss = 0;
697     char* line = nullptr;
698     size_t line_alloc = 0;
699     while (getline(&line, &line_alloc, fp.get()) > 0) {
700         uint64_t v;
701         if (sscanf(line, "Pss: %" SCNu64 " kB", &v) == 1) {
702             *pss += v;
703         }
704     }
705 
706     // free getline() managed buffer
707     free(line);
708     return true;
709 }
710 
GetFormat(std::string_view arg)711 Format GetFormat(std::string_view arg) {
712     if (arg == "json") {
713         return Format::JSON;
714     }
715     if (arg == "csv") {
716         return Format::CSV;
717     }
718     if (arg == "raw") {
719         return Format::RAW;
720     }
721     return Format::INVALID;
722 }
723 
EscapeCsvString(const std::string & raw)724 std::string EscapeCsvString(const std::string& raw) {
725     std::string ret;
726     for (auto it = raw.cbegin(); it != raw.cend(); it++) {
727         switch (*it) {
728             case '"':
729                 ret += "\"";
730                 break;
731             default:
732                 ret += *it;
733                 break;
734         }
735     }
736     return '"' + ret + '"';
737 }
738 
EscapeJsonString(const std::string & raw)739 std::string EscapeJsonString(const std::string& raw) {
740     std::string ret;
741     for (auto it = raw.cbegin(); it != raw.cend(); it++) {
742         switch (*it) {
743             case '\\':
744                 ret += "\\\\";
745                 break;
746             case '"':
747                 ret += "\\\"";
748                 break;
749             case '/':
750                 ret += "\\/";
751                 break;
752             case '\b':
753                 ret += "\\b";
754                 break;
755             case '\f':
756                 ret += "\\f";
757                 break;
758             case '\n':
759                 ret += "\\n";
760                 break;
761             case '\r':
762                 ret += "\\r";
763                 break;
764             case '\t':
765                 ret += "\\t";
766                 break;
767             default:
768                 ret += *it;
769                 break;
770         }
771     }
772     return '"' + ret + '"';
773 }
774 
775 }  // namespace meminfo
776 }  // namespace android
777