
#include "Debugger.h"
#include "DebuggerCoreInterface.h"
#include <QTextStream>
#include <QFile>
#include "Core.h"
#include "MemoryRegions.h"

//------------------------------------------------------------------------------
// Name: loadedLibraries()
// Desc: 
//------------------------------------------------------------------------------
QStringList edb::v1::loadedLibraries() {
	QStringList ret;
	
	memoryRegions().sync();

	const QVector<MemRegion> r = memoryRegions().regions();
	foreach(const MemRegion &region, r) {
	#ifdef Q_OS_LINUX
		// modules seem to have full paths
		if(region.name.startsWith("/")) {
			if(!ret.contains(region.name)) {
				ret << region.name;
			}
		}
	#else
		#error "Unsupported Platform"
	#endif
	}
	
	return ret;
}

//------------------------------------------------------------------------------
// Name: getProcessExecutable()
// Desc: 
//------------------------------------------------------------------------------
QString edb::v1::getProcessExecutable() {

	// TODO: make this work after the process has exited!
	//		 or work around the fact that it doesn't work
	//		 if the process has exited.

	QString ret;
	
	if(debuggerBase != 0) {
		// TODO: assert attached!
		const edb::pid_t pid = debuggerBase->pid();
	#ifdef Q_OS_LINUX
		ret = edb::core::symlinkTarget(QString("/proc/%1/exe").arg(pid));
	#else
		#error "Unsupported Platform"
	#endif
	}
	
	return ret;
}

//------------------------------------------------------------------------------
// Name: getProcessCurrentWorkingDirectory()
// Desc: 
//------------------------------------------------------------------------------
QString edb::v1::getProcessCurrentWorkingDirectory() {
	QString ret;
	if(debuggerBase != 0) {
		// TODO: assert attached!
		const edb::pid_t pid = debuggerBase->pid();
	#ifdef Q_OS_LINUX
		ret = edb::core::symlinkTarget(QString("/proc/%1/cwd").arg(pid));
	#else
		#error "Unsupported Platform"
	#endif
	}
	return ret;
}

//------------------------------------------------------------------------------
// Name: getProcessArguments()
// Desc: 
//------------------------------------------------------------------------------
QStringList edb::v1::getProcessArguments() {
	QStringList ret;
	if(debuggerBase != 0) {
	
		// TODO: assert attached!
	
		const edb::pid_t pid = debuggerBase->pid();
	#ifdef Q_OS_LINUX
		const QString cmdlineFile(QString("/proc/%1/cmdline").arg(pid));
		QFile file(cmdlineFile);

		if(file.open(QIODevice::ReadOnly | QIODevice::Text)) {
			QTextStream in(&file);

			QString s;
			QChar ch;

			while(in.status() == QTextStream::Ok) {
				in >> ch;
				if(ch == '\0') {
					if(!s.isEmpty()) {
						ret << s;
					}
					s.clear();
				} else {
					s += ch;
				}
			}

			if(!s.isEmpty()) {
				ret << s;
			}
		}
	#else
		#error "Unsupported Platform"
	#endif
	}
	return ret;
}
