blob: 5d6953888320193cb43583078128e3e6ca0f2f14 [file] [log] [blame]
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -08001#!/usr/bin/env python
Sasha Goldshtein50459642016-02-10 08:35:20 -08002#
Sasha Goldshtein0e856f42016-03-21 07:26:52 -07003# memleak Trace and display outstanding allocations to detect
4# memory leaks in user-mode processes and the kernel.
Sasha Goldshtein50459642016-02-10 08:35:20 -08005#
Sasha Goldshtein29e37d92016-02-14 06:56:07 -08006# USAGE: memleak [-h] [-p PID] [-t] [-a] [-o OLDER] [-c COMMAND]
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +03007# [--combined-only] [-s SAMPLE_RATE] [-T TOP] [-z MIN_SIZE]
8# [-Z MAX_SIZE] [-O OBJ]
Sasha Goldshtein0e856f42016-03-21 07:26:52 -07009# [interval] [count]
Sasha Goldshtein50459642016-02-10 08:35:20 -080010#
Sasha Goldshtein43fa0412016-02-10 22:17:26 -080011# Licensed under the Apache License, Version 2.0 (the "License")
Sasha Goldshtein50459642016-02-10 08:35:20 -080012# Copyright (C) 2016 Sasha Goldshtein.
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080013
Sasha Goldshtein49df9942017-02-08 23:22:06 -050014from bcc import BPF
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080015from time import sleep
Sasha Goldshteinc8148c82016-02-09 11:15:41 -080016from datetime import datetime
Yonghong Songeb6ddc02017-10-26 22:33:24 -070017import resource
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080018import argparse
19import subprocess
Sasha Goldshteincfce3112016-02-07 11:09:36 -080020import os
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080021
Vicent Martie25ae032016-03-25 17:14:34 +010022class Allocation(object):
23 def __init__(self, stack, size):
24 self.stack = stack
25 self.count = 1
26 self.size = size
27
28 def update(self, size):
29 self.count += 1
30 self.size += size
Sasha Goldshtein29228612016-02-07 12:20:19 -080031
Sasha Goldshtein751fce52016-02-08 02:57:02 -080032def run_command_get_output(command):
Sasha Goldshtein33522d72016-02-08 03:39:44 -080033 p = subprocess.Popen(command.split(),
34 stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
35 return iter(p.stdout.readline, b'')
Sasha Goldshtein29228612016-02-07 12:20:19 -080036
Sasha Goldshtein751fce52016-02-08 02:57:02 -080037def run_command_get_pid(command):
Sasha Goldshtein33522d72016-02-08 03:39:44 -080038 p = subprocess.Popen(command.split())
39 return p.pid
Sasha Goldshtein751fce52016-02-08 02:57:02 -080040
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080041examples = """
42EXAMPLES:
43
Sasha Goldshtein29e37d92016-02-14 06:56:07 -080044./memleak -p $(pidof allocs)
Sasha Goldshtein33522d72016-02-08 03:39:44 -080045 Trace allocations and display a summary of "leaked" (outstanding)
46 allocations every 5 seconds
Sasha Goldshtein29e37d92016-02-14 06:56:07 -080047./memleak -p $(pidof allocs) -t
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +030048 Trace allocations and display each individual allocator function call
Sasha Goldshtein29e37d92016-02-14 06:56:07 -080049./memleak -ap $(pidof allocs) 10
Sasha Goldshtein33522d72016-02-08 03:39:44 -080050 Trace allocations and display allocated addresses, sizes, and stacks
51 every 10 seconds for outstanding allocations
Sasha Goldshtein29e37d92016-02-14 06:56:07 -080052./memleak -c "./allocs"
Sasha Goldshtein33522d72016-02-08 03:39:44 -080053 Run the specified command and trace its allocations
Sasha Goldshtein29e37d92016-02-14 06:56:07 -080054./memleak
Sasha Goldshtein33522d72016-02-08 03:39:44 -080055 Trace allocations in kernel mode and display a summary of outstanding
56 allocations every 5 seconds
Sasha Goldshtein29e37d92016-02-14 06:56:07 -080057./memleak -o 60000
Sasha Goldshtein33522d72016-02-08 03:39:44 -080058 Trace allocations in kernel mode and display a summary of outstanding
59 allocations that are at least one minute (60 seconds) old
Sasha Goldshtein29e37d92016-02-14 06:56:07 -080060./memleak -s 5
Sasha Goldshtein521ab4f2016-02-08 05:48:31 -080061 Trace roughly every 5th allocation, to reduce overhead
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080062"""
63
64description = """
65Trace outstanding memory allocations that weren't freed.
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +030066Supports both user-mode allocations made with libc functions and kernel-mode
67allocations made with kmalloc/kmem_cache_alloc/get_free_pages and corresponding
68memory release functions.
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080069"""
70
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080071parser = argparse.ArgumentParser(description=description,
Sasha Goldshtein33522d72016-02-08 03:39:44 -080072 formatter_class=argparse.RawDescriptionHelpFormatter,
73 epilog=examples)
Sasha Goldshteind2241f42016-02-09 06:23:10 -080074parser.add_argument("-p", "--pid", type=int, default=-1,
Sasha Goldshtein33522d72016-02-08 03:39:44 -080075 help="the PID to trace; if not specified, trace kernel allocs")
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080076parser.add_argument("-t", "--trace", action="store_true",
Sasha Goldshtein33522d72016-02-08 03:39:44 -080077 help="print trace messages for each alloc/free call")
Sasha Goldshtein40e55ba2016-02-09 05:53:48 -080078parser.add_argument("interval", nargs="?", default=5, type=int,
Sasha Goldshtein33522d72016-02-08 03:39:44 -080079 help="interval in seconds to print outstanding allocations")
Sasha Goldshtein40e55ba2016-02-09 05:53:48 -080080parser.add_argument("count", nargs="?", type=int,
81 help="number of times to print the report before exiting")
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080082parser.add_argument("-a", "--show-allocs", default=False, action="store_true",
Sasha Goldshtein33522d72016-02-08 03:39:44 -080083 help="show allocation addresses and sizes as well as call stacks")
Sasha Goldshtein40e55ba2016-02-09 05:53:48 -080084parser.add_argument("-o", "--older", default=500, type=int,
Sasha Goldshtein33522d72016-02-08 03:39:44 -080085 help="prune allocations younger than this age in milliseconds")
Sasha Goldshtein29228612016-02-07 12:20:19 -080086parser.add_argument("-c", "--command",
Sasha Goldshtein33522d72016-02-08 03:39:44 -080087 help="execute and trace the specified command")
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +030088parser.add_argument("--combined-only", default=False, action="store_true",
89 help="show combined allocation statistics only")
Sasha Goldshtein40e55ba2016-02-09 05:53:48 -080090parser.add_argument("-s", "--sample-rate", default=1, type=int,
Sasha Goldshtein521ab4f2016-02-08 05:48:31 -080091 help="sample every N-th allocation to decrease the overhead")
Sasha Goldshteinc8148c82016-02-09 11:15:41 -080092parser.add_argument("-T", "--top", type=int, default=10,
93 help="display only this many top allocating stacks (by size)")
Sasha Goldshtein50459642016-02-10 08:35:20 -080094parser.add_argument("-z", "--min-size", type=int,
95 help="capture only allocations larger than this size")
96parser.add_argument("-Z", "--max-size", type=int,
97 help="capture only allocations smaller than this size")
Maria Kacik9389ab42017-01-18 21:43:41 -080098parser.add_argument("-O", "--obj", type=str, default="c",
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +030099 help="attach to allocator functions in the specified object")
Nathan Scottcf0792f2018-02-02 16:56:50 +1100100parser.add_argument("--ebpf", action="store_true",
101 help=argparse.SUPPRESS)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800102
103args = parser.parse_args()
104
Sasha Goldshteind2241f42016-02-09 06:23:10 -0800105pid = args.pid
Sasha Goldshtein29228612016-02-07 12:20:19 -0800106command = args.command
107kernel_trace = (pid == -1 and command is None)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800108trace_all = args.trace
Sasha Goldshtein40e55ba2016-02-09 05:53:48 -0800109interval = args.interval
110min_age_ns = 1e6 * args.older
Sasha Goldshtein521ab4f2016-02-08 05:48:31 -0800111sample_every_n = args.sample_rate
Sasha Goldshtein40e55ba2016-02-09 05:53:48 -0800112num_prints = args.count
Sasha Goldshteinc8148c82016-02-09 11:15:41 -0800113top_stacks = args.top
Sasha Goldshtein50459642016-02-10 08:35:20 -0800114min_size = args.min_size
115max_size = args.max_size
Maria Kacik9389ab42017-01-18 21:43:41 -0800116obj = args.obj
Sasha Goldshtein50459642016-02-10 08:35:20 -0800117
118if min_size is not None and max_size is not None and min_size > max_size:
119 print("min_size (-z) can't be greater than max_size (-Z)")
120 exit(1)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800121
Sasha Goldshtein33522d72016-02-08 03:39:44 -0800122if command is not None:
123 print("Executing '%s' and tracing the resulting process." % command)
124 pid = run_command_get_pid(command)
Sasha Goldshtein29228612016-02-07 12:20:19 -0800125
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800126bpf_source = """
127#include <uapi/linux/ptrace.h>
128
129struct alloc_info_t {
130 u64 size;
131 u64 timestamp_ns;
Vicent Martie25ae032016-03-25 17:14:34 +0100132 int stack_id;
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800133};
134
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300135struct combined_alloc_info_t {
136 u64 total_size;
137 u64 number_of_allocs;
138};
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800139
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300140BPF_HASH(sizes, u64);
141BPF_TABLE("hash", u64, struct alloc_info_t, allocs, 1000000);
142BPF_HASH(memptrs, u64, u64);
Song Liu67ae6052018-02-01 14:59:24 -0800143BPF_STACK_TRACE(stack_traces, 10240);
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300144BPF_TABLE("hash", u64, struct combined_alloc_info_t, combined_allocs, 10240);
145
146static inline void update_statistics_add(u64 stack_id, u64 sz) {
147 struct combined_alloc_info_t *existing_cinfo;
148 struct combined_alloc_info_t cinfo = {0};
149
150 existing_cinfo = combined_allocs.lookup(&stack_id);
151 if (existing_cinfo != 0)
152 cinfo = *existing_cinfo;
153
154 cinfo.total_size += sz;
155 cinfo.number_of_allocs += 1;
156
157 combined_allocs.update(&stack_id, &cinfo);
158}
159
160static inline void update_statistics_del(u64 stack_id, u64 sz) {
161 struct combined_alloc_info_t *existing_cinfo;
162 struct combined_alloc_info_t cinfo = {0};
163
164 existing_cinfo = combined_allocs.lookup(&stack_id);
165 if (existing_cinfo != 0)
166 cinfo = *existing_cinfo;
167
168 if (sz >= cinfo.total_size)
169 cinfo.total_size = 0;
170 else
171 cinfo.total_size -= sz;
172
173 if (cinfo.number_of_allocs > 0)
174 cinfo.number_of_allocs -= 1;
175
176 combined_allocs.update(&stack_id, &cinfo);
177}
178
179static inline int gen_alloc_enter(struct pt_regs *ctx, size_t size) {
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800180 SIZE_FILTER
181 if (SAMPLE_EVERY_N > 1) {
182 u64 ts = bpf_ktime_get_ns();
183 if (ts % SAMPLE_EVERY_N != 0)
184 return 0;
185 }
186
187 u64 pid = bpf_get_current_pid_tgid();
188 u64 size64 = size;
189 sizes.update(&pid, &size64);
190
191 if (SHOULD_PRINT)
192 bpf_trace_printk("alloc entered, size = %u\\n", size);
193 return 0;
194}
195
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300196static inline int gen_alloc_exit2(struct pt_regs *ctx, u64 address) {
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800197 u64 pid = bpf_get_current_pid_tgid();
198 u64* size64 = sizes.lookup(&pid);
199 struct alloc_info_t info = {0};
200
201 if (size64 == 0)
202 return 0; // missed alloc entry
203
204 info.size = *size64;
205 sizes.delete(&pid);
206
207 info.timestamp_ns = bpf_ktime_get_ns();
Vicent Martie25ae032016-03-25 17:14:34 +0100208 info.stack_id = stack_traces.get_stackid(ctx, STACK_FLAGS);
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800209 allocs.update(&address, &info);
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300210 update_statistics_add(info.stack_id, info.size);
Sasha Goldshtein0e856f42016-03-21 07:26:52 -0700211
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800212 if (SHOULD_PRINT) {
Vicent Martie25ae032016-03-25 17:14:34 +0100213 bpf_trace_printk("alloc exited, size = %lu, result = %lx\\n",
214 info.size, address);
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800215 }
216 return 0;
217}
218
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300219static inline int gen_alloc_exit(struct pt_regs *ctx) {
220 return gen_alloc_exit2(ctx, PT_REGS_RC(ctx));
221}
222
223static inline int gen_free_enter(struct pt_regs *ctx, void *address) {
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800224 u64 addr = (u64)address;
225 struct alloc_info_t *info = allocs.lookup(&addr);
226 if (info == 0)
227 return 0;
228
229 allocs.delete(&addr);
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300230 update_statistics_del(info->stack_id, info->size);
Sasha Goldshtein43fa0412016-02-10 22:17:26 -0800231
232 if (SHOULD_PRINT) {
233 bpf_trace_printk("free entered, address = %lx, size = %lu\\n",
234 address, info->size);
235 }
236 return 0;
237}
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300238
239int malloc_enter(struct pt_regs *ctx, size_t size) {
240 return gen_alloc_enter(ctx, size);
241}
242
243int malloc_exit(struct pt_regs *ctx) {
244 return gen_alloc_exit(ctx);
245}
246
247int free_enter(struct pt_regs *ctx, void *address) {
248 return gen_free_enter(ctx, address);
249}
250
251int calloc_enter(struct pt_regs *ctx, size_t nmemb, size_t size) {
252 return gen_alloc_enter(ctx, nmemb * size);
253}
254
255int calloc_exit(struct pt_regs *ctx) {
256 return gen_alloc_exit(ctx);
257}
258
259int realloc_enter(struct pt_regs *ctx, void *ptr, size_t size) {
260 gen_free_enter(ctx, ptr);
261 return gen_alloc_enter(ctx, size);
262}
263
264int realloc_exit(struct pt_regs *ctx) {
265 return gen_alloc_exit(ctx);
266}
267
268int posix_memalign_enter(struct pt_regs *ctx, void **memptr, size_t alignment,
269 size_t size) {
270 u64 memptr64 = (u64)(size_t)memptr;
271 u64 pid = bpf_get_current_pid_tgid();
272
273 memptrs.update(&pid, &memptr64);
274 return gen_alloc_enter(ctx, size);
275}
276
277int posix_memalign_exit(struct pt_regs *ctx) {
278 u64 pid = bpf_get_current_pid_tgid();
279 u64 *memptr64 = memptrs.lookup(&pid);
280 void *addr;
281
282 if (memptr64 == 0)
283 return 0;
284
285 memptrs.delete(&pid);
286
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200287 if (bpf_probe_read(&addr, sizeof(void*), (void*)(size_t)*memptr64))
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300288 return 0;
289
290 u64 addr64 = (u64)(size_t)addr;
291 return gen_alloc_exit2(ctx, addr64);
292}
293
294int aligned_alloc_enter(struct pt_regs *ctx, size_t alignment, size_t size) {
295 return gen_alloc_enter(ctx, size);
296}
297
298int aligned_alloc_exit(struct pt_regs *ctx) {
299 return gen_alloc_exit(ctx);
300}
301
302int valloc_enter(struct pt_regs *ctx, size_t size) {
303 return gen_alloc_enter(ctx, size);
304}
305
306int valloc_exit(struct pt_regs *ctx) {
307 return gen_alloc_exit(ctx);
308}
309
310int memalign_enter(struct pt_regs *ctx, size_t alignment, size_t size) {
311 return gen_alloc_enter(ctx, size);
312}
313
314int memalign_exit(struct pt_regs *ctx) {
315 return gen_alloc_exit(ctx);
316}
317
318int pvalloc_enter(struct pt_regs *ctx, size_t size) {
319 return gen_alloc_enter(ctx, size);
320}
321
322int pvalloc_exit(struct pt_regs *ctx) {
323 return gen_alloc_exit(ctx);
324}
Sasha Goldshtein0e856f42016-03-21 07:26:52 -0700325"""
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300326
327bpf_source_kernel = """
328
329TRACEPOINT_PROBE(kmem, kmalloc) {
330 gen_alloc_enter((struct pt_regs *)args, args->bytes_alloc);
331 return gen_alloc_exit2((struct pt_regs *)args, (size_t)args->ptr);
332}
333
334TRACEPOINT_PROBE(kmem, kmalloc_node) {
335 gen_alloc_enter((struct pt_regs *)args, args->bytes_alloc);
336 return gen_alloc_exit2((struct pt_regs *)args, (size_t)args->ptr);
337}
338
339TRACEPOINT_PROBE(kmem, kfree) {
340 return gen_free_enter((struct pt_regs *)args, (void *)args->ptr);
341}
342
343TRACEPOINT_PROBE(kmem, kmem_cache_alloc) {
344 gen_alloc_enter((struct pt_regs *)args, args->bytes_alloc);
345 return gen_alloc_exit2((struct pt_regs *)args, (size_t)args->ptr);
346}
347
348TRACEPOINT_PROBE(kmem, kmem_cache_alloc_node) {
349 gen_alloc_enter((struct pt_regs *)args, args->bytes_alloc);
350 return gen_alloc_exit2((struct pt_regs *)args, (size_t)args->ptr);
351}
352
353TRACEPOINT_PROBE(kmem, kmem_cache_free) {
354 return gen_free_enter((struct pt_regs *)args, (void *)args->ptr);
355}
356
357TRACEPOINT_PROBE(kmem, mm_page_alloc) {
358 gen_alloc_enter((struct pt_regs *)args, PAGE_SIZE << args->order);
359 return gen_alloc_exit2((struct pt_regs *)args, args->pfn);
360}
361
362TRACEPOINT_PROBE(kmem, mm_page_free) {
363 return gen_free_enter((struct pt_regs *)args, (void *)args->pfn);
364}
365"""
366
367if kernel_trace:
368 bpf_source += bpf_source_kernel
369
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800370bpf_source = bpf_source.replace("SHOULD_PRINT", "1" if trace_all else "0")
Sasha Goldshtein521ab4f2016-02-08 05:48:31 -0800371bpf_source = bpf_source.replace("SAMPLE_EVERY_N", str(sample_every_n))
Yonghong Songeb6ddc02017-10-26 22:33:24 -0700372bpf_source = bpf_source.replace("PAGE_SIZE", str(resource.getpagesize()))
Sasha Goldshtein50459642016-02-10 08:35:20 -0800373
374size_filter = ""
375if min_size is not None and max_size is not None:
376 size_filter = "if (size < %d || size > %d) return 0;" % \
377 (min_size, max_size)
378elif min_size is not None:
379 size_filter = "if (size < %d) return 0;" % min_size
380elif max_size is not None:
381 size_filter = "if (size > %d) return 0;" % max_size
382bpf_source = bpf_source.replace("SIZE_FILTER", size_filter)
383
Vicent Martie25ae032016-03-25 17:14:34 +0100384stack_flags = "BPF_F_REUSE_STACKID"
385if not kernel_trace:
386 stack_flags += "|BPF_F_USER_STACK"
387bpf_source = bpf_source.replace("STACK_FLAGS", stack_flags)
388
Nathan Scottcf0792f2018-02-02 16:56:50 +1100389if args.ebpf:
390 print(bpf_source)
391 exit()
392
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200393bpf = BPF(text=bpf_source)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800394
395if not kernel_trace:
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300396 print("Attaching to pid %d, Ctrl+C to quit." % pid)
397
398 def attach_probes(sym, fn_prefix=None, can_fail=False):
399 if fn_prefix is None:
400 fn_prefix = sym
401
402 try:
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200403 bpf.attach_uprobe(name=obj, sym=sym,
404 fn_name=fn_prefix + "_enter",
405 pid=pid)
406 bpf.attach_uretprobe(name=obj, sym=sym,
407 fn_name=fn_prefix + "_exit",
408 pid=pid)
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300409 except Exception:
410 if can_fail:
411 return
412 else:
413 raise
414
415 attach_probes("malloc")
416 attach_probes("calloc")
417 attach_probes("realloc")
418 attach_probes("posix_memalign")
419 attach_probes("valloc")
420 attach_probes("memalign")
421 attach_probes("pvalloc")
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200422 attach_probes("aligned_alloc", can_fail=True) # added in C11
423 bpf.attach_uprobe(name=obj, sym="free", fn_name="free_enter",
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300424 pid=pid)
425
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800426else:
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300427 print("Attaching to kernel allocators, Ctrl+C to quit.")
428
429 # No probe attaching here. Allocations are counted by attaching to
430 # tracepoints.
431 #
432 # Memory allocations in Linux kernel are not limited to malloc/free
433 # equivalents. It's also common to allocate a memory page or multiple
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200434 # pages. Page allocator have two interfaces, one working with page
435 # frame numbers (PFN), while other working with page addresses. It's
436 # possible to allocate pages with one kind of functions, and free them
437 # with another. Code in kernel can easy convert PFNs to addresses and
438 # back, but it's hard to do the same in eBPF kprobe without fragile
439 # hacks.
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300440 #
441 # Fortunately, Linux exposes tracepoints for memory allocations, which
442 # can be instrumented by eBPF programs. Tracepoint for page allocations
443 # gives access to PFNs for both allocator interfaces. So there is no
444 # need to guess which allocation corresponds to which free.
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800445
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800446def print_outstanding():
Sasha Goldshteinc8148c82016-02-09 11:15:41 -0800447 print("[%s] Top %d stacks with outstanding allocations:" %
448 (datetime.now().strftime("%H:%M:%S"), top_stacks))
Vicent Martie25ae032016-03-25 17:14:34 +0100449 alloc_info = {}
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200450 allocs = bpf["allocs"]
451 stack_traces = bpf["stack_traces"]
Sasha Goldshtein33522d72016-02-08 03:39:44 -0800452 for address, info in sorted(allocs.items(), key=lambda a: a[1].size):
Sasha Goldshtein60c41922017-02-09 04:19:53 -0500453 if BPF.monotonic_time() - min_age_ns < info.timestamp_ns:
Sasha Goldshtein33522d72016-02-08 03:39:44 -0800454 continue
Vicent Martie25ae032016-03-25 17:14:34 +0100455 if info.stack_id < 0:
456 continue
457 if info.stack_id in alloc_info:
458 alloc_info[info.stack_id].update(info.size)
Sasha Goldshtein33522d72016-02-08 03:39:44 -0800459 else:
Sasha Goldshtein49df9942017-02-08 23:22:06 -0500460 stack = list(stack_traces.walk(info.stack_id))
461 combined = []
462 for addr in stack:
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200463 combined.append(bpf.sym(addr, pid,
Sasha Goldshtein01553852017-02-09 03:58:09 -0500464 show_module=True, show_offset=True))
Sasha Goldshtein49df9942017-02-08 23:22:06 -0500465 alloc_info[info.stack_id] = Allocation(combined,
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300466 info.size)
Sasha Goldshtein33522d72016-02-08 03:39:44 -0800467 if args.show_allocs:
468 print("\taddr = %x size = %s" %
469 (address.value, info.size))
Sasha Goldshteinf41ae862016-10-19 01:14:30 +0300470 to_show = sorted(alloc_info.values(),
471 key=lambda a: a.size)[-top_stacks:]
Vicent Martie25ae032016-03-25 17:14:34 +0100472 for alloc in to_show:
Sasha Goldshtein33522d72016-02-08 03:39:44 -0800473 print("\t%d bytes in %d allocations from stack\n\t\t%s" %
Brenden Blanco42d60982017-04-24 14:31:28 -0700474 (alloc.size, alloc.count, b"\n\t\t".join(alloc.stack)))
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800475
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300476def print_outstanding_combined():
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200477 stack_traces = bpf["stack_traces"]
478 stacks = sorted(bpf["combined_allocs"].items(),
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300479 key=lambda a: -a[1].total_size)
480 cnt = 1
481 entries = []
482 for stack_id, info in stacks:
483 try:
484 trace = []
485 for addr in stack_traces.walk(stack_id.value):
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200486 sym = bpf.sym(addr, pid,
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300487 show_module=True,
488 show_offset=True)
489 trace.append(sym)
490 trace = "\n\t\t".join(trace)
491 except KeyError:
492 trace = "stack information lost"
493
494 entry = ("\t%d bytes in %d allocations from stack\n\t\t%s" %
495 (info.total_size, info.number_of_allocs, trace))
496 entries.append(entry)
497
498 cnt += 1
499 if cnt > top_stacks:
500 break
501
502 print("[%s] Top %d stacks with outstanding allocations:" %
503 (datetime.now().strftime("%H:%M:%S"), top_stacks))
504
505 print('\n'.join(reversed(entries)))
506
Sasha Goldshtein40e55ba2016-02-09 05:53:48 -0800507count_so_far = 0
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800508while True:
Sasha Goldshtein33522d72016-02-08 03:39:44 -0800509 if trace_all:
Paul Chaignon2e07ddc2017-10-07 11:07:10 +0200510 print(bpf.trace_fields())
Sasha Goldshtein33522d72016-02-08 03:39:44 -0800511 else:
512 try:
513 sleep(interval)
514 except KeyboardInterrupt:
515 exit()
Rinat Ibragimov2c1799c2017-07-11 21:14:08 +0300516 if args.combined_only:
517 print_outstanding_combined()
518 else:
519 print_outstanding()
Sasha Goldshtein40e55ba2016-02-09 05:53:48 -0800520 count_so_far += 1
521 if num_prints is not None and count_so_far >= num_prints:
522 exit()