Brendan Gregg | 0030d34 | 2016-01-28 22:39:23 -0800 | [diff] [blame] | 1 | #!/usr/bin/python |
| 2 | # |
| 3 | # strlen_count Trace strlen() and print a frequency count of strings. |
| 4 | # For Linux, uses BCC, eBPF. Embedded C. |
| 5 | # |
| 6 | # Written as a basic example of BCC and uprobes. |
| 7 | # |
| 8 | # Also see strlensnoop. |
| 9 | # |
| 10 | # Copyright 2016 Netflix, Inc. |
| 11 | # Licensed under the Apache License, Version 2.0 (the "License") |
| 12 | |
| 13 | from __future__ import print_function |
| 14 | from bcc import BPF |
| 15 | from time import sleep |
| 16 | |
| 17 | # load BPF program |
| 18 | b = BPF(text=""" |
| 19 | #include <uapi/linux/ptrace.h> |
| 20 | |
| 21 | struct key_t { |
| 22 | char c[80]; |
| 23 | }; |
| 24 | BPF_HASH(counts, struct key_t); |
| 25 | |
| 26 | int count(struct pt_regs *ctx) { |
Brendan Gregg | eb1b70d | 2016-07-25 16:13:35 -0700 | [diff] [blame] | 27 | if (!PT_REGS_PARM1(ctx)) |
Brendan Gregg | 0030d34 | 2016-01-28 22:39:23 -0800 | [diff] [blame] | 28 | return 0; |
| 29 | |
| 30 | struct key_t key = {}; |
| 31 | u64 zero = 0, *val; |
| 32 | |
Brendan Gregg | eb1b70d | 2016-07-25 16:13:35 -0700 | [diff] [blame] | 33 | bpf_probe_read(&key.c, sizeof(key.c), (void *)PT_REGS_PARM1(ctx)); |
Brendan Gregg | 0030d34 | 2016-01-28 22:39:23 -0800 | [diff] [blame] | 34 | val = counts.lookup_or_init(&key, &zero); |
| 35 | (*val)++; |
| 36 | return 0; |
| 37 | }; |
| 38 | """) |
| 39 | b.attach_uprobe(name="c", sym="strlen", fn_name="count") |
| 40 | |
| 41 | # header |
| 42 | print("Tracing strlen()... Hit Ctrl-C to end.") |
| 43 | |
| 44 | # sleep until Ctrl-C |
| 45 | try: |
| 46 | sleep(99999999) |
| 47 | except KeyboardInterrupt: |
| 48 | pass |
| 49 | |
| 50 | # print output |
| 51 | print("%10s %s" % ("COUNT", "STRING")) |
| 52 | counts = b.get_table("counts") |
| 53 | for k, v in sorted(counts.items(), key=lambda counts: counts[1].value): |
| 54 | print("%10d \"%s\"" % (v.value, k.c.encode('string-escape'))) |