void ResourceManager::AddMesh( sf::Uint32 id, std::string mesh_file ) { std::ifstream file( mesh_file.c_str() ); if( !file.good() ) { LogConsole( "Failed to load Mesh resource " + string_cast( id ) + ", file not good." ); return; } std::vector<sf::Vector3f> vertices; std::vector<sf::Vector3i> faces; std::string line; getline( file, line ); char type; sf::Vector3f vertex; sf::Vector3i face; while( file.good() ) { std::stringstream line_stream( line ); line_stream >> type; if( !line_stream.good() ) { LogConsole( "Failed to load Mesh resource " + string_cast( id ) + ", line stream not good." ); return; } if( type == 'v' ) { line_stream >> vertex.x >> vertex.y >> vertex.z; vertices.push_back( vertex ); } else if( type == 'f' ) {
void Player::HandlePacket( PacketPtr packet ) { if( packet->getDataSize() < 4 ) { LogConsole("Player sent packet size < 4"); return; } ObjectPtr agent( m_agent.lock() ); if( !agent ) { LogConsole( "Player agent deleted, deleting player." ); Delete(); return; } sf::Uint16 type0; (*packet) >> type0; switch( type0 ) { case ClientToServer::CLIENT_COMMAND: agent->HandlePacket( packet ); break; default: LogConsole( "Player sent packet with type0=" + string_cast( type0 ) ); break; } }
extern "C" __declspec(dllexport) void ExecuteLua(PVOID message) { PINIT_STRUCT messageStruct = reinterpret_cast<PINIT_STRUCT>(message); int result = luaL_loadbuffer_ss(luaPtr, messageStruct->Message, strlen(messageStruct->Message), messageStruct->Message) || lua_pcall_ss(luaPtr, 0, LUA_MULTRET, 0); if(result == 0) { LogConsole("[Run Lua] %s ran successfully\n", messageStruct->Message); } else { LogConsole("[Run Lua] %s failed\n", messageStruct->Message); } }
bool SigScanFunction(CSimpleScan &scan, const char *name, const char *sig, const char *mask, void **func) { if(scan.FindFunction(sig, mask, func)) { LogConsole("[SigScan] %s found at 0x%x\n", name, *func); return true; } else { LogConsole("[SigScan] %s not found\n", name); return false; } }
BOOL WINAPI DllMain( HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpvReserved ) { if(fdwReason == DLL_PROCESS_ATTACH) { AllocConsole(); logFile = fopen("injectedLog.txt", "w"); if(logFile == NULL) { return TRUE; } LogConsole("====== Driver San Francisco Mod Injector Started ======\n"); CSimpleScan driverGame("Driver.exe"); bool success = SigScanFunction(driverGame, "ri_dofile", RI_DOFILE_SIG, RI_DOFILE_MASK, (void **)&ri_dofile_Orig) && SigScanFunction(driverGame, "ri_loadfile", RI_LOADFILE_SIG, RI_LOADFILE_MASK, (void **)&ri_loadfile_Orig) && SigScanFunction(driverGame, "luaL_checklstring", LUAL_CHECKLSTRING_SIG, LUAL_CHECKLSTRING_MASK, (void **)&luaL_checklstring_ss) && SigScanFunction(driverGame, "lua_setfield", LUA_SETFIELD_SIG, LUA_SETFIELD_MASK, (void **)&lua_setfield_ss) && SigScanFunction(driverGame, "lua_pushcclosure", LUA_PUSHCCLOSURE_SIG, LUA_PUSHCCLOSURE_SIG, (void **)&lua_pushcclosure_ss) && SigScanFunction(driverGame, "lua_pcall", LUA_PCALL_SIG, LUA_PCALL_SIG, (void **)&lua_pcall_ss) && SigScanFunction(driverGame, "luaL_loadbuffer", LUAL_LOADBUFFER_SIG, LUAL_LOADBUFFER_SIG, (void **)&luaL_loadbuffer_ss); if(!success) { LogConsole("[SigScan] A function was not found. Halting execution.\n"); return TRUE; } ri_loadfile_Detour.Attach(); LogConsole("[Detours] ri_loadfile detoured\n"); ri_dofile_Detour.Attach(); LogConsole("[Detours] ri_dofile detoured\n"); } else if (fdwReason == DLL_PROCESS_DETACH) { LogConsole("====== DLL Detached ======\n"); ri_loadfile_Detour.Detach(); ri_dofile_Detour.Detach(); FreeConsole(); fclose(logFile); } return TRUE; }
void LogFileInitialize(void) { FILE* f; const char* logFilename = GetLogFilename(); // It is valid for there to be no Log File. However since this // is the only place where the log file is initialized, we flag // it as something to note in the console. if (logFilename != NULL) { // Open for writing - this will overwrite any previous logfile fopen_s(&f, logFilename, "w+"); // read binary if (f != NULL) { fprintf(f, "Logging Started: %s\n\n", GetTimeStr().asCharArray()); fclose(f); } else { LogConsole(logERROR, "Unable to open logfile %s for writing \n", logFilename); } } }
void CapturedAPICalls::PlayCapture() { unsigned int i = 0; try { for (CaptureList::iterator iter = m_captureList.begin(); iter != m_captureList.end(); ++iter) { if (m_LogCallsAsItReplays) { LogConsole(logMESSAGE, "replay: %4i %s\n", i, (*iter)->Print().c_str()); } // Debugging code used to locate which API call index is causing a problem //if (i % 1000 == 0) //{ //Log(logDEBUG, "Replay Index: %ld\n", i); //Log(logDEBUG, "replay: %4i %s\n", i, (*iter)->Print().c_str()); //} (*iter)->Play(); i++; } } catch (...) { OSWrappers::MessageBox(FormatString("Frame Capture playback: Exception at drawcall %i", i).c_str(), (const char*)"Exception!", 0); } }
//////////////////////////////////////////////////////////////////////// /// Writes a message to the console /// \param msg The message to display. //////////////////////////////////////////////////////////////////////// void ClientRequestThread::OutputScreenMessage(const char* msg) { PsAssert(s_output_criticalSection != NULL); s_output_criticalSection->enter(); LogConsole(logMESSAGE, "%s\n", msg); s_output_criticalSection->leave(); }
void RegisterCFunction(lua_State* L, lua_CFunction func, const char* name) { (*lua_pushcclosure_ss)(L, func, 0); (*lua_setfield_ss)(L, LUA_GLOBALSINDEX, name); LogConsole("[Lua C Funcs] %s registered in Lua\n", name); }
//////////////////////////////////////////////////////////////////////// /// Writes an error to the console. It clears the error before exiting. /// \param errmsg The message to display. //////////////////////////////////////////////////////////////////////// void ClientRequestThread::OutputScreenError(const char* errmsg) { PsAssert(s_output_criticalSection != NULL); s_output_criticalSection->enter(); LogConsole(logERROR, "%s - %i\n", errmsg, NetSocket::LastError()); s_output_criticalSection->leave(); }
bool Lock() { if (m_mutex->OpenOrCreate(s_mutexName) == false) { LogConsole(logERROR, "Could not create Mutex (%d).\n", osGetLastSystemError()); return (false); } if (m_mutex->Lock() == false) { LogConsole(logERROR, "Could not Lock Mutex (%d).\n", osGetLastSystemError()); return (false); } return true; }
void Player::Auth( PacketPtr packet ) { PacketPtr reply = std::make_shared<sf::Packet>(); if( CheckAuth( packet ) ) { (*reply) << sf::String("Authentication successful"); SendPacket( reply, true ); LogConsole("Authentication successful"); m_half_open = false; } else { (*reply) << sf::String("Authentication failed"); SendPacket( reply, true ); LogConsole( "Authentication failed: " + GetName() + " disconnected (auth failure).." ); Delete(); } }
Player::~Player() { ObjectPtr agent( m_agent.lock() ); if( agent ) { agent->Delete(); } LogConsole( "Player " + string_cast( m_id ) + " destroyed" ); }
//-------------------------------------------------------------- /// Initializes webserver /// \param port Port to listen on. /// \return Socket to listen to. //-------------------------------------------------------------- NetSocket* WebServerSetup(int port) { NetSocket* server_socket; s_dwPort = port; #ifdef DEBUG_COMMS_PERFORMANCE // set the performance counter frequency unsigned __int64 nPerfCountFreq ; QueryPerformanceFrequency((LARGE_INTEGER*)&nPerfCountFreq); CommandTimingManager::Instance()->SetPerformanceCounterFrequency(1.0 / (double)nPerfCountFreq); #endif s_output_criticalSection = new osCriticalSection(); NetSocket* s = NetSocket::Create(); if (s == NULL) { LogConsole(logERROR, "Error creating sock()\n"); return NULL; } // init the webserver server_socket = WebServerBind(s); if (server_socket) { if (WebServerListen(server_socket)) { return server_socket; } else { LogConsole(logERROR, "can't listen\n"); } } else { LogConsole(logERROR, "Error binding socket\n"); } return NULL; }
//------------------------------------------------------------------------------ ///load 被分割地图的.project file void CLocalSplitMapSaver::LoadAsMapProject(const string& path) { if( path.empty() ) { MessageBox(NULL, "被分割的地图名为空", "提示", MB_OK); return; } string strFile = path; strFile += ".project"; ////////////////////////////////////////////////////////////////////////// ///load map project LogConsole(strFile.c_str()); SQR_TRY { locale::global(locale("")); ifstream in(strFile.c_str()); CXmlConfig *pMapProjectFile = new CXmlConfig( "x", in ); ///x property TiXmlNode *pResourceSetNode = pMapProjectFile->Get<TiXmlElement*>("图素集"); if( pResourceSetNode ) { TiXmlElement *pElement = pResourceSetNode->ToElement(); if( pElement ) { int nCnt = atoi(pElement->Attribute("ResSetCount")); for ( int i = 0; i < nCnt; ++i ) { TCHAR s[64]; sprintf(s,"ResSetFileName%d",i); string str = pElement->Attribute(s); setTitleResourceName.insert(str); } } } in.close(); delete pMapProjectFile; pMapProjectFile = NULL; } SQR_CATCH(exp) { MessageBox(NULL, exp.ErrorMsg(), "错误", MB_OK); return; } SQR_TRY_END; }
void Player::SetAgent( ObjectPtr agent ) { if( !agent ) { LogConsole( "Tried to set non-existing agent, deleting player." ); Delete(); return; } m_agent = ObjectWeakPtr( agent ); agent->SetName( GetName() ); PacketPtr packet = std::make_shared<sf::Packet>(); (*packet) << static_cast<sf::Uint16>( ServerToClient::SERVER_SET_ID ) << agent->GetId(); SendPacket( packet ); }
int ri_dofile_New(lua_State *L, const char *filename) { LogConsole("[ri_dofile] filename = %s\n", filename); luaPtr = L; if(!injectedFunctions) { RegisterCFunction(L, lua_log, "injectedLog"); injectedFunctions = true; } return (*ri_dofile_Orig)(L, filename); }
void Player::Update() { m_inventory->SendUpdate( shared_from_this() ); FlushBuffer(); HandleSocketData(); ObjectPtr agent( m_agent.lock() ); if( !agent ) { LogConsole( "Player agent deleted, deleting player." ); Delete(); return; } }
//----------------------------------------------------------------------------- /// Initialize all class data. This should only be called once /// \return true if everything is properly initialized; false otherwise //----------------------------------------------------------------------------- bool SharedGlobal::Initialize() { // Create the Mutex used to control access to the Shared Memory block m_Mutex = new osMutex(); SharedMemory::MemStatus status = m_MapFile->OpenOrCreate(sizeof(PsSharedGlobal), SHARED_MEMORY_NAME); if (SharedMemory::ERROR_CREATE == status) { LogConsole(logERROR, "Could not create file mapping object (%d).\n", osGetLastSystemError()); return (false); } if (SharedMemory::ERROR_MAPPING == status) { LogConsole(logERROR, "Could not map view of file (%d).\n", osGetLastSystemError()); return (false); } m_bInitialized = true; return (true); }
//----------------------------------------------------------------------------- /// Provides access to the single instance of this class in the process. If the /// class does not exist, it will initialize it and log any errors that occur. /// \return pointer to the instance of this class. //----------------------------------------------------------------------------- SharedGlobal* SharedGlobal::Instance(void) { static SharedGlobal* sg = new SharedGlobal; PsAssert(sg != NULL); if (!sg->m_bInitialized && !sg->Initialize()) { LogConsole(logERROR, "Unable to create SharedGlobal data\n"); delete sg; sg = NULL; } return (sg); }
void Player::HandleSocketData() { while( !m_recv_buffer.empty() ) { PacketPtr packet = m_recv_buffer.front(); if( !m_half_open ) { HandlePacket( packet ); } else { LogConsole( "Client " + string_cast( m_id ) + " sent auth data" ); Auth( packet ); } m_recv_buffer.pop_front(); } }
Object::Object( sf::Uint16 type, sf::String name, sf::Vector2f size, sf::Vector2f position, sf::Vector2f velocity, float rotation, float rotational_velecity ) : m_id( Game::GetGame()->GetObjectManager()->NewID() ), m_type( type ), m_name( name ), m_resource_id( 0 ), m_size( size ), m_position( position ), m_velocity( velocity ), m_rotation( rotation ), m_rotational_velocity( rotational_velecity ), m_delete_me( false ), m_dirty( true ), m_fresh( true ) { LogConsole( "Created object " + string_cast( m_id ) + " of type " + string_cast( m_type ) ); }
void Player::SetAgent( sf::Uint16 id ) { m_tentative_agent_id = id; ObjectPtr object = Game::GetGame()->GetObjectManager()->GetObjectById( id ); if( !object ) { return; } if( object->GetType() != ObjectType::SHIP ) { return; } ShipPtr agent = std::static_pointer_cast<Ship>( Game::GetGame()->GetObjectManager()->GetObjectById( id ) ); agent->SetPlayer( true ); LogConsole( "Set player ship to object: " + string_cast( id ) ); m_tentative_agent_id = 0xffff; m_agent = agent; }
Player::Player( ObjectPtr agent ) : m_id( Game::GetGame()->GetPlayerManager()->NewID() ), m_delete_me( false ), m_half_open( true ), m_agent(), m_inventory( std::make_shared<Inventory>() ) { LogConsole( "Player " + string_cast( m_id ) + " created" ); // Set agent SetAgent( agent ); ItemPtr some_item = std::make_shared<Item>( "Some Item", "Some Type" ); ItemPtr another_item = std::make_shared<Item>( "Another Item", "Another Type" ); m_inventory->AddItem( some_item, 3 ); m_inventory->AddItem( another_item, 1 ); m_inventory->RemoveItem( some_item, 1 ); }
void LogPrintf(int Level, const char *format, ...) { va_list args; char buffer[2048]; va_start(args, format); vsnprintf_s(buffer, 2047, 2047, format, args); va_end(args); if (log == NULL) { fopen_s(&log, "libm3.log", "w"); } // Create log message std::string Log = StringFromFormat("%s %s", GetTimeFormatted().c_str(), buffer); fwrite(Log.c_str(), 1, strlen(Log.c_str()), log); fflush(log); LogConsole(Level, Log); }
// // Write log messages into the logfile. // static void _logWrite(const char* pMessage) { FILE* f; const char* logFilename = GetLogFilename(); if (logFilename != NULL) { if (LogMutexLock()) // wait for exclusive access to logfile { fopen_s(&f, logFilename, "a+"); // append if (f != NULL) { fprintf(f, "%s", pMessage); fclose(f); } else { #if defined (_WIN32) __declspec(thread) static bool recursiveWrite = false; // Avoid getting into an infinite loop if file can't be opened. #elif defined (_LINUX) static __thread bool recursiveWrite = false; // Avoid getting into an infinite loop if file can't be opened. #endif if (!recursiveWrite) { recursiveWrite = true; LogConsole(logERROR, "Unable to open logfile %s for append. Message Dropped = \n\t%s\n", logFilename, pMessage); recursiveWrite = false; } } LogMutexUnlock(); } } }
//-------------------------------------------------------------------------- /// Should be called by an API-specific FrameDebugger at each drawcall /// \param rDrawCall the API-specific DrawCall that is being executed //-------------------------------------------------------------------------- void FrameDebugger::OnDrawCall(IDrawCall& rDrawCall) { m_ulDrawCallCounter++; if (m_drawCallList.IsActive()) { m_LastDrawCall = &rDrawCall; gtASCIIString xmlString = rDrawCall.GetXML(); xmlString += XML("hash", rDrawCall.GetHash().asCharArray()); m_drawCallList += GetDrawCallXML(m_ulDrawCallCounter, xmlString.asCharArray()) ; } // Could collect drawcall XML here if desired if (IsDrawCallEnabled(m_ulDrawCallCounter)) { // Make sure to not render after the frame debugger's break point if (IsTargetDrawCall(m_ulDrawCallCounter) == false) { // execute the drawcall for the app rDrawCall.Execute(); } else { // have the pipeline process non-hud commands before drawing anything on HUD OnDrawCallAtBreakPointPreHUD(rDrawCall); // allow the API-specific FrameDebugger to decide whether or not to do the drawcall at the breakpoint DoDrawCallAtBreakPoint(rDrawCall); // Send the current draw call back to the client. if (m_CurrentDrawCall.IsActive()) { m_CurrentDrawCall.Send(rDrawCall.GetXML().asCharArray()); } bool bRes = BeginHUD(); PsAssert(bRes != false); if (bRes == false) { Log(logERROR, "BeginHUD() failed"); return; } // show the wireframe overlay if (m_bWireframeOverlay) { DoWireframeOverlay(rDrawCall, m_fWireframeOverlayColor[0], m_fWireframeOverlayColor[1], m_fWireframeOverlayColor[2], m_fWireframeOverlayColor[3]); } if (m_bAutoRenderTarget) { DoAutoRenderTarget(); } OnDrawCallAtBreakPoint(rDrawCall); EndHUD(); // skip the rest of the draws if HUD is being configured if (false == m_bConfigHUD) { // When the frame debugger is enabled we process the messages from inside the FD and no longer re-render the Frame Capture. This speeds up processing of messages // in apps that are running very slowly for (int ProcessedCommands = 0;;) { if (m_drawCallList.IsActive() == true || m_Stats.IsActive() == true) { break; } // have the pipeline process non-hud commands before drawing anything on HUD OnDrawCallAtBreakPointPreHUD(rDrawCall); OnDrawCallAtBreakPoint(rDrawCall); gtASCIIString SuCmd = PeekPendingRequests(); // Check for non FD command, if this changes then we have to re-render the HUD etc. So we break out if (SuCmd.length() != 0) { char* pCmd = (char*)SuCmd.asCharArray(); ProcessedCommands++; if (strstr(pCmd, "FD/Pipeline") == NULL) { LogConsole(logMESSAGE, "Processed in FD %3u\n", ProcessedCommands); break; } GetSinglePendingRequest(); } } } } } }
//-------------------------------------------------------------- // LaunchAppInNewProcess //-------------------------------------------------------------- PROCESS_INFORMATION ProcessTracker::LaunchAppInNewProcess(gtASCIIString strApp, gtASCIIString strDir, gtASCIIString strArgs, osModuleArchitecture binaryType) { #ifdef _LINUX PS_UNREFERENCED_PARAMETER(binaryType); #endif LogConsole(logMESSAGE, "About to launch: %s\n", strApp.asCharArray()); LogConsole(logMESSAGE, "Params: %s\n", strArgs.asCharArray()); LogConsole(logMESSAGE, "Working Directory: %s\n", strDir.asCharArray()); // Get app directory and make it default if (strDir.isEmpty()) { size_t pos = strApp.find_last_of("\\"); if (pos != std::string::npos) { strDir = strApp.substr(0, (int)pos); if (strApp[0] == '\"') { strDir += "\""; } } } PROCESS_INFORMATION pi; ZeroMemory(&pi, sizeof(pi)); #ifdef _WIN32 DWORD dwFlags = CREATE_DEFAULT_ERROR_MODE | CREATE_SUSPENDED; SetLastError(0); STARTUPINFO si; ZeroMemory(&si, sizeof(si)); si.cb = sizeof(si); #endif // Cmd line has to include the exe name since many apps expect the executable name to be in argv[0]! // Note argv[0] on the command line needs to be surrounded with quotes if it contains spaces. // The arguments in strArgs have already been "quoted" as they are parsed. gtASCIIString strCmdLine = AddQuotesIfStringHasSpaces(strApp.asCharArray()); strCmdLine += " "; strCmdLine += strArgs; LogConsole(logMESSAGE, "strApp: %s\n", strApp.asCharArray()); LogConsole(logMESSAGE, "strCmdLine: %s\n", strCmdLine.asCharArray()); // Attempt to initialize the environment that the new process will run in. The child process should inherit "this" environment. if (!PrelaunchEnvironmentInitialization()) { // Log a warning if this failed- initializing the environment for the new process can fail if Mantle support isn't installed. // In these cases, if the user is attempting to debug a Mantle application, they will have bigger problems to deal with. // In cases where a DX/GL app is being debugged, this warning can be ignored without any side effects. Log(logWARNING, "Environment initialization failed. If using DX/GL, it is safe to ignore this warning.\n"); } BOOL succeeded = FALSE; #ifdef _WIN32 char microDLLPath[PS_MAX_PATH]; const char* strServerPath; strServerPath = SG_GET_PATH(ServerPath); if (SG_GET_BOOL(OptionDllReplacement) == true) { DllReplacement::SetDllDirectory(binaryType == OS_X86_64_ARCHITECTURE); } // if using manual dll replacement or the AppInit_DLLs registry setting, don't use any kind of dll injection if (SG_GET_BOOL(OptionManualDllReplacement) == true || SG_GET_BOOL(OptionAppInitDll)) { succeeded = CreateProcess(strApp.asCharArray(), (LPSTR)strCmdLine.asCharArray(), NULL, NULL, TRUE, dwFlags, NULL, strDir.asCharArray(), &si, &pi); } else { #ifdef X64 // can only launch 64 bit applications if (binaryType != OS_X86_64_ARCHITECTURE) { sprintf_s(microDLLPath, PS_MAX_PATH, "%s" MICRODLLNAME "%s%s.dll", SG_GET_PATH(ServerPath), GDT_DEBUG_SUFFIX, GDT_BUILD_SUFFIX); succeeded = AMDT::CreateProcessAndInjectDll(strApp.asCharArray(), (LPSTR)strCmdLine.asCharArray(), NULL, NULL, TRUE, dwFlags, NULL, strDir.asCharArray(), &si, &pi, microDLLPath); } #else if (binaryType != OS_I386_ARCHITECTURE) { sprintf_s(microDLLPath, PS_MAX_PATH, "%s" MICRODLLNAME "-x64%s%s.dll", SG_GET_PATH(ServerPath), GDT_DEBUG_SUFFIX, GDT_BUILD_SUFFIX); succeeded = AMDT::CreateProcessAndInjectDll(strApp.asCharArray(), (LPSTR)strCmdLine.asCharArray(), NULL, NULL, TRUE, dwFlags, NULL, strDir.asCharArray(), &si, &pi, microDLLPath); } #endif // X64 else { succeeded = AMDT::CreateProcessAndInjectDll(strApp.asCharArray(), (LPSTR)strCmdLine.asCharArray(), NULL, NULL, TRUE, dwFlags, NULL, strDir.asCharArray(), &si, &pi, SG_GET_PATH(MicroDLLPath)); } } #else // Create the app process succeeded = CreateProcess(strApp.asCharArray(), strCmdLine.asCharArray(), strDir.asCharArray(), &pi); #endif // _WIN32 if (!succeeded) { osSystemErrorCode systemLastError = osGetLastSystemError(); gtString systemErrorString; osGetLastSystemErrorAsString(systemErrorString); Log(logERROR, "CreateProcessAndInjectDll failed; Error %d: %s\n", systemLastError, systemErrorString.asASCIICharArray()); pi.dwProcessId = 0; } #ifdef _WIN32 else { // Check to see if the Steam.exe has been hooked and if so, set the value in shared memory // If Steam.exe was used to launch the target application, then the checks for cmd.exe and fcx.exe // need to be ignored. if (strApp.length() > 0) { if (strstr(strApp.toLowerCase().asCharArray(), "steam.exe") != NULL) { SG_SET_BOOL(SteamInjected, true); } ShowLauncherReminder(strApp.toLowerCase().asCharArray()); } else { if (strstr(strCmdLine.toLowerCase().asCharArray(), "steam.exe") != NULL) { SG_SET_BOOL(SteamInjected, true); } ShowLauncherReminder(strCmdLine.toLowerCase().asCharArray()); } } #endif // _WIN32 return pi; }
//-------------------------------------------------------------- /// Writes information about the allowed plugins into shared memory /// and launches the application specified in s_strInjectedAppName /// \return true if the app is successfully launched; false otherwise //-------------------------------------------------------------- bool ProcessTracker::WritePluginsToSharedMemoryAndLaunchApp() { bool bGetType = false; if (OSDependentModulesInitialization() == false) { Log(logERROR, "Failed to initialize for plugins\n"); return false; } osModuleArchitecture binaryType; bGetType = OSWrappers::GetBinaryType(m_injectedAppName.c_str(), &binaryType); #ifdef _WIN32 if (!bGetType) { // try without quotes, should be W8x preference. This will update m_injectedAppName for later use also. m_injectedAppName.erase(0, 1); m_injectedAppName.resize(m_injectedAppName.size() - 1); bGetType = OSWrappers::GetBinaryType(m_injectedAppName.c_str(), &binaryType); } #endif // def _WIN32 if (!bGetType) { // file is not executable LogConsole(logERROR, "%s is not an executable file\n", m_injectedAppName.c_str()); return false; } Log(logMESSAGE, "WritePluginsToSharedMemoryAndLaunchApp()\n"); if (false == CreateSharedMemory()) { return false; } // now actually start the application PROCESS_INFORMATION pi = LaunchAppInNewProcess(m_injectedAppName.c_str(), m_injectedAppDir.c_str(), m_injectedAppArgs.c_str(), binaryType); if (pi.dwProcessId == 0) { LogConsole(logWARNING, "Failed to start application: %s %s\n\n", m_injectedAppName.c_str(), m_injectedAppArgs.c_str()); return false; } Log(logMESSAGE, "About to resume application thread\n"); #ifdef _WIN32 if (osResumeSuspendedProcess(0, 0, pi.hThread, false) == false) { osSystemErrorCode systemLastError = osGetLastSystemError(); gtString systemErrorString; osGetLastSystemErrorAsString(systemErrorString); Log(logERROR, "Resuming thread failed; Error %d: %s\n", systemLastError, systemErrorString.asASCIICharArray()); } #endif m_injectedAppID = pi.dwProcessId; return true; }
//-------------------------------------------------------------- /// Generates XML that describes the injected processes and which /// plugins were injected. /// \return string containing the XML //-------------------------------------------------------------- gtASCIIString ProcessTracker::GetProcessesXML() { std::unordered_map< DWORD, gtASCIIString > procXMLMap; this->UpdateListOfInjectedProcesses(); ProcessInfoList injectedProcesses = this->GetListOfInjectedProcesses(); WrapperMap wrappers = GetWrapperMap(); // the strPlatform is named this way to match options in the client. #ifdef X64 gtASCIIString strPlatform = "Win64"; #else gtASCIIString strPlatform = "Win32"; #endif #ifndef CODEXL_GRAPHICS if (injectedProcesses.empty() == true) { LogConsole(logERROR, "There are no processes running which have been injected with the GPU PerfStudio server plugin\n"); LogConsole(logERROR, "Please ensure that the server has the same bitness as the target application\n"); LogConsole(logERROR, "For example, use the 64-bit GPU PerfStudio server with a 64-bit application\n"); } #endif for (ProcessInfoList::iterator procIter = injectedProcesses.begin(); procIter != injectedProcesses.end(); ++procIter) { DWORD pid = procIter->th32ProcessID; // only add the process info if it wasn't already found. if (procXMLMap.find(pid) == procXMLMap.end()) { // insert new process and the process info gtASCIIString tmpString = XML("Name", XMLEscape(procIter->szExeFile).asCharArray()); tmpString += XML("PID", pid); tmpString += XML("Path", XMLEscape(procIter->szPath).asCharArray()); tmpString += XML("Platform", strPlatform.asCharArray()); procXMLMap[ pid ] = tmpString; // if this process is the one that was launched, then we know what the args and working directory were. // we could probably get the actual args and working dir from MicroDLL if it is a different app though, which // would be the case if this app uses a launcher app. if (m_injectedAppName.compare(procIter->szPath) == 0) { tmpString = XML("Args", XMLEscape(m_injectedAppArgs.c_str()).asCharArray()); tmpString += XML("WDir", XMLEscape(m_injectedAppDir.c_str()).asCharArray()); procXMLMap[ pid ] += tmpString.asCharArray(); } } // add an API node for each of the wrappers that are injected into the app for (WrapperMap::const_iterator wrapperIter = wrappers.begin(); wrapperIter != wrappers.end(); ++wrapperIter) { // List of plugin extensions to check for. On Windows, test for 32 and 64 bit plugins. // On linux, just check for the plugin corresponding to the server bitness static const char* pluginExtensions[] = { #ifdef WIN32 GDT_DEBUG_SUFFIX GDT_BUILD_SUFFIX "." DLL_EXTENSION, "-x64" GDT_DEBUG_SUFFIX GDT_BUILD_SUFFIX "." DLL_EXTENSION #else GDT_PROJECT_SUFFIX "." DLL_EXTENSION #endif }; int numPlugins = sizeof(pluginExtensions) / sizeof(pluginExtensions[0]); for (int loop = 0; loop < numPlugins; loop++) { // check to see if this wrapper is in the application gtASCIIString strPluginName = wrapperIter->second.strPluginName; if (SG_GET_BOOL(OptionDllReplacement) == false) { strPluginName += pluginExtensions[loop]; } if (IsLibraryLoadedInProcess(pid, strPluginName.asCharArray(), NULL)) { bool attached = false; if (g_activeWrappersMap.find(FormatText("%lu/%s", pid, wrapperIter->first.c_str()).asCharArray()) != g_activeWrappersMap.end()) { // the pid/plugin string was listed in the active wrappers map, so the plugin must be active. attached = true; } procXMLMap[pid] += XMLAttrib("API", FormatText("attached='%s'", attached ? "TRUE" : "FALSE").asCharArray(), wrapperIter->second.strPluginShortDesc.asCharArray()); } } } } // concatenate the process XML and additional info gtASCIIString xml; for (std::unordered_map< DWORD, gtASCIIString >::iterator iterP = procXMLMap.begin(); iterP != procXMLMap.end(); iterP++) { xml += XML("Process", (iterP->second).asCharArray()); } gtASCIIString out = XMLHeader(); out += XML("ProcessList", xml.asCharArray()); return out; }