xref: /aosp_15_r20/external/bcc/examples/tracing/urandomread-explicit.py (revision 387f9dfdfa2baef462e92476d413c7bc2470293e)
1#!/usr/bin/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
20from bcc.utils import printb
21
22# define BPF program
23bpf_text = """
24#include <uapi/linux/ptrace.h>
25
26struct urandom_read_args {
27    // from /sys/kernel/debug/tracing/events/random/urandom_read/format
28    u64 __unused__;
29    u32 got_bits;
30    u32 pool_left;
31    u32 input_left;
32};
33
34int printarg(struct urandom_read_args *args) {
35    bpf_trace_printk("%d\\n", args->got_bits);
36    return 0;
37}
38"""
39
40# load BPF program
41b = BPF(text=bpf_text)
42b.attach_tracepoint(tp="random:urandom_read", fn_name="printarg")
43
44# header
45print("%-18s %-16s %-6s %s" % ("TIME(s)", "COMM", "PID", "GOTBITS"))
46
47# format output
48while 1:
49    try:
50        (task, pid, cpu, flags, ts, msg) = b.trace_fields()
51    except ValueError:
52        continue
53    except KeyboardInterrupt:
54        exit()
55    printb(b"%-18.9f %-16s %-6d %s" % (ts, task, pid, msg))
56