#!/bin/sh
#
# Check that strace -p reports an existing tracer when EPERM is due to
# the target process already being traced.
#
# Copyright (c) 2026 The strace developers.
# All rights reserved.
#
# SPDX-License-Identifier: GPL-2.0-or-later

. "${srcdir=.}/init.sh"

$STRACE -q --trace=none --signal=none -- \
	sh -c "echo \$\$; sleep $TIMEOUT_DURATION" > "$OUT" 2>/dev/null &
tracer_pid=$!

while ! [ -s "$OUT" ]; do
	kill -0 "$tracer_pid" 2>/dev/null ||
		fail_ "background $STRACE failed to start"
done
tracee_pid=$(cat "$OUT")

$STRACE -p "$tracee_pid" 2>"$LOG" &&
	dump_log_and_fail_with "$STRACE -p $tracee_pid should have failed"

kill "$tracee_pid"
wait "$tracer_pid" 2>/dev/null

for cmd in PTRACE_SEIZE PTRACE_ATTACH; do
	cat > "$EXP" <<__EOF__
$STRACE_EXE: attach: ptrace($cmd, $tracee_pid): Operation not permitted
$STRACE_EXE: Process $tracee_pid is already being traced by pid $tracer_pid
__EOF__
	diff -u -- "$EXP" "$LOG" ||
		continue
	exit 0
done
dump_log_and_fail_with "unexpected $STRACE -p $tracee_pid output"
