/*
 * debug.c - Trace hard to debug programs
 * 
 * Copyright (C) 2002  Jochen Eisinger <jochen@penguin-breeder.org>
 * 
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 *
 */
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <string.h>

#include <sys/ptrace.h>
#include <sys/types.h>
#include <sys/wait.h>

#include <asm/io.h>
#include <asm/ptrace.h>

#include <sys/reg.h>

void debugger(char **argv)
{
	pid_t pid = 0;		/* PID of executable */
	int status;
	unsigned long val;
	long regs[17];

	/* divide in two */
	pid = fork();

	if (pid == 0) {

		/* This process will become the traced proggy */

		/* prepare for debugging */
		ptrace(PTRACE_TRACEME, 0, 0, 0);

		/* redirect output to stderr */
		fclose(stdout);
		stdout = fopen("/dev/stderr", "w");

		/* execute scan */
		execv(argv[0], argv);

		/* just in case exec failed */
		return;
	}

	/* debugger process */


	wait(&status);

	if (WIFEXITED(status) || WIFSIGNALED(status))
		return;

	printf("execve() successful\n");

	for (;;) {

		/* continue... */
		ptrace(PTRACE_SINGLESTEP, pid, 0, 0);

		wait(&status);

		if (WIFEXITED(status) || WIFSIGNALED(status) ||
		    (WIFSTOPPED(status)
		     && (WSTOPSIG(status) != SIGTRAP))) {

			printf(" died...\n");
			return;

		}

		/* read current registers of the proggy */
		ptrace(PTRACE_GETREGS, pid, (long) 0, (long) &regs);


		printf(" at %08x and still alive...\n", regs[EIP], status);

	}
}

int main(int argc, char **argv)
{

	char **param;
	int ctr;

	if (argc == 1) {

		printf("usage: %s program [params]", argv[0]);
		return;
	}

	param = malloc(sizeof(char *) * argc);
	memset(param, 0, sizeof(char *) * argc);

	for (ctr = 1; ctr < argc; ctr++)
		param[ctr - 1] = strdup(argv[ctr]);

	debugger(param);

	return 0;

}
