#include <unistd.h>
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <stdio.h>
#include <signal.h>
#include <stddef.h>

#include <linux/ptrace.h>

#define err(x) perror(x),exit(1)

int last_sig; 

void sighand(int s)
{
	last_sig = s;
}

/* Usable sigaction wrapper */
int setsignal(int sig, void (*hand)(int), int flags, sigset_t *mask)
{
	struct sigaction sa = {0};

	sa.sa_handler = hand;
	if (mask) 
		sa.sa_mask = *mask;
	sa.sa_flags = flags;
	return sigaction(sig, &sa, NULL); 
} 

static inline 
unsigned long get_register(pid_t pid, int regno)
{
	int res;

	res = ptrace(PTRACE_PEEKUSR, pid, regno*4, 0);
	return res;
}

#define MAXREG 14 /* 15 */
const char *regnames[] = { 
	"ebx","ecx","edx","esi","edi",
	"ebp","eax","ds","es","fs","gs","o_eax",
	"eip","cs","efl","uesp","ss" 
};
const int regs[] = { 
	EIP, 
	EAX, ECX, EDX, EBX, /* UESP*/-1,  ESI, EDI, EFL,
	CS, SS, DS, ES, FS, GS, 
}; 

void dump_reg(pid_t pid)
{
	int c;

	for (c = 0; c < MAXREG; c++) { 
		int reg = regs[c];
		if (reg == -1) continue; 
		printf("%s:\t%lx\n", regnames[reg], get_register(pid, reg)); 
	}
	
}

void step(pid_t pid)
{
	static int cnt;
	unsigned long eip;

	eip = get_register(pid, EIP); 
#if 1
	if (((cnt++) % 100) == 0) 
		printf("eip = %lx\n",eip);
#endif
}

void child(char **av)
{		
	printf("[child] (%d) starting\n", getpid());
	
	/* Dear Debugger. Please trace us. */
	if (ptrace(PTRACE_TRACEME, 0, 0, 0) < 0) 
		err("[child] ptrace(TRACEME)"); 
	if (kill(getpid(), SIGSTOP) < 0) 
		err("[child] signal(me)");

	printf("child running again\n");

#if 0
	for(;;) ;
#else
	execvp(av[0], av); 
	err("execvp");
#endif
}

int main(int ac, char **av)
{
	pid_t pid; 
	int status; 
	enum { Starting, Running } state;

	if (ac == 1) { 
		printf("usage: %s program [args..]\n", av[0]); 
		exit(1);
	}

	setsignal(SIGTRAP, sighand, SA_RESTART, NULL); 
	setsignal(SIGCHLD, sighand, SA_RESTART, NULL); 

	pid = fork();
	switch (pid) { 
	case -1:
		err("fork");
	case 0: /* child */
		child(av+1); 
		/* NOT REACHED */
	default: 
		break; 
	}
  
	printf("[parent] doing trace\n");

	state = Starting;
	for (;;) { 
		static int oldpid;

		if ((pid = waitpid(0, &status, WUNTRACED)) < 0) 
			err("waitpid");

		if (pid != oldpid) { 
			printf("new pid = %d\n", pid);
			oldpid = pid;
		}
		
		if (WIFSTOPPED(status)) {
			int sig = WSTOPSIG(status);

			switch (sig) {
			case SIGTRAP:
				step(pid);
				sig = 0;
				break;
			case SIGSTOP:
				if (state == Starting) {  /* Initial STOP */
					state = Running;
					sig = 0;  /* cancel the signal */
				}
				break;
			default:
				break;
			}
			/* wait for the next signal */
			ptrace(PTRACE_CONT, pid, 1, sig);       
		} else if (WIFEXITED(status)) {
			/* XXX: threads */
			printf("child exited.\n");
			break;
		} else {
			printf("???\n");
		}		
	}
	return 0; 
}

