void DbgMsg( char* szMessage, ... ) { char szFullMessage[MAX_PATH]; char szFormatMessage[MAX_PATH]; // format message va_list ap; va_start(ap, szMessage); (void)StringCchVPrintfA( szFormatMessage, NUMELMS(szFormatMessage), szMessage, ap ); va_end(ap); (void)StringCchCatA( szFormatMessage, NUMELMS(szFormatMessage), "\n" ); (void)StringCchCopyA( szFullMessage, NUMELMS(szFullMessage), "~*~*~*~*~*~ " ); (void)StringCchCatA( szFullMessage, NUMELMS(szFullMessage), szFormatMessage ); OutputDebugStringA( szFullMessage ); }
std::vector<std::string> *listFilesDir(const char* dir) { WIN32_FIND_DATAA ffd; HANDLE hFind = INVALID_HANDLE_VALUE; char szDir[MAX_PATH]; int arg_length; std::vector<std::string> *files_dir = new std::vector<std::string>(); arg_length= (int)strlen(dir); if (arg_length > (MAX_PATH - 3)) return files_dir; StringCchCopyA(szDir, MAX_PATH, dir); StringCchCatA(szDir, MAX_PATH, "\\*"); hFind = FindFirstFileA(szDir, &ffd); if (INVALID_HANDLE_VALUE == hFind) return files_dir; do { files_dir->push_back(ffd.cFileName); } while (FindNextFileA(hFind, &ffd) != 0); FindClose(hFind); return files_dir; }
// // warning -- this function is implemented twice for ansi applications // linking to the unicode library // void WINAPI DbgLogInfo(DWORD Type,DWORD Level,__format_string LPCSTR pFormat,...) { /* Check the current level for this type combination */ BOOL bAccept = DbgCheckModuleLevel(Type,Level); if (bAccept == FALSE) { return; } TCHAR szInfo[2000]; /* Format the variable length parameter list */ va_list va; va_start(va, pFormat); (void)StringCchPrintf(szInfo, NUMELMS(szInfo), TEXT("%s(tid %x) %8d : "), m_ModuleName, GetCurrentThreadId(), timeGetTime() - dwTimeOffset); CHAR szInfoA[2000]; WideCharToMultiByte(CP_ACP, 0, szInfo, -1, szInfoA, NUMELMS(szInfoA), 0, 0); (void)StringCchVPrintfA(szInfoA + lstrlenA(szInfoA), NUMELMS(szInfoA) - lstrlenA(szInfoA), pFormat, va); (void)StringCchCatA(szInfoA, NUMELMS(szInfoA), "\r\n"); WCHAR wszOutString[2000]; MultiByteToWideChar(CP_ACP, 0, szInfoA, -1, wszOutString, NUMELMS(wszOutString)); DbgOutString(wszOutString); va_end(va); }
void GBAConfigMakePortable(const struct GBAConfig* config) { struct VFile* portable = 0; #ifdef _WIN32 char out[MAX_PATH]; wchar_t wpath[MAX_PATH]; wchar_t wprojectName[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, projectName, -1, wprojectName, MAX_PATH); HMODULE hModule = GetModuleHandleW(NULL); GetModuleFileNameW(hModule, wpath, MAX_PATH); PathRemoveFileSpecW(wpath); WideCharToMultiByte(CP_UTF8, 0, wpath, -1, out, MAX_PATH, 0, 0); StringCchCatA(out, MAX_PATH, "\\portable.ini"); portable = VFileOpen(out, O_WRONLY | O_CREAT); #elif defined(PSP2) || defined(_3DS) || defined(GEKKO) // Already portable #else char out[PATH_MAX]; getcwd(out, PATH_MAX); strncat(out, PATH_SEP "portable.ini", PATH_MAX - strlen(out)); portable = VFileOpen(out, O_WRONLY | O_CREAT); #endif if (portable) { portable->close(portable); GBAConfigSave(config); } }
/******************************************************************** WcaLog() - outputs trace and log info *******************************************************************/ extern "C" void __cdecl WcaLog( __in LOGLEVEL llv, __in_z __format_string PCSTR fmt, ... ) { static char szFmt[LOG_BUFFER]; static char szBuf[LOG_BUFFER]; static bool fInLogPrint = false; // prevent re-entrant logprints. (recursion issues between assert/logging code) if (fInLogPrint) return; fInLogPrint = true; if (LOGMSG_STANDARD == llv || (LOGMSG_VERBOSE == llv && IsVerboseLoggingLite()) #ifdef DEBUG || LOGMSG_TRACEONLY == llv #endif ) { va_list args; va_start(args, fmt); LPCSTR szLogName = WcaGetLogName(); if (szLogName[0] != 0) StringCchPrintfA(szFmt, countof(szFmt), "%s: %s", szLogName, fmt); else StringCchCopyA(szFmt, countof(szFmt), fmt); StringCchVPrintfA(szBuf, countof(szBuf), szFmt, args); va_end(args); #ifdef DEBUG // always write to the log in debug #else if (llv == LOGMSG_STANDARD || (llv == LOGMSG_VERBOSE && IsVerboseLoggingLite())) #endif { PMSIHANDLE hrec = MsiCreateRecord(1); ::MsiRecordSetStringA(hrec, 0, szBuf); // TODO: Recursion on failure. May not be safe to assert from here. WcaProcessMessage(INSTALLMESSAGE_INFO, hrec); } #if DEBUG StringCchCatA(szBuf, countof(szBuf), "\n"); OutputDebugStringA(szBuf); #endif } fInLogPrint = false; return; }
void DebugMsg(const CHAR* pszFormat, ...) { CHAR buf[1024]; StringCchPrintfA(buf, sizeof(buf)/sizeof(CHAR), "(%lu): ", GetCurrentThreadId()); va_list arglist; va_start(arglist, pszFormat); StringCchVPrintfA(&buf[strlen(buf)], sizeof(buf)/sizeof(CHAR), pszFormat, arglist); va_end(arglist); StringCchCatA(buf, sizeof(buf)/sizeof(CHAR), "\n"); OutputDebugStringA(buf); }
void Trace(LPSTR format, ...) { char message[256]; va_list args = NULL; va_start(args, format); StringCchVPrintfA(message, 256, format, args); char buffer[256]; StringCchCopyA(buffer, 256, "ode: "); StringCchCatA(buffer, 256, message); OutputDebugStringA(buffer); }
void GBAConfigDirectory(char* out, size_t outLength) { struct VFile* portable; #ifdef _WIN32 wchar_t wpath[MAX_PATH]; wchar_t wprojectName[MAX_PATH]; MultiByteToWideChar(CP_UTF8, 0, projectName, -1, wprojectName, MAX_PATH); HMODULE hModule = GetModuleHandleW(NULL); GetModuleFileNameW(hModule, wpath, MAX_PATH); PathRemoveFileSpecW(wpath); WideCharToMultiByte(CP_UTF8, 0, wpath, -1, out, outLength, 0, 0); StringCchCatA(out, outLength, "\\portable.ini"); portable = VFileOpen(out, O_RDONLY); if (portable) { portable->close(portable); } else { wchar_t* home; SHGetKnownFolderPath(&FOLDERID_RoamingAppData, 0, NULL, &home); StringCchPrintfW(wpath, MAX_PATH, L"%ws\\%ws", home, wprojectName); CoTaskMemFree(home); CreateDirectoryW(wpath, NULL); } WideCharToMultiByte(CP_UTF8, 0, wpath, -1, out, outLength, 0, 0); #elif defined(PSP2) UNUSED(portable); snprintf(out, outLength, "cache0:/%s", projectName); sceIoMkdir(out, 0777); #elif defined(GEKKO) UNUSED(portable); snprintf(out, outLength, "/%s", projectName); mkdir(out, 0777); #elif defined(_3DS) UNUSED(portable); snprintf(out, outLength, "/%s", projectName); FSUSER_CreateDirectory(sdmcArchive, fsMakePath(PATH_ASCII, out), 0); #else getcwd(out, outLength); strncat(out, PATH_SEP "portable.ini", outLength - strlen(out)); portable = VFileOpen(out, O_RDONLY); if (portable) { getcwd(out, outLength); portable->close(portable); return; } char* home = getenv("HOME"); snprintf(out, outLength, "%s/.config", home); mkdir(out, 0755); snprintf(out, outLength, "%s/.config/%s", home, binaryName); mkdir(out, 0755); #endif }
void hippoDebugLogU(const char *format, ...) { char buf[1024]; va_list vap; va_start (vap, format); StringCchVPrintfA(buf, sizeof(buf) / sizeof(buf[0]) - 2, format, vap); va_end (vap); StringCchCatA(buf, sizeof(buf) / sizeof(buf[0]) - 2, "\r\n"); HippoBSTR strW; strW.setUTF8(buf); OutputDebugStringW(strW); }
LPSTR UnicodeStr4CodeToUTF8Str(LPSTR in) { LPSTR temp; unsigned int code, help; CHAR utf8[5]; size_t length; while(temp = StrChrA(in, '\\'), temp != NULL) { if((temp[1] == 'u')||(temp[1] == 'U')) { temp[0] = '\0'; StringCchLengthA(in, STRSAFE_MAX_CCH, &length); CHAR A[length+1]; StringCchCopyA(A, length+1, in); StringCchLengthA(temp+6, STRSAFE_MAX_CCH, &length); CHAR B[length+1]; StringCchCopyA(B, length+1, temp+6); temp[6] = '\0'; CHAR hex_code[7]; StringCchCopyA(hex_code, 7, "0x"); CharLowerA(temp+2); StringCchCatA(hex_code, 7, temp+2); if(StrToIntExA(hex_code, STIF_SUPPORT_HEX, (int *)&code) == TRUE) { help = code; if(code <= 0x007F) { utf8[0] = code; utf8[1] = '\0'; } else if(code <= 0x07FF) { utf8[0] = 0xC0+(help >> 6); utf8[1] = 0x80+(code&0x3F); utf8[2] = '\0'; } else if(code <= 0xFFFF)
bool GenerateBoundary(char* sDst, int nDstSize, const char* sFileName) { if (nDstSize<38) return false; UUID uuid; RPC_STATUS ret_val = ::UuidCreate(&uuid); bool result = false; if (ret_val == RPC_S_OK) { char* wszUuid = NULL; ::UuidToStringA(&uuid, (RPC_CSTR*)&wszUuid); if (wszUuid != NULL) { if(SUCCEEDED(StringCbCopyA(sDst, nDstSize, wszUuid))) { if(sFileName!=NULL) { StringCchCatA(sDst, nDstSize, sFileName); } result = true; } } ::RpcStringFreeA((RPC_CSTR*)&wszUuid); wszUuid = NULL; } return result; }
void GetResourcesPath(char *path, int size) { ZeroMemory(path, size); HMODULE hm = NULL; if (!GetModuleHandleExA(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, (LPCSTR) &GetResourcesPath, &hm)) { return; } DWORD x = GetModuleFileNameA(hm, path, size); if (!x) return; int p = lstrlenA(path); if (!p) return; while (p--) { if (path[p] == '\\') { path[p+1] = 0; break; } } StringCchCatA(path, MAX_PATH, "\\"BMP_PATH); }
int main(void){ char dest[11] = "test"; char empty[10] = ""; plan(12); ok(SUCCEEDED(StringCchCatA(dest, 11, "TEST")), "Concatenate two short strings."); is_string("testTEST", dest, "Result of concatenating short strings."); dest[4] = '\0'; /* Reset dest to "test". */ ok(SUCCEEDED(StringCchCatA(dest, 11, "")), "Concatenate with empty source."); is_string("test", dest, "Result of concatenating with empty source."); ok(SUCCEEDED(StringCchCatA(empty, 10, "test")), "Concatenate with empty destination."); is_string("test", empty, "Result of concatenating with empty destination."); ok(StringCchCatA(dest, 11, "longer string") == STRSAFE_E_INSUFFICIENT_BUFFER, "Concatenate two strings that are too long."); is_string("testlonger", dest, "Result of concatenating two strings that are too long."); ok(StringCchCatA(dest, 11, "test") == STRSAFE_E_INSUFFICIENT_BUFFER, "Concatenate to already full destination."); is_string("testlonger", dest, "Make sure destination was not modified."); ok(StringCchCatA(dest, 0, "test") == STRSAFE_E_INVALID_PARAMETER, "Make sure error is thrown if cchDest is zero."); is_string("testlonger", dest, "Make sure destination was not modified."); return 0; }
void ProcessDebugEvent() { static wchar_t wszDbgText[1024]; static char szDbgText[1024]; BOOL lbNonContinuable = FALSE; DEBUG_EVENT evt = {0}; BOOL lbEvent = WaitForDebugEvent(&evt,10); #ifdef _DEBUG DWORD dwErr = GetLastError(); #endif static bool bFirstExitThreadEvent = false; // Чтобы вывести на экран подсказку по возможностям "дебаггера" //HMODULE hCOMDLG32 = NULL; //typedef BOOL (WINAPI* GetSaveFileName_t)(LPOPENFILENAMEW lpofn); //GetSaveFileName_t _GetSaveFileName = NULL; DWORD dwContinueStatus = DBG_EXCEPTION_NOT_HANDLED; if (lbEvent) { lbNonContinuable = FALSE; switch (evt.dwDebugEventCode) { case CREATE_PROCESS_DEBUG_EVENT: case CREATE_THREAD_DEBUG_EVENT: case EXIT_PROCESS_DEBUG_EVENT: case EXIT_THREAD_DEBUG_EVENT: case RIP_EVENT: { LPCSTR pszName = "Unknown"; switch (evt.dwDebugEventCode) { case CREATE_PROCESS_DEBUG_EVENT: pszName = "CREATE_PROCESS_DEBUG_EVENT"; break; case CREATE_THREAD_DEBUG_EVENT: pszName = "CREATE_THREAD_DEBUG_EVENT"; break; case EXIT_PROCESS_DEBUG_EVENT: pszName = "EXIT_PROCESS_DEBUG_EVENT"; break; case EXIT_THREAD_DEBUG_EVENT: pszName = "EXIT_THREAD_DEBUG_EVENT"; break; case RIP_EVENT: pszName = "RIP_EVENT"; break; } _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} %s\n", evt.dwProcessId,evt.dwThreadId, pszName); _printf(szDbgText); if (!bFirstExitThreadEvent && evt.dwDebugEventCode == EXIT_THREAD_DEBUG_EVENT) { bFirstExitThreadEvent = true; if (gpSrv->DbgInfo.nDebugDumpProcess == 0) { _printf("ConEmuC: Press Ctrl+Break to create minidump of debugging process\n"); } else { // Сразу сделать дамп и выйти HandlerRoutine(CTRL_BREAK_EVENT); } } if (evt.dwDebugEventCode == CREATE_PROCESS_DEBUG_EVENT) { gpSrv->DbgInfo.nProcessCount++; _ASSERTE(gpSrv->DbgInfo.pDebugTreeProcesses!=NULL); CEDebugProcessInfo pi = {evt.dwProcessId}; gpSrv->DbgInfo.pDebugTreeProcesses->Set(evt.dwProcessId, pi); UpdateDebuggerTitle(); } else if (evt.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) { CEDebugProcessInfo pi = {}; if (gpSrv->DbgInfo.pDebugTreeProcesses && gpSrv->DbgInfo.pDebugTreeProcesses->Get(evt.dwProcessId, &pi, true) && pi.hProcess) { CloseHandle(pi.hProcess); } if (gpSrv->DbgInfo.nProcessCount > 0) gpSrv->DbgInfo.nProcessCount--; UpdateDebuggerTitle(); } break; } case LOAD_DLL_DEBUG_EVENT: case UNLOAD_DLL_DEBUG_EVENT: { LPCSTR pszName = "Unknown"; char szBase[32] = {}; char szFile[MAX_PATH+128] = {}; struct MY_FILE_NAME_INFO { DWORD FileNameLength; WCHAR FileName[1]; }; typedef BOOL (WINAPI* GetFileInformationByHandleEx_t)(HANDLE hFile, int FileInformationClass, LPVOID lpFileInformation, DWORD dwBufferSize); static GetFileInformationByHandleEx_t _GetFileInformationByHandleEx = NULL; switch (evt.dwDebugEventCode) { case LOAD_DLL_DEBUG_EVENT: //6 Reports a load-dynamic-link-library (DLL) debugging event. The value of u.LoadDll specifies a LOAD_DLL_DEBUG_INFO structure. pszName = "LOAD_DLL_DEBUG_EVENT"; if (evt.u.LoadDll.hFile) { if (gnOsVer >= 0x0600) { if (!_GetFileInformationByHandleEx) _GetFileInformationByHandleEx = (GetFileInformationByHandleEx_t)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "GetFileInformationByHandleEx"); if (_GetFileInformationByHandleEx) { DWORD nSize = sizeof(MY_FILE_NAME_INFO)+MAX_PATH*sizeof(wchar_t); MY_FILE_NAME_INFO* pfi = (MY_FILE_NAME_INFO*)calloc(nSize+2,1); if (pfi) { pfi->FileNameLength = MAX_PATH; if (_GetFileInformationByHandleEx(evt.u.LoadDll.hFile, 2/*FileNameInfo*/, pfi, nSize) && pfi->FileName[0]) { wchar_t szFullPath[MAX_PATH+1] = {}, *pszFile; DWORD n = GetFullPathName(pfi->FileName, countof(szFullPath), szFullPath, &pszFile); if (!n || (n >= countof(szFullPath))) { lstrcpyn(szFullPath, pfi->FileName, countof(szFullPath)); pszFile = (wchar_t*)PointToName(pfi->FileName); } else if (!pszFile) { pszFile = (wchar_t*)PointToName(szFullPath); } lstrcpyA(szFile, ", "); WideCharToMultiByte(CP_OEMCP, 0, pszFile, -1, szFile+lstrlenA(szFile), 80, 0,0); lstrcatA(szFile, "\n\t"); WideCharToMultiByte(CP_OEMCP, 0, szFullPath, -1, szFile+lstrlenA(szFile), MAX_PATH, 0,0); } free(pfi); } } } CloseHandle(evt.u.LoadDll.hFile); } _wsprintfA(szBase, SKIPLEN(countof(szBase)) " at " WIN3264TEST("0x%08X","0x%08X%08X"), WIN3264WSPRINT((DWORD_PTR)evt.u.LoadDll.lpBaseOfDll)); break; case UNLOAD_DLL_DEBUG_EVENT: //7 Reports an unload-DLL debugging event. The value of u.UnloadDll specifies an UNLOAD_DLL_DEBUG_INFO structure. pszName = "UNLOAD_DLL_DEBUG_EVENT"; _wsprintfA(szBase, SKIPLEN(countof(szBase)) " at " WIN3264TEST("0x%08X","0x%08X%08X"), WIN3264WSPRINT((DWORD_PTR)evt.u.UnloadDll.lpBaseOfDll)); break; } _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} %s%s%s\n", evt.dwProcessId,evt.dwThreadId, pszName, szBase, szFile); _printf(szDbgText); break; } case EXCEPTION_DEBUG_EVENT: //1 Reports an exception debugging event. The value of u.Exception specifies an EXCEPTION_DEBUG_INFO structure. { lbNonContinuable = (evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE)==EXCEPTION_NONCONTINUABLE; //static bool bAttachEventRecieved = false; //if (!bAttachEventRecieved) //{ // bAttachEventRecieved = true; // StringCchPrintfA(szDbgText, countof(szDbgText),"{%i.%i} Debugger attached successfully. (0x%08X address 0x%08X flags 0x%08X%s)\n", // evt.dwProcessId,evt.dwThreadId, // evt.u.Exception.ExceptionRecord.ExceptionCode, // evt.u.Exception.ExceptionRecord.ExceptionAddress, // evt.u.Exception.ExceptionRecord.ExceptionFlags, // (evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE) ? "(EXCEPTION_NONCONTINUABLE)" : ""); //} //else switch (evt.u.Exception.ExceptionRecord.ExceptionCode) { case EXCEPTION_ACCESS_VIOLATION: // The thread tried to read from or write to a virtual address for which it does not have the appropriate access. { if (evt.u.Exception.ExceptionRecord.NumberParameters>=2) { _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} EXCEPTION_ACCESS_VIOLATION at " WIN3264TEST("0x%08X","0x%08X%08X") " flags 0x%08X%s %s of " WIN3264TEST("0x%08X","0x%08X%08X") " FC=%u\n", evt.dwProcessId,evt.dwThreadId, WIN3264WSPRINT((DWORD_PTR)evt.u.Exception.ExceptionRecord.ExceptionAddress), evt.u.Exception.ExceptionRecord.ExceptionFlags, ((evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE) ? "(EXCEPTION_NONCONTINUABLE)" : ""), ((evt.u.Exception.ExceptionRecord.ExceptionInformation[0]==0) ? "Read" : (evt.u.Exception.ExceptionRecord.ExceptionInformation[0]==1) ? "Write" : (evt.u.Exception.ExceptionRecord.ExceptionInformation[0]==8) ? "DEP" : "???"), WIN3264WSPRINT(evt.u.Exception.ExceptionRecord.ExceptionInformation[1]), evt.u.Exception.dwFirstChance ); } else { _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} EXCEPTION_ACCESS_VIOLATION at " WIN3264TEST("0x%08X","0x%08X%08X") " flags 0x%08X%s FC=%u\n", evt.dwProcessId,evt.dwThreadId, WIN3264WSPRINT((DWORD_PTR)evt.u.Exception.ExceptionRecord.ExceptionAddress), evt.u.Exception.ExceptionRecord.ExceptionFlags, (evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE) ? "(EXCEPTION_NONCONTINUABLE)" : "", evt.u.Exception.dwFirstChance); } _printf(szDbgText); } break; default: { char szName[32]; LPCSTR pszName; pszName = szName; #define EXCASE(s) case s: pszName = #s; break switch(evt.u.Exception.ExceptionRecord.ExceptionCode) { EXCASE(EXCEPTION_ARRAY_BOUNDS_EXCEEDED); // The thread tried to access an array element that is out of bounds and the underlying hardware supports bounds checking. EXCASE(EXCEPTION_BREAKPOINT); // A breakpoint was encountered. EXCASE(EXCEPTION_DATATYPE_MISALIGNMENT); // The thread tried to read or write data that is misaligned on hardware that does not provide alignment. For example, 16-bit values must be aligned on 2-byte boundaries; 32-bit values on 4-byte boundaries, and so on. EXCASE(EXCEPTION_FLT_DENORMAL_OPERAND); // One of the operands in a floating-point operation is denormal. A denormal value is one that is too small to represent as a standard floating-point value. EXCASE(EXCEPTION_FLT_DIVIDE_BY_ZERO); // The thread tried to divide a floating-point value by a floating-point divisor of zero. EXCASE(EXCEPTION_FLT_INEXACT_RESULT); // The result of a floating-point operation cannot be represented exactly as a decimal fraction. EXCASE(EXCEPTION_FLT_INVALID_OPERATION); // This exception represents any floating-point exception not included in this list. EXCASE(EXCEPTION_FLT_OVERFLOW); // The exponent of a floating-point operation is greater than the magnitude allowed by the corresponding type. EXCASE(EXCEPTION_FLT_STACK_CHECK); // The stack overflowed or underflowed as the result of a floating-point operation. EXCASE(EXCEPTION_FLT_UNDERFLOW); // The exponent of a floating-point operation is less than the magnitude allowed by the corresponding type. EXCASE(EXCEPTION_ILLEGAL_INSTRUCTION); // The thread tried to execute an invalid instruction. EXCASE(EXCEPTION_IN_PAGE_ERROR); // The thread tried to access a page that was not present, and the system was unable to load the page. For example, this exception might occur if a network connection is lost while running a program over the network. EXCASE(EXCEPTION_INT_DIVIDE_BY_ZERO); // The thread tried to divide an integer value by an integer divisor of zero. EXCASE(EXCEPTION_INT_OVERFLOW); // The result of an integer operation caused a carry out of the most significant bit of the result. EXCASE(EXCEPTION_INVALID_DISPOSITION); // An exception handler returned an invalid disposition to the exception dispatcher. Programmers using a high-level language such as C should never encounter this exception. EXCASE(EXCEPTION_NONCONTINUABLE_EXCEPTION); // The thread tried to continue execution after a noncontinuable exception occurred. EXCASE(EXCEPTION_PRIV_INSTRUCTION); // The thread tried to execute an instruction whose operation is not allowed in the current machine mode. EXCASE(EXCEPTION_SINGLE_STEP); // A trace trap or other single-instruction mechanism signaled that one instruction has been executed. EXCASE(EXCEPTION_STACK_OVERFLOW); // The thread used up its stack. default: _wsprintfA(szName, SKIPLEN(countof(szName)) "Exception 0x%08X", evt.u.Exception.ExceptionRecord.ExceptionCode); } _wsprintfA(szDbgText, SKIPLEN(countof(szDbgText)) "{%i.%i} %s at " WIN3264TEST("0x%08X","0x%08X%08X") " flags 0x%08X%s FC=%u\n", evt.dwProcessId,evt.dwThreadId, pszName, WIN3264WSPRINT((DWORD_PTR)evt.u.Exception.ExceptionRecord.ExceptionAddress), evt.u.Exception.ExceptionRecord.ExceptionFlags, (evt.u.Exception.ExceptionRecord.ExceptionFlags&EXCEPTION_NONCONTINUABLE) ? "(EXCEPTION_NONCONTINUABLE)" : "", evt.u.Exception.dwFirstChance); _printf(szDbgText); } } BOOL bDumpOnBreakPoint = gpSrv->DbgInfo.bDebuggerRequestDump; if (gpSrv->DbgInfo.bDebugProcessTree && (!lbNonContinuable && (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT))) { // Когда отладчик цепляется к процессу в первый раз - возникает EXCEPTION_BREAKPOINT CEDebugProcessInfo pi = {}; if (gpSrv->DbgInfo.pDebugTreeProcesses && gpSrv->DbgInfo.pDebugTreeProcesses->Get(evt.dwProcessId, &pi)) { if (!pi.bWasBreak) { pi.bWasBreak = TRUE; gpSrv->DbgInfo.pDebugTreeProcesses->Set(evt.dwProcessId, pi); } else { bDumpOnBreakPoint = TRUE; } } } if (gpSrv->DbgInfo.bDebuggerRequestDump || (!lbNonContinuable && !gpSrv->DbgInfo.bDebugProcessTree && (evt.u.Exception.ExceptionRecord.ExceptionCode != EXCEPTION_BREAKPOINT)) || (gpSrv->DbgInfo.bDebugProcessTree && ((evt.u.Exception.ExceptionRecord.ExceptionCode>=0xC0000000) || (bDumpOnBreakPoint && (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT)))) ) { BOOL bGenerateTreeBreak = gpSrv->DbgInfo.bDebugProcessTree && (gpSrv->DbgInfo.bDebuggerRequestDump || lbNonContinuable); if (gpSrv->DbgInfo.bDebugProcessTree && !bGenerateTreeBreak && (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT)) { if (gpSrv->DbgInfo.nWaitTreeBreaks == 0) { bGenerateTreeBreak = TRUE; gpSrv->DbgInfo.nWaitTreeBreaks++; } } gpSrv->DbgInfo.bDebuggerRequestDump = FALSE; // один раз char szConfirm[2048]; if (evt.u.Exception.ExceptionRecord.ExceptionCode == EXCEPTION_BREAKPOINT) { if (gpSrv->DbgInfo.nDebugDumpProcess) szConfirm[0] = 0; else lstrcpynA(szConfirm, szDbgText, countof(szConfirm)); } else { _wsprintfA(szConfirm, SKIPLEN(countof(szConfirm)) "%s exception (FC=%u)\n", lbNonContinuable ? "Non continuable" : "Continuable", evt.u.Exception.dwFirstChance); StringCchCatA(szConfirm, countof(szConfirm), szDbgText); } StringCchCatA(szConfirm, countof(szConfirm), "\nCreate minidump (<No> - fulldump)?"); //GenerateTreeDebugBreak WriteMiniDump(evt.dwProcessId, evt.dwThreadId, &evt.u.Exception.ExceptionRecord, szConfirm, bGenerateTreeBreak); if (gpSrv->DbgInfo.bDebugProcessTree && (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT)) { if (gpSrv->DbgInfo.nWaitTreeBreaks > 0) gpSrv->DbgInfo.nWaitTreeBreaks--; } } if (!lbNonContinuable /*|| (evt.u.Exception.ExceptionRecord.ExceptionCode==EXCEPTION_BREAKPOINT)*/) { dwContinueStatus = DBG_CONTINUE; } } break; case OUTPUT_DEBUG_STRING_EVENT: //8 Reports an output-debugging-string debugging event. The value of u.DebugString specifies an OUTPUT_DEBUG_STRING_INFO structure. { wszDbgText[0] = 0; if (evt.u.DebugString.nDebugStringLength >= 1024) evt.u.DebugString.nDebugStringLength = 1023; DWORD_PTR nRead = 0; HANDLE hProcess = GetProcessHandleForDebug(evt.dwProcessId); if (evt.u.DebugString.fUnicode) { if (!ReadProcessMemory(hProcess, evt.u.DebugString.lpDebugStringData, wszDbgText, 2*evt.u.DebugString.nDebugStringLength, &nRead)) { wcscpy_c(wszDbgText, L"???"); } else { wszDbgText[min(1023,nRead+1)] = 0; } static int nPrefixLen = lstrlen(CONEMU_CONHOST_CREATED_MSG); if (memcmp(wszDbgText, CONEMU_CONHOST_CREATED_MSG, nPrefixLen*sizeof(wszDbgText[0])) == 0) { LPWSTR pszEnd = NULL; DWORD nConHostPID = wcstoul(wszDbgText+nPrefixLen, &pszEnd, 10); if (nConHostPID && !gpSrv->DbgInfo.pDebugTreeProcesses->Get(nConHostPID, NULL)) { AttachConHost(nConHostPID); } } } else { if (!ReadProcessMemory(hProcess, evt.u.DebugString.lpDebugStringData, szDbgText, evt.u.DebugString.nDebugStringLength, &nRead)) { wcscpy_c(wszDbgText, L"???"); } else { szDbgText[min(1023,nRead+1)] = 0; // CP_ACP differs from CP_OEMCP, thats why we need some overhead... MultiByteToWideChar(CP_ACP, 0, szDbgText, -1, wszDbgText, 1024); } } WideCharToMultiByte(CP_OEMCP, 0, wszDbgText, -1, szDbgText, 1024, 0, 0); #ifdef CRTPRINTF { _printf("{PID=%i.TID=%i} ", evt.dwProcessId,evt.dwThreadId, wszDbgText); } #else { _printf("{PID=%i.TID=%i} %s", evt.dwProcessId,evt.dwThreadId, szDbgText); int nLen = lstrlenA(szDbgText); if (nLen > 0 && szDbgText[nLen-1] != '\n') _printf("\n"); } #endif dwContinueStatus = DBG_CONTINUE; } break; } // Продолжить отлаживаемый процесс ContinueDebugEvent(evt.dwProcessId, evt.dwThreadId, dwContinueStatus); } //if (hCOMDLG32) // FreeLibrary(hCOMDLG32); }
int __cdecl main(void) { printf("symtest.exe: Starting.\n"); fflush(stdout); //////////////////////////////////////////////////////// Get the functions. // HMODULE hDbgHelp = LoadLibraryA("dbghelp.dll"); if (hDbgHelp == NULL) { printf("Couldn't load dbghelp.dll"); return 1; } pfImagehlpApiVersionEx = (PF_ImagehlpApiVersionEx)GetProcAddress(hDbgHelp, "ImagehlpApiVersionEx"); pfSymInitialize = (PF_SymInitialize)GetProcAddress(hDbgHelp, "SymInitialize"); pfSymSetOptions = (PF_SymSetOptions)GetProcAddress(hDbgHelp, "SymSetOptions"); pfSymGetOptions = (PF_SymGetOptions)GetProcAddress(hDbgHelp, "SymGetOptions"); pfSymLoadModule64 = (PF_SymLoadModule64)GetProcAddress(hDbgHelp, "SymLoadModule64"); pfSymGetModuleInfo64 = (PF_SymGetModuleInfo64)GetProcAddress(hDbgHelp, "SymGetModuleInfo64"); pfSymFromName = (PF_SymFromName)GetProcAddress(hDbgHelp, "SymFromName"); pfSymRegisterCallback64 = (PF_SymRegisterCallback64)GetProcAddress(hDbgHelp, "SymRegisterCallback64"); pfSymEnumerateModules64 = (PF_SymEnumerateModules64)GetProcAddress(hDbgHelp, "SymEnumerateModules64"); pfSymEnumSymbols = (PF_SymEnumSymbols)GetProcAddress(hDbgHelp, "SymEnumSymbols"); ////////////////////////////////////////////////////////////////////////////// // HANDLE hProcess = GetCurrentProcess(); API_VERSION av; ZeroMemory(&av, sizeof(av)); av.MajorVersion = API_VERSION_NUMBER; pfImagehlpApiVersionEx(&av); printf(" Version: %d.%d (%d)\n", av.MajorVersion, av.MinorVersion, API_VERSION_NUMBER); if (!pfSymInitialize(hProcess, NULL, FALSE)) { printf("SymInitialize failed: %d\n", GetLastError()); return 1; } #if (_MSC_VER > 1299) pfSymRegisterCallback64(hProcess, CallbackFunction, NULL); #endif DWORD dw = pfSymGetOptions(); printf("GetOptions = %08x\n", dw); dw &= ~(SYMOPT_CASE_INSENSITIVE | SYMOPT_UNDNAME | SYMOPT_DEFERRED_LOADS | 0); dw |= ( #if defined(SYMOPT_EXACT_SYMBOLS) SYMOPT_EXACT_SYMBOLS | #endif #if defined(SYMOPT_DEBUG) SYMOPT_DEBUG | #endif #if defined(SYMOPT_NO_UNQUALIFIED_LOADS) SYMOPT_NO_UNQUALIFIED_LOADS | #endif #if defined(SYMOPT_FAIL_CRITICAL_ERRORS) SYMOPT_FAIL_CRITICAL_ERRORS | #endif #if defined(SYMOPT_INCLUDE_32BIT_MODULES) SYMOPT_INCLUDE_32BIT_MODULES | #endif 0); printf("SetOptions = %08x\n", dw); pfSymSetOptions(dw); /////////////////////////////////////////////// First, try GetProcAddress. // PCHAR pszFile = "target.dll"; HMODULE hModule = LoadLibraryA(pszFile); if (hModule == NULL) { printf("LoadLibraryA(%s) failed: %d\n", pszFile, GetLastError()); return 2; } ////////////////////////////////////////////////////// Then try ImageHelp. // #if (_MSC_VER > 1299) //CHAR szFull[MAX_PATH]; //GetModuleFileNameA(hModule, szFull, sizeof(szFull)); printf("SymLoadModule64(%s) will be called.\n", pszFile /*szFull*/); DWORD64 loaded = pfSymLoadModule64(hProcess, NULL, (PCHAR)pszFile/*szFull*/, NULL, (DWORD64)hModule, 0); if (loaded == 0) { printf("SymLoadModule64(%p) failed: %d\n", hProcess, GetLastError()); printf("\n"); } else { printf("SymLoadModule64(%p) succeeded: 0x%p\n", hProcess, (PVOID)loaded); } CHAR szModName[512]; printf("Modules:\n"); // The first parameter of PSYM_ENUMMODULES_CALLBACK64 changed from PSTR to PCSTR // between Windows 2003 and Windows 7. Cast here to work with either. pfSymEnumerateModules64(hProcess, (PSYM_ENUMMODULES_CALLBACK64)SymEnumerateCallback, NULL); printf("\n"); IMAGEHLP_MODULE64 modinfo; ZeroMemory(&modinfo, sizeof(modinfo)); modinfo.SizeOfStruct = 512/*sizeof(modinfo)*/; if (!pfSymGetModuleInfo64(hProcess, (DWORD64)hModule, &modinfo)) { printf("SymGetModuleInfo64(%p, %p) [64] failed: %d\n", hProcess, hModule, GetLastError()); } else { printf("SymGetModuleInfo64(%p, %p) [64] succeeded: %d\n", hProcess, hModule, GetLastError()); StringCchCopyA(szModName, ARRAYSIZE(szModName), modinfo.ModuleName); StringCchCatA(szModName, ARRAYSIZE(szModName), "!"); printf("NumSyms: %d\n", modinfo.NumSyms); printf("SymType: %d\n", modinfo.SymType); printf("ModuleName: %s\n", modinfo.ModuleName); printf("ImageName: %s\n", modinfo.ImageName); printf("LoadedImageName: %s\n", modinfo.LoadedImageName); } printf("\n"); fflush(stdout); printf("DLLs:\n"); for (hModule = NULL; (hModule = DetourEnumerateModules(hModule)) != NULL;) { CHAR szName[MAX_PATH]; GetModuleFileNameA(hModule, szName, sizeof(szName)); printf(" %p: %s\n", hModule, szName); } if (pfSymEnumSymbols == NULL) { printf("Couldn't find SymEnumSymbols.\n"); } else { printf("===Enum===\n"); SetLastError(0); nSymbolCount = 0; if (!pfSymEnumSymbols(hProcess, (DWORD64)hModule, NULL, SymEnumerateSymbols, NULL)) { printf("SymEnumSymbols() failed: %d\n", GetLastError()); } } // Look for specific symbols. struct CFullSymbol : SYMBOL_INFO { CHAR szRestOfName[MAX_SYM_NAME]; } symbol; CHAR szFullName[512]; // Look for Target StringCchCopyA(szFullName, ARRAYSIZE(szFullName), szModName); StringCchCatA(szFullName, ARRAYSIZE(szFullName), "Target"); printf("Symbol: [%s]\n", szFullName); ZeroMemory(&symbol, sizeof(symbol)); symbol.SizeOfStruct = sizeof(SYMBOL_INFO); #ifdef DBHLPAPI symbol.MaxNameLen = MAX_SYM_NAME; #else symbol.MaxNameLength = MAX_SYM_NAME; #endif SetLastError(0); if (!pfSymFromName(hProcess, szFullName, &symbol)) { printf("--SymFromName(%s) failed: %d\n", szFullName, GetLastError()); } if (symbol.Address != 0) { printf("--SymFromName(%s) succeeded\n", szFullName); } printf("%s => %p\n\n", szFullName, (PBYTE)symbol.Address); // Look for Hidden StringCchCopyA(szFullName, ARRAYSIZE(szFullName), szModName); StringCchCatA(szFullName, ARRAYSIZE(szFullName), "Hidden"); printf("Symbol: [%s]\n", szFullName); ZeroMemory(&symbol, sizeof(symbol)); symbol.SizeOfStruct = sizeof(SYMBOL_INFO); #ifdef DBHLPAPI symbol.MaxNameLen = MAX_SYM_NAME; #else symbol.MaxNameLength = MAX_SYM_NAME; #endif SetLastError(0); if (!pfSymFromName(hProcess, szFullName, &symbol)) { printf("--SymFromName(%s) failed: %d\n", szFullName, GetLastError()); } if (symbol.Address != 0) { printf("--SymFromName(%s) succeeded\n", szFullName); } printf("%s => %p\n\n", szFullName, (PBYTE)symbol.Address); #endif // We call Target once to insure it is loaded. Target(0); return 0; }
bool RunProcessing(LPCWSTR fname, int mode, HWND hWnd, int curtrack) { SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; HANDLE hReadError, hReadOut, hWriteError, hWriteOut; char xxx[1000],tempbuf[1000]; DWORD dd; int i,pos=0; sa.nLength = sizeof(sa); sa.lpSecurityDescriptor = NULL; sa.bInheritHandle = TRUE; if (!CreatePipe(&hReadOut, &hWriteOut, &sa, 0)) return 1; if (!CreatePipe(&hReadError, &hWriteError, &sa, 0)) return 1; memset(&si, 0, sizeof(si)); memset(&pi, 0, sizeof(pi)); si.cb = sizeof(si); si.dwFlags = STARTF_USESTDHANDLES; si.hStdInput = NULL; si.hStdOutput = hWriteOut; si.hStdError = hWriteError; ////////////////////////////////////////////////////////////////////////// // запуск процесса wchar_t cmdline[1000]; StringCchPrintf(cmdline, 1000, L"aucdtect.exe -m%d -v \"%s\"", mode, fname); if (!CreateProcess(NULL,cmdline, NULL, NULL, TRUE, CREATE_NO_WINDOW, NULL, L".", &si, &pi)) { MessageBox(0, L"can not launch aucdtect.exe", NULL, MB_OK); return false; } CloseHandle(hWriteOut); CloseHandle(hWriteError); int oldpers = -1; SendMessage(hWnd, MES_SENDPROCID1, curtrack, GetProcessId(GetCurrentProcess())); SendMessage(hWnd, MES_SENDPROCID2, curtrack, pi.dwProcessId); while(ReadFile(hReadError,xxx,80,&dd,0)) { for(i=0;i<(int)dd;i++){ if(xxx[i]==13 || xxx[i]==10){ if(xxx[i]==13)i++; tempbuf[pos] = 0; int pers = ParsePercentString(tempbuf); // сообщение if( pers != oldpers){ if( !MySendMessage(hWnd, MES_PROGRESS, curtrack, pers) ) return false; oldpers = pers; } pos=0; }else{ if(xxx[i]==10)continue; tempbuf[pos++] = xxx[i]; } } } pos=0; while(ReadFile(hReadOut,xxx,80,&dd,0)) { for(int i=0;i<(int)dd;i++){ if(xxx[i]==13 || xxx[i]==10){ if(xxx[i]==13)i++; tempbuf[pos] = 0; StringCchCatA(tempbuf, 1000, "\r\n"); pos+=2; }else{ if(xxx[i]==10)continue; tempbuf[pos++] = xxx[i]; } } } CloseHandle( pi.hProcess ); CloseHandle( pi.hThread ); if( !SendStdOut(hWnd, tempbuf, curtrack) ) return false; return true; }
PVOID WINAPI DetourFindFunction(PCSTR pszModule, PCSTR pszFunction) { /////////////////////////////////////////////// First, try GetProcAddress. // HMODULE hModule = LoadLibraryExA(pszModule, NULL, 0); if (hModule == NULL) { return NULL; } PBYTE pbCode = (PBYTE)GetProcAddress(hModule, pszFunction); if (pbCode) { return pbCode; } ////////////////////////////////////////////////////// Then try ImageHelp. // DETOUR_TRACE(("DetourFindFunction(%s, %s)\n", pszModule, pszFunction)); PDETOUR_SYM_INFO pSymInfo = DetourLoadImageHlp(); if (pSymInfo == NULL) { DETOUR_TRACE(("DetourLoadImageHlp failed: %d\n", GetLastError())); return NULL; } if (pSymInfo->pfSymLoadModule64(pSymInfo->hProcess, NULL, (PCHAR)pszModule, NULL, (DWORD64)hModule, 0) == 0) { if (ERROR_SUCCESS != GetLastError()) { DETOUR_TRACE(("SymLoadModule64(%p) failed: %d\n", pSymInfo->hProcess, GetLastError())); return NULL; } } HRESULT hrRet; CHAR szFullName[512]; IMAGEHLP_MODULE64 modinfo; ZeroMemory(&modinfo, sizeof(modinfo)); modinfo.SizeOfStruct = sizeof(modinfo); if (!pSymInfo->pfSymGetModuleInfo64(pSymInfo->hProcess, (DWORD64)hModule, &modinfo)) { DETOUR_TRACE(("SymGetModuleInfo64(%p, %p) failed: %d\n", pSymInfo->hProcess, hModule, GetLastError())); return NULL; } hrRet = StringCchCopyA(szFullName, sizeof(szFullName)/sizeof(CHAR), modinfo.ModuleName); if (FAILED(hrRet)) { DETOUR_TRACE(("StringCchCopyA failed: %08x\n", hrRet)); return NULL; } hrRet = StringCchCatA(szFullName, sizeof(szFullName)/sizeof(CHAR), "!"); if (FAILED(hrRet)) { DETOUR_TRACE(("StringCchCatA failed: %08x\n", hrRet)); return NULL; } hrRet = StringCchCatA(szFullName, sizeof(szFullName)/sizeof(CHAR), pszFunction); if (FAILED(hrRet)) { DETOUR_TRACE(("StringCchCatA failed: %08x\n", hrRet)); return NULL; } struct CFullSymbol : SYMBOL_INFO { CHAR szRestOfName[512]; } symbol; ZeroMemory(&symbol, sizeof(symbol)); //symbol.ModBase = (ULONG64)hModule; symbol.SizeOfStruct = sizeof(SYMBOL_INFO); #ifdef DBHLPAPI symbol.MaxNameLen = sizeof(symbol.szRestOfName)/sizeof(symbol.szRestOfName[0]); #else symbol.MaxNameLength = sizeof(symbol.szRestOfName)/sizeof(symbol.szRestOfName[0]); #endif if (!pSymInfo->pfSymFromName(pSymInfo->hProcess, szFullName, &symbol)) { DETOUR_TRACE(("SymFromName(%s) failed: %d\n", szFullName, GetLastError())); return NULL; } #ifdef DETOURS_IA64 #error Feature not supported in this release. #else return (PBYTE)symbol.Address; #endif }
BOOL SetFile(PCHAR pszPath) { BOOL bGood = TRUE; HANDLE hOld = INVALID_HANDLE_VALUE; HANDLE hNew = INVALID_HANDLE_VALUE; PDETOUR_BINARY pBinary = NULL; CHAR szOrg[MAX_PATH]; CHAR szNew[MAX_PATH]; CHAR szOld[MAX_PATH]; szOld[0] = '\0'; szNew[0] = '\0'; StringCchCopyA(szOrg, sizeof(szOrg), pszPath); StringCchCopyA(szNew, sizeof(szNew), szOrg); StringCchCatA(szNew, sizeof(szNew), "#"); StringCchCopyA(szOld, sizeof(szOld), szOrg); StringCchCatA(szOld, sizeof(szOld), "~"); printf(" %s:\n", pszPath); hOld = CreateFileA(szOrg, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL); if (hOld == INVALID_HANDLE_VALUE) { printf("Couldn't open input file: %s, error: %d\n", szOrg, GetLastError()); bGood = FALSE; goto end; } hNew = CreateFileA(szNew, GENERIC_WRITE | GENERIC_READ, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN, NULL); if (hNew == INVALID_HANDLE_VALUE) { printf("Couldn't open output file: %s, error: %d\n", szNew, GetLastError()); bGood = FALSE; goto end; } if ((pBinary = DetourBinaryOpen(hOld)) == NULL) { printf("DetourBinaryOpen failed: %d\n", GetLastError()); goto end; } if (hOld != INVALID_HANDLE_VALUE) { CloseHandle(hOld); hOld = INVALID_HANDLE_VALUE; } { BOOL bAddedDll = FALSE; DetourBinaryResetImports(pBinary); if (!s_fRemove) { if (!DetourBinaryEditImports(pBinary, &bAddedDll, AddBywayCallback, NULL, NULL, NULL)) { printf("DetourBinaryEditImports failed: %d\n", GetLastError()); } } if (!DetourBinaryEditImports(pBinary, NULL, ListBywayCallback, ListFileCallback, NULL, NULL)) { printf("DetourBinaryEditImports failed: %d\n", GetLastError()); } if (!DetourBinaryWrite(pBinary, hNew)) { printf("DetourBinaryWrite failed: %d\n", GetLastError()); bGood = FALSE; } DetourBinaryClose(pBinary); pBinary = NULL; if (hNew != INVALID_HANDLE_VALUE) { CloseHandle(hNew); hNew = INVALID_HANDLE_VALUE; } if (bGood) { if (!DeleteFileA(szOld)) { DWORD dwError = GetLastError(); if (dwError != ERROR_FILE_NOT_FOUND) { printf("Warning: Couldn't delete %s: %d\n", szOld, dwError); bGood = FALSE; } } if (!MoveFileA(szOrg, szOld)) { printf("Error: Couldn't back up %s to %s: %d\n", szOrg, szOld, GetLastError()); bGood = FALSE; } if (!MoveFileA(szNew, szOrg)) { printf("Error: Couldn't install %s as %s: %d\n", szNew, szOrg, GetLastError()); bGood = FALSE; } } DeleteFileA(szNew); } end: if (pBinary) { DetourBinaryClose(pBinary); pBinary = NULL; } if (hNew != INVALID_HANDLE_VALUE) { CloseHandle(hNew); hNew = INVALID_HANDLE_VALUE; } if (hOld != INVALID_HANDLE_VALUE) { CloseHandle(hOld); hOld = INVALID_HANDLE_VALUE; } return bGood; }
// // Function: LoadUpdateProviderFunction // // Description: // This routine loads the WSCUpdateProvider function from ws2_32.dll. // This function is used when removing LSP entries and other LSPs are layered // on top of the one to be removed. If this API is present (which it is on // Windows XP and later), then the logic is much simpler. This routien will // load both the 32-bit and 64-bit versions of the function. // HMODULE LoadUpdateProviderFunction() { HMODULE hModule = NULL; HRESULT hr; char WinsockLibraryPath[ MAX_PATH+1 ], szExpandPath[ MAX_PATH+1 ]; // // See if we're on a platform that supports WSCUpdateProvider. If so then // uninstalling an LSP is easy; otherwise, it is very painful if you're // removing an LSP that has other LSPs on top if it. // if ( GetSystemDirectoryA( WinsockLibraryPath, MAX_PATH+1 ) == 0 ) { hr = StringCchCopyA( szExpandPath, MAX_PATH+1, "%SYSTEMROOT%\\system32" ); if ( FAILED( hr ) ) { fprintf( stderr, "LoadUpdateProviderFunctions: StringCchCopyA failed: 0x%x\n", hr ); goto cleanup; } if ( ExpandEnvironmentStringsA( WinsockLibraryPath, szExpandPath, MAX_PATH+1 ) == 0 ) { fprintf(stderr, "LoadUpdateProviderFunctions: Unable to expand environment string: %d\n", GetLastError() ); goto cleanup; } } hr = StringCchCatA( WinsockLibraryPath, MAX_PATH+1, WINSOCK_DLL ); if ( FAILED( hr ) ) { fprintf( stderr, "LoadUpdateProviderFunctions: StringCchCatA failed: 0x%x\n", hr ); goto cleanup; } hModule = LoadLibraryA( WinsockLibraryPath ); if (hModule == NULL) { fprintf(stderr, "LoadUpdateProviderFunctions: Unable to load %s: %d\n", WinsockLibraryPath, GetLastError() ); goto cleanup; } #ifdef _WIN64 fnWscUpdateProvider = (LPWSCUPDATEPROVIDER)GetProcAddress(hModule, "WSCUpdateProvider"); fnWscUpdateProvider32 = (LPWSCUPDATEPROVIDER)GetProcAddress(hModule, "WSCUpdateProvider32"); #else fnWscUpdateProvider = (LPWSCUPDATEPROVIDER)GetProcAddress(hModule, "WSCUpdateProvider"); #endif return hModule; cleanup: if ( NULL != hModule ) { FreeLibrary( hModule ); hModule = NULL; } return NULL; }
std::string AppSecInc::Formatter::FormatHexA(byte * szObj, unsigned long nNum) { std::string to; const int BUF_SIZE = 1024; char szTemp[ BUF_SIZE ]; char szMsg[BUF_SIZE]; unsigned long i; unsigned long j; unsigned long max; to.clear(); if ( szObj == NULL || nNum <= 0 ) { return to; } max = nNum; if ( ( nNum % 8 ) != 0 ) { max += 8 - ( nNum % 8 ); } for ( i = 0; i < max; i += 16 ) { SecureZeroMemory(szTemp, sizeof(szTemp)); SecureZeroMemory(szMsg, sizeof(szMsg)); StringCchPrintfA(szTemp, BUF_SIZE, "%5.5x\t", i); StringCchCopyA(szMsg, BUF_SIZE, szTemp); for( j = 0; j < 16; j++ ) { if ( ( j + i ) < nNum ) { SecureZeroMemory(szTemp, sizeof(szTemp)); StringCchPrintfA(szTemp, BUF_SIZE, "%.2x ", szObj[ j + i ]); if ( strlen( szTemp ) > 3 ) { szTemp[ 0 ] = szTemp[ strlen( szTemp ) - 3 ]; szTemp[ 1 ] = szTemp[ strlen( szTemp ) - 2 ]; szTemp[ 2 ] = ' '; szTemp[ 3 ] = '\0'; } } else { SecureZeroMemory(szTemp, sizeof(szTemp)); StringCchCopyA(szTemp, BUF_SIZE, " "); } StringCchCatA(szMsg, BUF_SIZE, szTemp); } StringCchCatA(szMsg, BUF_SIZE, " "); SecureZeroMemory(szTemp, sizeof(szTemp)); for( j = 0; j < 16 && ( j + i ) < nNum; j++ ) { if ( ( szObj[ j + i ] > 31 ) && ( szObj[ j + i ] < 127 ) ) { szTemp[ 0 ] = szObj[ j + i ]; szTemp[ 1 ] = '\0'; StringCchCatA(szMsg, BUF_SIZE, szTemp); } else { StringCchCatA(szMsg, BUF_SIZE, "."); } } if (to.length() > 0) to.append("\n"); to.append(szMsg); } return to; }
DWORD main(int argc, char **argv) { HANDLE hCompletionPort; BOOL fNeedHelp = FALSE; WCHAR wzzDrop[1024] = L"build\0nmake\0"; GetSystemTimeAsFileTime((FILETIME *)&s_llStartTime); StringCchPrintfA(s_szPipe, ARRAYSIZE(s_szPipe), "%s.%d", TBLOG_PIPE_NAME, GetCurrentProcessId()); int arg = 1; for (; arg < argc && (argv[arg][0] == '-' || argv[arg][0] == '/'); arg++) { CHAR *argn = argv[arg] + 1; CHAR *argp = argn; while (*argp && *argp != ':' && *argp != '=') { argp++; } if (*argp == ':' || *argp == '=') { *argp++ = '\0'; } switch (argn[0]) { case 'd': // Drop Processes case 'D': if (*argp) { PWCHAR pwz = wzzDrop; while (*argp) { if (*argp == ';') { *pwz++ = '\0'; } else { *pwz++ = *argp++; } } *pwz++ = '\0'; *pwz = '\0'; } case 'o': // Output file. case 'O': StringCchCopyA(s_szLogFile, ARRAYSIZE(s_szLogFile), argp); break; case 'v': // Verbose case 'V': s_fVerbose = TRUE; break; case '?': // Help. fNeedHelp = TRUE; break; default: fNeedHelp = TRUE; printf("TRACEBLD: Bad argument: %s:%s\n", argn, argp); break; } } if (arg >= argc) { fNeedHelp = TRUE; } if (fNeedHelp) { printf("Usage:\n" " tracebld [options] command {command arguments}\n" "Options:\n" " /o:file Log all events to the output files.\n" " /? Display this help message.\n" "Summary:\n" " Runs the build commands and figures out which files have dependencies..\n" "\n"); exit(9001); } // Create the completion port. hCompletionPort = CreateIoCompletionPort(INVALID_HANDLE_VALUE, NULL, NULL, 0); if (hCompletionPort == NULL) { MyErrExit("CreateIoCompletionPort"); } // Create completion port worker threads. // CreateWorkers(hCompletionPort); CreatePipeConnection(hCompletionPort, 0); printf("TRACEBLD: Ready for clients. Press Ctrl-C to stop.\n"); /////////////////////////////////////////////////////////// Validate DLLs. // CHAR szTmpPath[MAX_PATH]; CHAR szExePath[MAX_PATH]; CHAR szDllPath[MAX_PATH]; PCHAR pszFilePart = NULL; if (!GetModuleFileNameA(NULL, szTmpPath, ARRAYSIZE(szTmpPath))) { printf("TRACEBLD: Couldn't retreive exe name.\n"); return 9002; } if (!GetFullPathNameA(szTmpPath, ARRAYSIZE(szExePath), szExePath, &pszFilePart) || pszFilePart == NULL) { printf("TRACEBLD: Error: %s is not a valid path name..\n", szTmpPath); return 9002; } StringCchCopyA(pszFilePart, szExePath + ARRAYSIZE(szExePath) - pszFilePart, "trcbld" DETOURS_STRINGIFY(DETOURS_BITS) ".dll"); StringCchCopyA(szDllPath, ARRAYSIZE(szDllPath), szExePath); ////////////////////////////////////////////////////////////////////////// STARTUPINFOA si; PROCESS_INFORMATION pi; CHAR szCommand[2048]; CHAR szExe[MAX_PATH]; CHAR szFullExe[MAX_PATH] = "\0"; PCHAR pszFileExe = NULL; ZeroMemory(&si, sizeof(si)); ZeroMemory(&pi, sizeof(pi)); si.cb = sizeof(si); szCommand[0] = L'\0'; StringCchCopyA(szExe, sizeof(szExe), argv[arg]); for (; arg < argc; arg++) { if (strchr(argv[arg], ' ') != NULL || strchr(argv[arg], '\t') != NULL) { StringCchCatA(szCommand, sizeof(szCommand), "\""); StringCchCatA(szCommand, sizeof(szCommand), argv[arg]); StringCchCatA(szCommand, sizeof(szCommand), "\""); } else { StringCchCatA(szCommand, sizeof(szCommand), argv[arg]); } if (arg + 1 < argc) { StringCchCatA(szCommand, sizeof(szCommand), " "); } } printf("TRACEBLD: Starting: `%s'\n", szCommand); printf("TRACEBLD: with `%s'\n", szDllPath); fflush(stdout); DWORD dwFlags = CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED; SetLastError(0); SearchPathA(NULL, szExe, ".exe", ARRAYSIZE(szFullExe), szFullExe, &pszFileExe); if (!DetourCreateProcessWithDllExA(szFullExe[0] ? szFullExe : NULL, szCommand, NULL, NULL, TRUE, dwFlags, NULL, NULL, &si, &pi, szDllPath, NULL)) { printf("TRACEBLD: DetourCreateProcessWithDllEx failed: %d\n", GetLastError()); ExitProcess(9007); } ZeroMemory(&s_Payload, sizeof(s_Payload)); s_Payload.nParentProcessId = GetCurrentProcessId(); s_Payload.nTraceProcessId = GetCurrentProcessId(); s_Payload.nGeneology = 1; s_Payload.rGeneology[0] = 0; StringCchCopyW(s_Payload.wzStdin, ARRAYSIZE(s_Payload.wzStdin), L"\\\\.\\CONIN$"); StringCchCopyW(s_Payload.wzStdout, ARRAYSIZE(s_Payload.wzStdout), L"\\\\.\\CONOUT$"); StringCchCopyW(s_Payload.wzStderr, ARRAYSIZE(s_Payload.wzStderr), L"\\\\.\\CONOUT$"); StringCchCopyW(s_Payload.wzParents, ARRAYSIZE(s_Payload.wzParents), L""); CopyEnvironment(s_Payload.wzzDrop, wzzDrop); LPWCH pwStrings = GetEnvironmentStringsW(); CopyEnvironment(s_Payload.wzzEnvironment, pwStrings); FreeEnvironmentStringsW(pwStrings); if (!DetourCopyPayloadToProcess(pi.hProcess, s_guidTrace, &s_Payload, sizeof(s_Payload))) { printf("TRACEBLD: DetourCopyPayloadToProcess failed: %d\n", GetLastError()); ExitProcess(9008); } ResumeThread(pi.hThread); WaitForSingleObject(pi.hProcess, INFINITE); DWORD dwResult = 0; if (!GetExitCodeProcess(pi.hProcess, &dwResult)) { printf("TRACEBLD: GetExitCodeProcess failed: %d\n", GetLastError()); return 9008; } printf("TRACEBLD: %d processes.\n", s_nTotalClients); return dwResult; }
/******************************************************************* Dutil_AssertMsg *******************************************************************/ extern "C" void DAPI Dutil_AssertMsg( __in LPCSTR szMessage ) { static BOOL fInAssert = FALSE; // TODO: make this thread safe (this is a cheap hack to prevent re-entrant Asserts) HRESULT hr = S_OK; DWORD er; int id = IDRETRY; HKEY hkDebug = NULL; HANDLE hAssertFile = INVALID_HANDLE_VALUE; char szPath[MAX_PATH] = ""; DWORD cch; if (fInAssert) return; fInAssert = TRUE; char szMsg[DUTIL_STRING_BUFFER]; hr = StringCchCopyA(szMsg, countof(szMsg), szMessage); ExitOnFailure(hr, "failed to copy message while building assert message"); if (Dutil_pfnDisplayAssert) { // call custom function to display the assert string if (!Dutil_pfnDisplayAssert(szMsg)) ExitFunction(); } else OutputDebugStringA(szMsg); if (!Dutil_fNoAsserts) { er = ::RegOpenKeyExW(HKEY_LOCAL_MACHINE, L"SOFTWARE\\Microsoft\\Delivery\\Debug", 0, KEY_QUERY_VALUE, &hkDebug); if (ERROR_SUCCESS == er) { cch = countof(szPath); er = ::RegQueryValueExA(hkDebug, "DeliveryAssertsLog", NULL, NULL, reinterpret_cast<BYTE*>(szPath), &cch); if (ERROR_SUCCESS == er) { hAssertFile = ::CreateFileA(szPath, GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_DELETE, NULL, OPEN_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (INVALID_HANDLE_VALUE != hAssertFile) { ::SetFilePointer(hAssertFile, 0, 0, FILE_END); StringCchCatA(szMsg, countof(szMsg), "\r\n"); ::WriteFile(hAssertFile, szMsg, lstrlenA(szMsg), &cch, NULL); } } } // if anything went wrong while fooling around with the registry, just show the usual assert dialog box if (ERROR_SUCCESS != er) { hr = StringCchCatA(szMsg, countof(szMsg), "\nAbort=Debug, Retry=Skip, Ignore=Skip all"); ExitOnFailure(hr, "failed to concat string while building assert message"); id = ::MessageBoxA(0, szMsg, "Debug Assert Message", MB_SERVICE_NOTIFICATION | MB_TOPMOST | MB_DEFBUTTON2 | MB_ABORTRETRYIGNORE); } } if (id == IDABORT) { if (Dutil_hAssertModule) { ::GetModuleFileNameA(Dutil_hAssertModule, szPath, countof(szPath)); hr = StringCchPrintfA(szMsg, countof(szMsg), "Module is running from: %s\nIf you are not using pdb-stamping, place your PDB near the module and attach to process id: %d (0x%x)", szPath, ::GetCurrentProcessId(), ::GetCurrentProcessId()); if (SUCCEEDED(hr)) ::MessageBoxA(0, szMsg, "Debug Assert Message", MB_SERVICE_NOTIFICATION | MB_TOPMOST | MB_OK); } ::DebugBreak(); } else if (id == IDIGNORE) Dutil_fNoAsserts = TRUE; LExit: if (INVALID_HANDLE_VALUE != hAssertFile) ::CloseHandle(hAssertFile); if (hkDebug) ::RegCloseKey(hkDebug); fInAssert = FALSE; }
//----------------------------------------------------------------------------- // Name: InitGeometry() // Desc: Load the mesh and build the material and texture arrays //----------------------------------------------------------------------------- HRESULT InitGeometry() { LPD3DXBUFFER pD3DXMtrlBuffer; // Load the mesh from the specified file if( FAILED( D3DXLoadMeshFromX( L"Tiger.x", D3DXMESH_SYSTEMMEM, g_pd3dDevice, NULL, &pD3DXMtrlBuffer, NULL, &g_dwNumMaterials, &g_pMesh ) ) ) { // If model is not in current folder, try parent folder if( FAILED( D3DXLoadMeshFromX( L"..\\Tiger.x", D3DXMESH_SYSTEMMEM, g_pd3dDevice, NULL, &pD3DXMtrlBuffer, NULL, &g_dwNumMaterials, &g_pMesh ) ) ) { MessageBox( NULL, L"Could not find tiger.x", L"D3DRenderer", MB_OK ); return E_FAIL; } } // We need to extract the material properties and texture names from the // pD3DXMtrlBuffer D3DXMATERIAL* d3dxMaterials = ( D3DXMATERIAL* )pD3DXMtrlBuffer->GetBufferPointer(); g_pMeshMaterials = new D3DMATERIAL9[g_dwNumMaterials]; if( g_pMeshMaterials == NULL ) return E_OUTOFMEMORY; g_pMeshTextures = new LPDIRECT3DTEXTURE9[g_dwNumMaterials]; if( g_pMeshTextures == NULL ) return E_OUTOFMEMORY; for( DWORD i = 0; i < g_dwNumMaterials; i++ ) { // Copy the material g_pMeshMaterials[i] = d3dxMaterials[i].MatD3D; // Set the ambient color for the material (D3DX does not do this) g_pMeshMaterials[i].Ambient = g_pMeshMaterials[i].Diffuse; g_pMeshTextures[i] = NULL; if( d3dxMaterials[i].pTextureFilename != NULL && lstrlenA( d3dxMaterials[i].pTextureFilename ) > 0 ) { // Create the texture if( FAILED( D3DXCreateTextureFromFileA( g_pd3dDevice, d3dxMaterials[i].pTextureFilename, &g_pMeshTextures[i] ) ) ) { // If texture is not in current folder, try parent folder const CHAR* strPrefix = "..\\"; CHAR strTexture[MAX_PATH]; StringCchCopyA( strTexture, MAX_PATH, strPrefix ); StringCchCatA( strTexture, MAX_PATH, d3dxMaterials[i].pTextureFilename ); // If texture is not in current folder, try parent folder if( FAILED( D3DXCreateTextureFromFileA( g_pd3dDevice, strTexture, &g_pMeshTextures[i] ) ) ) { MessageBox( NULL, L"Could not find texture map", L"D3DRenderer.exe", MB_OK ); } } } } // Done with the material buffer pD3DXMtrlBuffer->Release(); return S_OK; }
PVOID WINAPI DetourFindFunction(PCSTR pszModule, PCSTR pszFunction) { /////////////////////////////////////////////// First, Try GetProcAddress. // HMODULE hModule = LoadLibraryA(pszModule); if (hModule == NULL) { return NULL; } PBYTE pbCode = (PBYTE)GetProcAddress(hModule, pszFunction); if (pbCode) { return pbCode; } ////////////////////////////////////////////////////// Then Try ImageHelp. // PDETOUR_SYM_INFO pSymInfo = DetourLoadImageHlp(); if (pSymInfo == NULL || pSymInfo->pfSymLoadModule64 == NULL || pSymInfo->pfSymGetModuleInfo64 == NULL || pSymInfo->pfSymFromName == NULL) { return NULL; } if ((*pSymInfo->pfSymLoadModule64)(pSymInfo->hProcess, NULL, (PCHAR)pszModule, NULL, (DWORD64)hModule, 0) == 0) { return NULL; } IMAGEHLP_MODULE64 modinfo; ZeroMemory(&modinfo, sizeof(modinfo)); modinfo.SizeOfStruct = sizeof(modinfo); if (!(*pSymInfo->pfSymGetModuleInfo64)(pSymInfo->hProcess, (DWORD64)hModule, &modinfo)) { return NULL; } CHAR szFullName[512]; HRESULT hrRet = E_FAIL; hrRet = StringCchCopyA(szFullName,sizeof(szFullName)/sizeof(CHAR), modinfo.ModuleName); if (FAILED(hrRet)) return NULL; hrRet = StringCchCatA(szFullName, sizeof(szFullName)/sizeof(CHAR), "!"); if (FAILED(hrRet)) return NULL; hrRet = StringCchCatA(szFullName, sizeof(szFullName)/sizeof(CHAR), pszFunction); if (FAILED(hrRet)) return NULL; struct CFullSymbol : SYMBOL_INFO { CHAR szRestOfName[512]; } symbol; ZeroMemory(&symbol, sizeof(symbol)); symbol.SizeOfStruct = sizeof(SYMBOL_INFO); symbol.MaxNameLen = sizeof(symbol.szRestOfName)/sizeof(0); if (!(*pSymInfo->pfSymFromName)(pSymInfo->hProcess, szFullName, &symbol)) { return NULL; } return (PBYTE)symbol.Address; }
int main(int argc, char **argv) { BOOL fNeedHelp = FALSE; BOOL fRequestExitOnClose = FALSE; int arg = 1; for (; arg < argc && (argv[arg][0] == '-' || argv[arg][0] == '/'); arg++) { CHAR *argn = argv[arg] + 1; CHAR *argp = argn; while (*argp && *argp != ':') { argp++; } if (*argp == ':') { *argp++ = '\0'; } switch (argn[0]) { case 'x': // Request exit on close. case 'X': fRequestExitOnClose = TRUE; break; case '?': // Help. fNeedHelp = TRUE; break; default: fNeedHelp = TRUE; printf("SLTEST: Bad argument: %s:%s\n", argn, argp); break; } } if (fNeedHelp) { printf("Usage:\n" " sltest.exe [options] message\n" "Options:\n" " /x Ask syelogd.exe to terminate when this connect closes.\n" " /? Display this help message.\n" "\n"); exit(1); } SyelogOpen("sltest", SYELOG_FACILITY_APPLICATION); if (arg >= argc) { Syelog(SYELOG_SEVERITY_INFORMATION, "Hello World! [1 of 4]"); Syelog(SYELOG_SEVERITY_INFORMATION, "Hello World! [2 of 4]"); Syelog(SYELOG_SEVERITY_INFORMATION, "Hello World! [3 of 4]"); Syelog(SYELOG_SEVERITY_INFORMATION, "Hello World! [4 of 4]"); } else { CHAR Buffer[1024] = ""; for (; arg < argc; arg++) { StringCchCatA(Buffer, ARRAYSIZE(Buffer), argv[arg]); if (arg + 1 < argc) { StringCchCatA(Buffer, ARRAYSIZE(Buffer), " "); } } Syelog(SYELOG_SEVERITY_INFORMATION, Buffer); } SyelogClose(fRequestExitOnClose); return 0; }