Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(10)

Side by Side Diff: tools/android/heap_profiler/heap_profiler.c

Issue 323893002: [Android] Introduce libheap_profiler for memory profiling. (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: Created 6 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
(Empty)
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 // This is a OS-independent* module which purpose is tracking allocations and
6 // their call sites (stack traces). It is able to deal with hole punching
7 // (read: munmap). Also, it is very fast and its presence in the system its
8 // barely noticeable, even if tracing *all* the processes.
9 // This module does NOT know how to deal with stack unwinding. The caller must
10 // do that and pass the addresses of the unwound stack.
11 // * (Modulo three lines for mutexes.)
12 //
13 // Exposed API:
14 // void heap_profiler_init(HeapStats*);
15 // void heap_profiler_alloc(addr, size, stack_frames, depth, flags);
16 // void heap_profiler_free(addr, size); (size == 0 means free entire region).
17 //
18 // The profiling information is tracked into two data structures:
19 // 1) A RB-Tree of non overlapping virtual memory regions (VMAs) sorted by their
20 // start addr. Each entry tracks the start-end addresses and points to the
21 // stack trace which created that allocation (see below).
22 // 2) A (hash) table of stack traces. In general the #allocations >> #call sites
23 // which create those allocations. In order to avoid duplicating the latter,
24 // they are stored distinctly in this hash table and used by reference.
25 //
26 // / Process virtual address space \
27 // +------+ +------+ +------+
28 // | VMA1 | | VMA2 | | VMA3 | <- VMAs (a RB-Tree underneath)
29 // +------+ +------+ +------+
30 // Len: 12 Len: 4 Len: 4
31 // | | | stack_traces
32 // | | | +-----------+--------------+
33 // | | | | Alloc tot | stack frames +
34 // | | | +-----------+--------------+
35 // +------------|-------------+------------> | 16 | 0x1234 .... |
36 // | +-----------+--------------+
37 // +--------------------------> | 4 | 0x5678 .... |
38 // +-----------+--------------+
39 // (A hash-table underneath)
40 //
41 // Final note: the memory for both 1) and 2) entries is carved out from two
42 // static pools (i.e. stack_traces and vmas). The pools are treated as
43 // a sbrk essentially, and are kept compact by reusing freed elements (hence
44 // having a freelist for each of them).
45 //
46 // All the internal (static) functions here assume that the |lock| is held.
47
48 #include <assert.h>
49 #include <string.h>
50
51 // Platform-dependent mutex boilerplate.
52 #if defined(__linux__) || defined(__ANDROID__)
53 #include <pthread.h>
54 #define DEFINE_MUTEX(x) pthread_mutex_t x = PTHREAD_MUTEX_INITIALIZER
55 #define LOCK_MUTEX(x) pthread_mutex_lock(&x)
56 #define UNLOCK_MUTEX(x) pthread_mutex_unlock(&x)
57 #else
58 #error OS not supported.
59 #endif
60
61 #include "tools/android/heap_profiler/heap_profiler.h"
62
63
64 static DEFINE_MUTEX(lock);
65
66 // |stats| contains the global tracking metadata and is the entry point which
67 // is read by the hdump tool.
68 static HeapStats* stats;
69
70
71 // +---------------------------------------------------------------------------+
72 // + Stack traces hash-table +
73 // +---------------------------------------------------------------------------+
74 #define ST_ENTRIES_MAX (64 * 1024)
75 #define ST_HASHTABLE_BUCKETS (64 * 1024) /* Must be a power of 2. */
76
77 static StacktraceEntry stack_traces[ST_ENTRIES_MAX];
78 static StacktraceEntry* stack_traces_freelist;
79 static StacktraceEntry* stack_traces_ht[ST_HASHTABLE_BUCKETS];
80
81 // Looks up a stack trace from the stack frames. Creates a new one if necessary.
82 static StacktraceEntry* record_stacktrace(uintptr_t* frames, uint32_t depth) {
83 if (depth == 0)
84 return NULL;
85
86 if (depth > HEAP_PROFILER_MAX_DEPTH)
87 depth = HEAP_PROFILER_MAX_DEPTH;
88
89 uint32_t i;
90 uintptr_t hash = 0;
91 for (i = 0; i < depth; ++i)
92 hash = (hash << 1) ^ (frames[i]);
93 const uint32_t slot = hash & (ST_HASHTABLE_BUCKETS - 1);
94 StacktraceEntry* st = stack_traces_ht[slot];
95
96 // Look for an existing entry in the hash-table.
97 const size_t frames_length = depth * sizeof(uintptr_t);
98 while (st != NULL && st->hash != hash &&
99 memcmp(frames, st->frames, frames_length) != 0) {
100 st = st->next;
101 }
102
103 // Is none is found, create a new one from the stack_traces array and add it
104 // to the hash-table.
105 if (st == NULL) {
106 // Get a free element either from the freelist or from the pool.
107 if (stack_traces_freelist != NULL) {
108 st = stack_traces_freelist;
109 stack_traces_freelist = stack_traces_freelist->next;
110 } else if (stats->max_stack_traces < ST_ENTRIES_MAX) {
111 st = &stack_traces[stats->max_stack_traces];
112 ++stats->max_stack_traces;
113 } else {
114 return NULL;
115 }
116
117 memset(st, 0, sizeof(*st));
118 memcpy(st->frames, frames, frames_length);
119 st->hash = hash;
120 st->next = stack_traces_ht[slot];
121 stack_traces_ht[slot] = st;
122 ++stats->num_stack_traces;
123 }
124
125 return st;
126 }
127
128 // Frees up a stack trace and appends it to the corresponding freelist.
129 static void free_stacktrace(StacktraceEntry* st) {
130 assert(st->alloc_bytes == 0);
131 const uint32_t slot = st->hash & (ST_HASHTABLE_BUCKETS - 1);
132
133 // The expected load factor of the hash-table is very low. Frees should be
134 // pretty rare. Hence don't bother with a doubly linked list, might cost more.
135 StacktraceEntry** prev = &stack_traces_ht[slot];
136 while (*prev != st)
137 prev = &((*prev)->next);
138
139 // Remove from the hash-table bucket.
140 assert(*prev == st);
141 *prev = st->next;
142
143 // Add to the freelist.
144 st->next = stack_traces_freelist;
145 stack_traces_freelist = st;
146 --stats->num_stack_traces;
147 }
148
149 // +---------------------------------------------------------------------------+
150 // + VMAs RB-tree +
151 // +---------------------------------------------------------------------------+
152 #define VMA_ENTRIES_MAX (256 * 1024)
153
154 static VMA vmas[VMA_ENTRIES_MAX];
155 static VMA* vmas_freelist;
156 static RB_HEAD(HeapEntriesTree, VMA) vmas_tree = RB_INITIALIZER(&vmas_tree);
157
158 // Comparator used by the RB-Tree (mind the overflow, avoid arith on addresses).
159 static int vmas_tree_cmp(VMA *e1, VMA *e2) {
160 if (e1->start < e2->start)
161 return -1;
162 if (e1->start > e2->start)
163 return 1;
164 return 0;
165 }
166
167 RB_PROTOTYPE(HeapEntriesTree, VMA, rb_node, vmas_tree_cmp);
168 RB_GENERATE(HeapEntriesTree, VMA, rb_node, vmas_tree_cmp);
169
170 // Allocates a new VMA and inserts it in the tree.
171 static VMA* insert_vma(
172 uintptr_t start, uintptr_t end, StacktraceEntry* st, uint32_t flags) {
173 VMA* vma = NULL;
174
175 // First of all, get a free element either from the freelist or from the pool.
176 if (vmas_freelist != NULL) {
177 vma = vmas_freelist;
178 vmas_freelist = vma->next_free;
179 } else if (stats->max_allocs < VMA_ENTRIES_MAX) {
180 vma = &vmas[stats->max_allocs];
181 ++stats->max_allocs;
182 } else {
183 return NULL; // OOM.
184 }
185
186 vma->start = start;
187 vma->end = end;
188 vma->st = st;
189 vma->flags = flags;
190 vma->next_free = NULL;
191 RB_INSERT(HeapEntriesTree, &vmas_tree, vma);
192 ++stats->num_allocs;
193 return vma;
194 }
195
196 // Deletes all the vmas in the range [addr, addr+size[ dealing with partial
197 // frees and hole punching. Note that in the general case this function might
198 // need to deal with very unfortunate cases, as below:
199 //
200 // VMA tree @ begin: [ VMA 1 ]----[ VMA 2 ]-------[ VMA 3 ][ VMA 4 ]---[ VMA 5 ]
201 // Deletion range: [xxxxxxxxxxxxxxxxxxxx]
202 // VMA tree @ end: [ VMA 1 ]----[VMA2]----------------------[VMA4]---[ VMA 5 ]
203 // VMA3 has to be deleted and VMA 2,4 shrunk.
204 static uint32_t delete_vmas_in_range(void* addr, size_t size) {
205 uintptr_t del_start = (uintptr_t) addr;
206 uintptr_t del_end = del_start + size - 1;
207 uint32_t flags = 0;
208
209 VMA* vma = NULL;
210 VMA* next_vma = RB_ROOT(&vmas_tree);
211
212 // Lookup the first (by address) relevant VMA to initiate the deletion walk.
213 // At the end of the loop next_vma is either:
214 // - the closest VMA starting before (or exactly at) the start of the deletion
215 // range (i.e. addr == del_start).
216 // - the first VMA inside the deletion range.
217 // - the first VMA after the deletion range iff the range was already empty
218 // (in this case the next loop will just bail out doing nothing).
219 // - NULL: iff the entire tree is empty (as above).
220 while (next_vma != NULL) {
221 vma = next_vma;
222 if (vma->start > del_start) {
223 next_vma = RB_LEFT(vma, rb_node);
224 } else if (vma->end < del_start) {
225 next_vma = RB_RIGHT(vma, rb_node);
226 } else { // vma->start <= del_start && vma->end >= del_start
227 break;
228 }
229 }
230
231 // Now scan the VMAs linearly deleting chunks (or eventually the whole VMAs)
232 // until passing the end of the deleting region.
233 next_vma = vma;
234 while (next_vma != NULL) {
235 vma = next_vma;
236 next_vma = RB_NEXT(HeapEntriesTree, &vmas_tree, vma);
237
238 if (size != 0) {
239 // In the general case we stop passed the end of the deletion range.
240 if (vma->start > del_end)
241 break;
242
243 // This deals with the case of the first VMA laying before the range.
244 if (vma->end < del_start)
245 continue;
246 } else {
247 // size == 0 is a special case. It means deleting only the vma which
248 // starts exactly @ |del_start| if any (for dealing with free(ptr)).
249 if (vma->start > del_start)
250 break;
251 if (vma->start < del_start)
252 continue;
253 del_end = vma->end;
254 }
255
256 // Reached this point the VMA must overlap (partially or completely) with
257 // the deletion range.
258 assert(!(vma->start > del_end || vma->end < del_start));
259
260 StacktraceEntry* st = vma->st;
261 flags |= vma->flags;
262 uintptr_t freed_bytes = 0; // Bytes freed in this cycle.
263
264 if (del_start <= vma->start) {
265 if (del_end >= vma->end) {
266 // Complete overlap. Delete full VMA. Note: the range might might still
267 // overlap with the next vmas.
268 // Begin: ------[vma.start vma.end]-[next vma]
269 // Del range: [xxxxxxxxxxxxxxxxxxxxxxxxxxxx]
270 // Result: -----------------------------[next vma]
271 // Note: at the next iteration we'll deal with the next vma.
272 freed_bytes = vma->end - vma->start + 1;
273 RB_REMOVE(HeapEntriesTree, &vmas_tree, vma);
274
275 // Clean-up, so hdump can tell this is a free entry and skip it.
276 vma->start = vma->end = 0;
277 vma->st = NULL;
278
279 // Put in the freelist.
280 vma->next_free = vmas_freelist;
281 vmas_freelist = vma;
282 --stats->num_allocs;
283 } else {
284 // Partial overlap at beginning. Cut first part and shrink the vma.
285 // Begin: ------[vma.start vma.end]-[next vma]
286 // Del range: [xxxxxx]
287 // Result: ------------[start vma.end]-[next vma]
288 freed_bytes = del_end - vma->start + 1;
289 vma->start = del_end + 1;
290 // No need to update the tree even if we changed the key. The keys are
291 // still monotonic (because the ranges are guaranteed to not overlap).
292 }
293 } else {
294 if (del_end >= vma->end) {
295 // Partial overlap at end. Cut last part and shrink the vma left.
296 // Begin: ------[vma.start vma.end]-[next vma]
297 // Del range: [xxxxxx]
298 // Result: ------[vma.start vma.end]-[next vma]
299 // Note: at the next iteration we'll deal with the next vma.
300 freed_bytes = vma->end - del_start + 1;
301 vma->end = del_start - 1;
302 } else {
303 // Hole punching. Requires creating an extra vma.
304 // Begin: ------[vma.start vma.end]-[next vma]
305 // Del range: [xxx]
306 // Result: ------[ vma 1 ]-----[ vma 2 ]-[next vma]
307 freed_bytes = del_end - del_start + 1;
308 const uintptr_t old_end = vma->end;
309 vma->end = del_start - 1;
310 insert_vma(del_end + 1, old_end, st, vma->flags);
311 }
312 }
313 // Now update the StackTraceEntry the VMA was pointing to, eventually
314 // freeing it up.
315 assert(st->alloc_bytes >= freed_bytes);
316 st->alloc_bytes -= freed_bytes;
317 if (st->alloc_bytes == 0)
318 free_stacktrace(st);
319 stats->total_alloc_bytes -= freed_bytes;
320 }
321 return flags;
322 }
323
324 // +---------------------------------------------------------------------------+
325 // + Library entry points (refer to heap_profiler.h for API doc). +
326 // +---------------------------------------------------------------------------+
327 void heap_profiler_free(void* addr, size_t size, uint32_t* old_flags) {
328 assert(size == 0 || ((uintptr_t) addr + (size - 1)) >= (uintptr_t) addr);
329
330 LOCK_MUTEX(lock);
331 uint32_t flags = delete_vmas_in_range(addr, size);
332 UNLOCK_MUTEX(lock);
333
334 if (old_flags != NULL)
335 *old_flags = flags;
336 }
337
338 void heap_profiler_alloc(void* addr, size_t size, uintptr_t* frames,
339 uint32_t depth, uint32_t flags) {
340 if (depth > HEAP_PROFILER_MAX_DEPTH)
341 depth = HEAP_PROFILER_MAX_DEPTH;
342
343 if (size == 0) // Apps calling malloc(0), sometimes it happens.
344 return;
345
346 const uintptr_t start = (uintptr_t) addr;
347 const uintptr_t end = start + (size - 1);
348 assert(start <= end);
349
350 LOCK_MUTEX(lock);
351
352 delete_vmas_in_range(addr, size);
353
354 StacktraceEntry* st = record_stacktrace(frames, depth);
355 if (st != NULL) {
356 VMA* vma = insert_vma(start, end, st, flags);
357 if (vma != NULL) {
358 st->alloc_bytes += size;
359 stats->total_alloc_bytes += size;
360 }
361 }
362
363 UNLOCK_MUTEX(lock);
364 }
365
366 void heap_profiler_init(HeapStats* heap_stats) {
367 LOCK_MUTEX(lock);
368
369 assert(stats == NULL);
370 stats = heap_stats;
371 memset(stats, 0, sizeof(HeapStats));
372 stats->magic_start = HEAP_PROFILER_MAGIC_MARKER;
373 stats->allocs = &vmas[0];
374 stats->stack_traces = &stack_traces[0];
375
376 UNLOCK_MUTEX(lock);
377 }
378
379 void heap_profiler_cleanup(void) {
380 LOCK_MUTEX(lock);
381
382 assert(stats != NULL);
383 memset(stack_traces, 0, sizeof(StacktraceEntry) * stats->max_stack_traces);
384 memset(stack_traces_ht, 0, sizeof(stack_traces_ht));
385 stack_traces_freelist = NULL;
386
387 memset(vmas, 0, sizeof(VMA) * stats->max_allocs);
388 vmas_freelist = NULL;
389 RB_INIT(&vmas_tree);
390
391 stats = NULL;
392
393 UNLOCK_MUTEX(lock);
394 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698