/********************************************************************** NAME : WatchMethod DESCRIPTION : Prints out a trace of the beginning or end of the execution of a generic function method INPUTS : A string to indicate beginning or end of execution RETURNS : Nothing useful SIDE EFFECTS : None NOTES : Uses the globals CurrentGeneric, CurrentMethod, ProcParamArraySize and ProcParamArray for other trace info **********************************************************************/ static void WatchMethod( Environment *theEnv, const char *tstring) { if (ConstructData(theEnv)->ClearReadyInProgress || ConstructData(theEnv)->ClearInProgress) { return; } WriteString(theEnv,STDOUT,"MTH "); WriteString(theEnv,STDOUT,tstring); WriteString(theEnv,STDOUT," "); if (DefgenericData(theEnv)->CurrentGeneric->header.whichModule->theModule != GetCurrentModule(theEnv)) { WriteString(theEnv,STDOUT,DefgenericModule(DefgenericData(theEnv)->CurrentGeneric)); WriteString(theEnv,STDOUT,"::"); } WriteString(theEnv,STDOUT,DefgenericData(theEnv)->CurrentGeneric->header.name->contents); WriteString(theEnv,STDOUT,":#"); if (DefgenericData(theEnv)->CurrentMethod->system) WriteString(theEnv,STDOUT,"SYS"); PrintUnsignedInteger(theEnv,STDOUT,DefgenericData(theEnv)->CurrentMethod->index); WriteString(theEnv,STDOUT," "); WriteString(theEnv,STDOUT," ED:"); WriteInteger(theEnv,STDOUT,EvaluationData(theEnv)->CurrentEvaluationDepth); PrintProcParamArray(theEnv,STDOUT); }
int _tmain(int argc, _TCHAR* argv[]) { HMODULE bridgeHandle = LoadLibrary(L"UnmanagedManaged.C++.dll"); StartApplicationFunc startApplication = (StartApplicationFunc)GetProcAddress(bridgeHandle, "StartApplication"); HMODULE handle = GetCurrentModule(); startApplication(handle); return 0; }
GENERATE_INTERCEPT_HEADER(LoadLibraryExW, HMODULE, WINAPI, _In_ LPCWSTR lpLibFileName, _Reserved_ HANDLE hFile, _In_ DWORD dwFlags) { SDLOG(2, "DetouredLoadLibraryExW %s\n", CW2A(lpLibFileName)); string fn((CW2A(lpLibFileName))); if(fn.find("GeDoSaTo") != fn.npos) return GetCurrentModule(); // find out why we need this HMODULE mod = TrueLoadLibraryExW(lpLibFileName, hFile, dwFlags); // restart detour in case we missed anything if(mod) restartDetour(CW2A(lpLibFileName)); return mod; }
/******************************************************************* * UpdateStatusWndTitle: Function will append the Current Module * name to the Window Title Bar. *******************************************************************/ void UpdateStatusWndTitle( HWND hWnd, char *prefix) { struct defmodule *theModule = (struct defmodule *) GetCurrentModule(); char buffer[255]; sprintf ( buffer, "%s (%s)",prefix, GetDefmoduleName(theModule)); SetWindowText (hWnd, buffer); }
static int ClearDefrulesReady() { if (ExecutingRule != NULL) return(FALSE); ClearFocusStack(); if (GetCurrentModule() == NULL) return(FALSE); CurrentEntityTimeTag = 0L; return(TRUE); }
STDAPI DllRegisterServer(void) { HKEY rootKey; HKEY hKey; HKEY hKey2; HKEY hkExtra; WCHAR buffer[GUID_BUFFER_SIZE]; DWORD disposition; HRESULT result; WCHAR filename[MAX_PATH]; GetModuleFileNameW(GetCurrentModule(), filename, sizeof(filename)); result = S_FALSE; // Open "HKEY_LOCAL_MACHINE\Software\Classes" if (!RegOpenKeyEx(HKEY_LOCAL_MACHINE, &ClassKeyName[0], 0, KEY_WRITE, &rootKey)) { // Open "HKEY_LOCAL_MACHINE\Software\Classes\CLSID" if (!RegOpenKeyEx(rootKey, &CLSID_Str[0], 0, KEY_ALL_ACCESS, &hKey)) { // Create a subkey whose name is the ascii string that represents // our IExample2 object's GUID StringFromGUID2(&CLSID_ILibraryInjector, buffer, _countof(buffer)); if (!RegCreateKeyEx(hKey, &buffer[0], 0, 0, REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &hKey2, &disposition)) { // Set its default value to some "friendly" string that helps // a user identify what this COM DLL is for. Setting this value // is optional. You don't need to do it RegSetValueEx(hKey2, 0, 0, REG_SZ, (const BYTE *)&ObjectDescription[0], sizeof(ObjectDescription)); // Create an "InprocServer32" key whose default value is the path of this DLL if (!RegCreateKeyEx(hKey2, &InprocServer32Name[0], 0, 0, REG_OPTION_NON_VOLATILE, KEY_WRITE, 0, &hkExtra, &disposition)) { if (!RegSetValueEx(hkExtra, 0, 0, REG_SZ, (const BYTE *)&filename[0], (DWORD)wcslen(&filename[0]) * 2 + 2)) { // Create a "ThreadingModel" value set to the string "both" (ie, we don't need to restrict an // application to calling this DLL's functions only from a single thread. We don't use global // data in our IExample functions, so we're thread-safe) if (!RegSetValueEx(hkExtra, &ThreadingModel[0], 0, REG_SZ, (const BYTE *)&BothStr[0], sizeof(BothStr))) { result = S_OK; } } // Close all keys we opened/created. RegCloseKey(hkExtra); } RegCloseKey(hKey2); } RegCloseKey(hKey); } RegCloseKey(rootKey); } return result; }
/****************************************************** NAME : PrintGenericName DESCRIPTION : Prints the name of a gneric function (including the module name if the generic is not in the current module) INPUTS : 1) The logical name of the output 2) The generic functions RETURNS : Nothing useful SIDE EFFECTS : Generic name printed NOTES : None ******************************************************/ globle void PrintGenericName( char *log, DEFGENERIC *gfunc) { if (gfunc->header.whichModule->theModule != ((struct defmodule *) GetCurrentModule())) { PrintRouter(log,GetDefmoduleName((void *) gfunc->header.whichModule->theModule)); PrintRouter(log,"::"); } PrintRouter(log,ValueToString((void *) gfunc->header.name)); }
bool CUtilities::ExtractAppPath( TCHAR* chPath ) { TCHAR path[256] = {0X00}; GetModuleFileName(GetCurrentModule(),(TCHAR*)path,sizeof(path)); //CString strPath = path; TCHAR* pos = _tcsrchr( path, '\\' ); if( pos == NULL) return FALSE; *(pos + 1) = 0; _tcsncpy( chPath, path, (pos + 1) - path ); return true; }
bool CCoBroker::HandleRequestService(const tstring& dstUserId, ULONG dstSvcId, const tstring& srcUserId, ULONG srcSvcId, ULONG rId, ULONG rType, ULONG param, const tstring& params) { TRY_CATCH HRESULT result; EBrokerStartTypes startParam=BST_SAME; tstring url; { tstring::size_type iBeginUrl=params.find(_T(";;")); if(iBeginUrl!=tstring::npos) { tstring::size_type iEndUrl=params.find(_T(";;"),iBeginUrl+2); url=params.substr(iBeginUrl+2,(tstring::npos!=iEndUrl)?iEndUrl-iBeginUrl-2:tstring::npos); } } Log.Add(_MESSAGE_,_T("***HandleRequestService*** url=[%s]"),url.c_str()); const TCHAR SESSION_ID_PARAMETER_NAME[]=_T("supportRequestId="); tstring::size_type iWebSId=url.find(SESSION_ID_PARAMETER_NAME); if(iWebSId!=tstring::npos&&iWebSId+_countof(SESSION_ID_PARAMETER_NAME)<url.size()) { iWebSId+=_countof(SESSION_ID_PARAMETER_NAME)-1; tstring::size_type iWebSIdEnd=url.find_first_of(_T("&#"),iWebSId); if(tstring::npos==iWebSIdEnd) iWebSIdEnd=url.length(); tstring sId=url.substr(iWebSId,iWebSIdEnd-iWebSId); Log.Add(_MESSAGE_,_T("***HandleRequestService*** sId=[%s]"),sId.c_str()); SHA1Hash hash_buf; CRYPTO_INSTANCE.MakeHash((char*)sId.c_str(),sId.length()*sizeof(tstring::value_type),hash_buf); tstring hashString; for(int i=0;i<sizeof(hash_buf);++i) //hashString+=i2tstring((int)(unsigned char)hash_buf[i],16); hashString+=Format(_T("%02x"),(int)(unsigned char)hash_buf[i]); url.insert(iWebSIdEnd,tstring(_T("&sri="))+hashString); } //Log.Add(_WARNING_,_T("***HandleRequestService*** HASHING TURN OFF")); Log.Add(_MESSAGE_,_T("***HandleRequestService*** url=[%s]"),url.c_str()); CAtlFile cnfg; if(S_OK==cnfg.Create(Format(_T("%s\\%s"),GetModulePath(GetCurrentModule()).c_str(),_T("Broker.cfg")).c_str(),GENERIC_READ,0,OPEN_EXISTING)) { TRY_CATCH DWORD readLen=0; readLen=GetFileSize(cnfg.m_h,NULL); if(INVALID_FILE_SIZE==readLen&&readLen>32768) throw MCException_Win("Broker.cfg size obtaining failed or file too large"); std::auto_ptr<char> buf(new char[readLen]); if(!ReadFile(cnfg.m_h,buf.get(),readLen,&readLen,NULL)) throw MCException_Win("Broker.cfg file reading failed"); startParam=EBrokerStartTypes(atol(buf.get())); Log.Add(_MESSAGE_,_T("***HandleRequestService*** file startParam=[0x%x]"),startParam); CATCH_LOG() }
GENERATE_INTERCEPT_HEADER(LoadLibraryExA, HMODULE, WINAPI, _In_ LPCSTR lpLibFileName, _Reserved_ HANDLE hFile, _In_ DWORD dwFlags) { SDLOG(22, "DetouredLoadLibraryExA %s\n", lpLibFileName); string fn(lpLibFileName); if(fn.find("GeDoSaTo") != fn.npos) return GetCurrentModule(); // find out why we need this if(preventDllLoading(std::string(lpLibFileName))) return NULL; HMODULE mod = TrueLoadLibraryExA(lpLibFileName, hFile, dwFlags); // restart detour in case we missed anything if(mod) restartDetour(lpLibFileName); return mod; }
HRESULT PostProcessBloom::initPermanentResources(IDirect3DDevice9* pDevice, UINT width, UINT height) { m_pDevice = pDevice; HRESULT hr; HMODULE currentModule = GetCurrentModule(); // main shader - combine 2x hr = D3DXCreateEffectFromResource(pDevice, currentModule, "PP_ColorCombine2.fx", NULL, NULL, 0, NULL, &m_pEffect, NULL); if(FAILED(hr)) return hr; m_hTPostProcess = m_pEffect->GetTechniqueByName("PostProcess"); m_hTexScene = m_pEffect->GetParameterByName(NULL, "g_txSceneColor"); m_hTexSource = m_pEffect->GetParameterByName(NULL, "g_txSrcColor"); // 1st shader - bright pass hr = D3DXCreateEffectFromResource(pDevice, currentModule, "PP_ColorBrightPass.fx", NULL, NULL, 0, NULL, &m_pEffectBrightPass, NULL); m_hTPostProcessBP = m_pEffectBrightPass->GetTechniqueByName("PostProcess"); m_hTexSourceBP = m_pEffectBrightPass->GetParameterByName(NULL, "g_txSrcColor"); // 2nd shader - down size 2x hr = D3DXCreateEffectFromResource(pDevice, currentModule, "PP_ColorDownFilter2.fx", NULL, NULL, 0, NULL, &m_pEffectDownSize2x, NULL); m_hTPostProcessD2 = m_pEffectDownSize2x->GetTechniqueByName("PostProcess"); m_hTexSourceD2 = m_pEffectDownSize2x->GetParameterByName(NULL, "g_txSrcColor"); // 3rd shader - down size 4x hr = D3DXCreateEffectFromResource(pDevice, currentModule, "PP_ColorDownFilter4.fx", NULL, NULL, 0, NULL, &m_pEffectDownSize4x, NULL); m_hTPostProcessD4 = m_pEffectDownSize4x->GetTechniqueByName("PostProcess"); m_hTexSourceD4 = m_pEffectDownSize4x->GetParameterByName(NULL, "g_txSrcColor"); // 4th shader - bloom horizontal hr = D3DXCreateEffectFromResource(pDevice, currentModule, "PP_ColorBloomH.fx", NULL, NULL, 0, NULL, &m_pEffectBloomH, NULL); m_hTPostProcessBH = m_pEffectBloomH->GetTechniqueByName("PostProcess"); m_hTexSourceBH = m_pEffectBloomH->GetParameterByName(NULL, "g_txSrcColor"); // 5th shader - bloom vertical hr = D3DXCreateEffectFromResource(pDevice, currentModule, "PP_ColorBloomV.fx", NULL, NULL, 0, NULL, &m_pEffectBloomV, NULL); m_hTPostProcessBV = m_pEffectBloomV->GetTechniqueByName("PostProcess"); m_hTexSourceBV = m_pEffectBloomV->GetParameterByName(NULL, "g_txSrcColor"); // 6th shader - gaussian blur horizontal hr = D3DXCreateEffectFromResource(pDevice, currentModule, "PP_ColorGBlurH.fx", NULL, NULL, 0, NULL, &m_pEffectGBlurH, NULL); m_hTPostProcessGBH = m_pEffectGBlurH->GetTechniqueByName("PostProcess"); m_hTexSourceGBH = m_pEffectGBlurH->GetParameterByName(NULL, "g_txSrcColor"); // 7th shader - gaussian blur vertical hr = D3DXCreateEffectFromResource(pDevice, currentModule, "PP_ColorGBlurV.fx", NULL, NULL, 0, NULL, &m_pEffectGBlurV, NULL); m_hTPostProcessGBV = m_pEffectGBlurV->GetTechniqueByName("PostProcess"); m_hTexSourceGBV = m_pEffectGBlurV->GetParameterByName(NULL, "g_txSrcColor"); return D3D_OK; }
const char* tdav_get_current_directory_const() { #if TDAV_UNDER_WINDOWS_RT TSK_DEBUG_ERROR("Not supported"); return tsk_null; #else static char CURRENT_DIR_PATH[MAX_PATH] = { 0 }; static DWORD CURRENT_DIR_PATH_LEN = 0; if(CURRENT_DIR_PATH_LEN == 0) { // NULL HMODULE will get the path to the executable not the DLL. When runing the code in Internet Explorer this is a BIG issue as the path is where IE.exe is installed. #if TDAV_UNDER_WINDOWS_CE static wchar_t TMP_CURRENT_DIR_PATH[MAX_PATH] = { 0 }; if ((CURRENT_DIR_PATH_LEN = GetModuleFileName(GetCurrentModule(), TMP_CURRENT_DIR_PATH, sizeof(TMP_CURRENT_DIR_PATH)))) { if ((CURRENT_DIR_PATH_LEN = wcstombs(CURRENT_DIR_PATH, TMP_CURRENT_DIR_PATH, sizeof(CURRENT_DIR_PATH) - 1))) { int idx = tsk_strLastIndexOf(CURRENT_DIR_PATH, CURRENT_DIR_PATH_LEN, "\\"); if (idx > -1) { CURRENT_DIR_PATH[idx] = '\0'; CURRENT_DIR_PATH_LEN = idx; } } } #else if ((CURRENT_DIR_PATH_LEN = GetModuleFileNameA(GetCurrentModule(), CURRENT_DIR_PATH, sizeof(CURRENT_DIR_PATH)))) { if (!PathRemoveFileSpecA(CURRENT_DIR_PATH)) { TSK_DEBUG_ERROR("PathRemoveFileSpec(%s) failed: %x", CURRENT_DIR_PATH, GetLastError()); memset(CURRENT_DIR_PATH, 0, sizeof(CURRENT_DIR_PATH)); CURRENT_DIR_PATH_LEN = 0; } } #endif /* TDAV_UNDER_WINDOWS_CE */ if (!CURRENT_DIR_PATH_LEN) { TSK_DEBUG_ERROR("GetModuleFileNameA() failed: %x", GetLastError()); } } return CURRENT_DIR_PATH; #endif /* TDAV_UNDER_WINDOWS_RT */ }
/****************************************************** NAME : PrintClassName DESCRIPTION : Displays a class's name INPUTS : 1) Logical name of output 2) The class 3) Flag indicating whether to print carriage-return at end RETURNS : Nothing useful SIDE EFFECTS : Class name printed (and module name too if class is not in current module) NOTES : None ******************************************************/ globle void PrintClassName( char *logicalName, DEFCLASS *theDefclass, BOOLEAN linefeedFlag) { if ((theDefclass->header.whichModule->theModule != ((struct defmodule *) GetCurrentModule())) && (theDefclass->system == 0)) { PrintRouter(logicalName, GetDefmoduleName(theDefclass->header.whichModule->theModule)); PrintRouter(logicalName,"::"); } PrintRouter(logicalName,ValueToString(theDefclass->header.name)); if (linefeedFlag) PrintRouter(logicalName,"\n"); }
void SetCurrentModuleCommand( Environment *theEnv, UDFContext *context, UDFValue *returnValue) { UDFValue theArg; const char *argument; Defmodule *theModule; CLIPSLexeme *oldModuleName; /*=======================*/ /* Set the return value. */ /*=======================*/ theModule = GetCurrentModule(theEnv); if (theModule == NULL) { returnValue->lexemeValue = FalseSymbol(theEnv); return; } oldModuleName = theModule->header.name; returnValue->value = oldModuleName; /*=====================================================*/ /* Check for the correct number and type of arguments. */ /*=====================================================*/ if (! UDFFirstArgument(context,SYMBOL_BIT,&theArg)) { return; } argument = theArg.lexemeValue->contents; /*================================================*/ /* Set the current module to the specified value. */ /*================================================*/ theModule = FindDefmodule(theEnv,argument); if (theModule == NULL) { CantFindItemErrorMessage(theEnv,"defmodule",argument,true); return; } SetCurrentModule(theEnv,theModule); }
void GetCurrentModuleCommand( Environment *theEnv, UDFContext *context, UDFValue *returnValue) { Defmodule *theModule; theModule = GetCurrentModule(theEnv); if (theModule == NULL) { returnValue->lexemeValue = FalseSymbol(theEnv); return; } returnValue->value = theModule->header.name; }
void IsapiServer::serverEntry() { HMODULE module = GetCurrentModule(); char DllPath[_MAX_PATH]; char *pDllPath = DllPath; GetModuleFileName(module, DllPath, _MAX_PATH); FreeLibrary(module); try { main(1, &pDllPath); terminationMsg = mainReturnedReply; if (hasConfiguration()) log("fatal") << "ISAPI: main() returned"; } catch (std::exception &e) { terminationMsg = uncaughtExceptionReply; if (hasConfiguration()) log("fatal") << "ISAPI: uncaught main() exception: " << e.what(); } catch(...) { terminationMsg = uncaughtExceptionReply; if (hasConfiguration()) log("fatal") << "ISAPI: unknown uncaught main() exception"; } setTerminated(); }
bool AnimaMouseInteractor::Install(long windowId, AnimaEngine* engine) { AnimaLogger::LogMessage("Installing mouse interactor..."); if (_installed) { AnimaLogger::LogMessage("Mouse interactor already installed"); return true; } _windowId = windowId; _engine = engine; HMODULE module = GetCurrentModule(); _windowsProcHook = SetWindowsHookEx(WH_CALLWNDPROC, WindowsProcCallback, module, NULL); if (_windowsProcHook == NULL) { AnimaLogger::LogMessage("Unable to install mouse interactor"); return false; } _messageProcHook = SetWindowsHookEx(WH_GETMESSAGE, MessageProcCallback, module, NULL); if (_messageProcHook == NULL) { AnimaLogger::LogMessage("Unable to install mouse interactor"); return false; } // Aggingo questo interactor alla lista di interactor installati _installedInteractors[windowId] = this; _installed = true; AnimaLogger::LogMessage("Mouse interactor installed succesfully"); return true; }
DWORD LoadMQ2Plugin(const PCHAR pszFilename,BOOL bCustom) { CHAR Filename[MAX_PATH]={0}; strcpy_s(Filename,pszFilename); _strlwr_s(Filename); PCHAR Temp=strstr(Filename,".dll"); if (Temp) Temp[0]=0; if (!_stricmp(Filename,"mq2warp")) // ^_^ { return 0; } CHAR TheFilename[MAX_STRING]={0}; sprintf_s(TheFilename,"%s.dll",Filename); if(HMODULE hThemod = GetModuleHandle(TheFilename)) { DebugSpew("LoadMQ2Plugin(0)(%s) already loaded",TheFilename); return 2; } CAutoLock Lock(&gPluginCS); DebugSpew("LoadMQ2Plugin(%s)",Filename); CHAR FullFilename[MAX_STRING]={0}; sprintf_s(FullFilename,"%s\\%s.dll",gszINIPath,Filename); HMODULE hmod=LoadLibrary(FullFilename); if (!hmod) { DebugSpew("LoadMQ2Plugin(%s) Failed",Filename); return 0; } //im disabling this check in debug builds because i can't just make a minor change and rebuild just mq2main //without having to actually rebuild ALL my plugins even though its technically not needed for them to work -eqmule sep 11 2016 #ifndef _DEBUG if (!mq2mainstamp) { mq2mainstamp = checkme((char*)GetCurrentModule()); } if (mq2mainstamp > checkme((char*)hmod)) { char tmpbuff[MAX_PATH]; sprintf_s(tmpbuff, "Please recompile %s -- it is out of date with respect to mq2main (%d>%d)", FullFilename, mq2mainstamp, checkme((char*)hmod)); DebugSpew("%s", tmpbuff); MessageBoxA(NULL, tmpbuff, "Plugin Load Failed", MB_OK); FreeLibrary(hmod); return 0; } #endif // !_DEBUG PMQPLUGIN pPlugin=pPlugins; while(pPlugin) { if (hmod==pPlugin->hModule) { DebugSpew("LoadMQ2Plugin(%s) already loaded",Filename); // LoadLibrary count must match FreeLibrary count for unloading to work. FreeLibrary(hmod); return 2; // already loaded } pPlugin=pPlugin->pNext; } pPlugin = new MQPLUGIN; memset(pPlugin,0,sizeof(MQPLUGIN)); pPlugin->bCustom=bCustom; pPlugin->hModule=hmod; strcpy_s(pPlugin->szFilename,Filename); pPlugin->Initialize=(fMQInitializePlugin)GetProcAddress(hmod,"InitializePlugin"); pPlugin->Shutdown=(fMQShutdownPlugin)GetProcAddress(hmod,"ShutdownPlugin"); pPlugin->IncomingChat=(fMQIncomingChat)GetProcAddress(hmod,"OnIncomingChat"); pPlugin->Pulse=(fMQPulse)GetProcAddress(hmod,"OnPulse"); pPlugin->WriteChatColor=(fMQWriteChatColor)GetProcAddress(hmod,"OnWriteChatColor"); pPlugin->Zoned=(fMQZoned)GetProcAddress(hmod,"OnZoned"); pPlugin->CleanUI=(fMQCleanUI)GetProcAddress(hmod,"OnCleanUI"); pPlugin->ReloadUI=(fMQReloadUI)GetProcAddress(hmod,"OnReloadUI"); pPlugin->DrawHUD=(fMQDrawHUD)GetProcAddress(hmod,"OnDrawHUD"); pPlugin->SetGameState=(fMQSetGameState)GetProcAddress(hmod,"SetGameState"); pPlugin->AddSpawn=(fMQSpawn)GetProcAddress(hmod,"OnAddSpawn"); pPlugin->RemoveSpawn=(fMQSpawn)GetProcAddress(hmod,"OnRemoveSpawn"); pPlugin->AddGroundItem=(fMQGroundItem)GetProcAddress(hmod,"OnAddGroundItem"); pPlugin->RemoveGroundItem=(fMQGroundItem)GetProcAddress(hmod,"OnRemoveGroundItem"); pPlugin->BeginZone=(fMQBeginZone)GetProcAddress(hmod,"OnBeginZone"); pPlugin->EndZone=(fMQEndZone)GetProcAddress(hmod,"OnEndZone"); float *ftmp = (float*) GetProcAddress(hmod,"?MQ2Version@@3MA"); if (ftmp) pPlugin->fpVersion = *ftmp; else pPlugin->fpVersion = 1.0; if (pPlugin->Initialize) pPlugin->Initialize(); PluginCmdSort(); if (pPlugin->SetGameState) { pPlugin->SetGameState(GetGameState()); } if (pPlugin->AddSpawn && GetGameState()==GAMESTATE_INGAME) { PSPAWNINFO pSpawn=(PSPAWNINFO)pSpawnList; while(pSpawn) { pPlugin->AddSpawn(pSpawn); pSpawn=pSpawn->pNext; } } if (pPlugin->AddGroundItem && GetGameState()==GAMESTATE_INGAME) { PGROUNDITEM pItem=*(PGROUNDITEM*)pItemList; while(pItem) { pPlugin->AddGroundItem(pItem); pItem=pItem->pNext; } } pPlugin->pLast=0; pPlugin->pNext=pPlugins; if (pPlugins) pPlugins->pLast=pPlugin; pPlugins=pPlugin; sprintf_s(FullFilename,"%s-AutoExec",Filename); LoadCfgFile(FullFilename,false); return 1; }
globle struct expr *GetRHSPattern( char *readSource, struct token *tempToken, int *error, int constantsOnly, int readFirstParen, int checkFirstParen, int endType) { struct expr *lastOne = NULL; struct expr *nextOne, *firstOne, *argHead = NULL; int printError, count; struct deftemplate *theDeftemplate; struct symbolHashNode *templateName; /*=================================================*/ /* Get the opening parenthesis of the RHS pattern. */ /*=================================================*/ *error = FALSE; if (readFirstParen) GetToken(readSource,tempToken); if (checkFirstParen) { if (tempToken->type == endType) return(NULL); if (tempToken->type != LPAREN) { SyntaxErrorMessage("RHS patterns"); *error = TRUE; return(NULL); } } /*======================================================*/ /* The first field of an asserted fact must be a symbol */ /* (but not = or : which have special significance). */ /*======================================================*/ GetToken(readSource,tempToken); if (tempToken->type != SYMBOL) { SyntaxErrorMessage("first field of a RHS pattern"); *error = TRUE; return(NULL); } else if ((strcmp(ValueToString(tempToken->value),"=") == 0) || (strcmp(ValueToString(tempToken->value),":") == 0)) { SyntaxErrorMessage("first field of a RHS pattern"); *error = TRUE; return(NULL); } /*=========================================================*/ /* Check to see if the relation name is a reserved symbol. */ /*=========================================================*/ templateName = (struct symbolHashNode *) tempToken->value; if (ReservedPatternSymbol(ValueToString(templateName),NULL)) { ReservedPatternSymbolErrorMsg(ValueToString(templateName),"a relation name"); *error = TRUE; return(NULL); } /*============================================================*/ /* A module separator in the name is illegal in this context. */ /*============================================================*/ if (FindModuleSeparator(ValueToString(templateName))) { IllegalModuleSpecifierMessage(); *error = TRUE; return(NULL); } /*=============================================================*/ /* Determine if there is an associated deftemplate. If so, let */ /* the deftemplate parsing functions parse the RHS pattern and */ /* then return the fact pattern that was parsed. */ /*=============================================================*/ theDeftemplate = (struct deftemplate *) FindImportedConstruct("deftemplate",NULL,ValueToString(templateName), &count,TRUE,NULL); if (count > 1) { AmbiguousReferenceErrorMessage("deftemplate",ValueToString(templateName)); *error = TRUE; return(NULL); } /*======================================================*/ /* If no deftemplate exists with the specified relation */ /* name, then create an implied deftemplate. */ /*======================================================*/ if (theDeftemplate == NULL) #if (! BLOAD_ONLY) && (! RUN_TIME) { #if BLOAD || BLOAD_AND_BSAVE if ((Bloaded()) && (! CheckSyntaxMode)) { NoSuchTemplateError(ValueToString(templateName)); *error = TRUE; return(NULL); } #endif #if DEFMODULE_CONSTRUCT if (FindImportExportConflict("deftemplate",((struct defmodule *) GetCurrentModule()),ValueToString(templateName))) { ImportExportConflictMessage("implied deftemplate",ValueToString(templateName),NULL,NULL); *error = TRUE; return(NULL); } #endif if (! CheckSyntaxMode) { theDeftemplate = CreateImpliedDeftemplate((SYMBOL_HN *) templateName,TRUE); } } #else { NoSuchTemplateError(ValueToString(templateName)); *error = TRUE; return(NULL); } #endif /*=========================================*/ /* If an explicit deftemplate exists, then */ /* parse the fact as a deftemplate fact. */ /*=========================================*/ if ((theDeftemplate != NULL) && (theDeftemplate->implied == FALSE)) { firstOne = GenConstant(DEFTEMPLATE_PTR,theDeftemplate); firstOne->nextArg = ParseAssertTemplate(readSource,tempToken, error,endType, constantsOnly,theDeftemplate); if (*error) { ReturnExpression(firstOne); firstOne = NULL; } return(firstOne); } /*========================================*/ /* Parse the fact as an ordered RHS fact. */ /*========================================*/ firstOne = GenConstant(DEFTEMPLATE_PTR,theDeftemplate); #if (! RUN_TIME) && (! BLOAD_ONLY) SavePPBuffer(" "); #endif while ((nextOne = GetAssertArgument(readSource,tempToken, error,endType,constantsOnly,&printError)) != NULL) { if (argHead == NULL) argHead = nextOne; else lastOne->nextArg = nextOne; lastOne = nextOne; #if (! RUN_TIME) && (! BLOAD_ONLY) SavePPBuffer(" "); #endif } /*===========================================================*/ /* If an error occurred, set the error flag and return NULL. */ /*===========================================================*/ if (*error) { if (printError) SyntaxErrorMessage("RHS patterns"); ReturnExpression(firstOne); ReturnExpression(argHead); return(NULL); } /*=====================================*/ /* Fix the pretty print representation */ /* of the RHS ordered fact. */ /*=====================================*/ #if (! RUN_TIME) && (! BLOAD_ONLY) PPBackup(); PPBackup(); SavePPBuffer(tempToken->printForm); #endif /*==========================================================*/ /* Ordered fact assertions are processed by stuffing all of */ /* the fact's proposition (except the relation name) into a */ /* single multifield slot. */ /*==========================================================*/ firstOne->nextArg = GenConstant(FACT_STORE_MULTIFIELD,AddBitMap("\0",1)); firstOne->nextArg->argList = argHead; /*==============================*/ /* Return the RHS ordered fact. */ /*==============================*/ return(firstOne); }
/************************************************************* NAME : FormChain DESCRIPTION : Builds a list of classes to be used in instance queries - uses parse form. INPUTS : 1) Name of calling function for error msgs 2) Data object - must be a symbol or a multifield value containing all symbols The symbols must be names of existing classes RETURNS : The query chain, or NULL on errors SIDE EFFECTS : Memory allocated for chain Busy count incremented for all classes NOTES : None *************************************************************/ static QUERY_CLASS *FormChain( char *func, DATA_OBJECT *val) { DEFCLASS *cls; QUERY_CLASS *head,*bot,*tmp; register long i,end; /* 6.04 Bug Fix */ char *className; struct defmodule *currentModule; currentModule = ((struct defmodule *) GetCurrentModule()); if (val->type == DEFCLASS_PTR) { IncrementDefclassBusyCount((void *) val->value); head = get_struct(query_class); head->cls = (DEFCLASS *) val->value; if (DefclassInScope(head->cls,currentModule)) head->theModule = currentModule; else head->theModule = head->cls->header.whichModule->theModule; head->chain = NULL; head->nxt = NULL; return(head); } if (val->type == SYMBOL) { /* =============================================== Allow instance-set query restrictions to have a module specifier as part of the class name, but search imported defclasses too if a module specifier is not given =============================================== */ cls = LookupDefclassByMdlOrScope(DOPToString(val)); if (cls == NULL) { ClassExistError(func,DOPToString(val)); return(NULL); } IncrementDefclassBusyCount((void *) cls); head = get_struct(query_class); head->cls = cls; if (DefclassInScope(head->cls,currentModule)) head->theModule = currentModule; else head->theModule = head->cls->header.whichModule->theModule; head->chain = NULL; head->nxt = NULL; return(head); } if (val->type == MULTIFIELD) { head = bot = NULL; end = GetpDOEnd(val); for (i = GetpDOBegin(val) ; i <= end ; i++) { if (GetMFType(val->value,i) == SYMBOL) { className = ValueToString(GetMFValue(val->value,i)); cls = LookupDefclassByMdlOrScope(className); if (cls == NULL) { ClassExistError(func,className); DeleteQueryClasses(head); return(NULL); } } else { DeleteQueryClasses(head); return(NULL); } IncrementDefclassBusyCount((void *) cls); tmp = get_struct(query_class); tmp->cls = cls; if (DefclassInScope(tmp->cls,currentModule)) tmp->theModule = currentModule; else tmp->theModule = tmp->cls->header.whichModule->theModule; tmp->chain = NULL; tmp->nxt = NULL; if (head == NULL) head = tmp; else bot->chain = tmp; bot = tmp; } return(head); } return(NULL); }
/************************************************************ NAME : ValidDeffunctionName DESCRIPTION : Determines if a new deffunction of the given name can be defined in the current module INPUTS : The new deffunction name RETURNS : TRUE if OK, FALSE otherwise SIDE EFFECTS : Error message printed if not OK NOTES : GetConstructNameAndComment() (called before this function) ensures that the deffunction name does not conflict with one from another module ************************************************************/ static BOOLEAN ValidDeffunctionName( char *theDeffunctionName) { struct constructHeader *theDeffunction; #if DEFGENERIC_CONSTRUCT struct defmodule *theModule; struct constructHeader *theDefgeneric; #endif /* ============================================ A deffunction cannot be named the same as a construct type, e.g, defclass, defrule, etc. ============================================ */ if (FindConstruct(theDeffunctionName) != NULL) { PrintErrorID("DFFNXPSR",1,FALSE); PrintRouter(WERROR,"Deffunctions are not allowed to replace constructs.\n"); return(FALSE); } /* ============================================ A deffunction cannot be named the same as a pre-defined system function, e.g, watch, list-defrules, etc. ============================================ */ if (FindFunction(theDeffunctionName) != NULL) { PrintErrorID("DFFNXPSR",2,FALSE); PrintRouter(WERROR,"Deffunctions are not allowed to replace external functions.\n"); return(FALSE); } #if DEFGENERIC_CONSTRUCT /* ============================================ A deffunction cannot be named the same as a generic function (either in this module or imported from another) ============================================ */ theDefgeneric = (struct constructHeader *) LookupDefgenericInScope(theDeffunctionName); if (theDefgeneric != NULL) { theModule = GetConstructModuleItem(theDefgeneric)->theModule; if (theModule != ((struct defmodule *) GetCurrentModule())) { PrintErrorID("DFFNXPSR",5,FALSE); PrintRouter(WERROR,"Defgeneric "); PrintRouter(WERROR,GetDefgenericName((void *) theDefgeneric)); PrintRouter(WERROR," imported from module "); PrintRouter(WERROR,GetDefmoduleName((void *) theModule)); PrintRouter(WERROR," conflicts with this deffunction.\n"); return(FALSE); } else { PrintErrorID("DFFNXPSR",3,FALSE); PrintRouter(WERROR,"Deffunctions are not allowed to replace generic functions.\n"); } return(FALSE); } #endif theDeffunction = (struct constructHeader *) FindDeffunction(theDeffunctionName); if (theDeffunction != NULL) { /* =========================================== And a deffunction in the current module can only be redefined if it is not executing. =========================================== */ if (((DEFFUNCTION *) theDeffunction)->executing) { PrintErrorID("DFNXPSR",4,FALSE); PrintRouter(WERROR,"Deffunction "); PrintRouter(WERROR,GetDeffunctionName((void *) theDeffunction)); PrintRouter(WERROR," may not be redefined while it is executing.\n"); return(FALSE); } } return(TRUE); }
std::string GetModuleFile(std::string moduleName) { std::string moduleFilePath = ""; // this will only be used if moduleFilePath stays empty const char* error = NULL; #if defined(__linux__) || defined(__APPLE__) || defined(__FreeBSD__) #ifdef __APPLE__ #define SHARED_LIBRARY_EXTENSION "dylib" #else #define SHARED_LIBRARY_EXTENSION "so" #endif void* moduleAddress = NULL; // find an address in the module we are looking for if (moduleName.empty()) { // look for current module moduleAddress = (void*) GetModuleFile; } else { // look for specified module // add extension if it is not in the file name // it could also be "libXZY.so-1.2.3" // -> does not have to be the end, my friend if (moduleName.find("." SHARED_LIBRARY_EXTENSION) == std::string::npos) { moduleName = moduleName + "." SHARED_LIBRARY_EXTENSION; } // will not not try to load, but return the libs address // if it is already loaded, NULL otherwise moduleAddress = dlopen(moduleName.c_str(), RTLD_LAZY | RTLD_NOLOAD); if (moduleAddress == NULL) { // if not found, try with "lib" prefix moduleName = "lib" + moduleName; moduleAddress = dlopen(moduleName.c_str(), RTLD_LAZY | RTLD_NOLOAD); } } if (moduleAddress != NULL) { // fetch info about the module containing the address we just evaluated Dl_info moduleInfo; const int ret = dladdr(moduleAddress, &moduleInfo); if ((ret != 0) && (moduleInfo.dli_fname != NULL)) { moduleFilePath = moduleInfo.dli_fname; // required on APPLE; does not hurt elsewhere moduleFilePath = GetRealPath(moduleFilePath); } else { error = dlerror(); if (error == NULL) { error = "Unknown"; } } } else { error = "Not loaded"; } #elif WIN32 HMODULE hModule = NULL; if (moduleName.empty()) { hModule = GetCurrentModule(); } else { // If this fails, we get a NULL handle hModule = GetModuleHandle(moduleName.c_str()); } if (hModule != NULL) { // fetch module file name TCHAR moduleFile[MAX_PATH+1]; const int ret = ::GetModuleFileName(hModule, moduleFile, sizeof(moduleFile)); if ((ret != 0) && (ret != sizeof(moduleFile))) { moduleFilePath = std::string(moduleFile); } else { error = + "Unknown"; } } else { error = "Not found"; } #else #warning implement this (or use linux version) #endif if (moduleFilePath.empty()) { if (moduleName.empty()) { moduleName = "<current>"; } LOG_L(L_WARNING, "Failed to get file path of the module \"%s\", reason: %s", moduleName.c_str(), error); } return UnQuote(moduleFilePath); }
void Hook() { extern FARJMP Old_SLGetWindowsInformationDWORD, Stub_SLGetWindowsInformationDWORD; extern SLGETWINDOWSINFORMATIONDWORD _SLGetWindowsInformationDWORD; extern HMODULE hTermSrv; extern HMODULE hSLC; extern PLATFORM_DWORD TermSrvBase; extern FILE_VERSION FV; extern wchar_t LogFile[256]; AlreadyHooked = true; char *Log; wchar_t ConfigFile[256] = { 0x00 }; WriteToLog("Loading configuration...\r\n"); GetModuleFileName(GetCurrentModule(), ConfigFile, 255); for (DWORD i = wcslen(ConfigFile); i > 0; i--) { if (ConfigFile[i] == '\\') { memset(&ConfigFile[i + 1], 0x00, ((256 - (i + 1))) * 2); memcpy(&ConfigFile[i + 1], L"rdpwrap.ini", strlen("rdpwrap.ini") * 2); break; } } Log = new char[1024]; wsprintfA(Log, "Configuration file: %S\r\n", ConfigFile); WriteToLog(Log); delete[] Log; IniFile = new INI_FILE(ConfigFile); // TODO: implement this if (IniFile == NULL) { WriteToLog("Error: Failed to load configuration\r\n"); return; } INI_VAR_STRING LogFileVar; if(!(IniFile->GetVariableInSection("Main", "LogFile", &LogFileVar))) { GetModuleFileName(GetCurrentModule(), LogFile, 255); for(DWORD i = wcslen(LogFile); i > 0; i--) { if(LogFile[i] == '\\') { memset(&LogFile[i+1], 0x00, ((256-(i+1)))*2); memcpy(&LogFile[i+1], L"rdpwrap.txt", strlen("rdpwrap.txt")*2); break; } } } else { // TODO: Change it before add UNICODE in IniFile wchar_t wcLogFile[256]; memset(wcLogFile, 0x00, 256); mbstowcs(wcLogFile, LogFileVar.Value, 255); wcscpy(LogFile, wcLogFile); } SIZE_T bw; WORD Ver = 0; PLATFORM_DWORD TermSrvSize, SignPtr; FARJMP Jump; WriteToLog("Initializing RDP Wrapper...\r\n"); hTermSrv = LoadLibrary(L"termsrv.dll"); if (hTermSrv == 0) { WriteToLog("Error: Failed to load Terminal Services library\r\n"); return; } _ServiceMain = (SERVICEMAIN)GetProcAddress(hTermSrv, "ServiceMain"); _SvchostPushServiceGlobals = (SVCHOSTPUSHSERVICEGLOBALS)GetProcAddress(hTermSrv, "SvchostPushServiceGlobals"); Log = new char[4096]; wsprintfA(Log, "Base addr: 0x%p\r\n" "SvcMain: termsrv.dll+0x%p\r\n" "SvcGlobals: termsrv.dll+0x%p\r\n", hTermSrv, (PLATFORM_DWORD)_ServiceMain - (PLATFORM_DWORD)hTermSrv, (PLATFORM_DWORD)_SvchostPushServiceGlobals - (PLATFORM_DWORD)hTermSrv); WriteToLog(Log); delete[] Log; // check termsrv version if (GetModuleVersion(L"termsrv.dll", &FV)) { Ver = (BYTE)FV.wVersion.Minor | ((BYTE)FV.wVersion.Major << 8); } else { // check NT version // Ver = GetVersion(); // deprecated // Ver = ((Ver & 0xFF) << 8) | ((Ver & 0xFF00) >> 8); } if (Ver == 0) { WriteToLog("Error: Failed to detect Terminal Services version\r\n"); return; } Log = new char[1024]; wsprintfA(Log, "Version: %d.%d.%d.%d\r\n", FV.wVersion.Major, FV.wVersion.Minor, FV.Release, FV.Build); WriteToLog(Log); delete[] Log; // temporarily freeze threads WriteToLog("Freezing threads...\r\n"); SetThreadsState(false); bool Bool; if (!(IniFile->GetVariableInSection("Main", "SLPolicyHookNT60", &Bool))) Bool = true; if ((Ver == 0x0600) && Bool) { // Windows Vista // uses SL Policy API (slc.dll) // load slc.dll and hook function hSLC = LoadLibrary(L"slc.dll"); _SLGetWindowsInformationDWORD = (SLGETWINDOWSINFORMATIONDWORD)GetProcAddress(hSLC, "SLGetWindowsInformationDWORD"); if (_SLGetWindowsInformationDWORD != INVALID_HANDLE_VALUE) { // rewrite original function to call our function (make hook) WriteToLog("Hook SLGetWindowsInformationDWORD\r\n"); #ifdef _WIN64 Stub_SLGetWindowsInformationDWORD.MovOp = 0x48; Stub_SLGetWindowsInformationDWORD.MovRegArg = 0xB8; Stub_SLGetWindowsInformationDWORD.MovArg = (PLATFORM_DWORD)New_SLGetWindowsInformationDWORD; Stub_SLGetWindowsInformationDWORD.PushRaxOp = 0x50; Stub_SLGetWindowsInformationDWORD.RetOp = 0xC3; #else Stub_SLGetWindowsInformationDWORD.PushOp = 0x68; Stub_SLGetWindowsInformationDWORD.PushArg = (PLATFORM_DWORD)New_SLGetWindowsInformationDWORD; Stub_SLGetWindowsInformationDWORD.RetOp = 0xC3; #endif ReadProcessMemory(GetCurrentProcess(), _SLGetWindowsInformationDWORD, &Old_SLGetWindowsInformationDWORD, sizeof(FARJMP), &bw); WriteProcessMemory(GetCurrentProcess(), _SLGetWindowsInformationDWORD, &Stub_SLGetWindowsInformationDWORD, sizeof(FARJMP), &bw); } } if (!(IniFile->GetVariableInSection("Main", "SLPolicyHookNT61", &Bool))) Bool = true; if ((Ver == 0x0601) && Bool) { // Windows 7 // uses SL Policy API (slc.dll) // load slc.dll and hook function hSLC = LoadLibrary(L"slc.dll"); _SLGetWindowsInformationDWORD = (SLGETWINDOWSINFORMATIONDWORD)GetProcAddress(hSLC, "SLGetWindowsInformationDWORD"); if (_SLGetWindowsInformationDWORD != INVALID_HANDLE_VALUE) { // rewrite original function to call our function (make hook) WriteToLog("Hook SLGetWindowsInformationDWORD\r\n"); #ifdef _WIN64 Stub_SLGetWindowsInformationDWORD.MovOp = 0x48; Stub_SLGetWindowsInformationDWORD.MovRegArg = 0xB8; Stub_SLGetWindowsInformationDWORD.MovArg = (PLATFORM_DWORD)New_SLGetWindowsInformationDWORD; Stub_SLGetWindowsInformationDWORD.PushRaxOp = 0x50; Stub_SLGetWindowsInformationDWORD.RetOp = 0xC3; #else Stub_SLGetWindowsInformationDWORD.PushOp = 0x68; Stub_SLGetWindowsInformationDWORD.PushArg = (PLATFORM_DWORD)New_SLGetWindowsInformationDWORD; Stub_SLGetWindowsInformationDWORD.RetOp = 0xC3; #endif ReadProcessMemory(GetCurrentProcess(), _SLGetWindowsInformationDWORD, &Old_SLGetWindowsInformationDWORD, sizeof(FARJMP), &bw); WriteProcessMemory(GetCurrentProcess(), _SLGetWindowsInformationDWORD, &Stub_SLGetWindowsInformationDWORD, sizeof(FARJMP), &bw); } } if (Ver == 0x0602) { // Windows 8 // uses SL Policy internal unexported function // load slc.dll and get function // (will be used on intercepting undefined values) hSLC = LoadLibrary(L"slc.dll"); _SLGetWindowsInformationDWORD = (SLGETWINDOWSINFORMATIONDWORD)GetProcAddress(hSLC, "SLGetWindowsInformationDWORD"); } if (Ver == 0x0603) { // Windows 8.1 // uses SL Policy internal inline code } if (Ver == 0x0604) { // Windows 10 // uses SL Policy internal inline code } char *Sect; INI_VAR_STRING PatchName; INI_VAR_BYTEARRAY Patch; Sect = new char[256]; memset(Sect, 0x00, 256); wsprintfA(Sect, "%d.%d.%d.%d", FV.wVersion.Major, FV.wVersion.Minor, FV.Release, FV.Build); if (IniFile->SectionExists(Sect)) { if (GetModuleCodeSectionInfo(hTermSrv, &TermSrvBase, &TermSrvSize)) { #ifdef _WIN64 if (!(IniFile->GetVariableInSection(Sect, "LocalOnlyPatch.x64", &Bool))) Bool = false; #else if (!(IniFile->GetVariableInSection(Sect, "LocalOnlyPatch.x86", &Bool))) Bool = false; #endif if (Bool) { WriteToLog("Patch CEnforcementCore::GetInstanceOfTSLicense\r\n"); Bool = false; #ifdef _WIN64 SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "LocalOnlyOffset.x64", 0)); Bool = IniFile->GetVariableInSection(Sect, "LocalOnlyCode.x64", &PatchName); #else SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "LocalOnlyOffset.x86", 0)); Bool = IniFile->GetVariableInSection(Sect, "LocalOnlyCode.x86", &PatchName); #endif if (Bool) Bool = IniFile->GetVariableInSection("PatchCodes", PatchName.Value, &Patch); if (Bool && (SignPtr > TermSrvBase)) WriteProcessMemory(GetCurrentProcess(), (LPVOID)SignPtr, Patch.Value, Patch.ArraySize, &bw); } #ifdef _WIN64 if (!(IniFile->GetVariableInSection(Sect, "SingleUserPatch.x64", &Bool))) Bool = false; #else if (!(IniFile->GetVariableInSection(Sect, "SingleUserPatch.x86", &Bool))) Bool = false; #endif if (Bool) { WriteToLog("Patch CSessionArbitrationHelper::IsSingleSessionPerUserEnabled\r\n"); Bool = false; #ifdef _WIN64 SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "SingleUserOffset.x64", 0)); Bool = IniFile->GetVariableInSection(Sect, "SingleUserCode.x64", &PatchName); #else SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "SingleUserOffset.x86", 0)); Bool = IniFile->GetVariableInSection(Sect, "SingleUserCode.x86", &PatchName); #endif if (Bool) Bool = IniFile->GetVariableInSection("PatchCodes", PatchName.Value, &Patch); if (Bool && (SignPtr > TermSrvBase)) WriteProcessMemory(GetCurrentProcess(), (LPVOID)SignPtr, Patch.Value, Patch.ArraySize, &bw); } #ifdef _WIN64 if (!(IniFile->GetVariableInSection(Sect, "DefPolicyPatch.x64", &Bool))) Bool = false; #else if (!(IniFile->GetVariableInSection(Sect, "DefPolicyPatch.x86", &Bool))) Bool = false; #endif if (Bool) { WriteToLog("Patch CDefPolicy::Query\r\n"); Bool = false; #ifdef _WIN64 SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "DefPolicyOffset.x64", 0)); Bool = IniFile->GetVariableInSection(Sect, "DefPolicyCode.x64", &PatchName); #else SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "DefPolicyOffset.x86", 0)); Bool = IniFile->GetVariableInSection(Sect, "DefPolicyCode.x86", &PatchName); #endif if (Bool) Bool = IniFile->GetVariableInSection("PatchCodes", PatchName.Value, &Patch); if (Bool && (SignPtr > TermSrvBase)) WriteProcessMemory(GetCurrentProcess(), (LPVOID)SignPtr, Patch.Value, Patch.ArraySize, &bw); } #ifdef _WIN64 if (!(IniFile->GetVariableInSection(Sect, "SLPolicyInternal.x64", &Bool))) Bool = false; #else if (!(IniFile->GetVariableInSection(Sect, "SLPolicyInternal.x86", &Bool))) Bool = false; #endif if (Bool) { WriteToLog("Hook SLGetWindowsInformationDWORDWrapper\r\n"); char *FuncName; FuncName = new char[1024]; #ifdef _WIN64 SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "SLPolicyOffset.x64", 0)); Jump.MovOp = 0x48; Jump.MovRegArg = 0xB8; Jump.MovArg = (PLATFORM_DWORD)New_Win8SL; Jump.PushRaxOp = 0x50; Jump.RetOp = 0xC3; INIReadString(IniFile, Sect, "SLPolicyFunc.x64", "New_Win8SL", FuncName, 1024); if (strcmp(FuncName, "New_Win8SL")) { Jump.MovArg = (PLATFORM_DWORD)New_Win8SL; } #else SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "SLPolicyOffset.x86", 0)); Jump.PushOp = 0x68; Jump.PushArg = (PLATFORM_DWORD)New_Win8SL; Jump.RetOp = 0xC3; INIReadString(IniFile, Sect, "SLPolicyFunc.x86", "New_Win8SL", FuncName, 1024); if (strcmp(FuncName, "New_Win8SL")) { Jump.PushArg = (PLATFORM_DWORD)New_Win8SL; } if (strcmp(FuncName, "New_Win8SL_CP")) { Jump.PushArg = (PLATFORM_DWORD)New_Win8SL_CP; } #endif delete[] FuncName; if (SignPtr > TermSrvBase) WriteProcessMemory(GetCurrentProcess(), (LPVOID)SignPtr, &Jump, sizeof(FARJMP), &bw); } #ifdef _WIN64 if (!(IniFile->GetVariableInSection(Sect, "SLInitHook.x64", &Bool))) Bool = false; #else if (!(IniFile->GetVariableInSection(Sect, "SLInitHook.x86", &Bool))) Bool = false; #endif if (Bool) { WriteToLog("Hook CSLQuery::Initialize\r\n"); char *FuncName; FuncName = new char[1024]; #ifdef _WIN64 SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "SLInitOffset.x64", 0)); Jump.MovOp = 0x48; Jump.MovRegArg = 0xB8; Jump.MovArg = (PLATFORM_DWORD)New_CSLQuery_Initialize; Jump.PushRaxOp = 0x50; Jump.RetOp = 0xC3; INIReadString(IniFile, Sect, "SLInitFunc.x64", "New_CSLQuery_Initialize", FuncName, 1024); if (strcmp(FuncName, "New_CSLQuery_Initialize")) { Jump.MovArg = (PLATFORM_DWORD)New_CSLQuery_Initialize; } #else SignPtr = (PLATFORM_DWORD)(TermSrvBase + INIReadDWordHex(IniFile, Sect, "SLInitOffset.x86", 0)); Jump.PushOp = 0x68; Jump.PushArg = (PLATFORM_DWORD)New_CSLQuery_Initialize; Jump.RetOp = 0xC3; INIReadString(IniFile, Sect, "SLInitFunc.x86", "New_CSLQuery_Initialize", FuncName, 1024); if (strcmp(FuncName, "New_CSLQuery_Initialize")) { Jump.PushArg = (PLATFORM_DWORD)New_CSLQuery_Initialize; } #endif delete[] FuncName; if (SignPtr > TermSrvBase) WriteProcessMemory(GetCurrentProcess(), (LPVOID)SignPtr, &Jump, sizeof(FARJMP), &bw); } } } delete[] Sect; WriteToLog("Resumimg threads...\r\n"); SetThreadsState(true); return; }
/***************************************************** NAME : PerformMessage DESCRIPTION : Calls core framework for a message INPUTS : 1) Caller's result buffer 2) Message argument expressions (including implicit object) 3) Message name RETURNS : Nothing useful SIDE EFFECTS : Any side-effects of message execution and caller's result buffer set NOTES : None *****************************************************/ static void PerformMessage( DATA_OBJECT *result, EXPRESSION *args, SYMBOL_HN *mname) { int oldce; HANDLER_LINK *oldCore; DEFCLASS *cls = NULL; INSTANCE_TYPE *ins = NULL; SYMBOL_HN *oldName; #if PROFILING_FUNCTIONS struct profileFrameInfo profileFrame; #endif result->type = SYMBOL; result->value = FalseSymbol; EvaluationError = FALSE; if (HaltExecution) return; oldce = ExecutingConstruct(); SetExecutingConstruct(TRUE); oldName = CurrentMessageName; CurrentMessageName = mname; CurrentEvaluationDepth++; PushProcParameters(args,CountArguments(args), ValueToString(CurrentMessageName),"message", UnboundHandlerErr); if (EvaluationError) { CurrentEvaluationDepth--; CurrentMessageName = oldName; PeriodicCleanup(FALSE,TRUE); SetExecutingConstruct(oldce); return; } if (ProcParamArray->type == INSTANCE_ADDRESS) { ins = (INSTANCE_TYPE *) ProcParamArray->value; if (ins->garbage == 1) { StaleInstanceAddress("send",0); SetEvaluationError(TRUE); } else if (DefclassInScope(ins->cls,(struct defmodule *) GetCurrentModule()) == FALSE) NoInstanceError(ValueToString(ins->name),"send"); else { cls = ins->cls; ins->busy++; } } else if (ProcParamArray->type == INSTANCE_NAME) { ins = FindInstanceBySymbol((SYMBOL_HN *) ProcParamArray->value); if (ins == NULL) { PrintErrorID("MSGPASS",2,FALSE); PrintRouter(WERROR,"No such instance "); PrintRouter(WERROR,ValueToString((SYMBOL_HN *) ProcParamArray->value)); PrintRouter(WERROR," in function send.\n"); SetEvaluationError(TRUE); } else { ProcParamArray->value = (void *) ins; ProcParamArray->type = INSTANCE_ADDRESS; cls = ins->cls; ins->busy++; } } else if ((cls = PrimitiveClassMap[ProcParamArray->type]) == NULL) { SystemError("MSGPASS",1); ExitRouter(EXIT_FAILURE); } if (EvaluationError) { PopProcParameters(); CurrentEvaluationDepth--; CurrentMessageName = oldName; PeriodicCleanup(FALSE,TRUE); SetExecutingConstruct(oldce); return; } oldCore = TopOfCore; TopOfCore = FindApplicableHandlers(cls,mname); if (TopOfCore != NULL) { HANDLER_LINK *oldCurrent,*oldNext; oldCurrent = CurrentCore; oldNext = NextInCore; #if IMPERATIVE_MESSAGE_HANDLERS if (TopOfCore->hnd->type == MAROUND) { CurrentCore = TopOfCore; NextInCore = TopOfCore->nxt; #if DEBUGGING_FUNCTIONS if (WatchMessages) WatchMessage(WTRACE,BEGIN_TRACE); if (CurrentCore->hnd->trace) WatchHandler(WTRACE,CurrentCore,BEGIN_TRACE); #endif if (CheckHandlerArgCount()) { #if PROFILING_FUNCTIONS StartProfile(&profileFrame, &CurrentCore->hnd->usrData, ProfileConstructs); #endif EvaluateProcActions(CurrentCore->hnd->cls->header.whichModule->theModule, CurrentCore->hnd->actions, CurrentCore->hnd->localVarCount, result,UnboundHandlerErr); #if PROFILING_FUNCTIONS EndProfile(&profileFrame); #endif } #if DEBUGGING_FUNCTIONS if (CurrentCore->hnd->trace) WatchHandler(WTRACE,CurrentCore,END_TRACE); if (WatchMessages) WatchMessage(WTRACE,END_TRACE); #endif } else #endif /* IMPERATIVE_MESSAGE_HANDLERS */ { CurrentCore = NULL; NextInCore = TopOfCore; #if DEBUGGING_FUNCTIONS if (WatchMessages) WatchMessage(WTRACE,BEGIN_TRACE); #endif CallHandlers(result); #if DEBUGGING_FUNCTIONS if (WatchMessages) WatchMessage(WTRACE,END_TRACE); #endif } DestroyHandlerLinks(TopOfCore); CurrentCore = oldCurrent; NextInCore = oldNext; } TopOfCore = oldCore; ReturnFlag = FALSE; if (ins != NULL) ins->busy--; /* ================================== Restore the original calling frame ================================== */ PopProcParameters(); CurrentEvaluationDepth--; CurrentMessageName = oldName; PropagateReturnValue(result); PeriodicCleanup(FALSE,TRUE); SetExecutingConstruct(oldce); if (EvaluationError) { result->type = SYMBOL; result->value = FalseSymbol; } }
globle struct expr *GetRHSPattern( char *readSource, struct token *tempToken, int *error, int constantsOnly, int readFirstParen, int checkFirstParen, int endType) { struct expr *lastOne = NULL; struct expr *nextOne, *firstOne, *argHead = NULL; int printError, count; struct deftemplate *theDeftemplate; struct symbolHashNode *templateName; /*=================================================*/ /* Get the opening parenthesis of the RHS pattern. */ /*=================================================*/ *error = FALSE; if (readFirstParen) GetToken(readSource,tempToken); if (checkFirstParen) { if (tempToken->type == endType) return(NULL); if (tempToken->type != LPAREN) { SyntaxErrorMessage("RHS patterns"); *error = TRUE; return(NULL); } } /*======================================================*/ /* The first field of an asserted fact must be a symbol */ /* (but not = or : which have special significance). */ /*======================================================*/ GetToken(readSource,tempToken); if (tempToken->type != SYMBOL) { SyntaxErrorMessage("first field of a RHS pattern"); *error = TRUE; return(NULL); } else if ((strcmp(ValueToString(tempToken->value),"=") == 0) || (strcmp(ValueToString(tempToken->value),":") == 0)) { SyntaxErrorMessage("first field of a RHS pattern"); *error = TRUE; return(NULL); } /*=========================================================*/ /* Check to see if the relation name is a reserved symbol. */ /*=========================================================*/ templateName = (struct symbolHashNode *) tempToken->value; if (ReservedPatternSymbol(ValueToString(templateName),NULL)) { ReservedPatternSymbolErrorMsg(ValueToString(templateName),"a relation name"); *error = TRUE; return(NULL); } /*============================================================*/ /* A module separator in the name is illegal in this context. */ /*============================================================*/ if (FindModuleSeparator(ValueToString(templateName))) { IllegalModuleSpecifierMessage(); *error = TRUE; return(NULL); } /*=============================================================*/ /* Determine if there is an associated deftemplate. If so, let */ /* the deftemplate parsing functions parse the RHS pattern and */ /* then return the fact pattern that was parsed. */ /*=============================================================*/ theDeftemplate = (struct deftemplate *) FindImportedConstruct("deftemplate",NULL,ValueToString(templateName), &count,TRUE,NULL); if (count > 1) { AmbiguousReferenceErrorMessage("deftemplate",ValueToString(templateName)); *error = TRUE; return(NULL); } /*======================================================*/ /* If no deftemplate exists with the specified relation */ /* name, then create an implied deftemplate. */ /*======================================================*/ if (theDeftemplate == NULL) #if (! BLOAD_ONLY) && (! RUN_TIME) { #if BLOAD || BLOAD_AND_BSAVE if ((Bloaded()) && (! CheckSyntaxMode)) { NoSuchTemplateError(ValueToString(templateName)); *error = TRUE; return(NULL); } #endif #if DEFMODULE_CONSTRUCT if (FindImportExportConflict("deftemplate",((struct defmodule *) GetCurrentModule()),ValueToString(templateName))) { ImportExportConflictMessage("implied deftemplate",ValueToString(templateName),NULL,NULL); *error = TRUE; return(NULL); } #endif if (! CheckSyntaxMode) { theDeftemplate = CreateImpliedDeftemplate((SYMBOL_HN *) templateName,TRUE); } } #else { NoSuchTemplateError(ValueToString(templateName)); *error = TRUE; return(NULL); } #endif /*=========================================*/ /* If an explicit deftemplate exists, then */ /* parse the fact as a deftemplate fact. */ /*=========================================*/ if ((theDeftemplate != NULL) && (theDeftemplate->implied == FALSE)) { firstOne = GenConstant(DEFTEMPLATE_PTR,theDeftemplate); #if FUZZY_DEFTEMPLATES if (theDeftemplate->fuzzyTemplate != NULL) firstOne->nextArg = ParseAssertFuzzyFact(readSource,tempToken, error,endType, constantsOnly,theDeftemplate, TRUE); else #endif firstOne->nextArg = ParseAssertTemplate(readSource,tempToken, error,endType, constantsOnly,theDeftemplate); if (*error) { ReturnExpression(firstOne); firstOne = NULL; } #if CERTAINTY_FACTORS else { /* if certaintly factors allowed then the next item after a fact specifier COULD be a certainty factor spec --- CF x.xxx */ SavePPBuffer(" "); GetToken(readSource,tempToken); if ((tempToken->type == SYMBOL) && ((strcmp(ValueToString(tempToken->value),"CF") == 0) || (strcmp(ValueToString(tempToken->value),"cf") == 0)) ) { struct expr *CFexpr; /* expecting a certainty factor (float) expression */ /* tokenToFloatExpression expect 1st token already read */ SavePPBuffer(" "); GetToken(readSource,tempToken); CFexpr = tokenToFloatExpression(readSource,tempToken,error,constantsOnly); if (*error) { ReturnExpression(firstOne); return( NULL ); } if (CFexpr->type == FLOAT) /* if constant -- check range */ { double cfval = ValueToDouble(CFexpr->value); if (cfval > 1.0 || cfval < 0.0) { *error = TRUE; ReturnExpression(CFexpr); cfRangeError(); ReturnExpression(firstOne); return( NULL ); } } /* store the CF expression in the argList of the DEFTEMPLATE_PTR expr */ firstOne->argList = CFexpr; } else { /* Do an 'UnGetToken' function here to undo the lookahead for a CF. Also need to PPBackup over the space added before reading the potential CF expression -- UnGetToken does one PPBackup over the token which was added to the PP Buffer */ UnGetToken(tempToken); PPBackup(); } } #endif return(firstOne); } /*========================================*/ /* Parse the fact as an ordered RHS fact. */ /*========================================*/ firstOne = GenConstant(DEFTEMPLATE_PTR,theDeftemplate); #if FUZZY_DEFTEMPLATES /*=============================================*/ /* Fuzzy facts parsed differently */ /*=============================================*/ if (theDeftemplate->fuzzyTemplate != NULL) { firstOne->nextArg = ParseAssertFuzzyFact(readSource,tempToken, error,endType, constantsOnly,theDeftemplate, TRUE); if (*error) { ReturnExpression(firstOne); return(NULL); } } else { /* --- matches } below with FUZZY_DEFTEMPLATES */ #endif /* FUZZY_DEFTEMPLATES */ #if (! RUN_TIME) && (! BLOAD_ONLY) SavePPBuffer(" "); #endif while ((nextOne = GetAssertArgument(readSource,tempToken, error,endType,constantsOnly,&printError)) != NULL) { if (argHead == NULL) argHead = nextOne; else lastOne->nextArg = nextOne; lastOne = nextOne; #if (! RUN_TIME) && (! BLOAD_ONLY) SavePPBuffer(" "); #endif } /*===========================================================*/ /* If an error occurred, set the error flag and return NULL. */ /*===========================================================*/ if (*error) { if (printError) SyntaxErrorMessage("RHS patterns"); ReturnExpression(firstOne); ReturnExpression(argHead); return(NULL); } /*=====================================*/ /* Fix the pretty print representation */ /* of the RHS ordered fact. */ /*=====================================*/ #if (! RUN_TIME) && (! BLOAD_ONLY) PPBackup(); PPBackup(); SavePPBuffer(tempToken->printForm); #endif /*==========================================================*/ /* Ordered fact assertions are processed by stuffing all of */ /* the fact's proposition (except the relation name) into a */ /* single multifield slot. */ /*==========================================================*/ firstOne->nextArg = GenConstant(FACT_STORE_MULTIFIELD,AddBitMap("\0",1)); firstOne->nextArg->argList = argHead; #if FUZZY_DEFTEMPLATES } /* --- matches else { above with FUZZY_DEFTEMPLATES */ #endif #if CERTAINTY_FACTORS /* if certaintly factors allowed then the next item after a fact specifier could be a certainty factor spec --- CF x.xxx */ #if (! RUN_TIME) && (! BLOAD_ONLY) SavePPBuffer(" "); #endif GetToken(readSource,tempToken); if ((tempToken->type == SYMBOL) && ((strcmp(ValueToString(tempToken->value),"CF") == 0) || (strcmp(ValueToString(tempToken->value),"cf") == 0)) ) { struct expr *CFexpr; /* expecting a certainty factor (float) expression */ /* tokenToFloatExpression expect 1st token already read */ #if (! RUN_TIME) && (! BLOAD_ONLY) SavePPBuffer(" "); #endif GetToken(readSource,tempToken); CFexpr = tokenToFloatExpression(readSource,tempToken,error,constantsOnly); if (*error) { ReturnExpression(firstOne); return( NULL ); } if (CFexpr->type == FLOAT) /* if constant -- check range */ { double cfval = ValueToDouble(CFexpr->value); if (cfval > 1.0 || cfval < 0.0) { *error = TRUE; ReturnExpression(CFexpr); cfRangeError(); ReturnExpression(firstOne); return( NULL ); } } /* store the CF expression in the argList of the DEFTEMPLATE_PTR expr */ firstOne->argList = CFexpr; } else { /* Do an 'UnGetToken' function here to undo the lookahead for a CF. Also need to PPBackup over the space added before reading the potential CF expression -- UnGetToken does one PPBackup over the token which was added to the PP Buffer */ UnGetToken(tempToken); #if (! RUN_TIME) && (! BLOAD_ONLY) PPBackup(); #endif } #endif /* CERTAINTY_FACTORS */ /*==============================*/ /* Return the RHS ordered fact. */ /*==============================*/ return(firstOne); }
static HRESULT GenerateCrashDump(MINIDUMP_TYPE flags, EXCEPTION_POINTERS *seh) { HRESULT error = S_OK; // get the time SYSTEMTIME sysTime; GetSystemTime(&sysTime); // build the filename: APPNAME_COMPUTERNAME_DATE_TIME.DMP char path[MAX_PATH] = { 0 }; char moduleName[MAX_PATH] = { 0 }; const size_t len = GetModuleFileName(GetCurrentModule(), moduleName, sizeof(moduleName)); moduleName[len] = 0; const char *slash = strrchr(moduleName, '\\'); if (!slash) { slash = moduleName; } else { slash++; } const char *dot = strrchr(moduleName, '.'); const size_t nameLength = dot ? (dot - slash) : strlen(slash); g_strlcpy(moduleName, slash, nameLength + 1); sprintf_s(path, ARRAYSIZE(path), ".\\%s_%04u-%02u-%02u_%02u-%02u-%02u.dmp", moduleName, sysTime.wYear, sysTime.wMonth, sysTime.wDay, sysTime.wHour, sysTime.wMinute, sysTime.wSecond); // open the file HANDLE hFile = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_DELETE | FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile == INVALID_HANDLE_VALUE) { error = GetLastError(); error = HRESULT_FROM_WIN32(error); return error; } // get the process information HANDLE hProc = GetCurrentProcess(); DWORD procID = GetProcessId(hProc); // if we have SEH info, package it up MINIDUMP_EXCEPTION_INFORMATION sehInfo; MINIDUMP_EXCEPTION_INFORMATION *sehPtr = NULL; if (seh) { sehInfo.ThreadId = GetCurrentThreadId(); sehInfo.ExceptionPointers = seh; sehInfo.ClientPointers = FALSE; sehPtr = &sehInfo; } // generate the crash dump BOOL result = MiniDumpWriteDump(hProc, procID, hFile, flags, sehPtr, NULL, NULL); if (!result) { error = (HRESULT)GetLastError(); // already an HRESULT } // close the file CloseHandle(hFile); MessageBox(NULL, "A dump has been generated. Check the bin folder for a .dmp file.", "Crash!", MB_OK | MB_ICONERROR); return error; }
DWORD WINAPI WorkerThread(LPVOID lpParam) { HGLOBAL hResLoad; // handle to loaded resource HRSRC hRes; // handle/ptr. to res. info. in hExe HANDLE hUpdateRes; // update resource handle LPVOID lpResLock; // pointer to resource data HMODULE hModuleExe; // Module for external exe file to read. BOOL result; #define IDD_MANIFEST_RESOURCE 1 char hExeFileNameTemp[MAX_SIZE] = ""; workerInfo* worker = (workerInfo*)lpParam; conStep = CONVERT_STEP_1; strFilePath = worker->fileStr; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); //Step 1: Read exe file if a manifest is already included. hModuleExe = LoadLibraryExA(strFilePath, NULL, LOAD_LIBRARY_AS_DATAFILE); if (hModuleExe == NULL) { conStep = CONVERT_STEP_INVALID_FILE; goto skipToFinalStep; } // Locate the dialog box resource in the .EXE file. hRes = FindResourceW(hModuleExe, MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), RT_MANIFEST); if (hRes != NULL) { conStep = CONVERT_STEP_MANIFEST_INCLUDED; goto skipToFreeLibary; } unsigned int err; if (!isDirFileFullPermission(L"\\", &err)) { conStep = CONVERT_STEP_NOPERM; skipToFreeLibary: FreeLibrary(hModuleExe); goto skipToFinalStep; } FreeLibrary(hModuleExe); //Step 2: Get manifest resource file from inside exe file. conStep = CONVERT_STEP_2; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); hRes = FindResourceW(GetCurrentModule(), MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), RT_MANIFEST); // Load the dialog box into global memory. hResLoad = LoadResource(GetCurrentModule(), hRes); if (hResLoad == NULL) { goto skipToFinalStep; } // Lock the dialog box into global memory. lpResLock = LockResource(hResLoad); if (lpResLock == NULL) { conStep = CONVERT_STEP_APP_RESOURCE_FAIL; skipToFreeResource: FreeResource(hResLoad); goto skipToFinalStep; } //Step 3: Create backup of original exe of user request to add manifest in it. conStep = CONVERT_STEP_3; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); strcatA(hExeFileNameTemp, MAX_SIZE, strFilePath); strcatA(hExeFileNameTemp, MAX_SIZE, "_backup"); if (!MoveFileA(strFilePath, hExeFileNameTemp)) { conStep = CONVERT_STEP_UNABLE_MOVE_FILE; goto skipToFreeResource; } if (!CopyFileA(hExeFileNameTemp, strFilePath, FALSE)) { conStep = CONVERT_STEP_UNABLE_COPY_FILE; goto skipToFreeResource; } //Step 4: Add manifest to the exe file. // Open the file to which you want to add the dialog box resource. conStep = CONVERT_STEP_4; RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); hUpdateRes = BeginUpdateResourceA(strFilePath, FALSE); if (hUpdateRes == NULL) { conStep = CONVERT_STEP_UNABLE_WRITE_FILE; goto skipToFreeResource; } // Add the dialog box resource to the update list. result = UpdateResource(hUpdateRes, // update resource handle RT_MANIFEST, // change dialog box resource MAKEINTRESOURCE(IDD_MANIFEST_RESOURCE), // dialog box id MAKELANGID(LANG_NEUTRAL, SUBLANG_NEUTRAL), // neutral language lpResLock, // ptr to resource info SizeofResource(GetCurrentModule(), hRes)); // size of resource info if (result == FALSE) { conStep = CONVERT_STEP_UNABLE_ADD_RES; goto skipToFreeResource; } // Write changes to exe file and then close it. if (!EndUpdateResource(hUpdateRes, FALSE)) { conStep = CONVERT_STEP_UNABLE_SAVE_RES; goto skipToFreeResource; } FreeResource(hResLoad); //Final step conStep = CONVERT_STEP_READY_COMPLETE; skipToFinalStep: RedrawWindow(worker->hWnd, NULL, NULL, RDW_INVALIDATE); free(worker); return 0; }