android_os_Debug.cpp revision 7fc9176c8a2102fb5be3668404bd15feb6878c89
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#include "JNIHelp.h"
19#include "jni.h"
20#include <utils/String8.h>
21#include "utils/misc.h"
22#include "cutils/debugger.h"
23#include <memtrack/memtrack.h>
24
25#include <cutils/log.h>
26#include <fcntl.h>
27#include <inttypes.h>
28#include <stdio.h>
29#include <stdlib.h>
30#include <string.h>
31#include <unistd.h>
32#include <time.h>
33#include <sys/time.h>
34#include <errno.h>
35#include <assert.h>
36#include <ctype.h>
37
38#ifdef HAVE_MALLOC_H
39#include <malloc.h>
40#endif
41
42namespace android
43{
44
45enum {
46    HEAP_UNKNOWN,
47    HEAP_DALVIK,
48    HEAP_NATIVE,
49
50    HEAP_DALVIK_OTHER,
51    HEAP_STACK,
52    HEAP_CURSOR,
53    HEAP_ASHMEM,
54    HEAP_GL_DEV,
55    HEAP_UNKNOWN_DEV,
56    HEAP_SO,
57    HEAP_JAR,
58    HEAP_APK,
59    HEAP_TTF,
60    HEAP_DEX,
61    HEAP_OAT,
62    HEAP_ART,
63    HEAP_UNKNOWN_MAP,
64    HEAP_GRAPHICS,
65    HEAP_GL,
66    HEAP_OTHER_MEMTRACK,
67
68    HEAP_DALVIK_NORMAL,
69    HEAP_DALVIK_LARGE,
70    HEAP_DALVIK_LINEARALLOC,
71    HEAP_DALVIK_ACCOUNTING,
72    HEAP_DALVIK_CODE_CACHE,
73
74    _NUM_HEAP,
75    _NUM_EXCLUSIVE_HEAP = HEAP_OTHER_MEMTRACK+1,
76    _NUM_CORE_HEAP = HEAP_NATIVE+1
77};
78
79struct stat_fields {
80    jfieldID pss_field;
81    jfieldID pssSwappable_field;
82    jfieldID privateDirty_field;
83    jfieldID sharedDirty_field;
84    jfieldID privateClean_field;
85    jfieldID sharedClean_field;
86    jfieldID swappedOut_field;
87};
88
89struct stat_field_names {
90    const char* pss_name;
91    const char* pssSwappable_name;
92    const char* privateDirty_name;
93    const char* sharedDirty_name;
94    const char* privateClean_name;
95    const char* sharedClean_name;
96    const char* swappedOut_name;
97};
98
99static stat_fields stat_fields[_NUM_CORE_HEAP];
100
101static stat_field_names stat_field_names[_NUM_CORE_HEAP] = {
102    { "otherPss", "otherSwappablePss", "otherPrivateDirty", "otherSharedDirty",
103        "otherPrivateClean", "otherSharedClean", "otherSwappedOut" },
104    { "dalvikPss", "dalvikSwappablePss", "dalvikPrivateDirty", "dalvikSharedDirty",
105        "dalvikPrivateClean", "dalvikSharedClean", "dalvikSwappedOut" },
106    { "nativePss", "nativeSwappablePss", "nativePrivateDirty", "nativeSharedDirty",
107        "nativePrivateClean", "nativeSharedClean", "nativeSwappedOut" }
108};
109
110jfieldID otherStats_field;
111
112static bool memtrackLoaded;
113
114struct stats_t {
115    int pss;
116    int swappablePss;
117    int privateDirty;
118    int sharedDirty;
119    int privateClean;
120    int sharedClean;
121    int swappedOut;
122};
123
124#define BINDER_STATS "/proc/binder/stats"
125
126static jlong android_os_Debug_getNativeHeapSize(JNIEnv *env, jobject clazz)
127{
128#ifdef HAVE_MALLOC_H
129    struct mallinfo info = mallinfo();
130    return (jlong) info.usmblks;
131#else
132    return -1;
133#endif
134}
135
136static jlong android_os_Debug_getNativeHeapAllocatedSize(JNIEnv *env, jobject clazz)
137{
138#ifdef HAVE_MALLOC_H
139    struct mallinfo info = mallinfo();
140    return (jlong) info.uordblks;
141#else
142    return -1;
143#endif
144}
145
146static jlong android_os_Debug_getNativeHeapFreeSize(JNIEnv *env, jobject clazz)
147{
148#ifdef HAVE_MALLOC_H
149    struct mallinfo info = mallinfo();
150    return (jlong) info.fordblks;
151#else
152    return -1;
153#endif
154}
155
156// Container used to retrieve graphics memory pss
157struct graphics_memory_pss
158{
159    int graphics;
160    int gl;
161    int other;
162};
163
164/*
165 * Uses libmemtrack to retrieve graphics memory that the process is using.
166 * Any graphics memory reported in /proc/pid/smaps is not included here.
167 */
168static int read_memtrack_memory(struct memtrack_proc* p, int pid,
169        struct graphics_memory_pss* graphics_mem)
170{
171    int err = memtrack_proc_get(p, pid);
172    if (err != 0) {
173        ALOGW("failed to get memory consumption info: %d", err);
174        return err;
175    }
176
177    ssize_t pss = memtrack_proc_graphics_pss(p);
178    if (pss < 0) {
179        ALOGW("failed to get graphics pss: %zd", pss);
180        return pss;
181    }
182    graphics_mem->graphics = pss / 1024;
183
184    pss = memtrack_proc_gl_pss(p);
185    if (pss < 0) {
186        ALOGW("failed to get gl pss: %zd", pss);
187        return pss;
188    }
189    graphics_mem->gl = pss / 1024;
190
191    pss = memtrack_proc_other_pss(p);
192    if (pss < 0) {
193        ALOGW("failed to get other pss: %zd", pss);
194        return pss;
195    }
196    graphics_mem->other = pss / 1024;
197
198    return 0;
199}
200
201/*
202 * Retrieves the graphics memory that is unaccounted for in /proc/pid/smaps.
203 */
204static int read_memtrack_memory(int pid, struct graphics_memory_pss* graphics_mem)
205{
206    if (!memtrackLoaded) {
207        return -1;
208    }
209
210    struct memtrack_proc* p = memtrack_proc_new();
211    if (p == NULL) {
212        ALOGW("failed to create memtrack_proc");
213        return -1;
214    }
215
216    int err = read_memtrack_memory(p, pid, graphics_mem);
217    memtrack_proc_destroy(p);
218    return err;
219}
220
221static void read_mapinfo(FILE *fp, stats_t* stats)
222{
223    char line[1024];
224    int len, nameLen;
225    bool skip, done = false;
226
227    unsigned size = 0, resident = 0, pss = 0, swappable_pss = 0;
228    float sharing_proportion = 0.0;
229    unsigned shared_clean = 0, shared_dirty = 0;
230    unsigned private_clean = 0, private_dirty = 0;
231    unsigned swapped_out = 0;
232    bool is_swappable = false;
233    unsigned referenced = 0;
234    unsigned temp;
235
236    uint64_t start;
237    uint64_t end = 0;
238    uint64_t prevEnd = 0;
239    char* name;
240    int name_pos;
241
242    int whichHeap = HEAP_UNKNOWN;
243    int subHeap = HEAP_UNKNOWN;
244    int prevHeap = HEAP_UNKNOWN;
245
246    if(fgets(line, sizeof(line), fp) == 0) return;
247
248    while (!done) {
249        prevHeap = whichHeap;
250        prevEnd = end;
251        whichHeap = HEAP_UNKNOWN;
252        subHeap = HEAP_UNKNOWN;
253        skip = false;
254        is_swappable = false;
255
256        len = strlen(line);
257        if (len < 1) return;
258        line[--len] = 0;
259
260        if (sscanf(line, "%" SCNx64 "-%" SCNx64 " %*s %*x %*x:%*x %*d%n", &start, &end, &name_pos) != 2) {
261            skip = true;
262        } else {
263            while (isspace(line[name_pos])) {
264                name_pos += 1;
265            }
266            name = line + name_pos;
267            nameLen = strlen(name);
268
269            if ((strstr(name, "[heap]") == name)) {
270                whichHeap = HEAP_NATIVE;
271            } else if (strncmp(name, "/dev/ashmem", 11) == 0) {
272                if (strncmp(name, "/dev/ashmem/dalvik-", 19) == 0) {
273                    whichHeap = HEAP_DALVIK_OTHER;
274                    if (strstr(name, "/dev/ashmem/dalvik-LinearAlloc") == name) {
275                        subHeap = HEAP_DALVIK_LINEARALLOC;
276                    } else if ((strstr(name, "/dev/ashmem/dalvik-alloc space") == name) ||
277                               (strstr(name, "/dev/ashmem/dalvik-main space") == name) ||
278                               (strstr(name, "/dev/ashmem/dalvik-zygote space") == name) ||
279                               (strstr(name, "/dev/ashmem/dalvik-non moving space") == name)) {
280                        // This is the regular Dalvik heap.
281                        whichHeap = HEAP_DALVIK;
282                        subHeap = HEAP_DALVIK_NORMAL;
283                    } else if (strstr(name, "/dev/ashmem/dalvik-large object space") == name) {
284                        whichHeap = HEAP_DALVIK;
285                        subHeap = HEAP_DALVIK_LARGE;
286                    } else if (strstr(name, "/dev/ashmem/dalvik-jit-code-cache") == name) {
287                        subHeap = HEAP_DALVIK_CODE_CACHE;
288                    } else {
289                        subHeap = HEAP_DALVIK_ACCOUNTING;  // Default to accounting.
290                    }
291                } else if (strncmp(name, "/dev/ashmem/CursorWindow", 24) == 0) {
292                    whichHeap = HEAP_CURSOR;
293                } else if (strncmp(name, "/dev/ashmem/libc malloc", 23) == 0) {
294                    whichHeap = HEAP_NATIVE;
295                } else {
296                    whichHeap = HEAP_ASHMEM;
297                }
298            } else if (strncmp(name, "[anon:libc_malloc]", 18) == 0) {
299                whichHeap = HEAP_NATIVE;
300            } else if (strncmp(name, "[stack", 6) == 0) {
301                whichHeap = HEAP_STACK;
302            } else if (strncmp(name, "/dev/", 5) == 0) {
303                if (strncmp(name, "/dev/kgsl-3d0", 13) == 0) {
304                    whichHeap = HEAP_GL_DEV;
305                } else {
306                    whichHeap = HEAP_UNKNOWN_DEV;
307                }
308            } else if (nameLen > 3 && strcmp(name+nameLen-3, ".so") == 0) {
309                whichHeap = HEAP_SO;
310                is_swappable = true;
311            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".jar") == 0) {
312                whichHeap = HEAP_JAR;
313                is_swappable = true;
314            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".apk") == 0) {
315                whichHeap = HEAP_APK;
316                is_swappable = true;
317            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".ttf") == 0) {
318                whichHeap = HEAP_TTF;
319                is_swappable = true;
320            } else if ((nameLen > 4 && strcmp(name+nameLen-4, ".dex") == 0) ||
321                       (nameLen > 5 && strcmp(name+nameLen-5, ".odex") == 0)) {
322                whichHeap = HEAP_DEX;
323                is_swappable = true;
324            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".oat") == 0) {
325                whichHeap = HEAP_OAT;
326                is_swappable = true;
327            } else if (nameLen > 4 && strcmp(name+nameLen-4, ".art") == 0) {
328                whichHeap = HEAP_ART;
329                is_swappable = true;
330            } else if (strncmp(name, "[anon:", 6) == 0) {
331                whichHeap = HEAP_UNKNOWN;
332            } else if (nameLen > 0) {
333                whichHeap = HEAP_UNKNOWN_MAP;
334            } else if (start == prevEnd && prevHeap == HEAP_SO) {
335                // bss section of a shared library.
336                whichHeap = HEAP_SO;
337            }
338        }
339
340        //ALOGI("native=%d dalvik=%d sqlite=%d: %s\n", isNativeHeap, isDalvikHeap,
341        //    isSqliteHeap, line);
342
343        shared_clean = 0;
344        shared_dirty = 0;
345        private_clean = 0;
346        private_dirty = 0;
347        swapped_out = 0;
348
349        while (true) {
350            if (fgets(line, 1024, fp) == 0) {
351                done = true;
352                break;
353            }
354
355            if (line[0] == 'S' && sscanf(line, "Size: %d kB", &temp) == 1) {
356                size = temp;
357            } else if (line[0] == 'R' && sscanf(line, "Rss: %d kB", &temp) == 1) {
358                resident = temp;
359            } else if (line[0] == 'P' && sscanf(line, "Pss: %d kB", &temp) == 1) {
360                pss = temp;
361            } else if (line[0] == 'S' && sscanf(line, "Shared_Clean: %d kB", &temp) == 1) {
362                shared_clean = temp;
363            } else if (line[0] == 'S' && sscanf(line, "Shared_Dirty: %d kB", &temp) == 1) {
364                shared_dirty = temp;
365            } else if (line[0] == 'P' && sscanf(line, "Private_Clean: %d kB", &temp) == 1) {
366                private_clean = temp;
367            } else if (line[0] == 'P' && sscanf(line, "Private_Dirty: %d kB", &temp) == 1) {
368                private_dirty = temp;
369            } else if (line[0] == 'R' && sscanf(line, "Referenced: %d kB", &temp) == 1) {
370                referenced = temp;
371            } else if (line[0] == 'S' && sscanf(line, "Swap: %d kB", &temp) == 1) {
372                swapped_out = temp;
373            } else if (sscanf(line, "%" SCNx64 "-%" SCNx64 " %*s %*x %*x:%*x %*d", &start, &end) == 2) {
374                // looks like a new mapping
375                // example: "10000000-10001000 ---p 10000000 00:00 0"
376                break;
377            }
378        }
379
380        if (!skip) {
381            if (is_swappable && (pss > 0)) {
382                sharing_proportion = 0.0;
383                if ((shared_clean > 0) || (shared_dirty > 0)) {
384                    sharing_proportion = (pss - private_clean
385                            - private_dirty)/(shared_clean+shared_dirty);
386                }
387                swappable_pss = (sharing_proportion*shared_clean) + private_clean;
388            } else
389                swappable_pss = 0;
390
391            stats[whichHeap].pss += pss;
392            stats[whichHeap].swappablePss += swappable_pss;
393            stats[whichHeap].privateDirty += private_dirty;
394            stats[whichHeap].sharedDirty += shared_dirty;
395            stats[whichHeap].privateClean += private_clean;
396            stats[whichHeap].sharedClean += shared_clean;
397            stats[whichHeap].swappedOut += swapped_out;
398            if (whichHeap == HEAP_DALVIK || whichHeap == HEAP_DALVIK_OTHER) {
399                stats[subHeap].pss += pss;
400                stats[subHeap].swappablePss += swappable_pss;
401                stats[subHeap].privateDirty += private_dirty;
402                stats[subHeap].sharedDirty += shared_dirty;
403                stats[subHeap].privateClean += private_clean;
404                stats[subHeap].sharedClean += shared_clean;
405                stats[subHeap].swappedOut += swapped_out;
406            }
407        }
408    }
409}
410
411static void load_maps(int pid, stats_t* stats)
412{
413    char tmp[128];
414    FILE *fp;
415
416    sprintf(tmp, "/proc/%d/smaps", pid);
417    fp = fopen(tmp, "r");
418    if (fp == 0) return;
419
420    read_mapinfo(fp, stats);
421    fclose(fp);
422}
423
424static void android_os_Debug_getDirtyPagesPid(JNIEnv *env, jobject clazz,
425        jint pid, jobject object)
426{
427    stats_t stats[_NUM_HEAP];
428    memset(&stats, 0, sizeof(stats));
429
430    load_maps(pid, stats);
431
432    struct graphics_memory_pss graphics_mem;
433    if (read_memtrack_memory(pid, &graphics_mem) == 0) {
434        stats[HEAP_GRAPHICS].pss = graphics_mem.graphics;
435        stats[HEAP_GRAPHICS].privateDirty = graphics_mem.graphics;
436        stats[HEAP_GL].pss = graphics_mem.gl;
437        stats[HEAP_GL].privateDirty = graphics_mem.gl;
438        stats[HEAP_OTHER_MEMTRACK].pss = graphics_mem.other;
439        stats[HEAP_OTHER_MEMTRACK].privateDirty = graphics_mem.other;
440    }
441
442    for (int i=_NUM_CORE_HEAP; i<_NUM_EXCLUSIVE_HEAP; i++) {
443        stats[HEAP_UNKNOWN].pss += stats[i].pss;
444        stats[HEAP_UNKNOWN].swappablePss += stats[i].swappablePss;
445        stats[HEAP_UNKNOWN].privateDirty += stats[i].privateDirty;
446        stats[HEAP_UNKNOWN].sharedDirty += stats[i].sharedDirty;
447        stats[HEAP_UNKNOWN].privateClean += stats[i].privateClean;
448        stats[HEAP_UNKNOWN].sharedClean += stats[i].sharedClean;
449        stats[HEAP_UNKNOWN].swappedOut += stats[i].swappedOut;
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].privateDirty_field, stats[i].privateDirty);
456        env->SetIntField(object, stat_fields[i].sharedDirty_field, stats[i].sharedDirty);
457        env->SetIntField(object, stat_fields[i].privateClean_field, stats[i].privateClean);
458        env->SetIntField(object, stat_fields[i].sharedClean_field, stats[i].sharedClean);
459        env->SetIntField(object, stat_fields[i].swappedOut_field, stats[i].swappedOut);
460    }
461
462
463    jintArray otherIntArray = (jintArray)env->GetObjectField(object, otherStats_field);
464
465    jint* otherArray = (jint*)env->GetPrimitiveArrayCritical(otherIntArray, 0);
466    if (otherArray == NULL) {
467        return;
468    }
469
470    int j=0;
471    for (int i=_NUM_CORE_HEAP; i<_NUM_HEAP; i++) {
472        otherArray[j++] = stats[i].pss;
473        otherArray[j++] = stats[i].swappablePss;
474        otherArray[j++] = stats[i].privateDirty;
475        otherArray[j++] = stats[i].sharedDirty;
476        otherArray[j++] = stats[i].privateClean;
477        otherArray[j++] = stats[i].sharedClean;
478        otherArray[j++] = stats[i].swappedOut;
479    }
480
481    env->ReleasePrimitiveArrayCritical(otherIntArray, otherArray, 0);
482}
483
484static void android_os_Debug_getDirtyPages(JNIEnv *env, jobject clazz, jobject object)
485{
486    android_os_Debug_getDirtyPagesPid(env, clazz, getpid(), object);
487}
488
489static jlong android_os_Debug_getPssPid(JNIEnv *env, jobject clazz, jint pid, jlongArray outUss)
490{
491    char line[1024];
492    jlong pss = 0;
493    jlong uss = 0;
494    unsigned temp;
495
496    char tmp[128];
497    FILE *fp;
498
499    struct graphics_memory_pss graphics_mem;
500    if (read_memtrack_memory(pid, &graphics_mem) == 0) {
501        pss = uss = graphics_mem.graphics + graphics_mem.gl + graphics_mem.other;
502    }
503
504    sprintf(tmp, "/proc/%d/smaps", pid);
505    fp = fopen(tmp, "r");
506
507    if (fp != 0) {
508        while (true) {
509            if (fgets(line, 1024, fp) == NULL) {
510                break;
511            }
512
513            if (line[0] == 'P') {
514                if (strncmp(line, "Pss:", 4) == 0) {
515                    char* c = line + 4;
516                    while (*c != 0 && (*c < '0' || *c > '9')) {
517                        c++;
518                    }
519                    pss += atoi(c);
520                } else if (strncmp(line, "Private_Clean:", 14)
521                        || strncmp(line, "Private_Dirty:", 14)) {
522                    char* c = line + 14;
523                    while (*c != 0 && (*c < '0' || *c > '9')) {
524                        c++;
525                    }
526                    uss += atoi(c);
527                }
528            }
529        }
530
531        fclose(fp);
532    }
533
534    if (outUss != NULL) {
535        if (env->GetArrayLength(outUss) >= 1) {
536            jlong* outUssArray = env->GetLongArrayElements(outUss, 0);
537            if (outUssArray != NULL) {
538                outUssArray[0] = uss;
539            }
540            env->ReleaseLongArrayElements(outUss, outUssArray, 0);
541        }
542    }
543
544    return pss;
545}
546
547static jlong android_os_Debug_getPss(JNIEnv *env, jobject clazz)
548{
549    return android_os_Debug_getPssPid(env, clazz, getpid(), NULL);
550}
551
552enum {
553    MEMINFO_TOTAL,
554    MEMINFO_FREE,
555    MEMINFO_BUFFERS,
556    MEMINFO_CACHED,
557    MEMINFO_SHMEM,
558    MEMINFO_SLAB,
559    MEMINFO_SWAP_TOTAL,
560    MEMINFO_SWAP_FREE,
561    MEMINFO_ZRAM_TOTAL,
562    MEMINFO_MAPPED,
563    MEMINFO_VMALLOC_USED,
564    MEMINFO_PAGE_TABLES,
565    MEMINFO_KERNEL_STACK,
566    MEMINFO_COUNT
567};
568
569static void android_os_Debug_getMemInfo(JNIEnv *env, jobject clazz, jlongArray out)
570{
571    char buffer[1024];
572    int numFound = 0;
573
574    if (out == NULL) {
575        jniThrowNullPointerException(env, "out == null");
576        return;
577    }
578
579    int fd = open("/proc/meminfo", O_RDONLY);
580
581    if (fd < 0) {
582        ALOGW("Unable to open /proc/meminfo: %s\n", strerror(errno));
583        return;
584    }
585
586    int len = read(fd, buffer, sizeof(buffer)-1);
587    close(fd);
588
589    if (len < 0) {
590        ALOGW("Empty /proc/meminfo");
591        return;
592    }
593    buffer[len] = 0;
594
595    static const char* const tags[] = {
596            "MemTotal:",
597            "MemFree:",
598            "Buffers:",
599            "Cached:",
600            "Shmem:",
601            "Slab:",
602            "SwapTotal:",
603            "SwapFree:",
604            "ZRam:",
605            "Mapped:",
606            "VmallocUsed:",
607            "PageTables:",
608            "KernelStack:",
609            NULL
610    };
611    static const int tagsLen[] = {
612            9,
613            8,
614            8,
615            7,
616            6,
617            5,
618            10,
619            9,
620            5,
621            7,
622            12,
623            11,
624            12,
625            0
626    };
627    long mem[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
628
629    char* p = buffer;
630    while (*p && numFound < 13) {
631        int i = 0;
632        while (tags[i]) {
633            if (strncmp(p, tags[i], tagsLen[i]) == 0) {
634                p += tagsLen[i];
635                while (*p == ' ') p++;
636                char* num = p;
637                while (*p >= '0' && *p <= '9') p++;
638                if (*p != 0) {
639                    *p = 0;
640                    p++;
641                }
642                mem[i] = atoll(num);
643                numFound++;
644                break;
645            }
646            i++;
647        }
648        while (*p && *p != '\n') {
649            p++;
650        }
651        if (*p) p++;
652    }
653
654    fd = open("/sys/block/zram0/mem_used_total", O_RDONLY);
655    if (fd >= 0) {
656        len = read(fd, buffer, sizeof(buffer)-1);
657        close(fd);
658        if (len > 0) {
659            buffer[len] = 0;
660            mem[MEMINFO_ZRAM_TOTAL] = atoll(buffer)/1024;
661        }
662    }
663
664    int maxNum = env->GetArrayLength(out);
665    if (maxNum > MEMINFO_COUNT) {
666        maxNum = MEMINFO_COUNT;
667    }
668    jlong* outArray = env->GetLongArrayElements(out, 0);
669    if (outArray != NULL) {
670        for (int i=0; i<maxNum; i++) {
671            outArray[i] = mem[i];
672        }
673    }
674    env->ReleaseLongArrayElements(out, outArray, 0);
675}
676
677static jint read_binder_stat(const char* stat)
678{
679    FILE* fp = fopen(BINDER_STATS, "r");
680    if (fp == NULL) {
681        return -1;
682    }
683
684    char line[1024];
685
686    char compare[128];
687    int len = snprintf(compare, 128, "proc %d", getpid());
688
689    // loop until we have the block that represents this process
690    do {
691        if (fgets(line, 1024, fp) == 0) {
692            fclose(fp);
693            return -1;
694        }
695    } while (strncmp(compare, line, len));
696
697    // now that we have this process, read until we find the stat that we are looking for
698    len = snprintf(compare, 128, "  %s: ", stat);
699
700    do {
701        if (fgets(line, 1024, fp) == 0) {
702            fclose(fp);
703            return -1;
704        }
705    } while (strncmp(compare, line, len));
706
707    // we have the line, now increment the line ptr to the value
708    char* ptr = line + len;
709    jint result = atoi(ptr);
710    fclose(fp);
711    return result;
712}
713
714static jint android_os_Debug_getBinderSentTransactions(JNIEnv *env, jobject clazz)
715{
716    return read_binder_stat("bcTRANSACTION");
717}
718
719static jint android_os_getBinderReceivedTransactions(JNIEnv *env, jobject clazz)
720{
721    return read_binder_stat("brTRANSACTION");
722}
723
724// these are implemented in android_util_Binder.cpp
725jint android_os_Debug_getLocalObjectCount(JNIEnv* env, jobject clazz);
726jint android_os_Debug_getProxyObjectCount(JNIEnv* env, jobject clazz);
727jint android_os_Debug_getDeathObjectCount(JNIEnv* env, jobject clazz);
728
729
730/* pulled out of bionic */
731extern "C" void get_malloc_leak_info(uint8_t** info, size_t* overallSize,
732    size_t* infoSize, size_t* totalMemory, size_t* backtraceSize);
733extern "C" void free_malloc_leak_info(uint8_t* info);
734#define SIZE_FLAG_ZYGOTE_CHILD  (1<<31)
735#define BACKTRACE_SIZE          32
736
737/*
738 * This is a qsort() callback.
739 *
740 * See dumpNativeHeap() for comments about the data format and sort order.
741 */
742static int compareHeapRecords(const void* vrec1, const void* vrec2)
743{
744    const size_t* rec1 = (const size_t*) vrec1;
745    const size_t* rec2 = (const size_t*) vrec2;
746    size_t size1 = *rec1;
747    size_t size2 = *rec2;
748
749    if (size1 < size2) {
750        return 1;
751    } else if (size1 > size2) {
752        return -1;
753    }
754
755    intptr_t* bt1 = (intptr_t*)(rec1 + 2);
756    intptr_t* bt2 = (intptr_t*)(rec2 + 2);
757    for (size_t idx = 0; idx < BACKTRACE_SIZE; idx++) {
758        intptr_t addr1 = bt1[idx];
759        intptr_t addr2 = bt2[idx];
760        if (addr1 == addr2) {
761            if (addr1 == 0)
762                break;
763            continue;
764        }
765        if (addr1 < addr2) {
766            return -1;
767        } else if (addr1 > addr2) {
768            return 1;
769        }
770    }
771
772    return 0;
773}
774
775/*
776 * The get_malloc_leak_info() call returns an array of structs that
777 * look like this:
778 *
779 *   size_t size
780 *   size_t allocations
781 *   intptr_t backtrace[32]
782 *
783 * "size" is the size of the allocation, "backtrace" is a fixed-size
784 * array of function pointers, and "allocations" is the number of
785 * allocations with the exact same size and backtrace.
786 *
787 * The entries are sorted by descending total size (i.e. size*allocations)
788 * then allocation count.  For best results with "diff" we'd like to sort
789 * primarily by individual size then stack trace.  Since the entries are
790 * fixed-size, and we're allowed (by the current implementation) to mangle
791 * them, we can do this in place.
792 */
793static void dumpNativeHeap(FILE* fp)
794{
795    uint8_t* info = NULL;
796    size_t overallSize, infoSize, totalMemory, backtraceSize;
797
798    get_malloc_leak_info(&info, &overallSize, &infoSize, &totalMemory,
799        &backtraceSize);
800    if (info == NULL) {
801        fprintf(fp, "Native heap dump not available. To enable, run these"
802                    " commands (requires root):\n");
803        fprintf(fp, "$ adb shell setprop libc.debug.malloc 1\n");
804        fprintf(fp, "$ adb shell stop\n");
805        fprintf(fp, "$ adb shell start\n");
806        return;
807    }
808    assert(infoSize != 0);
809    assert(overallSize % infoSize == 0);
810
811    fprintf(fp, "Android Native Heap Dump v1.0\n\n");
812
813    size_t recordCount = overallSize / infoSize;
814    fprintf(fp, "Total memory: %zu\n", totalMemory);
815    fprintf(fp, "Allocation records: %zd\n", recordCount);
816    if (backtraceSize != BACKTRACE_SIZE) {
817        fprintf(fp, "WARNING: mismatched backtrace sizes (%zu vs. %d)\n",
818            backtraceSize, BACKTRACE_SIZE);
819    }
820    fprintf(fp, "\n");
821
822    /* re-sort the entries */
823    qsort(info, recordCount, infoSize, compareHeapRecords);
824
825    /* dump the entries to the file */
826    const uint8_t* ptr = info;
827    for (size_t idx = 0; idx < recordCount; idx++) {
828        size_t size = *(size_t*) ptr;
829        size_t allocations = *(size_t*) (ptr + sizeof(size_t));
830        intptr_t* backtrace = (intptr_t*) (ptr + sizeof(size_t) * 2);
831
832        fprintf(fp, "z %d  sz %8zu  num %4zu  bt",
833                (size & SIZE_FLAG_ZYGOTE_CHILD) != 0,
834                size & ~SIZE_FLAG_ZYGOTE_CHILD,
835                allocations);
836        for (size_t bt = 0; bt < backtraceSize; bt++) {
837            if (backtrace[bt] == 0) {
838                break;
839            } else {
840#ifdef __LP64__
841                fprintf(fp, " %016" PRIxPTR, backtrace[bt]);
842#else
843                fprintf(fp, " %08" PRIxPTR, backtrace[bt]);
844#endif
845            }
846        }
847        fprintf(fp, "\n");
848
849        ptr += infoSize;
850    }
851
852    free_malloc_leak_info(info);
853
854    fprintf(fp, "MAPS\n");
855    const char* maps = "/proc/self/maps";
856    FILE* in = fopen(maps, "r");
857    if (in == NULL) {
858        fprintf(fp, "Could not open %s\n", maps);
859        return;
860    }
861    char buf[BUFSIZ];
862    while (size_t n = fread(buf, sizeof(char), BUFSIZ, in)) {
863        fwrite(buf, sizeof(char), n, fp);
864    }
865    fclose(in);
866
867    fprintf(fp, "END\n");
868}
869
870/*
871 * Dump the native heap, writing human-readable output to the specified
872 * file descriptor.
873 */
874static void android_os_Debug_dumpNativeHeap(JNIEnv* env, jobject clazz,
875    jobject fileDescriptor)
876{
877    if (fileDescriptor == NULL) {
878        jniThrowNullPointerException(env, "fd == null");
879        return;
880    }
881    int origFd = jniGetFDFromFileDescriptor(env, fileDescriptor);
882    if (origFd < 0) {
883        jniThrowRuntimeException(env, "Invalid file descriptor");
884        return;
885    }
886
887    /* dup() the descriptor so we don't close the original with fclose() */
888    int fd = dup(origFd);
889    if (fd < 0) {
890        ALOGW("dup(%d) failed: %s\n", origFd, strerror(errno));
891        jniThrowRuntimeException(env, "dup() failed");
892        return;
893    }
894
895    FILE* fp = fdopen(fd, "w");
896    if (fp == NULL) {
897        ALOGW("fdopen(%d) failed: %s\n", fd, strerror(errno));
898        close(fd);
899        jniThrowRuntimeException(env, "fdopen() failed");
900        return;
901    }
902
903    ALOGD("Native heap dump starting...\n");
904    dumpNativeHeap(fp);
905    ALOGD("Native heap dump complete.\n");
906
907    fclose(fp);
908}
909
910
911static void android_os_Debug_dumpNativeBacktraceToFile(JNIEnv* env, jobject clazz,
912    jint pid, jstring fileName)
913{
914    if (fileName == NULL) {
915        jniThrowNullPointerException(env, "file == null");
916        return;
917    }
918    const jchar* str = env->GetStringCritical(fileName, 0);
919    String8 fileName8;
920    if (str) {
921        fileName8 = String8(str, env->GetStringLength(fileName));
922        env->ReleaseStringCritical(fileName, str);
923    }
924
925    int fd = open(fileName8.string(), O_CREAT | O_WRONLY | O_NOFOLLOW, 0666);  /* -rw-rw-rw- */
926    if (fd < 0) {
927        fprintf(stderr, "Can't open %s: %s\n", fileName8.string(), strerror(errno));
928        return;
929    }
930
931    if (lseek(fd, 0, SEEK_END) < 0) {
932        fprintf(stderr, "lseek: %s\n", strerror(errno));
933    } else {
934        dump_backtrace_to_file(pid, fd);
935    }
936
937    close(fd);
938}
939
940/*
941 * JNI registration.
942 */
943
944static JNINativeMethod gMethods[] = {
945    { "getNativeHeapSize",      "()J",
946            (void*) android_os_Debug_getNativeHeapSize },
947    { "getNativeHeapAllocatedSize", "()J",
948            (void*) android_os_Debug_getNativeHeapAllocatedSize },
949    { "getNativeHeapFreeSize",  "()J",
950            (void*) android_os_Debug_getNativeHeapFreeSize },
951    { "getMemoryInfo",          "(Landroid/os/Debug$MemoryInfo;)V",
952            (void*) android_os_Debug_getDirtyPages },
953    { "getMemoryInfo",          "(ILandroid/os/Debug$MemoryInfo;)V",
954            (void*) android_os_Debug_getDirtyPagesPid },
955    { "getPss",                 "()J",
956            (void*) android_os_Debug_getPss },
957    { "getPss",                 "(I[J)J",
958            (void*) android_os_Debug_getPssPid },
959    { "getMemInfo",             "([J)V",
960            (void*) android_os_Debug_getMemInfo },
961    { "dumpNativeHeap",         "(Ljava/io/FileDescriptor;)V",
962            (void*) android_os_Debug_dumpNativeHeap },
963    { "getBinderSentTransactions", "()I",
964            (void*) android_os_Debug_getBinderSentTransactions },
965    { "getBinderReceivedTransactions", "()I",
966            (void*) android_os_getBinderReceivedTransactions },
967    { "getBinderLocalObjectCount", "()I",
968            (void*)android_os_Debug_getLocalObjectCount },
969    { "getBinderProxyObjectCount", "()I",
970            (void*)android_os_Debug_getProxyObjectCount },
971    { "getBinderDeathObjectCount", "()I",
972            (void*)android_os_Debug_getDeathObjectCount },
973    { "dumpNativeBacktraceToFile", "(ILjava/lang/String;)V",
974            (void*)android_os_Debug_dumpNativeBacktraceToFile },
975};
976
977int register_android_os_Debug(JNIEnv *env)
978{
979    int err = memtrack_init();
980    if (err != 0) {
981        memtrackLoaded = false;
982        ALOGE("failed to load memtrack module: %d", err);
983    } else {
984        memtrackLoaded = true;
985    }
986
987    jclass clazz = env->FindClass("android/os/Debug$MemoryInfo");
988
989    // Sanity check the number of other statistics expected in Java matches here.
990    jfieldID numOtherStats_field = env->GetStaticFieldID(clazz, "NUM_OTHER_STATS", "I");
991    jint numOtherStats = env->GetStaticIntField(clazz, numOtherStats_field);
992    jfieldID numDvkStats_field = env->GetStaticFieldID(clazz, "NUM_DVK_STATS", "I");
993    jint numDvkStats = env->GetStaticIntField(clazz, numDvkStats_field);
994    int expectedNumOtherStats = _NUM_HEAP - _NUM_CORE_HEAP;
995    if ((numOtherStats + numDvkStats) != expectedNumOtherStats) {
996        jniThrowExceptionFmt(env, "java/lang/RuntimeException",
997                             "android.os.Debug.Meminfo.NUM_OTHER_STATS+android.os.Debug.Meminfo.NUM_DVK_STATS=%d expected %d",
998                             numOtherStats+numDvkStats, expectedNumOtherStats);
999        return JNI_ERR;
1000    }
1001
1002    otherStats_field = env->GetFieldID(clazz, "otherStats", "[I");
1003
1004    for (int i=0; i<_NUM_CORE_HEAP; i++) {
1005        stat_fields[i].pss_field =
1006                env->GetFieldID(clazz, stat_field_names[i].pss_name, "I");
1007        stat_fields[i].pssSwappable_field =
1008                env->GetFieldID(clazz, stat_field_names[i].pssSwappable_name, "I");
1009        stat_fields[i].privateDirty_field =
1010                env->GetFieldID(clazz, stat_field_names[i].privateDirty_name, "I");
1011        stat_fields[i].sharedDirty_field =
1012                env->GetFieldID(clazz, stat_field_names[i].sharedDirty_name, "I");
1013        stat_fields[i].privateClean_field =
1014                env->GetFieldID(clazz, stat_field_names[i].privateClean_name, "I");
1015        stat_fields[i].sharedClean_field =
1016                env->GetFieldID(clazz, stat_field_names[i].sharedClean_name, "I");
1017        stat_fields[i].swappedOut_field =
1018                env->GetFieldID(clazz, stat_field_names[i].swappedOut_name, "I");
1019    }
1020
1021    return jniRegisterNativeMethods(env, "android/os/Debug", gMethods, NELEM(gMethods));
1022}
1023
1024}; // namespace android
1025