#include <stdio.h>
#include <sys/ptrace.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <sys/wait.h>
void *eip;
typedef struct regs {
        long ebx, ecx, edx, esi, edi, ebp, eax;
        unsigned short ds, __ds, es, __es;
        unsigned short fs, __fs, gs, __gs;
        long orig_eax, eip;
        unsigned short cs, __cs;
        long eflags, esp;
        unsigned short ss, __ss;
} REGS;

volatile pid_t pid = 0;

void usr1_intercept(int sig, siginfo_t *info, void *p) {
	pid = info->si_pid;
	printf("Got pid %d!\n", pid);
};

void die(char *where)
{
	ptrace(PTRACE_DETACH, pid, NULL, NULL);
	perror(where);
	exit(1);
}

int main(int argc, char **arg)
{
        struct regs rgs;

    struct sigaction sigh;
    sigh.sa_sigaction=usr1_intercept;
    sigemptyset(&sigh.sa_mask);
    sigh.sa_flags=SA_SIGINFO;
    sigaction(SIGUSR1, &sigh, NULL);

	arg++;

	printf("my pid is %d\n", getpid());

    wait(NULL); // for SIGUSR1
    wait(NULL); // for SIGUSR1
    select(0,NULL,NULL,NULL,NULL);

	//        if (pid = fork()) {
    if (ptrace(PTRACE_ATTACH, pid, NULL, NULL) < 0) die("ptattach");
                printf("[pid %d] cekam...\n", pid);
                printf("ready...\n");
                waitpid(pid, NULL, WUNTRACED);
                while(1) {
			static int been=0;
                //waitpid(pid, NULL, WUNTRACED);
                        if (ptrace(PTRACE_SINGLESTEP, pid, 0x1, NULL) < 0) die("ptsstep");
                waitpid(pid, NULL, WUNTRACED);
			if (!been) { sleep(2); been=1; }
                        if (ptrace(PTRACE_GETREGS, pid, 0x1, &rgs) < 0) die("ptgetregs");
                        eip = rgs.eip;
                        printf("%x\n", eip);
                }

//        } else {
             //   ptrace(PTRACE_TRACEME, 0, NULL, NULL);
  //              execvp(arg[0], arg);
    //    }
}
