/*<<<***************************************************************************
The MIT License (MIT)

Copyright(C) 2013 - 2015 Marc Mirti Mancinelli, Christophe Lardau and Philippe Pamart (xdcube.org)

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
////////////////////////////////////////////////////////////////////////////////
#Title: xbODbase
#Project: xdcBase
////////////////////////////////////////////////////////////////////////////////
#Author: Marc MIRTI MANCINELLI
#History:
<11/09/2013: creation.
12/02/2014: this notice inserted.
***************************************************************************>>>*/
#include "stdafx.h"

#ifdef xbOS_MSWIN
#include "xbODbase.h"
#include "../../xbConfig.h"
#include "../../xbDnItf.h"

volatile long g_xbDebuggerPresentCtx = 0;
bool xbIsDebuggerPresent()
{
	if (g_xbDebuggerPresentCtx != 0)
	{
		return g_xbDebuggerPresentCtx > 0 ?true:false;
	}
#if defined(_DEBUG) || defined(_RELDBG)
	HINSTANCE hinst = xbLoadLibrary("kernel32.dll");
	if (!hinst)
	{
		g_xbDebuggerPresentCtx = -1;
		xbRelOutputLow("xbIsDebuggerPresent() : LoadLibrary('kernel32.dll') failed !");
		return false;
	}

	try
	{
		typedef BOOL (__stdcall * IsDebuggerPresentProc)( ); 
		
		IsDebuggerPresentProc proc = (IsDebuggerPresentProc)GetProcAddress(hinst,"IsDebuggerPresent");
		if (proc)
		{
			g_xbDebuggerPresentCtx = ((*proc)())?1:-1;
			xbRelOutputLowFmt("Execution context : %s",(g_xbDebuggerPresentCtx>0?"Running under debugger":"Running without debugger"));
		}
		else
		{
			g_xbDebuggerPresentCtx = -1;
			xbRelOutputLow("xbIsDebuggerPresent() : No entry in 'kernel32.dll' for IsDebuggerPresent (doesn't exist on 95 & 98)");
		}
	}
	catch(...)
	{
		xbRelOutputLow("xbIsDebuggerPresent() : Exception raised !");
		g_xbDebuggerPresentCtx = -1;
	}
	xbFreeLibrary(hinst);
	return g_xbDebuggerPresentCtx > 0 ?true:false;
#endif
	g_xbDebuggerPresentCtx = -1;
	return false;
}

void xbDebugBreak(bool bForce)
{
	::xbBeep(xbMBicon_Stop);
	if (!bForce && !xbIsDebuggerPresent())
		return;

	::DebugBreak();
}

void xbBeep(xbMBiconType beepType)
{
	::MessageBeep((UINT)beepType);
}

bool	g_xbPerfCounter = false; 
bool	g_xbGetTimeFirst = true; 
uint64	g_xbPerfFreq = 0;
int	g_xbPerfProcBug = 0;
uint64 xbGetTimeSpentInMicroSec()
{
	if (g_xbPerfCounter)
		return xbGetTimeInMicroSec();

	FILETIME t1,t2,kt,ut;
	if (!GetThreadTimes( GetCurrentThread(),&t1,&t2,&kt,&ut)) 
	{
		if (!g_xbGetTimeFirst) 
			return 0xFFFFFFFFFFFFFFFF;
		g_xbGetTimeFirst = false;
		if (g_xbPerfFreq == 0 && !QueryPerformanceFrequency((LARGE_INTEGER*)&g_xbPerfFreq)) 
			return 0xFFFFFFFFFFFFFFFF;
		g_xbPerfCounter = g_xbPerfFreq > 0;
		if (!g_xbPerfCounter) 
			return 0xFFFFFFFFFFFFFFFF;

		return xbGetTimeInMicroSec();
	}
	g_xbGetTimeFirst = false;
	return ((uint64)kt.dwLowDateTime+ut.dwLowDateTime + (((uint64)kt.dwHighDateTime+ut.dwHighDateTime)<<32))/10;
}

uint64 xbGetTimeInMicroSec()
{
	DWORD_PTR oldMask;
	if (g_xbPerfFreq == 0)
	{
		if (!QueryPerformanceFrequency((LARGE_INTEGER*)&g_xbPerfFreq)) 
			return 0xFFFFFFFFFFFFFFFF;
		if (g_xbPerfFreq == 0) 
			return 0xFFFFFFFFFFFFFFFF;
	}
	if (!g_xbPerfProcBug)
	{
		g_xbPerfProcBug = g_xbCfgEngine.GetSettingBoolToNum("PerfCounterBug");
	}
	if (g_xbPerfProcBug==1)
	{
		oldMask = ::SetThreadAffinityMask(::GetCurrentThread(),0x1);
	}
	int64 nCnt = 0;
	BOOL ret = QueryPerformanceCounter((LARGE_INTEGER*)&nCnt);

	if (g_xbPerfProcBug==1)
		::SetThreadAffinityMask(::GetCurrentThread(),oldMask);

	if (!ret)
		return 0xFFFFFFFFFFFFFFFF;

	return uint64(int64(double(nCnt) / int64(g_xbPerfFreq) * 1000000.0));
}

void xbFreeLibrary(HMODULE hMod)
{
	::FreeLibrary(hMod);
}
xbEXPORT HMODULE xbLoadLibrary(LPCSTR path)
{
	return ::LoadLibrary(path);
}
xbEXPORT HMODULE xbLoadLibraryAsPlug(LPCSTR path)
{
	//::AfxLoadLibraryEx(modulepath,NULL,LOAD_IGNORE_CODE_AUTHZ_LEVEL|LOAD_WITH_ALTERED_SEARCH_PATH);
	return ::LoadLibrary(path);
}
xbEXPORT HMODULE xbLoadLibraryAsData(LPCSTR path)
{
	return ::LoadLibraryEx(path,NULL,LOAD_LIBRARY_AS_DATAFILE);
}

xbEXPORT xbString xbPathSlash(const xbString &path) //os dep: Aslash for win, slash for linux
{
	return _xbUrlAslash(path);
}
#endif
