• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (C) 2014 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 <err.h>
18 #include <errno.h>
19 #include <fcntl.h>
20 #include <inttypes.h>
21 #include <stdint.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <sys/types.h>
25 #include <sys/stat.h>
26 #include <unistd.h>
27 
28 #include <android-base/unique_fd.h>
29 
30 #include "LineBuffer.h"
31 #include "NativeInfo.h"
32 
33 // This function is not re-entrant since it uses a static buffer for
34 // the line data.
GetNativeInfo(int smaps_fd,size_t * pss_bytes,size_t * va_bytes)35 void GetNativeInfo(int smaps_fd, size_t* pss_bytes, size_t* va_bytes) {
36   static char map_buffer[65535];
37   LineBuffer line_buf(smaps_fd, map_buffer, sizeof(map_buffer));
38   char* line;
39   size_t total_pss_bytes = 0;
40   size_t total_va_bytes = 0;
41   size_t line_len;
42   bool native_map = false;
43   while (line_buf.GetLine(&line, &line_len)) {
44     uintptr_t start, end;
45     int name_pos;
46     size_t native_pss_kB;
47     if (sscanf(line, "%" SCNxPTR "-%" SCNxPTR " %*4s %*x %*x:%*x %*d %n",
48         &start, &end, &name_pos) == 2) {
49       if (strcmp(line + name_pos, "[anon:libc_malloc]") == 0 ||
50           strcmp(line + name_pos, "[heap]") == 0) {
51         total_va_bytes += end - start;
52         native_map = true;
53       } else {
54         native_map = false;
55       }
56     } else if (native_map && sscanf(line, "Pss: %zu", &native_pss_kB) == 1) {
57       total_pss_bytes += native_pss_kB * 1024;
58     }
59   }
60   *pss_bytes = total_pss_bytes;
61   *va_bytes = total_va_bytes;
62 }
63 
PrintNativeInfo(const char * preamble)64 void PrintNativeInfo(const char* preamble) {
65   size_t pss_bytes;
66   size_t va_bytes;
67 
68   android::base::unique_fd smaps_fd(open("/proc/self/smaps", O_RDONLY));
69   if (smaps_fd == -1) {
70     err(1, "Cannot open /proc/self/smaps: %s\n", strerror(errno));
71   }
72 
73   GetNativeInfo(smaps_fd, &pss_bytes, &va_bytes);
74   printf("%sNative PSS: %zu bytes %0.2fMB\n", preamble, pss_bytes, pss_bytes/(1024*1024.0));
75   printf("%sNative VA Space: %zu bytes %0.2fMB\n", preamble, va_bytes, va_bytes/(1024*1024.0));
76   fflush(stdout);
77 }
78