# dup2 _______________________________________________________
# long sys_dup2(unsigned int oldfd, unsigned int newfd)

@define _SYSCALL_DUP2_NAME
%(
	name = "dup2"
%)

@define _SYSCALL_DUP2_ARGSTR
%(
	argstr = sprintf("%d, %d", oldfd, newfd)
%)

@define _SYSCALL_DUP2_REGARGS
%(
	oldfd = int_arg(1)
	newfd = int_arg(2)
	# The dup2 syscall doesn't have a 'flags' argument. But, the
	# syscall.dup2 and syscall.dup3 probes used to be combined, so
	# both probes need a 'flags' and 'flags_str' variable.
	flags = 0
	flags_str = "0x0"
%)

probe syscall.dup2 = dw_syscall.dup2 !, nd_syscall.dup2 {}
probe syscall.dup2.return = dw_syscall.dup2.return !, nd_syscall.dup2.return {}

# dw_dup2 _____________________________________________________

probe dw_syscall.dup2 = kernel.function("sys_dup2").call
{
	@_SYSCALL_DUP2_NAME
	oldfd = __int32($oldfd)
	newfd = __int32($newfd)
	# The dup2 syscall doesn't have a 'flags' argument. But, the
	# dw_syscall.dup2 and syscall.dup3 probes used to be combined, so
	# both probes need a 'flags' and 'flags_str' variable.
	flags = 0
	flags_str = "0x0"
	@_SYSCALL_DUP2_ARGSTR
}
probe dw_syscall.dup2.return = kernel.function("sys_dup2").return
{
	@_SYSCALL_DUP2_NAME
	@SYSC_RETVALSTR($return)
}

# nd_dup2 _____________________________________________________

probe nd_syscall.dup2 = nd1_syscall.dup2!, nd2_syscall.dup2!, tp_syscall.dup2
  { }

probe nd1_syscall.dup2 = kprobe.function("sys_dup2")
{
	@_SYSCALL_DUP2_NAME
	asmlinkage()
	@_SYSCALL_DUP2_REGARGS
	@_SYSCALL_DUP2_ARGSTR
}

/* kernel 4.17+ */
probe nd2_syscall.dup2 = kprobe.function(@arch_syscall_prefix "sys_dup2") ?
{
	__set_syscall_pt_regs(pointer_arg(1))
	@_SYSCALL_DUP2_NAME
	@_SYSCALL_DUP2_REGARGS
	@_SYSCALL_DUP2_ARGSTR
}

/* kernel 3.5+, but undesirable because it affects all syscalls */
probe tp_syscall.dup2 = kernel.trace("sys_enter")
{
	__set_syscall_pt_regs($regs)
	@__syscall_compat_gate(@const("__NR_dup2"), @const("__NR_compat_dup2"))
	@_SYSCALL_DUP2_NAME
	@_SYSCALL_DUP2_REGARGS
	@_SYSCALL_DUP2_ARGSTR
}

probe nd_syscall.dup2.return = nd1_syscall.dup2.return!, nd2_syscall.dup2.return!, tp_syscall.dup2.return
  { }
  
probe nd1_syscall.dup2.return = kprobe.function("sys_dup2").return
{
	@_SYSCALL_DUP2_NAME
	@SYSC_RETVALSTR(returnval())
}

/* kernel 4.17+ */
probe nd2_syscall.dup2.return = kprobe.function(@arch_syscall_prefix "sys_dup2").return ?
{
	@_SYSCALL_DUP2_NAME
	@SYSC_RETVALSTR(returnval())
}
 
/* kernel 3.5+, but undesirable because it affects all syscalls */
probe tp_syscall.dup2.return = kernel.trace("sys_exit")
{
	__set_syscall_pt_regs($regs)
	@__syscall_compat_gate(@const("__NR_dup2"), @const("__NR_compat_dup2"))
	@_SYSCALL_DUP2_NAME
	@SYSC_RETVALSTR($ret)
}
