• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2#
3# urandomread-explicit  Example of instrumenting a kernel tracepoint.
4#                       For Linux, uses BCC, BPF. Embedded C.
5#
6# This is an older example of instrumenting a tracepoint, which defines
7# the argument struct and makes an explicit call to attach_tracepoint().
8# See urandomread for a newer version that uses TRACEPOINT_PROBE().
9#
10# REQUIRES: Linux 4.7+ (BPF_PROG_TYPE_TRACEPOINT support).
11#
12# Test by running this, then in another shell, run:
13#     dd if=/dev/urandom of=/dev/null bs=1k count=5
14#
15# Copyright 2016 Netflix, Inc.
16# Licensed under the Apache License, Version 2.0 (the "License")
17
18from __future__ import print_function
19from bcc import BPF
20
21# define BPF program
22bpf_text = """
23#include <uapi/linux/ptrace.h>
24
25struct urandom_read_args {
26    // from /sys/kernel/debug/tracing/events/random/urandom_read/format
27    u64 __unused__;
28    u32 got_bits;
29    u32 pool_left;
30    u32 input_left;
31};
32
33int printarg(struct urandom_read_args *args) {
34    bpf_trace_printk("%d\\n", args->got_bits);
35    return 0;
36}
37"""
38
39# load BPF program
40b = BPF(text=bpf_text)
41b.attach_tracepoint(tp="random:urandom_read", fn_name="printarg")
42
43# header
44print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "GOTBITS"))
45
46# format output
47while 1:
48    try:
49        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
50    except ValueError:
51        continue
52    print("%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))
53