#include <stdio.h>
#include <stdlib.h>
#include <sys/user.h>
#include <sys/syscall.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/ptrace.h>

enum exit_codes {
    exit_success,
    exit_failure,
    exit_arguments,
    exit_process,
    exit_signal,
    exit_file
};

void terminate(const char *msg, int code)
{
    perror(msg);
    exit(code);
}

void terminate_exec(const char *msg, int code)
{
    fflush(stderr);
    perror(msg);
    _exit(code);
}

void wait_process(pipe_t p, int n)
{
    int i, wr, status, exit_status;

    do {
	    wr = wait(&status);
	    if (wr == -1)
		    fprintf(stderr, "Error: child process failed\n");
    } while ();

    if (WIFEXITED(status)) {
        exit_status = WEXITSTATUS(status);
        if (exit_status != 0)
            printf("exited with code: %d\n", exit_status);
    } else
        printf("killed with signal: %d\n", WTERMSIG(status));

    set_sigactions(SIGCHLD, handler_sigchld);
}

void wait_process(int pid)
{
    int wr, status;

    do {
        wr = wait(&status);
        if (wr == -1)
            terminate("wait", 1);
    } while (wr != pid);

    if (WIFEXITED(status))
        printf("exited with code: %d\n", WEXITSTATUS(status));
    else
        printf("stopped with signal: %d\n", WSTOPSIG(status));
}

int launch_process(char *const cmds[])
{
    int pid;

    pid = fork();
    if (pid == -1)
        terminate("fork", exit_failure);
    if (pid == 0) {
        ptrace(PTRACE_TRACEME, 0, NULL, NULL);
        execvp(cmds[0], cmds);
        terminate_exec("execvp", exit_process);
    }

    return pid;
}

int wait_process(int pid)
{
    int wr, status;

    r = waitpid(pid, &status, 0);
    if (r == -1)
        terminate("waitpid", 1);

    if (WIFEXITED(status) || !WIFSTOPPED(status))
        return 1;

    return 0;
}

void debug(int pid)
{
    unsigned long i_addr;
    long word;
    int i_value;

    int r, to_break;
    while (1) {
        r = ptrace(PTRACE_SINGLESTEP, pid, NULL, NULL);
        if (r == -1)
            terminate("ptrace singlestep", 1);

        to_break = wait_process(pid);
        if (to_break)
            break;

        r = ptrace(PTRACE_GETREGS, pid, NULL, &regs);
        if (r == -1)
            terminate("ptrace getregs", 1);

        i_addr = regs.rbp - 4;
        word = ptrace(PTRACE_PEEKDATA, pid, (void *)i_addr, NULL);
        i_value = *(int *)&word;

        printf("RIP=0x%llx i=%d\n", (unsigned long long)regs.rip, i_value);
    }
}

int main(int argc, char **argv)
{
    int pid, status;
    struct user_regs_struct regs;

    if (argc < 2) {
        fprintf(stderr,
                "Usage: %s <commands with parameters ...> \n", argv[0]);
        exit(exit_arguments);
    }

    pid = launch_process(argv+1);
    waitpid(pid, &status, 0);
    debug(pid);

    return 0;
}
