Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | |
| 3 | from bcc import BPF |
| 4 | from time import sleep |
| 5 | import argparse |
| 6 | import subprocess |
Sasha Goldshtein | cfce311 | 2016-02-07 11:09:36 -0800 | [diff] [blame] | 7 | import ctypes |
| 8 | import os |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 9 | |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 10 | class Time(object): |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 11 | # BPF timestamps come from the monotonic clock. To be able to filter |
| 12 | # and compare them from Python, we need to invoke clock_gettime. |
| 13 | # Adapted from http://stackoverflow.com/a/1205762 |
| 14 | CLOCK_MONOTONIC_RAW = 4 # see <linux/time.h> |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 15 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 16 | class timespec(ctypes.Structure): |
| 17 | _fields_ = [ |
| 18 | ('tv_sec', ctypes.c_long), |
| 19 | ('tv_nsec', ctypes.c_long) |
| 20 | ] |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 21 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 22 | librt = ctypes.CDLL('librt.so.1', use_errno=True) |
| 23 | clock_gettime = librt.clock_gettime |
| 24 | clock_gettime.argtypes = [ctypes.c_int, ctypes.POINTER(timespec)] |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 25 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 26 | @staticmethod |
| 27 | def monotonic_time(): |
| 28 | t = Time.timespec() |
| 29 | if Time.clock_gettime( |
| 30 | 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 |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 34 | |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 35 | class StackDecoder(object): |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 36 | def __init__(self, pid, bpf): |
| 37 | self.pid = pid |
| 38 | self.bpf = bpf |
| 39 | self.ranges_cache = {} |
| 40 | self.refresh_code_ranges() |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 41 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 42 | def refresh_code_ranges(self): |
| 43 | if self.pid == -1: |
| 44 | return |
| 45 | self.code_ranges = self._get_code_ranges() |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 46 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 47 | @staticmethod |
| 48 | def _is_binary_segment(parts): |
| 49 | return len(parts) == 6 and \ |
Sasha Goldshtein | 521ab4f | 2016-02-08 05:48:31 -0800 | [diff] [blame] | 50 | parts[5][0] != '[' and 'x' in parts[1] |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 51 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 52 | def _get_code_ranges(self): |
| 53 | ranges = {} |
| 54 | raw_ranges = open("/proc/%d/maps" % self.pid).readlines() |
| 55 | # A typical line from /proc/PID/maps looks like this: |
| 56 | # 7f21b6635000-7f21b67eb000 r-xp ... /usr/lib64/libc-2.21.so |
| 57 | # We are looking for executable segments that have a .so file |
| 58 | # or the main executable. The first two lines are the range of |
| 59 | # that memory segment, which we index by binary name. |
| 60 | for raw_range in raw_ranges: |
| 61 | parts = raw_range.split() |
| 62 | if not StackDecoder._is_binary_segment(parts): |
| 63 | continue |
| 64 | binary = parts[5] |
| 65 | range_parts = parts[0].split('-') |
| 66 | addr_range = (int(range_parts[0], 16), |
| 67 | int(range_parts[1], 16)) |
| 68 | ranges[binary] = addr_range |
| 69 | return ranges |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 70 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 71 | @staticmethod |
| 72 | def _is_function_symbol(parts): |
| 73 | return len(parts) == 6 and parts[3] == ".text" \ |
| 74 | and parts[2] == "F" |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 75 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 76 | def _get_sym_ranges(self, binary): |
| 77 | if binary in self.ranges_cache: |
| 78 | return self.ranges_cache[binary] |
| 79 | sym_ranges = {} |
| 80 | raw_symbols = run_command_get_output("objdump -t %s" % binary) |
| 81 | for raw_symbol in raw_symbols: |
| 82 | # A typical line from objdump -t looks like this: |
| 83 | # 00000000004007f5 g F .text 000000000000010e main |
| 84 | # We only care about functions in the .text segment. |
| 85 | # The first number is the start address, and the second |
| 86 | # number is the length. |
| 87 | parts = raw_symbol.split() |
| 88 | if not StackDecoder._is_function_symbol(parts): |
| 89 | continue |
| 90 | sym_start = int(parts[0], 16) |
| 91 | sym_len = int(parts[4], 16) |
| 92 | sym_name = parts[5] |
| 93 | sym_ranges[sym_name] = (sym_start, sym_len) |
| 94 | self.ranges_cache[binary] = sym_ranges |
| 95 | return sym_ranges |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 96 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 97 | def _decode_sym(self, binary, offset): |
| 98 | sym_ranges = self._get_sym_ranges(binary) |
| 99 | # Find the symbol that contains the specified offset. |
| 100 | # There might not be one. |
| 101 | for name, (start, length) in sym_ranges.items(): |
| 102 | if offset >= start and offset <= (start + length): |
| 103 | return "%s+0x%x" % (name, offset - start) |
| 104 | return "%x" % offset |
| 105 | |
| 106 | def _decode_addr(self, addr): |
| 107 | code_ranges = self._get_code_ranges() |
| 108 | # Find the binary that contains the specified address. |
| 109 | # For .so files, look at the relative address; for the main |
| 110 | # executable, look at the absolute address. |
| 111 | for binary, (start, end) in code_ranges.items(): |
| 112 | if addr >= start and addr <= end: |
| 113 | offset = addr - start \ |
| 114 | if binary.endswith(".so") else addr |
| 115 | return "%s [%s]" % (self._decode_sym(binary, |
| 116 | offset), binary) |
| 117 | return "%x" % addr |
| 118 | |
| 119 | def decode_stack(self, info, is_kernel_trace): |
| 120 | stack = "" |
| 121 | if info.num_frames <= 0: |
| 122 | return "???" |
| 123 | for i in range(0, info.num_frames): |
| 124 | addr = info.callstack[i] |
| 125 | if is_kernel_trace: |
| 126 | stack += " %s [kernel] (%x) ;" % \ |
| 127 | (self.bpf.ksym(addr), addr) |
| 128 | else: |
| 129 | # At some point, we hope to have native BPF |
| 130 | # user-mode symbol decoding, but for now we |
| 131 | # have to use our own. |
| 132 | stack += " %s (%x) ;" % \ |
| 133 | (self._decode_addr(addr), addr) |
| 134 | return stack |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 135 | |
Sasha Goldshtein | 751fce5 | 2016-02-08 02:57:02 -0800 | [diff] [blame] | 136 | def run_command_get_output(command): |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 137 | p = subprocess.Popen(command.split(), |
| 138 | stdout=subprocess.PIPE, stderr=subprocess.STDOUT) |
| 139 | return iter(p.stdout.readline, b'') |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 140 | |
Sasha Goldshtein | 751fce5 | 2016-02-08 02:57:02 -0800 | [diff] [blame] | 141 | def run_command_get_pid(command): |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 142 | p = subprocess.Popen(command.split()) |
| 143 | return p.pid |
Sasha Goldshtein | 751fce5 | 2016-02-08 02:57:02 -0800 | [diff] [blame] | 144 | |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 145 | examples = """ |
| 146 | EXAMPLES: |
| 147 | |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 148 | ./memleak.py -p $(pidof allocs) |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 149 | Trace allocations and display a summary of "leaked" (outstanding) |
| 150 | allocations every 5 seconds |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 151 | ./memleak.py -p $(pidof allocs) -t |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 152 | Trace allocations and display each individual call to malloc/free |
Sasha Goldshtein | 75ba13f | 2016-02-09 06:03:46 -0800 | [diff] [blame^] | 153 | ./memleak.py -ap $(pidof allocs) 10 |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 154 | Trace allocations and display allocated addresses, sizes, and stacks |
| 155 | every 10 seconds for outstanding allocations |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 156 | ./memleak.py -c "./allocs" |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 157 | Run the specified command and trace its allocations |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 158 | ./memleak.py |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 159 | Trace allocations in kernel mode and display a summary of outstanding |
| 160 | allocations every 5 seconds |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 161 | ./memleak.py -o 60000 |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 162 | Trace allocations in kernel mode and display a summary of outstanding |
| 163 | allocations that are at least one minute (60 seconds) old |
Sasha Goldshtein | 521ab4f | 2016-02-08 05:48:31 -0800 | [diff] [blame] | 164 | ./memleak.py -s 5 |
| 165 | Trace roughly every 5th allocation, to reduce overhead |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 166 | """ |
| 167 | |
| 168 | description = """ |
| 169 | Trace outstanding memory allocations that weren't freed. |
| 170 | Supports both user-mode allocations made with malloc/free and kernel-mode |
| 171 | allocations made with kmalloc/kfree. |
| 172 | """ |
| 173 | |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 174 | parser = argparse.ArgumentParser(description=description, |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 175 | formatter_class=argparse.RawDescriptionHelpFormatter, |
| 176 | epilog=examples) |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 177 | parser.add_argument("-p", "--pid", type=int, |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 178 | help="the PID to trace; if not specified, trace kernel allocs") |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 179 | parser.add_argument("-t", "--trace", action="store_true", |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 180 | help="print trace messages for each alloc/free call") |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 181 | parser.add_argument("interval", nargs="?", default=5, type=int, |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 182 | help="interval in seconds to print outstanding allocations") |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 183 | parser.add_argument("count", nargs="?", type=int, |
| 184 | help="number of times to print the report before exiting") |
Sasha Goldshtein | a7cc6c2 | 2016-02-07 12:03:54 -0800 | [diff] [blame] | 185 | parser.add_argument("-a", "--show-allocs", default=False, action="store_true", |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 186 | help="show allocation addresses and sizes as well as call stacks") |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 187 | parser.add_argument("-o", "--older", default=500, type=int, |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 188 | help="prune allocations younger than this age in milliseconds") |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 189 | parser.add_argument("-c", "--command", |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 190 | help="execute and trace the specified command") |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 191 | parser.add_argument("-s", "--sample-rate", default=1, type=int, |
Sasha Goldshtein | 521ab4f | 2016-02-08 05:48:31 -0800 | [diff] [blame] | 192 | help="sample every N-th allocation to decrease the overhead") |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 193 | |
| 194 | args = parser.parse_args() |
| 195 | |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 196 | pid = -1 if args.pid is None else args.pid |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 197 | command = args.command |
| 198 | kernel_trace = (pid == -1 and command is None) |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 199 | trace_all = args.trace |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 200 | interval = args.interval |
| 201 | min_age_ns = 1e6 * args.older |
Sasha Goldshtein | 521ab4f | 2016-02-08 05:48:31 -0800 | [diff] [blame] | 202 | sample_every_n = args.sample_rate |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 203 | num_prints = args.count |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 204 | |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 205 | if command is not None: |
| 206 | print("Executing '%s' and tracing the resulting process." % command) |
| 207 | pid = run_command_get_pid(command) |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 208 | |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 209 | bpf_source = open("memleak.c").read() |
| 210 | bpf_source = bpf_source.replace("SHOULD_PRINT", "1" if trace_all else "0") |
Sasha Goldshtein | 521ab4f | 2016-02-08 05:48:31 -0800 | [diff] [blame] | 211 | bpf_source = bpf_source.replace("SAMPLE_EVERY_N", str(sample_every_n)) |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 212 | |
| 213 | bpf_program = BPF(text=bpf_source) |
| 214 | |
| 215 | if not kernel_trace: |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 216 | print("Attaching to malloc and free in pid %d, Ctrl+C to quit." % pid) |
| 217 | bpf_program.attach_uprobe(name="c", sym="malloc", |
| 218 | fn_name="alloc_enter", pid=pid) |
| 219 | bpf_program.attach_uretprobe(name="c", sym="malloc", |
| 220 | fn_name="alloc_exit", pid=pid) |
| 221 | bpf_program.attach_uprobe(name="c", sym="free", |
| 222 | fn_name="free_enter", pid=pid) |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 223 | else: |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 224 | print("Attaching to kmalloc and kfree, Ctrl+C to quit.") |
| 225 | bpf_program.attach_kprobe(event="__kmalloc", fn_name="alloc_enter") |
| 226 | bpf_program.attach_kretprobe(event="__kmalloc", fn_name="alloc_exit") |
| 227 | bpf_program.attach_kprobe(event="kfree", fn_name="free_enter") |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 228 | |
Sasha Goldshtein | 2922861 | 2016-02-07 12:20:19 -0800 | [diff] [blame] | 229 | decoder = StackDecoder(pid, bpf_program) |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 230 | |
| 231 | def print_outstanding(): |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 232 | stacks = {} |
| 233 | print("*** Outstanding allocations:") |
| 234 | allocs = bpf_program.get_table("allocs") |
| 235 | for address, info in sorted(allocs.items(), key=lambda a: a[1].size): |
| 236 | if Time.monotonic_time() - min_age_ns < info.timestamp_ns: |
| 237 | continue |
| 238 | stack = decoder.decode_stack(info, kernel_trace) |
| 239 | if stack in stacks: |
| 240 | stacks[stack] = (stacks[stack][0] + 1, |
| 241 | stacks[stack][1] + info.size) |
| 242 | else: |
| 243 | stacks[stack] = (1, info.size) |
| 244 | if args.show_allocs: |
| 245 | print("\taddr = %x size = %s" % |
| 246 | (address.value, info.size)) |
| 247 | for stack, (count, size) in sorted(stacks.items(), |
| 248 | key=lambda s: s[1][1]): |
| 249 | print("\t%d bytes in %d allocations from stack\n\t\t%s" % |
| 250 | (size, count, stack.replace(";", "\n\t\t"))) |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 251 | |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 252 | count_so_far = 0 |
Sasha Goldshtein | 4f1ea67 | 2016-02-07 01:57:42 -0800 | [diff] [blame] | 253 | while True: |
Sasha Goldshtein | 33522d7 | 2016-02-08 03:39:44 -0800 | [diff] [blame] | 254 | if trace_all: |
| 255 | print bpf_program.trace_fields() |
| 256 | else: |
| 257 | try: |
| 258 | sleep(interval) |
| 259 | except KeyboardInterrupt: |
| 260 | exit() |
| 261 | decoder.refresh_code_ranges() |
| 262 | print_outstanding() |
Sasha Goldshtein | 40e55ba | 2016-02-09 05:53:48 -0800 | [diff] [blame] | 263 | count_so_far += 1 |
| 264 | if num_prints is not None and count_so_far >= num_prints: |
| 265 | exit() |