COpenSubtitlesSearch::COpenSubtitlesSearch() : m_strUser("") , m_strPass("") , m_authenticated(false) { m_authenticated = CPasswordManager::GetInstance().GetUserPass(ModuleName(), m_strUser, m_strPass); }
/* for temporary testing */ void cCA::Test(int slot, CaIdVector caids) { char buf[255]; char mname[200]; char fname[20]; int count, cx, cy, i; snprintf(fname, sizeof(fname), "/tmp/ci-slot%d" , slot); ModuleName(CA_SLOT_TYPE_CI, slot, mname); FILE* fd = fopen(fname, "w"); if (fd == NULL) return; snprintf(buf, sizeof(buf), "%s\n" , mname); fputs(buf, fd); if (caids.size() > 40) count = 40; else count = caids.size(); cx = snprintf(buf, sizeof(buf), "Anzahl Caids: %d Slot: %d > ", count, slot); for (i = 0; i < count; i++) { cy = snprintf(buf + cx, sizeof(buf) - cx, "%04x ", caids[i]); cx += cy; } snprintf(buf + cx, sizeof(buf) - cx, "\n"); fputs(buf, fd); fclose(fd); }
void MsgModule::ModuleInit() { ConfigModule* conf_module = FindModule<ConfigModule>(app_); // ZMQ初始化 zmq_ctx_ = zmq_init(1); PCHECK(zmq_ctx_ != NULL) << "zmq_init error!"; connsvr_zmq_sock_ = zmq_socket(zmq_ctx_, ZMQ_PAIR); PCHECK(connsvr_zmq_sock_ != NULL) << "zmq_socket error!"; PCHECK(zmq_bind(connsvr_zmq_sock_, conf_module->GetConnsvrZmqAddr()) == 0) << "zmq_bind error!"; datasvr_zmq_sock_ = zmq_socket(zmq_ctx_, ZMQ_PAIR); PCHECK(datasvr_zmq_sock_ != NULL) << "zmq_socket error!"; PCHECK(zmq_connect(datasvr_zmq_sock_, conf_module->GetDatasvrZmqAddr()) == 0) << "zmq_connect error!"; // 注册消息处理函数 REGISTER_MSG_BEGIN(MsgModule, ProtoCs::Msg) REGISTER_MSG(this, ProtoCs::Msg::kQuickRegReqFieldNumber, &MsgModule::OnClientQuickRegReq) REGISTER_MSG(this, ProtoCs::Msg::kNormalRegReqFieldNumber, &MsgModule::OnClientNormalRegReq) REGISTER_MSG(this, ProtoCs::Msg::kLoginReqFieldNumber, &MsgModule::OnClientLoginReq) REGISTER_MSG_END; REGISTER_MSG_BEGIN(MsgModule, ProtoSs::Msg) REGISTER_MSG(this, ProtoSs::Msg::kAccountRegResFieldNumber, &MsgModule::OnDatasvrAccountRegRes) REGISTER_MSG(this, ProtoSs::Msg::kAccountVerifyResFieldNumber, &MsgModule::OnDatasvrAccountVerifyRes) REGISTER_MSG(this, ProtoSs::Msg::kGetPlayerDataResFieldNumber, &MsgModule::OnDatasvrGetPlayerDataRes) REGISTER_MSG(this, ProtoSs::Msg::kSetPlayerDataResFieldNumber, &MsgModule::OnDatasvrSetPlayerDataRes) REGISTER_MSG_END; LOG(INFO) << ModuleName() << " init ok!"; }
void device_node::Dump(int32 level) { put_level(level); kprintf("(%" B_PRId32 ") @%p \"%s\" (ref %" B_PRId32 ", init %" B_PRId32 ", module %p, data %p)\n", level, this, ModuleName(), fRefCount, fInitialized, DriverModule(), DriverData()); AttributeList::Iterator attribute = Attributes().GetIterator(); while (attribute.HasNext()) { dump_attribute(attribute.Next(), level); } DeviceList::Iterator deviceIterator = fDevices.GetIterator(); while (deviceIterator.HasNext()) { Device* device = deviceIterator.Next(); put_level(level); kprintf("device: %s, %p\n", device->ModuleName(), device->Data()); } NodeList::ConstIterator iterator = Children().GetIterator(); while (iterator.HasNext()) { iterator.Next()->Dump(level + 1); } }
std::unique_ptr<CodeGenerator> BuildCodeGen(CompilerInstance &CI, llvm::LLVMContext &LLVMCtx) { StringRef ModuleName("$__module"); return std::unique_ptr<CodeGenerator>(CreateLLVMCodeGen( CI.getDiagnostics(), ModuleName, CI.getHeaderSearchOpts(), CI.getPreprocessorOpts(), CI.getCodeGenOpts(), LLVMCtx)); }
bool device_node::UninitDriver() { if (fInitialized-- > 1) { if (Parent() != NULL) Parent()->UninitDriver(); Release(); return false; } TRACE(("uninit driver for node %p\n", this)); if (fDriver->uninit_driver != NULL) fDriver->uninit_driver(fDriverData); fDriver = NULL; fDriverData = NULL; put_module(ModuleName()); if (Parent() != NULL) Parent()->UninitDriver(); Release(); return true; }
bool COpenSubtitlesSearch::LogIn() { if (!m_authenticated) { m_authenticated = CPasswordManager::GetInstance().SetUserPass(ModuleName(), m_strUser, m_strPass); } std::string strUA = StringUtils::Format("%s_v%i.%i" , CCompileInfo::GetAppName(), CCompileInfo::GetMajor(),CCompileInfo::GetMinor()); StringUtils::ToLower(strUA); ulxr::MethodCall methodcall(ULXR_PCHAR("LogIn")); methodcall.addParam(ulxr::RpcString(ULXR_PCHAR(m_strUser))); // username methodcall.addParam(ulxr::RpcString(ULXR_PCHAR(m_strPass))); // password methodcall.addParam(ulxr::RpcString(ULXR_PCHAR("eng"))); // language methodcall.addParam(ulxr::RpcString(ULXR_PCHAR(strUA))); // useragent string ulxr::MethodResponse response = ServerChat(methodcall); ulxr::Struct cap = response.getResult(); if (response.isOK() && cap.hasMember(ULXR_PCHAR("status"))) { ulxr::RpcString status = cap.getMember(ULXR_PCHAR("status")); CLog::Log(LOGDEBUG, "%s - response - %s", __PRETTY_FUNCTION__, status.getString().c_str()); if (status.getString() == "200 OK") { ulxr::RpcString token = cap.getMember(ULXR_PCHAR("token")); m_strToken = token.getString(); return true; } } return false; }
// Ejects a module (fully qualified path) via process id void Injector::EjectLib(DWORD ProcID, const std::wstring& Path) { // Grab a new snapshot of the process EnsureCloseHandle Snapshot(CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, ProcID)); if (Snapshot == INVALID_HANDLE_VALUE) throw std::runtime_error("Could not get module snapshot for remote process.");; // Get the HMODULE of the desired library MODULEENTRY32W ModEntry = { sizeof(ModEntry) }; bool Found = false; BOOL bMoreMods = Module32FirstW(Snapshot, &ModEntry); for (; bMoreMods; bMoreMods = Module32NextW(Snapshot, &ModEntry)) { std::wstring ModuleName(ModEntry.szModule); std::wstring ExePath(ModEntry.szExePath); Found = (ModuleName == Path || ExePath == Path); if (Found) break; } if (!Found) throw std::runtime_error("Could not find module in remote process.");; // Get a handle for the target process. EnsureCloseHandle Process(OpenProcess( PROCESS_QUERY_INFORMATION | PROCESS_CREATE_THREAD | PROCESS_VM_OPERATION, // For CreateRemoteThread FALSE, ProcID)); if (!Process) throw std::runtime_error("Could not get handle to process."); // Get the real address of LoadLibraryW in Kernel32.dll HMODULE hKernel32 = GetModuleHandle(TEXT("Kernel32")); if (hKernel32 == NULL) throw std::runtime_error("Could not get handle to Kernel32."); PTHREAD_START_ROUTINE pfnThreadRtn = (PTHREAD_START_ROUTINE) GetProcAddress(hKernel32, "FreeLibrary"); if (pfnThreadRtn == NULL) throw std::runtime_error("Could not get pointer to FreeLibrary."); // Create a remote thread that calls FreeLibrary() EnsureCloseHandle Thread(CreateRemoteThread(Process, NULL, 0, pfnThreadRtn, ModEntry.modBaseAddr, 0, NULL)); if (!Thread) throw std::runtime_error("Could not create thread in remote process."); // Wait for the remote thread to terminate WaitForSingleObject(Thread, INFINITE); // Get thread exit code DWORD ExitCode; if (!GetExitCodeThread(Thread,&ExitCode)) throw std::runtime_error("Could not get thread exit code."); // Check LoadLibrary succeeded and returned a module base if(!ExitCode) throw std::runtime_error("Call to FreeLibrary in remote process failed."); }
status_t device_node::InitDriver() { if (fInitialized++ > 0) { if (Parent() != NULL) { Parent()->InitDriver(); // acquire another reference to our parent as well } Acquire(); return B_OK; } status_t status = get_module(ModuleName(), (module_info**)&fDriver); if (status == B_OK && Parent() != NULL) { // our parent always has to be initialized status = Parent()->InitDriver(); } if (status < B_OK) { fInitialized--; return status; } if (fDriver->init_driver != NULL) { status = fDriver->init_driver(this, &fDriverData); if (status != B_OK) { dprintf("driver %s init failed: %s\n", ModuleName(), strerror(status)); } } if (status < B_OK) { if (Parent() != NULL) Parent()->UninitDriver(); fInitialized--; put_module(ModuleName()); fDriver = NULL; fDriverData = NULL; return status; } Acquire(); return B_OK; }
status_t Device::InitDevice() { RecursiveLocker _(sLock); if ((fNode->Flags() & NODE_FLAG_DEVICE_REMOVED) != 0) { // TODO: maybe the device should be unlinked in devfs, too return ENODEV; } if ((fNode->Flags() & NODE_FLAG_WAITING_FOR_DRIVER) != 0) return B_BUSY; if (fInitialized++ > 0) { fNode->InitDriver(); // acquire another reference to our parent as well return B_OK; } status_t status = get_module(ModuleName(), (module_info**)&fDeviceModule); if (status == B_OK) { // our parent always has to be initialized status = fNode->InitDriver(); } if (status < B_OK) { fInitialized--; return status; } if (Module()->init_device != NULL) status = Module()->init_device(fNode->DriverData(), &fDeviceData); if (status < B_OK) { fNode->UninitDriver(); fInitialized--; put_module(ModuleName()); fDeviceModule = NULL; fDeviceData = NULL; } return status; }
Dictionary Function::SerializeNativeImpl() const { Dictionary dict; dict[userDefinedStateKey] = Serialize(); dict[udfModuleNameKey] = ModuleName(); dict[udfFactoryMethodNameKey] = DeserializeMethodName(); dict[opKey] = OpName(); dict[versionKey] = s_serializationVersion; dict[typeKey] = s_nativeUDFTypeValue; return dict; }
void MsgModule::ModuleFini() { // zmq 释放 if (connsvr_zmq_sock_ != NULL) zmq_close(connsvr_zmq_sock_); if (datasvr_zmq_sock_ != NULL) zmq_close(datasvr_zmq_sock_); if (zmq_ctx_ != NULL) zmq_term(zmq_ctx_); LOG(INFO) << ModuleName() << " fini completed!"; }
void EventModule::ModuleFini() { // fd 释放 close(listen_fd_); // zmq 释放 zmq_close(zmq_sock_); zmq_term(zmq_ctx_); delete(epoller_); LOG(INFO) << ModuleName() << " fini completed!"; }
void EventModule::ModuleInit() { // TCP 初始化 listen_fd_ = socket(AF_INET, SOCK_STREAM, 0); PCHECK(listen_fd_ > 0) << "socket error!"; Epoller::SetNonBlock(listen_fd_); Epoller::SetSocketOpt(listen_fd_); ConfigModule* conf_module = FindModule<ConfigModule>(app_); int32_t listen_port = conf_module->config().listen_port(); struct sockaddr_in sin; sin.sin_family = AF_INET; sin.sin_addr.s_addr = 0; sin.sin_port = htons(listen_port); CHECK(bind(listen_fd_, (struct sockaddr*)&sin, sizeof(sin)) == 0) << "bind error!"; CHECK(listen(listen_fd_, 32) == 0) << "listen error!"; // ZMQ初始化 zmq_ctx_ = zmq_init(1); PCHECK(zmq_ctx_ != NULL) << "zmq_init error!"; zmq_sock_ = zmq_socket(zmq_ctx_, ZMQ_PAIR); PCHECK(zmq_sock_ != NULL) << "zmq_socket error!"; PCHECK(zmq_connect(zmq_sock_, conf_module->config().gamesvr_zmq_addr().c_str()) == 0) << "zmq_connect error!"; // 初始化 Epoller int32_t conn_pool_size = conf_module->config().conn_pool_size(); epoller_ = new Epoller(); epoller_->Init(conn_pool_size); // 增加tcp accept事件 int ret = epoller_->AddEvent(listen_fd_, EVENT_READ, EventModule::DoTcpAccept, (void*)epoller_); CHECK(ret == 0) << "epoller_.AddEvent error."; LOG(INFO) << ModuleName() << " init ok!"; }
void Device::UninitDevice() { RecursiveLocker _(sLock); if (fInitialized-- > 1) { fNode->UninitDriver(); return; } TRACE(("uninit driver for node %p\n", this)); if (Module()->uninit_device != NULL) Module()->uninit_device(fDeviceData); fDeviceModule = NULL; fDeviceData = NULL; put_module(ModuleName()); fNode->UninitDriver(); }
void COpenSubtitlesSearch::ChangeUserPass() { m_authenticated = CPasswordManager::GetInstance().SetUserPass(ModuleName(), m_strUser, m_strPass); }
// nTimeout - таймаут подключения HANDLE ExecuteOpenPipe(const wchar_t* szPipeName, wchar_t (&szErr)[MAX_PATH*2], const wchar_t* szModule, DWORD nServerPID, DWORD nTimeout) { HANDLE hPipe = NULL; DWORD dwErr = 0, dwMode = 0; BOOL fSuccess = FALSE; DWORD dwStartTick = GetTickCount(); DWORD nSleepError = 10; int nTries = 10; // допустимое количество обломов, отличных от ERROR_PIPE_BUSY. после каждого - Sleep(nSleepError); DWORD nOpenPipeTimeout = nTimeout ? max(nTimeout,EXECUTE_CMD_OPENPIPE_TIMEOUT) : EXECUTE_CMD_OPENPIPE_TIMEOUT; BOOL bWaitPipeRc = FALSE, bWaitCalled = FALSE; DWORD nWaitPipeErr = 0; DWORD nDuration = 0; #ifdef _DEBUG wchar_t szDbgMsg[512], szTitle[128]; #endif _ASSERTE(LocalSecurity()!=NULL); #ifdef _DEBUG BOOL lbServerIsDebugged = FALSE; // WinXP SP1 и выше typedef BOOL (WINAPI* CheckRemoteDebuggerPresent_t)(HANDLE hProcess, PBOOL pbDebuggerPresent); static CheckRemoteDebuggerPresent_t _CheckRemoteDebuggerPresent = NULL; if (nServerPID) { if (!_CheckRemoteDebuggerPresent) _CheckRemoteDebuggerPresent = (CheckRemoteDebuggerPresent_t)GetProcAddress(GetModuleHandle(L"kernel32.dll"), "CheckRemoteDebuggerPresent"); if (_CheckRemoteDebuggerPresent) { HANDLE hProcess = OpenProcess(MY_PROCESS_ALL_ACCESS, FALSE, nServerPID); if (hProcess) { BOOL lb = FALSE; if (_CheckRemoteDebuggerPresent(hProcess, &lb) && lb) lbServerIsDebugged = TRUE; CloseHandle(hProcess); } } } #endif // 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 0, // default attributes NULL); // no template file dwErr = GetLastError(); // Break if the pipe handle is valid. if (hPipe != INVALID_HANDLE_VALUE) break; // OK, открыли #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 (dwErr == ERROR_PIPE_BUSY) { if ((nTries > 0) && (nDuration < nOpenPipeTimeout)) { bWaitCalled = TRUE; // All pipe instances are busy, so wait for 500 ms. bWaitPipeRc = WaitNamedPipe(szPipeName, 500); nWaitPipeErr = GetLastError(); UNREFERENCED_PARAMETER(bWaitPipeRc); UNREFERENCED_PARAMETER(nWaitPipeErr); // -- 120602 раз они заняты (но живы), то будем ждать, пока не освободятся //nTries--; continue; } else { _ASSERTEX(dwErr != ERROR_PIPE_BUSY); } } // Сделаем так, чтобы хотя бы пару раз он попробовал повторить if ((nTries <= 0) || (nDuration > nOpenPipeTimeout)) { //if (pszErr) { msprintf(szErr, countof(szErr), L"%s.%u: CreateFile(%s) failed, code=0x%08X, Timeout", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); } return NULL; } else { nTries--; } // Может быть пайп еще не создан (в процессе срабатывания семафора) if (dwErr == ERROR_FILE_NOT_FOUND) { Sleep(nSleepError); continue; } // Exit if an error other than ERROR_PIPE_BUSY occurs. // -- if (dwErr != ERROR_PIPE_BUSY) // уже проверено выше { //if (pszErr) { msprintf(szErr, countof(szErr), L"%s.%u: CreateFile(%s) failed, code=0x%08X", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); } 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 = PIPE_READMODE_MESSAGE; 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 return hPipe; }
static void stack_trace( PEXCEPTION_POINTERS pInfo ) { char message[1024]; int len = 0; size_t i; HANDLE process = GetCurrentProcess(); HANDLE thread = GetCurrentThread(); IMAGEHLP_LINE64 line; DWORD dline = 0; DWORD options; CONTEXT context; STACKFRAME64 stackframe; DWORD image; memcpy( &context, pInfo->ContextRecord, sizeof(CONTEXT) ); options = SymGetOptions(); options |= SYMOPT_DEBUG; options |= SYMOPT_LOAD_LINES; SymSetOptions( options ); SymInitialize( process, NULL, TRUE ); ZeroMemory( &stackframe, sizeof(STACKFRAME64) ); #ifdef _M_IX86 image = IMAGE_FILE_MACHINE_I386; stackframe.AddrPC.Offset = context.Eip; stackframe.AddrPC.Mode = AddrModeFlat; stackframe.AddrFrame.Offset = context.Ebp; stackframe.AddrFrame.Mode = AddrModeFlat; stackframe.AddrStack.Offset = context.Esp; stackframe.AddrStack.Mode = AddrModeFlat; #elif _M_X64 image = IMAGE_FILE_MACHINE_AMD64; stackframe.AddrPC.Offset = context.Rip; stackframe.AddrPC.Mode = AddrModeFlat; stackframe.AddrFrame.Offset = context.Rsp; stackframe.AddrFrame.Mode = AddrModeFlat; stackframe.AddrStack.Offset = context.Rsp; stackframe.AddrStack.Mode = AddrModeFlat; #elif _M_IA64 image = IMAGE_FILE_MACHINE_IA64; stackframe.AddrPC.Offset = context.StIIP; stackframe.AddrPC.Mode = AddrModeFlat; stackframe.AddrFrame.Offset = context.IntSp; stackframe.AddrFrame.Mode = AddrModeFlat; stackframe.AddrBStore.Offset = context.RsBSP; stackframe.AddrBStore.Mode = AddrModeFlat; stackframe.AddrStack.Offset = context.IntSp; stackframe.AddrStack.Mode = AddrModeFlat; #endif len += snprintf( message + len, 1024 - len, "Sys_Crash: address %p, code %p\n", pInfo->ExceptionRecord->ExceptionAddress, pInfo->ExceptionRecord->ExceptionCode ); if( SymGetLineFromAddr64( process, (DWORD64)pInfo->ExceptionRecord->ExceptionAddress, &dline, &line ) ) { len += snprintf(message + len, 1024 - len,"Exception: %s:%d:%d\n", (char*)line.FileName, (int)line.LineNumber, (int)dline); } if( SymGetLineFromAddr64( process, stackframe.AddrPC.Offset, &dline, &line ) ) { len += snprintf(message + len, 1024 - len,"PC: %s:%d:%d\n", (char*)line.FileName, (int)line.LineNumber, (int)dline); } if( SymGetLineFromAddr64( process, stackframe.AddrFrame.Offset, &dline, &line ) ) { len += snprintf(message + len, 1024 - len,"Frame: %s:%d:%d\n", (char*)line.FileName, (int)line.LineNumber, (int)dline); } for( i = 0; i < 25; i++ ) { char buffer[sizeof(SYMBOL_INFO) + MAX_SYM_NAME * sizeof(TCHAR)]; PSYMBOL_INFO symbol = (PSYMBOL_INFO)buffer; BOOL result = StackWalk64( image, process, thread, &stackframe, &context, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL); DWORD64 displacement = 0; if( !result ) break; symbol->SizeOfStruct = sizeof(SYMBOL_INFO); symbol->MaxNameLen = MAX_SYM_NAME; len += snprintf( message + len, 1024 - len, "% 2d %p", i, (void*)stackframe.AddrPC.Offset ); if( SymFromAddr( process, stackframe.AddrPC.Offset, &displacement, symbol ) ) { len += snprintf( message + len, 1024 - len, " %s ", symbol->Name ); } if( SymGetLineFromAddr64( process, stackframe.AddrPC.Offset, &dline, &line ) ) { len += snprintf(message + len, 1024 - len,"(%s:%d:%d) ", (char*)line.FileName, (int)line.LineNumber, (int)dline); } len += snprintf( message + len, 1024 - len, "("); len += ModuleName( process, message + len, (void*)stackframe.AddrPC.Offset, 1024 - len ); len += snprintf( message + len, 1024 - len, ")\n"); } #ifdef XASH_SDL if( host.type != HOST_DEDICATED ) // let system to restart server automaticly SDL_ShowSimpleMessageBox( SDL_MESSAGEBOX_ERROR,"Sys_Crash", message, host.hWnd ); #endif Sys_PrintLog(message); SymCleanup(process); }
// 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*/) { HANDLE hPipe = NULL; DWORD dwErr = 0, dwMode = 0; BOOL fSuccess = FALSE; DWORD dwStartTick = GetTickCount(); DWORD nSleepError = 10; // допустимое количество обломов, отличных от ERROR_PIPE_BUSY. после каждого - Sleep(nSleepError); int nTries = 10; // 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 != INVALID_HANDLE_VALUE) { _ASSERTE(hPipe); break; // OK, открыли } #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)) { //if (pszErr) { msprintf(szErr, countof(szErr), L"%s.%u: CreateFile(%s) failed, code=0x%08X, Timeout", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); _ASSERTEX(FALSE && "Pipe open failed with timeout!"); } 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) // уже проверено выше { //if (pszErr) { msprintf(szErr, countof(szErr), L"%s.%u: CreateFile(%s) failed, code=0x%08X", ModuleName(szModule), GetCurrentProcessId(), szPipeName, dwErr); } 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; }