Helper function bpf_probe_read_user_str
Definition
Copyright (c) 2015 The Libbpf Authors. All rights reserved.
Copy a NUL terminated string from an unsafe user address unsafe_ptr to dst. The size should include the terminating NUL byte. In case the string length is smaller than size, the target is not padded with further NUL bytes. If the string length is larger than size, just size-1 bytes are copied and the last byte is set to NUL.
On success, returns the number of bytes that were written, including the terminal NUL. This makes this helper useful in tracing programs for reading strings, and more importantly to get its length at runtime. See the following snippet:
SEC("kprobe/sys_open") void bpf_sys_open(struct pt_regs _ctx) { char buf[PATHLEN]; // PATHLEN is defined to 256 int res = bpf_probe_read_user_str(buf, sizeof(buf),
ctx->di);
// Consume buf, for example push it to // userspace via bpf_perf_event_output(); we // can use res (the string length) as event // size, after checking its boundaries.
}
In comparison, using bpf_probe_read_user() helper here instead to read the string would require to estimate the length at compile time, and would often result in copying more memory than necessary.
Another useful use case is when parsing individual process arguments or individual environment variables navigating current->mm->arg_start and current\ ->mm->env_start: using this helper and the return value, one can quickly iterate at the right offset of the memory area.
Returns
On success, the strictly positive length of the output string, including the trailing NUL character. On error, a negative value.
static long (* const bpf_probe_read_user_str)(void *dst, __u32 size, const void *unsafe_ptr) = (void *) 114;
Usage
Docs could be improved
This part of the docs is incomplete, contributions are very welcome
Program types
This helper call can be used in the following program types:
- BPF_PROG_TYPE_CGROUP_DEVICE
- BPF_PROG_TYPE_CGROUP_SKB
- BPF_PROG_TYPE_CGROUP_SOCK
- BPF_PROG_TYPE_CGROUP_SOCKOPT
- BPF_PROG_TYPE_CGROUP_SOCK_ADDR
- BPF_PROG_TYPE_CGROUP_SYSCTL
- BPF_PROG_TYPE_FLOW_DISSECTOR
- BPF_PROG_TYPE_KPROBE
- BPF_PROG_TYPE_LSM
- BPF_PROG_TYPE_LWT_IN
- BPF_PROG_TYPE_LWT_OUT
- BPF_PROG_TYPE_LWT_SEG6LOCAL
- BPF_PROG_TYPE_LWT_XMIT
- BPF_PROG_TYPE_PERF_EVENT
- BPF_PROG_TYPE_RAW_TRACEPOINT
- BPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLE
- BPF_PROG_TYPE_SCHED_ACT
- BPF_PROG_TYPE_SCHED_CLS
- BPF_PROG_TYPE_SK_LOOKUP
- BPF_PROG_TYPE_SK_MSG
- BPF_PROG_TYPE_SK_REUSEPORT
- BPF_PROG_TYPE_SK_SKB
- BPF_PROG_TYPE_SOCKET_FILTER
- BPF_PROG_TYPE_SOCK_OPS
- BPF_PROG_TYPE_SYSCALL
- BPF_PROG_TYPE_TRACEPOINT
- BPF_PROG_TYPE_TRACING
- BPF_PROG_TYPE_XDP
Example
Docs could be improved
This part of the docs is incomplete, contributions are very welcome