blob: cc56a2189e7a54d149a7341cbb6367bf0b760c1c [file] [log] [blame]
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -08001#!/usr/bin/env python
2
3from bcc import BPF
4from time import sleep
5import argparse
6import subprocess
Sasha Goldshteincfce3112016-02-07 11:09:36 -08007import ctypes
8import os
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -08009
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080010class Time(object):
11 # Adapted from http://stackoverflow.com/a/1205762
12 CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h>
13
14 class timespec(ctypes.Structure):
15 _fields_ = [
16 ('tv_sec', ctypes.c_long),
17 ('tv_nsec', ctypes.c_long)
18 ]
19
20 librt = ctypes.CDLL('librt.so.1', use_errno=True)
21 clock_gettime = librt.clock_gettime
22 clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)]
23
24 @staticmethod
25 def monotonic_time():
26 """monotonic_time()
27 Returns the reading of the monotonic clock, in nanoseconds.
28 """
29 t = Time.timespec()
30 if Time.clock_gettime(Time.CLOCK_MONOTONIC_RAW , ctypes.pointer(t)) != 0:
31 errno_ = ctypes.get_errno()
32 raise OSError(errno_, os.strerror(errno_))
33 return t.tv_sec*1e9 + t.tv_nsec
34
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080035examples = """
36EXAMPLES:
37
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080038./memleak.py -p $(pidof allocs)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080039 Trace allocations and display a summary of "leaked" (outstanding)
40 allocations every 5 seconds
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080041./memleak.py -p $(pidof allocs) -t
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080042 Trace allocations and display each individual call to malloc/free
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080043./memleak.py -p $(pidof allocs) -a -i 10
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080044 Trace allocations and display allocated addresses, sizes, and stacks
45 every 10 seconds for outstanding allocations
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080046./memleak.py
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080047 Trace allocations in kernel mode and display a summary of outstanding
48 allocations every 5 seconds
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080049./memleak.py -o 60000
50 Trace allocations in kernel mode and display a summary of outstanding
51 allocations that are at least one minute (60 seconds) old
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080052"""
53
54description = """
55Trace outstanding memory allocations that weren't freed.
56Supports both user-mode allocations made with malloc/free and kernel-mode
57allocations made with kmalloc/kfree.
58"""
59
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -080060parser = argparse.ArgumentParser(description=description,
61 formatter_class=argparse.RawDescriptionHelpFormatter,
62 epilog=examples)
63parser.add_argument("-p", "--pid",
64 help="the PID to trace; if not specified, trace kernel allocs")
65parser.add_argument("-t", "--trace", action="store_true",
66 help="print trace messages for each alloc/free call")
67parser.add_argument("-i", "--interval", default=5,
68 help="interval in seconds to print outstanding allocations")
69parser.add_argument("-a", "--show-allocs", default=False, action="store_true",
70 help="show allocation addresses and sizes as well as call stacks")
71parser.add_argument("-o", "--older", default=500,
72 help="prune allocations younger than this age in milliseconds")
73# TODO Run a command and trace that command (-c)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080074
75args = parser.parse_args()
76
77pid = -1 if args.pid is None else int(args.pid)
78kernel_trace = (pid == -1)
79trace_all = args.trace
80interval = int(args.interval)
Sasha Goldshteincfce3112016-02-07 11:09:36 -080081min_age_ns = 1e6*int(args.older)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -080082
83bpf_source = open("memleak.c").read()
84bpf_source = bpf_source.replace("SHOULD_PRINT", "1" if trace_all else "0")
85
86bpf_program = BPF(text=bpf_source)
87
88if not kernel_trace:
89 print("Attaching to malloc and free in pid %d, Ctrl+C to quit." % pid)
90 bpf_program.attach_uprobe(name="c", sym="malloc", fn_name="alloc_enter", pid=pid)
91 bpf_program.attach_uretprobe(name="c", sym="malloc", fn_name="alloc_exit", pid=pid)
92 bpf_program.attach_uprobe(name="c", sym="free", fn_name="free_enter", pid=pid)
93else:
94 print("Attaching to kmalloc and kfree, Ctrl+C to quit.")
95 bpf_program.attach_kprobe(event="__kmalloc", fn_name="alloc_enter")
96 bpf_program.attach_kretprobe(event="__kmalloc", fn_name="alloc_exit")
97 bpf_program.attach_kprobe(event="kfree", fn_name="free_enter")
98
99def get_code_ranges(pid):
100 ranges = {}
101 raw_ranges = open("/proc/%d/maps" % pid).readlines()
102 for raw_range in raw_ranges:
103 parts = raw_range.split()
104 if len(parts) < 6 or parts[5][0] == '[' or not 'x' in parts[1]:
105 continue
106 binary = parts[5]
107 range_parts = parts[0].split('-')
108 addr_range = (int(range_parts[0], 16), int(range_parts[1], 16))
109 ranges[binary] = addr_range
110 return ranges
111
112def run_command(command):
113 p = subprocess.Popen(command.split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
114 return iter(p.stdout.readline, b'')
115
116ranges_cache = {}
117
118def get_sym_ranges(binary):
119 if binary in ranges_cache:
120 return ranges_cache[binary]
121 sym_ranges = {}
122 raw_symbols = run_command("objdump -t %s" % binary)
123 for raw_symbol in raw_symbols:
124 parts = raw_symbol.split()
125 if len(parts) < 6 or parts[3] != ".text" or parts[2] != "F":
126 continue
127 sym_start = int(parts[0], 16)
128 sym_len = int(parts[4], 16)
129 sym_name = parts[5]
130 sym_ranges[sym_name] = (sym_start, sym_len)
131 ranges_cache[binary] = sym_ranges
132 return sym_ranges
133
134def decode_sym(binary, offset):
135 sym_ranges = get_sym_ranges(binary)
136 for name, (start, length) in sym_ranges.items():
137 if offset >= start and offset <= (start + length):
138 return "%s+0x%x" % (name, offset - start)
139 return "%x" % offset
140
141def decode_addr(code_ranges, addr):
142 for binary, (start, end) in code_ranges.items():
143 if addr >= start and addr <= end:
144 offset = addr - start if binary.endswith(".so") else addr
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -0800145 return "%s [%s]" % (decode_sym(binary, offset), binary)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800146 return "%x" % addr
147
148def decode_stack(info):
149 stack = ""
150 if info.num_frames <= 0:
151 return "???"
152 for i in range(0, info.num_frames):
153 addr = info.callstack[i]
154 if kernel_trace:
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -0800155 stack += " %s [kernel] (%x) ;" % (bpf_program.ksym(addr), addr)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800156 else:
157 stack += " %s (%x) ;" % (decode_addr(code_ranges, addr), addr)
158 return stack
159
160def print_outstanding():
161 stacks = {}
162 print("*** Outstanding allocations:")
163 allocs = bpf_program.get_table("allocs")
164 for address, info in sorted(allocs.items(), key=lambda a: -a[1].size):
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -0800165 if Time.monotonic_time() - min_age_ns < info.timestamp_ns:
Sasha Goldshteincfce3112016-02-07 11:09:36 -0800166 continue
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800167 stack = decode_stack(info)
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -0800168 if stack in stacks: stacks[stack] = (stacks[stack][0] + 1, stacks[stack][1] + info.size)
169 else: stacks[stack] = (1, info.size)
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800170 if args.show_allocs:
171 print("\taddr = %x size = %s" % (address.value, info.size))
Sasha Goldshteina7cc6c22016-02-07 12:03:54 -0800172 for stack, (count, size) in sorted(stacks.items(), key=lambda s: -s[1][1]):
173 print("\t%d bytes in %d allocations from stack\n\t\t%s" % (size, count, stack.replace(";", "\n\t\t")))
Sasha Goldshtein4f1ea672016-02-07 01:57:42 -0800174
175while True:
176 if trace_all:
177 print bpf_program.trace_fields()
178 else:
179 try:
180 sleep(interval)
181 except KeyboardInterrupt:
182 exit()
183 if not kernel_trace:
184 code_ranges = get_code_ranges(pid)
185 print_outstanding()
186