1#!/usr/bin/env python 2# Copyright (c) PLUMgrid, Inc. 3# Licensed under the Apache License, Version 2.0 (the "License") 4 5# This is an example of tracing an event and printing custom fields. 6# run in project examples directory with: 7# sudo ./trace_fields.py" 8 9import atexit 10from bcc import BPF 11import ctypes as ct 12 13class Data(ct.Structure): 14 _fields_ = [("ts", ct.c_ulonglong), 15 ("magic", ct.c_ulonglong)] 16 17counter = 0 18def cb(cpu, data, size): 19 assert size >= ct.sizeof(Data) 20 event = ct.cast(data, ct.POINTER(Data)).contents 21 print("[%0d] %f: %x" % (cpu, float(event.ts) / 1000000, event.magic)) 22 global counter 23 counter += 1 24 25prog = """ 26BPF_PERF_OUTPUT(events); 27BPF_ARRAY(counters, u64, 10); 28int do_sys_clone(void *ctx) { 29 struct { 30 u64 ts; 31 u64 magic; 32 } data = {bpf_ktime_get_ns(), 0x12345678}; 33 int rc; 34 if ((rc = events.perf_submit(ctx, &data, sizeof(data))) < 0) 35 bpf_trace_printk("perf_output failed: %d\\n", rc); 36 int zero = 0; 37 u64 *val = counters.lookup(&zero); 38 if (val) lock_xadd(val, 1); 39 return 0; 40} 41""" 42b = BPF(text=prog) 43event_name = b.get_syscall_fnname("clone") 44b.attach_kprobe(event=event_name, fn_name="do_sys_clone") 45b["events"].open_perf_buffer(cb) 46 47@atexit.register 48def print_counter(): 49 global counter 50 global b 51 print("counter = %d vs %d" % (counter, b["counters"][ct.c_int(0)].value)) 52 53print("Tracing " + event_name + ", try `dd if=/dev/zero of=/dev/null`") 54print("Tracing... Hit Ctrl-C to end.") 55while 1: 56 b.perf_buffer_poll() 57