/*
 * Server-side ptrace support
 *
 * Copyright (C) 1999 Alexandre Julliard
 */

#include "config.h"
#include "wine/port.h"

#include <assert.h>
#include <errno.h>
#include <stdio.h>
#include <signal.h>
#ifdef HAVE_SYS_TYPES_H
# include <sys/types.h>
#endif
#ifdef HAVE_SYS_PTRACE_H
# include <sys/ptrace.h>
#endif
#ifdef HAVE_SYS_WAIT_H
# include <sys/wait.h>
#endif
#include <unistd.h>

#include "process.h"
#include "thread.h"
#include "request.h"


#ifndef PTRACE_CONT
#define PTRACE_CONT PT_CONTINUE
#endif
#ifndef PTRACE_SINGLESTEP
#define PTRACE_SINGLESTEP PT_STEP
#endif
#ifndef PTRACE_ATTACH
#define PTRACE_ATTACH PT_ATTACH
#endif
#ifndef PTRACE_DETACH
#define PTRACE_DETACH PT_DETACH
#endif
#ifndef PTRACE_PEEKDATA
#define PTRACE_PEEKDATA PT_READ_D
#endif
#ifndef PTRACE_POKEDATA
#define PTRACE_POKEDATA PT_WRITE_D
#endif

#ifndef HAVE_SYS_PTRACE_H
#define PT_CONTINUE 0
#define PT_ATTACH   1
#define PT_DETACH   2
#define PT_READ_D   3
#define PT_WRITE_D  4
#define PT_STEP     5
inline static int ptrace(int req, ...) { errno = EPERM; return -1; /*FAIL*/ }
#endif  /* HAVE_SYS_PTRACE_H */

#ifndef __WALL
/* OpenBSD doesn't provide __WALL */
#define __WALL 0
#endif

static const int use_ptrace = 1;  /* set to 0 to disable ptrace */
extern int alarming;

#if !defined(linux)
const
#endif /* !defined(linux) */
int wait4__WALL = 0;

/* handle a status returned by wait4 */
static int handle_child_status( struct thread *thread, int tid, int status )
{
    if (WIFSTOPPED(status))
    {
        int sig = WSTOPSIG(status);
        if (thread)
            info_msg( WITH_DEBUG, thread, "*signal* signal=%d\n", sig );
        switch(sig)
        {
        case SIGSTOP:  /* continue at once if not suspended */
            if (thread && (thread->process->suspend + thread->suspend)) break;
            /* fall through */
        default:  /* ignore other signals for now */
            if (thread && get_thread_single_step( thread ))
                ptrace( PTRACE_SINGLESTEP, tid, (caddr_t)1, sig );
            else
	    {
		ptrace( PTRACE_DETACH, tid, NULL, NULL );
		thread->attached = 0;
	    }
            break;
        }
        return sig;
    }
    if (thread && (WIFSIGNALED(status) || WIFEXITED(status)))
    {
        thread->attached = 0;
        thread->unix_tid = 0;
        if (WIFSIGNALED(status))
            info_msg( WITH_DEBUG, thread, "*exited* signal=%d\n", WTERMSIG(status) );
        else
            info_msg( WITH_DEBUG, thread, "*exited* status=%d\n", WEXITSTATUS(status) );
    }
    return 0;
}

/* handle a SIGCHLD signal */
void sigchld_handler( int sig )
{
    int tid, status;

    for (;;)
    {
        if (!(tid = wait4( -1, &status, WUNTRACED | WNOHANG | wait4__WALL, NULL ))) break;
        if (tid != -1) handle_child_status( get_thread_from_tid(tid), tid, status );
        else break;
    }
}

/* wait for a ptraced child to get a certain signal */
void wait4_thread( struct thread *thread, int signal )
{
    int res, status;

    do
    {
        alarming = 0;
        alarm(1); /* make wait4 timeout in 1 second */
        if ((res = wait4( thread->unix_tid, &status, WUNTRACED | wait4__WALL, NULL )) == -1)
        {
            if (errno == EINTR && alarming) {
                fprintf(stderr, "WARNING: wait4 timed out\n");
                return;
            }
            perror( "wait4" );
            return;
        }
        alarm(0);
        res = handle_child_status( thread, res, status );
    } while (res && res != signal);
}

/* attach to a Unix thread */
static int attach_thread( struct thread *thread )
{
    /* this may fail if the client is already being debugged */
    if (!use_ptrace) return 0;
    if (ptrace( PTRACE_ATTACH, thread->unix_tid, 0, 0 ) == -1)
    {
        if (errno == ESRCH) thread->unix_tid = 0;  /* process got killed */
        return 0;
    }
    info_msg( WITH_DEBUG, thread, "*attached*\n" );
    thread->attached = 1;
    wait4_thread( thread, SIGSTOP );
    return 1;
}

/* detach from a Unix thread and kill it */
void detach_thread( struct thread *thread, int sig )
{
    if (!thread->unix_tid) return;
    if (thread->attached)
    {
        /* make sure it is stopped */
        suspend_thread( thread, 0 );
        if (sig) wine_tkill( thread->unix_tid, sig );
        info_msg( WITH_DEBUG, thread, "*detached*\n" );
        ptrace( PTRACE_DETACH, thread->unix_tid, (caddr_t)1, sig );
        thread->suspend = 0;  /* detach makes it continue */
        thread->attached = 0;
    }
    else
    {
        if (sig) wine_tkill( thread->unix_tid, sig );
        if (thread->suspend + thread->process->suspend) continue_thread( thread );
    }
}

/* stop a thread (at the Unix level) */
void stop_thread( struct thread *thread )
{
    /* can't stop a thread while initialisation is in progress */
    if (!thread->unix_tid || thread->process->init_event) return;
    /* first try to attach to it */
    if (!thread->attached)
        if (attach_thread( thread )) return;  /* this will have stopped it */
    /* attached already, or attach failed -> send a signal */
    if (!thread->unix_tid) return;
    wine_tkill( thread->unix_tid, SIGSTOP );
    if (thread->attached) wait4_thread( thread, SIGSTOP );
}

/* make a thread continue (at the Unix level) */
void continue_thread( struct thread *thread )
{
    if (!thread->unix_tid) return;
    if (!thread->attached) wine_tkill( thread->unix_tid, SIGCONT );
    else if (get_thread_single_step(thread))
	ptrace( PTRACE_SINGLESTEP, thread->unix_tid, (caddr_t)1, SIGSTOP);
    else
    {
	ptrace( PTRACE_DETACH, thread->unix_tid, NULL, NULL);
	thread->attached = 0;
    }
}

/* suspend a thread to allow using ptrace on it */
/* you must do a resume_thread when finished with the thread */
int suspend_for_ptrace( struct thread *thread )
{
    if (thread->attached)
    {
        suspend_thread( thread, 0 );
        return 1;
    }
    /* can't stop a thread while initialisation is in progress */
    if (!thread->unix_tid || thread->process->init_event) goto error;
    thread->suspend++;
    if (attach_thread( thread )) return 1;
    thread->suspend--;
 error:
    set_error( STATUS_ACCESS_DENIED );
    return 0;
}

/* read an int from a thread address space */
static int read_thread_int( struct thread *thread, uintptr_t addr,
			    uint32_t *data )
{
    errno = 0;
    *data = ptrace( PTRACE_PEEKDATA, thread->unix_tid, (caddr_t)addr, 0 );
    if ( *data == -1 && errno)
    {
        file_set_error();
        return -1;
    }
    return 0;
}

int read_thread_data( struct thread *thread, uintptr_t addr, size_t len,
		      void* data, size_t* p_num_read )
{
    size_t num_read = 0;
    char* p_data = (char *)data;
    size_t num_words;
    const uintptr_t offset = addr % sizeof(uint32_t);

    if (offset)
    {
	/* partial read from first word */

	uintptr_t aligned_addr = addr - offset;
	unsigned int bytes_wanted = sizeof(uint32_t) - offset;
	uint32_t buf;

	if (bytes_wanted > len)  /* needs to handle case (len < sizeof(uint32_t)) */
	    bytes_wanted = len;

	if (read_thread_int( thread, aligned_addr, &buf ) == -1) goto out_err;

	/* endian-specific: transfer the last bytes_wanted bytes from buf */
	memcpy(p_data, (char *)&buf + offset, bytes_wanted);

	p_data += bytes_wanted;
	num_read += bytes_wanted;
	addr += bytes_wanted;
	len -= bytes_wanted;
    }

    num_words = len / sizeof(uint32_t);

    while (num_words-- > 0)
    {
	uint32_t buf;
	if (read_thread_int( thread, addr, &buf ) == -1) goto out_err;

	memcpy(p_data, &buf, sizeof(buf));

	p_data += sizeof(buf);
	num_read += sizeof(buf);
	addr += sizeof(buf);
    }

    len %= sizeof(uint32_t);

    if ( len != 0 )
    {
	/* partial read from last word*/

	uint32_t buf;
	if (read_thread_int( thread, addr, &buf ) == -1) goto out_err;

	/* endian-specific: transfer the first bytes in buf */
	memcpy(p_data, (char *)&buf, len);

	num_read += len;
    }

    *p_num_read = num_read;
    return 0;

out_err:
    *p_num_read = num_read;
    return -1;
}

/* write an int to a thread address space */
static int write_thread_int( struct thread *thread, uintptr_t addr,
			     uint32_t data )
{
    int res;
    if ((res = ptrace( PTRACE_POKEDATA, thread->unix_tid, (caddr_t)addr, data )) == -1)
        file_set_error();
    return res;
}

int write_thread_data( struct thread *thread, uintptr_t addr, size_t len,
		       const void* data, size_t* p_num_written )
{
    size_t num_written = 0;
    const char* p_data = (const char *)data;
    size_t num_words;
    const uintptr_t offset = addr % sizeof(uint32_t);

    if ( offset )
    {
	/* partial write to first word */

	uintptr_t aligned_addr = addr - offset;
	unsigned int bytes_wanted = sizeof(uint32_t) - offset;
	uint32_t buf;

	if (bytes_wanted > len)  /* needs to handle case (len < sizeof(uint32_t)) */
	    bytes_wanted = len;

	if (read_thread_int( thread, aligned_addr, &buf ) == -1) goto out_err;

	/* endian-specific: transfer the last bytes_wanted bytes into buf */
	memcpy((char *)&buf + offset, p_data, bytes_wanted);

	if (write_thread_int( thread, aligned_addr, buf ) == -1) goto out_err;

	p_data += bytes_wanted;
	num_written += bytes_wanted;
	addr += bytes_wanted;
	len -= bytes_wanted;
    }

    num_words = len / sizeof(uint32_t);

    while (num_words-- > 0)
    {
	uint32_t buf;
	memcpy(&buf, p_data, sizeof(buf));

	if (write_thread_int( thread, addr, buf ) == -1) goto out_err;

	p_data += sizeof(buf);
	num_written += sizeof(buf);
	addr += sizeof(buf);
    }

    len %= sizeof(uint32_t);

    if ( len != 0 )
    {
	/* partial write to last word */

	uint32_t buf;
	if (read_thread_int( thread, addr, &buf ) == -1) goto out_err;

	/* endian-specific: transfer the first bytes into buf */
	memcpy((char *)&buf, p_data, len);

	if (write_thread_int( thread, addr, buf ) == -1) goto out_err;

	num_written += len;
    }

    *p_num_written = num_written;
    return 0;

out_err:
    *p_num_written = num_written;
    return -1;
}
