1 /*
2  * Copyright (C) 2007 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 #define LOG_TAG "android.os.Debug"
18 
19 #include <assert.h>
20 #include <ctype.h>
21 #include <errno.h>
22 #include <fcntl.h>
23 #include <inttypes.h>
24 #include <malloc.h>
25 #include <stdio.h>
26 #include <stdlib.h>
27 #include <string.h>
28 #include <sys/time.h>
29 #include <time.h>
30 #include <unistd.h>
31 
32 #include <iomanip>
33 #include <string>
34 #include <vector>
35 
36 #include <android-base/logging.h>
37 #include <bionic/malloc.h>
38 #include <debuggerd/client.h>
39 #include <log/log.h>
40 #include <utils/misc.h>
41 #include <utils/String8.h>
42 
43 #include <nativehelper/JNIHelp.h>
44 #include <nativehelper/ScopedUtfChars.h>
45 #include "jni.h"
46 #include <dmabufinfo/dmabufinfo.h>
47 #include <meminfo/procmeminfo.h>
48 #include <meminfo/sysmeminfo.h>
49 #include <memtrack/memtrack.h>
50 #include <memunreachable/memunreachable.h>
51 #include <android-base/strings.h>
52 #include "android_os_Debug.h"
53 #include <vintf/VintfObject.h>
54 
55 namespace android
56 {
57 
58 enum {
59     HEAP_UNKNOWN,
60     HEAP_DALVIK,
61     HEAP_NATIVE,
62 
63     HEAP_DALVIK_OTHER,
64     HEAP_STACK,
65     HEAP_CURSOR,
66     HEAP_ASHMEM,
67     HEAP_GL_DEV,
68     HEAP_UNKNOWN_DEV,
69     HEAP_SO,
70     HEAP_JAR,
71     HEAP_APK,
72     HEAP_TTF,
73     HEAP_DEX,
74     HEAP_OAT,
75     HEAP_ART,
76     HEAP_UNKNOWN_MAP,
77     HEAP_GRAPHICS,
78     HEAP_GL,
79     HEAP_OTHER_MEMTRACK,
80 
81     // Dalvik extra sections (heap).
82     HEAP_DALVIK_NORMAL,
83     HEAP_DALVIK_LARGE,
84     HEAP_DALVIK_ZYGOTE,
85     HEAP_DALVIK_NON_MOVING,
86 
87     // Dalvik other extra sections.
88     HEAP_DALVIK_OTHER_LINEARALLOC,
89     HEAP_DALVIK_OTHER_ACCOUNTING,
90     HEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE,
91     HEAP_DALVIK_OTHER_APP_CODE_CACHE,
92     HEAP_DALVIK_OTHER_COMPILER_METADATA,
93     HEAP_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE,
94 
95     // Boot vdex / app dex / app vdex
96     HEAP_DEX_BOOT_VDEX,
97     HEAP_DEX_APP_DEX,
98     HEAP_DEX_APP_VDEX,
99 
100     // App art, boot art.
101     HEAP_ART_APP,
102     HEAP_ART_BOOT,
103 
104     _NUM_HEAP,
105     _NUM_EXCLUSIVE_HEAP = HEAP_OTHER_MEMTRACK+1,
106     _NUM_CORE_HEAP = HEAP_NATIVE+1
107 };
108 
109 struct stat_fields {
110     jfieldID pss_field;
111     jfieldID pssSwappable_field;
112     jfieldID rss_field;
113     jfieldID privateDirty_field;
114     jfieldID sharedDirty_field;
115     jfieldID privateClean_field;
116     jfieldID sharedClean_field;
117     jfieldID swappedOut_field;
118     jfieldID swappedOutPss_field;
119 };
120 
121 struct stat_field_names {
122     const char* pss_name;
123     const char* pssSwappable_name;
124     const char* rss_name;
125     const char* privateDirty_name;
126     const char* sharedDirty_name;
127     const char* privateClean_name;
128     const char* sharedClean_name;
129     const char* swappedOut_name;
130     const char* swappedOutPss_name;
131 };
132 
133 static stat_fields stat_fields[_NUM_CORE_HEAP];
134 
135 static stat_field_names stat_field_names[_NUM_CORE_HEAP] = {
136     { "otherPss", "otherSwappablePss", "otherRss", "otherPrivateDirty", "otherSharedDirty",
137         "otherPrivateClean", "otherSharedClean", "otherSwappedOut", "otherSwappedOutPss" },
138     { "dalvikPss", "dalvikSwappablePss", "dalvikRss", "dalvikPrivateDirty", "dalvikSharedDirty",
139         "dalvikPrivateClean", "dalvikSharedClean", "dalvikSwappedOut", "dalvikSwappedOutPss" },
140     { "nativePss", "nativeSwappablePss", "nativeRss", "nativePrivateDirty", "nativeSharedDirty",
141         "nativePrivateClean", "nativeSharedClean", "nativeSwappedOut", "nativeSwappedOutPss" }
142 };
143 
144 static jfieldID otherStats_field;
145 static jfieldID hasSwappedOutPss_field;
146 
147 struct stats_t {
148     int pss;
149     int swappablePss;
150     int rss;
151     int privateDirty;
152     int sharedDirty;
153     int privateClean;
154     int sharedClean;
155     int swappedOut;
156     int swappedOutPss;
157 };
158 
159 #define BINDER_STATS "/proc/binder/stats"
160 
android_os_Debug_getNativeHeapSize(JNIEnv * env,jobject clazz)161 static jlong android_os_Debug_getNativeHeapSize(JNIEnv *env, jobject clazz)
162 {
163     struct mallinfo info = mallinfo();
164     return (jlong) info.usmblks;
165 }
166 
android_os_Debug_getNativeHeapAllocatedSize(JNIEnv * env,jobject clazz)167 static jlong android_os_Debug_getNativeHeapAllocatedSize(JNIEnv *env, jobject clazz)
168 {
169     struct mallinfo info = mallinfo();
170     return (jlong) info.uordblks;
171 }
172 
android_os_Debug_getNativeHeapFreeSize(JNIEnv * env,jobject clazz)173 static jlong android_os_Debug_getNativeHeapFreeSize(JNIEnv *env, jobject clazz)
174 {
175     struct mallinfo info = mallinfo();
176     return (jlong) info.fordblks;
177 }
178 
179 // Container used to retrieve graphics memory pss
180 struct graphics_memory_pss
181 {
182     int graphics;
183     int gl;
184     int other;
185 };
186 
187 /*
188  * Uses libmemtrack to retrieve graphics memory that the process is using.
189  * Any graphics memory reported in /proc/pid/smaps is not included here.
190  */
read_memtrack_memory(struct memtrack_proc * p,int pid,struct graphics_memory_pss * graphics_mem)191 static int read_memtrack_memory(struct memtrack_proc* p, int pid,
192         struct graphics_memory_pss* graphics_mem)
193 {
194     int err = memtrack_proc_get(p, pid);
195     if (err != 0) {
196         // The memtrack HAL may not be available, do not log to avoid flooding
197         // logcat.
198         return err;
199     }
200 
201     ssize_t pss = memtrack_proc_graphics_pss(p);
202     if (pss < 0) {
203         ALOGW("failed to get graphics pss: %zd", pss);
204         return pss;
205     }
206     graphics_mem->graphics = pss / 1024;
207 
208     pss = memtrack_proc_gl_pss(p);
209     if (pss < 0) {
210         ALOGW("failed to get gl pss: %zd", pss);
211         return pss;
212     }
213     graphics_mem->gl = pss / 1024;
214 
215     pss = memtrack_proc_other_pss(p);
216     if (pss < 0) {
217         ALOGW("failed to get other pss: %zd", pss);
218         return pss;
219     }
220     graphics_mem->other = pss / 1024;
221 
222     return 0;
223 }
224 
225 /*
226  * Retrieves the graphics memory that is unaccounted for in /proc/pid/smaps.
227  */
read_memtrack_memory(int pid,struct graphics_memory_pss * graphics_mem)228 static int read_memtrack_memory(int pid, struct graphics_memory_pss* graphics_mem)
229 {
230     struct memtrack_proc* p = memtrack_proc_new();
231     if (p == NULL) {
232         ALOGW("failed to create memtrack_proc");
233         return -1;
234     }
235 
236     int err = read_memtrack_memory(p, pid, graphics_mem);
237     memtrack_proc_destroy(p);
238     return err;
239 }
240 
load_maps(int pid,stats_t * stats,bool * foundSwapPss)241 static bool load_maps(int pid, stats_t* stats, bool* foundSwapPss)
242 {
243     *foundSwapPss = false;
244     uint64_t prev_end = 0;
245     int prev_heap = HEAP_UNKNOWN;
246 
247     std::string smaps_path = base::StringPrintf("/proc/%d/smaps", pid);
248     auto vma_scan = [&](const meminfo::Vma& vma) {
249         int which_heap = HEAP_UNKNOWN;
250         int sub_heap = HEAP_UNKNOWN;
251         bool is_swappable = false;
252         std::string name;
253         if (base::EndsWith(vma.name, " (deleted)")) {
254             name = vma.name.substr(0, vma.name.size() - strlen(" (deleted)"));
255         } else {
256             name = vma.name;
257         }
258 
259         uint32_t namesz = name.size();
260         if (base::StartsWith(name, "[heap]")) {
261             which_heap = HEAP_NATIVE;
262         } else if (base::StartsWith(name, "[anon:libc_malloc]")) {
263             which_heap = HEAP_NATIVE;
264         } else if (base::StartsWith(name, "[anon:scudo:")) {
265             which_heap = HEAP_NATIVE;
266         } else if (base::StartsWith(name, "[anon:GWP-ASan")) {
267             which_heap = HEAP_NATIVE;
268         } else if (base::StartsWith(name, "[stack")) {
269             which_heap = HEAP_STACK;
270         } else if (base::StartsWith(name, "[anon:stack_and_tls:")) {
271             which_heap = HEAP_STACK;
272         } else if (base::EndsWith(name, ".so")) {
273             which_heap = HEAP_SO;
274             is_swappable = true;
275         } else if (base::EndsWith(name, ".jar")) {
276             which_heap = HEAP_JAR;
277             is_swappable = true;
278         } else if (base::EndsWith(name, ".apk")) {
279             which_heap = HEAP_APK;
280             is_swappable = true;
281         } else if (base::EndsWith(name, ".ttf")) {
282             which_heap = HEAP_TTF;
283             is_swappable = true;
284         } else if ((base::EndsWith(name, ".odex")) ||
285                 (namesz > 4 && strstr(name.c_str(), ".dex") != nullptr)) {
286             which_heap = HEAP_DEX;
287             sub_heap = HEAP_DEX_APP_DEX;
288             is_swappable = true;
289         } else if (base::EndsWith(name, ".vdex")) {
290             which_heap = HEAP_DEX;
291             // Handle system@framework@boot and system/framework/boot|apex
292             if ((strstr(name.c_str(), "@boot") != nullptr) ||
293                     (strstr(name.c_str(), "/boot") != nullptr) ||
294                     (strstr(name.c_str(), "/apex") != nullptr)) {
295                 sub_heap = HEAP_DEX_BOOT_VDEX;
296             } else {
297                 sub_heap = HEAP_DEX_APP_VDEX;
298             }
299             is_swappable = true;
300         } else if (base::EndsWith(name, ".oat")) {
301             which_heap = HEAP_OAT;
302             is_swappable = true;
303         } else if (base::EndsWith(name, ".art") || base::EndsWith(name, ".art]")) {
304             which_heap = HEAP_ART;
305             // Handle system@framework@boot* and system/framework/boot|apex*
306             if ((strstr(name.c_str(), "@boot") != nullptr) ||
307                     (strstr(name.c_str(), "/boot") != nullptr) ||
308                     (strstr(name.c_str(), "/apex") != nullptr)) {
309                 sub_heap = HEAP_ART_BOOT;
310             } else {
311                 sub_heap = HEAP_ART_APP;
312             }
313             is_swappable = true;
314         } else if (base::StartsWith(name, "/dev/")) {
315             which_heap = HEAP_UNKNOWN_DEV;
316             if (base::StartsWith(name, "/dev/kgsl-3d0")) {
317                 which_heap = HEAP_GL_DEV;
318             } else if (base::StartsWith(name, "/dev/ashmem/CursorWindow")) {
319                 which_heap = HEAP_CURSOR;
320             } else if (base::StartsWith(name, "/dev/ashmem/jit-zygote-cache")) {
321                 which_heap = HEAP_DALVIK_OTHER;
322                 sub_heap = HEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE;
323             } else if (base::StartsWith(name, "/dev/ashmem")) {
324                 which_heap = HEAP_ASHMEM;
325             }
326         } else if (base::StartsWith(name, "/memfd:jit-cache")) {
327           which_heap = HEAP_DALVIK_OTHER;
328           sub_heap = HEAP_DALVIK_OTHER_APP_CODE_CACHE;
329         } else if (base::StartsWith(name, "/memfd:jit-zygote-cache")) {
330           which_heap = HEAP_DALVIK_OTHER;
331           sub_heap = HEAP_DALVIK_OTHER_ZYGOTE_CODE_CACHE;
332         } else if (base::StartsWith(name, "[anon:")) {
333             which_heap = HEAP_UNKNOWN;
334             if (base::StartsWith(name, "[anon:dalvik-")) {
335                 which_heap = HEAP_DALVIK_OTHER;
336                 if (base::StartsWith(name, "[anon:dalvik-LinearAlloc")) {
337                     sub_heap = HEAP_DALVIK_OTHER_LINEARALLOC;
338                 } else if (base::StartsWith(name, "[anon:dalvik-alloc space") ||
339                         base::StartsWith(name, "[anon:dalvik-main space")) {
340                     // This is the regular Dalvik heap.
341                     which_heap = HEAP_DALVIK;
342                     sub_heap = HEAP_DALVIK_NORMAL;
343                 } else if (base::StartsWith(name,
344                             "[anon:dalvik-large object space") ||
345                         base::StartsWith(
346                             name, "[anon:dalvik-free list large object space")) {
347                     which_heap = HEAP_DALVIK;
348                     sub_heap = HEAP_DALVIK_LARGE;
349                 } else if (base::StartsWith(name, "[anon:dalvik-non moving space")) {
350                     which_heap = HEAP_DALVIK;
351                     sub_heap = HEAP_DALVIK_NON_MOVING;
352                 } else if (base::StartsWith(name, "[anon:dalvik-zygote space")) {
353                     which_heap = HEAP_DALVIK;
354                     sub_heap = HEAP_DALVIK_ZYGOTE;
355                 } else if (base::StartsWith(name, "[anon:dalvik-indirect ref")) {
356                     sub_heap = HEAP_DALVIK_OTHER_INDIRECT_REFERENCE_TABLE;
357                 } else if (base::StartsWith(name, "[anon:dalvik-jit-code-cache") ||
358                         base::StartsWith(name, "[anon:dalvik-data-code-cache")) {
359                     sub_heap = HEAP_DALVIK_OTHER_APP_CODE_CACHE;
360                 } else if (base::StartsWith(name, "[anon:dalvik-CompilerMetadata")) {
361                     sub_heap = HEAP_DALVIK_OTHER_COMPILER_METADATA;
362                 } else {
363                     sub_heap = HEAP_DALVIK_OTHER_ACCOUNTING;  // Default to accounting.
364                 }
365             }
366         } else if (namesz > 0) {
367             which_heap = HEAP_UNKNOWN_MAP;
368         } else if (vma.start == prev_end && prev_heap == HEAP_SO) {
369             // bss section of a shared library
370             which_heap = HEAP_SO;
371         }
372 
373         prev_end = vma.end;
374         prev_heap = which_heap;
375 
376         const meminfo::MemUsage& usage = vma.usage;
377         if (usage.swap_pss > 0 && *foundSwapPss != true) {
378             *foundSwapPss = true;
379         }
380 
381         uint64_t swapable_pss = 0;
382         if (is_swappable && (usage.pss > 0)) {
383             float sharing_proportion = 0.0;
384             if ((usage.shared_clean > 0) || (usage.shared_dirty > 0)) {
385                 sharing_proportion = (usage.pss - usage.uss) / (usage.shared_clean + usage.shared_dirty);
386             }
387             swapable_pss = (sharing_proportion * usage.shared_clean) + usage.private_clean;
388         }
389 
390         stats[which_heap].pss += usage.pss;
391         stats[which_heap].swappablePss += swapable_pss;
392         stats[which_heap].rss += usage.rss;
393         stats[which_heap].privateDirty += usage.private_dirty;
394         stats[which_heap].sharedDirty += usage.shared_dirty;
395         stats[which_heap].privateClean += usage.private_clean;
396         stats[which_heap].sharedClean += usage.shared_clean;
397         stats[which_heap].swappedOut += usage.swap;
398         stats[which_heap].swappedOutPss += usage.swap_pss;
399         if (which_heap == HEAP_DALVIK || which_heap == HEAP_DALVIK_OTHER ||
400                 which_heap == HEAP_DEX || which_heap == HEAP_ART) {
401             stats[sub_heap].pss += usage.pss;
402             stats[sub_heap].swappablePss += swapable_pss;
403             stats[sub_heap].rss += usage.rss;
404             stats[sub_heap].privateDirty += usage.private_dirty;
405             stats[sub_heap].sharedDirty += usage.shared_dirty;
406             stats[sub_heap].privateClean += usage.private_clean;
407             stats[sub_heap].sharedClean += usage.shared_clean;
408             stats[sub_heap].swappedOut += usage.swap;
409             stats[sub_heap].swappedOutPss += usage.swap_pss;
410         }
411     };
412 
413     return meminfo::ForEachVmaFromFile(smaps_path, vma_scan);
414 }
415 
android_os_Debug_getDirtyPagesPid(JNIEnv * env,jobject clazz,jint pid,jobject object)416 static jboolean android_os_Debug_getDirtyPagesPid(JNIEnv *env, jobject clazz,
417         jint pid, jobject object)
418 {
419     bool foundSwapPss;
420     stats_t stats[_NUM_HEAP];
421     memset(&stats, 0, sizeof(stats));
422 
423     if (!load_maps(pid, stats, &foundSwapPss)) {
424         return JNI_FALSE;
425     }
426 
427     struct graphics_memory_pss graphics_mem;
428     if (read_memtrack_memory(pid, &graphics_mem) == 0) {
429         stats[HEAP_GRAPHICS].pss = graphics_mem.graphics;
430         stats[HEAP_GRAPHICS].privateDirty = graphics_mem.graphics;
431         stats[HEAP_GRAPHICS].rss = graphics_mem.graphics;
432         stats[HEAP_GL].pss = graphics_mem.gl;
433         stats[HEAP_GL].privateDirty = graphics_mem.gl;
434         stats[HEAP_GL].rss = graphics_mem.gl;
435         stats[HEAP_OTHER_MEMTRACK].pss = graphics_mem.other;
436         stats[HEAP_OTHER_MEMTRACK].privateDirty = graphics_mem.other;
437         stats[HEAP_OTHER_MEMTRACK].rss = graphics_mem.other;
438     }
439 
440     for (int i=_NUM_CORE_HEAP; i<_NUM_EXCLUSIVE_HEAP; i++) {
441         stats[HEAP_UNKNOWN].pss += stats[i].pss;
442         stats[HEAP_UNKNOWN].swappablePss += stats[i].swappablePss;
443         stats[HEAP_UNKNOWN].rss += stats[i].rss;
444         stats[HEAP_UNKNOWN].privateDirty += stats[i].privateDirty;
445         stats[HEAP_UNKNOWN].sharedDirty += stats[i].sharedDirty;
446         stats[HEAP_UNKNOWN].privateClean += stats[i].privateClean;
447         stats[HEAP_UNKNOWN].sharedClean += stats[i].sharedClean;
448         stats[HEAP_UNKNOWN].swappedOut += stats[i].swappedOut;
449         stats[HEAP_UNKNOWN].swappedOutPss += stats[i].swappedOutPss;
450     }
451 
452     for (int i=0; i<_NUM_CORE_HEAP; i++) {
453         env->SetIntField(object, stat_fields[i].pss_field, stats[i].pss);
454         env->SetIntField(object, stat_fields[i].pssSwappable_field, stats[i].swappablePss);
455         env->SetIntField(object, stat_fields[i].rss_field, stats[i].rss);
456         env->SetIntField(object, stat_fields[i].privateDirty_field, stats[i].privateDirty);
457         env->SetIntField(object, stat_fields[i].sharedDirty_field, stats[i].sharedDirty);
458         env->SetIntField(object, stat_fields[i].privateClean_field, stats[i].privateClean);
459         env->SetIntField(object, stat_fields[i].sharedClean_field, stats[i].sharedClean);
460         env->SetIntField(object, stat_fields[i].swappedOut_field, stats[i].swappedOut);
461         env->SetIntField(object, stat_fields[i].swappedOutPss_field, stats[i].swappedOutPss);
462     }
463 
464 
465     env->SetBooleanField(object, hasSwappedOutPss_field, foundSwapPss);
466     jintArray otherIntArray = (jintArray)env->GetObjectField(object, otherStats_field);
467 
468     jint* otherArray = (jint*)env->GetPrimitiveArrayCritical(otherIntArray, 0);
469     if (otherArray == NULL) {
470         return JNI_FALSE;
471     }
472 
473     int j=0;
474     for (int i=_NUM_CORE_HEAP; i<_NUM_HEAP; i++) {
475         otherArray[j++] = stats[i].pss;
476         otherArray[j++] = stats[i].swappablePss;
477         otherArray[j++] = stats[i].rss;
478         otherArray[j++] = stats[i].privateDirty;
479         otherArray[j++] = stats[i].sharedDirty;
480         otherArray[j++] = stats[i].privateClean;
481         otherArray[j++] = stats[i].sharedClean;
482         otherArray[j++] = stats[i].swappedOut;
483         otherArray[j++] = stats[i].swappedOutPss;
484     }
485 
486     env->ReleasePrimitiveArrayCritical(otherIntArray, otherArray, 0);
487     return JNI_TRUE;
488 }
489 
android_os_Debug_getDirtyPages(JNIEnv * env,jobject clazz,jobject object)490 static void android_os_Debug_getDirtyPages(JNIEnv *env, jobject clazz, jobject object)
491 {
492     android_os_Debug_getDirtyPagesPid(env, clazz, getpid(), object);
493 }
494 
android_os_Debug_getPssPid(JNIEnv * env,jobject clazz,jint pid,jlongArray outUssSwapPssRss,jlongArray outMemtrack)495 static jlong android_os_Debug_getPssPid(JNIEnv *env, jobject clazz, jint pid,
496         jlongArray outUssSwapPssRss, jlongArray outMemtrack)
497 {
498     jlong pss = 0;
499     jlong rss = 0;
500     jlong swapPss = 0;
501     jlong uss = 0;
502     jlong memtrack = 0;
503 
504     struct graphics_memory_pss graphics_mem;
505     if (read_memtrack_memory(pid, &graphics_mem) == 0) {
506         pss = uss = rss = memtrack = graphics_mem.graphics + graphics_mem.gl + graphics_mem.other;
507     }
508 
509     ::android::meminfo::ProcMemInfo proc_mem(pid);
510     ::android::meminfo::MemUsage stats;
511     if (proc_mem.SmapsOrRollup(&stats)) {
512         pss += stats.pss;
513         uss += stats.uss;
514         rss += stats.rss;
515         swapPss = stats.swap_pss;
516         pss += swapPss; // Also in swap, those pages would be accounted as Pss without SWAP
517     } else {
518         return 0;
519     }
520 
521     if (outUssSwapPssRss != NULL) {
522         if (env->GetArrayLength(outUssSwapPssRss) >= 1) {
523             jlong* outUssSwapPssRssArray = env->GetLongArrayElements(outUssSwapPssRss, 0);
524             if (outUssSwapPssRssArray != NULL) {
525                 outUssSwapPssRssArray[0] = uss;
526                 if (env->GetArrayLength(outUssSwapPssRss) >= 2) {
527                     outUssSwapPssRssArray[1] = swapPss;
528                 }
529                 if (env->GetArrayLength(outUssSwapPssRss) >= 3) {
530                     outUssSwapPssRssArray[2] = rss;
531                 }
532             }
533             env->ReleaseLongArrayElements(outUssSwapPssRss, outUssSwapPssRssArray, 0);
534         }
535     }
536 
537     if (outMemtrack != NULL) {
538         if (env->GetArrayLength(outMemtrack) >= 1) {
539             jlong* outMemtrackArray = env->GetLongArrayElements(outMemtrack, 0);
540             if (outMemtrackArray != NULL) {
541                 outMemtrackArray[0] = memtrack;
542             }
543             env->ReleaseLongArrayElements(outMemtrack, outMemtrackArray, 0);
544         }
545     }
546 
547     return pss;
548 }
549 
android_os_Debug_getPss(JNIEnv * env,jobject clazz)550 static jlong android_os_Debug_getPss(JNIEnv *env, jobject clazz)
551 {
552     return android_os_Debug_getPssPid(env, clazz, getpid(), NULL, NULL);
553 }
554 
555 // The 1:1 mapping of MEMINFO_* enums here must match with the constants from
556 // Debug.java.
557 enum {
558     MEMINFO_TOTAL,
559     MEMINFO_FREE,
560     MEMINFO_BUFFERS,
561     MEMINFO_CACHED,
562     MEMINFO_SHMEM,
563     MEMINFO_SLAB,
564     MEMINFO_SLAB_RECLAIMABLE,
565     MEMINFO_SLAB_UNRECLAIMABLE,
566     MEMINFO_SWAP_TOTAL,
567     MEMINFO_SWAP_FREE,
568     MEMINFO_ZRAM_TOTAL,
569     MEMINFO_MAPPED,
570     MEMINFO_VMALLOC_USED,
571     MEMINFO_PAGE_TABLES,
572     MEMINFO_KERNEL_STACK,
573     MEMINFO_KERNEL_RECLAIMABLE,
574     MEMINFO_COUNT
575 };
576 
android_os_Debug_getMemInfo(JNIEnv * env,jobject clazz,jlongArray out)577 static void android_os_Debug_getMemInfo(JNIEnv *env, jobject clazz, jlongArray out)
578 {
579     if (out == NULL) {
580         jniThrowNullPointerException(env, "out == null");
581         return;
582     }
583 
584     int outLen = env->GetArrayLength(out);
585     if (outLen < MEMINFO_COUNT) {
586         jniThrowRuntimeException(env, "outLen < MEMINFO_COUNT");
587         return;
588     }
589 
590     // Read system memory info including ZRAM. The values are stored in the vector
591     // in the same order as MEMINFO_* enum
592     std::vector<std::string_view> tags(
593         ::android::meminfo::SysMemInfo::kDefaultSysMemInfoTags.begin(),
594         ::android::meminfo::SysMemInfo::kDefaultSysMemInfoTags.end());
595     tags.insert(tags.begin() + MEMINFO_ZRAM_TOTAL, "Zram:");
596     std::vector<uint64_t> mem(tags.size());
597     ::android::meminfo::SysMemInfo smi;
598     if (!smi.ReadMemInfo(tags.size(), tags.data(), mem.data())) {
599         jniThrowRuntimeException(env, "SysMemInfo read failed");
600         return;
601     }
602 
603     jlong* outArray = env->GetLongArrayElements(out, 0);
604     if (outArray != NULL) {
605         outLen = MEMINFO_COUNT;
606         for (int i = 0; i < outLen; i++) {
607             if (i == MEMINFO_VMALLOC_USED && mem[i] == 0) {
608                 outArray[i] = smi.ReadVmallocInfo() / 1024;
609                 continue;
610             }
611             outArray[i] = mem[i];
612         }
613     }
614 
615     env->ReleaseLongArrayElements(out, outArray, 0);
616 }
617 
read_binder_stat(const char * stat)618 static jint read_binder_stat(const char* stat)
619 {
620     UniqueFile fp = MakeUniqueFile(BINDER_STATS, "re");
621     if (fp == nullptr) {
622         return -1;
623     }
624 
625     char line[1024];
626 
627     char compare[128];
628     int len = snprintf(compare, 128, "proc %d", getpid());
629 
630     // loop until we have the block that represents this process
631     do {
632         if (fgets(line, 1024, fp.get()) == 0) {
633             return -1;
634         }
635     } while (strncmp(compare, line, len));
636 
637     // now that we have this process, read until we find the stat that we are looking for
638     len = snprintf(compare, 128, "  %s: ", stat);
639 
640     do {
641         if (fgets(line, 1024, fp.get()) == 0) {
642             return -1;
643         }
644     } while (strncmp(compare, line, len));
645 
646     // we have the line, now increment the line ptr to the value
647     char* ptr = line + len;
648     jint result = atoi(ptr);
649     return result;
650 }
651 
android_os_Debug_getBinderSentTransactions(JNIEnv * env,jobject clazz)652 static jint android_os_Debug_getBinderSentTransactions(JNIEnv *env, jobject clazz)
653 {
654     return read_binder_stat("bcTRANSACTION");
655 }
656 
android_os_getBinderReceivedTransactions(JNIEnv * env,jobject clazz)657 static jint android_os_getBinderReceivedTransactions(JNIEnv *env, jobject clazz)
658 {
659     return read_binder_stat("brTRANSACTION");
660 }
661 
662 // these are implemented in android_util_Binder.cpp
663 jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz);
664 jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz);
665 jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz);
666 
openFile(JNIEnv * env,jobject fileDescriptor,UniqueFile & fp)667 static bool openFile(JNIEnv* env, jobject fileDescriptor, UniqueFile& fp)
668 {
669     if (fileDescriptor == NULL) {
670         jniThrowNullPointerException(env, "fd == null");
671         return false;
672     }
673     int origFd = jniGetFDFromFileDescriptor(env, fileDescriptor);
674     if (origFd < 0) {
675         jniThrowRuntimeException(env, "Invalid file descriptor");
676         return false;
677     }
678 
679     /* dup() the descriptor so we don't close the original with fclose() */
680     int fd = fcntl(origFd, F_DUPFD_CLOEXEC, 0);
681     if (fd < 0) {
682         ALOGW("dup(%d) failed: %s\n", origFd, strerror(errno));
683         jniThrowRuntimeException(env, "dup() failed");
684         return false;
685     }
686 
687     fp.reset(fdopen(fd, "w"));
688     if (fp == nullptr) {
689         ALOGW("fdopen(%d) failed: %s\n", fd, strerror(errno));
690         close(fd);
691         jniThrowRuntimeException(env, "fdopen() failed");
692         return false;
693     }
694     return true;
695 }
696 
697 /*
698  * Dump the native heap, writing human-readable output to the specified
699  * file descriptor.
700  */
android_os_Debug_dumpNativeHeap(JNIEnv * env,jobject,jobject fileDescriptor)701 static void android_os_Debug_dumpNativeHeap(JNIEnv* env, jobject,
702     jobject fileDescriptor)
703 {
704     UniqueFile fp(nullptr, safeFclose);
705     if (!openFile(env, fileDescriptor, fp)) {
706         return;
707     }
708 
709     ALOGD("Native heap dump starting...\n");
710     // Formatting of the native heap dump is handled by malloc debug itself.
711     // See https://android.googlesource.com/platform/bionic/+/master/libc/malloc_debug/README.md#backtrace-heap-dump-format
712     if (android_mallopt(M_WRITE_MALLOC_LEAK_INFO_TO_FILE, fp.get(), sizeof(FILE*))) {
713       ALOGD("Native heap dump complete.\n");
714     } else {
715       PLOG(ERROR) << "Failed to write native heap dump to file";
716     }
717 }
718 
719 /*
720  * Dump the native malloc info, writing xml output to the specified
721  * file descriptor.
722  */
android_os_Debug_dumpNativeMallocInfo(JNIEnv * env,jobject,jobject fileDescriptor)723 static void android_os_Debug_dumpNativeMallocInfo(JNIEnv* env, jobject,
724     jobject fileDescriptor)
725 {
726     UniqueFile fp(nullptr, safeFclose);
727     if (!openFile(env, fileDescriptor, fp)) {
728         return;
729     }
730 
731     malloc_info(0, fp.get());
732 }
733 
dumpTraces(JNIEnv * env,jint pid,jstring fileName,jint timeoutSecs,DebuggerdDumpType dumpType)734 static bool dumpTraces(JNIEnv* env, jint pid, jstring fileName, jint timeoutSecs,
735                        DebuggerdDumpType dumpType) {
736     const ScopedUtfChars fileNameChars(env, fileName);
737     if (fileNameChars.c_str() == nullptr) {
738         return false;
739     }
740 
741     android::base::unique_fd fd(open(fileNameChars.c_str(),
742                                      O_CREAT | O_WRONLY | O_NOFOLLOW | O_CLOEXEC | O_APPEND,
743                                      0666));
744     if (fd < 0) {
745         PLOG(ERROR) << "Can't open " << fileNameChars.c_str();
746         return false;
747     }
748 
749     int res = dump_backtrace_to_file_timeout(pid, dumpType, timeoutSecs, fd);
750     if (fdatasync(fd.get()) != 0) {
751         PLOG(ERROR) << "Failed flushing trace.";
752     }
753     return res == 0;
754 }
755 
android_os_Debug_dumpJavaBacktraceToFileTimeout(JNIEnv * env,jobject clazz,jint pid,jstring fileName,jint timeoutSecs)756 static jboolean android_os_Debug_dumpJavaBacktraceToFileTimeout(JNIEnv* env, jobject clazz,
757         jint pid, jstring fileName, jint timeoutSecs) {
758     const bool ret = dumpTraces(env, pid, fileName, timeoutSecs, kDebuggerdJavaBacktrace);
759     return ret ? JNI_TRUE : JNI_FALSE;
760 }
761 
android_os_Debug_dumpNativeBacktraceToFileTimeout(JNIEnv * env,jobject clazz,jint pid,jstring fileName,jint timeoutSecs)762 static jboolean android_os_Debug_dumpNativeBacktraceToFileTimeout(JNIEnv* env, jobject clazz,
763         jint pid, jstring fileName, jint timeoutSecs) {
764     const bool ret = dumpTraces(env, pid, fileName, timeoutSecs, kDebuggerdNativeBacktrace);
765     return ret ? JNI_TRUE : JNI_FALSE;
766 }
767 
android_os_Debug_getUnreachableMemory(JNIEnv * env,jobject clazz,jint limit,jboolean contents)768 static jstring android_os_Debug_getUnreachableMemory(JNIEnv* env, jobject clazz,
769     jint limit, jboolean contents)
770 {
771     std::string s = GetUnreachableMemoryString(contents, limit);
772     return env->NewStringUTF(s.c_str());
773 }
774 
android_os_Debug_getFreeZramKb(JNIEnv * env,jobject clazz)775 static jlong android_os_Debug_getFreeZramKb(JNIEnv* env, jobject clazz) {
776 
777     jlong zramFreeKb = 0;
778 
779     std::string status_path = android::base::StringPrintf("/proc/meminfo");
780     UniqueFile file = MakeUniqueFile(status_path.c_str(), "re");
781 
782     char line[256];
783     while (file != nullptr && fgets(line, sizeof(line), file.get())) {
784         jlong v;
785         if (sscanf(line, "SwapFree: %" SCNd64 " kB", &v) == 1) {
786             zramFreeKb = v;
787             break;
788         }
789     }
790 
791     return zramFreeKb;
792 }
793 
android_os_Debug_getIonHeapsSizeKb(JNIEnv * env,jobject clazz)794 static jlong android_os_Debug_getIonHeapsSizeKb(JNIEnv* env, jobject clazz) {
795     jlong heapsSizeKb = 0;
796     uint64_t size;
797 
798     if (meminfo::ReadIonHeapsSizeKb(&size)) {
799         heapsSizeKb = size;
800     }
801 
802     return heapsSizeKb;
803 }
804 
android_os_Debug_getIonPoolsSizeKb(JNIEnv * env,jobject clazz)805 static jlong android_os_Debug_getIonPoolsSizeKb(JNIEnv* env, jobject clazz) {
806     jlong poolsSizeKb = 0;
807     uint64_t size;
808 
809     if (meminfo::ReadIonPoolsSizeKb(&size)) {
810         poolsSizeKb = size;
811     }
812 
813     return poolsSizeKb;
814 }
815 
android_os_Debug_getIonMappedSizeKb(JNIEnv * env,jobject clazz)816 static jlong android_os_Debug_getIonMappedSizeKb(JNIEnv* env, jobject clazz) {
817     jlong ionPss = 0;
818     std::vector<dmabufinfo::DmaBuffer> dmabufs;
819 
820     std::unique_ptr<DIR, int (*)(DIR*)> dir(opendir("/proc"), closedir);
821     if (!dir) {
822         LOG(ERROR) << "Failed to open /proc directory";
823         return false;
824     }
825 
826     struct dirent* dent;
827     while ((dent = readdir(dir.get()))) {
828         if (dent->d_type != DT_DIR) continue;
829 
830         int pid = atoi(dent->d_name);
831         if (pid == 0) {
832             continue;
833         }
834 
835         if (!AppendDmaBufInfo(pid, &dmabufs, false)) {
836             LOG(ERROR) << "Failed to read maps for pid " << pid;
837         }
838     }
839 
840     for (const dmabufinfo::DmaBuffer& buf : dmabufs) {
841         ionPss += buf.size() / 1024;
842     }
843 
844     return ionPss;
845 }
846 
android_os_Debug_isVmapStack(JNIEnv * env,jobject clazz)847 static jboolean android_os_Debug_isVmapStack(JNIEnv *env, jobject clazz)
848 {
849     static enum {
850         CONFIG_UNKNOWN,
851         CONFIG_SET,
852         CONFIG_UNSET,
853     } cfg_state = CONFIG_UNKNOWN;
854 
855     if (cfg_state == CONFIG_UNKNOWN) {
856         auto runtime_info = vintf::VintfObject::GetInstance()
857                                     ->getRuntimeInfo(false /* skip cache */,
858                                                      vintf::RuntimeInfo::FetchFlag::CONFIG_GZ);
859         CHECK(runtime_info != nullptr) << "Kernel configs cannot be fetched. b/151092221";
860         const std::map<std::string, std::string>& configs = runtime_info->kernelConfigs();
861         std::map<std::string, std::string>::const_iterator it = configs.find("CONFIG_VMAP_STACK");
862         cfg_state = (it != configs.end() && it->second == "y") ? CONFIG_SET : CONFIG_UNSET;
863     }
864     return cfg_state == CONFIG_SET;
865 }
866 
867 /*
868  * JNI registration.
869  */
870 
871 static const JNINativeMethod gMethods[] = {
872     { "getNativeHeapSize",      "()J",
873             (void*) android_os_Debug_getNativeHeapSize },
874     { "getNativeHeapAllocatedSize", "()J",
875             (void*) android_os_Debug_getNativeHeapAllocatedSize },
876     { "getNativeHeapFreeSize",  "()J",
877             (void*) android_os_Debug_getNativeHeapFreeSize },
878     { "getMemoryInfo",          "(Landroid/os/Debug$MemoryInfo;)V",
879             (void*) android_os_Debug_getDirtyPages },
880     { "getMemoryInfo",          "(ILandroid/os/Debug$MemoryInfo;)Z",
881             (void*) android_os_Debug_getDirtyPagesPid },
882     { "getPss",                 "()J",
883             (void*) android_os_Debug_getPss },
884     { "getPss",                 "(I[J[J)J",
885             (void*) android_os_Debug_getPssPid },
886     { "getMemInfo",             "([J)V",
887             (void*) android_os_Debug_getMemInfo },
888     { "dumpNativeHeap",         "(Ljava/io/FileDescriptor;)V",
889             (void*) android_os_Debug_dumpNativeHeap },
890     { "dumpNativeMallocInfo",   "(Ljava/io/FileDescriptor;)V",
891             (void*) android_os_Debug_dumpNativeMallocInfo },
892     { "getBinderSentTransactions", "()I",
893             (void*) android_os_Debug_getBinderSentTransactions },
894     { "getBinderReceivedTransactions", "()I",
895             (void*) android_os_getBinderReceivedTransactions },
896     { "getBinderLocalObjectCount", "()I",
897             (void*)android_os_Debug_getLocalObjectCount },
898     { "getBinderProxyObjectCount", "()I",
899             (void*)android_os_Debug_getProxyObjectCount },
900     { "getBinderDeathObjectCount", "()I",
901             (void*)android_os_Debug_getDeathObjectCount },
902     { "dumpJavaBacktraceToFileTimeout", "(ILjava/lang/String;I)Z",
903             (void*)android_os_Debug_dumpJavaBacktraceToFileTimeout },
904     { "dumpNativeBacktraceToFileTimeout", "(ILjava/lang/String;I)Z",
905             (void*)android_os_Debug_dumpNativeBacktraceToFileTimeout },
906     { "getUnreachableMemory", "(IZ)Ljava/lang/String;",
907             (void*)android_os_Debug_getUnreachableMemory },
908     { "getZramFreeKb", "()J",
909             (void*)android_os_Debug_getFreeZramKb },
910     { "getIonHeapsSizeKb", "()J",
911             (void*)android_os_Debug_getIonHeapsSizeKb },
912     { "getIonPoolsSizeKb", "()J",
913             (void*)android_os_Debug_getIonPoolsSizeKb },
914     { "getIonMappedSizeKb", "()J",
915             (void*)android_os_Debug_getIonMappedSizeKb },
916     { "isVmapStack", "()Z",
917             (void*)android_os_Debug_isVmapStack },
918 };
919 
register_android_os_Debug(JNIEnv * env)920 int register_android_os_Debug(JNIEnv *env)
921 {
922     jclass clazz = env->FindClass("android/os/Debug$MemoryInfo");
923 
924     // Sanity check the number of other statistics expected in Java matches here.
925     jfieldID numOtherStats_field = env->GetStaticFieldID(clazz, "NUM_OTHER_STATS", "I");
926     jint numOtherStats = env->GetStaticIntField(clazz, numOtherStats_field);
927     jfieldID numDvkStats_field = env->GetStaticFieldID(clazz, "NUM_DVK_STATS", "I");
928     jint numDvkStats = env->GetStaticIntField(clazz, numDvkStats_field);
929     int expectedNumOtherStats = _NUM_HEAP - _NUM_CORE_HEAP;
930     if ((numOtherStats + numDvkStats) != expectedNumOtherStats) {
931         jniThrowExceptionFmt(env, "java/lang/RuntimeException",
932                              "android.os.Debug.Meminfo.NUM_OTHER_STATS+android.os.Debug.Meminfo.NUM_DVK_STATS=%d expected %d",
933                              numOtherStats+numDvkStats, expectedNumOtherStats);
934         return JNI_ERR;
935     }
936 
937     otherStats_field = env->GetFieldID(clazz, "otherStats", "[I");
938     hasSwappedOutPss_field = env->GetFieldID(clazz, "hasSwappedOutPss", "Z");
939 
940     for (int i=0; i<_NUM_CORE_HEAP; i++) {
941         stat_fields[i].pss_field =
942                 env->GetFieldID(clazz, stat_field_names[i].pss_name, "I");
943         stat_fields[i].pssSwappable_field =
944                 env->GetFieldID(clazz, stat_field_names[i].pssSwappable_name, "I");
945         stat_fields[i].rss_field =
946                 env->GetFieldID(clazz, stat_field_names[i].rss_name, "I");
947         stat_fields[i].privateDirty_field =
948                 env->GetFieldID(clazz, stat_field_names[i].privateDirty_name, "I");
949         stat_fields[i].sharedDirty_field =
950                 env->GetFieldID(clazz, stat_field_names[i].sharedDirty_name, "I");
951         stat_fields[i].privateClean_field =
952                 env->GetFieldID(clazz, stat_field_names[i].privateClean_name, "I");
953         stat_fields[i].sharedClean_field =
954                 env->GetFieldID(clazz, stat_field_names[i].sharedClean_name, "I");
955         stat_fields[i].swappedOut_field =
956                 env->GetFieldID(clazz, stat_field_names[i].swappedOut_name, "I");
957         stat_fields[i].swappedOutPss_field =
958                 env->GetFieldID(clazz, stat_field_names[i].swappedOutPss_name, "I");
959     }
960 
961     return jniRegisterNativeMethods(env, "android/os/Debug", gMethods, NELEM(gMethods));
962 }
963 
964 }; // namespace android
965