I’m trying to use an eBPF program to trace the file descriptor passed to the sys_read syscall in a specific process. However, the program always traces negative file descriptor values.
Here are the details:
C Program (simple_read.c):
This C program reads from a file every 2 seconds and prints the content to the console.
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <time.h>
int main() {
int fd = open("sample.txt", O_RDONLY, 0644);
if (fd < 0) {
perror("Error reading");
return 0;
}
printf("current pid is: %dn", getpid());
char buffer[20];
int read_bytes;
while (read_bytes = read(fd, buffer, sizeof(buffer))) {
printf("%s", buffer);
sleep(2);
}
close(fd);
return 0;
}
eBPF Program (read_call.c):
#include <linux/ptrace.h>
int kprobe__sys_read(struct pt_regs* ctx) {
u64 target_pid = 8219;
u64 current_pid = bpf_get_current_pid_tgid() >> 32;
if (target_pid == current_pid) {
long fd = PT_REGS_PARM1(ctx);
bpf_trace_printk("fd is: %ldn", fd);
}
return 0;
}
int kretprobe__sys_read(struct pt_regs* ctx)
{
u64 target_pid = 8219;
u64 current_pid = bpf_get_current_pid_tgid() >> 32;
if (target_pid == current_pid) {
long ret = (long) PT_REGS_RC(ctx);
bpf_trace_printk("Return value is: %ldn", ret);
}
return 0;
}
Python Loader (read_call.py):
from bcc import BPF
try:
b = BPF(src_file="read_call.c")
b.trace_print()
except KeyboardInterrupt:
exit(0)
output:
b’ sample_read-8219 [000] …21 4773.866846: bpf_trace_printk: fd is: -101327861203112′
b’ sample_read-8219 [000] …21 4773.866871: bpf_trace_printk: return value is: 20′
The logic of my program is to manipulate the buffer content of the sys_write call before printing it onto the actual file. For that purpose first I was about to learn and hook the sys_read system call and retrieve the file descriptor, buffer content and length of the buffer and just trace print it nothing other than that.
So my simple_read.c program continuously read 20 character from a file and sleep for 2 seconds and read the next 20 characters. This loop continues until the file is completely being read. I have printed the pid of the process in c program.
In this eBPF program, I just check the hardcoded process id to filter only that specific process syscall read function. After that inside if statement I was about to extract the first parameter of sys_read() which is file descriptor of the process. But my output always prints the negative value.
The second parameter prints 0, and third parameter prints -1.
I don’t know why I am always getting negative value. If I have some logic mistakes in my code and due to that incorrect mistake, guide me to get the correct fd and read the contents of the buffer before printing it on to the terminal.
Anonymous_806 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.