#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/ptrace.h>
#include <sys/syscall.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);
}

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

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

    return pid;
}

void debug(int pid)
{
    int entering, res, status;
    struct user_regs_struct r;

    entering = 1;
    while (1) {
        res = ptrace(PTRACE_SINGLESTEP, pid, 0, 0);
        if (res == -1)
            terminate("PTRACE_SINGLESTEP", exit_process);

        waitpid(pid, &status, 0);

        if (WIFEXITED(status))
            break;

        res = ptrace(PTRACE_GETREGS, pid, 0, &r);
        if (res == -1)
            terminate("PTRACE_GETREGS", exit_process);

        if (entering && r.orig_rax == SYS_write)
            printf("write(fd=%lld, buf=0x%llx, count=%lld)\n", r.rdi, r.rsi, r.rdx);
        entering = !entering;
    }
}

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

    if (argc < 2) {
        fprintf(stderr, "Usage: %s program <args...>\n", argv[0]);
        return 1;
    }

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

    return 0;
}
