1 /*
2 * Copyright 2011, 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
18 //#define LOG_NDEBUG 0
19 #define LOG_TAG "MemoryLeackTrackUtil"
20 #include <utils/Log.h>
21
22 #include <mediautils/MemoryLeakTrackUtil.h>
23 #include <sstream>
24
25 #include <bionic/malloc.h>
26
27 /*
28 * The code here originally resided in MediaPlayerService.cpp
29 */
30
31 // Figure out the abi based on defined macros.
32 #if defined(__arm__)
33 #define ABI_STRING "arm"
34 #elif defined(__aarch64__)
35 #define ABI_STRING "arm64"
36 #elif defined(__riscv)
37 #define ABI_STRING "riscv64"
38 #elif defined(__i386__)
39 #define ABI_STRING "x86"
40 #elif defined(__x86_64__)
41 #define ABI_STRING "x86_64"
42 #else
43 #error "Unsupported ABI"
44 #endif
45
46 extern std::string backtrace_string(const uintptr_t* frames, size_t frame_count);
47
48 namespace android {
49
dumpMemoryAddresses(size_t limit)50 std::string dumpMemoryAddresses(size_t limit)
51 {
52 android_mallopt_leak_info_t leak_info;
53 if (!android_mallopt(M_GET_MALLOC_LEAK_INFO, &leak_info, sizeof(leak_info))) {
54 return "";
55 }
56
57 size_t count;
58 if (leak_info.buffer == nullptr || leak_info.overall_size == 0 || leak_info.info_size == 0
59 || (count = leak_info.overall_size / leak_info.info_size) == 0) {
60 ALOGD("no malloc info, libc.debug.malloc.program property should be set");
61 return "";
62 }
63
64 std::ostringstream oss;
65 oss << leak_info.total_memory << " bytes in " << count << " allocations\n";
66 oss << " ABI: '" ABI_STRING "'" << "\n\n";
67 if (count > limit) count = limit;
68
69 // The memory is sorted based on total size which is useful for finding
70 // worst memory offenders. For diffs, sometimes it is preferable to sort
71 // based on the backtrace.
72 for (size_t i = 0; i < count; i++) {
73 struct AllocEntry {
74 size_t size; // bit 31 is set if this is zygote allocated memory
75 size_t allocations;
76 uintptr_t backtrace[];
77 };
78
79 const AllocEntry * const e = (AllocEntry *)(leak_info.buffer + i * leak_info.info_size);
80
81 oss << (e->size * e->allocations)
82 << " bytes ( " << e->size << " bytes * " << e->allocations << " allocations )\n";
83 oss << backtrace_string(e->backtrace, leak_info.backtrace_size) << "\n";
84 }
85 oss << "\n";
86 android_mallopt(M_FREE_MALLOC_LEAK_INFO, &leak_info, sizeof(leak_info));
87 return oss.str();
88 }
89
90 } // namespace android
91