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

#define I_FROM 0x401135
#define I_TO   0x401160

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 print_i(int pid)
{
    struct user_regs_struct r;
    long word;
    int res;

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

    if (r.rip < I_FROM || r.rip > I_TO)
        return;

    errno = 0;
    word = ptrace(PTRACE_PEEKDATA, pid, (void *)(r.rbp - 4), 0);
    if (word == -1)
        terminate("PEEKDATA", exit_process);

    printf("rip=%llx i=%d\n", r.rip, (int)word);
}

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

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

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

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

        waitpid(pid, &st, 0);

        if (WIFEXITED(st))
            break;

        print_i(pid);
    }

    return 0;
}
