Brendan Gregg | 239e863 | 2016-07-25 15:02:32 -0700 | [diff] [blame] | 1 | #!/usr/bin/env python |
| 2 | # |
| 3 | # This is a Hello World example that uses BPF_PERF_OUTPUT. |
| 4 | |
| 5 | from bcc import BPF |
| 6 | import ctypes as ct |
| 7 | |
| 8 | # define BPF program |
| 9 | prog = """ |
| 10 | #include <linux/sched.h> |
| 11 | |
| 12 | // define output data structure in C |
Brendan Gregg | 239e863 | 2016-07-25 15:02:32 -0700 | [diff] [blame] | 13 | struct data_t { |
| 14 | u32 pid; |
| 15 | u64 ts; |
| 16 | char comm[TASK_COMM_LEN]; |
| 17 | }; |
| 18 | BPF_PERF_OUTPUT(events); |
| 19 | |
| 20 | int hello(struct pt_regs *ctx) { |
| 21 | struct data_t data = {}; |
| 22 | |
| 23 | data.pid = bpf_get_current_pid_tgid(); |
| 24 | data.ts = bpf_ktime_get_ns(); |
| 25 | bpf_get_current_comm(&data.comm, sizeof(data.comm)); |
| 26 | |
| 27 | events.perf_submit(ctx, &data, sizeof(data)); |
| 28 | |
| 29 | return 0; |
| 30 | } |
| 31 | """ |
| 32 | |
| 33 | # load BPF program |
| 34 | b = BPF(text=prog) |
| 35 | b.attach_kprobe(event="sys_clone", fn_name="hello") |
| 36 | |
| 37 | # define output data structure in Python |
| 38 | TASK_COMM_LEN = 16 # linux/sched.h |
Brendan Gregg | 239e863 | 2016-07-25 15:02:32 -0700 | [diff] [blame] | 39 | class Data(ct.Structure): |
Gary Lin | 759c76a | 2016-11-30 17:13:37 +0800 | [diff] [blame] | 40 | _fields_ = [("pid", ct.c_uint), |
Brendan Gregg | 239e863 | 2016-07-25 15:02:32 -0700 | [diff] [blame] | 41 | ("ts", ct.c_ulonglong), |
| 42 | ("comm", ct.c_char * TASK_COMM_LEN)] |
| 43 | |
| 44 | # header |
| 45 | print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "MESSAGE")) |
| 46 | |
| 47 | # process event |
| 48 | start = 0 |
| 49 | def print_event(cpu, data, size): |
| 50 | global start |
| 51 | event = ct.cast(data, ct.POINTER(Data)).contents |
| 52 | if start == 0: |
| 53 | start = event.ts |
| 54 | time_s = (float(event.ts - start)) / 1000000000 |
| 55 | print("%-18.9f %-16s %-6d %s" % (time_s, event.comm, event.pid, |
| 56 | "Hello, perf_output!")) |
| 57 | |
| 58 | # loop with callback to print_event |
| 59 | b["events"].open_perf_buffer(print_event) |
| 60 | while 1: |
| 61 | b.kprobe_poll() |