• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
13from __future__ import print_function
14from bcc import BPF
15from bcc.utils import printb
16from time import sleep
17
18# load BPF program
19b = BPF(text="""
20#include <uapi/linux/ptrace.h>
21
22struct key_t {
23    char c[80];
24};
25BPF_HASH(counts, struct key_t);
26
27int count(struct pt_regs *ctx) {
28    if (!PT_REGS_PARM1(ctx))
29        return 0;
30
31    struct key_t key = {};
32    u64 zero = 0, *val;
33
34    bpf_probe_read_user(&key.c, sizeof(key.c), (void *)PT_REGS_PARM1(ctx));
35    // could also use `counts.increment(key)`
36    val = counts.lookup_or_try_init(&key, &zero);
37    if (val) {
38      (*val)++;
39    }
40    return 0;
41};
42""")
43b.attach_uprobe(name="c", sym="strlen", fn_name="count")
44
45# header
46print("Tracing strlen()... Hit Ctrl-C to end.")
47
48# sleep until Ctrl-C
49try:
50    sleep(99999999)
51except KeyboardInterrupt:
52    pass
53
54# print output
55print("%10s %s" % ("COUNT", "STRING"))
56counts = b.get_table("counts")
57for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
58    printb(b"%10d \"%s\"" % (v.value, k.c))
59