#include "stdafx.h"
#include "DbgHelper.h"

#ifdef WINDOWS

static bool init(HANDLE process) {
	SymSetOptions(SYMOPT_DEFERRED_LOADS | SYMOPT_LOAD_LINES);
	if (SymInitialize(process, NULL, TRUE))
		return true;

	DWORD error = GetLastError();
	WARNING(L"Failed to initialize the DbgHelp library. This usually means that it was initialized more than once."
			L"\nError code: " << error);
	return false;

	// SymRefreshModuleList(process);
}

static HANDLE currentProcessHandle() {
	HANDLE currProc = GetCurrentProcess();
	HANDLE real = INVALID_HANDLE_VALUE;
	BOOL ok = DuplicateHandle(currProc, currProc, currProc, &real, 0, FALSE, DUPLICATE_SAME_ACCESS);
	return currProc;
	if (ok) {
		return real;
	} else {
		// Not ideal, but works. Some part of the doc (Symbol Handler Initialization) states that it
		// *is* fine to pass GetCurrentProcess(). Other parts of the doc says to not use
		// GetCurrentProcess(), at least if using fInvadeProcess.
		return currProc;
	}
}

DbgHelp::DbgHelp() : process(currentProcessHandle()), initialized(init(process)) {
	// Check if we managed to initialize the debug help library.
	if (!initialized)
		CloseHandle(process);
}

DbgHelp::~DbgHelp() {
	if (initialized) {
		SymCleanup(process);
	}
	CloseHandle(process);
}


#endif
