Helper function bpf_probe_read_kernel_str
Definition
Copyright (c) 2015 The Libbpf Authors. All rights reserved.
Copy a NUL terminated string from an unsafe kernel address unsafe_ptr to dst. Same semantics as with bpf_probe_read_user_str() apply.
Returns
On success, the strictly positive length of the string, including the trailing NUL character. On error, a negative value.
static long (* const bpf_probe_read_kernel_str)(void *dst, __u32 size, const void *unsafe_ptr) = (void *) 115;
Usage
The dst
argument must be a pointer to a buffer where the null-terminated string will be copied. The size
argument specifies the maximum number of bytes to copy, including the null terminator. The unsafe_ptr
argument must be a pointer located in kernel memory.
The return value is the number of bytes copied, including the null terminator, or a negative error code if the memory is inaccessible. This function ensures the copied string is null-terminated. If the string is shorter than size
, the buffer is not padded with extra null bytes. If the string is longer than size - 1
, only size - 1
bytes are copied, and the last byte is set to null.
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_NETFILTER
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_STRUCT_OPS
BPF_PROG_TYPE_SYSCALL
BPF_PROG_TYPE_TRACEPOINT
BPF_PROG_TYPE_TRACING
BPF_PROG_TYPE_XDP
Example
SEC("tracepoint/syscalls/sys_exit_openat")
int trace_open(struct trace_event_raw_sys_exit *ctx) {
char comm[256];
struct task_struct *task = (struct task_struct *)bpf_get_current_task();
// Try to read the process name and check for errors
int ret = bpf_probe_read_kernel_str(comm, sizeof(comm), task->comm);
if (ret < 0) {
bpf_printk("Failed to read process name, error: %d\n", ret);
return 0;
}
bpf_printk("Process name: %s\n", comm);
return 0;
}