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_DEVICEBPF_PROG_TYPE_CGROUP_SKBBPF_PROG_TYPE_CGROUP_SOCKBPF_PROG_TYPE_CGROUP_SOCKOPTBPF_PROG_TYPE_CGROUP_SOCK_ADDRBPF_PROG_TYPE_CGROUP_SYSCTLBPF_PROG_TYPE_FLOW_DISSECTORBPF_PROG_TYPE_KPROBEBPF_PROG_TYPE_LSMBPF_PROG_TYPE_LWT_INBPF_PROG_TYPE_LWT_OUTBPF_PROG_TYPE_LWT_SEG6LOCALBPF_PROG_TYPE_LWT_XMITBPF_PROG_TYPE_NETFILTERBPF_PROG_TYPE_PERF_EVENTBPF_PROG_TYPE_RAW_TRACEPOINTBPF_PROG_TYPE_RAW_TRACEPOINT_WRITABLEBPF_PROG_TYPE_SCHED_ACTBPF_PROG_TYPE_SCHED_CLSBPF_PROG_TYPE_SK_LOOKUPBPF_PROG_TYPE_SK_MSGBPF_PROG_TYPE_SK_REUSEPORTBPF_PROG_TYPE_SK_SKBBPF_PROG_TYPE_SOCKET_FILTERBPF_PROG_TYPE_SOCK_OPSBPF_PROG_TYPE_STRUCT_OPSBPF_PROG_TYPE_SYSCALLBPF_PROG_TYPE_TRACEPOINTBPF_PROG_TYPE_TRACINGBPF_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;
}