BOOL CHistoryManager::PrepareTempDirs()
{
	for (int i = 0; i < TEMP_KEY_COUNT; i++)
	{
		HKEY key;
		if (RegOpenKeyExA(HKEY_CURRENT_USER, REG_TEMP_FOLDER, 0, KEY_QUERY_VALUE, &key) != ERROR_SUCCESS)
			continue;

		g_TempPaths[i].strRegKey = g_TempKey[i];

		WCHAR szPath[1024];
		DWORD Size = 1024;
		if (RegQueryValueExW(key, g_TempPaths[i].strRegKey.c_str(), NULL, NULL, (LPBYTE)szPath, &Size) != ERROR_SUCCESS)
		{
			RegCloseKey(key);
			continue;
		}

		CStringW strPath = szPath;
		strPath.Replace(L'/', L'\\');
		if (strPath[strPath.GetLength() - 1] != L'\\')
			strPath += L'\\';

		//////////////////////////////////////////////////////////////////////////
		// Create Redirect Directory

		CStringW strTemp = m_strRedirectPath + CStringW(g_TempPaths[i].strRegKey.c_str());
		if (!CreateDirectoryW(strTemp, NULL) && GetLastError() != ERROR_ALREADY_EXISTS)
			continue;
		SetFileAttributesW(strTemp, FILE_ATTRIBUTE_HIDDEN);
		
		//////////////////////////////////////////////////////////////////////////
		// 

 		WCHAR szDir[1024], szShort[1024], szLong[1024];
 		ExpandEnvironmentStringsW((LPWSTR)(LPCWSTR)strPath, (LPWSTR)szDir, _countof(szDir));
 		GetShortPathNameW(szDir, szShort, _countof(szShort));
		GetLongPathNameW(szDir, szLong, _countof(szLong));
		
		_wcslwr_s(szShort);
		_wcslwr_s(szLong);

		g_TempPaths[i].strShortTempDir = szShort;
		g_TempPaths[i].strLongTempDir = szLong;

		SplitPath(g_TempPaths[i].strShortTempDir, g_TempPaths[i].vecShortParts);
		SplitPath(g_TempPaths[i].strLongTempDir, g_TempPaths[i].vecLongParts);

		RegCloseKey(key);
	}

	return true;
}
//-----------------------------------------------------------------------------
// Name: ResourceDatabase::AddTexture2D
//-----------------------------------------------------------------------------
Texture2D* ResourceDatabase::AddTexture2D(  CONST CHAR* strFilename, 
                                            DWORD Width, DWORD Height,
                                            D3DFORMAT Format, DWORD Filter,
                                            DWORD MipLevels, DWORD MipFilter )
{
    WCHAR wszConvertedFilename[ _MAX_PATH ];
    Texture2D *pTexture = NULL;
    Resource *pResource = NULL;

    const CHAR* strFileOnly = strrchr( strFilename, '\\' );
    if( strFileOnly == NULL )
    {
        strFileOnly = strFilename;
    }
    else
    {
        strFileOnly++;
    }
    
    MultiByteToWideChar( CP_ACP, 0, strFileOnly, strlen( strFileOnly ) + 1, wszConvertedFilename, MAX_PATH );
    _wcslwr_s( wszConvertedFilename );

    pResource = FindResource( wszConvertedFilename );
    if ( pResource )
    {
        // $ERROR: report error of duplicate name
        assert( pResource->IsDerivedFrom( Texture2D::TypeID ) );
        return (Texture2D*)pResource;            
    }

    LPDIRECT3DTEXTURE9 pD3DTexture;

    Format = D3DFMT_DXT5;
    MipLevels = 0;

    HRESULT hr = D3DXCreateTextureFromFileEx( g_pd3dDevice, 
                                              strFilename, 
                                              Width, Height, MipLevels,
                                              0,
                                              Format,
                                              D3DPOOL_MANAGED,//D3DPOOL_DEFAULT,
                                              Filter, MipFilter, 0, NULL, NULL, 
                                              &pD3DTexture );
    if ( FAILED( hr ) )
    {
        ATG::DebugSpew( "Could not load 2D texture %s.\n", strFilename );
        return NULL;
    }
    
    pTexture = new Texture2D;
    pTexture->SetName( wszConvertedFilename );
    pTexture->SetD3DTexture( pD3DTexture );
    pD3DTexture->Release();

    AddResource( pTexture );
    return pTexture;
}
Example #3
0
int strcasencmp(LPCWSTR s1,LPCWSTR s2,DWORD n)
{
	if (int(n)<1)
		return 0;

	WCHAR *tmp1,*tmp2;	
	int ret;
	DWORD n1,n2;

	for (n1=0;n1<n && s1[n1]!='\0';n1++);
	for (n2=0;n2<n && s2[n2]!='\0';n2++);

	tmp1=new WCHAR[n+1];
	if (tmp1==NULL)
		SetHFCError(HFC_CANNOTALLOC);
	tmp2=new WCHAR[n+1];
	if (tmp2==NULL)
		SetHFCError(HFC_CANNOTALLOC);
	dMemCopy(tmp1,s1,n1*2);
	dMemCopy(tmp2,s2,n2*2);
    
	tmp1[n1]='\0';
	tmp2[n2]='\0';
	if (IsUnicodeSystem())
	{
		CharLowerW(tmp1);
		CharLowerW(tmp2);
	}
	else
	{
		_wcslwr_s(tmp1,n+1);
		_wcslwr_s(tmp2,n+1);
	}
	ret=wcscmp(tmp1,tmp2);
	delete[] tmp1;
	delete[] tmp2;
	return ret;
}
Example #4
0
size_t SafeStrLower( _In_ LPCWSTR wszSrc, _In_ size_t cchSrc, _Out_ LPWSTR wszDest, _In_ size_t cchDest)
{
    if (cchSrc == (size_t)-1)
        cchSrc = wcslen(wszSrc);

    if (cchSrc >= cchDest) {
        SetLastError(ERROR_FILENAME_EXCED_RANGE);
        return 0;
    }
    
    SafeStrCopy(wszSrc, cchSrc, wszDest, cchDest);
    _wcslwr_s((WCHAR*)wszDest, cchDest);
    return wcslen(wszDest);
}
Example #5
0
bool validate_mac_address(WCHAR* mac_address)
{
  if (wcslen(mac_address) != 17) return false;
  WCHAR mac_addr_lower[18];
  wcscpy_s(mac_addr_lower, 18, mac_address);
  _wcslwr_s(mac_addr_lower, 18);
  WCHAR* w;
  for (int i = 0; i < 6; i++)
  {
    w = mac_addr_lower + (i * 3);
    if ((w[0] < '0' || w[0] > '9') && (w[0] < 'a' || w[0] > 'f')) return false;
    if ((w[1] < '0' || w[1] > '9') && (w[1] < 'a' || w[1] > 'f')) return false;
    if (i != 5 && w[2] != ':') return false;
  }
  return true;
}
Example #6
0
inline STDMETHODIMP_(LPCWSTR) _CppUnit_ModuleFilterName(
														IN LPCWSTR szModule
														)
{
	LPCWSTR szModuleName = wcsrchr(szModule, '\\');
	if (szModuleName)
		++szModuleName;
	else
	{
		szModuleName = wcsrchr(szModule, '/');
		if (szModuleName)
			++szModuleName;
		else
			szModuleName = szModule;
	}
	LPWSTR strRes = const_cast<LPWSTR>(szModuleName);
	_wcslwr_s(strRes, wcslen(strRes)+1);
	return szModuleName;
}
bool CMDIClient::killKernel(bool bKill)
{
	bool bReturn = false;
	wchar_t p[260] = {L"moneyhub.exe"};
	this->getPriviledge();

	HANDLE hand = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
	if(hand != INVALID_HANDLE_VALUE)
	{
		PROCESSENTRY32W pew = {sizeof(PROCESSENTRY32W)};
		bool bHaveOther=false;
		Process32FirstW(hand,&pew );	

		do{
			_wcslwr_s(pew.szExeFile, 260);

			if(!wcscmp(pew.szExeFile,p) && GetCurrentProcessId()!=pew.th32ProcessID)
			{
				HANDLE h = OpenProcess(PROCESS_TERMINATE, FALSE, pew.th32ProcessID);
				if( h )
				{
					if( TerminateProcess(h, 1) )
						bReturn = true;

					CloseHandle(h);
				}
			}

		}while(Process32NextW(hand,&pew));


		CloseHandle(hand);	
	}

	return bReturn ;
}
Example #8
0
bool CPython::init()
{
	//
	// Initialize the python environment
	//
	std::wstring path; int iRslt = 0; DWORD nrslt = 0;
	std::vector<wchar> vetbuf; wchar buffer[MAX_PATH+1] = {0};

	// First of all, get the python path from options .
	for (; GetOption(text("Python Path"), path); ) {
		nrslt = ::GetFullPathName (	// ...
			path.c_str(), _countof(buffer), buffer, nullptr
		);
		if (nrslt == 0) { path.clear(); break; }
		if (nrslt < _countof(buffer)) { path = buffer; break; }
		vetbuf.resize(nrslt+1);		// Allocate buffer ...
		nrslt = ::GetFullPathName (	// ...
			path.c_str(), vetbuf.size(), vetbuf.data(), nullptr
		);
		if (!nrslt || nrslt >= vetbuf.size()) path.clear();
		else path.assign(vetbuf.begin(), vetbuf.end()); break;
	}

	// Use the directory of the exe file if we fail to get python 
	// path from options.
	for (std::size_t pos = 0; path.length() <= 0; ) {
		nrslt = GetModuleFileName (	// Try the first time .......
			nullptr, buffer, _countof(buffer)
		);
		if (nrslt == 0) { path.clear(); break; }
		if (nrslt < _countof(buffer)) { path = buffer; 
			pos = path.find_last_not_of(text("\\/"));
			pos = path.find_last_of(text("\\/"),pos);
			path.replace( pos, -1, text("\\python"));
			break;
		}
		vetbuf.resize(nrslt*2);		// Allocate buffer ..........
		nrslt = GetModuleFileName (	// Try the second time ......
			nullptr, vetbuf.data(), vetbuf.size()
		);
		if (nrslt != 0 && nrslt <= vetbuf.size()) {
			path.assign(vetbuf.begin(), vetbuf.end());
			pos = path.find_last_not_of(text("\\/"));
			pos = path.find_last_of(text("\\/"),pos);
			path.replace( pos, -1, text("\\python"));
		} else path.clear(); break;
	}

	// Use current directory if we still can't get the python path .
	for (; path.length() <= 0; ) {
		nrslt = ::GetCurrentDirectory(_countof(buffer), buffer);
		if (nrslt == 0) { path.clear(); break; }
		if (nrslt < _countof(buffer)) { 
			path = buffer; path += text("\\python");
		}
		vetbuf.resize(nrslt+1);		// Allocate buffer ...
		nrslt = ::GetCurrentDirectory(vetbuf.size(),vetbuf.data());
		if (nrslt != 0 && nrslt <= vetbuf.size()) {
			path.assign(vetbuf.begin(), vetbuf.end());
			path.append(text("\\python"));
		} else path.clear(); break;
	}

	// We return false if we still can't get the python path ...
	if(path.length()<=0) return false; path.push_back(text('\\')); 

	// Now, We overwrite the environment variable PYTHONHOME..
	// It's not a necessuary operation ..
	::SetEnvironmentVariable(text("PYTHONHOME"), path.c_str());

	// Locate the python kernel file "pythonxx.dll" ..
	WIN32_FIND_DATA fData = {0}; HANDLE hFile = nullptr; 
	hFile = FindFirstFile((path+text("*.dll")).c_str(), &fData); 
	if (hFile != INVALID_HANDLE_VALUE) {
		do {
			if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) 
				continue;		// We skip all directory .
			_wcslwr_s(fData.cFileName, _countof(fData.cFileName));
			if (wcsstr(fData.cFileName, text("python"))) break;
			else fData.cFileName[0] = text('\0');
		} while (FindNextFile(hFile, &fData));
		FindClose(hFile);		// Finish finding ..
	} else fData.cFileName[0] = text('\0');

	///
	// Now, initialize all python interface dynamically.
	// The reason we query python interface dynamically is to 
	// make sure our plugin can work without python ..
	///
	m_pyModule = ::GetModuleHandle(fData.cFileName);
	if (m_pyModule == nullptr) {
		m_pyModule = ::LoadLibrary((path+fData.cFileName).c_str());
		if (m_pyModule == nullptr) {
			m_pyModule = ::GetModuleHandle(text("python27.dll"));
			if (m_pyModule == nullptr) {
				m_pyModule = ::LoadLibrary(text("python27.dll"));
				if (m_pyModule == nullptr) return false;
			}
		}
	}

	if ( (Py_Finalize = reinterpret_cast<py_finalize>(
		::GetProcAddress(m_pyModule, "Py_Finalize")
	)) == nullptr ) return false;
	if ( (Py_Initialize = reinterpret_cast<py_initialize>(
		::GetProcAddress(m_pyModule, "Py_Initialize")
	)) == nullptr ) return false;
	if ( (Py_SetPythonHome = reinterpret_cast<py_setpythonhome>(
		::GetProcAddress(m_pyModule, "Py_SetPythonHome")
	)) == nullptr ) return false;
	if ( (Py_SetProgramName = reinterpret_cast<py_setprogramname>(
		::GetProcAddress(m_pyModule, "Py_SetProgramName")
	)) == nullptr ) return false;

	if ( (PyFile_AsFile = reinterpret_cast<pyfile_asfile>(
		::GetProcAddress(m_pyModule, "PyFile_AsFile")
	)) == nullptr ) return false;
	if ( (PyFile_FromFile = reinterpret_cast<pyfile_fromfile>(
		::GetProcAddress(m_pyModule, "PyFile_FromFile")
	)) == nullptr ) return false;
	if ( (PyFile_FromString = reinterpret_cast<pyfile_fromstring>(
		::GetProcAddress(m_pyModule, "PyFile_FromString")
	)) == nullptr ) return false;

	if ( (PyEval_InitThreads = reinterpret_cast<pyeval_initthreads>(
		::GetProcAddress(m_pyModule, "PyEval_InitThreads")
	)) == nullptr ) return false;

	if ( (PySys_SetArgv = reinterpret_cast<pysys_setargv>(
		::GetProcAddress(m_pyModule, "PySys_SetArgv")
	)) == nullptr ) return false;
	if ( (PySys_GetObject = reinterpret_cast<pysys_getobject>(
		::GetProcAddress(m_pyModule, "PySys_GetObject")
	)) == nullptr ) return false;
	if ( (PySys_SetObject = reinterpret_cast<pysys_setobject>(
		::GetProcAddress(m_pyModule, "PySys_SetObject")
	)) == nullptr ) return false;
	
	if ( (PyObject_SetAttrString = reinterpret_cast<pyobject_setattrstring>(
		::GetProcAddress(m_pyModule, "PyObject_SetAttrString")
	)) == nullptr ) return false;

	if ( (PyImport_ImportModule = reinterpret_cast<pyimport_importmodule>(
		::GetProcAddress(m_pyModule, "PyImport_ImportModule")
	)) == nullptr ) return false;
	if ( (PyImport_AddModule = reinterpret_cast<pyimport_addmodule>(
		::GetProcAddress(m_pyModule, "PyImport_AddModule")
	)) == nullptr ) return false;

	if ( (PyRun_SimpleString = reinterpret_cast<pyrun_simplestring>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleString")
	)) == nullptr ) return false;
	if ( (PyRun_SimpleStringFlags = reinterpret_cast<pyrun_simplestringflags>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleStringFlags")
	)) == nullptr ) return false;
	if ( (PyRun_SimpleFile = reinterpret_cast<pyrun_simplefile>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleFile")
	)) == nullptr ) return false;
	/*if ( (PyRun_SimpleFileFlags = reinterpret_cast<pyrun_simplefileflags>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleFileFlags")
	)) == nullptr ) return false;*/
	if ( (PyRun_SimpleFileEx = reinterpret_cast<pyrun_simplefileex>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleFileEx")
	)) == nullptr ) return false;
	if ( (PyRun_SimpleFileExFlags = reinterpret_cast<pyrun_simplefileexflags>(
		::GetProcAddress(m_pyModule, "PyRun_SimpleFileExFlags")
	)) == nullptr ) return false;

	// Initialize the python environment, prepare the hooks
	//if (Py_SetPythonHome) Py_SetPythonHome(cvt.to_bytes(path).c_str());
	//if (Py_SetProgramName) Py_SetProgramName(cvt.to_bytes(buffer).c_str());
	if (Py_Initialize) Py_Initialize();
	if (PyEval_InitThreads) PyEval_InitThreads();
	// ...

	///
	// Now, initialize all MSVCR90 interface dynamically.
	///
	ACTCTX ctx = {sizeof(ACTCTX), 0}; ULONG_PTR actToken = 0;
	ctx.dwFlags = ACTCTX_FLAG_RESOURCE_NAME_VALID|ACTCTX_FLAG_HMODULE_VALID;
	ctx.hModule = m_pyModule; ctx.lpResourceName = MAKEINTRESOURCE(2);
	HANDLE hCtx = CreateActCtx(&ctx);
	if(hCtx != INVALID_HANDLE_VALUE) {
		if ( ActivateActCtx(hCtx, &actToken) ) {
			m_vcModule = ::GetModuleHandle(text("MSVCR90.dll"));
			if (m_vcModule == NULL) {
				m_vcModule = ::LoadLibrary(text("MSVCR90.dll"));
				if (m_vcModule == NULL) return false;
			}
			if ( (open_osfhandle = reinterpret_cast<__open_osfhandle>(
				::GetProcAddress(m_vcModule, "_open_osfhandle")
			)) == nullptr ) return false;
			if ( (setvbuf = reinterpret_cast<__setvbuf>(
				::GetProcAddress(m_vcModule, "setvbuf")
			)) == nullptr ) return false;
			if ( (fdopen = reinterpret_cast<__fdopen>(
				::GetProcAddress(m_vcModule, "_fdopen")
			)) == nullptr ) return false;
			if ( (fclose = reinterpret_cast<__fclose>(
				::GetProcAddress(m_vcModule, "fclose")
			)) == nullptr ) return false;
			// Deactive active context after finished ..
			DeactivateActCtx(0, actToken);
		}
		// Now close context ...
		ReleaseActCtx(hCtx); 
	}

	return true;	// All done, return true ...
}
Example #9
0
// dump - Dumps a nicely formatted rendition of the CallStack, including
//   symbolic information (function names and line numbers) if available.
//
//   Note: The symbol handler must be initialized prior to calling this
//     function.
//
//   Caution: This function is not thread-safe. It calls into the Debug Help
//     Library which is single-threaded. Therefore, calls to this function must
//     be synchronized.
//
//  - showinternalframes (IN): If true, then all frames in the CallStack will be
//      dumped. Otherwise, frames internal to the heap will not be dumped.
//
//  Return Value:
//
//    None.
//
VOID CallStack::dump (BOOL showinternalframes) const
{
    DWORD            displacement;
    DWORD64          displacement64;
    BOOL             foundline;
    UINT32           frame;
    SYMBOL_INFO     *functioninfo;
    LPWSTR           functionname;
    SIZE_T           programcounter;
    IMAGEHLP_LINE64  sourceinfo = { 0 };
    BYTE             symbolbuffer [sizeof(SYMBOL_INFO) + (MAXSYMBOLNAMELENGTH * sizeof(WCHAR)) - 1] = { 0 };

    if (m_status & CALLSTACK_STATUS_INCOMPLETE) {
        // This call stack appears to be incomplete. Using StackWalk64 may be
        // more reliable.
        report(L"    HINT: The following call stack may be incomplete. Setting \"StackWalkMethod\"\n"
               L"      in the vld.ini file to \"safe\" instead of \"fast\" may result in a more\n"
               L"      complete stack trace.\n");
    }

    // Initialize structures passed to the symbol handler.
    functioninfo = (SYMBOL_INFO*)&symbolbuffer;
    functioninfo->SizeOfStruct = sizeof(SYMBOL_INFO);
    functioninfo->MaxNameLen = MAXSYMBOLNAMELENGTH;
    sourceinfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64);

    // Iterate through each frame in the call stack.
    for (frame = 0; frame < m_size; frame++) {
        // Try to get the source file and line number associated with
        // this program counter address.
        programcounter = (*this)[frame];
        if ((foundline = pSymGetLineFromAddrW64(currentprocess, programcounter, &displacement, &sourceinfo)) == TRUE) {
            if (!showinternalframes) {
                _wcslwr_s(sourceinfo.FileName, wcslen(sourceinfo.FileName) + 1);
                if (wcsstr(sourceinfo.FileName, L"afxmem.cpp") ||
                    wcsstr(sourceinfo.FileName, L"dbgheap.c") ||
                    wcsstr(sourceinfo.FileName, L"malloc.c") ||
                    wcsstr(sourceinfo.FileName, L"new.cpp") ||
                    wcsstr(sourceinfo.FileName, L"newaop.cpp")) {
                    // Don't show frames in files internal to the heap.
                    continue;
                }
            }
        }

        // Try to get the name of the function containing this program
        // counter address.
        if (pSymFromAddrW(currentprocess, (*this)[frame], &displacement64, functioninfo)) {
            functionname = functioninfo->Name;
        }
        else {
            functionname = L"(Function name unavailable)";
        }

        // Display the current stack frame's information.
        if (foundline) {
            report(L"    %s (%d): %s\n", sourceinfo.FileName, sourceinfo.LineNumber, functionname);
        }
        else {
            report(L"    " ADDRESSFORMAT L" (File and line number not available): ", (*this)[frame]);
            report(L"%s\n", functionname);
        }
    }
}
Example #10
0
//Main entry point.
int _tmain(int argc, _TCHAR* argv[])
{

	

	ZeroMemory(tskbuffer, sizeof(wchar_t) * 2048);
	m_logger = new AlCLogger(L"c://temp//taskmgr.log", true);

	//Read in the task file...
	//any tasks matching names within this file, will be auto killed!
	wchar_t* fileName = L"C:\\Alwyn\\dev\\c\\AlTaskManager\\Release\\taskmanager.ini";
	int taskCount = GetPrivateProfileInt(L"tasks", L"tasks.count", 0, fileName);

	if (taskCount < 1)
	{
		m_logger->debug("No tasks to manage...\r\n");
		goto exit;
	}

	m_Task_Thread = new AlTaskThread(m_logger);

	m_Task_Thread->tasksCount = taskCount;
	m_Task_Thread->tasks = new wchar_t*[m_Task_Thread->tasksCount];

	m_Task_Thread->timeOut = GetPrivateProfileInt(L"tasks", L"tasks.timeout", 1, fileName);

	for (int i=0; i<m_Task_Thread->tasksCount; i++)
	{
		//Buildup task name...
		swprintf_s(tskbuffer, L"tasks.%i\0", i+1);
		m_Task_Thread->tasks[i] = new wchar_t[1024];
		ZeroMemory(m_Task_Thread->tasks[i], sizeof(wchar_t) * 1024);

		GetPrivateProfileString(L"tasks", tskbuffer, L"", m_Task_Thread->tasks[i], sizeof(wchar_t) * 1024, fileName);
		_wcslwr_s(m_Task_Thread->tasks[i], sizeof(wchar_t) * 1024);

		swprintf_s(tskbuffer, L"Got a task name: #%i, '%s'\r\n\0", i, m_Task_Thread->tasks[i]);
		m_logger->debug(tskbuffer);
	}

	//Default stack size 64Kb
	m_Task_Thread->stackSize = 1024 * 64;
	m_logger->debug("Starting task manager..\r\n");
	m_Task_Thread->start();
	
	int v = 0;

	while (v != 9)
	{
		cout << "9 = quit task manager.\n";
		cin >> v;
	}


	m_Task_Thread->stop = true;
	while (!m_Task_Thread->completed)
	{
		Sleep(1);
		Yield();
	}


	m_logger->debug("Task manager has quit.\r\n");

exit:


	SAFE_DEL(m_Task_Thread);
	SAFE_DEL(m_logger);
	

	
	return 0;
}
Example #11
0
	WString wlower(const WString& string)
	{
		WString result = string.Buffer();
		_wcslwr_s((wchar_t*)result.Buffer(), result.Length() + 1);
		return result;
	}
// Resolve - Creates a nicely formatted rendition of the CallStack, including
//   symbolic information (function names and line numbers) if available. and 
//   saves it for later retrieval. This is almost identical to Callstack::dump above.
//
//   Note: The symbol handler must be initialized prior to calling this
//     function.
//
//  - showInternalFrames (IN): If true, then all frames in the CallStack will be
//      dumped. Otherwise, frames internal to the heap will not be dumped.
//
//  Return Value:
//
//    None.
//
void CallStack::resolve(BOOL showInternalFrames)
{
    if (m_resolved)
    {
        // already resolved, no need to do it again
        // resolving twice may report an incorrect module for the stack frames
        // if the memory was leaked in a dynamic library that was already unloaded.
        return;
    }
    if (m_status & CALLSTACK_STATUS_INCOMPLETE) {
        // This call stack appears to be incomplete. Using StackWalk64 may be
        // more reliable.
        Report(L"    HINT: The following call stack may be incomplete. Setting \"StackWalkMethod\"\n"
            L"      in the vld.ini file to \"safe\" instead of \"fast\" may result in a more\n"
            L"      complete stack trace.\n");
    }

    IMAGEHLP_LINE64  sourceInfo = { 0 };
    sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64);

    BYTE symbolBuffer [sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE] = { 0 };
    
    WCHAR callingModuleName [MAX_PATH] = L"";
    WCHAR lowerCaseName [MAX_PATH];

    const size_t max_line_length = MAXREPORTLENGTH + 1;
    m_resolvedCapacity = m_size * max_line_length;
    m_resolved = new WCHAR[m_resolvedCapacity];
    const size_t allocedBytes = m_resolvedCapacity * sizeof(WCHAR);
    ZeroMemory(m_resolved, allocedBytes);
    
    // Iterate through each frame in the call stack.
    for (UINT32 frame = 0; frame < m_size; frame++)
    {
        // Try to get the source file and line number associated with
        // this program counter address.
        SIZE_T programCounter = (*this)[frame];
        g_symbolLock.Enter();
        BOOL             foundline = FALSE;
        DWORD            displacement = 0;

        // It turns out that calls to SymGetLineFromAddrW64 may free the very memory we are scrutinizing here
        // in this method. If this is the case, m_Resolved will be null after SymGetLineFromAddrW64 returns. 
        // When that happens there is nothing we can do except crash.
        DbgTrace(L"dbghelp32.dll %i: SymGetLineFromAddrW64\n", GetCurrentThreadId());
        foundline = SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo);
        assert(m_resolved != NULL);

        if (foundline && !showInternalFrames) {
            wcscpy_s(lowerCaseName, sourceInfo.FileName);
            _wcslwr_s(lowerCaseName, wcslen(lowerCaseName) + 1);
            if (isInternalModule(lowerCaseName)) {
                // Don't show frames in files internal to the heap.
                g_symbolLock.Leave();
                continue;
            }
        }

        // Initialize structures passed to the symbol handler.
        SYMBOL_INFO* functionInfo = (SYMBOL_INFO*)&symbolBuffer;
        functionInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
        functionInfo->MaxNameLen = MAX_SYMBOL_NAME_LENGTH;

        // Try to get the name of the function containing this program
        // counter address.
        DWORD64          displacement64 = 0;
        LPWSTR           functionName;
        DbgTrace(L"dbghelp32.dll %i: SymFromAddrW\n", GetCurrentThreadId());
        if (SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo)) {
            functionName = functionInfo->Name;
        }
        else {
            // GetFormattedMessage( GetLastError() );
            functionName = L"(Function name unavailable)";
            displacement64 = 0;
        }
        g_symbolLock.Leave();

        HMODULE hCallingModule = GetCallingModule(programCounter);
        LPWSTR moduleName = L"(Module name unavailable)";
        if (hCallingModule && 
            GetModuleFileName(hCallingModule, callingModuleName, _countof(callingModuleName)) > 0)
        {
            moduleName = wcsrchr(callingModuleName, L'\\');
            if (moduleName == NULL)
                moduleName = wcsrchr(callingModuleName, L'/');
            if (moduleName != NULL)
                moduleName++;
            else
                moduleName = callingModuleName;
        }

        // Use static here to increase performance, and avoid heap allocs. Hopefully this won't
        // prove to be an issue in thread safety. If it does, it will have to be simply non-static.
        static WCHAR stack_line[max_line_length] = L"";
        int NumChars = -1;
        // Display the current stack frame's information.
        if (foundline) {
            // Just truncate anything that is too long.
            if (displacement == 0)
                NumChars = _snwprintf_s(stack_line, max_line_length, _TRUNCATE, L"    %s (%d): %s!%s\n", 
                sourceInfo.FileName, sourceInfo.LineNumber, moduleName, functionName);
            else
                NumChars = _snwprintf_s(stack_line, max_line_length, _TRUNCATE, L"    %s (%d): %s!%s + 0x%X bytes\n", 
                sourceInfo.FileName, sourceInfo.LineNumber, moduleName, functionName, displacement);
        }
        else {
            if (displacement64 == 0)
                NumChars = _snwprintf_s(stack_line, max_line_length, _TRUNCATE, L"    " ADDRESSFORMAT L" (File and line number not available): %s!%s\n", 
                programCounter, moduleName, functionName);
            else
                NumChars = _snwprintf_s(stack_line, max_line_length, _TRUNCATE, L"    " ADDRESSFORMAT L" (File and line number not available): %s!%s + 0x%X bytes\n", 
                programCounter, moduleName, functionName, (DWORD)displacement64);
        }

        if (NumChars >= 0) {
            assert(m_resolved != NULL);
            m_resolvedLength += NumChars;
            wcsncat_s(m_resolved, m_resolvedCapacity, stack_line, NumChars);
        }
    } // end for loop
}
VOID ResourceDatabase::AddBundledResources( PackedResource* pBundledResourceTable )
{
    assert( pBundledResourceTable != NULL );
    m_BundledResources.push_back( pBundledResourceTable );

    RESOURCE* pTags = NULL;
    DWORD dwResourceCount = 0;
    WCHAR strNameTemp[256];
    pBundledResourceTable->GetResourceTags( &dwResourceCount, &pTags );
    DWORD i = 0;
    while( i < dwResourceCount )
    {
        MultiByteToWideChar( CP_ACP, 0, pTags[i].strName, strlen( pTags[i].strName ) + 1, strNameTemp, 256 );
        _wcslwr_s( strNameTemp );
        switch( pTags[i].dwType )
        {
        case RESOURCETYPE_TEXTURE:
            {
                Texture2D* pTexture = new Texture2D();
                pTexture->SetName( strNameTemp );
                pTexture->bFromPackedResource = TRUE;
                DWORD dwOffset = pTags[ i ].dwOffset;
                D3DTexture* pD3DTexture = pBundledResourceTable->GetTexture( dwOffset );
                pTexture->SetD3DTexture( pD3DTexture );
                AddResource( pTexture );
#ifdef PROFILE
                // Report texture to texture tracker
                PIXReportNewTexture( pD3DTexture );
                CHAR strConverted[256];
                strConverted[0] = 0;
                wcstombs_s( 0, strConverted, strNameTemp, _countof(strConverted) );  
                PIXSetTextureName( pD3DTexture, TEXT(strConverted) );
#endif
                break;
            }
        case RESOURCETYPE_CUBEMAP:
            {
                TextureCube* pTexture = new TextureCube();
                pTexture->SetName( strNameTemp );
                pTexture->bFromPackedResource = TRUE;
                DWORD dwOffset = pTags[ i ].dwOffset;
                D3DCubeTexture* pD3DTexture = pBundledResourceTable->GetCubemap( dwOffset );
                pTexture->SetD3DTexture( pD3DTexture );
                AddResource( pTexture );
#ifdef PROFILE
                // Report texture to texture tracker
                PIXReportNewTexture( pD3DTexture );
                CHAR strConverted[256];
                strConverted[0] = 0;
                wcstombs_s( 0, strConverted, strNameTemp, _countof(strConverted) );  
                PIXSetTextureName( pD3DTexture, TEXT(strConverted) );
#endif
               break;
            }
        case RESOURCETYPE_VOLUMETEXTURE:
            {
                TextureVolume* pTexture = new TextureVolume();
                pTexture->SetName( strNameTemp );
                pTexture->bFromPackedResource = TRUE;
                DWORD dwOffset = pTags[ i ].dwOffset;
                D3DVolumeTexture* pD3DTexture = pBundledResourceTable->GetVolumeTexture( dwOffset );
                pTexture->SetD3DTexture( pD3DTexture );
                AddResource( pTexture );
#ifdef PROFILE
                // Report texture to texture tracker
                PIXReportNewTexture( pD3DTexture );
                CHAR strConverted[256];
                strConverted[0] = 0;
                wcstombs_s( 0, strConverted, strNameTemp, _countof(strConverted) );  
                PIXSetTextureName( pD3DTexture, TEXT(strConverted) );
#endif
              break;
            }
        case RESOURCETYPE_VERTEXBUFFER:
        case RESOURCETYPE_INDEXBUFFER:
        case RESOURCETYPE_USERDATA:
        default:
            {
                // not supported yet
                DebugSpew( "Unsupported resource type %d for resource \"%s\".\n", pTags[i].dwType, pTags[i].strName );
                break;
            }
        }
        ++i;
    }
}
Example #14
0
wstring toLowerCase(wstring str)
{
	if (str.length())
		_wcslwr_s(&str[0], str.length() + 1);
	return str;
}
LRESULT CALLBACK ScanWndProc( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam )
{
    switch ( msg )
    {
		case WM_CREATE:
		{
			RECT rc;
			GetClientRect( hWnd, &rc );

			g_hWnd_tab = CreateWindowEx( WS_EX_CONTROLPARENT, WC_TABCONTROL, NULL, WS_CHILD | WS_CLIPCHILDREN | WS_TABSTOP | WS_VISIBLE, 10, 10, rc.right - 20, rc.bottom - 50, hWnd, NULL, NULL, NULL );

			TCITEMA ti = { 0 };
			ti.mask = TCIF_PARAM | TCIF_TEXT;	// The tab will have text and an lParam value.
			ti.pszText = "Scan Directory";
			ti.lParam = ( LPARAM )0;
			SendMessageA( g_hWnd_tab, TCM_INSERTITEMA, 0, ( LPARAM )&ti );	// Insert a new tab at the end.

			ti.pszText = "Load ESE Database";
			ti.lParam = ( LPARAM )1;
			SendMessageA( g_hWnd_tab, TCM_INSERTITEMA, 1, ( LPARAM )&ti );	// Insert a new tab at the end.

			SendMessage( g_hWnd_tab, WM_SETFONT, ( WPARAM )hFont, 0 );

			// Set the tab's font before we get the item rect so that we have an accurate height.
			RECT rc_tab;
			GetClientRect( g_hWnd_tab, &rc );
			SendMessage( g_hWnd_tab, TCM_GETITEMRECT, 0, ( LPARAM )&rc_tab );

			g_hWnd_scan_tab = CreateWindowEx( WS_EX_CONTROLPARENT, L"scan_tab", NULL, WS_CHILD | WS_TABSTOP | WS_VISIBLE, 10, ( rc_tab.bottom + rc_tab.top ) + 8, rc.right - 20, rc.bottom - ( ( rc_tab.bottom + rc_tab.top ) + 16 ), g_hWnd_tab, NULL, NULL, NULL );

			g_hWnd_btn_details = CreateWindowA( WC_BUTTONA, "Show Details \xBB", WS_CHILD | WS_TABSTOP | WS_VISIBLE, 0, 0, 0, 0, hWnd, ( HMENU )BTN_DETAILS, NULL, NULL );

			g_hWnd_btn_scan = CreateWindowA( WC_BUTTONA, "Scan", BS_DEFPUSHBUTTON | WS_CHILD | WS_TABSTOP | WS_VISIBLE, 0, 0, 0, 0, hWnd, ( HMENU )BTN_SCAN, NULL, NULL );
			g_hWnd_btn_cancel = CreateWindowA( WC_BUTTONA, "Cancel", WS_CHILD | WS_TABSTOP | WS_VISIBLE, 0, 0, 0, 0, hWnd, ( HMENU )BTN_CANCEL, NULL, NULL );

			// Make pretty font.
			SendMessage( g_hWnd_btn_details, WM_SETFONT, ( WPARAM )hFont, 0 );
			SendMessage( g_hWnd_btn_scan, WM_SETFONT, ( WPARAM )hFont, 0 );
			SendMessage( g_hWnd_btn_cancel, WM_SETFONT, ( WPARAM )hFont, 0 );

			return 0;
		}
		break;

		case WM_CHANGE_CURSOR:
		{
			// SetCursor must be called from the window thread.
			if ( wParam == TRUE )
			{
				wait_cursor = LoadCursor( NULL, IDC_APPSTARTING );	// Arrow + hourglass.
				SetCursor( wait_cursor );
			}
			else
			{
				SetCursor( LoadCursor( NULL, IDC_ARROW ) );	// Default arrow.
				wait_cursor = NULL;
			}
		}
		break;

		case WM_SETCURSOR:
		{
			if ( wait_cursor != NULL )
			{
				SetCursor( wait_cursor );	// Keep setting our cursor if it reverts back to the default.
				return TRUE;
			}

			DefWindowProc( hWnd, msg, wParam, lParam );
			return FALSE;
		}
		break;

		case WM_COMMAND:
		{
			switch( LOWORD( wParam ) )
			{
				case IDOK:
				case BTN_SCAN:
				{
					if ( g_kill_scan == false )
					{
						EnableWindow( g_hWnd_btn_scan, FALSE );
						g_kill_scan = true;
						break;
					}

					int length = SendMessage( g_hWnd_path[ tab_index ], WM_GETTEXT, MAX_PATH, ( LPARAM )g_filepath );
					if ( length >= 3 )
					{
						// We need to have at least the drive path. Example: "C:\"
						if ( g_filepath[ 1 ] == L':' && g_filepath[ 2 ] == L'\\' )
						{
							// Remove any trailing "\" from the path.
							if ( g_filepath[ length - 1 ] == L'\\' )
							{
								g_filepath[ length - 1 ] = '\0';
							}

							// Now get our extension filters.
							length = SendMessage( g_hWnd_extensions[ tab_index ], WM_GETTEXT, MAX_PATH, ( LPARAM )( g_extension_filter + 1 ) );
							if ( length > 0 )
							{
								g_extension_filter[ 0 ] = L'|';					// Append the delimiter to the beginning of the string.
								g_extension_filter[ length + 1 ] = L'|';		// Append the delimiter to the end of the string.
								g_extension_filter[ length + 2 ] = L'\0';
								_wcslwr_s( g_extension_filter, length + 3 );	// Set them to lowercase for later comparison.
							}
							else
							{
								g_extension_filter[ 0 ] = L'\0';
							}

							g_include_folders = SendMessage( g_hWnd_chk_folders[ tab_index ], BM_GETCHECK, 0, 0 ) ? true : false;

							g_retrieve_extended_information = SendMessage( g_hWnd_extended_information, BM_GETCHECK, 0, 0 ) ? true : false;

							scan_type = tab_index;	// scan_type will allow the correct windows to update regardless of the selected tab.

							// If use_scanner == false, then read the ese database.
							CloseHandle( ( HANDLE )_beginthreadex( NULL, 0, &map_entries, ( void * )scan_type, 0, NULL ) );
						}
						else
						{
							MessageBoxA( hWnd, "You must specify a valid path.", PROGRAM_CAPTION_A, MB_APPLMODAL | MB_ICONWARNING );
						}
					}
				}
				break;

				case BTN_CANCEL:
				{
					SendMessage( hWnd, WM_CLOSE, 0, 0 );
				}
				break;

				case BTN_DETAILS:
				{
					g_show_details = !g_show_details;

					// Hiding the details will allow for a faster scan since it doesn't have to update our controls.
					if ( g_show_details == true )
					{
						SendMessageA( g_hWnd_btn_details, WM_SETTEXT, 0, ( LPARAM )"Hide Details \xAB" );
						ShowWindow( g_hWnd_static3, SW_SHOW );
						ShowWindow( g_hWnd_static4, SW_SHOW );
						ShowWindow( g_hWnd_static5, SW_SHOW );
						ShowWindow( g_hWnd_hashing[ tab_index ], SW_SHOW );
						ShowWindow( g_hWnd_static_hash[ tab_index ], SW_SHOW );
						ShowWindow( g_hWnd_static_count[ tab_index ], SW_SHOW );
					}
					else
					{
						SendMessageA( g_hWnd_btn_details, WM_SETTEXT, 0, ( LPARAM )"Show Details \xBB" );
						ShowWindow( g_hWnd_static3, SW_HIDE );
						ShowWindow( g_hWnd_static4, SW_HIDE );
						ShowWindow( g_hWnd_static5, SW_HIDE );
						ShowWindow( g_hWnd_hashing[ 0 ], SW_HIDE );
						ShowWindow( g_hWnd_hashing[ 1 ], SW_HIDE );
						ShowWindow( g_hWnd_static_hash[ 0 ], SW_HIDE );
						ShowWindow( g_hWnd_static_hash[ 1 ], SW_HIDE );
						ShowWindow( g_hWnd_static_count[ 0 ], SW_HIDE );
						ShowWindow( g_hWnd_static_count[ 1 ], SW_HIDE );
					}

					// Adjust the window height.
					RECT rc;
					GetWindowRect( hWnd, &rc );
					SetWindowPos( hWnd, NULL, 0, 0, rc.right - rc.left, MIN_HEIGHT - ( g_show_details == true ? 25 : 115 ), SWP_NOMOVE );
				}
				break;
			}

			return 0;
		}
		break;

		case WM_NOTIFY:
		{
			// Get our listview codes.
			switch ( ( ( LPNMHDR )lParam )->code )
			{
				case TCN_SELCHANGING:		// The tab that's about to lose focus
				{
					NMHDR *nmhdr = ( NMHDR * )lParam;

					int index = SendMessage( nmhdr->hwndFrom, TCM_GETCURSEL, 0, 0 );		// Get the selected tab
					if ( index == 0 || index == 1 )
					{
						ShowWindow( g_hWnd_path[ index ], SW_HIDE );
						ShowWindow( g_hWnd_extensions[ index ], SW_HIDE );
						ShowWindow( g_hWnd_chk_folders[ index ], SW_HIDE );
						ShowWindow( g_hWnd_hashing[ index ], SW_HIDE );
						ShowWindow( g_hWnd_static_hash[ index ], SW_HIDE );
						ShowWindow( g_hWnd_static_count[ index ], SW_HIDE );

						if ( index == 1 )
						{
							ShowWindow( g_hWnd_extended_information, SW_HIDE );
						}
					}

					return FALSE;
				}
				break;

				case TCN_SELCHANGE:			// The tab that gains focus
                {
					NMHDR *nmhdr = ( NMHDR * )lParam;

					int index = SendMessage( nmhdr->hwndFrom, TCM_GETCURSEL, 0, 0 );		// Get the selected tab
					if ( index == 0 || index == 1 )
					{
						SendMessageA( g_hWnd_static1, WM_SETTEXT, 0, ( LPARAM )( index == 0 ? "Initial scan directory:" : "Extensible Storage Engine Database file:" ) );

						ShowWindow( g_hWnd_path[ index ], SW_SHOW );
						ShowWindow( g_hWnd_extensions[ index ], SW_SHOW );
						ShowWindow( g_hWnd_chk_folders[ index ], SW_SHOW );

						if ( g_show_details == true )
						{
							ShowWindow( g_hWnd_hashing[ index ], SW_SHOW );
							ShowWindow( g_hWnd_static_hash[ index ], SW_SHOW );
							ShowWindow( g_hWnd_static_count[ index ], SW_SHOW );
						}

						if ( index == 1 )
						{
							ShowWindow( g_hWnd_extended_information, SW_SHOW );
						}

						// If we're scanning, then enable the scan button. Otherwise, check for a valid path.
						EnableWindow( g_hWnd_btn_scan, ( g_kill_scan == false || SendMessage( g_hWnd_path[ index ], WM_GETTEXTLENGTH, 0, 0 ) >= 3 ) ? TRUE : FALSE );

						tab_index = index;
					}

					return FALSE;
                }
				break;
			}

			return FALSE;
		}
		break;

		case WM_SIZE:
		{
			RECT rc;
			GetClientRect( hWnd, &rc );

			// Allow our controls to move in relation to the parent window.
			HDWP hdwp = BeginDeferWindowPos( 4 );
			DeferWindowPos( hdwp, g_hWnd_tab, HWND_TOP, 10, 10, rc.right - 20, rc.bottom - 50, SWP_NOZORDER );
			DeferWindowPos( hdwp, g_hWnd_btn_details, HWND_TOP, 10, rc.bottom - 32, 100, 23, SWP_NOZORDER );
			DeferWindowPos( hdwp, g_hWnd_btn_scan, HWND_TOP, rc.right - 175, rc.bottom - 32, 80, 23, SWP_NOZORDER );
			DeferWindowPos( hdwp, g_hWnd_btn_cancel, HWND_TOP, rc.right - 90, rc.bottom - 32, 80, 23, SWP_NOZORDER );
			EndDeferWindowPos( hdwp );

			RECT rc_tab;
			GetClientRect( g_hWnd_tab, &rc );
			SendMessage( g_hWnd_tab, TCM_GETITEMRECT, 0, ( LPARAM )&rc_tab );

			SetWindowPos( g_hWnd_scan_tab, HWND_TOP, 10, ( rc_tab.bottom + rc_tab.top ) + 8, rc.right - 20, rc.bottom - ( ( rc_tab.bottom + rc_tab.top ) + 16 ), SWP_NOZORDER );

			return 0;
		}
		break;

		case WM_GETMINMAXINFO:
		{
			// Set the minimum dimensions that the window can be sized to.
			( ( MINMAXINFO * )lParam )->ptMinTrackSize.x = MIN_WIDTH;
			( ( MINMAXINFO * )lParam )->ptMinTrackSize.y = MIN_HEIGHT - ( g_show_details == true ? 25 : 115 );
			( ( MINMAXINFO * )lParam )->ptMaxTrackSize.y = MIN_HEIGHT - ( g_show_details == true ? 25 : 115 );

			return 0;
		}
		break;

		case WM_ACTIVATE:
		{
			// 0 = inactive, > 0 = active
			g_hWnd_active = ( wParam == 0 ? NULL : hWnd );

            return FALSE;
		}
		break;

		case WM_CLOSE:
		{
			g_kill_scan = true;

			// Reenable the main window.
			EnableWindow( g_hWnd_main, TRUE );
			SetForegroundWindow( g_hWnd_main );

			ShowWindow( hWnd, SW_HIDE );
		}
		break;

		case WM_ALERT:
		{
			MessageBoxA( hWnd, ( LPCSTR )lParam, PROGRAM_CAPTION_A, MB_APPLMODAL | ( wParam == 1 ? MB_ICONINFORMATION : MB_ICONWARNING ) | MB_SETFOREGROUND );
		}
		break;

		case WM_PROPAGATE:
		{
			if ( wParam == 1 )
			{
				g_kill_scan = false;

				EnableWindow( g_hWnd_path[ 0 ], FALSE );
				EnableWindow( g_hWnd_path[ 1 ], FALSE );
				EnableWindow( g_hWnd_load, FALSE );
				EnableWindow( g_hWnd_extensions[ 0 ], FALSE );
				EnableWindow( g_hWnd_extensions[ 1 ], FALSE );
				EnableWindow( g_hWnd_chk_folders[ 0 ], FALSE );
				EnableWindow( g_hWnd_chk_folders[ 1 ], FALSE );
				EnableWindow( g_hWnd_extended_information, FALSE );

				// We're scanning. Set the button's text to "Stop".
				SendMessageA( g_hWnd_btn_scan, WM_SETTEXT, 0, ( LPARAM )"Stop" );
			}
			else if ( wParam == 2 )
			{
				// Clear the current file info if we finished the scan without stopping.
				if ( g_kill_scan == false )
				{
					SendMessage( g_hWnd_hashing[ scan_type ], WM_SETTEXT, 0, 0 );
					SendMessageA( g_hWnd_static_hash[ scan_type ], WM_SETTEXT, 0, 0 );
				}

				g_kill_scan = true;

				EnableWindow( g_hWnd_path[ 0 ], TRUE );
				EnableWindow( g_hWnd_path[ 1 ], TRUE );
				EnableWindow( g_hWnd_load, TRUE );
				EnableWindow( g_hWnd_extensions[ 0 ], TRUE );
				EnableWindow( g_hWnd_extensions[ 1 ], TRUE );
				EnableWindow( g_hWnd_chk_folders[ 0 ], TRUE );
				EnableWindow( g_hWnd_chk_folders[ 1 ], TRUE );
				EnableWindow( g_hWnd_extended_information, TRUE );

				// We've stopped/finished scanning. Set the button's text to "Scan".
				SendMessageA( g_hWnd_btn_scan, WM_SETTEXT, 0, ( LPARAM )"Scan" );
				EnableWindow( g_hWnd_btn_scan, ( SendMessage( g_hWnd_path[ tab_index ], WM_GETTEXTLENGTH, 0, 0 ) >= 3 ) ? TRUE : FALSE );
			}
			else if ( wParam == 3 )
			{
				SendMessage( g_hWnd_hashing[ scan_type ], WM_SETTEXT, 0, lParam );
			}
			else if ( wParam == 4 )
			{
				SendMessageA( g_hWnd_static_hash[ scan_type ], WM_SETTEXT, 0, lParam );
			}
			else if ( wParam == 5 )
			{
				SendMessageA( g_hWnd_static_count[ scan_type ], WM_SETTEXT, 0, lParam );
			}
			else
			{
				g_kill_scan = true;

				// Reset text information.
				SendMessage( g_hWnd_hashing[ 0 ], WM_SETTEXT, 0, 0 );
				SendMessage( g_hWnd_hashing[ 1 ], WM_SETTEXT, 0, 0 );
				SendMessageA( g_hWnd_static_hash[ 0 ], WM_SETTEXT, 0, 0 );
				SendMessageA( g_hWnd_static_hash[ 1 ], WM_SETTEXT, 0, 0 );
				SendMessageA( g_hWnd_static_count[ 0 ], WM_SETTEXT, 0, 0 );
				SendMessageA( g_hWnd_static_count[ 1 ], WM_SETTEXT, 0, 0 );
				SendMessageA( g_hWnd_btn_scan, WM_SETTEXT, 0, ( LPARAM )"Scan" );
				EnableWindow( g_hWnd_btn_scan, ( SendMessage( g_hWnd_path[ tab_index ], WM_GETTEXTLENGTH, 0, 0 ) >= 3 ) ? TRUE : FALSE );

				SendMessage( g_hWnd_tab, TCM_SETCURFOCUS, 0, 0 );

				// Disable the main window.
				EnableWindow( g_hWnd_main, FALSE );

				// Set the window above all other windows.
				SetForegroundWindow( hWnd );
				SetWindowPos( hWnd, HWND_TOP, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE );
				ShowWindow( hWnd, SW_SHOW );
			}
		}
		break;

		default:
		{
			return DefWindowProc( hWnd, msg, wParam, lParam );
		}
		break;
	}
	return TRUE;
}
Example #16
0
std::vector<CHARRANGE> CLogDlgFilter::GetMatchRanges (std::wstring& textUTF16) const
{
    std::vector<CHARRANGE> ranges;

    // normalize to lower case

    if (!caseSensitive && !textUTF16.empty())
        _wcslwr_s (&textUTF16.at(0), textUTF16.length()+1);
    std::string textUTF8 = CUnicodeUtils::StdGetUTF8 (textUTF16);

    if (patterns.empty())
    {
        // require all strings to be present

        const char* toScan = textUTF8.c_str();
        for ( auto iter = subStringConditions.begin()
            , end = subStringConditions.end()
            ; iter != end
            ; ++iter)
        {
            if (iter->prefix != and_not)
            {
                const char * toFind = iter->subString.c_str();
                size_t toFindLength = iter->subString.length();
                const char * pFound = strstr (toScan, toFind);
                while (pFound)
                {
                    CHARRANGE range;
                    range.cpMin = (LONG)(pFound - toScan);
                    range.cpMax = (LONG)(range.cpMin + toFindLength);
                    ranges.push_back(range);
                    pFound = strstr (pFound+1, toFind);
                }
            }
        }
    }
    else
    {
        for (std::vector<std::tr1::regex>::const_iterator it = patterns.begin(); it != patterns.end(); ++it)
        {
            const std::tr1::sregex_iterator end;
            for (std::tr1::sregex_iterator it2(textUTF8.begin(), textUTF8.end(), *it); it2 != end; ++it2)
            {
                ptrdiff_t matchposID = it2->position(0);
                CHARRANGE range = {(LONG)(matchposID), (LONG)(matchposID+(*it2)[0].str().size())};
                ranges.push_back(range);
            }
        }
    }

    // the caller expects the result to be ordered by position which
    // which may not be the case after scanninf for multiple sub-strings

    if (ranges.size() > 1)
    {
        auto begin = ranges.begin();
        auto end = ranges.end();

        std::sort(begin, end,
                    [] (const CHARRANGE& lhs, const CHARRANGE& rhs) -> bool
                        {return lhs.cpMin < rhs.cpMin;}
                 );

        // once we are at it, merge adjacent and / or overlapping ranges

        auto target = begin;
        for (auto source = begin + 1; source != end; ++source)
            if (target->cpMax < source->cpMin)
                *(++target) = *source;
            else
                target->cpMax = max (target->cpMax, source->cpMax);

        ranges.erase (++target, end);
    }

    // translate UTF8 ranges to UTF16 ranges

    size_t utf8Pos = 0;
    size_t utf16Pos = 0;
    for ( auto iter = ranges.begin(), end = ranges.end()
        ; iter != end
        ; ++iter)
    {
        AdvanceUnicodePos (textUTF8, utf8Pos, utf16Pos, iter->cpMin);
        iter->cpMin = (LONG)utf16Pos;
        AdvanceUnicodePos (textUTF8, utf8Pos, utf16Pos, iter->cpMax);
        iter->cpMax = (LONG)utf16Pos;
    }

    return ranges;
}
///
/// Disassemble the instruction at the given address, creating an instruction object
///
bool
Disassemble( const DEBUGGER_CONTROLS &objControls, ULONG64 offAddress, ULONG dwProcessor, bool fFlagsRegisterValid, const OPERAND_SET& setProcessorFlags, INSTRUCTION *pInstruction )
{
	// Disassemble the instruction
	ULONG cchInstruction;
	ULONG dwAssemblyOptions;
	HRESULT dwResult;

	// For ARM/THUMB processors, mask off the lowest address bit
	if( (dwProcessor == IMAGE_FILE_MACHINE_ARM) || (dwProcessor == IMAGE_FILE_MACHINE_THUMB) || (dwProcessor == IMAGE_FILE_MACHINE_ARMNT) )
	{
		offAddress = offAddress & ~0x1;
	}

	objControls.pDebugControl->GetAssemblyOptions( &dwAssemblyOptions );
	objControls.pDebugControl->SetAssemblyOptions( dwAssemblyOptions & ~(DEBUG_ASMOPT_NO_CODE_BYTES | DEBUG_ASMOPT_SOURCE_LINE_NUMBER) );
	objControls.pDebugControl->DisassembleWide( offAddress, 0, NULL, 0, &cchInstruction, &pInstruction->offNextInstruction );
	pInstruction->pwzInstructionBuffer = new WCHAR[cchInstruction + 1];

	if( pInstruction->pwzInstructionBuffer == NULL )
	{
		return( false );
	}

	dwResult = objControls.pDebugControl->DisassembleWide( offAddress, 0, (PWSTR) pInstruction->pwzInstructionBuffer, cchInstruction + 1, NULL, &pInstruction->offNextInstruction );
	objControls.pDebugControl->SetAssemblyOptions( dwAssemblyOptions );

	if( dwResult != S_OK )
	{
		return( false );
	}
	else
	{
		pInstruction->offAddress = offAddress;
		_wcslwr_s( (PWSTR) pInstruction->pwzInstructionBuffer, cchInstruction );
	}

	// Check for disassembly errors that would cause infinite loops, this is usually due to a mismatch
	// between the debugger machine mode and the process machine mode (x86 versus x64)
	if( pInstruction->offAddress == pInstruction->offNextInstruction )
	{
		return( false );
	}

	// Check for a mismatch in the disassembly
	if( wcsstr( pInstruction->pwzInstructionBuffer, L"disassembly not possible" ) != NULL )
	{
		return( false );
	}

	// Store the instruction flags information
	pInstruction->fFlagsRegisterValid = fFlagsRegisterValid;

	// Parse the fields for the continued processing
	PWSTR pwzIndex = (PWSTR) pInstruction->pwzInstructionBuffer;
	pInstruction->pwzAddress = (PCWSTR) pwzIndex ;
	ParseDisassemblyFieldInPlace( &pwzIndex, NULL );
	pInstruction->pwzOpCode = (PCWSTR) pwzIndex;
	ParseDisassemblyFieldInPlace( &pwzIndex, NULL );
	pInstruction->pwzMnemonic = (PCWSTR) pwzIndex;

	switch( dwProcessor )
	{
		case IMAGE_FILE_MACHINE_I386:
			{
				ParseDisassemblyFieldInPlace( &pwzIndex, X86_MNEMONIC_PREFIXES );
			}
			break;

		case IMAGE_FILE_MACHINE_AMD64:
			{
				ParseDisassemblyFieldInPlace( &pwzIndex, X64_MNEMONIC_PREFIXES );
			}
			break;

		case IMAGE_FILE_MACHINE_ARM:
		case IMAGE_FILE_MACHINE_THUMB:
		case IMAGE_FILE_MACHINE_ARMNT:
			{
				ParseDisassemblyFieldInPlace( &pwzIndex, ARM_MNEMONIC_PREFIXES );
			}
			break;

		default:
			return( false );
	}
	pInstruction->pwzArguments = (PCWSTR) pwzIndex;
	
	if( pInstruction->pwzArguments != NULL )
	{
		size_t cchArguments = wcslen( pInstruction->pwzArguments );

		if( cchArguments > 0 )
		{
			if( pInstruction->pwzArguments[cchArguments - 1] == '\n' )
			{
				((PWSTR) pInstruction->pwzArguments)[cchArguments - 1] = '\0';
			}
		}
	}

	// Check for invalid op codes or menmonics, that indicate a disassembly failure
	if( *pInstruction->pwzMnemonic == '?' )
	{
		return( false );
	}

	if( *pInstruction->pwzOpCode == '<' )
	{
		return( false );
	}

	// Classify the instruction
	//
	// Note that we don't consider our inability to match an instruction to be an error here, we'll continue with it
	// until we find an error in the actual disassembly routines (above)
	switch( dwProcessor )
	{
		case IMAGE_FILE_MACHINE_I386:
			{
				ClassifyX86Instruction( pInstruction );
				return( true );
			}

		case IMAGE_FILE_MACHINE_AMD64:
			{
				ClassifyX64Instruction( pInstruction );
				return( true );
			}

		case IMAGE_FILE_MACHINE_ARM:
		case IMAGE_FILE_MACHINE_THUMB:
		case IMAGE_FILE_MACHINE_ARMNT:
			{
				ClassifyARMInstruction( pInstruction, setProcessorFlags );
				return( true );
			}

		default:
			return( false );
	}
}
// dump - Dumps a nicely formatted rendition of the CallStack, including
//   symbolic information (function names and line numbers) if available.
//
//   Note: The symbol handler must be initialized prior to calling this
//     function.
//
//  - showinternalframes (IN): If true, then all frames in the CallStack will be
//      dumped. Otherwise, frames internal to the heap will not be dumped.
//
//  Return Value:
//
//    None.
//
void CallStack::dump(BOOL showInternalFrames, UINT start_frame) const
{
    // The stack was dumped already
    if (m_resolved)
    {
        dumpResolved();
        return;
    }

    if (m_status & CALLSTACK_STATUS_INCOMPLETE) {
        // This call stack appears to be incomplete. Using StackWalk64 may be
        // more reliable.
        Report(L"    HINT: The following call stack may be incomplete. Setting \"StackWalkMethod\"\n"
            L"      in the vld.ini file to \"safe\" instead of \"fast\" may result in a more\n"
            L"      complete stack trace.\n");
    }

    IMAGEHLP_LINE64  sourceInfo = { 0 };
    sourceInfo.SizeOfStruct = sizeof(IMAGEHLP_LINE64);

    BYTE symbolBuffer [sizeof(SYMBOL_INFO) + MAX_SYMBOL_NAME_SIZE] = { 0 };

    WCHAR lowerCaseName [MAX_PATH];
    WCHAR callingModuleName [MAX_PATH];

    const size_t max_size = MAXREPORTLENGTH + 1;

    // Iterate through each frame in the call stack.
    for (UINT32 frame = start_frame; frame < m_size; frame++)
    {
        // Try to get the source file and line number associated with
        // this program counter address.
        SIZE_T programCounter = (*this)[frame];
        g_symbolLock.Enter();
        BOOL             foundline = FALSE;
        DWORD            displacement = 0;
        DbgTrace(L"dbghelp32.dll %i: SymGetLineFromAddrW64\n", GetCurrentThreadId());
        foundline = SymGetLineFromAddrW64(g_currentProcess, programCounter, &displacement, &sourceInfo);
        if (foundline && !showInternalFrames) {
            wcscpy_s(lowerCaseName, sourceInfo.FileName);
            _wcslwr_s(lowerCaseName, wcslen(lowerCaseName) + 1);
            if (isInternalModule(lowerCaseName)) {
                // Don't show frames in files internal to the heap.
                g_symbolLock.Leave();
                continue;
            }
        }

        // Initialize structures passed to the symbol handler.
        SYMBOL_INFO* functionInfo = (SYMBOL_INFO*)&symbolBuffer;
        functionInfo->SizeOfStruct = sizeof(SYMBOL_INFO);
        functionInfo->MaxNameLen = MAX_SYMBOL_NAME_LENGTH;

        // Try to get the name of the function containing this program
        // counter address.
        DWORD64          displacement64 = 0;
        LPWSTR           functionName;
        DbgTrace(L"dbghelp32.dll %i: SymFromAddrW\n", GetCurrentThreadId());
        if (SymFromAddrW(g_currentProcess, programCounter, &displacement64, functionInfo)) {
            functionName = functionInfo->Name;
        }
        else {
            // GetFormattedMessage( GetLastError() );
            functionName = L"(Function name unavailable)";
            displacement64 = 0;
        }
        g_symbolLock.Leave();

        HMODULE hCallingModule = GetCallingModule(programCounter);
        LPWSTR moduleName = L"(Module name unavailable)";
        if (hCallingModule && 
            GetModuleFileName(hCallingModule, callingModuleName, _countof(callingModuleName)) > 0)
        {
            moduleName = wcsrchr(callingModuleName, L'\\');
            if (moduleName == NULL)
                moduleName = wcsrchr(callingModuleName, L'/');
            if (moduleName != NULL)
                moduleName++;
            else
                moduleName = callingModuleName;
        }

        // Use static here to increase performance, and avoid heap allocs. Hopefully this won't
        // prove to be an issue in thread safety. If it does, it will have to be simply non-static.
        static WCHAR stack_line[MAXREPORTLENGTH + 1] = L"";
        int NumChars = -1;
        // Display the current stack frame's information.
        if (foundline) {
            if (displacement == 0)
                NumChars = _snwprintf_s(stack_line, max_size, _TRUNCATE, L"    %s (%d): %s!%s\n", 
                sourceInfo.FileName, sourceInfo.LineNumber, moduleName, functionName);
            else
                NumChars = _snwprintf_s(stack_line, max_size, _TRUNCATE, L"    %s (%d): %s!%s + 0x%X bytes\n", 
                sourceInfo.FileName, sourceInfo.LineNumber, moduleName, functionName, displacement);
        }
        else {
            if (displacement64 == 0)
                NumChars = _snwprintf_s(stack_line, max_size, _TRUNCATE, L"    " ADDRESSFORMAT L" (File and line number not available): %s!%s\n", 
                programCounter, moduleName, functionName);
            else
                NumChars = _snwprintf_s(stack_line, max_size, _TRUNCATE, L"    " ADDRESSFORMAT L" (File and line number not available): %s!%s + 0x%X bytes\n", 
                programCounter, moduleName, functionName, (DWORD)displacement64);	
        }

        Print(stack_line);
    }
}