#!/usr/bin/env bpftrace
/*
 * sydtrace.bt: Trace syd syscalls with eBPF.
 *
 * Copyright (c) 2025 Ali Polatel <alip@chesswob.org>
 * SPDX-License-Identifier: GPL-3.0
 */

tracepoint:raw_syscalls:sys_enter
/ (strncmp(comm, "syd", 3) == 0) || (comm == "4") /
{
	if (args->id == 3 || args->id == 4 || args->id == 45 || args->id == 192) {
		// skip read,write,brk,mmap,mmap2
	} else {
		@call_id[tid] = args->id;
		@a0[tid] = args->args[0];
		@a1[tid] = args->args[1];
		@a2[tid] = args->args[2];
		@a3[tid] = args->args[3];
		@a4[tid] = args->args[4];
		@a5[tid] = args->args[5];
	}
}

tracepoint:raw_syscalls:sys_exit
/ @call_id[tid] /*&& args->ret == -38*/ /
{
	$sid = @call_id[tid];
	$arg0 = @a0[tid];
	$arg1 = @a1[tid];
	$arg2 = @a2[tid];
	$arg3 = @a3[tid];
	$arg4 = @a4[tid];
	$arg5 = @a5[tid];

	printf("%s %lu:%lu comm=%s sys=%d ret=%lld args=[%llu, %llu, %llu, %llu, %llu, %llu]\n",
				 strftime("%s", nsecs),
				 pid, tid, comm,
				 $sid, args->ret,
				 $arg0, $arg1, $arg2, $arg3, $arg4, $arg5);
	printf("ustack:%s", ustack(perf, 16));
	//printf("kstack:%s", kstack(perf, 32));

	delete(@call_id[tid]);
	delete(@a0[tid]); delete(@a1[tid]); delete(@a2[tid]);
	delete(@a3[tid]); delete(@a4[tid]); delete(@a5[tid]);
}

END {
	clear(@call_id);
	clear(@a0); clear(@a1); clear(@a2); clear(@a3); clear(@a4); clear(@a5);
}
