blob: eb1e9979be9c2ec63b4e4fd8d49b3b13c6a5f254 [file] [log] [blame]
Brendan Gregg239e8632016-07-25 15:02:32 -07001#!/usr/bin/env python
2#
3# This is a Hello World example that uses BPF_PERF_OUTPUT.
4
5from bcc import BPF
6import ctypes as ct
7
8# define BPF program
9prog = """
10#include <linux/sched.h>
11
12// define output data structure in C
Brendan Gregg239e8632016-07-25 15:02:32 -070013struct data_t {
14 u32 pid;
15 u64 ts;
16 char comm[TASK_COMM_LEN];
17};
18BPF_PERF_OUTPUT(events);
19
20int 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
34b = BPF(text=prog)
Yonghong Song83b49ad2018-04-24 10:15:24 -070035b.attach_kprobe(event=b.get_syscall_fnname("clone"), fn_name="hello")
Brendan Gregg239e8632016-07-25 15:02:32 -070036
37# define output data structure in Python
38TASK_COMM_LEN = 16 # linux/sched.h
Brendan Gregg239e8632016-07-25 15:02:32 -070039class Data(ct.Structure):
Gary Lin759c76a2016-11-30 17:13:37 +080040 _fields_ = [("pid", ct.c_uint),
Brendan Gregg239e8632016-07-25 15:02:32 -070041 ("ts", ct.c_ulonglong),
42 ("comm", ct.c_char * TASK_COMM_LEN)]
43
44# header
45print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "MESSAGE"))
46
47# process event
48start = 0
49def 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
59b["events"].open_perf_buffer(print_event)
60while 1:
Teng Qindbf00292018-02-28 21:47:50 -080061 b.perf_buffer_poll()