3 Intended for search (Ctrl-F) and reference. For tutorials, start with [tutorial.md](tutorial.md).
5 This guide is incomplete. If something feels missing, check the bcc and kernel source. And if you confirm we're missing something, please send a pull request to fix it, and help out everyone.
10 - [Events & Arguments](#events--arguments)
11 - [1. kprobes](#1-kprobes)
12 - [2. kretprobes](#2-kretprobes)
13 - [3. Tracepoints](#3-tracepoints)
14 - [4. uprobes](#4-uprobes)
15 - [5. uretprobes](#5-uretprobes)
16 - [6. USDT probes](#6-usdt-probes)
17 - [7. Raw Tracepoints](#7-raw-tracepoints)
18 - [8. system call tracepoints](#8-system-call-tracepoints)
19 - [9. kfuncs](#9-kfuncs)
20 - [10. kretfuncs](#10-kretfuncs)
21 - [11. lsm probes](#11-lsm-probes)
22 - [12. bpf iterators](#12-bpf-iterators)
24 - [1. bpf_probe_read_kernel()](#1-bpf_probe_read_kernel)
25 - [2. bpf_probe_read_kernel_str()](#2-bpf_probe_read_kernel_str)
26 - [3. bpf_ktime_get_ns()](#3-bpf_ktime_get_ns)
27 - [4. bpf_get_current_pid_tgid()](#4-bpf_get_current_pid_tgid)
28 - [5. bpf_get_current_uid_gid()](#5-bpf_get_current_uid_gid)
29 - [6. bpf_get_current_comm()](#6-bpf_get_current_comm)
30 - [7. bpf_get_current_task()](#7-bpf_get_current_task)
31 - [8. bpf_log2l()](#8-bpf_log2l)
32 - [9. bpf_get_prandom_u32()](#9-bpf_get_prandom_u32)
33 - [10. bpf_probe_read_user()](#10-bpf_probe_read_user)
34 - [11. bpf_probe_read_user_str()](#11-bpf_probe_read_user_str)
35 - [12. bpf_get_ns_current_pid_tgid()](#12-bpf_get_ns_current_pid_tgid)
36 - [Debugging](#debugging)
37 - [1. bpf_override_return()](#1-bpf_override_return)
39 - [1. bpf_trace_printk()](#1-bpf_trace_printk)
40 - [2. BPF_PERF_OUTPUT](#2-bpf_perf_output)
41 - [3. perf_submit()](#3-perf_submit)
42 - [4. perf_submit_skb()](#4-perf_submit_skb)
43 - [5. BPF_RINGBUF_OUTPUT](#5-bpf_ringbuf_output)
44 - [6. ringbuf_output()](#6-ringbuf_output)
45 - [7. ringbuf_reserve()](#7-ringbuf_reserve)
46 - [8. ringbuf_submit()](#8-ringbuf_submit)
47 - [9. ringbuf_discard()](#9-ringbuf_submit)
49 - [1. BPF_TABLE](#1-bpf_table)
50 - [2. BPF_HASH](#2-bpf_hash)
51 - [3. BPF_ARRAY](#3-bpf_array)
52 - [4. BPF_HISTOGRAM](#4-bpf_histogram)
53 - [5. BPF_STACK_TRACE](#5-bpf_stack_trace)
54 - [6. BPF_PERF_ARRAY](#6-bpf_perf_array)
55 - [7. BPF_PERCPU_HASH](#7-bpf_percpu_hash)
56 - [8. BPF_PERCPU_ARRAY](#8-bpf_percpu_array)
57 - [9. BPF_LPM_TRIE](#9-bpf_lpm_trie)
58 - [10. BPF_PROG_ARRAY](#10-bpf_prog_array)
59 - [11. BPF_DEVMAP](#11-bpf_devmap)
60 - [12. BPF_CPUMAP](#12-bpf_cpumap)
61 - [13. BPF_XSKMAP](#13-bpf_xskmap)
62 - [14. BPF_ARRAY_OF_MAPS](#14-bpf_array_of_maps)
63 - [15. BPF_HASH_OF_MAPS](#15-bpf_hash_of_maps)
64 - [16. BPF_STACK](#16-bpf_stack)
65 - [17. BPF_QUEUE](#17-bpf_queue)
66 - [18. BPF_SOCKHASH](#18-bpf_sockhash)
67 - [19. map.lookup()](#19-maplookup)
68 - [20. map.lookup_or_try_init()](#20-maplookup_or_try_init)
69 - [21. map.delete()](#21-mapdelete)
70 - [22. map.update()](#22-mapupdate)
71 - [23. map.insert()](#23-mapinsert)
72 - [24. map.increment()](#24-mapincrement)
73 - [25. map.get_stackid()](#25-mapget_stackid)
74 - [26. map.perf_read()](#26-mapperf_read)
75 - [27. map.call()](#27-mapcall)
76 - [28. map.redirect_map()](#28-mapredirect_map)
77 - [29. map.push()](#29-mappush)
78 - [30. map.pop()](#30-mappop)
79 - [31. map.peek()](#31-mappeek)
80 - [32. map.sock_hash_update()](#32-mapsock_hash_update)
81 - [Licensing](#licensing)
82 - [Rewriter](#rewriter)
84 - [bcc Python](#bcc-python)
85 - [Initialization](#initialization)
89 - [1. attach_kprobe()](#1-attach_kprobe)
90 - [2. attach_kretprobe()](#2-attach_kretprobe)
91 - [3. attach_tracepoint()](#3-attach_tracepoint)
92 - [4. attach_uprobe()](#4-attach_uprobe)
93 - [5. attach_uretprobe()](#5-attach_uretprobe)
94 - [6. USDT.enable_probe()](#6-usdtenable_probe)
95 - [7. attach_raw_tracepoint()](#7-attach_raw_tracepoint)
96 - [8. attach_raw_socket()](#8-attach_raw_socket)
97 - [9. attach_xdp()](#9-attach_xdp)
98 - [Debug Output](#debug-output)
99 - [1. trace_print()](#1-trace_print)
100 - [2. trace_fields()](#2-trace_fields)
102 - [1. perf_buffer_poll()](#1-perf_buffer_poll)
103 - [2. ring_buffer_poll()](#2-ring_buffer_poll)
104 - [3. ring_buffer_consume()](#3-ring_buffer_consume)
106 - [1. get_table()](#1-get_table)
107 - [2. open_perf_buffer()](#2-open_perf_buffer)
108 - [3. items()](#3-items)
109 - [4. values()](#4-values)
110 - [5. clear()](#5-clear)
111 - [6. items_lookup_and_delete_batch()](#6-items_lookup_and_delete_batch)
112 - [7. items_lookup_batch()](#7-items_lookup_batch)
113 - [8. items_delete_batch()](#8-items_delete_batch)
114 - [9. items_update_batch()](#9-items_update_batch)
115 - [10. print_log2_hist()](#10-print_log2_hist)
116 - [11. print_linear_hist()](#11-print_linear_hist)
117 - [12. open_ring_buffer()](#12-open_ring_buffer)
118 - [13. push()](#13-push)
119 - [14. pop()](#14-pop)
120 - [15. peek()](#15-peek)
121 - [Helpers](#helpers)
122 - [1. ksym()](#1-ksym)
123 - [2. ksymname()](#2-ksymname)
125 - [4. num_open_kprobes()](#4-num_open_kprobes)
126 - [5. get_syscall_fnname()](#5-get_syscall_fnname)
128 - [BPF Errors](#bpf-errors)
129 - [1. Invalid mem access](#1-invalid-mem-access)
130 - [2. Cannot call GPL only function from proprietary program](#2-cannot-call-gpl-only-function-from-proprietary-program)
132 - [Environment Variables](#envvars)
133 - [1. kernel source directory](#1-kernel-source-directory)
134 - [2. kernel version overriding](#2-kernel-version-overriding)
138 This section describes the C part of a bcc program.
140 ## Events & Arguments
144 Syntax: kprobe__*kernel_function_name*
146 ```kprobe__``` is a special prefix that creates a kprobe (dynamic tracing of a kernel function call) for the kernel function name provided as the remainder. You can also use kprobes by declaring a normal C function, then using the Python ```BPF.attach_kprobe()``` (covered later) to associate it with a kernel function.
148 Arguments are specified on the function declaration: kprobe__*kernel_function_name*(struct pt_regs *ctx [, *argument1* ...])
153 int kprobe__tcp_v4_connect(struct pt_regs *ctx, struct sock *sk)
158 This instruments the tcp_v4_connect() kernel function using a kprobe, with the following arguments:
160 - ```struct pt_regs *ctx```: Registers and BPF context.
161 - ```struct sock *sk```: First argument to tcp_v4_connect().
163 The first argument is always ```struct pt_regs *```, the remainder are the arguments to the function (they don't need to be specified, if you don't intend to use them).
166 [code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/tcpv4connect.py#L28) ([output](https://github.com/iovisor/bcc/blob/5bd0eb21fd148927b078deb8ac29fff2fb044b66/examples/tracing/tcpv4connect_example.txt#L8)),
167 [code](https://github.com/iovisor/bcc/commit/310ab53710cfd46095c1f6b3e44f1dbc8d1a41d8#diff-8cd1822359ffee26e7469f991ce0ef00R26) ([output](https://github.com/iovisor/bcc/blob/3b9679a3bd9b922c736f6061dc65cb56de7e0250/examples/tracing/bitehist_example.txt#L6))
168 <!--- I can't add search links here, since github currently cannot handle partial-word searches needed for "kprobe__" --->
172 Syntax: kretprobe__*kernel_function_name*
174 ```kretprobe__``` is a special prefix that creates a kretprobe (dynamic tracing of a kernel function return) for the kernel function name provided as the remainder. You can also use kretprobes by declaring a normal C function, then using the Python ```BPF.attach_kretprobe()``` (covered later) to associate it with a kernel function.
176 Return value is available as ```PT_REGS_RC(ctx)```, given a function declaration of: kretprobe__*kernel_function_name*(struct pt_regs *ctx)
181 int kretprobe__tcp_v4_connect(struct pt_regs *ctx)
183 int ret = PT_REGS_RC(ctx);
188 This instruments the return of the tcp_v4_connect() kernel function using a kretprobe, and stores the return value in ```ret```.
191 [code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/tcpv4connect.py#L38) ([output](https://github.com/iovisor/bcc/blob/5bd0eb21fd148927b078deb8ac29fff2fb044b66/examples/tracing/tcpv4connect_example.txt#L8))
195 Syntax: TRACEPOINT_PROBE(*category*, *event*)
197 This is a macro that instruments the tracepoint defined by *category*:*event*.
199 Arguments are available in an ```args``` struct, which are the tracepoint arguments. One way to list these is to cat the relevant format file under /sys/kernel/debug/tracing/events/*category*/*event*/format.
201 The ```args``` struct can be used in place of ``ctx`` in each functions requiring a context as an argument. This includes notably [perf_submit()](#3-perf_submit).
206 TRACEPOINT_PROBE(random, urandom_read) {
207 // args is from /sys/kernel/debug/tracing/events/random/urandom_read/format
208 bpf_trace_printk("%d\\n", args->got_bits);
213 This instruments the random:urandom_read tracepoint, and prints the tracepoint argument ```got_bits```.
216 [code](https://github.com/iovisor/bcc/blob/a4159da8c4ea8a05a3c6e402451f530d6e5a8b41/examples/tracing/urandomread.py#L19) ([output](https://github.com/iovisor/bcc/commit/e422f5e50ecefb96579b6391a2ada7f6367b83c4#diff-41e5ecfae4a3b38de5f4e0887ed160e5R10)),
217 [search /examples](https://github.com/iovisor/bcc/search?q=TRACEPOINT_PROBE+path%3Aexamples&type=Code),
218 [search /tools](https://github.com/iovisor/bcc/search?q=TRACEPOINT_PROBE+path%3Atools&type=Code)
222 These are instrumented by declaring a normal function in C, then associating it as a uprobe probe in Python via ```BPF.attach_uprobe()``` (covered later).
224 Arguments can be examined using ```PT_REGS_PARM``` macros.
229 int count(struct pt_regs *ctx) {
231 bpf_probe_read_user(&buf, sizeof(buf), (void *)PT_REGS_PARM1(ctx));
232 bpf_trace_printk("%s %d", buf, PT_REGS_PARM2(ctx));
237 This reads the first argument as a string, and then prints it with the second argument as an integer.
240 [code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/strlen_count.py#L26)
244 These are instrumented by declaring a normal function in C, then associating it as a uretprobe probe in Python via ```BPF.attach_uretprobe()``` (covered later).
246 Return value is available as ```PT_REGS_RC(ctx)```, given a function declaration of: *function_name*(struct pt_regs *ctx)
252 int count(struct pt_regs *ctx) {
253 dist.increment(PT_REGS_RC(ctx));
258 This increments the bucket in the ```dist``` histogram that is indexed by the return value.
261 [code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/strlen_hist.py#L39) ([output](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/examples/tracing/strlen_hist.py#L15)),
262 [code](https://github.com/iovisor/bcc/blob/4afa96a71c5dbfc4c507c3355e20baa6c184a3a8/tools/bashreadline.py) ([output](https://github.com/iovisor/bcc/commit/aa87997d21e5c1a6a20e2c96dd25eb92adc8e85d#diff-2fd162f9e594206f789246ce97d62cf0R7))
266 These are User Statically-Defined Tracing (USDT) probes, which may be placed in some applications or libraries to provide a user-level equivalent of tracepoints. The primary BPF method provided for USDT support method is ```enable_probe()```. USDT probes are instrumented by declaring a normal function in C, then associating it as a USDT probe in Python via ```USDT.enable_probe()```.
268 Arguments can be read via: bpf_usdt_readarg(*index*, ctx, &addr)
273 int do_trace(struct pt_regs *ctx) {
276 bpf_usdt_readarg(6, ctx, &addr);
277 bpf_probe_read_user(&path, sizeof(path), (void *)addr);
278 bpf_trace_printk("path:%s\\n", path);
283 This reads the sixth USDT argument, and then pulls it in as a string to ```path```.
285 When initializing USDTs via the third argument of ```BPF::init``` in the C API, if any USDT fails to ```init```, entire ```BPF::init``` will fail. If you're OK with some USDTs failing to ```init```, use ```BPF::init_usdt``` before calling ```BPF::init```.
288 [code](https://github.com/iovisor/bcc/commit/4f88a9401357d7b75e917abd994aa6ea97dda4d3#diff-04a7cad583be5646080970344c48c1f4R24),
289 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_usdt_readarg+path%3Aexamples&type=Code),
290 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_usdt_readarg+path%3Atools&type=Code)
292 ### 7. Raw Tracepoints
294 Syntax: RAW_TRACEPOINT_PROBE(*event*)
296 This is a macro that instruments the raw tracepoint defined by *event*.
298 The argument is a pointer to struct ```bpf_raw_tracepoint_args```, which is defined in [bpf.h](https://github.com/iovisor/bcc/blob/master/src/cc/compat/linux/virtual_bpf.h). The struct field ```args``` contains all parameters of the raw tracepoint where you can found at linux tree [include/trace/events](https://github.com/torvalds/linux/tree/master/include/trace/events)
303 RAW_TRACEPOINT_PROBE(sched_switch)
305 // TP_PROTO(bool preempt, struct task_struct *prev, struct task_struct *next)
306 struct task_struct *prev = (struct task_struct *)ctx->args[1];
307 struct task_struct *next= (struct task_struct *)ctx->args[2];
308 s32 prev_tgid, next_tgid;
310 bpf_probe_read_kernel(&prev_tgid, sizeof(prev->tgid), &prev->tgid);
311 bpf_probe_read_kernel(&next_tgid, sizeof(next->tgid), &next->tgid);
312 bpf_trace_printk("%d -> %d\\n", prev_tgid, next_tgid);
316 This instruments the sched:sched_switch tracepoint, and prints the prev and next tgid.
319 [search /tools](https://github.com/iovisor/bcc/search?q=RAW_TRACEPOINT_PROBE+path%3Atools&type=Code)
321 ### 8. system call tracepoints
323 Syntax: ```syscall__SYSCALLNAME```
325 ```syscall__``` is a special prefix that creates a kprobe for the system call name provided as the remainder. You can use it by declaring a normal C function, then using the Python ```BPF.get_syscall_fnname(SYSCALLNAME)``` and ```BPF.attach_kprobe()``` to associate it.
327 Arguments are specified on the function declaration: ```syscall__SYSCALLNAME(struct pt_regs *ctx, [, argument1 ...])```.
331 int syscall__execve(struct pt_regs *ctx,
332 const char __user *filename,
333 const char __user *const __user *__argv,
334 const char __user *const __user *__envp)
340 This instruments the execve system call.
342 The first argument is always ```struct pt_regs *```, the remainder are the arguments to the function (they don't need to be specified, if you don't intend to use them).
344 Corresponding Python code:
346 b = BPF(text=bpf_text)
347 execve_fnname = b.get_syscall_fnname("execve")
348 b.attach_kprobe(event=execve_fnname, fn_name="syscall__execve")
352 [code](https://github.com/iovisor/bcc/blob/552658edda09298afdccc8a4b5e17311a2d8a771/tools/execsnoop.py#L101) ([output](https://github.com/iovisor/bcc/blob/552658edda09298afdccc8a4b5e17311a2d8a771/tools/execsnoop_example.txt#L8))
356 Syntax: KFUNC_PROBE(*function*, typeof(arg1) arg1, typeof(arg2) arge ...)
358 This is a macro that instruments the kernel function via trampoline
359 *before* the function is executed. It's defined by *function* name and
360 the function arguments defined as *argX*.
364 KFUNC_PROBE(do_sys_open, int dfd, const char *filename, int flags, int mode)
369 This instruments the do_sys_open kernel function and make its arguments
370 accessible as standard argument values.
373 [search /tools](https://github.com/iovisor/bcc/search?q=KFUNC_PROBE+path%3Atools&type=Code)
377 Syntax: KRETFUNC_PROBE(*event*, typeof(arg1) arg1, typeof(arg2) arge ..., int ret)
379 This is a macro that instruments the kernel function via trampoline
380 *after* the function is executed. It's defined by *function* name and
381 the function arguments defined as *argX*.
383 The last argument of the probe is the return value of the instrumented function.
387 KRETFUNC_PROBE(do_sys_open, int dfd, const char *filename, int flags, int mode, int ret)
392 This instruments the do_sys_open kernel function and make its arguments
393 accessible as standard argument values together with its return value.
396 [search /tools](https://github.com/iovisor/bcc/search?q=KRETFUNC_PROBE+path%3Atools&type=Code)
401 Syntax: LSM_PROBE(*hook*, typeof(arg1) arg1, typeof(arg2) arg2 ...)
403 This is a macro that instruments an LSM hook as a BPF program. It can be
404 used to audit security events and implement MAC security policies in BPF.
405 It is defined by specifying the hook name followed by its arguments.
407 Hook names can be found in
408 [include/linux/security.h](https://github.com/torvalds/linux/tree/master/include/linux/security.h#L254)
409 by taking functions like `security_hookname` and taking just the `hookname` part.
410 For example, `security_bpf` would simply become `bpf`.
412 Unlike other BPF program types, the return value specified in an LSM probe
413 matters. A return value of 0 allows the hook to succeed, whereas
414 any non-zero return value will cause the hook to fail and deny the
417 The following example instruments a hook that denies all future BPF operations:
419 LSM_PROBE(bpf, int cmd, union bpf_attr *attr, unsigned int size)
425 This instruments the `security_bpf` hook and causes it to return `-EPERM`.
426 Changing `return -EPERM` to `return 0` would cause the BPF program
427 to allow the operation instead.
429 LSM probes require at least a 5.7+ kernel with the following configuation options set:
431 - `CONFIG_LSM` comma separated string must contain "bpf" (for example,
432 `CONFIG_LSM="lockdown,yama,bpf"`)
435 [search /tests](https://github.com/iovisor/bcc/search?q=LSM_PROBE+path%3Atests&type=Code)
437 ### 12. BPF ITERATORS
439 Syntax: BPF_ITER(target)
441 This is a macro to define a program signature for a bpf iterator program. The argument *target* specifies what to iterate for the program.
443 Currently, kernel does not have interface to discover what targets are supported. A good place to find what is supported is in [tools/testing/selftests/bpf/prog_test/bpf_iter.c](https://github.com/torvalds/linux/blob/master/tools/testing/selftests/bpf/prog_tests/bpf_iter.c) and some sample bpf iter programs are in [tools/testing/selftests/bpf/progs](https://github.com/torvalds/linux/tree/master/tools/testing/selftests/bpf/progs) with file name prefix *bpf_iter*.
445 The following example defines a program for target *task*, which traverses all tasks in the kernel.
449 struct seq_file *seq = ctx->meta->seq;
450 struct task_struct *task = ctx->task;
452 if (task == (void *)0)
455 ... task->pid, task->tgid, task->comm, ...
460 BPF iterators are introduced in 5.8 kernel for task, task_file, bpf_map, netlink_sock and ipv6_route . In 5.9, support is added to tcp/udp sockets and bpf map element (hashmap, arraymap and sk_local_storage_map) traversal.
464 ### 1. bpf_probe_read_kernel()
466 Syntax: ```int bpf_probe_read_kernel(void *dst, int size, const void *src)```
470 This copies size bytes from kernel address space to the BPF stack, so that BPF can later operate on it. For safety, all kernel memory reads must pass through bpf_probe_read_kernel(). This happens automatically in some cases, such as dereferencing kernel variables, as bcc will rewrite the BPF program to include the necessary bpf_probe_read_kernel().
473 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel+path%3Aexamples&type=Code),
474 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel+path%3Atools&type=Code)
476 ### 2. bpf_probe_read_kernel_str()
478 Syntax: ```int bpf_probe_read_kernel_str(void *dst, int size, const void *src)```
481 - \> 0 length of the string including the trailing NULL on success
484 This copies a `NULL` terminated string from kernel address space to the BPF stack, so that BPF can later operate on it. In case the string length is smaller than size, the target is not padded with further `NULL` bytes. In case the string length is larger than size, just `size - 1` bytes are copied and the last byte is set to `NULL`.
487 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel_str+path%3Aexamples&type=Code),
488 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_kernel_str+path%3Atools&type=Code)
490 ### 3. bpf_ktime_get_ns()
492 Syntax: ```u64 bpf_ktime_get_ns(void)```
494 Return: u64 number of nanoseconds. Starts at system boot time but stops during suspend.
497 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_ktime_get_ns+path%3Aexamples&type=Code),
498 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_ktime_get_ns+path%3Atools&type=Code)
500 ### 4. bpf_get_current_pid_tgid()
502 Syntax: ```u64 bpf_get_current_pid_tgid(void)```
504 Return: ```current->tgid << 32 | current->pid```
506 Returns the process ID in the lower 32 bits (kernel's view of the PID, which in user space is usually presented as the thread ID), and the thread group ID in the upper 32 bits (what user space often thinks of as the PID). By directly setting this to a u32, we discard the upper 32 bits.
509 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_pid_tgid+path%3Aexamples&type=Code),
510 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_pid_tgid+path%3Atools&type=Code)
512 ### 5. bpf_get_current_uid_gid()
514 Syntax: ```u64 bpf_get_current_uid_gid(void)```
516 Return: ```current_gid << 32 | current_uid```
518 Returns the user ID and group IDs.
521 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_uid_gid+path%3Aexamples&type=Code),
522 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_uid_gid+path%3Atools&type=Code)
524 ### 6. bpf_get_current_comm()
526 Syntax: ```bpf_get_current_comm(char *buf, int size_of_buf)```
530 Populates the first argument address with the current process name. It should be a pointer to a char array of at least size TASK_COMM_LEN, which is defined in linux/sched.h. For example:
533 #include <linux/sched.h>
535 int do_trace(struct pt_regs *ctx) {
536 char comm[TASK_COMM_LEN];
537 bpf_get_current_comm(&comm, sizeof(comm));
542 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_comm+path%3Aexamples&type=Code),
543 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_comm+path%3Atools&type=Code)
545 ### 7. bpf_get_current_task()
547 Syntax: ```bpf_get_current_task()```
549 Return: current task as a pointer to struct task_struct.
551 Returns a pointer to the current task's task_struct object. This helper can be used to compute the on-CPU time for a process, identify kernel threads, get the current CPU's run queue, or retrieve many other pieces of information.
553 With Linux 4.13, due to issues with field randomization, you may need two #define directives before the includes:
555 #define randomized_struct_fields_start struct {
556 #define randomized_struct_fields_end };
557 #include <linux/sched.h>
559 int do_trace(void *ctx) {
560 struct task_struct *t = (struct task_struct *)bpf_get_current_task();
565 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_current_task+path%3Aexamples&type=Code),
566 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_current_task+path%3Atools&type=Code)
570 Syntax: ```unsigned int bpf_log2l(unsigned long v)```
572 Returns the log-2 of the provided value. This is often used to create indexes for histograms, to construct power-of-2 histograms.
575 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_log2l+path%3Aexamples&type=Code),
576 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_log2l+path%3Atools&type=Code)
578 ### 9. bpf_get_prandom_u32()
580 Syntax: ```u32 bpf_get_prandom_u32()```
582 Returns a pseudo-random u32.
585 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_prandom_u32+path%3Aexamples&type=Code),
586 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_prandom_u32+path%3Atools&type=Code)
588 ### 10. bpf_probe_read_user()
590 Syntax: ```int bpf_probe_read_user(void *dst, int size, const void *src)```
594 This attempts to safely read size bytes from user address space to the BPF stack, so that BPF can later operate on it. For safety, all user address space memory reads must pass through bpf_probe_read_user().
597 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user+path%3Aexamples&type=Code),
598 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user+path%3Atools&type=Code)
600 ### 11. bpf_probe_read_user_str()
602 Syntax: ```int bpf_probe_read_user_str(void *dst, int size, const void *src)```
605 - \> 0 length of the string including the trailing NULL on success
608 This copies a `NULL` terminated string from user address space to the BPF stack, so that BPF can later operate on it. In case the string length is smaller than size, the target is not padded with further `NULL` bytes. In case the string length is larger than size, just `size - 1` bytes are copied and the last byte is set to `NULL`.
611 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user_str+path%3Aexamples&type=Code),
612 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_probe_read_user_str+path%3Atools&type=Code)
615 ### 12. bpf_get_ns_current_pid_tgid()
617 Syntax: ```u32 bpf_get_ns_current_pid_tgid(u64 dev, u64 ino, struct bpf_pidns_info* nsdata, u32 size)```
619 Values for *pid* and *tgid* as seen from the current *namespace* will be returned in *nsdata*.
621 Return 0 on success, or one of the following in case of failure:
623 - **-EINVAL** if dev and inum supplied don't match dev_t and inode number with nsfs of current task, or if dev conversion to dev_t lost high bits.
625 - **-ENOENT** if pidns does not exists for the current task.
628 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_get_ns_current_pid_tgid+path%3Aexamples&type=Code),
629 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_get_ns_current_pid_tgid+path%3Atools&type=Code)
634 ### 1. bpf_override_return()
636 Syntax: ```int bpf_override_return(struct pt_regs *, unsigned long rc)```
640 When used in a program attached to a function entry kprobe, causes the
641 execution of the function to be skipped, immediately returning `rc` instead.
642 This is used for targeted error injection.
644 bpf_override_return will only work when the kprobed function is whitelisted to
645 allow error injections. Whitelisting entails tagging a function with
646 `ALLOW_ERROR_INJECTION()` in the kernel source tree; see `io_ctl_init` for
647 an example. If the kprobed function is not whitelisted, the bpf program will
648 fail to attach with ` ioctl(PERF_EVENT_IOC_SET_BPF): Invalid argument`
652 int kprobe__io_ctl_init(void *ctx) {
653 bpf_override_return(ctx, -ENOMEM);
660 ### 1. bpf_trace_printk()
662 Syntax: ```int bpf_trace_printk(const char *fmt, ...)```
666 A simple kernel facility for printf() to the common trace_pipe (/sys/kernel/debug/tracing/trace_pipe). This is ok for some quick examples, but has limitations: 3 args max, 1 %s only, and trace_pipe is globally shared, so concurrent programs will have clashing output. A better interface is via BPF_PERF_OUTPUT(). Note that calling this helper is made simpler than the original kernel version, which has ```fmt_size``` as the second parameter.
669 [search /examples](https://github.com/iovisor/bcc/search?q=bpf_trace_printk+path%3Aexamples&type=Code),
670 [search /tools](https://github.com/iovisor/bcc/search?q=bpf_trace_printk+path%3Atools&type=Code)
672 ### 2. BPF_PERF_OUTPUT
674 Syntax: ```BPF_PERF_OUTPUT(name)```
676 Creates a BPF table for pushing out custom event data to user space via a perf ring buffer. This is the preferred method for pushing per-event data to user space.
684 char comm[TASK_COMM_LEN];
686 BPF_PERF_OUTPUT(events);
688 int hello(struct pt_regs *ctx) {
689 struct data_t data = {};
691 data.pid = bpf_get_current_pid_tgid();
692 data.ts = bpf_ktime_get_ns();
693 bpf_get_current_comm(&data.comm, sizeof(data.comm));
695 events.perf_submit(ctx, &data, sizeof(data));
701 The output table is named ```events```, and data is pushed to it via ```events.perf_submit()```.
704 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERF_OUTPUT+path%3Aexamples&type=Code),
705 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERF_OUTPUT+path%3Atools&type=Code)
709 Syntax: ```int perf_submit((void *)ctx, (void *)data, u32 data_size)```
713 A method of a BPF_PERF_OUTPUT table, for submitting custom event data to user space. See the BPF_PERF_OUTPUT entry. (This ultimately calls bpf_perf_event_output().)
715 The ```ctx``` parameter is provided in [kprobes](#1-kprobes) or [kretprobes](#2-kretprobes). For ```SCHED_CLS``` or ```SOCKET_FILTER``` programs, the ```struct __sk_buff *skb``` must be used instead.
718 [search /examples](https://github.com/iovisor/bcc/search?q=perf_submit+path%3Aexamples&type=Code),
719 [search /tools](https://github.com/iovisor/bcc/search?q=perf_submit+path%3Atools&type=Code)
721 ### 4. perf_submit_skb()
723 Syntax: ```int perf_submit_skb((void *)ctx, u32 packet_size, (void *)data, u32 data_size)```
727 A method of a BPF_PERF_OUTPUT table available in networking program types, for submitting custom event data to user space, along with the first ```packet_size``` bytes of the packet buffer. See the BPF_PERF_OUTPUT entry. (This ultimately calls bpf_perf_event_output().)
730 [search /examples](https://github.com/iovisor/bcc/search?q=perf_submit_skb+path%3Aexamples&type=Code),
731 [search /tools](https://github.com/iovisor/bcc/search?q=perf_submit_skb+path%3Atools&type=Code)
733 ### 5. BPF_RINGBUF_OUTPUT
735 Syntax: ```BPF_RINGBUF_OUTPUT(name, page_cnt)```
737 Creates a BPF table for pushing out custom event data to user space via a ringbuf ring buffer.
738 ```BPF_RINGBUF_OUTPUT``` has several advantages over ```BPF_PERF_OUTPUT```, summarized as follows:
740 - Buffer is shared across all CPUs, meaning no per-CPU allocation
741 - Supports two APIs for BPF programs
742 - ```map.ringbuf_output()``` works like ```map.perf_submit()``` (covered in [ringbuf_output](#5-ringbuf_output))
743 - ```map.ringbuf_reserve()```/```map.ringbuf_submit()```/```map.ringbuf_discard()```
744 split the process of reserving buffer space and submitting events into two steps
745 (covered in [ringbuf_reserve](#6-ringbuf_reserve), [ringbuf_submit](#7-ringbuf_submit), [ringbuf_discard](#8-ringbuf_submit))
746 - BPF APIs do not require access to a CPU ctx argument
747 - Superior performance and latency in userspace thanks to a shared ring buffer manager
748 - Supports two ways of consuming data in userspace
750 Starting in Linux 5.8, this should be the preferred method for pushing per-event data to user space.
752 Example of both APIs:
758 char comm[TASK_COMM_LEN];
761 // Creates a ringbuf called events with 8 pages of space, shared across all CPUs
762 BPF_RINGBUF_OUTPUT(events, 8);
764 int first_api_example(struct pt_regs *ctx) {
765 struct data_t data = {};
767 data.pid = bpf_get_current_pid_tgid();
768 data.ts = bpf_ktime_get_ns();
769 bpf_get_current_comm(&data.comm, sizeof(data.comm));
771 events.ringbuf_output(&data, sizeof(data), 0 /* flags */);
776 int second_api_example(struct pt_regs *ctx) {
777 struct data_t *data = events.ringbuf_reserve(sizeof(struct data_t));
778 if (!data) { // Failed to reserve space
782 data->pid = bpf_get_current_pid_tgid();
783 data->ts = bpf_ktime_get_ns();
784 bpf_get_current_comm(&data->comm, sizeof(data->comm));
786 events.ringbuf_submit(data, 0 /* flags */);
792 The output table is named ```events```. Data is allocated via ```events.ringbuf_reserve()``` and pushed to it via ```events.ringbuf_submit()```.
794 Examples in situ: <!-- TODO -->
795 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_RINGBUF_OUTPUT+path%3Aexamples&type=Code),
797 ### 6. ringbuf_output()
799 Syntax: ```int ringbuf_output((void *)data, u64 data_size, u64 flags)```
804 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability
805 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally
807 A method of the BPF_RINGBUF_OUTPUT table, for submitting custom event data to user space. This method works like ```perf_submit()```,
808 although it does not require a ctx argument.
810 Examples in situ: <!-- TODO -->
811 [search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_output+path%3Aexamples&type=Code),
813 ### 7. ringbuf_reserve()
815 Syntax: ```void* ringbuf_reserve(u64 data_size)```
817 Return: Pointer to data struct on success, NULL on failure
819 A method of the BPF_RINGBUF_OUTPUT table, for reserving space in the ring buffer and simultaenously
820 allocating a data struct for output. Must be used with one of ```ringbuf_submit``` or ```ringbuf_discard```.
822 Examples in situ: <!-- TODO -->
823 [search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_reserve+path%3Aexamples&type=Code),
825 ### 8. ringbuf_submit()
827 Syntax: ```void ringbuf_submit((void *)data, u64 flags)```
829 Return: Nothing, always succeeds
832 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability
833 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally
835 A method of the BPF_RINGBUF_OUTPUT table, for submitting custom event data to user space. Must be preceded by a call to
836 ```ringbuf_reserve()``` to reserve space for the data.
838 Examples in situ: <!-- TODO -->
839 [search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_submit+path%3Aexamples&type=Code),
841 ### 9. ringbuf_discard()
843 Syntax: ```void ringbuf_discard((void *)data, u64 flags)```
845 Return: Nothing, always succeeds
848 - ```BPF_RB_NO_WAKEUP```: Do not sent notification of new data availability
849 - ```BPF_RB_FORCE_WAKEUP```: Send notification of new data availability unconditionally
851 A method of the BPF_RINGBUF_OUTPUT table, for discarding custom event data; userspace
852 ignores the data associated with the discarded event. Must be preceded by a call to
853 ```ringbuf_reserve()``` to reserve space for the data.
855 Examples in situ: <!-- TODO -->
856 [search /examples](https://github.com/iovisor/bcc/search?q=ringbuf_submit+path%3Aexamples&type=Code),
860 Maps are BPF data stores, and are the basis for higher level object types including tables, hashes, and histograms.
864 Syntax: ```BPF_TABLE(_table_type, _key_type, _leaf_type, _name, _max_entries)```
866 Creates a map named ```_name```. Most of the time this will be used via higher-level macros, like BPF_HASH, BPF_ARRAY, BPF_HISTGRAM, etc.
868 `BPF_F_TABLE` is a variant that takes a flag in the last parameter. `BPF_TABLE(...)` is actually a wrapper to `BPF_F_TABLE(..., 0 /* flag */)`.
870 Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment().
873 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_TABLE+path%3Aexamples&type=Code),
874 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_TABLE+path%3Atools&type=Code)
878 Syntax: ```BPF_TABLE_PINNED(_table_type, _key_type, _leaf_type, _name, _max_entries, "/sys/fs/bpf/xyz")```
880 Create a new map if it doesn't exist and pin it to the bpffs as a FILE, otherwise use the map that was pinned to the bpffs. The type information is not enforced and the actual map type depends on the map that got pinned to the location.
885 BPF_TABLE_PINNED("hash", u64, u64, ids, 1024, "/sys/fs/bpf/ids");
890 Syntax: ```BPF_HASH(name [, key_type [, leaf_type [, size]]])```
892 Creates a hash map (associative array) named ```name```, with optional parameters.
894 Defaults: ```BPF_HASH(name, key_type=u64, leaf_type=u64, size=10240)```
899 BPF_HASH(start, struct request *);
902 This creates a hash named ```start``` where the key is a ```struct request *```, and the value defaults to u64. This hash is used by the disksnoop.py example for saving timestamps for each I/O request, where the key is the pointer to struct request, and the value is the timestamp.
904 This is a wrapper macro for `BPF_TABLE("hash", ...)`.
906 Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment().
909 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_HASH+path%3Aexamples&type=Code),
910 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_HASH+path%3Atools&type=Code)
914 Syntax: ```BPF_ARRAY(name [, leaf_type [, size]])```
916 Creates an int-indexed array which is optimized for fastest lookup and update, named ```name```, with optional parameters.
918 Defaults: ```BPF_ARRAY(name, leaf_type=u64, size=10240)```
923 BPF_ARRAY(counts, u64, 32);
926 This creates an array named ```counts``` where with 32 buckets and 64-bit integer values. This array is used by the funccount.py example for saving call count of each function.
928 This is a wrapper macro for `BPF_TABLE("array", ...)`.
930 Methods (covered later): map.lookup(), map.update(), map.increment(). Note that all array elements are pre-allocated with zero values and can not be deleted.
933 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_ARRAY+path%3Aexamples&type=Code),
934 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_ARRAY+path%3Atools&type=Code)
938 Syntax: ```BPF_HISTOGRAM(name [, key_type [, size ]])```
940 Creates a histogram map named ```name```, with optional parameters.
942 Defaults: ```BPF_HISTOGRAM(name, key_type=int, size=64)```
950 This creates a histogram named ```dist```, which defaults to 64 buckets indexed by keys of type int.
952 This is a wrapper macro for `BPF_TABLE("histgram", ...)`.
954 Methods (covered later): map.increment().
957 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_HISTOGRAM+path%3Aexamples&type=Code),
958 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_HISTOGRAM+path%3Atools&type=Code)
960 ### 5. BPF_STACK_TRACE
962 Syntax: ```BPF_STACK_TRACE(name, max_entries)```
964 Creates stack trace map named ```name```, with a maximum entry count provided. These maps are used to store stack traces.
969 BPF_STACK_TRACE(stack_traces, 1024);
972 This creates stack trace map named ```stack_traces```, with a maximum number of stack trace entries of 1024.
974 This is a wrapper macro for `BPF_TABLE("stacktrace", ...)`.
976 Methods (covered later): map.get_stackid().
979 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_STACK_TRACE+path%3Aexamples&type=Code),
980 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_STACK_TRACE+path%3Atools&type=Code)
982 ### 6. BPF_PERF_ARRAY
984 Syntax: ```BPF_PERF_ARRAY(name, max_entries)```
986 Creates perf array named ```name```, with a maximum entry count provided, which must be equal to the number of system cpus. These maps are used to fetch hardware performance counters.
992 BPF_PERF_ARRAY(cpu_cycles, NUM_CPUS);
994 b = bcc.BPF(text=text, cflags=["-DNUM_CPUS=%d" % multiprocessing.cpu_count()])
995 b["cpu_cycles"].open_perf_event(b["cpu_cycles"].HW_CPU_CYCLES)
998 This creates a perf array named ```cpu_cycles```, with number of entries equal to the number of cpus/cores. The array is configured so that later calling map.perf_read() will return a hardware-calculated counter of the number of cycles elapsed from some point in the past. Only one type of hardware counter may be configured per table at a time.
1000 Methods (covered later): map.perf_read().
1003 [search /tests](https://github.com/iovisor/bcc/search?q=BPF_PERF_ARRAY+path%3Atests&type=Code)
1005 ### 7. BPF_PERCPU_HASH
1007 Syntax: ```BPF_PERCPU_HASH(name [, key_type [, leaf_type [, size]]])```
1009 Creates NUM_CPU int-indexed hash maps (associative arrays) named ```name```, with optional parameters. Each CPU will have a separate copy of this array. The copies are not kept synchronized in any way.
1011 Note that due to limits defined in the kernel (in linux/mm/percpu.c), the ```leaf_type``` cannot have a size of more than 32KB.
1012 In other words, ```BPF_PERCPU_HASH``` elements cannot be larger than 32KB in size.
1015 Defaults: ```BPF_PERCPU_HASH(name, key_type=u64, leaf_type=u64, size=10240)```
1020 BPF_PERCPU_HASH(start, struct request *);
1023 This creates NUM_CPU hashes named ```start``` where the key is a ```struct request *```, and the value defaults to u64.
1025 This is a wrapper macro for `BPF_TABLE("percpu_hash", ...)`.
1027 Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment().
1030 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_HASH+path%3Aexamples&type=Code),
1031 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_HASH+path%3Atools&type=Code)
1034 ### 8. BPF_PERCPU_ARRAY
1036 Syntax: ```BPF_PERCPU_ARRAY(name [, leaf_type [, size]])```
1038 Creates NUM_CPU int-indexed arrays which are optimized for fastest lookup and update, named ```name```, with optional parameters. Each CPU will have a separate copy of this array. The copies are not kept synchronized in any way.
1040 Note that due to limits defined in the kernel (in linux/mm/percpu.c), the ```leaf_type``` cannot have a size of more than 32KB.
1041 In other words, ```BPF_PERCPU_ARRAY``` elements cannot be larger than 32KB in size.
1044 Defaults: ```BPF_PERCPU_ARRAY(name, leaf_type=u64, size=10240)```
1049 BPF_PERCPU_ARRAY(counts, u64, 32);
1052 This creates NUM_CPU arrays named ```counts``` where with 32 buckets and 64-bit integer values.
1054 This is a wrapper macro for `BPF_TABLE("percpu_array", ...)`.
1056 Methods (covered later): map.lookup(), map.update(), map.increment(). Note that all array elements are pre-allocated with zero values and can not be deleted.
1059 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_ARRAY+path%3Aexamples&type=Code),
1060 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_PERCPU_ARRAY+path%3Atools&type=Code)
1064 Syntax: `BPF_LPM_TRIE(name [, key_type [, leaf_type [, size]]])`
1066 Creates a longest prefix match trie map named `name`, with optional parameters.
1068 Defaults: `BPF_LPM_TRIE(name, key_type=u64, leaf_type=u64, size=10240)`
1073 BPF_LPM_TRIE(trie, struct key_v6);
1076 This creates an LPM trie map named `trie` where the key is a `struct key_v6`, and the value defaults to u64.
1078 This is a wrapper macro to `BPF_F_TABLE("lpm_trie", ..., BPF_F_NO_PREALLOC)`.
1080 Methods (covered later): map.lookup(), map.lookup_or_try_init(), map.delete(), map.update(), map.insert(), map.increment().
1083 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_LPM_TRIE+path%3Aexamples&type=Code),
1084 [search /tools](https://github.com/iovisor/bcc/search?q=BPF_LPM_TRIE+path%3Atools&type=Code)
1086 ### 10. BPF_PROG_ARRAY
1088 Syntax: ```BPF_PROG_ARRAY(name, size)```
1090 This creates a program array named ```name``` with ```size``` entries. Each entry of the array is either a file descriptor to a bpf program or ```NULL```. The array acts as a jump table so that bpf programs can "tail-call" other bpf programs.
1092 This is a wrapper macro for `BPF_TABLE("prog", ...)`.
1094 Methods (covered later): map.call().
1097 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_PROG_ARRAY+path%3Aexamples&type=Code),
1098 [search /tests](https://github.com/iovisor/bcc/search?q=BPF_PROG_ARRAY+path%3Atests&type=Code),
1099 [assign fd](https://github.com/iovisor/bcc/blob/master/examples/networking/tunnel_monitor/monitor.py#L24-L26)
1103 Syntax: ```BPF_DEVMAP(name, size)```
1105 This creates a device map named ```name``` with ```size``` entries. Each entry of the map is an `ifindex` to a network interface. This map is only used in XDP.
1109 BPF_DEVMAP(devmap, 10);
1112 Methods (covered later): map.redirect_map().
1115 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_DEVMAP+path%3Aexamples&type=Code),
1119 Syntax: ```BPF_CPUMAP(name, size)```
1121 This creates a cpu map named ```name``` with ```size``` entries. The index of the map represents the CPU id and each entry is the size of the ring buffer allocated for the CPU. This map is only used in XDP.
1125 BPF_CPUMAP(cpumap, 16);
1128 Methods (covered later): map.redirect_map().
1131 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_CPUMAP+path%3Aexamples&type=Code),
1135 Syntax: ```BPF_XSKMAP(name, size)```
1137 This creates a xsk map named ```name``` with ```size``` entries. Each entry represents one NIC's queue id. This map is only used in XDP to redirect packet to an AF_XDP socket. If the AF_XDP socket is binded to a queue which is different than the current packet's queue id, the packet will be dropped. For kernel v5.3 and latter, `lookup` method is available and can be used to check whether and AF_XDP socket is available for the current packet's queue id. More details at [AF_XDP](https://www.kernel.org/doc/html/latest/networking/af_xdp.html).
1141 BPF_XSKMAP(xsks_map, 8);
1144 Methods (covered later): map.redirect_map(). map.lookup()
1147 [search /examples](https://github.com/iovisor/bcc/search?q=BPF_XSKMAP+path%3Aexamples&type=Code),
1149 ### 14. BPF_ARRAY_OF_MAPS
1151 Syntax: ```BPF_ARRAY_OF_MAPS(name, inner_map_name, size)```
1153 This creates an array map with a map-in-map type (BPF_MAP_TYPE_HASH_OF_MAPS) map named ```name``` with ```size``` entries. The inner map meta data is provided by map ```inner_map_name``` and can be most of array or hash maps except ```BPF_MAP_TYPE_PROG_ARRAY```, ```BPF_MAP_TYPE_CGROUP_STORAGE``` and ```BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE```.
1157 BPF_TABLE("hash", int, int, ex1, 1024);
1158 BPF_TABLE("hash", int, int, ex2, 1024);
1159 BPF_ARRAY_OF_MAPS(maps_array, "ex1", 10);
1162 ### 15. BPF_HASH_OF_MAPS
1164 Syntax: ```BPF_HASH_OF_MAPS(name, inner_map_name, size)```
1166 This creates a hash map with a map-in-map type (BPF_MAP_TYPE_HASH_OF_MAPS) map named ```name``` with ```size``` entries. The inner map meta data is provided by map ```inner_map_name``` and can be most of array or hash maps except ```BPF_MAP_TYPE_PROG_ARRAY```, ```BPF_MAP_TYPE_CGROUP_STORAGE``` and ```BPF_MAP_TYPE_PERCPU_CGROUP_STORAGE```.
1170 BPF_ARRAY(ex1, int, 1024);
1171 BPF_ARRAY(ex2, int, 1024);
1172 BPF_HASH_OF_MAPS(maps_hash, "ex1", 10);
1177 Syntax: ```BPF_STACK(name, leaf_type, max_entries[, flags])```
1179 Creates a stack named ```name``` with value type ```leaf_type``` and max entries ```max_entries```.
1180 Stack and Queue maps are only available from Linux 4.20+.
1185 BPF_STACK(stack, struct event, 10240);
1188 This creates a stack named ```stack``` where the value type is ```struct event```, that holds up to 10240 entries.
1190 Methods (covered later): map.push(), map.pop(), map.peek().
1193 [search /tests](https://github.com/iovisor/bcc/search?q=BPF_STACK+path%3Atests&type=Code),
1197 Syntax: ```BPF_QUEUE(name, leaf_type, max_entries[, flags])```
1199 Creates a queue named ```name``` with value type ```leaf_type``` and max entries ```max_entries```.
1200 Stack and Queue maps are only available from Linux 4.20+.
1205 BPF_QUEUE(queue, struct event, 10240);
1208 This creates a queue named ```queue``` where the value type is ```struct event```, that holds up to 10240 entries.
1210 Methods (covered later): map.push(), map.pop(), map.peek().
1213 [search /tests](https://github.com/iovisor/bcc/search?q=BPF_QUEUE+path%3Atests&type=Code),
1215 ### 18. BPF_SOCKHASH
1217 Syntax: ```BPF_SOCKHASH(name[, key_type [, max_entries)```
1219 Creates a hash named ```name```, with optional parameters. sockhash is only available from Linux 4.18+.
1221 Default: ```BPF_SOCKHASH(name, key_type=u32, max_entries=10240)```
1232 BPF_HASH(skh, struct sock_key, 65535);
1235 This creates a hash named ```skh``` where the key is a ```struct sock_key```.
1237 A sockhash is a BPF map type that holds references to sock structs. Then with a new sk/msg redirect bpf helper BPF programs can use the map to redirect skbs/msgs between sockets (```bpf_sk_redirect_hash/bpf_msg_redirect_hash```).
1239 The difference between ```BPF_SOCKHASH``` and ```BPF_SOCKMAP``` is that ```BPF_SOCKMAP``` is implemented based on an array, and enforces keys to be four bytes. While ```BPF_SOCKHASH``` is implemented based on hash table, and the type of key can be specified freely.
1241 Methods (covered later): map.sock_hash_update().
1243 [search /tests](https://github.com/iovisor/bcc/search?q=BPF_SOCKHASH+path%3Atests&type=Code)
1245 ### 19. map.lookup()
1247 Syntax: ```*val map.lookup(&key)```
1249 Lookup the key in the map, and return a pointer to its value if it exists, else NULL. We pass the key in as an address to a pointer.
1252 [search /examples](https://github.com/iovisor/bcc/search?q=lookup+path%3Aexamples&type=Code),
1253 [search /tools](https://github.com/iovisor/bcc/search?q=lookup+path%3Atools&type=Code)
1255 ### 20. map.lookup_or_try_init()
1257 Syntax: ```*val map.lookup_or_try_init(&key, &zero)```
1259 Lookup the key in the map, and return a pointer to its value if it exists, else initialize the key's value to the second argument. This is often used to initialize values to zero. If the key cannot be inserted (e.g. the map is full) then NULL is returned.
1262 [search /examples](https://github.com/iovisor/bcc/search?q=lookup_or_try_init+path%3Aexamples&type=Code),
1263 [search /tools](https://github.com/iovisor/bcc/search?q=lookup_or_try_init+path%3Atools&type=Code)
1265 Note: The old map.lookup_or_init() may cause return from the function, so lookup_or_try_init() is recommended as it
1266 does not have this side effect.
1268 ### 21. map.delete()
1270 Syntax: ```map.delete(&key)```
1272 Delete the key from the hash.
1275 [search /examples](https://github.com/iovisor/bcc/search?q=delete+path%3Aexamples&type=Code),
1276 [search /tools](https://github.com/iovisor/bcc/search?q=delete+path%3Atools&type=Code)
1278 ### 22. map.update()
1280 Syntax: ```map.update(&key, &val)```
1282 Associate the value in the second argument to the key, overwriting any previous value.
1285 [search /examples](https://github.com/iovisor/bcc/search?q=update+path%3Aexamples&type=Code),
1286 [search /tools](https://github.com/iovisor/bcc/search?q=update+path%3Atools&type=Code)
1288 ### 23. map.insert()
1290 Syntax: ```map.insert(&key, &val)```
1292 Associate the value in the second argument to the key, only if there was no previous value.
1295 [search /examples](https://github.com/iovisor/bcc/search?q=insert+path%3Aexamples&type=Code),
1296 [search /tools](https://github.com/iovisor/bcc/search?q=insert+path%3Atools&type=Code)
1298 ### 24. map.increment()
1300 Syntax: ```map.increment(key[, increment_amount])```
1302 Increments the key's value by `increment_amount`, which defaults to 1. Used for histograms.
1305 [search /examples](https://github.com/iovisor/bcc/search?q=increment+path%3Aexamples&type=Code),
1306 [search /tools](https://github.com/iovisor/bcc/search?q=increment+path%3Atools&type=Code)
1308 ### 25. map.get_stackid()
1310 Syntax: ```int map.get_stackid(void *ctx, u64 flags)```
1312 This walks the stack found via the struct pt_regs in ```ctx```, saves it in the stack trace map, and returns a unique ID for the stack trace.
1315 [search /examples](https://github.com/iovisor/bcc/search?q=get_stackid+path%3Aexamples&type=Code),
1316 [search /tools](https://github.com/iovisor/bcc/search?q=get_stackid+path%3Atools&type=Code)
1318 ### 26. map.perf_read()
1320 Syntax: ```u64 map.perf_read(u32 cpu)```
1322 This returns the hardware performance counter as configured in [5. BPF_PERF_ARRAY](#5-bpf_perf_array)
1325 [search /tests](https://github.com/iovisor/bcc/search?q=perf_read+path%3Atests&type=Code)
1329 Syntax: ```void map.call(void *ctx, int index)```
1331 This invokes ```bpf_tail_call()``` to tail-call the bpf program which the ```index``` entry in [9. BPF_PROG_ARRAY](#9-bpf_prog_array) points to. A tail-call is different from the normal call. It reuses the current stack frame after jumping to another bpf program and never goes back. If the ```index``` entry is empty, it won't jump anywhere and the program execution continues as normal.
1336 BPF_PROG_ARRAY(prog_array, 10);
1338 int tail_call(void *ctx) {
1339 bpf_trace_printk("Tail-call\n");
1343 int do_tail_call(void *ctx) {
1344 bpf_trace_printk("Original program\n");
1345 prog_array.call(ctx, 2);
1351 b = BPF(src_file="example.c")
1352 tail_fn = b.load_func("tail_call", BPF.KPROBE)
1353 prog_array = b.get_table("prog_array")
1354 prog_array[c_int(2)] = c_int(tail_fn.fd)
1355 b.attach_kprobe(event="some_kprobe_event", fn_name="do_tail_call")
1358 This assigns ```tail_call()``` to ```prog_array[2]```. In the end of ```do_tail_call()```, ```prog_array.call(ctx, 2)``` tail-calls ```tail_call()``` and executes it.
1360 **NOTE:** To prevent infinite loop, the maximum number of tail-calls is 32 ([```MAX_TAIL_CALL_CNT```](https://github.com/torvalds/linux/search?l=C&q=MAX_TAIL_CALL_CNT+path%3Ainclude%2Flinux&type=Code)).
1363 [search /examples](https://github.com/iovisor/bcc/search?l=C&q=call+path%3Aexamples&type=Code),
1364 [search /tests](https://github.com/iovisor/bcc/search?l=C&q=call+path%3Atests&type=Code)
1366 ### 28. map.redirect_map()
1368 Syntax: ```int map.redirect_map(int index, int flags)```
1370 This redirects the incoming packets based on the ```index``` entry. If the map is [10. BPF_DEVMAP](#10-bpf_devmap), the packet will be sent to the transmit queue of the network interface that the entry points to. If the map is [11. BPF_CPUMAP](#11-bpf_cpumap), the packet will be sent to the ring buffer of the ```index``` CPU and be processed by the CPU later. If the map is [12. BPF_XSKMAP](#12-bpf_xskmap), the packet will be sent to the AF_XDP socket attached to the queue.
1372 If the packet is redirected successfully, the function will return XDP_REDIRECT. Otherwise, it will return XDP_ABORTED to discard the packet.
1376 BPF_DEVMAP(devmap, 1);
1378 int redirect_example(struct xdp_md *ctx) {
1379 return devmap.redirect_map(0, 0);
1381 int xdp_dummy(struct xdp_md *ctx) {
1387 ip = pyroute2.IPRoute()
1388 idx = ip.link_lookup(ifname="eth1")[0]
1390 b = bcc.BPF(src_file="example.c")
1392 devmap = b.get_table("devmap")
1393 devmap[c_uint32(0)] = c_int(idx)
1395 in_fn = b.load_func("redirect_example", BPF.XDP)
1396 out_fn = b.load_func("xdp_dummy", BPF.XDP)
1397 b.attach_xdp("eth0", in_fn, 0)
1398 b.attach_xdp("eth1", out_fn, 0)
1402 [search /examples](https://github.com/iovisor/bcc/search?l=C&q=redirect_map+path%3Aexamples&type=Code),
1406 Syntax: ```int map.push(&val, int flags)```
1408 Push an element onto a Stack or Queue table.
1409 Passing BPF_EXIST as a flag causes the Queue or Stack to discard the oldest element if it is full.
1410 Returns 0 on success, negative error on failure.
1413 [search /tests](https://github.com/iovisor/bcc/search?q=push+path%3Atests&type=Code),
1417 Syntax: ```int map.pop(&val)```
1419 Pop an element from a Stack or Queue table. ```*val``` is populated with the result.
1420 Unlike peeking, popping removes the element.
1421 Returns 0 on success, negative error on failure.
1424 [search /tests](https://github.com/iovisor/bcc/search?q=pop+path%3Atests&type=Code),
1428 Syntax: ```int map.peek(&val)```
1430 Peek an element at the head of a Stack or Queue table. ```*val``` is populated with the result.
1431 Unlike popping, peeking does not remove the element.
1432 Returns 0 on success, negative error on failure.
1435 [search /tests](https://github.com/iovisor/bcc/search?q=peek+path%3Atests&type=Code),
1437 ### 32. map.sock_hash_update()
1439 Syntax: ```int map.sock_hash_update(struct bpf_sock_ops *, &key, int flags)```
1441 Add an entry to, or update a sockhash map referencing sockets. The skops is used as a new value for the entry associated to key. flags is one of:
1444 BPF_NOEXIST: The entry for key must not exist in the map.
1445 BPF_EXIST: The entry for key must already exist in the map.
1446 BPF_ANY: No condition on the existence of the entry for key.
1449 If the map has eBPF programs (parser and verdict), those will be inherited by the socket being added. If the socket is already attached to eBPF programs, this results in an error.
1451 Return 0 on success, or a negative error in case of failure.
1454 [search /tests](https://github.com/iovisor/bcc/search?q=sock_hash_update+path%3Atests&type=Code),
1458 Depending on which [BPF helpers](kernel-versions.md#helpers) are used, a GPL-compatible license is required.
1460 The special BCC macro `BPF_LICENSE` specifies the license of the BPF program. You can set the license as a comment in your source code, but the kernel has a special interface to specify it programmatically. If you need to use GPL-only helpers, it is recommended to specify the macro in your C code so that the kernel can understand it:
1463 // SPDX-License-Identifier: GPL-2.0+
1464 #define BPF_LICENSE GPL
1467 Otherwise, the kernel may reject loading your program (see the [error description](#2-cannot-call-gpl-only-function-from-proprietary-program) below). Note that it supports multiple words and quotes are not necessary:
1470 // SPDX-License-Identifier: GPL-2.0+ OR BSD-2-Clause
1471 #define BPF_LICENSE Dual BSD/GPL
1474 Check the [BPF helpers reference](kernel-versions.md#helpers) to see which helpers are GPL-only and what the kernel understands as GPL-compatible.
1476 **If the macro is not specified, BCC will automatically define the license of the program as GPL.**
1480 One of jobs for rewriter is to turn implicit memory accesses to explicit ones using kernel helpers. Recent kernel introduced a config option ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE which will be set for architectures who user address space and kernel address are disjoint. x86 and arm has this config option set while s390 does not. If ARCH_HAS_NON_OVERLAPPING_ADDRESS_SPACE is not set, the bpf old helper `bpf_probe_read()` will not be available. Some existing users may have implicit memory accesses to access user memory, so using `bpf_probe_read_kernel()` will cause their application to fail. Therefore, for non-s390, the rewriter will use `bpf_probe_read()` for these implicit memory accesses. For s390, `bpf_probe_read_kernel()` is used as default and users should use `bpf_probe_read_user()` explicitly when accessing user memories.
1490 Syntax: ```BPF({text=BPF_program | src_file=filename} [, usdt_contexts=[USDT_object, ...]] [, cflags=[arg1, ...]] [, debug=int])```
1492 Creates a BPF object. This is the main object for defining a BPF program, and interacting with its output.
1494 Exactly one of `text` or `src_file` must be supplied (not both).
1496 The `cflags` specifies additional arguments to be passed to the compiler, for example `-DMACRO_NAME=value` or `-I/include/path`. The arguments are passed as an array, with each element being an additional argument. Note that strings are not split on whitespace, so each argument must be a different element of the array, e.g. `["-include", "header.h"]`.
1498 The `debug` flags control debug output, and can be or'ed together:
1499 - `DEBUG_LLVM_IR = 0x1` compiled LLVM IR
1500 - `DEBUG_BPF = 0x2` loaded BPF bytecode and register state on branches
1501 - `DEBUG_PREPROCESSOR = 0x4` pre-processor result
1502 - `DEBUG_SOURCE = 0x8` ASM instructions embedded with source
1503 - `DEBUG_BPF_REGISTER_STATE = 0x10` register state on all instructions in addition to DEBUG_BPF
1504 - `DEBUG_BTF = 0x20` print the messages from the `libbpf` library.
1509 # define entire BPF program in one line:
1510 BPF(text='int do_trace(void *ctx) { bpf_trace_printk("hit!\\n"); return 0; }');
1512 # define program as a variable:
1514 int hello(void *ctx) {
1515 bpf_trace_printk("Hello, World!\\n");
1522 b = BPF(src_file = "vfsreadlat.c")
1524 # include a USDT object:
1525 u = USDT(pid=int(pid))
1527 b = BPF(text=bpf_text, usdt_contexts=[u])
1529 # add include paths:
1530 u = BPF(text=prog, cflags=["-I/path/to/include"])
1534 [search /examples](https://github.com/iovisor/bcc/search?q=BPF+path%3Aexamples+language%3Apython&type=Code),
1535 [search /tools](https://github.com/iovisor/bcc/search?q=BPF+path%3Atools+language%3Apython&type=Code)
1539 Syntax: ```USDT({pid=pid | path=path})```
1541 Creates an object to instrument User Statically-Defined Tracing (USDT) probes. Its primary method is ```enable_probe()```.
1545 - pid: attach to this process ID.
1546 - path: instrument USDT probes from this binary path.
1551 # include a USDT object:
1552 u = USDT(pid=int(pid))
1554 b = BPF(text=bpf_text, usdt_contexts=[u])
1558 [search /examples](https://github.com/iovisor/bcc/search?q=USDT+path%3Aexamples+language%3Apython&type=Code),
1559 [search /tools](https://github.com/iovisor/bcc/search?q=USDT+path%3Atools+language%3Apython&type=Code)
1563 ### 1. attach_kprobe()
1565 Syntax: ```BPF.attach_kprobe(event="event", fn_name="name")```
1567 Instruments the kernel function ```event()``` using kernel dynamic tracing of the function entry, and attaches our C defined function ```name()``` to be called when the kernel function is called.
1572 b.attach_kprobe(event="sys_clone", fn_name="do_trace")
1575 This will instrument the kernel ```sys_clone()``` function, which will then run our BPF defined ```do_trace()``` function each time it is called.
1577 You can call attach_kprobe() more than once, and attach your BPF function to multiple kernel functions.
1579 See the previous kprobes section for how to instrument arguments from BPF.
1582 [search /examples](https://github.com/iovisor/bcc/search?q=attach_kprobe+path%3Aexamples+language%3Apython&type=Code),
1583 [search /tools](https://github.com/iovisor/bcc/search?q=attach_kprobe+path%3Atools+language%3Apython&type=Code)
1585 ### 2. attach_kretprobe()
1587 Syntax: ```BPF.attach_kretprobe(event="event", fn_name="name" [, maxactive=int])```
1589 Instruments the return of the kernel function ```event()``` using kernel dynamic tracing of the function return, and attaches our C defined function ```name()``` to be called when the kernel function returns.
1594 b.attach_kretprobe(event="vfs_read", fn_name="do_return")
1597 This will instrument the kernel ```vfs_read()``` function, which will then run our BPF defined ```do_return()``` function each time it is called.
1599 You can call attach_kretprobe() more than once, and attach your BPF function to multiple kernel function returns.
1601 When a kretprobe is installed on a kernel function, there is a limit on how many parallel calls it can catch. You can change that limit with ```maxactive```. See the kprobes documentation for its default value.
1603 See the previous kretprobes section for how to instrument the return value from BPF.
1606 [search /examples](https://github.com/iovisor/bcc/search?q=attach_kretprobe+path%3Aexamples+language%3Apython&type=Code),
1607 [search /tools](https://github.com/iovisor/bcc/search?q=attach_kretprobe+path%3Atools+language%3Apython&type=Code)
1609 ### 3. attach_tracepoint()
1611 Syntax: ```BPF.attach_tracepoint(tp="tracepoint", fn_name="name")```
1613 Instruments the kernel tracepoint described by ```tracepoint```, and when hit, runs the BPF function ```name()```.
1615 This is an explicit way to instrument tracepoints. The ```TRACEPOINT_PROBE``` syntax, covered in the earlier tracepoints section, is an alternate method with the advantage of auto-declaring an ```args``` struct containing the tracepoint arguments. With ```attach_tracepoint()```, the tracepoint arguments need to be declared in the BPF program.
1620 # define BPF program
1622 #include <uapi/linux/ptrace.h>
1624 struct urandom_read_args {
1625 // from /sys/kernel/debug/tracing/events/random/urandom_read/format
1632 int printarg(struct urandom_read_args *args) {
1633 bpf_trace_printk("%d\\n", args->got_bits);
1639 b = BPF(text=bpf_text)
1640 b.attach_tracepoint("random:urandom_read", "printarg")
1643 Notice how the first argument to ```printarg()``` is now our defined struct.
1646 [code](https://github.com/iovisor/bcc/blob/a4159da8c4ea8a05a3c6e402451f530d6e5a8b41/examples/tracing/urandomread-explicit.py#L41),
1647 [search /examples](https://github.com/iovisor/bcc/search?q=attach_tracepoint+path%3Aexamples+language%3Apython&type=Code),
1648 [search /tools](https://github.com/iovisor/bcc/search?q=attach_tracepoint+path%3Atools+language%3Apython&type=Code)
1650 ### 4. attach_uprobe()
1652 Syntax: ```BPF.attach_uprobe(name="location", sym="symbol", fn_name="name" [, sym_off=int])```, ```BPF.attach_uprobe(name="location", sym_re="regex", fn_name="name")```, ```BPF.attach_uprobe(name="location", addr=int, fn_name="name")```
1655 Instruments the user-level function ```symbol()``` from either the library or binary named by ```location``` using user-level dynamic tracing of the function entry, and attach our C defined function ```name()``` to be called whenever the user-level function is called. If ```sym_off``` is given, the function is attached to the offset within the symbol.
1657 The real address ```addr``` may be supplied in place of ```sym```, in which case ```sym``` must be set to its default value. If the file is a non-PIE executable, ```addr``` must be a virtual address, otherwise it must be an offset relative to the file load address.
1659 Instead of a symbol name, a regular expression can be provided in ```sym_re```. The uprobe will then attach to symbols that match the provided regular expression.
1661 Libraries can be given in the name argument without the lib prefix, or with the full path (/usr/lib/...). Binaries can be given only with the full path (/bin/sh).
1666 b.attach_uprobe(name="c", sym="strlen", fn_name="count")
1669 This will instrument ```strlen()``` function from libc, and call our BPF function ```count()``` when it is called. Note how the "lib" in "libc" is not necessary to specify.
1674 b.attach_uprobe(name="c", sym="getaddrinfo", fn_name="do_entry")
1675 b.attach_uprobe(name="/usr/bin/python", sym="main", fn_name="do_main")
1678 You can call attach_uprobe() more than once, and attach your BPF function to multiple user-level functions.
1680 See the previous uprobes section for how to instrument arguments from BPF.
1683 [search /examples](https://github.com/iovisor/bcc/search?q=attach_uprobe+path%3Aexamples+language%3Apython&type=Code),
1684 [search /tools](https://github.com/iovisor/bcc/search?q=attach_uprobe+path%3Atools+language%3Apython&type=Code)
1686 ### 5. attach_uretprobe()
1688 Syntax: ```BPF.attach_uretprobe(name="location", sym="symbol", fn_name="name")```
1690 Instruments the return of the user-level function ```symbol()``` from either the library or binary named by ```location``` using user-level dynamic tracing of the function return, and attach our C defined function ```name()``` to be called whenever the user-level function returns.
1695 b.attach_uretprobe(name="c", sym="strlen", fn_name="count")
1698 This will instrument ```strlen()``` function from libc, and call our BPF function ```count()``` when it returns.
1703 b.attach_uretprobe(name="c", sym="getaddrinfo", fn_name="do_return")
1704 b.attach_uretprobe(name="/usr/bin/python", sym="main", fn_name="do_main")
1707 You can call attach_uretprobe() more than once, and attach your BPF function to multiple user-level functions.
1709 See the previous uretprobes section for how to instrument the return value from BPF.
1712 [search /examples](https://github.com/iovisor/bcc/search?q=attach_uretprobe+path%3Aexamples+language%3Apython&type=Code),
1713 [search /tools](https://github.com/iovisor/bcc/search?q=attach_uretprobe+path%3Atools+language%3Apython&type=Code)
1715 ### 6. USDT.enable_probe()
1717 Syntax: ```USDT.enable_probe(probe=probe, fn_name=name)```
1719 Attaches a BPF C function ```name``` to the USDT probe ```probe```.
1724 # enable USDT probe from given PID
1725 u = USDT(pid=int(pid))
1726 u.enable_probe(probe="http__server__request", fn_name="do_trace")
1729 To check if your binary has USDT probes, and what they are, you can run ```readelf -n binary``` and check the stap debug section.
1732 [search /examples](https://github.com/iovisor/bcc/search?q=enable_probe+path%3Aexamples+language%3Apython&type=Code),
1733 [search /tools](https://github.com/iovisor/bcc/search?q=enable_probe+path%3Atools+language%3Apython&type=Code)
1735 ### 7. attach_raw_tracepoint()
1737 Syntax: ```BPF.attach_raw_tracepoint(tp="tracepoint", fn_name="name")```
1739 Instruments the kernel raw tracepoint described by ```tracepoint``` (```event``` only, no ```category```), and when hit, runs the BPF function ```name()```.
1741 This is an explicit way to instrument tracepoints. The ```RAW_TRACEPOINT_PROBE``` syntax, covered in the earlier raw tracepoints section, is an alternate method.
1746 b.attach_raw_tracepoint("sched_switch", "do_trace")
1750 [search /tools](https://github.com/iovisor/bcc/search?q=attach_raw_tracepoint+path%3Atools+language%3Apython&type=Code)
1752 ### 8. attach_raw_socket()
1754 Syntax: ```BPF.attach_raw_socket(fn, dev)```
1756 Attache a BPF function to the specified network interface.
1758 The ```fn``` must be the type of ```BPF.function``` and the bpf_prog type needs to be ```BPF_PROG_TYPE_SOCKET_FILTER``` (```fn=BPF.load_func(func_name, BPF.SOCKET_FILTER)```)
1760 ```fn.sock``` is a non-blocking raw socket that was created and bound to ```dev```.
1762 All network packets processed by ```dev``` are copied to the ```recv-q``` of ```fn.sock``` after being processed by bpf_prog. Try to recv packet form ```fn.sock``` with rev/recvfrom/recvmsg. Note that if the ```recv-q``` is not read in time after the ```recv-q``` is full, the copied packets will be discarded.
1764 We can use this feature to capture network packets just like ```tcpdump```.
1766 We can use ```ss --bpf --packet -p``` to observe ```fn.sock```.
1771 BPF.attach_raw_socket(bpf_func, ifname)
1775 [search /examples](https://github.com/iovisor/bcc/search?q=attach_raw_socket+path%3Aexamples+language%3Apython&type=Code)
1777 Syntax: ```BPF.attach_xdp(dev="device", fn=b.load_func("fn_name",BPF_XDP), flags)```
1779 Instruments the network driver described by ```dev``` , and then receives the packet, run the BPF function ```fn_name()``` with flags.
1781 Here is a list of optional flags.
1784 # from xdp_flags uapi/linux/if_link.h
1785 XDP_FLAGS_UPDATE_IF_NOEXIST = (1 << 0)
1786 XDP_FLAGS_SKB_MODE = (1 << 1)
1787 XDP_FLAGS_DRV_MODE = (1 << 2)
1788 XDP_FLAGS_HW_MODE = (1 << 3)
1789 XDP_FLAGS_REPLACE = (1 << 4)
1792 You can use flags like this ```BPF.attach_xdp(dev="device", fn=b.load_func("fn_name",BPF_XDP), flags=BPF.XDP_FLAGS_UPDATE_IF_NOEXIST)```
1794 The default value of flgas is 0. This means if there is no xdp program with `device`, the fn will run with that device. If there is an xdp program running with device, the old program will be replaced with new fn program.
1796 Currently, bcc does not support XDP_FLAGS_REPLACE flag. The following are the descriptions of other flags.
1798 #### 1. XDP_FLAGS_UPDATE_IF_NOEXIST
1799 If an XDP program is already attached to the specified driver, attaching the XDP program again will fail.
1801 #### 2. XDP_FLAGS_SKB_MODE
1802 Driver doesn’t have support for XDP, but the kernel fakes it.
1803 XDP program works, but there’s no real performance benefit because packets are handed to kernel stack anyways which then emulates XDP – this is usually supported with generic network drivers used in home computers, laptops, and virtualized HW.
1805 #### 3. XDP_FLAGS_DRV_MODE
1806 A driver has XDP support and can hand then to XDP without kernel stack interaction – Few drivers can support it and those are usually for enterprise HW.
1808 #### 4. XDP_FLAGS_HW_MODE
1809 XDP can be loaded and executed directly on the NIC – just a handful of NICs can do that.
1815 b.attach_xdp(dev="ens1", fn=b.load_func("do_xdp", BPF.XDP))
1818 This will instrument the network device ```ens1``` , which will then run our BPF defined ```do_xdp()``` function each time it receives packets.
1820 Don't forget to call ```b.remove_xdp("ens1")``` at the end!
1823 [search /examples](https://github.com/iovisor/bcc/search?q=attach_xdp+path%3Aexamples+language%3Apython&type=Code),
1824 [search /tools](https://github.com/iovisor/bcc/search?q=attach_xdp+path%3Atools+language%3Apython&type=Code)
1828 ### 1. trace_print()
1830 Syntax: ```BPF.trace_print(fmt="fields")```
1832 This method continually reads the globally shared /sys/kernel/debug/tracing/trace_pipe file and prints its contents. This file can be written to via BPF and the bpf_trace_printk() function, however, that method has limitations, including a lack of concurrent tracing support. The BPF_PERF_OUTPUT mechanism, covered earlier, is preferred.
1836 - ```fmt```: optional, and can contain a field formatting string. It defaults to ```None```.
1841 # print trace_pipe output as-is:
1844 # print PID and message:
1845 b.trace_print(fmt="{1} {5}")
1849 [search /examples](https://github.com/iovisor/bcc/search?q=trace_print+path%3Aexamples+language%3Apython&type=Code),
1850 [search /tools](https://github.com/iovisor/bcc/search?q=trace_print+path%3Atools+language%3Apython&type=Code)
1852 ### 2. trace_fields()
1854 Syntax: ```BPF.trace_fields(nonblocking=False)```
1856 This method reads one line from the globally shared /sys/kernel/debug/tracing/trace_pipe file and returns it as fields. This file can be written to via BPF and the bpf_trace_printk() function, however, that method has limitations, including a lack of concurrent tracing support. The BPF_PERF_OUTPUT mechanism, covered earlier, is preferred.
1860 - ```nonblocking```: optional, defaults to ```False```. When set to ```True```, the program will not block waiting for input.
1867 (task, pid, cpu, flags, ts, msg) = b.trace_fields()
1874 [search /examples](https://github.com/iovisor/bcc/search?q=trace_fields+path%3Aexamples+language%3Apython&type=Code),
1875 [search /tools](https://github.com/iovisor/bcc/search?q=trace_fields+path%3Atools+language%3Apython&type=Code)
1879 Normal output from a BPF program is either:
1881 - per-event: using PERF_EVENT_OUTPUT, open_perf_buffer(), and perf_buffer_poll().
1882 - map summary: using items(), or print_log2_hist(), covered in the Maps section.
1884 ### 1. perf_buffer_poll()
1886 Syntax: ```BPF.perf_buffer_poll(timeout=T)```
1888 This polls from all open perf ring buffers, calling the callback function that was provided when calling open_perf_buffer for each entry.
1890 The timeout parameter is optional and measured in milliseconds. In its absence, polling continues indefinitely.
1895 # loop with callback to print_event
1896 b["events"].open_perf_buffer(print_event)
1899 b.perf_buffer_poll()
1900 except KeyboardInterrupt:
1905 [code](https://github.com/iovisor/bcc/blob/v0.9.0/examples/tracing/hello_perf_output.py#L55),
1906 [search /examples](https://github.com/iovisor/bcc/search?q=perf_buffer_poll+path%3Aexamples+language%3Apython&type=Code),
1907 [search /tools](https://github.com/iovisor/bcc/search?q=perf_buffer_poll+path%3Atools+language%3Apython&type=Code)
1909 ### 2. ring_buffer_poll()
1911 Syntax: ```BPF.ring_buffer_poll(timeout=T)```
1913 This polls from all open ringbuf ring buffers, calling the callback function that was provided when calling open_ring_buffer for each entry.
1915 The timeout parameter is optional and measured in milliseconds. In its absence, polling continues until
1916 there is no more data or the callback returns a negative value.
1921 # loop with callback to print_event
1922 b["events"].open_ring_buffer(print_event)
1925 b.ring_buffer_poll(30)
1926 except KeyboardInterrupt:
1931 [search /examples](https://github.com/iovisor/bcc/search?q=ring_buffer_poll+path%3Aexamples+language%3Apython&type=Code),
1933 ### 3. ring_buffer_consume()
1935 Syntax: ```BPF.ring_buffer_consume()```
1937 This consumes from all open ringbuf ring buffers, calling the callback function that was provided when calling open_ring_buffer for each entry.
1939 Unlike ```ring_buffer_poll```, this method **does not poll for data** before attempting to consume.
1940 This reduces latency at the expense of higher CPU consumption. If you are unsure which to use,
1941 use ```ring_buffer_poll```.
1946 # loop with callback to print_event
1947 b["events"].open_ring_buffer(print_event)
1950 b.ring_buffer_consume()
1951 except KeyboardInterrupt:
1956 [search /examples](https://github.com/iovisor/bcc/search?q=ring_buffer_consume+path%3Aexamples+language%3Apython&type=Code),
1960 Maps are BPF data stores, and are used in bcc to implement a table, and then higher level objects on top of tables, including hashes and histograms.
1964 Syntax: ```BPF.get_table(name)```
1966 Returns a table object. This is no longer used, as tables can now be read as items from BPF. Eg: ```BPF[name]```.
1971 counts = b.get_table("counts")
1973 counts = b["counts"]
1976 These are equivalent.
1978 ### 2. open_perf_buffer()
1980 Syntax: ```table.open_perf_buffers(callback, page_cnt=N, lost_cb=None)```
1982 This operates on a table as defined in BPF as BPF_PERF_OUTPUT(), and associates the callback Python function ```callback``` to be called when data is available in the perf ring buffer. This is part of the recommended mechanism for transferring per-event data from kernel to user space. The size of the perf ring buffer can be specified via the ```page_cnt``` parameter, which must be a power of two number of pages and defaults to 8. If the callback is not processing data fast enough, some submitted data may be lost. ```lost_cb``` will be called to log / monitor the lost count. If ```lost_cb``` is the default ```None``` value, it will just print a line of message to ```stderr```.
1988 def print_event(cpu, data, size):
1989 event = ct.cast(data, ct.POINTER(Data)).contents
1992 # loop with callback to print_event
1993 b["events"].open_perf_buffer(print_event)
1996 b.perf_buffer_poll()
1997 except KeyboardInterrupt:
2001 Note that the data structure transferred will need to be declared in C in the BPF program. For example:
2004 // define output data structure in C
2008 char comm[TASK_COMM_LEN];
2010 BPF_PERF_OUTPUT(events);
2014 In Python, you can either let bcc generate the data structure from C declaration automatically (recommended):
2017 def print_event(cpu, data, size):
2018 event = b["events"].event(data)
2022 or define it manually:
2025 # define output data structure in Python
2026 TASK_COMM_LEN = 16 # linux/sched.h
2027 class Data(ct.Structure):
2028 _fields_ = [("pid", ct.c_ulonglong),
2029 ("ts", ct.c_ulonglong),
2030 ("comm", ct.c_char * TASK_COMM_LEN)]
2032 def print_event(cpu, data, size):
2033 event = ct.cast(data, ct.POINTER(Data)).contents
2038 [code](https://github.com/iovisor/bcc/blob/v0.9.0/examples/tracing/hello_perf_output.py#L52),
2039 [search /examples](https://github.com/iovisor/bcc/search?q=open_perf_buffer+path%3Aexamples+language%3Apython&type=Code),
2040 [search /tools](https://github.com/iovisor/bcc/search?q=open_perf_buffer+path%3Atools+language%3Apython&type=Code)
2044 Syntax: ```table.items()```
2046 Returns an array of the keys in a table. This can be used with BPF_HASH maps to fetch, and iterate, over the keys.
2052 print("%10s %s" % ("COUNT", "STRING"))
2053 counts = b.get_table("counts")
2054 for k, v in sorted(counts.items(), key=lambda counts: counts[1].value):
2055 print("%10d \"%s\"" % (v.value, k.c.encode('string-escape')))
2058 This example also uses the ```sorted()``` method to sort by value.
2061 [search /examples](https://github.com/iovisor/bcc/search?q=items+path%3Aexamples+language%3Apython&type=Code),
2062 [search /tools](https://github.com/iovisor/bcc/search?q=items+path%3Atools+language%3Apython&type=Code)
2066 Syntax: ```table.values()```
2068 Returns an array of the values in a table.
2072 Syntax: ```table.clear()```
2074 Clears the table: deletes all entries.
2079 # print map summary every second:
2082 print("%-8s\n" % time.strftime("%H:%M:%S"), end="")
2083 dist.print_log2_hist(sym + " return:")
2088 [search /examples](https://github.com/iovisor/bcc/search?q=clear+path%3Aexamples+language%3Apython&type=Code),
2089 [search /tools](https://github.com/iovisor/bcc/search?q=clear+path%3Atools+language%3Apython&type=Code)
2091 ### 6. items_lookup_and_delete_batch()
2093 Syntax: ```table.items_lookup_and_delete_batch()```
2095 Returns an array of the keys in a table with a single call to BPF syscall. This can be used with BPF_HASH maps to fetch, and iterate, over the keys. It also clears the table: deletes all entries.
2096 You should rather use table.items_lookup_and_delete_batch() than table.items() followed by table.clear(). It requires kernel v5.6.
2101 # print call rate per second:
2102 print("%9s-%9s-%8s-%9s" % ("PID", "COMM", "fname", "counter"))
2104 for k, v in sorted(b['map'].items_lookup_and_delete_batch(), key=lambda kv: (kv[0]).pid):
2105 print("%9s-%9s-%8s-%9d" % (k.pid, k.comm, k.fname, v.counter))
2109 ### 7. items_lookup_batch()
2111 Syntax: ```table.items_lookup_batch()```
2113 Returns an array of the keys in a table with a single call to BPF syscall. This can be used with BPF_HASH maps to fetch, and iterate, over the keys.
2114 You should rather use table.items_lookup_batch() than table.items(). It requires kernel v5.6.
2119 # print current value of map:
2120 print("%9s-%9s-%8s-%9s" % ("PID", "COMM", "fname", "counter"))
2122 for k, v in sorted(b['map'].items_lookup_batch(), key=lambda kv: (kv[0]).pid):
2123 print("%9s-%9s-%8s-%9d" % (k.pid, k.comm, k.fname, v.counter))
2126 ### 8. items_delete_batch()
2128 Syntax: ```table.items_delete_batch(keys)```
2130 It clears all entries of a BPF_HASH map when keys is None. It is more efficient than table.clear() since it generates only one system call. You can delete a subset of a map by giving an array of keys as parameter. Those keys and their associated values will be deleted. It requires kernel v5.6.
2134 - keys is optional and by default is None.
2138 ### 9. items_update_batch()
2140 Syntax: ```table.items_update_batch(keys, values)```
2142 Update all the provided keys with new values. The two arguments must be the same length and within the map limits (between 1 and the maximum entries). It requires kernel v5.6.
2146 - keys is the list of keys to be updated
2147 - values is the list containing the new values.
2150 ### 10. print_log2_hist()
2152 Syntax: ```table.print_log2_hist(val_type="value", section_header="Bucket ptr", section_print_fn=None)```
2154 Prints a table as a log2 histogram in ASCII. The table must be stored as log2, which can be done using the BPF function ```bpf_log2l()```.
2158 - val_type: optional, column header.
2159 - section_header: if the histogram has a secondary key, multiple tables will print and section_header can be used as a header description for each.
2160 - section_print_fn: if section_print_fn is not None, it will be passed the bucket value.
2166 BPF_HISTOGRAM(dist);
2168 int kprobe__blk_account_io_done(struct pt_regs *ctx, struct request *req)
2170 dist.increment(bpf_log2l(req->__data_len / 1024));
2176 b["dist"].print_log2_hist("kbytes")
2182 kbytes : count distribution
2185 4 -> 7 : 211 |********** |
2190 128 -> 255 : 800 |**************************************|
2193 This output shows a multi-modal distribution, with the largest mode of 128->255 kbytes and a count of 800.
2195 This is an efficient way to summarize data, as the summarization is performed in-kernel, and only the count column is passed to user space.
2198 [search /examples](https://github.com/iovisor/bcc/search?q=print_log2_hist+path%3Aexamples+language%3Apython&type=Code),
2199 [search /tools](https://github.com/iovisor/bcc/search?q=print_log2_hist+path%3Atools+language%3Apython&type=Code)
2201 ### 11. print_linear_hist()
2203 Syntax: ```table.print_linear_hist(val_type="value", section_header="Bucket ptr", section_print_fn=None)```
2205 Prints a table as a linear histogram in ASCII. This is intended to visualize small integer ranges, eg, 0 to 100.
2209 - val_type: optional, column header.
2210 - section_header: if the histogram has a secondary key, multiple tables will print and section_header can be used as a header description for each.
2211 - section_print_fn: if section_print_fn is not None, it will be passed the bucket value.
2217 BPF_HISTOGRAM(dist);
2219 int kprobe__blk_account_io_done(struct pt_regs *ctx, struct request *req)
2221 dist.increment(req->__data_len / 1024);
2227 b["dist"].print_linear_hist("kbytes")
2233 kbytes : count distribution
2238 4 : 19 |****************************************|
2254 This is an efficient way to summarize data, as the summarization is performed in-kernel, and only the values in the count column are passed to user space.
2257 [search /examples](https://github.com/iovisor/bcc/search?q=print_linear_hist+path%3Aexamples+language%3Apython&type=Code),
2258 [search /tools](https://github.com/iovisor/bcc/search?q=print_linear_hist+path%3Atools+language%3Apython&type=Code)
2260 ### 12. open_ring_buffer()
2262 Syntax: ```table.open_ring_buffer(callback, ctx=None)```
2264 This operates on a table as defined in BPF as BPF_RINGBUF_OUTPUT(), and associates the callback Python function ```callback``` to be called when data is available in the ringbuf ring buffer. This is part of the new (Linux 5.8+) recommended mechanism for transferring per-event data from kernel to user space. Unlike perf buffers, ringbuf sizes are specified within the BPF program, as part of the ```BPF_RINGBUF_OUTPUT``` macro. If the callback is not processing data fast enough, some submitted data may be lost. In this case, the events should be polled more frequently and/or the size of the ring buffer should be increased.
2270 def print_event(ctx, data, size):
2271 event = ct.cast(data, ct.POINTER(Data)).contents
2274 # loop with callback to print_event
2275 b["events"].open_ring_buffer(print_event)
2278 b.ring_buffer_poll()
2279 except KeyboardInterrupt:
2283 Note that the data structure transferred will need to be declared in C in the BPF program. For example:
2286 // define output data structure in C
2290 char comm[TASK_COMM_LEN];
2292 BPF_RINGBUF_OUTPUT(events, 8);
2296 In Python, you can either let bcc generate the data structure from C declaration automatically (recommended):
2299 def print_event(ctx, data, size):
2300 event = b["events"].event(data)
2304 or define it manually:
2307 # define output data structure in Python
2308 TASK_COMM_LEN = 16 # linux/sched.h
2309 class Data(ct.Structure):
2310 _fields_ = [("pid", ct.c_ulonglong),
2311 ("ts", ct.c_ulonglong),
2312 ("comm", ct.c_char * TASK_COMM_LEN)]
2314 def print_event(ctx, data, size):
2315 event = ct.cast(data, ct.POINTER(Data)).contents
2320 [search /examples](https://github.com/iovisor/bcc/search?q=open_ring_buffer+path%3Aexamples+language%3Apython&type=Code),
2324 Syntax: ```table.push(leaf, flags=0)```
2326 Push an element onto a Stack or Queue table. Raises an exception if the operation does not succeed.
2327 Passing QueueStack.BPF_EXIST as a flag causes the Queue or Stack to discard the oldest element if it is full.
2330 [search /tests](https://github.com/iovisor/bcc/search?q=push+path%3Atests+language%3Apython&type=Code),
2334 Syntax: ```leaf = table.pop()```
2336 Pop an element from a Stack or Queue table. Unlike ```peek()```, ```pop()```
2337 removes the element from the table before returning it.
2338 Raises a KeyError exception if the operation does not succeed.
2341 [search /tests](https://github.com/iovisor/bcc/search?q=pop+path%3Atests+language%3Apython&type=Code),
2345 Syntax: ```leaf = table.peek()```
2347 Peek the element at the head of a Stack or Queue table. Unlike ```pop()```, ```peek()```
2348 does not remove the element from the table. Raises an exception if the operation does not succeed.
2351 [search /tests](https://github.com/iovisor/bcc/search?q=peek+path%3Atests+language%3Apython&type=Code),
2355 Some helper methods provided by bcc. Note that since we're in Python, we can import any Python library and their methods, including, for example, the libraries: argparse, collections, ctypes, datetime, re, socket, struct, subprocess, sys, and time.
2359 Syntax: ```BPF.ksym(addr)```
2361 Translate a kernel memory address into a kernel function name, which is returned.
2366 print("kernel function: " + b.ksym(addr))
2370 [search /examples](https://github.com/iovisor/bcc/search?q=ksym+path%3Aexamples+language%3Apython&type=Code),
2371 [search /tools](https://github.com/iovisor/bcc/search?q=ksym+path%3Atools+language%3Apython&type=Code)
2375 Syntax: ```BPF.ksymname(name)```
2377 Translate a kernel name into an address. This is the reverse of ksym. Returns -1 when the function name is unknown.
2382 print("kernel address: %x" % b.ksymname("vfs_read"))
2386 [search /examples](https://github.com/iovisor/bcc/search?q=ksymname+path%3Aexamples+language%3Apython&type=Code),
2387 [search /tools](https://github.com/iovisor/bcc/search?q=ksymname+path%3Atools+language%3Apython&type=Code)
2391 Syntax: ```BPF.sym(addr, pid, show_module=False, show_offset=False)```
2393 Translate a memory address into a function name for a pid, which is returned. A pid of less than zero will access the kernel symbol cache. The `show_module` and `show_offset` parameters control whether the module in which the symbol lies should be displayed, and whether the instruction offset from the beginning of the symbol should be displayed. These extra parameters default to `False`.
2398 print("function: " + b.sym(addr, pid))
2402 [search /examples](https://github.com/iovisor/bcc/search?q=sym+path%3Aexamples+language%3Apython&type=Code),
2403 [search /tools](https://github.com/iovisor/bcc/search?q=sym+path%3Atools+language%3Apython&type=Code)
2405 ### 4. num_open_kprobes()
2407 Syntax: ```BPF.num_open_kprobes()```
2409 Returns the number of open k[ret]probes. Can be useful for scenarios where event_re is used while attaching and detaching probes. Excludes perf_events readers.
2414 b.attach_kprobe(event_re=pattern, fn_name="trace_count")
2415 matched = b.num_open_kprobes()
2417 print("0 functions matched by \"%s\". Exiting." % args.pattern)
2422 [search /examples](https://github.com/iovisor/bcc/search?q=num_open_kprobes+path%3Aexamples+language%3Apython&type=Code),
2423 [search /tools](https://github.com/iovisor/bcc/search?q=num_open_kprobes+path%3Atools+language%3Apython&type=Code)
2425 ### 5. get_syscall_fnname()
2427 Syntax: ```BPF.get_syscall_fnname(name : str)```
2429 Return the corresponding kernel function name of the syscall. This helper function will try different prefixes and use the right one to concatenate with the syscall name. Note that the return value may vary in different versions of linux kernel and sometimes it will causing trouble. (see [#2590](https://github.com/iovisor/bcc/issues/2590))
2434 print("The function name of %s in kernel is %s" % ("clone", b.get_syscall_fnname("clone")))
2435 # sys_clone or __x64_sys_clone or ...
2439 [search /examples](https://github.com/iovisor/bcc/search?q=get_syscall_fnname+path%3Aexamples+language%3Apython&type=Code),
2440 [search /tools](https://github.com/iovisor/bcc/search?q=get_syscall_fnname+path%3Atools+language%3Apython&type=Code)
2444 See the "Understanding eBPF verifier messages" section in the kernel source under Documentation/networking/filter.txt.
2446 ## 1. Invalid mem access
2448 This can be due to trying to read memory directly, instead of operating on memory on the BPF stack. All kernel memory reads must be passed via bpf_probe_read_kernel() to copy kernel memory into the BPF stack, which can be automatic by the bcc rewriter in some cases of simple dereferencing. bpf_probe_read_kernel() does all the required checks.
2453 bpf: Permission denied
2455 1: (79) r7 = *(u64 *)(r6 +80)
2459 23: (69) r1 = *(u16 *)(r7 +16)
2460 R7 invalid mem access 'inv'
2462 Traceback (most recent call last):
2463 File "./tcpaccept", line 179, in <module>
2464 b = BPF(text=bpf_text)
2465 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 172, in __init__
2466 self._trace_autoload()
2467 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 612, in _trace_autoload
2468 fn = self.load_func(func_name, BPF.KPROBE)
2469 File "/usr/lib/python2.7/dist-packages/bcc/__init__.py", line 212, in load_func
2470 raise Exception("Failed to load BPF program %s" % func_name)
2471 Exception: Failed to load BPF program kretprobe__inet_csk_accept
2474 ## 2. Cannot call GPL only function from proprietary program
2476 This error happens when a GPL-only helper is called from a non-GPL BPF program. To fix this error, do not use GPL-only helpers from a proprietary BPF program, or relicense the BPF program under a GPL-compatible license. Check which [BPF helpers](https://github.com/iovisor/bcc/blob/master/docs/kernel-versions.md#helpers) are GPL-only, and what licenses are considered GPL-compatible.
2478 Example calling `bpf_get_stackid()`, a GPL-only BPF helper, from a proprietary program (`#define BPF_LICENSE Proprietary`):
2481 bpf: Failed to load program: Invalid argument
2483 8: (85) call bpf_get_stackid#27
2484 cannot call GPL only function from proprietary program
2487 # Environment Variables
2489 ## 1. Kernel source directory
2491 eBPF program compilation needs kernel sources or kernel headers with headers
2492 compiled. In case your kernel sources are at a non-standard location where BCC
2493 cannot find then, its possible to provide BCC the absolute path of the location
2494 by setting `BCC_KERNEL_SOURCE` to it.
2496 ## 2. Kernel version overriding
2498 By default, BCC stores the `LINUX_VERSION_CODE` in the generated eBPF object
2499 which is then passed along to the kernel when the eBPF program is loaded.
2500 Sometimes this is quite inconvenient especially when the kernel is slightly
2501 updated such as an LTS kernel release. Its extremely unlikely the slight
2502 mismatch would cause any issues with the loaded eBPF program. By setting
2503 `BCC_LINUX_VERSION_CODE` to the version of the kernel that's running, the check
2504 for verifying the kernel version can be bypassed. This is needed for programs
2505 that use kprobes. This needs to be encoded in the format: `(VERSION * 65536) +
2506 (PATCHLEVEL * 256) + SUBLEVEL`. For example, if the running kernel is `4.9.10`,
2507 then can set `export BCC_LINUX_VERSION_CODE=264458` to override the kernel
2508 version check successfully.