/*
Copyright (C) 2006 - 2009 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 "DebuggerCoreOpenBSD.h"
#include "State.h"
#include "DebugEvent.h"

#include <boost/bind.hpp>

#include <QDebug>

#include <cerrno>
#include <cstring>

#include <signal.h>
#include <sys/param.h>
#include <sys/mman.h>
#include <sys/ptrace.h>
#include <sys/user.h>
#include <sys/wait.h>
#include <unistd.h>
#include <machine/reg.h>

//------------------------------------------------------------------------------
// Name: DebuggerCore()
// Desc: constructor
//------------------------------------------------------------------------------
DebuggerCore::DebuggerCore() {
#if defined(_SC_PAGESIZE)
	m_PageSize = sysconf(_SC_PAGESIZE);
#elif defined(_SC_PAGE_SIZE)
	m_PageSize = sysconf(_SC_PAGE_SIZE);
#else
	m_PageSize = PAGE_SIZE;
#endif
}

//------------------------------------------------------------------------------
// Name: pageSize() const
// Desc: returns the size of a page on this system
//------------------------------------------------------------------------------
edb::address_t DebuggerCore::pageSize() const {
	return m_PageSize;
}

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

//------------------------------------------------------------------------------
// Name: waitForDebugEvent(DebugEvent &event, int msecs)
// Desc: waits for a debug event, msecs is a timeout
//      it will return false if an error or timeout occurs
//------------------------------------------------------------------------------
bool DebuggerCore::waitForDebugEvent(DebugEvent &event, int msecs) {
	if(attached()) {		
		int status;
		bool timeout;
		
		const edb::tid_t tid = waitpid_timeout(-1, &status, WAIT_ANY, msecs, timeout);
		if(!timeout) {
			if(tid > 0) {
			
				// avoid spurious messages from other PIDs we used to be tracing
				if(!m_Threads.contains(tid)) {
					return false;
				}
			
				event = DebugEvent(status, pid(), tid);
								
				m_ActiveThread			= event.thread();
				m_Threads[tid].status	= status;
				return true;
			}
		}
	}
	return false;
}

//------------------------------------------------------------------------------
// Name: readData(edb::address_t address, bool &ok)
// Desc: 
//------------------------------------------------------------------------------
long DebuggerCore::readData(edb::address_t address, bool &ok) {
	// NOTE: this will fail on newer versions of linux if called from a 
	// different thread than the one which attached to process
	errno = 0;
	const long v = ptrace(PT_READ_D, pid(), (char*)address, 0);
	SET_OK(ok, v);
	return v;
}

//------------------------------------------------------------------------------
// Name: writeData(edb::address_t address, long value)
// Desc: 
//------------------------------------------------------------------------------
bool DebuggerCore::writeData(edb::address_t address, long value) {
	return ptrace(PT_WRITE_D, pid(), (char*)address, value) != -1;
}

//------------------------------------------------------------------------------
// Name: attach(edb::pid_t pid)
// Desc: 
//------------------------------------------------------------------------------
bool DebuggerCore::attach(edb::pid_t pid) {
	detach();
	
	const long ret = ptrace(PT_ATTACH, pid, 0, 0);
	if(ret == 0) {
		m_PID			= pid;
		m_ActiveThread	= pid;
		m_Threads.clear();
		m_Threads.insert(pid, ThreadInfo());
		
		// TODO: attach to all of the threads
	}

	return ret == 0;
}

//------------------------------------------------------------------------------
// Name: detach()
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::detach() {
	if(attached()) {
		clearBreakpoints();
		for(threadmap_t::const_iterator it = m_Threads.begin(); it != m_Threads.end(); ++it) {
			ptrace(PT_DETACH, it.key(), 0, 0);
		}
		
		m_PID = 0;
		m_Threads.clear();
	}
}

//------------------------------------------------------------------------------
// Name: kill()
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::kill() {
	if(attached()) {
		clearBreakpoints();
		ptrace(PT_KILL, pid(), 0, 0);
		native_waitpid(pid(), 0, WAIT_ANY);
		m_PID = 0;
		m_Threads.clear();
	}
}

//------------------------------------------------------------------------------
// Name: pause()
// Desc: stops *all* threads of a process
//------------------------------------------------------------------------------
void DebuggerCore::pause() {
	if(attached()) {
		for(threadmap_t::const_iterator it = m_Threads.begin(); it != m_Threads.end(); ++it) {
			::kill(it.key(), SIGSTOP);
		}
	}
}

//------------------------------------------------------------------------------
// Name: resume(EVENT_STATUS status)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::resume(EVENT_STATUS status) {
	// TOOD: assert that we are paused
	
	if(attached()) {
		int code = 0;
		const edb::tid_t tid = activeThread();
		if(status == DEBUG_EXCEPTION_NOT_HANDLED) {
			const int s = m_Threads[tid].status;
			
			if(WIFSIGNALED(s)) {
				code = WTERMSIG(s);
			} else if(WIFSTOPPED(s)) {
				code = WSTOPSIG(s);
			}
		}
		ptrace(PT_CONTINUE, tid, 0, code);
	}
}

//------------------------------------------------------------------------------
// Name: step(EVENT_STATUS status)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::step(EVENT_STATUS status) {
	// TOOD: assert that we are paused
	
	if(attached()) {
		int code = 0;
		const edb::tid_t tid = activeThread();
		if(status == DEBUG_EXCEPTION_NOT_HANDLED) {
			const int s = m_Threads[tid].status;
			
			if(WIFSIGNALED(s)) {
				code = WTERMSIG(s);
			} else if(WIFSTOPPED(s)) {
				code = WSTOPSIG(s);
			}
		}
		
		ptrace(PT_STEP, tid, 0, code);
	}
}

//------------------------------------------------------------------------------
// Name: getState(State &state)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::getState(State &state) {
	// TOOD: assert that we are paused
	
	if(attached()) {
		struct reg regs;
		struct fpreg fpregs;
	#if defined(EDB_X86)		
		if(ptrace(PT_GETREGS, activeThread(), (char*)&regs, 0) != -1) {
			state.eax = regs.r_eax;
			state.ebx = regs.r_ebx;
			state.ecx = regs.r_ecx;
			state.edx = regs.r_edx;
			state.esp = regs.r_esp;
			state.ebp = regs.r_ebp;
			state.edi = regs.r_edi;
			state.esi = regs.r_esi;
			state.eip = regs.r_eip;
			state.eflags = regs.r_eflags;
			state._cs = regs.r_cs;
			state._ds = regs.r_ds;
			state._es = regs.r_es;
			state._fs = regs.r_fs;
			state._gs = regs.r_gs;
			state._ss = regs.r_ss;
			state.orig_eax = 0;
			
#if 0
			struct user_desc desc;
			std::memset(&desc, 0, sizeof(desc));
			if(ptrace(PTRACE_GET_THREAD_AREA, activeThread(), (state._gs / LDT_ENTRY_SIZE), &desc) != -1) {
				state.gs_base = desc.base_addr;
			} else {
				state.gs_base = 0;
			}

			if(ptrace(PTRACE_GET_THREAD_AREA, activeThread(), (state._fs / LDT_ENTRY_SIZE), &desc) != -1) {
				state.fs_base = desc.base_addr;
			} else {
				state.fs_base = 0;
			}
#endif
		}
	#elif defined(EDB_X86_64)
		if(ptrace(PT_GETREGS, activeThread(), (char*)&regs, 0) != -1) {
			state.rax = regs.r_rax;
			state.rbx = regs.r_rbx;
			state.rcx = regs.r_rcx;
			state.rdx = regs.r_rdx;
			state.rsp = regs.r_rsp;
			state.rbp = regs.r_rbp;
			state.rdi = regs.r_rdi;
			state.rsi = regs.r_rsi;
			state.rip = regs.r_rip;
			state.r8 = regs.r_r8;
			state.r9 = regs.r_r9;
			state.r10 = regs.r_r10;
			state.r11 = regs.r_r11;
			state.r12 = regs.r_r12;
			state.r13 = regs.r_r13;
			state.r14 = regs.r_r14;
			state.r15 = regs.r_r15;
			state.rflags = regs.r_eflags;
			state.cs = regs.r_cs;
			state.ds = regs.r_ds;
			state.es = regs.r_es;
			state.fs = regs.r_fs;
			state.gs = regs.r_gs;
			state.ss = regs.r_ss;
			state.orig_rax = 0;
#if 0
			state.fs_base = regs.fs_base;
			state.gs_base = regs.gs_base;
#endif
		}
#endif

		if(ptrace(PT_GETFPREGS, activeThread(), (char*)&fpregs, 0) != -1) {
			State::i387Register *const p = reinterpret_cast<State::i387Register *>(fpregs.__data);
			qCopy(&p[0], &p[8], state.st);
		}
		
#if 0
		state.dr[0] = ptrace(PTRACE_PEEKUSER, activeThread(), offsetof(user, u_debugreg[0]), 0);
		state.dr[1] = ptrace(PTRACE_PEEKUSER, activeThread(), offsetof(user, u_debugreg[1]), 0);
		state.dr[2] = ptrace(PTRACE_PEEKUSER, activeThread(), offsetof(user, u_debugreg[2]), 0);
		state.dr[3] = ptrace(PTRACE_PEEKUSER, activeThread(), offsetof(user, u_debugreg[3]), 0);
		state.dr[4] = 0;
		state.dr[5] = 0;
		state.dr[6] = ptrace(PTRACE_PEEKUSER, activeThread(), offsetof(user, u_debugreg[6]), 0);
		state.dr[7] = ptrace(PTRACE_PEEKUSER, activeThread(), offsetof(user, u_debugreg[7]), 0);
#endif

	} else {
		state.clear();
	}
}

//------------------------------------------------------------------------------
// Name: setState(const State &state)
// Desc: 
//------------------------------------------------------------------------------
void DebuggerCore::setState(const State &state) {
	
	// TOOD: assert that we are paused
	
	if(attached()) {
		struct reg regs;
#if defined(EDB_X86)
		regs.r_eax = state.eax;
		regs.r_ebx = state.ebx;
		regs.r_ecx = state.ecx;
		regs.r_edx = state.edx;
		regs.r_esp = state.esp;
		regs.r_ebp = state.ebp;
		regs.r_edi = state.edi;
		regs.r_esi = state.esi;
		regs.r_eip = state.eip;
		regs.r_eflags = state.eflags;
		regs.r_cs = state._cs;
		regs.r_ds = state._ds;
		regs.r_es = state._es;
		regs.r_fs = state._fs;
		regs.r_gs = state._gs;
		regs.r_ss = state._ss;
#elif defined(EDB_X86_64)
		regs.r_rax = state.rax;
		regs.r_rbx = state.rbx;
		regs.r_rcx = state.rcx;
		regs.r_rdx = state.rdx;
		regs.r_rsp = state.rsp;
		regs.r_rbp = state.rbp;
		regs.r_rdi = state.rdi;
		regs.r_rsi = state.rsi;
		regs.r_r8 = state.r8;
		regs.r_r9 = state.r9;
		regs.r_r10 = state.r10;
		regs.r_r11 = state.r11;
		regs.r_r12 = state.r12;
		regs.r_r13 = state.r13;
		regs.r_r14 = state.r14;
		regs.r_r15 = state.r15;
		regs.r_rip = state.rip;
		regs.r_eflags = state.rflags;
		regs.r_cs = state.cs;
		regs.r_ds = state.ds;
		regs.r_es = state.es;
		regs.r_fs = state.fs;
		regs.r_gs = state.gs;
		regs.r_ss = state.ss;
#endif
		ptrace(PT_SETREGS, activeThread(), (char*)&regs, 0);

#if 0
		ptrace(PTRACE_POKEUSER, activeThread(), offsetof(user, u_debugreg[0]), state.dr[0]);
		ptrace(PTRACE_POKEUSER, activeThread(), offsetof(user, u_debugreg[1]), state.dr[1]);
		ptrace(PTRACE_POKEUSER, activeThread(), offsetof(user, u_debugreg[2]), state.dr[2]);
		ptrace(PTRACE_POKEUSER, activeThread(), offsetof(user, u_debugreg[3]), state.dr[3]);
//		ptrace(PTRACE_POKEUSER, activeThread(), offsetof(user, u_debugreg[4]), state.dr[4]);
//		ptrace(PTRACE_POKEUSER, activeThread(), offsetof(user, u_debugreg[5]), state.dr[5]);
		ptrace(PTRACE_POKEUSER, activeThread(), offsetof(user, u_debugreg[6]), state.dr[6]);
		ptrace(PTRACE_POKEUSER, activeThread(), offsetof(user, u_debugreg[7]), state.dr[7]);
#endif
	}
}

//------------------------------------------------------------------------------
// 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;
	
	switch(pid = fork()) {
	case 0:
		// we are in the child now...
	
		// set ourselves (the child proc) up to be traced
		ptrace(PT_TRACE_ME, 0, 0, 0);
		
		// redirect it's I/O
		if(!tty.isEmpty()) {
			FILE *const std_out	= freopen(qPrintable(tty), "r+b", stdout);
			FILE *const std_in	= freopen(qPrintable(tty), "r+b", stdin);
			FILE *const std_err	= freopen(qPrintable(tty), "r+b", stderr);
			
			Q_UNUSED(std_out);
			Q_UNUSED(std_in);
			Q_UNUSED(std_err);
		}
		
		// do the actual exec
		executeProcess(path, cwd, args);
		
		// we should never get here!
		abort();
		break;
	case -1:
		// error!
		m_PID = 0;
		return false;
	default:
		// parent
		do {
			m_Threads.clear();
			
			int status;
			if(native_waitpid(pid, &status, WAIT_ANY) == -1) {
				return false;
			}
			
			// the very first event should be a STOP of type SIGTRAP
			if(!WIFSTOPPED(status) || WSTOPSIG(status) != SIGTRAP) {
				detach();
				return false;
			}
			
			// setup the first event data for the primary thread
			m_Threads.insert(pid, ThreadInfo());
			m_PID					= pid;
			m_ActiveThread			= pid;
			m_Threads[pid].status	= status;
			return true;
		} while(0);
		break;
	}
}

void DebuggerCore::setActiveThread(edb::tid_t tid) {
	Q_ASSERT(m_Threads.contains(tid));
	m_ActiveThread = tid;

}

Q_EXPORT_PLUGIN2(DebuggerCore, DebuggerCore)
