/*
Copyright (C) 2006 Evan Teran
                   eteran@alum.rit.edu

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., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

#include "DebuggerCore.h"
#include "State.h"
#include "Util.h"
#include "DebugEvent.h"

#include <QStringList>
#include <QProcess>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <sys/mman.h>
#include <cerrno>
#include <cassert>
#include <climits>
#include <signal.h>
#include <endian.h>
#include <signal.h>
#include <unistd.h>

// doesn't always seem to be defined in the headers
#ifndef PTRACE_GETSIGINFO
#define PTRACE_GETSIGINFO	(__ptrace_request)0x4202
#endif

#define SUPPORT_TIMEOUTS

#define SET_OK(ok, v) do { (ok) = ((v) != -1) || (errno != EBUSY && errno != EFAULT && errno != EIO && errno != ESRCH); } while(0)

#if 1
#define EDB_PAGESIZE PAGE_SIZE
#else
// TODO: find out if this is the ideal solution
#define EDB_PAGESIZE sysconf(_SC_PAGESIZE)	
#endif
#define EDB_WORDSIZE sizeof(long)

// int 3
const char DebuggerCore::m_BreakInstruction[] = { 0xcc };

//------------------------------------------------------------------------------
// Name: DebuggerCore()
// Desc: constructor
//------------------------------------------------------------------------------
DebuggerCore::DebuggerCore() : m_PID(0) {
}

//------------------------------------------------------------------------------
// Name: ~DebuggerCore()
// Desc: destructor
//------------------------------------------------------------------------------
DebuggerCore::~DebuggerCore() {
	detach();
}

//------------------------------------------------------------------------------
// Name: getFaultAddress()
// Desc: gets the address of a segfault (Linux >= 2.3.99-pre6)
//------------------------------------------------------------------------------
edb::address_t DebuggerCore::getFaultAddress() {
	edb::address_t ret = static_cast<edb::address_t>(-1);

	siginfo_t info;
	if(attached()) {
		const int r = ptrace(PTRACE_GETSIGINFO, pid(), 0, &info);
		if(r != -1) {
			ret = reinterpret_cast<edb::address_t>(info.si_addr);
		}
	}
	return ret;
}

//------------------------------------------------------------------------------
// Name: executionBreakpointSize() const
// Desc: returns the size of a breakpoint
//------------------------------------------------------------------------------
int DebuggerCore::executionBreakpointSize() const {
	return sizeof(m_BreakInstruction);
}

//------------------------------------------------------------------------------
// Name: executionBreakpointData() const
// Desc: returns the value of a breakpoint
//------------------------------------------------------------------------------
QByteArray DebuggerCore::executionBreakpointData() const {
	return QByteArray(&m_BreakInstruction[0], sizeof(m_BreakInstruction));
}

//------------------------------------------------------------------------------
// Name: waitForDebugEvent(DebugEvent *event, bool &ok, int secs)
// Desc: waits for a debug event, secs is a timeout (but is not yet respected)
//       ok will be set to false if the timeout expires
//------------------------------------------------------------------------------
void DebuggerCore::waitForDebugEvent(DebugEvent *event, bool &ok, int secs) {
	Q_UNUSED(secs);

	// TODO: implement the timeout here...

	ok = false;
	if(attached()) {

		int status = 0;
		const int ret = waitpid(pid(), &status, 0);
		ok = (ret != -1 && errno != EINTR);
		if(ok && event != 0) {
			*event = DebugEvent(status);
		}
	}
}

//------------------------------------------------------------------------------
// Name: readBytes(edb::address_t address, void *buf, std::size_t len)
// Desc: reads <len> bytes into <buf> starting at <address>
// Note: if the read failed, the part of the buffer that could not be read will 
//       be filled with 0xff bytes
//------------------------------------------------------------------------------
bool DebuggerCore::readBytes(edb::address_t address, void *buf, std::size_t len) {
	uint8_t *p = reinterpret_cast<uint8_t *>(buf);
	bool ok = true;
	
	while(ok && len--) {
		*p++ = readByte(address++, &ok);
	}
	
	if(!ok) {
		while(len--) {
			*p++ = 0xff;
		}
	}
	
	return ok;
}

//------------------------------------------------------------------------------
// Name: writeBytes(edb::address_t address, const void *buf, std::size_t len)
// Desc: writes <len> bytes from <buf> starting at <address>
//------------------------------------------------------------------------------
bool DebuggerCore::writeBytes(edb::address_t address, const void *buf, std::size_t len) {
	const uint8_t *p = reinterpret_cast<const uint8_t *>(buf);
	bool ok = true;
	while(ok && len--) {
		writeByte(address++, *p++, &ok);
	}
	
	return ok;
}


//------------------------------------------------------------------------------
// Name: writeByte(edb::address_t address, uint8_t value, bool *ok)
// Desc: writes a single byte at a given address
//------------------------------------------------------------------------------
void DebuggerCore::writeByte(edb::address_t address, uint8_t value, bool *ok) {
	bool readOK;
	writeByteBase(address, value, readOK);
	
	// TODO: warn if the write will trample a breakpoint
	
	setBool(ok, readOK);
}

//------------------------------------------------------------------------------
// Name: readByte(edb::address_t address, bool *ok)
// Desc: reads a single bytes at a given address
//------------------------------------------------------------------------------
uint8_t DebuggerCore::readByte(edb::address_t address, bool *ok) {

	// TODO: handle if breakponts have a size more than 1!
	bool readOK;
	uint8_t ret = readByteBase(address, readOK);
	
	if(readOK) {
		Breakpoint *const bp = findBreakpoint(address);
		if(bp != 0) {
			ret = bp->originalBytes[0];
		}
	}
	
	setBool(ok, readOK);
	return ret;
}

//------------------------------------------------------------------------------
// Name: writeByteBase(edb::address_t address, uint8_t value, bool &ok)
// Desc: the base implementation of writing a byte
//------------------------------------------------------------------------------
void DebuggerCore::writeByteBase(edb::address_t address, uint8_t value, bool &ok) {
	// TOOD: assert that we are paused
	
	ok = true;
	if(attached()) {
		long v;
		long mask;
		// EDB_PAGESIZE - 1 will always be 0xf* because pagesizes
		// are always 0x10*, so the masking works
		// range of a is [1..n] where n=pagesize, and we have to adjust
		// if a < wordsize
		const edb::address_t a = EDB_PAGESIZE - (address & (EDB_PAGESIZE - 1));
		
		v = value;
#if __BYTE_ORDER == __LITTLE_ENDIAN
		if (a < EDB_WORDSIZE) {
			address -= (EDB_WORDSIZE - a);							// LE + BE
			mask = ~(0xffUL << (CHAR_BIT * (EDB_WORDSIZE - a)));	// LE
			v <<= CHAR_BIT * (EDB_WORDSIZE - a);					// LE
		} else {
			mask = ~0xffUL; // LE
		}
#else /* BIG ENDIAN */
		if (a < EDB_WORDSIZE) {
			address -= (EDB_WORDSIZE - a);				// LE + BE
			mask = ~(0xffUL << (CHAR_BIT * (a - 1)));	// BE
			v <<= CHAR_BIT * (a - 1);					// BE
		} else {
			mask = ~(0xffUL << (CHAR_BIT * (EDB_WORDSIZE - 1)));	// BE
			v <<= CHAR_BIT * (EDB_WORDSIZE-1);						// BE
		}
#endif
		v = (ptrace(PTRACE_PEEKTEXT, pid(), address, 0) & mask) | v;
		SET_OK(ok, v);
		if(ok) {
			v = ptrace(PTRACE_POKETEXT, pid(), address, v);
			SET_OK(ok, v);
		}
	}
}

//------------------------------------------------------------------------------
// Name: readByteBase(edb::address_t address, bool &ok)
// Desc: the base implementation of reading a byte
//------------------------------------------------------------------------------
uint8_t DebuggerCore::readByteBase(edb::address_t address, bool &ok) {
	// TOOD: assert that we are paused

	uint8_t ret = 0xff;
	ok = true;
	errno = -1;
	if(attached()) {
		// if this spot is unreadable, then just return 0xff, otherwise
		// continue as normal and hide any breakpoints we may have
		
		// EDB_PAGESIZE - 1 will always be 0xf* because pagesizes
		// are always 0x10*, so the masking works
		// range of a is [1..n] where n=pagesize, and we have to adjust
		// if a < wordsize
		const edb::address_t a = EDB_PAGESIZE - (address & (EDB_PAGESIZE - 1));
				
		if (a < EDB_WORDSIZE) {
			address -= (EDB_WORDSIZE - a);		// LE + BE
		}
		
		long value = ptrace(PTRACE_PEEKTEXT, pid(), address, 0);
		SET_OK(ok, value);
		if(ok) {
#if __BYTE_ORDER == __LITTLE_ENDIAN
			if (a < EDB_WORDSIZE) {
				value >>= CHAR_BIT * (EDB_WORDSIZE - a);	// LE
			}
#else
			if (a < EDB_WORDSIZE) {
				value >>= CHAR_BIT * (a - 1);				// BE
			} else {
				value >>= CHAR_BIT * (EDB_WORDSIZE - 1);	// BE
			}
#endif
			ret = value & 0xff;
		}
	}
	return ret;
}

//------------------------------------------------------------------------------
// Name: attach(edb::pid_t pid)
// Desc: 
//------------------------------------------------------------------------------
bool DebuggerCore::attach(edb::pid_t pid) {
	detach();
	
	const long ret = ptrace(PTRACE_ATTACH, pid, 0, 0);
	if(ret == 0) {
		m_PID = pid;
		bool ok;
		waitForDebugEvent(0, ok, INT_MAX);
	}
	
	return ret == 0;
}

//------------------------------------------------------------------------------
// Name: clearBreakpoints()
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::clearBreakpoints() {

	foreach(Breakpoint bp, m_Breakpoints) {
		removeBreakpoint(bp.address);
	}

	m_Breakpoints.clear();
}

//------------------------------------------------------------------------------
// Name: detach()
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::detach() {
	if(attached()) {
		clearBreakpoints();
		ptrace(PTRACE_DETACH, pid(), 0, 0);
		m_PID = 0;
	}
}

//------------------------------------------------------------------------------
// Name: kill()
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::kill() {
	if(attached()) {
		clearBreakpoints();
		ptrace(PTRACE_KILL, pid(), 0, 0);
		m_PID = 0;
	}
}

//------------------------------------------------------------------------------
// Name: addBreakpoint(edb::address_t address, bool oneTime)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::addBreakpoint(edb::address_t address, bool oneTime) {

	// TODO: assert paused

	if(findBreakpoint(address) == 0) {
		// backup original bytes
		char prev[executionBreakpointSize()];
		if(readBytes(address, prev, executionBreakpointSize())) {

			// write the breakpoint
			if(writeBytes(address, executionBreakpointData(), executionBreakpointSize())) {

				// create accounting structure
				Breakpoint data;
				data.address = address;
				data.setOneTime(oneTime);
				data.setEnabled(true);
				data.originalBytes = QByteArray(prev, executionBreakpointSize());

				m_Breakpoints[address] = data;
			}
		}
	}
}

//------------------------------------------------------------------------------
// Name: setBreakpointCondition(edb::address_t address, const QString &condition)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::setBreakpointCondition(edb::address_t address, const QString &condition) {
	Breakpoint *const bp = findBreakpoint(address);
	if(bp != 0) {
		bp->condition = condition;
	}
}

//------------------------------------------------------------------------------
// Name: setBreakpointCondition(edb::address_t address, const QString &condition)
// Desc: 
//------------------------------------------------------------------------------
QString DebuggerCore::getBreakpointCondition(edb::address_t address) {
	QString ret;
	Breakpoint *const bp = findBreakpoint(address);
	if(bp != 0) {
		ret = bp->condition;
	}
	
	return ret;
}

//------------------------------------------------------------------------------
// Name: findBreakpoint(edb::address_t address) const
// Desc: 
//------------------------------------------------------------------------------
Breakpoint *DebuggerCore::findBreakpoint(edb::address_t address) {
	BreakpointState::iterator i = m_Breakpoints.find(address);
	return (i != m_Breakpoints.end()) ? &(i.value()) : 0;
}


//------------------------------------------------------------------------------
// Name: removeBreakpoint(edb::address_t address)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::removeBreakpoint(edb::address_t address) {

	// TODO: assert paused
	
	BreakpointState::iterator i = m_Breakpoints.find(address);
	if(i != m_Breakpoints.end()) {
		// this is an existing breakpoint
		if(writeBytes(address, i.value().originalBytes, executionBreakpointSize())) {
			m_Breakpoints.erase(i);
		}
	}
}

//------------------------------------------------------------------------------
// Name: disableBreakpoint(edb::address_t address)
// Desc: 
//------------------------------------------------------------------------------
edb::address_t DebuggerCore::disableBreakpoint(edb::address_t address) {

	// TODO: assert paused
	if(address != 0) {
		Breakpoint *const bp = findBreakpoint(address);
		if(bp != 0) {
			// this is an existing breakpoint
			if(writeBytes(address, bp->originalBytes, executionBreakpointSize())) {
				bp->setEnabled(false);
				return address;
			}	
		}
	}
	return 0;
}

//------------------------------------------------------------------------------
// Name: enableBreakpoint(edb::address_t address)
// Desc: 
//------------------------------------------------------------------------------
edb::address_t DebuggerCore::enableBreakpoint(edb::address_t address) {

	// TODO: assert paused
	if(address != 0) {
		Breakpoint *const bp = findBreakpoint(address);
		if(bp != 0) {
			if(!bp->enabled()) {

				char prev[executionBreakpointSize()];
				if(readBytes(address, prev, executionBreakpointSize())) {

					if(writeBytes(address, executionBreakpointData(), executionBreakpointSize())) {
						bp->setEnabled(true);
						bp->originalBytes = QByteArray(prev, executionBreakpointSize());
						return address;
					}
				}
			}
		}
	}
	return 0;
}

//------------------------------------------------------------------------------
// Name: backupBreakpoints(BreakpointState &state) const
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::backupBreakpoints(BreakpointState &state) {
	state = m_Breakpoints;
}

//------------------------------------------------------------------------------
// Name: pause()
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::pause() {

	if(attached()) {
		::kill(pid(), SIGSTOP);
	}
}

//------------------------------------------------------------------------------
// Name: resume(int signum)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::resume(int signum) {
	// TOOD: assert that we are paused
	
	if(attached()) {
		ptrace(PTRACE_CONT, pid(), 0, reinterpret_cast<void *>(signum));
	}
}

//------------------------------------------------------------------------------
// Name: step(int signum)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::step(int signum) {
	// TOOD: assert that we are paused
	
	if(attached()) {
		ptrace(PTRACE_SINGLESTEP, pid(), 0, reinterpret_cast<void *>(signum));
	}
}

//------------------------------------------------------------------------------
// Name: getState(State &state)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::getState(State &state) {
	// TOOD: assert that we are paused
	
	if(attached()) {
		user_regs_struct	regs;
		user_fpregs_struct	i387_regs;
		
		if(ptrace(PTRACE_GETREGS, pid(), 0, &regs) != -1) {
			state.eax = regs.eax;
			state.ebx = regs.ebx;
			state.ecx = regs.ecx;
			state.edx = regs.edx;
			state.esp = regs.esp;
			state.ebp = regs.ebp;
			state.edi = regs.edi;
			state.esi = regs.esi;
			state.eip = regs.eip;
			state.eflags = regs.eflags;
			state._cs = regs.xcs;
			state._ds = regs.xds;
			state._es = regs.xes;
			state._fs = regs.xfs;
			state._gs = regs.xgs;
			state._ss = regs.xss;
			state.orig_eax = regs.orig_eax;
		}
		
		if(ptrace(PTRACE_GETFPREGS, pid(), 0, &i387_regs) != -1) {
			State::i387Register *const p = reinterpret_cast<State::i387Register *>(i387_regs.st_space);
			for(int i = 0; i < 8; ++i) {
				state.st[i] = p[i];
			}
		}	
	} else {
		state.clear();
	}
}

//------------------------------------------------------------------------------
// Name: setState(const State &state)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::setState(const State &state) {
	
	// TOOD: assert that we are paused
	
	if(attached()) {
		user_regs_struct regs;
				
		regs.eax = state.eax;
		regs.ebx = state.ebx;
		regs.ecx = state.ecx;
		regs.edx = state.edx;
		regs.esp = state.esp;
		regs.ebp = state.ebp;
		regs.edi = state.edi;
		regs.esi = state.esi;
		regs.eip = state.eip;
		regs.eflags = state.eflags;
		regs.xcs = state._cs;
		regs.xds = state._ds;
		regs.xes = state._es;
		regs.xfs = state._fs;
		regs.xgs = state._gs;
		regs.xss = state._ss;
		regs.orig_eax = state.orig_eax;
		
		ptrace(PTRACE_SETREGS, pid(), 0, &regs);
	}
}

//------------------------------------------------------------------------------
// Name: doExecProcess(const QString &path, const QString &cwd, const QStringList &args)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::doExecProcess(const QString &path, const QString &cwd, const QStringList &args) {
	// change to the desired working directory
	chdir(cwd.toAscii());

	// allocate space for all the arguments
	char **const argv_pointers = new char *[args.count() + 2];

	char **p = argv_pointers;

	*p = new char[path.length() + 1];
	std::strcpy(*p, qPrintable(path));
	++p;

	for(int i = 0; i < args.count(); ++i) {
		const QString s(args[i]);
		*p = new char[s.length() + 1];
		std::strcpy(*p, qPrintable(s));
		++p;
	}

	*p = 0;

	execvp(argv_pointers[0], &argv_pointers[0]);
	
	// no need to cleanup, the process which allocated all that space no longer exists!
	// if we get here...execvep failed!
	p = argv_pointers;
	while(*p != 0) {
		delete [] *p++;
	}
	delete [] argv_pointers;
}

//------------------------------------------------------------------------------
// Name: open(const QString &path, const QString &cwd, const QStringList &args, const QString &tty)
// Desc: 
//------------------------------------------------------------------------------
bool DebuggerCore::open(const QString &path, const QString &cwd, const QStringList &args, const QString &tty) {
	detach();
	pid_t pid;
	bool ret = false;

	switch(pid = fork()) {
	case 0:
		// we are in the child now...
	
		// set ourselves (the child proc) up to be traced
		ptrace(PTRACE_TRACEME, 0, 0, 0);
		
		if(!tty.isEmpty()) {
			freopen(qPrintable(tty), "r+b", stdout);
			freopen(qPrintable(tty), "r+b", stdin);
			freopen(qPrintable(tty), "r+b", stderr);
		}
		
		// do the actual exec
		doExecProcess(path, cwd, args);
		
		// we should never get here!
		abort();
		break;
	case -1:
		// error!
		m_PID = 0;
		break;
	default:
		// parent
		do {
			m_PID = pid;
			DebugEvent event;
			
			bool ok;
			waitForDebugEvent(&event, ok, INT_MAX);
			
			if(event.reason() == DebugEvent::EVENT_STOPPED) {
				switch(event.stopSignal()) {
				case SIGABRT:
					m_PID = 0;
					break;
				default:
					ret = true;
					break;
				}
			} else {
				m_PID = 0;
			}
		} while(0);
		break;
	}
	
	return ret;
}

//------------------------------------------------------------------------------
// Name: open(const QString &path, const QString &cwd, const QStringList &args)
// Desc: 
//------------------------------------------------------------------------------
bool DebuggerCore::open(const QString &path, const QString &cwd, const QStringList &args) {
	return open(path, cwd, args, "");
}

//------------------------------------------------------------------------------
// Name: pid() const
// Desc: returns the pid of the currently debugged process
//------------------------------------------------------------------------------
edb::pid_t DebuggerCore::pid() const {
	return m_PID;
}

//------------------------------------------------------------------------------
// Name: attached() const
// Desc: 
//------------------------------------------------------------------------------
bool DebuggerCore::attached() const {
	return pid() != 0;
}

//------------------------------------------------------------------------------
// Name: author() const
// Desc: 
//------------------------------------------------------------------------------
QString DebuggerCore::author() const {
	return "Evan Teran";
}

Q_EXPORT_PLUGIN2(DebuggerCorePtrace, DebuggerCore)
