# brk ________________________________________________________
# unsigned long sys_brk(unsigned long brk)

@define _SYSCALL_BRK_NAME
%(
	name = "brk"
%)

@define _SYSCALL_BRK_ARGSTR
%(
	argstr = sprintf("%p", brk)
%)

@define _SYSCALL_BRK_REGARGS
%(
	brk = ulong_arg(1)
%)

@define _SYSCALL_BRK_REGARGS_STORE
%(
        if (@probewrite(brk))
          set_ulong_arg(1, brk)
%)

probe syscall.brk = dw_syscall.brk !, nd_syscall.brk ? {}
probe syscall.brk.return = dw_syscall.brk.return !, nd_syscall.brk.return ? {}

# dw_brk _____________________________________________________

probe dw_syscall.brk = kernel.function("ia64_brk").call ?,
                    kernel.function("sys_brk").call
{
	@_SYSCALL_BRK_NAME
	brk = __ulong($brk)
	@_SYSCALL_BRK_ARGSTR
}
probe dw_syscall.brk.return = kernel.function("ia64_brk").return ?,
                           kernel.function("sys_brk").return
{
	@_SYSCALL_BRK_NAME
	@SYSC_RETVALSTR($return)
}

# nd_brk _____________________________________________________

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

probe nd1_syscall.brk = kprobe.function("ia64_brk") ?,
                        kprobe.function("sys_brk") ?
{
	@_SYSCALL_BRK_NAME
	asmlinkage()
	@_SYSCALL_BRK_REGARGS
	@_SYSCALL_BRK_ARGSTR
}

/* kernel 4.17+ */
probe nd2_syscall.brk = kprobe.function(@arch_syscall_prefix "sys_brk")
{
	__set_syscall_pt_regs(pointer_arg(1))
	@_SYSCALL_BRK_NAME
	@_SYSCALL_BRK_REGARGS
	@_SYSCALL_BRK_ARGSTR
},
{
        %( @_IS_SREG_KERNEL %? @_SYSCALL_BRK_REGARGS_STORE %)
}

/* kernel 3.5+, but undesirable because it affects all syscalls */
probe tp_syscall.brk = kernel.trace("sys_enter")
{
	__set_syscall_pt_regs($regs)
	@__syscall_compat_gate(@const("__NR_brk"), @const("__NR_compat_brk"))
	@_SYSCALL_BRK_NAME
	@_SYSCALL_BRK_REGARGS
	@_SYSCALL_BRK_ARGSTR
},
{
        %( @_IS_SREG_KERNEL %? @_SYSCALL_BRK_REGARGS_STORE %)
}

probe nd_syscall.brk.return = nd1_syscall.brk.return!, nd2_syscall.brk.return!, tp_syscall.brk.return
  { }
  
probe nd1_syscall.brk.return = kprobe.function("ia64_brk").return ?,
                               kprobe.function("sys_brk").return ?
{
	@_SYSCALL_BRK_NAME
	@SYSC_RETVALSTR(returnval())
}

/* kernel 4.17+ */
probe nd2_syscall.brk.return = kprobe.function(@arch_syscall_prefix "sys_brk").return
{
	@_SYSCALL_BRK_NAME
	@SYSC_RETVALSTR(returnval())
}
 
/* kernel 3.5+, but undesirable because it affects all syscalls */
probe tp_syscall.brk.return = kernel.trace("sys_exit")
{
	__set_syscall_pt_regs($regs)
	@__syscall_compat_gate(@const("__NR_brk"), @const("__NR_compat_brk"))
	@_SYSCALL_BRK_NAME
	@SYSC_RETVALSTR($ret)
}
